content stringlengths 5 1.04M | avg_line_length float64 1.75 12.9k | max_line_length int64 2 244k | alphanum_fraction float64 0 0.98 | licenses list | repository_name stringlengths 7 92 | path stringlengths 3 249 | size int64 5 1.04M | lang stringclasses 2
values |
|---|---|---|---|---|---|---|---|---|
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
public partial class UserControls_TimerControl : System.Web.UI.UserControl
{
private string _sessionExpiredRedirect;
protected void Page_Load(object sender, EventArgs e)
{
int milliseconds = 60000;
TimerTimeout.Interval = (Session.Timeout) * milliseconds;
}
public string SessionExpiredRedirect
{
get { return _sessionExpiredRedirect; }
set { _sessionExpiredRedirect = value; }
}
protected void TimerTimout_Tick(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(SessionExpiredRedirect))
{
if (SessionExpiredRedirect.IndexOf("~") == 0)
Response.Redirect(
VirtualPathUtility.ToAppRelative(
SessionExpiredRedirect));
else
Response.Redirect(SessionExpiredRedirect);
}
}
}
| 27.142857 | 74 | 0.665789 | [
"MIT"
] | jlpatton/AuditBenefits | UserControls/TimerControl.ascx.cs | 1,140 | C# |
using System.Diagnostics.CodeAnalysis;
using System.Xml.Serialization;
namespace AIT.TFS.SyncService.Service.Configuration.Serialization
{
/// <summary>
/// Class used to serialize a header configuration.
/// </summary>
public class MappingHeader
{
/// <summary>
/// Property used to serialize 'RelatedTemplate' xml attribute.
/// </summary>
[XmlAttribute("RelatedTemplate")]
public string RelatedTemplate { get; set; }
/// <summary>
/// Property used to serialize 'Identifier' xml attribute.
/// </summary>
[XmlAttribute("Identifier")]
public string Identifier { get; set; }
/// <summary>
/// Property used to serialize 'AssignTo' xml attribute.
/// </summary>
[XmlAttribute("AssignTo")]
public string AssignTo { get; set; }
/// <summary>
/// Property used to serialize 'Row' xml attribute.
/// </summary>
[XmlAttribute("Row")]
public int Row { get; set; }
/// <summary>
/// Property used to serialize 'Column' xml attribute.
/// </summary>
[XmlAttribute("Column")]
public int Column { get; set; }
/// <summary>
/// Property used to serialize 'Level' xml attribute.
/// </summary>
[XmlAttribute("Level")]
public int Level { get; set; }
/// <summary>
/// Property used to serialize 'Fields/Field' xml nodes.
/// </summary>
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
[XmlArray("Fields")]
[XmlArrayItem("Field")]
public MappingField[] Fields { get; set; }
/// <summary>
/// Property used to serialize 'Converters/Converter' xml nodes.
/// </summary>
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
[XmlArray("Converters")]
[XmlArrayItem("Converter")]
public MappingConverter[] Converters { get; set; }
/// <summary>
/// Property used to serialize image file name.
/// </summary>
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
[XmlAttribute("ImageFile")]
public string ImageFile { get; set; }
}
} | 34.457143 | 93 | 0.570481 | [
"MIT"
] | AITGmbH/WordToTFS | Sources/TFS.SyncService.Service/Configuration/Serialization/MappingHeader.cs | 2,412 | C# |
// *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.Gcp.Iap.Inputs
{
public sealed class AppEngineVersionIamBindingConditionArgs : Pulumi.ResourceArgs
{
/// <summary>
/// An optional description of the expression. This is a longer text which describes the expression, e.g. when hovered over it in a UI.
/// </summary>
[Input("description")]
public Input<string>? Description { get; set; }
/// <summary>
/// Textual representation of an expression in Common Expression Language syntax.
/// </summary>
[Input("expression", required: true)]
public Input<string> Expression { get; set; } = null!;
/// <summary>
/// A title for the expression, i.e. a short string describing its purpose.
/// </summary>
[Input("title", required: true)]
public Input<string> Title { get; set; } = null!;
public AppEngineVersionIamBindingConditionArgs()
{
}
}
}
| 33.631579 | 143 | 0.641628 | [
"ECL-2.0",
"Apache-2.0"
] | dimpu47/pulumi-gcp | sdk/dotnet/Iap/Inputs/AppEngineVersionIamBindingConditionArgs.cs | 1,278 | C# |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Configuration;
namespace Doddle.Importing
{
public class Importer
{
private readonly IImportValidator _validator;
public MissingColumnAction MissingColumnAction { get; set; }
public Importer()
{
_validator = new ImportValidator();
}
public Importer(IImportValidator validator)
{
_validator = validator;
}
/// <summary>
/// Event fired before a Speadsheet row is imported to the Import Destination, allowing last minute alterations
/// </summary>
public event EventHandler<ImportRowEventArgs> RowImporting;
/// <summary>
/// Event fired after a Speadsheet row has been imported to the Import Destination
/// </summary>
public event EventHandler<ImportRowEventArgs> RowImported;
protected virtual void OnRowImporting(ImportRow row)
{
EventHandler<ImportRowEventArgs> handler = RowImporting;
if (handler != null)
handler(this, new ImportRowEventArgs(row));
}
protected virtual void OnRowImported(ImportRow row)
{
EventHandler<ImportRowEventArgs> handler = RowImported;
if (handler != null)
handler(this, new ImportRowEventArgs(row));
}
public ImportValidationResult Validate(IImportSource source, IImportDestination destination)
{
return _validator.Validate(source, destination);
}
public ImportResult Import(IImportSource source, IImportDestination destination)
{
return Import(source, destination, ImportValidationMode.Validate);
}
public ImportResult Import(IImportSource source, IImportDestination destination, ImportValidationMode validationMode)
{
if (validationMode == ImportValidationMode.Validate)
{
ImportValidationResult validation = _validator.Validate(source, destination);
if (validation.IsSourceValid == false)
{
throw new ImportValidationException("This import source did not pass validation and cannot be imported.");
}
}
foreach (ImportField sourceField in source.Fields)
{
EnsureFieldExists(destination, sourceField);
}
int rowCount = 0;
foreach (ImportRow row in source.Rows)
{
OnRowImporting(row);
destination.ImportRow(row);
OnRowImported(row);
rowCount++;
}
ImportResult result = new ImportResult();
result.ImportedRows = rowCount;
return result;
}
private void EnsureFieldExists(IImportDestination destination, ImportField field)
{
if (!destination.FieldExists(field.Name))
{
if (MissingColumnAction == MissingColumnAction.CreateColumn)
{
if (destination.SupportsFieldCreation)
{
destination.CreateField(field.Name, field.DataType);
}
}
}
}
}
} | 33.740385 | 127 | 0.573383 | [
"MIT"
] | matthidinger/DoddleImport | Doddle.Importing/Importer.cs | 3,509 | 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 Microsoft.CodeAnalysis.Text;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.UnitTests.CodeGeneration
{
public class StatementGenerationTests : AbstractCodeGenerationTests
{
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public void TestThrowStatement1()
{
Test(f => f.ThrowStatement(),
cs: "throw;",
vb: "Throw");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public void TestThrowStatement2()
{
Test(f => f.ThrowStatement(
f.IdentifierName("e")),
cs: "throw e;",
vb: "Throw e");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public void TestThrowStatement3()
{
Test(f => f.ThrowStatement(
f.ObjectCreationExpression(
CreateClass("NotImplementedException"))),
cs: "throw new NotImplementedException();",
vb: "Throw New NotImplementedException()");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public void TestReturnStatement1()
{
Test(f => f.ReturnStatement(),
cs: "return;",
vb: "Return");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public void TestReturnStatement2()
{
Test(f => f.ReturnStatement(
f.IdentifierName("e")),
cs: "return e;",
vb: "Return e");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public void TestReturnStatement3()
{
Test(f => f.ReturnStatement(
f.ObjectCreationExpression(
CreateClass("NotImplementedException"))),
cs: "return new NotImplementedException();",
vb: "Return New NotImplementedException()");
}
}
}
| 34 | 160 | 0.568182 | [
"Apache-2.0"
] | 0x53A/roslyn | src/EditorFeatures/Test/CodeGeneration/StatementGenerationTests.cs | 2,244 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using Azure.Core;
namespace Azure.AI.MetricsAdvisor.Models
{
/// <summary>
/// Alerts will only be triggered for anomalies in the top N series.
/// Use <see cref="Top"/> to specify the number of timestamps to take into account, and <see cref="MinimumTopCount"/>
/// to specify how many anomalies must be in them to send the alert.
/// </summary>
public partial class TopNGroupScope
{
/// <summary>
/// Initializes a new instance of the <see cref="TopNGroupScope"/> class.
/// </summary>
/// <param name="top"> top N, value range : [1, +∞). </param>
/// <param name="period"> point count used to look back, value range : [1, +∞). </param>
/// <param name="minimumTopCount">
/// min count should be in top N, value range : [1, +∞)
/// should be less than or equal to period.
/// </param>
public TopNGroupScope(int top, int period, int minimumTopCount)
{
Top = top;
Period = period;
MinimumTopCount = minimumTopCount;
}
/// <summary>
/// The number of timestamps to take into account.
/// </summary>
public int Top { get; set; }
/// <summary>
/// The number of items a period contains.
/// </summary>
public int Period { get; set; }
/// <summary>
/// The number of anomalies that must be in the specified <see cref="Top"/> number of timestamps to send an alert.
/// </summary>
[CodeGenMember("MinTopCount")]
public int MinimumTopCount { get; set; }
}
}
| 35.833333 | 122 | 0.578488 | [
"MIT"
] | AME-Redmond/azure-sdk-for-net | sdk/metricsadvisor/Azure.AI.MetricsAdvisor/src/Models/AlertTriggering/TopNGroupScope.cs | 1,728 | C# |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Runtime.InteropServices;
using System.Security.Permissions;
using System.Text;
namespace Microsoft.Deployment.Compression.Cab
{
internal class CabUnpacker : CabWorker
{
private NativeMethods.FDI.Handle fdiHandle;
private NativeMethods.FDI.PFNALLOC fdiAllocMemHandler;
private NativeMethods.FDI.PFNFREE fdiFreeMemHandler;
private NativeMethods.FDI.PFNOPEN fdiOpenStreamHandler;
private NativeMethods.FDI.PFNREAD fdiReadStreamHandler;
private NativeMethods.FDI.PFNWRITE fdiWriteStreamHandler;
private NativeMethods.FDI.PFNCLOSE fdiCloseStreamHandler;
private NativeMethods.FDI.PFNSEEK fdiSeekStreamHandler;
private IUnpackStreamContext context;
private List<ArchiveFileInfo> fileList;
private int folderId;
private Predicate<string> filter;
[SecurityPermission(SecurityAction.Assert, UnmanagedCode = true)]
public CabUnpacker(CabEngine cabEngine)
: base(cabEngine)
{
fdiAllocMemHandler = base.CabAllocMem;
fdiFreeMemHandler = base.CabFreeMem;
fdiOpenStreamHandler = base.CabOpenStream;
fdiReadStreamHandler = base.CabReadStream;
fdiWriteStreamHandler = base.CabWriteStream;
fdiCloseStreamHandler = base.CabCloseStream;
fdiSeekStreamHandler = base.CabSeekStream;
fdiHandle = NativeMethods.FDI.Create(fdiAllocMemHandler, fdiFreeMemHandler, fdiOpenStreamHandler, fdiReadStreamHandler, fdiWriteStreamHandler, fdiCloseStreamHandler, fdiSeekStreamHandler, 1, base.ErfHandle.AddrOfPinnedObject());
if (base.Erf.Error)
{
int oper = base.Erf.Oper;
int type = base.Erf.Type;
base.ErfHandle.Free();
throw new CabException(oper, type, CabException.GetErrorMessage(oper, type, extracting: true));
}
}
[SecurityPermission(SecurityAction.Assert, UnmanagedCode = true)]
public bool IsArchive(Stream stream)
{
if (stream == null)
{
throw new ArgumentNullException("stream");
}
lock (this)
{
short id;
int cabFolderCount;
int fileCount;
return IsCabinet(stream, out id, out cabFolderCount, out fileCount);
}
}
[SecurityPermission(SecurityAction.Assert, UnmanagedCode = true)]
public IList<ArchiveFileInfo> GetFileInfo(IUnpackStreamContext streamContext, Predicate<string> fileFilter)
{
if (streamContext == null)
{
throw new ArgumentNullException("streamContext");
}
lock (this)
{
context = streamContext;
filter = fileFilter;
base.NextCabinetName = string.Empty;
fileList = new List<ArchiveFileInfo>();
bool suppressProgressEvents = base.SuppressProgressEvents;
base.SuppressProgressEvents = true;
try
{
short num = 0;
while (base.NextCabinetName != null)
{
base.Erf.Clear();
base.CabNumbers[base.NextCabinetName] = num;
NativeMethods.FDI.Copy(fdiHandle, base.NextCabinetName, string.Empty, 0, CabListNotify, IntPtr.Zero, IntPtr.Zero);
CheckError(extracting: true);
num = checked((short)(num + 1));
}
List<ArchiveFileInfo> list = fileList;
fileList = null;
return list.AsReadOnly();
}
finally
{
base.SuppressProgressEvents = suppressProgressEvents;
if (base.CabStream != null)
{
context.CloseArchiveReadStream(currentArchiveNumber, currentArchiveName, base.CabStream);
base.CabStream = null;
}
context = null;
}
}
}
[SecurityPermission(SecurityAction.Assert, UnmanagedCode = true)]
public void Unpack(IUnpackStreamContext streamContext, Predicate<string> fileFilter)
{
checked
{
lock (this)
{
IList<ArchiveFileInfo> fileInfo = GetFileInfo(streamContext, fileFilter);
ResetProgressData();
if (fileInfo != null)
{
totalFiles = fileInfo.Count;
for (int i = 0; i < fileInfo.Count; i++)
{
totalFileBytes += fileInfo[i].Length;
if (fileInfo[i].ArchiveNumber >= totalArchives)
{
int num = fileInfo[i].ArchiveNumber + 1;
totalArchives = (short)num;
}
}
}
context = streamContext;
fileList = null;
base.NextCabinetName = string.Empty;
folderId = -1;
currentFileNumber = -1;
try
{
short num2 = 0;
while (base.NextCabinetName != null)
{
base.Erf.Clear();
base.CabNumbers[base.NextCabinetName] = num2;
NativeMethods.FDI.Copy(fdiHandle, base.NextCabinetName, string.Empty, 0, CabExtractNotify, IntPtr.Zero, IntPtr.Zero);
CheckError(extracting: true);
num2 = (short)(num2 + 1);
}
}
finally
{
if (base.CabStream != null)
{
context.CloseArchiveReadStream(currentArchiveNumber, currentArchiveName, base.CabStream);
base.CabStream = null;
}
if (base.FileStream != null)
{
context.CloseFileWriteStream(currentFileName, base.FileStream, FileAttributes.Normal, DateTime.Now);
base.FileStream = null;
}
context = null;
}
}
}
}
internal override int CabOpenStreamEx(string path, int openFlags, int shareMode, out int err, IntPtr pv)
{
checked
{
if (base.CabNumbers.ContainsKey(path))
{
Stream cabStream = base.CabStream;
if (cabStream == null)
{
short num = base.CabNumbers[path];
cabStream = context.OpenArchiveReadStream(num, path, base.CabEngine);
if (cabStream == null)
{
throw new FileNotFoundException(string.Format(CultureInfo.InvariantCulture, "Cabinet {0} not provided.", num));
}
currentArchiveName = path;
currentArchiveNumber = num;
if (totalArchives <= currentArchiveNumber)
{
int num2 = currentArchiveNumber + 1;
totalArchives = (short)num2;
}
currentArchiveTotalBytes = cabStream.Length;
currentArchiveBytesProcessed = 0L;
if (folderId != -3)
{
OnProgress(ArchiveProgressType.StartArchive);
}
base.CabStream = cabStream;
}
path = "%%CAB%%";
}
return base.CabOpenStreamEx(path, openFlags, shareMode, out err, pv);
}
}
internal override int CabReadStreamEx(int streamHandle, IntPtr memory, int cb, out int err, IntPtr pv)
{
int result = base.CabReadStreamEx(streamHandle, memory, cb, out err, pv);
checked
{
if (err == 0 && base.CabStream != null && fileList == null && DuplicateStream.OriginalStream(base.StreamHandles[streamHandle]) == DuplicateStream.OriginalStream(base.CabStream))
{
currentArchiveBytesProcessed += cb;
if (currentArchiveBytesProcessed > currentArchiveTotalBytes)
{
currentArchiveBytesProcessed = currentArchiveTotalBytes;
}
}
return result;
}
}
internal override int CabWriteStreamEx(int streamHandle, IntPtr memory, int cb, out int err, IntPtr pv)
{
int num = base.CabWriteStreamEx(streamHandle, memory, cb, out err, pv);
checked
{
if (num > 0 && err == 0)
{
currentFileBytesProcessed += cb;
fileBytesProcessed += cb;
OnProgress(ArchiveProgressType.PartialFile);
}
return num;
}
}
internal override int CabCloseStreamEx(int streamHandle, out int err, IntPtr pv)
{
Stream stream = DuplicateStream.OriginalStream(base.StreamHandles[streamHandle]);
if (stream == DuplicateStream.OriginalStream(base.CabStream))
{
if (folderId != -3)
{
OnProgress(ArchiveProgressType.FinishArchive);
}
context.CloseArchiveReadStream(currentArchiveNumber, currentArchiveName, stream);
currentArchiveName = base.NextCabinetName;
currentArchiveBytesProcessed = (currentArchiveTotalBytes = 0L);
base.CabStream = null;
}
return base.CabCloseStreamEx(streamHandle, out err, pv);
}
protected override void Dispose(bool disposing)
{
try
{
if (disposing && fdiHandle != null)
{
fdiHandle.Dispose();
fdiHandle = null;
}
}
finally
{
base.Dispose(disposing);
}
}
private static string GetFileName(NativeMethods.FDI.NOTIFICATION notification)
{
Encoding encoding = ((((uint)notification.attribs & 0x80u) != 0) ? Encoding.UTF8 : Encoding.Default);
int i;
for (i = 0; Marshal.ReadByte(notification.psz1, i) != 0; i = checked(i + 1))
{
}
byte[] array = new byte[i];
Marshal.Copy(notification.psz1, array, 0, i);
string text = encoding.GetString(array);
if (Path.IsPathRooted(text))
{
string text2 = text;
char volumeSeparatorChar = Path.VolumeSeparatorChar;
text = text2.Replace(volumeSeparatorChar.ToString() ?? "", "");
}
return text;
}
private bool IsCabinet(Stream cabStream, out short id, out int cabFolderCount, out int fileCount)
{
int num = base.StreamHandles.AllocHandle(cabStream);
try
{
base.Erf.Clear();
NativeMethods.FDI.CABINFO pfdici;
bool result = NativeMethods.FDI.IsCabinet(fdiHandle, num, out pfdici) != 0;
if (base.Erf.Error)
{
if (base.Erf.Oper != 3)
{
throw new CabException(base.Erf.Oper, base.Erf.Type, CabException.GetErrorMessage(base.Erf.Oper, base.Erf.Type, extracting: true));
}
result = false;
}
id = pfdici.setID;
cabFolderCount = pfdici.cFolders;
fileCount = pfdici.cFiles;
return result;
}
finally
{
base.StreamHandles.FreeHandle(num);
}
}
private int CabListNotify(NativeMethods.FDI.NOTIFICATIONTYPE notificationType, NativeMethods.FDI.NOTIFICATION notification)
{
checked
{
switch (notificationType)
{
case NativeMethods.FDI.NOTIFICATIONTYPE.CABINET_INFO:
{
string text = Marshal.PtrToStringAnsi(notification.psz1);
base.NextCabinetName = ((text.Length != 0) ? text : null);
return 0;
}
case NativeMethods.FDI.NOTIFICATIONTYPE.PARTIAL_FILE:
return 0;
case NativeMethods.FDI.NOTIFICATIONTYPE.COPY_FILE:
{
string fileName = GetFileName(notification);
if ((filter == null || filter(fileName)) && fileList != null)
{
FileAttributes fileAttributes = unchecked((FileAttributes)(notification.attribs & 0x27));
if (fileAttributes == (FileAttributes)0)
{
fileAttributes = FileAttributes.Normal;
}
CompressionEngine.DosDateAndTimeToDateTime(notification.date, notification.time, out var dateTime);
long length = notification.cb;
CabFileInfo item = new CabFileInfo(fileName, notification.iFolder, notification.iCabinet, fileAttributes, dateTime, length);
fileList.Add(item);
currentFileNumber = fileList.Count - 1;
fileBytesProcessed += notification.cb;
}
totalFiles++;
totalFileBytes += notification.cb;
return 0;
}
default:
return 0;
}
}
}
private int CabExtractNotify(NativeMethods.FDI.NOTIFICATIONTYPE notificationType, NativeMethods.FDI.NOTIFICATION notification)
{
switch (notificationType)
{
case NativeMethods.FDI.NOTIFICATIONTYPE.CABINET_INFO:
if (base.NextCabinetName != null && base.NextCabinetName.StartsWith("?", StringComparison.Ordinal))
{
base.NextCabinetName = base.NextCabinetName.Substring(1);
}
else
{
string text = Marshal.PtrToStringAnsi(notification.psz1);
base.NextCabinetName = ((text.Length != 0) ? text : null);
}
return 0;
case NativeMethods.FDI.NOTIFICATIONTYPE.NEXT_CABINET:
{
string key = Marshal.PtrToStringAnsi(notification.psz1);
base.CabNumbers[key] = notification.iCabinet;
base.NextCabinetName = "?" + base.NextCabinetName;
return 0;
}
case NativeMethods.FDI.NOTIFICATIONTYPE.COPY_FILE:
return CabExtractCopyFile(notification);
case NativeMethods.FDI.NOTIFICATIONTYPE.CLOSE_FILE_INFO:
return CabExtractCloseFile(notification);
default:
return 0;
}
}
private int CabExtractCopyFile(NativeMethods.FDI.NOTIFICATION notification)
{
checked
{
if (notification.iFolder != folderId)
{
if (notification.iFolder != -3 && folderId != -1)
{
currentFolderNumber++;
}
folderId = notification.iFolder;
}
string fileName = GetFileName(notification);
if (filter == null || filter(fileName))
{
currentFileNumber++;
currentFileName = fileName;
currentFileBytesProcessed = 0L;
currentFileTotalBytes = notification.cb;
OnProgress(ArchiveProgressType.StartFile);
CompressionEngine.DosDateAndTimeToDateTime(notification.date, notification.time, out var dateTime);
Stream stream = context.OpenFileWriteStream(fileName, notification.cb, dateTime);
if (stream != null)
{
base.FileStream = stream;
return base.StreamHandles.AllocHandle(stream);
}
fileBytesProcessed += notification.cb;
OnProgress(ArchiveProgressType.FinishFile);
currentFileName = null;
}
return 0;
}
}
private int CabExtractCloseFile(NativeMethods.FDI.NOTIFICATION notification)
{
Stream stream = base.StreamHandles[notification.hf];
base.StreamHandles.FreeHandle(notification.hf);
string fileName = GetFileName(notification);
FileAttributes fileAttributes = (FileAttributes)(notification.attribs & 0x27);
if (fileAttributes == (FileAttributes)0)
{
fileAttributes = FileAttributes.Normal;
}
CompressionEngine.DosDateAndTimeToDateTime(notification.date, notification.time, out var dateTime);
stream.Flush();
context.CloseFileWriteStream(fileName, stream, fileAttributes, dateTime);
base.FileStream = null;
checked
{
long num = currentFileTotalBytes - currentFileBytesProcessed;
currentFileBytesProcessed += num;
fileBytesProcessed += num;
OnProgress(ArchiveProgressType.FinishFile);
currentFileName = null;
return 1;
}
}
}
}
| 30.174009 | 231 | 0.689612 | [
"MIT"
] | daoluong/MSFTCompressionCab.Core | Microsoft.Deployment.Compression.Cab/Microsoft.Deployment.Compression.Cab/CabUnpacker.cs | 13,699 | C# |
using System.Collections.Generic;
using System.Linq;
namespace PanoramicData.OData.Client;
public abstract class MetadataBase : IMetadata
{
protected MetadataBase(INameMatchResolver nameMatchResolver, bool ignoreUnmappedProperties, bool unqualifiedNameCall)
{
IgnoreUnmappedProperties = ignoreUnmappedProperties;
NameMatchResolver = nameMatchResolver;
UnqualifiedNameCall = unqualifiedNameCall;
}
public bool IgnoreUnmappedProperties { get; }
public INameMatchResolver NameMatchResolver { get; }
public bool UnqualifiedNameCall { get; }
public abstract string GetEntityCollectionExactName(string collectionName);
public abstract string GetDerivedEntityTypeExactName(string collectionName, string entityTypeName);
public abstract bool EntityCollectionRequiresOptimisticConcurrencyCheck(string collectionName);
public abstract string GetEntityTypeExactName(string collectionName);
public abstract string GetLinkedCollectionName(string instanceTypeName, string typeName, out bool isSingleton);
public abstract string GetQualifiedTypeName(string collectionName);
public abstract bool IsOpenType(string collectionName);
public abstract bool IsTypeWithId(string collectionName);
public abstract IEnumerable<string> GetStructuralPropertyNames(string collectionName);
public abstract bool HasStructuralProperty(string collectionName, string propertyName);
public abstract string GetStructuralPropertyExactName(string collectionName, string propertyName);
public abstract string GetStructuralPropertyPath(string collectionName, params string[] propertyNames);
public abstract IEnumerable<string> GetDeclaredKeyPropertyNames(string collectionName);
public abstract IEnumerable<string> GetNavigationPropertyNames(string collectionName);
public abstract IEnumerable<IEnumerable<string>> GetAlternateKeyPropertyNames(string collectionName);
public abstract bool HasNavigationProperty(string collectionName, string propertyName);
public abstract string GetNavigationPropertyExactName(string collectionName, string propertyName);
public abstract string GetNavigationPropertyPartnerTypeName(string collectionName, string propertyName);
public abstract bool IsNavigationPropertyCollection(string collectionName, string propertyName);
public abstract string GetFunctionFullName(string functionName);
public abstract EntityCollection GetFunctionReturnCollection(string functionName);
public abstract string GetFunctionVerb(string functionName);
public abstract string GetActionFullName(string actionName);
public abstract EntityCollection GetActionReturnCollection(string actionName);
public EntityCollection GetEntityCollection(string collectionPath)
{
var segments = collectionPath.Split('/');
if (segments.Count() > 1)
{
if (SegmentsIncludeTypeSpecification(segments))
{
var baseEntitySet = GetEntityCollection(Utils.ExtractCollectionName(segments[segments.Length - 2]));
return GetDerivedEntityCollection(baseEntitySet, Utils.ExtractCollectionName(segments.Last()));
}
else
{
return new EntityCollection(GetEntityCollectionExactName(Utils.ExtractCollectionName(segments.Last())));
}
}
else
{
return new EntityCollection(GetEntityCollectionExactName(Utils.ExtractCollectionName(collectionPath)));
}
}
public EntityCollection GetDerivedEntityCollection(EntityCollection baseCollection, string entityTypeName)
{
var actualName = GetDerivedEntityTypeExactName(baseCollection.Name, entityTypeName);
return new EntityCollection(actualName, baseCollection);
}
public EntityCollection NavigateToCollection(string path)
{
var segments = GetCollectionPathSegments(path);
return IsSingleSegmentWithTypeSpecification(segments)
? GetEntityCollection(path)
: NavigateToCollection(GetEntityCollection(segments.First()), segments.Skip(1));
}
public EntityCollection NavigateToCollection(EntityCollection rootCollection, string path) => NavigateToCollection(rootCollection, GetCollectionPathSegments(path));
private EntityCollection NavigateToCollection(EntityCollection rootCollection, IEnumerable<string> segments)
{
if (!segments.Any())
{
return rootCollection;
}
var associationName = GetNavigationPropertyExactName(rootCollection.Name, segments.First());
var typeName = IsSingleSegmentWithTypeSpecification(segments)
? segments.Last()
: GetNavigationPropertyPartnerTypeName(rootCollection.Name, associationName);
var entityCollection = GetEntityCollection(typeName);
return segments.Count() == 1 || IsSingleSegmentWithTypeSpecification(segments)
? entityCollection
: NavigateToCollection(entityCollection, segments.Skip(1));
}
protected bool SegmentsIncludeTypeSpecification(IEnumerable<string> segments) => segments.Last().Contains(".");
protected bool IsSingleSegmentWithTypeSpecification(IEnumerable<string> segments) => segments.Count() == 2 && SegmentsIncludeTypeSpecification(segments);
public EntryDetails ParseEntryDetails(string collectionName, IDictionary<string, object> entryData, string contentId = null)
{
var entryDetails = new EntryDetails();
foreach (var item in entryData)
{
if (HasStructuralProperty(collectionName, item.Key))
{
entryDetails.AddProperty(item.Key, item.Value);
}
else if (HasNavigationProperty(collectionName, item.Key))
{
if (IsNavigationPropertyCollection(collectionName, item.Key))
{
switch (item.Value)
{
case null:
entryDetails.AddLink(item.Key, null, contentId);
break;
case IEnumerable<object> collection:
foreach (var element in collection)
{
entryDetails.AddLink(item.Key, element, contentId);
}
break;
}
}
else
{
entryDetails.AddLink(item.Key, item.Value, contentId);
}
}
else if (IsOpenType(collectionName))
{
entryDetails.HasOpenTypeProperties = true;
entryDetails.AddProperty(item.Key, item.Value);
}
else if (!IgnoreUnmappedProperties)
{
throw new UnresolvableObjectException(item.Key, $"No property or association found for [{item.Key}].");
}
}
return entryDetails;
}
public IEnumerable<string> GetCollectionPathSegments(string path) => path.Split('/').Select(x => x.Contains("(") ? x.Substring(0, x.IndexOf("(")) : x);
}
| 40.655367 | 165 | 0.694414 | [
"MIT"
] | panoramicdata/PanoramicData.OData.Client | src/PanoramicData.OData.Client.Core/Adapter/MetadataBase.cs | 7,198 | C# |
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Workplaces.DataModel.Models;
using Workplaces.Service.Interfaces;
namespace Workplaces.Controllers
{
[ApiController]
[Route("api/[controller]")]
public class UserWorkplacesController : ControllerBase
{
private readonly IUserWorkplacesService userWorkplacesService;
private readonly IUsersService usersService;
private readonly IWorkplacesService workplacesService;
public UserWorkplacesController(
IUserWorkplacesService userWorkplacesService,
IUsersService usersService,
IWorkplacesService workplacesService)
{
this.userWorkplacesService = userWorkplacesService ?? throw new ArgumentNullException();
this.usersService = usersService ?? throw new ArgumentNullException();
this.workplacesService = workplacesService ?? throw new ArgumentNullException();
}
/// <summary>
/// Gets all user workplaces
/// </summary>
/// <returns>All user work places(without deleted)</returns>
/// <response code="200">Returns all user work places(without deleted) or empty collection</response>
[HttpGet(Name = nameof(GetUserWorkplaces))]
public ActionResult<IEnumerable<UserWorkplaceDTO>> GetUserWorkplaces()
{
var userWorkplaces = userWorkplacesService.GetUserWorkplaces();
return Ok(userWorkplaces);
}
/// <summary>
/// Gets all options for user work place
/// </summary>
/// <returns>All options for user work place(without deleted)</returns>
/// <response code="200">All options for user work place(without deleted) or empty collection</response>
[HttpGet("options")]
public ActionResult<UserWorkplaceOptionsDTO> GetUserWorkplaceOptions()
{
var userWorkplaceOptions = userWorkplacesService.GetUserWorkplaceOptions();
return Ok(userWorkplaceOptions);
}
/// <summary>
/// Gets specific user workplace
/// </summary>
/// <param name="userWorkplaceId">Id of the user workplace</param>
/// <returns>The user workplace with the given Id</returns>
/// <response code="200">Returns a user workplace with the given Id</response>
/// <response code="404">If a user workplace with the given id does not exist</response>
[HttpGet("{userWorkplaceId}")]
public async Task<ActionResult<UserWorkplaceForManipulationDTO>> GetUserWorkplace(int userWorkplaceId)
{
if (!await userWorkplacesService.UserWorkplaceExistsAsync(userWorkplaceId))
{
return NotFound();
}
var userWorkplace = await userWorkplacesService.GetUserWorkplaceAsync(userWorkplaceId);
return Ok(userWorkplace);
}
/// <summary>
/// Creates new user workplace
/// </summary>
/// <param name="userWorkplace"></param>
/// <returns>A newly created user workplace</returns>
/// <response code="201">Returns the newly created user workplace</response>
[HttpPost]
public async Task<ActionResult<UserWorkplaceDTO>> CreateUserWorkplace(UserWorkplaceForManipulationDTO userWorkplace)
{
if (!await usersService.UserExistsAsync(userWorkplace.UserId) ||
!await workplacesService.WorkplaceExistsAsync(userWorkplace.WorkplaceId))
{
return NotFound();
}
var userWorkplaceToReturn = await userWorkplacesService.CreateUserWorkplaceAsync(userWorkplace);
return CreatedAtRoute(nameof(GetUserWorkplaces),
new { userWorkplaceId = userWorkplaceToReturn.Id }, userWorkplaceToReturn);
}
/// <summary>
/// Updates user workplace
/// </summary>
/// <param name="userWorkplaceId">Id of the user workplace</param>
/// <param name="userWorkplace"></param>
/// <returns>No content</returns>
/// <response code="204">If the user workplace is updated successfully</response>
/// <response code="404">If a user workplace, user or workplace with the given id does not exist</response>
[HttpPut("{userWorkplaceId}")]
public async Task<IActionResult> UpdateUserWorkplace(int userWorkplaceId, UserWorkplaceForManipulationDTO userWorkplace)
{
if (!await userWorkplacesService.UserWorkplaceExistsAsync(userWorkplaceId) ||
!await usersService.UserExistsAsync(userWorkplace.UserId) ||
!await workplacesService.WorkplaceExistsAsync(userWorkplace.WorkplaceId))
{
return NotFound();
}
await userWorkplacesService.UpdateUserWorkplaceAsync(userWorkplaceId, userWorkplace);
return NoContent();
}
/// <summary>
/// Deletes user workplace
/// </summary>
/// <param name="userWorkplaceId">Id of the user workplace</param>
/// <returns>No content</returns>
/// <response code="204">If the user workplace is deleted successfully</response>
/// <response code="404">If a user workplace with the given id does not exist</response>
[HttpDelete("{userWorkplaceId}")]
public async Task<IActionResult> DeleteUserWorkplace(int userWorkplaceId)
{
if (!await userWorkplacesService.UserWorkplaceExistsAsync(userWorkplaceId))
{
return NotFound();
}
await userWorkplacesService.DeleteUserWorkplaceAsync(userWorkplaceId);
return NoContent();
}
}
}
| 43.571429 | 128 | 0.648318 | [
"MIT"
] | borislavdostov/WorkPlacesAPI | Workplaces/Controllers/UserWorkplacesController.cs | 5,797 | C# |
/*
http://www.cgsoso.com/forum-211-1.html
CG搜搜 Unity3d 每日Unity3d插件免费更新 更有VIP资源!
CGSOSO 主打游戏开发,影视设计等CG资源素材。
插件如若商用,请务必官网购买!
daily assets update for try.
U should buy the asset from home store if u use it in your project!
*/
using RootSystem = System;
using System.Linq;
using System.Collections.Generic;
namespace Windows.Kinect
{
//
// Windows.Kinect.ColorSpacePoint
//
[RootSystem.Runtime.InteropServices.StructLayout(RootSystem.Runtime.InteropServices.LayoutKind.Sequential)]
public struct ColorSpacePoint
{
public float X { get; set; }
public float Y { get; set; }
public override int GetHashCode()
{
return X.GetHashCode() ^ Y.GetHashCode();
}
public override bool Equals(object obj)
{
if (!(obj is ColorSpacePoint))
{
return false;
}
return this.Equals((ColorSpacePoint)obj);
}
public bool Equals(ColorSpacePoint obj)
{
return X.Equals(obj.X) && Y.Equals(obj.Y);
}
public static bool operator ==(ColorSpacePoint a, ColorSpacePoint b)
{
return a.Equals(b);
}
public static bool operator !=(ColorSpacePoint a, ColorSpacePoint b)
{
return !(a.Equals(b));
}
}
}
| 22.163934 | 111 | 0.596893 | [
"Apache-2.0"
] | 154544017/BorderEscape | Assets/Standard Assets/Windows/Kinect/ColorSpacePoint.cs | 1,446 | C# |
namespace Northwind.Application.Rooms.Models
{
public class RoomPreviewModel
{
public int RoomId { get; set; }
public int RoomNumber { get; set; }
public int RoomCapacity { get; set; }
public string Notes { get; set; }
}
}
| 24.363636 | 45 | 0.608209 | [
"MIT"
] | marekprokurat/DotNet-zadanie3 | Northwind.Application/Rooms/Models/RoomPreviewModel.cs | 270 | C# |
using System;
using System.Collections.Generic;
using System.DirectoryServices.AccountManagement;
using System.Linq;
using System.Net;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
namespace PurpleSharp.Lib
{
public class Targets
{
public static List<Computer> GetNetworkNeighborTargets(int count)
{
List<Computer> targets = new List<Computer>();
List<IPAddress> neighbors = Lib.Networking.GetNeighbors(count);
List<Task> tasklist = new List<Task>();
Console.WriteLine("[*] Obtaining network neighbor targets ...");
foreach (IPAddress ip in neighbors)
{
tasklist.Add(Task.Factory.StartNew(() => {
TimeSpan interval = TimeSpan.FromSeconds(3);
if (Lib.Networking.OpenPort(ip.ToString(), 445, interval))
{
Console.WriteLine("trying to resolve " + ip.ToString());
string hostname = Lib.Networking.ResolveIp(ip);
if (hostname != "")
{
Computer newhost = new Computer();
newhost.Fqdn = hostname;
newhost.IPv4 = ip.ToString();
targets.Add(newhost);
//Console.WriteLine("Found " + hostname);
}
}
}));
}
Task.WaitAll(tasklist.ToArray());
return targets;
}
public static List<Computer> GetDomainNeighborTargets(int count)
{
List<Computer> targets = new List<Computer>();
PrincipalContext context = new PrincipalContext(ContextType.Domain);
string dc = context.ConnectedServer;
//logger.TimestampInfo("[*] Obtaining domain neighbor targets ...");
Console.WriteLine("[*] Obtaining domain neighbor targets ...");
targets = Ldap.GetADComputers(count, dc);
//Console.WriteLine("[*] Finished");
return targets;
}
public static List<Computer> GetDomainRandomTargets(int count)
{
List<Computer> targets = new List<Computer>();
Console.WriteLine("[*] Obtaining domain random targets ...");
targets = Ldap.GetADComputers(count);
return targets;
}
public static List<Computer> GetServerRangeTargets(int count)
{
List<Task> tasklist = new List<Task>();
Console.WriteLine("[*] Obtaining random server targets ...");
List<Computer> targets = new List<Computer>();
List<IPAddress> ips = new List<IPAddress>();
List<Computer> dcs = Ldap.GetDcs();
Random random = new Random();
int index = random.Next(dcs.Count);
IPAddress dc = IPAddress.Parse(dcs[index].IPv4);
Console.WriteLine("[*] Wrandomly picked DC {0}", dcs[index].Fqdn);
ips = Lib.Networking.GetRange(dc, 24, count);
foreach (IPAddress ip in ips)
{
tasklist.Add(Task.Factory.StartNew(() => {
TimeSpan interval = TimeSpan.FromSeconds(3);
if (Lib.Networking.OpenPort(ip.ToString(), 445, interval))
{
string hostname = Lib.Networking.ResolveIp(ip);
if (hostname != "")
{
Computer newhost = new Computer();
newhost.Fqdn = hostname;
newhost.IPv4 = ip.ToString();
targets.Add(newhost);
//Console.WriteLine("Found " + hostname);
}
}
}));
}
Task.WaitAll(tasklist.ToArray());
return targets;
}
public static List<User> GetRandomUsernames(int count)
{
List<User> users = new List<User>();
Console.WriteLine("[*] Generating random usernames ...");
for (int i = 0; i < count; i++ )
{
Random random = new Random();
string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
User nuser = new User();
nuser.UserName = new string(Enumerable.Repeat(chars, 8).Select(s => s[random.Next(s.Length)]).ToArray()); ;
users.Add(nuser);
}
return users;
}
public static List<User> GetUserTargets(int usertype, int nuser)
{
List<User> targetusers = new List<User>();
PrincipalContext context = new PrincipalContext(ContextType.Domain);
string dc = context.ConnectedServer;
switch (usertype)
{
case 1:
Console.WriteLine("[*] Targeting domain neighbor users");
targetusers = Ldap.GetADUsers(nuser, dc, true);
break;
case 2:
Console.WriteLine("[*] Targeting domain foreign users");
targetusers = Ldap.GetADUsers(nuser, "", true);
break;
case 3:
Console.WriteLine("[*] Targeting disabled users");
targetusers = Ldap.GetADUsers(nuser, dc, false);
break;
case 4:
Console.WriteLine("[*] Targeting administrative accounts (adminCount=1) ");
targetusers = Ldap.GetADAdmins(nuser);
break;
case 5:
Console.WriteLine("[*] Targeting domain admins");
targetusers = Ldap.GetDomainAdmins();
break;
case 6:
targetusers = Targets.GetRandomUsernames(nuser);
break;
default:
return targetusers;
}
return targetusers;
}
public static List<Computer> GetHostTargets(int servertype, int nhosts)
{
List<Computer> targethosts = new List<Computer>();
/*
switch (servertype)
{
case 1:
targethosts = GetDomainNeighborTargets(nhosts);
break;
case 2:
targethosts = GetDomainRandomTargets(nhosts);
break;
case 3:
targethosts = GetServerRangeTargets(nhosts);
break;
case 4:
targethosts = GetNetworkNeighborTargets(nhosts);
break;
default:
return targethosts;
}
*/
targethosts = GetDomainNeighborTargets(nhosts);
return targethosts;
}
}
}
| 33.771429 | 123 | 0.488438 | [
"BSD-3-Clause"
] | clr2of8/PurpleSharp | PurpleSharp/Lib/Targets.cs | 7,094 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
namespace TextSheet___Beta
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Main_Form());
}
}
}
| 23.181818 | 66 | 0.580392 | [
"MIT"
] | Depthgr8/TextSheet | TextSheet - Beta/TextSheet - Beta/Program.cs | 512 | C# |
using AntDesign;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Rendering;
using Microsoft.AspNetCore.Components.RenderTree;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text.RegularExpressions;
namespace OpsMain.Client.Shared.Component.AntdExt
{
public class TabsRouteView : ReuseTabsRouteView
{
protected override void Render(RenderTreeBuilder builder)
{
base.Render(builder);
builder.Clear();
var layoutType = RouteData.PageType.GetCustomAttribute<LayoutAttribute>()?.LayoutType ?? DefaultLayout;
var body = CreateBody(RouteData, Navmgr.Uri);
builder.OpenComponent<CascadingValue<ReuseTabsRouteView>>(0);
builder.AddAttribute(1, "Name", "RouteView");
builder.AddAttribute(2, "Value", this);
builder.AddAttribute(3, "ChildContent", (RenderFragment)(b =>
{
b.OpenComponent(20, layoutType);
b.AddAttribute(21, "Body", body);
b.CloseComponent();
}));
builder.CloseComponent();
}
private RenderFragment CreateBody(RouteData routeData, string url)
{
return builder =>
{
builder.OpenComponent(0, routeData.PageType);
foreach (var routeValue in routeData.RouteValues)
{
builder.AddAttribute(1, routeValue.Key, routeValue.Value);
}
//builder.AddComponentReferenceCapture(2, @ref =>
//{
// GetPageInfo(_pageMap[url], routeData.PageType, url, @ref);
//});
builder.CloseComponent();
};
}
private void GetPageInfo(ReuseTabsPageItem pageItem, Type pageType, string url, object page)
{
if (page is IReuseTabsPage resuse)
{
pageItem.Title ??= resuse.GetPageTitle();
}
var attributes = pageType.GetCustomAttributes(true);
if (attributes.FirstOrDefault(x => x is ReuseTabsPageTitleAttribute) is ReuseTabsPageTitleAttribute titleAttr && titleAttr != null)
{
pageItem.Title ??= titleAttr.Title?.ToRenderFragment();
}
if (attributes.FirstOrDefault(x => x is ReuseTabsPageAttribute) is ReuseTabsPageAttribute attr && attr != null)
{
pageItem.Title ??= attr.Title?.ToRenderFragment();
pageItem.Ignore = attr.Ignore;
pageItem.Closable = attr.Closable;
}
pageItem.Title ??= new Uri(url).PathAndQuery.ToRenderFragment();
}
}
}
| 32.229885 | 143 | 0.585592 | [
"MIT"
] | Guyiming/Blazor-Treadstone | src/OpsMain/Client/Shared/Component/AntdExt/TabsRouteView.cs | 2,806 | C# |
namespace UIWidgets
{
using UnityEngine;
/// <summary>
/// Autocomplete for ListViewIcons.
/// </summary>
public class AutocompleteIcons : AutocompleteCustom<ListViewIconsItemDescription, ListViewIconsItemComponent, ListViewIcons>
{
/// <summary>
/// Determines whether the beginning of value matches the Input.
/// </summary>
/// <param name="value">Value.</param>
/// <returns>true if beginning of value matches the Input; otherwise, false.</returns>
public override bool Startswith(ListViewIconsItemDescription value)
{
if (CaseSensitive)
{
return value.Name.StartsWith(Query) || (value.LocalizedName != null && value.LocalizedName.StartsWith(Query));
}
return value.Name.ToLower().StartsWith(Query.ToLower()) || (value.LocalizedName != null && value.LocalizedName.ToLower().StartsWith(Query.ToLower()));
}
/// <summary>
/// Returns a value indicating whether Input occurs within specified value.
/// </summary>
/// <param name="value">Value.</param>
/// <returns>true if the Input occurs within value parameter; otherwise, false.</returns>
public override bool Contains(ListViewIconsItemDescription value)
{
if (CaseSensitive)
{
return value.Name.Contains(Query) || (value.LocalizedName != null && value.LocalizedName.Contains(Query));
}
return value.Name.ToLower().Contains(Query.ToLower()) || (value.LocalizedName != null && value.LocalizedName.ToLower().Contains(Query.ToLower()));
}
/// <summary>
/// Convert value to string.
/// </summary>
/// <returns>The string value.</returns>
/// <param name="value">Value.</param>
protected override string GetStringValue(ListViewIconsItemDescription value)
{
return value.LocalizedName ?? value.Name;
}
}
} | 35.02 | 153 | 0.706453 | [
"MIT"
] | cschladetsch/CardChess | Assets/External/NewUIWidgets/Scripts/Autocomplete/AutocompleteIcons.cs | 1,753 | C# |
/*
* tweak-api
*
* Tweak API to integrate with all the Tweak services. You can find out more about Tweak at <a href='https://www.tweak.com'>https://www.tweak.com</a>, #tweak.
*
* OpenAPI spec version: 1.0.8-beta.0
*
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*
* 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.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using RestSharp;
using TweakApi.Client;
using TweakApi.Model;
namespace TweakApi.Api
{
/// <summary>
/// Represents a collection of functions to interact with the API endpoints
/// </summary>
public interface IProductTypeApi : IApiAccessor
{
#region Synchronous Operations
/// <summary>
/// Create a change stream.
/// </summary>
/// <remarks>
///
/// </remarks>
/// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="options"> (optional)</param>
/// <returns>System.IO.Stream</returns>
System.IO.Stream ProductTypesChangeStreamGet (string options = null);
/// <summary>
/// Create a change stream.
/// </summary>
/// <remarks>
///
/// </remarks>
/// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="options"> (optional)</param>
/// <returns>ApiResponse of System.IO.Stream</returns>
ApiResponse<System.IO.Stream> ProductTypesChangeStreamGetWithHttpInfo (string options = null);
/// <summary>
/// Create a change stream.
/// </summary>
/// <remarks>
///
/// </remarks>
/// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="options"> (optional)</param>
/// <returns>System.IO.Stream</returns>
System.IO.Stream ProductTypesChangeStreamPost (string options = null);
/// <summary>
/// Create a change stream.
/// </summary>
/// <remarks>
///
/// </remarks>
/// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="options"> (optional)</param>
/// <returns>ApiResponse of System.IO.Stream</returns>
ApiResponse<System.IO.Stream> ProductTypesChangeStreamPostWithHttpInfo (string options = null);
/// <summary>
/// Count instances of the model matched by where from the data source.
/// </summary>
/// <remarks>
///
/// </remarks>
/// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="where">Criteria to match model instances (optional)</param>
/// <returns>InlineResponse2001</returns>
InlineResponse2001 ProductTypesCountGet (string where = null);
/// <summary>
/// Count instances of the model matched by where from the data source.
/// </summary>
/// <remarks>
///
/// </remarks>
/// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="where">Criteria to match model instances (optional)</param>
/// <returns>ApiResponse of InlineResponse2001</returns>
ApiResponse<InlineResponse2001> ProductTypesCountGetWithHttpInfo (string where = null);
/// <summary>
/// Find first instance of the model matched by filter from the data source.
/// </summary>
/// <remarks>
///
/// </remarks>
/// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="filter">Filter defining fields, where, include, order, offset, and limit - must be a JSON-encoded string ({\"something\":\"value\"}) (optional)</param>
/// <returns>ProductType</returns>
ProductType ProductTypesFindOneGet (string filter = null);
/// <summary>
/// Find first instance of the model matched by filter from the data source.
/// </summary>
/// <remarks>
///
/// </remarks>
/// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="filter">Filter defining fields, where, include, order, offset, and limit - must be a JSON-encoded string ({\"something\":\"value\"}) (optional)</param>
/// <returns>ApiResponse of ProductType</returns>
ApiResponse<ProductType> ProductTypesFindOneGetWithHttpInfo (string filter = null);
/// <summary>
/// Find all instances of the model matched by filter from the data source.
/// </summary>
/// <remarks>
///
/// </remarks>
/// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="filter">Filter defining fields, where, include, order, offset, and limit - must be a JSON-encoded string ({\"something\":\"value\"}) (optional)</param>
/// <returns>List<ProductType></returns>
List<ProductType> ProductTypesGet (string filter = null);
/// <summary>
/// Find all instances of the model matched by filter from the data source.
/// </summary>
/// <remarks>
///
/// </remarks>
/// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="filter">Filter defining fields, where, include, order, offset, and limit - must be a JSON-encoded string ({\"something\":\"value\"}) (optional)</param>
/// <returns>ApiResponse of List<ProductType></returns>
ApiResponse<List<ProductType>> ProductTypesGetWithHttpInfo (string filter = null);
/// <summary>
/// Delete a model instance by {{id}} from the data source.
/// </summary>
/// <remarks>
///
/// </remarks>
/// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="id">Model id</param>
/// <returns>Object</returns>
Object ProductTypesIdDelete (string id);
/// <summary>
/// Delete a model instance by {{id}} from the data source.
/// </summary>
/// <remarks>
///
/// </remarks>
/// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="id">Model id</param>
/// <returns>ApiResponse of Object</returns>
ApiResponse<Object> ProductTypesIdDeleteWithHttpInfo (string id);
/// <summary>
/// Check whether a model instance exists in the data source.
/// </summary>
/// <remarks>
///
/// </remarks>
/// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="id">Model id</param>
/// <returns>InlineResponse2002</returns>
InlineResponse2002 ProductTypesIdExistsGet (string id);
/// <summary>
/// Check whether a model instance exists in the data source.
/// </summary>
/// <remarks>
///
/// </remarks>
/// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="id">Model id</param>
/// <returns>ApiResponse of InlineResponse2002</returns>
ApiResponse<InlineResponse2002> ProductTypesIdExistsGetWithHttpInfo (string id);
/// <summary>
/// Find a model instance by {{id}} from the data source.
/// </summary>
/// <remarks>
///
/// </remarks>
/// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="id">Model id</param>
/// <param name="filter">Filter defining fields and include - must be a JSON-encoded string ({\"something\":\"value\"}) (optional)</param>
/// <returns>ProductType</returns>
ProductType ProductTypesIdGet (string id, string filter = null);
/// <summary>
/// Find a model instance by {{id}} from the data source.
/// </summary>
/// <remarks>
///
/// </remarks>
/// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="id">Model id</param>
/// <param name="filter">Filter defining fields and include - must be a JSON-encoded string ({\"something\":\"value\"}) (optional)</param>
/// <returns>ApiResponse of ProductType</returns>
ApiResponse<ProductType> ProductTypesIdGetWithHttpInfo (string id, string filter = null);
/// <summary>
/// Fetches belongsTo relation group.
/// </summary>
/// <remarks>
///
/// </remarks>
/// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="id">ProductType id</param>
/// <param name="refresh"> (optional)</param>
/// <returns>ProductGroup</returns>
ProductGroup ProductTypesIdGroupGet (string id, bool? refresh = null);
/// <summary>
/// Fetches belongsTo relation group.
/// </summary>
/// <remarks>
///
/// </remarks>
/// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="id">ProductType id</param>
/// <param name="refresh"> (optional)</param>
/// <returns>ApiResponse of ProductGroup</returns>
ApiResponse<ProductGroup> ProductTypesIdGroupGetWithHttpInfo (string id, bool? refresh = null);
/// <summary>
/// Check whether a model instance exists in the data source.
/// </summary>
/// <remarks>
///
/// </remarks>
/// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="id">Model id</param>
/// <returns>InlineResponse2002</returns>
InlineResponse2002 ProductTypesIdHead (string id);
/// <summary>
/// Check whether a model instance exists in the data source.
/// </summary>
/// <remarks>
///
/// </remarks>
/// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="id">Model id</param>
/// <returns>ApiResponse of InlineResponse2002</returns>
ApiResponse<InlineResponse2002> ProductTypesIdHeadWithHttpInfo (string id);
/// <summary>
/// Patch attributes for a model instance and persist it into the data source.
/// </summary>
/// <remarks>
///
/// </remarks>
/// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="id">ProductType id</param>
/// <param name="data">An object of model property name/value pairs (optional)</param>
/// <returns>ProductType</returns>
ProductType ProductTypesIdPatch (string id, ProductType data = null);
/// <summary>
/// Patch attributes for a model instance and persist it into the data source.
/// </summary>
/// <remarks>
///
/// </remarks>
/// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="id">ProductType id</param>
/// <param name="data">An object of model property name/value pairs (optional)</param>
/// <returns>ApiResponse of ProductType</returns>
ApiResponse<ProductType> ProductTypesIdPatchWithHttpInfo (string id, ProductType data = null);
/// <summary>
/// Replace attributes for a model instance and persist it into the data source.
/// </summary>
/// <remarks>
///
/// </remarks>
/// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="id">Model id</param>
/// <param name="data">Model instance data (optional)</param>
/// <returns>ProductType</returns>
ProductType ProductTypesIdPut (string id, ProductType data = null);
/// <summary>
/// Replace attributes for a model instance and persist it into the data source.
/// </summary>
/// <remarks>
///
/// </remarks>
/// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="id">Model id</param>
/// <param name="data">Model instance data (optional)</param>
/// <returns>ApiResponse of ProductType</returns>
ApiResponse<ProductType> ProductTypesIdPutWithHttpInfo (string id, ProductType data = null);
/// <summary>
/// Replace attributes for a model instance and persist it into the data source.
/// </summary>
/// <remarks>
///
/// </remarks>
/// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="id">Model id</param>
/// <param name="data">Model instance data (optional)</param>
/// <returns>ProductType</returns>
ProductType ProductTypesIdReplacePost (string id, ProductType data = null);
/// <summary>
/// Replace attributes for a model instance and persist it into the data source.
/// </summary>
/// <remarks>
///
/// </remarks>
/// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="id">Model id</param>
/// <param name="data">Model instance data (optional)</param>
/// <returns>ApiResponse of ProductType</returns>
ApiResponse<ProductType> ProductTypesIdReplacePostWithHttpInfo (string id, ProductType data = null);
/// <summary>
/// Counts sizes of ProductType.
/// </summary>
/// <remarks>
///
/// </remarks>
/// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="id">ProductType id</param>
/// <param name="where">Criteria to match model instances (optional)</param>
/// <returns>InlineResponse2001</returns>
InlineResponse2001 ProductTypesIdSizesCountGet (string id, string where = null);
/// <summary>
/// Counts sizes of ProductType.
/// </summary>
/// <remarks>
///
/// </remarks>
/// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="id">ProductType id</param>
/// <param name="where">Criteria to match model instances (optional)</param>
/// <returns>ApiResponse of InlineResponse2001</returns>
ApiResponse<InlineResponse2001> ProductTypesIdSizesCountGetWithHttpInfo (string id, string where = null);
/// <summary>
/// Delete a related item by id for sizes.
/// </summary>
/// <remarks>
///
/// </remarks>
/// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="id">ProductType id</param>
/// <param name="fk">Foreign key for sizes</param>
/// <returns></returns>
void ProductTypesIdSizesFkDelete (string id, string fk);
/// <summary>
/// Delete a related item by id for sizes.
/// </summary>
/// <remarks>
///
/// </remarks>
/// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="id">ProductType id</param>
/// <param name="fk">Foreign key for sizes</param>
/// <returns>ApiResponse of Object(void)</returns>
ApiResponse<Object> ProductTypesIdSizesFkDeleteWithHttpInfo (string id, string fk);
/// <summary>
/// Find a related item by id for sizes.
/// </summary>
/// <remarks>
///
/// </remarks>
/// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="id">ProductType id</param>
/// <param name="fk">Foreign key for sizes</param>
/// <returns>ProductSize</returns>
ProductSize ProductTypesIdSizesFkGet (string id, string fk);
/// <summary>
/// Find a related item by id for sizes.
/// </summary>
/// <remarks>
///
/// </remarks>
/// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="id">ProductType id</param>
/// <param name="fk">Foreign key for sizes</param>
/// <returns>ApiResponse of ProductSize</returns>
ApiResponse<ProductSize> ProductTypesIdSizesFkGetWithHttpInfo (string id, string fk);
/// <summary>
/// Update a related item by id for sizes.
/// </summary>
/// <remarks>
///
/// </remarks>
/// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="id">ProductType id</param>
/// <param name="fk">Foreign key for sizes</param>
/// <param name="data"> (optional)</param>
/// <returns>ProductSize</returns>
ProductSize ProductTypesIdSizesFkPut (string id, string fk, ProductSize data = null);
/// <summary>
/// Update a related item by id for sizes.
/// </summary>
/// <remarks>
///
/// </remarks>
/// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="id">ProductType id</param>
/// <param name="fk">Foreign key for sizes</param>
/// <param name="data"> (optional)</param>
/// <returns>ApiResponse of ProductSize</returns>
ApiResponse<ProductSize> ProductTypesIdSizesFkPutWithHttpInfo (string id, string fk, ProductSize data = null);
/// <summary>
/// Queries sizes of ProductType.
/// </summary>
/// <remarks>
///
/// </remarks>
/// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="id">ProductType id</param>
/// <param name="filter"> (optional)</param>
/// <returns>List<ProductSize></returns>
List<ProductSize> ProductTypesIdSizesGet (string id, string filter = null);
/// <summary>
/// Queries sizes of ProductType.
/// </summary>
/// <remarks>
///
/// </remarks>
/// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="id">ProductType id</param>
/// <param name="filter"> (optional)</param>
/// <returns>ApiResponse of List<ProductSize></returns>
ApiResponse<List<ProductSize>> ProductTypesIdSizesGetWithHttpInfo (string id, string filter = null);
/// <summary>
/// Creates a new instance in sizes of this model.
/// </summary>
/// <remarks>
///
/// </remarks>
/// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="id">ProductType id</param>
/// <param name="data"> (optional)</param>
/// <returns>ProductSize</returns>
ProductSize ProductTypesIdSizesPost (string id, ProductSize data = null);
/// <summary>
/// Creates a new instance in sizes of this model.
/// </summary>
/// <remarks>
///
/// </remarks>
/// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="id">ProductType id</param>
/// <param name="data"> (optional)</param>
/// <returns>ApiResponse of ProductSize</returns>
ApiResponse<ProductSize> ProductTypesIdSizesPostWithHttpInfo (string id, ProductSize data = null);
/// <summary>
/// Create a new instance of the model and persist it into the data source.
/// </summary>
/// <remarks>
///
/// </remarks>
/// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="data">Model instance data (optional)</param>
/// <returns>ProductType</returns>
ProductType ProductTypesPost (ProductType data = null);
/// <summary>
/// Create a new instance of the model and persist it into the data source.
/// </summary>
/// <remarks>
///
/// </remarks>
/// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="data">Model instance data (optional)</param>
/// <returns>ApiResponse of ProductType</returns>
ApiResponse<ProductType> ProductTypesPostWithHttpInfo (ProductType data = null);
#endregion Synchronous Operations
#region Asynchronous Operations
/// <summary>
/// Create a change stream.
/// </summary>
/// <remarks>
///
/// </remarks>
/// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="options"> (optional)</param>
/// <returns>Task of System.IO.Stream</returns>
System.Threading.Tasks.Task<System.IO.Stream> ProductTypesChangeStreamGetAsync (string options = null);
/// <summary>
/// Create a change stream.
/// </summary>
/// <remarks>
///
/// </remarks>
/// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="options"> (optional)</param>
/// <returns>Task of ApiResponse (System.IO.Stream)</returns>
System.Threading.Tasks.Task<ApiResponse<System.IO.Stream>> ProductTypesChangeStreamGetAsyncWithHttpInfo (string options = null);
/// <summary>
/// Create a change stream.
/// </summary>
/// <remarks>
///
/// </remarks>
/// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="options"> (optional)</param>
/// <returns>Task of System.IO.Stream</returns>
System.Threading.Tasks.Task<System.IO.Stream> ProductTypesChangeStreamPostAsync (string options = null);
/// <summary>
/// Create a change stream.
/// </summary>
/// <remarks>
///
/// </remarks>
/// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="options"> (optional)</param>
/// <returns>Task of ApiResponse (System.IO.Stream)</returns>
System.Threading.Tasks.Task<ApiResponse<System.IO.Stream>> ProductTypesChangeStreamPostAsyncWithHttpInfo (string options = null);
/// <summary>
/// Count instances of the model matched by where from the data source.
/// </summary>
/// <remarks>
///
/// </remarks>
/// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="where">Criteria to match model instances (optional)</param>
/// <returns>Task of InlineResponse2001</returns>
System.Threading.Tasks.Task<InlineResponse2001> ProductTypesCountGetAsync (string where = null);
/// <summary>
/// Count instances of the model matched by where from the data source.
/// </summary>
/// <remarks>
///
/// </remarks>
/// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="where">Criteria to match model instances (optional)</param>
/// <returns>Task of ApiResponse (InlineResponse2001)</returns>
System.Threading.Tasks.Task<ApiResponse<InlineResponse2001>> ProductTypesCountGetAsyncWithHttpInfo (string where = null);
/// <summary>
/// Find first instance of the model matched by filter from the data source.
/// </summary>
/// <remarks>
///
/// </remarks>
/// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="filter">Filter defining fields, where, include, order, offset, and limit - must be a JSON-encoded string ({\"something\":\"value\"}) (optional)</param>
/// <returns>Task of ProductType</returns>
System.Threading.Tasks.Task<ProductType> ProductTypesFindOneGetAsync (string filter = null);
/// <summary>
/// Find first instance of the model matched by filter from the data source.
/// </summary>
/// <remarks>
///
/// </remarks>
/// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="filter">Filter defining fields, where, include, order, offset, and limit - must be a JSON-encoded string ({\"something\":\"value\"}) (optional)</param>
/// <returns>Task of ApiResponse (ProductType)</returns>
System.Threading.Tasks.Task<ApiResponse<ProductType>> ProductTypesFindOneGetAsyncWithHttpInfo (string filter = null);
/// <summary>
/// Find all instances of the model matched by filter from the data source.
/// </summary>
/// <remarks>
///
/// </remarks>
/// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="filter">Filter defining fields, where, include, order, offset, and limit - must be a JSON-encoded string ({\"something\":\"value\"}) (optional)</param>
/// <returns>Task of List<ProductType></returns>
System.Threading.Tasks.Task<List<ProductType>> ProductTypesGetAsync (string filter = null);
/// <summary>
/// Find all instances of the model matched by filter from the data source.
/// </summary>
/// <remarks>
///
/// </remarks>
/// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="filter">Filter defining fields, where, include, order, offset, and limit - must be a JSON-encoded string ({\"something\":\"value\"}) (optional)</param>
/// <returns>Task of ApiResponse (List<ProductType>)</returns>
System.Threading.Tasks.Task<ApiResponse<List<ProductType>>> ProductTypesGetAsyncWithHttpInfo (string filter = null);
/// <summary>
/// Delete a model instance by {{id}} from the data source.
/// </summary>
/// <remarks>
///
/// </remarks>
/// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="id">Model id</param>
/// <returns>Task of Object</returns>
System.Threading.Tasks.Task<Object> ProductTypesIdDeleteAsync (string id);
/// <summary>
/// Delete a model instance by {{id}} from the data source.
/// </summary>
/// <remarks>
///
/// </remarks>
/// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="id">Model id</param>
/// <returns>Task of ApiResponse (Object)</returns>
System.Threading.Tasks.Task<ApiResponse<Object>> ProductTypesIdDeleteAsyncWithHttpInfo (string id);
/// <summary>
/// Check whether a model instance exists in the data source.
/// </summary>
/// <remarks>
///
/// </remarks>
/// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="id">Model id</param>
/// <returns>Task of InlineResponse2002</returns>
System.Threading.Tasks.Task<InlineResponse2002> ProductTypesIdExistsGetAsync (string id);
/// <summary>
/// Check whether a model instance exists in the data source.
/// </summary>
/// <remarks>
///
/// </remarks>
/// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="id">Model id</param>
/// <returns>Task of ApiResponse (InlineResponse2002)</returns>
System.Threading.Tasks.Task<ApiResponse<InlineResponse2002>> ProductTypesIdExistsGetAsyncWithHttpInfo (string id);
/// <summary>
/// Find a model instance by {{id}} from the data source.
/// </summary>
/// <remarks>
///
/// </remarks>
/// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="id">Model id</param>
/// <param name="filter">Filter defining fields and include - must be a JSON-encoded string ({\"something\":\"value\"}) (optional)</param>
/// <returns>Task of ProductType</returns>
System.Threading.Tasks.Task<ProductType> ProductTypesIdGetAsync (string id, string filter = null);
/// <summary>
/// Find a model instance by {{id}} from the data source.
/// </summary>
/// <remarks>
///
/// </remarks>
/// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="id">Model id</param>
/// <param name="filter">Filter defining fields and include - must be a JSON-encoded string ({\"something\":\"value\"}) (optional)</param>
/// <returns>Task of ApiResponse (ProductType)</returns>
System.Threading.Tasks.Task<ApiResponse<ProductType>> ProductTypesIdGetAsyncWithHttpInfo (string id, string filter = null);
/// <summary>
/// Fetches belongsTo relation group.
/// </summary>
/// <remarks>
///
/// </remarks>
/// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="id">ProductType id</param>
/// <param name="refresh"> (optional)</param>
/// <returns>Task of ProductGroup</returns>
System.Threading.Tasks.Task<ProductGroup> ProductTypesIdGroupGetAsync (string id, bool? refresh = null);
/// <summary>
/// Fetches belongsTo relation group.
/// </summary>
/// <remarks>
///
/// </remarks>
/// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="id">ProductType id</param>
/// <param name="refresh"> (optional)</param>
/// <returns>Task of ApiResponse (ProductGroup)</returns>
System.Threading.Tasks.Task<ApiResponse<ProductGroup>> ProductTypesIdGroupGetAsyncWithHttpInfo (string id, bool? refresh = null);
/// <summary>
/// Check whether a model instance exists in the data source.
/// </summary>
/// <remarks>
///
/// </remarks>
/// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="id">Model id</param>
/// <returns>Task of InlineResponse2002</returns>
System.Threading.Tasks.Task<InlineResponse2002> ProductTypesIdHeadAsync (string id);
/// <summary>
/// Check whether a model instance exists in the data source.
/// </summary>
/// <remarks>
///
/// </remarks>
/// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="id">Model id</param>
/// <returns>Task of ApiResponse (InlineResponse2002)</returns>
System.Threading.Tasks.Task<ApiResponse<InlineResponse2002>> ProductTypesIdHeadAsyncWithHttpInfo (string id);
/// <summary>
/// Patch attributes for a model instance and persist it into the data source.
/// </summary>
/// <remarks>
///
/// </remarks>
/// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="id">ProductType id</param>
/// <param name="data">An object of model property name/value pairs (optional)</param>
/// <returns>Task of ProductType</returns>
System.Threading.Tasks.Task<ProductType> ProductTypesIdPatchAsync (string id, ProductType data = null);
/// <summary>
/// Patch attributes for a model instance and persist it into the data source.
/// </summary>
/// <remarks>
///
/// </remarks>
/// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="id">ProductType id</param>
/// <param name="data">An object of model property name/value pairs (optional)</param>
/// <returns>Task of ApiResponse (ProductType)</returns>
System.Threading.Tasks.Task<ApiResponse<ProductType>> ProductTypesIdPatchAsyncWithHttpInfo (string id, ProductType data = null);
/// <summary>
/// Replace attributes for a model instance and persist it into the data source.
/// </summary>
/// <remarks>
///
/// </remarks>
/// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="id">Model id</param>
/// <param name="data">Model instance data (optional)</param>
/// <returns>Task of ProductType</returns>
System.Threading.Tasks.Task<ProductType> ProductTypesIdPutAsync (string id, ProductType data = null);
/// <summary>
/// Replace attributes for a model instance and persist it into the data source.
/// </summary>
/// <remarks>
///
/// </remarks>
/// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="id">Model id</param>
/// <param name="data">Model instance data (optional)</param>
/// <returns>Task of ApiResponse (ProductType)</returns>
System.Threading.Tasks.Task<ApiResponse<ProductType>> ProductTypesIdPutAsyncWithHttpInfo (string id, ProductType data = null);
/// <summary>
/// Replace attributes for a model instance and persist it into the data source.
/// </summary>
/// <remarks>
///
/// </remarks>
/// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="id">Model id</param>
/// <param name="data">Model instance data (optional)</param>
/// <returns>Task of ProductType</returns>
System.Threading.Tasks.Task<ProductType> ProductTypesIdReplacePostAsync (string id, ProductType data = null);
/// <summary>
/// Replace attributes for a model instance and persist it into the data source.
/// </summary>
/// <remarks>
///
/// </remarks>
/// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="id">Model id</param>
/// <param name="data">Model instance data (optional)</param>
/// <returns>Task of ApiResponse (ProductType)</returns>
System.Threading.Tasks.Task<ApiResponse<ProductType>> ProductTypesIdReplacePostAsyncWithHttpInfo (string id, ProductType data = null);
/// <summary>
/// Counts sizes of ProductType.
/// </summary>
/// <remarks>
///
/// </remarks>
/// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="id">ProductType id</param>
/// <param name="where">Criteria to match model instances (optional)</param>
/// <returns>Task of InlineResponse2001</returns>
System.Threading.Tasks.Task<InlineResponse2001> ProductTypesIdSizesCountGetAsync (string id, string where = null);
/// <summary>
/// Counts sizes of ProductType.
/// </summary>
/// <remarks>
///
/// </remarks>
/// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="id">ProductType id</param>
/// <param name="where">Criteria to match model instances (optional)</param>
/// <returns>Task of ApiResponse (InlineResponse2001)</returns>
System.Threading.Tasks.Task<ApiResponse<InlineResponse2001>> ProductTypesIdSizesCountGetAsyncWithHttpInfo (string id, string where = null);
/// <summary>
/// Delete a related item by id for sizes.
/// </summary>
/// <remarks>
///
/// </remarks>
/// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="id">ProductType id</param>
/// <param name="fk">Foreign key for sizes</param>
/// <returns>Task of void</returns>
System.Threading.Tasks.Task ProductTypesIdSizesFkDeleteAsync (string id, string fk);
/// <summary>
/// Delete a related item by id for sizes.
/// </summary>
/// <remarks>
///
/// </remarks>
/// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="id">ProductType id</param>
/// <param name="fk">Foreign key for sizes</param>
/// <returns>Task of ApiResponse</returns>
System.Threading.Tasks.Task<ApiResponse<Object>> ProductTypesIdSizesFkDeleteAsyncWithHttpInfo (string id, string fk);
/// <summary>
/// Find a related item by id for sizes.
/// </summary>
/// <remarks>
///
/// </remarks>
/// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="id">ProductType id</param>
/// <param name="fk">Foreign key for sizes</param>
/// <returns>Task of ProductSize</returns>
System.Threading.Tasks.Task<ProductSize> ProductTypesIdSizesFkGetAsync (string id, string fk);
/// <summary>
/// Find a related item by id for sizes.
/// </summary>
/// <remarks>
///
/// </remarks>
/// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="id">ProductType id</param>
/// <param name="fk">Foreign key for sizes</param>
/// <returns>Task of ApiResponse (ProductSize)</returns>
System.Threading.Tasks.Task<ApiResponse<ProductSize>> ProductTypesIdSizesFkGetAsyncWithHttpInfo (string id, string fk);
/// <summary>
/// Update a related item by id for sizes.
/// </summary>
/// <remarks>
///
/// </remarks>
/// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="id">ProductType id</param>
/// <param name="fk">Foreign key for sizes</param>
/// <param name="data"> (optional)</param>
/// <returns>Task of ProductSize</returns>
System.Threading.Tasks.Task<ProductSize> ProductTypesIdSizesFkPutAsync (string id, string fk, ProductSize data = null);
/// <summary>
/// Update a related item by id for sizes.
/// </summary>
/// <remarks>
///
/// </remarks>
/// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="id">ProductType id</param>
/// <param name="fk">Foreign key for sizes</param>
/// <param name="data"> (optional)</param>
/// <returns>Task of ApiResponse (ProductSize)</returns>
System.Threading.Tasks.Task<ApiResponse<ProductSize>> ProductTypesIdSizesFkPutAsyncWithHttpInfo (string id, string fk, ProductSize data = null);
/// <summary>
/// Queries sizes of ProductType.
/// </summary>
/// <remarks>
///
/// </remarks>
/// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="id">ProductType id</param>
/// <param name="filter"> (optional)</param>
/// <returns>Task of List<ProductSize></returns>
System.Threading.Tasks.Task<List<ProductSize>> ProductTypesIdSizesGetAsync (string id, string filter = null);
/// <summary>
/// Queries sizes of ProductType.
/// </summary>
/// <remarks>
///
/// </remarks>
/// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="id">ProductType id</param>
/// <param name="filter"> (optional)</param>
/// <returns>Task of ApiResponse (List<ProductSize>)</returns>
System.Threading.Tasks.Task<ApiResponse<List<ProductSize>>> ProductTypesIdSizesGetAsyncWithHttpInfo (string id, string filter = null);
/// <summary>
/// Creates a new instance in sizes of this model.
/// </summary>
/// <remarks>
///
/// </remarks>
/// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="id">ProductType id</param>
/// <param name="data"> (optional)</param>
/// <returns>Task of ProductSize</returns>
System.Threading.Tasks.Task<ProductSize> ProductTypesIdSizesPostAsync (string id, ProductSize data = null);
/// <summary>
/// Creates a new instance in sizes of this model.
/// </summary>
/// <remarks>
///
/// </remarks>
/// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="id">ProductType id</param>
/// <param name="data"> (optional)</param>
/// <returns>Task of ApiResponse (ProductSize)</returns>
System.Threading.Tasks.Task<ApiResponse<ProductSize>> ProductTypesIdSizesPostAsyncWithHttpInfo (string id, ProductSize data = null);
/// <summary>
/// Create a new instance of the model and persist it into the data source.
/// </summary>
/// <remarks>
///
/// </remarks>
/// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="data">Model instance data (optional)</param>
/// <returns>Task of ProductType</returns>
System.Threading.Tasks.Task<ProductType> ProductTypesPostAsync (ProductType data = null);
/// <summary>
/// Create a new instance of the model and persist it into the data source.
/// </summary>
/// <remarks>
///
/// </remarks>
/// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="data">Model instance data (optional)</param>
/// <returns>Task of ApiResponse (ProductType)</returns>
System.Threading.Tasks.Task<ApiResponse<ProductType>> ProductTypesPostAsyncWithHttpInfo (ProductType data = null);
#endregion Asynchronous Operations
}
/// <summary>
/// Represents a collection of functions to interact with the API endpoints
/// </summary>
public partial class ProductTypeApi : IProductTypeApi
{
private TweakApi.Client.ExceptionFactory _exceptionFactory = (name, response) => null;
/// <summary>
/// Initializes a new instance of the <see cref="ProductTypeApi"/> class.
/// </summary>
/// <returns></returns>
public ProductTypeApi(String basePath)
{
this.Configuration = new Configuration(new ApiClient(basePath));
ExceptionFactory = TweakApi.Client.Configuration.DefaultExceptionFactory;
// ensure API client has configuration ready
if (Configuration.ApiClient.Configuration == null)
{
this.Configuration.ApiClient.Configuration = this.Configuration;
}
}
/// <summary>
/// Initializes a new instance of the <see cref="ProductTypeApi"/> class
/// using Configuration object
/// </summary>
/// <param name="configuration">An instance of Configuration</param>
/// <returns></returns>
public ProductTypeApi(Configuration configuration = null)
{
if (configuration == null) // use the default one in Configuration
this.Configuration = Configuration.Default;
else
this.Configuration = configuration;
ExceptionFactory = TweakApi.Client.Configuration.DefaultExceptionFactory;
// ensure API client has configuration ready
if (Configuration.ApiClient.Configuration == null)
{
this.Configuration.ApiClient.Configuration = this.Configuration;
}
}
/// <summary>
/// Gets the base path of the API client.
/// </summary>
/// <value>The base path</value>
public String GetBasePath()
{
return this.Configuration.ApiClient.RestClient.BaseUrl.ToString();
}
/// <summary>
/// Sets the base path of the API client.
/// </summary>
/// <value>The base path</value>
[Obsolete("SetBasePath is deprecated, please do 'Configuration.ApiClient = new ApiClient(\"http://new-path\")' instead.")]
public void SetBasePath(String basePath)
{
// do nothing
}
/// <summary>
/// Gets or sets the configuration object
/// </summary>
/// <value>An instance of the Configuration</value>
public Configuration Configuration {get; set;}
/// <summary>
/// Provides a factory method hook for the creation of exceptions.
/// </summary>
public TweakApi.Client.ExceptionFactory ExceptionFactory
{
get
{
if (_exceptionFactory != null && _exceptionFactory.GetInvocationList().Length > 1)
{
throw new InvalidOperationException("Multicast delegate for ExceptionFactory is unsupported.");
}
return _exceptionFactory;
}
set { _exceptionFactory = value; }
}
/// <summary>
/// Gets the default header.
/// </summary>
/// <returns>Dictionary of HTTP header</returns>
[Obsolete("DefaultHeader is deprecated, please use Configuration.DefaultHeader instead.")]
public Dictionary<String, String> DefaultHeader()
{
return this.Configuration.DefaultHeader;
}
/// <summary>
/// Add default header.
/// </summary>
/// <param name="key">Header field name.</param>
/// <param name="value">Header field value.</param>
/// <returns></returns>
[Obsolete("AddDefaultHeader is deprecated, please use Configuration.AddDefaultHeader instead.")]
public void AddDefaultHeader(string key, string value)
{
this.Configuration.AddDefaultHeader(key, value);
}
/// <summary>
/// Create a change stream.
/// </summary>
/// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="options"> (optional)</param>
/// <returns>System.IO.Stream</returns>
public System.IO.Stream ProductTypesChangeStreamGet (string options = null)
{
ApiResponse<System.IO.Stream> localVarResponse = ProductTypesChangeStreamGetWithHttpInfo(options);
return localVarResponse.Data;
}
/// <summary>
/// Create a change stream.
/// </summary>
/// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="options"> (optional)</param>
/// <returns>ApiResponse of System.IO.Stream</returns>
public ApiResponse< System.IO.Stream > ProductTypesChangeStreamGetWithHttpInfo (string options = null)
{
var localVarPath = "/ProductTypes/change-stream";
var localVarPathParams = new Dictionary<String, String>();
var localVarQueryParams = new Dictionary<String, String>();
var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader);
var localVarFormParams = new Dictionary<String, String>();
var localVarFileParams = new Dictionary<String, FileParameter>();
Object localVarPostBody = null;
// to determine the Content-Type header
String[] localVarHttpContentTypes = new String[] {
"application/json",
"application/x-www-form-urlencoded",
"application/xml",
"text/xml"
};
String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes);
// to determine the Accept header
String[] localVarHttpHeaderAccepts = new String[] {
"application/json",
"application/xml",
"text/xml",
"application/javascript",
"text/javascript"
};
String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts);
if (localVarHttpHeaderAccept != null)
localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept);
// set "format" to json by default
// e.g. /pet/{petId}.{format} becomes /pet/{petId}.json
localVarPathParams.Add("format", "json");
if (options != null) localVarQueryParams.Add("options", Configuration.ApiClient.ParameterToString(options)); // query parameter
// authentication (access_token) required
if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("access_token")))
{
localVarQueryParams["access_token"] = Configuration.GetApiKeyWithPrefix("access_token");
}
// make the HTTP request
IRestResponse localVarResponse = (IRestResponse) Configuration.ApiClient.CallApi(localVarPath,
Method.GET, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams,
localVarPathParams, localVarHttpContentType);
int localVarStatusCode = (int) localVarResponse.StatusCode;
if (ExceptionFactory != null)
{
Exception exception = ExceptionFactory("ProductTypesChangeStreamGet", localVarResponse);
if (exception != null) throw exception;
}
return new ApiResponse<System.IO.Stream>(localVarStatusCode,
localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()),
(System.IO.Stream) Configuration.ApiClient.Deserialize(localVarResponse, typeof(System.IO.Stream)));
}
/// <summary>
/// Create a change stream.
/// </summary>
/// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="options"> (optional)</param>
/// <returns>Task of System.IO.Stream</returns>
public async System.Threading.Tasks.Task<System.IO.Stream> ProductTypesChangeStreamGetAsync (string options = null)
{
ApiResponse<System.IO.Stream> localVarResponse = await ProductTypesChangeStreamGetAsyncWithHttpInfo(options);
return localVarResponse.Data;
}
/// <summary>
/// Create a change stream.
/// </summary>
/// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="options"> (optional)</param>
/// <returns>Task of ApiResponse (System.IO.Stream)</returns>
public async System.Threading.Tasks.Task<ApiResponse<System.IO.Stream>> ProductTypesChangeStreamGetAsyncWithHttpInfo (string options = null)
{
var localVarPath = "/ProductTypes/change-stream";
var localVarPathParams = new Dictionary<String, String>();
var localVarQueryParams = new Dictionary<String, String>();
var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader);
var localVarFormParams = new Dictionary<String, String>();
var localVarFileParams = new Dictionary<String, FileParameter>();
Object localVarPostBody = null;
// to determine the Content-Type header
String[] localVarHttpContentTypes = new String[] {
"application/json",
"application/x-www-form-urlencoded",
"application/xml",
"text/xml"
};
String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes);
// to determine the Accept header
String[] localVarHttpHeaderAccepts = new String[] {
"application/json",
"application/xml",
"text/xml",
"application/javascript",
"text/javascript"
};
String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts);
if (localVarHttpHeaderAccept != null)
localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept);
// set "format" to json by default
// e.g. /pet/{petId}.{format} becomes /pet/{petId}.json
localVarPathParams.Add("format", "json");
if (options != null) localVarQueryParams.Add("options", Configuration.ApiClient.ParameterToString(options)); // query parameter
// authentication (access_token) required
if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("access_token")))
{
localVarQueryParams["access_token"] = Configuration.GetApiKeyWithPrefix("access_token");
}
// make the HTTP request
IRestResponse localVarResponse = (IRestResponse) await Configuration.ApiClient.CallApiAsync(localVarPath,
Method.GET, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams,
localVarPathParams, localVarHttpContentType);
int localVarStatusCode = (int) localVarResponse.StatusCode;
if (ExceptionFactory != null)
{
Exception exception = ExceptionFactory("ProductTypesChangeStreamGet", localVarResponse);
if (exception != null) throw exception;
}
return new ApiResponse<System.IO.Stream>(localVarStatusCode,
localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()),
(System.IO.Stream) Configuration.ApiClient.Deserialize(localVarResponse, typeof(System.IO.Stream)));
}
/// <summary>
/// Create a change stream.
/// </summary>
/// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="options"> (optional)</param>
/// <returns>System.IO.Stream</returns>
public System.IO.Stream ProductTypesChangeStreamPost (string options = null)
{
ApiResponse<System.IO.Stream> localVarResponse = ProductTypesChangeStreamPostWithHttpInfo(options);
return localVarResponse.Data;
}
/// <summary>
/// Create a change stream.
/// </summary>
/// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="options"> (optional)</param>
/// <returns>ApiResponse of System.IO.Stream</returns>
public ApiResponse< System.IO.Stream > ProductTypesChangeStreamPostWithHttpInfo (string options = null)
{
var localVarPath = "/ProductTypes/change-stream";
var localVarPathParams = new Dictionary<String, String>();
var localVarQueryParams = new Dictionary<String, String>();
var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader);
var localVarFormParams = new Dictionary<String, String>();
var localVarFileParams = new Dictionary<String, FileParameter>();
Object localVarPostBody = null;
// to determine the Content-Type header
String[] localVarHttpContentTypes = new String[] {
"application/json",
"application/x-www-form-urlencoded",
"application/xml",
"text/xml"
};
String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes);
// to determine the Accept header
String[] localVarHttpHeaderAccepts = new String[] {
"application/json",
"application/xml",
"text/xml",
"application/javascript",
"text/javascript"
};
String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts);
if (localVarHttpHeaderAccept != null)
localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept);
// set "format" to json by default
// e.g. /pet/{petId}.{format} becomes /pet/{petId}.json
localVarPathParams.Add("format", "json");
if (options != null) localVarFormParams.Add("options", Configuration.ApiClient.ParameterToString(options)); // form parameter
// authentication (access_token) required
if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("access_token")))
{
localVarQueryParams["access_token"] = Configuration.GetApiKeyWithPrefix("access_token");
}
// make the HTTP request
IRestResponse localVarResponse = (IRestResponse) Configuration.ApiClient.CallApi(localVarPath,
Method.POST, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams,
localVarPathParams, localVarHttpContentType);
int localVarStatusCode = (int) localVarResponse.StatusCode;
if (ExceptionFactory != null)
{
Exception exception = ExceptionFactory("ProductTypesChangeStreamPost", localVarResponse);
if (exception != null) throw exception;
}
return new ApiResponse<System.IO.Stream>(localVarStatusCode,
localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()),
(System.IO.Stream) Configuration.ApiClient.Deserialize(localVarResponse, typeof(System.IO.Stream)));
}
/// <summary>
/// Create a change stream.
/// </summary>
/// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="options"> (optional)</param>
/// <returns>Task of System.IO.Stream</returns>
public async System.Threading.Tasks.Task<System.IO.Stream> ProductTypesChangeStreamPostAsync (string options = null)
{
ApiResponse<System.IO.Stream> localVarResponse = await ProductTypesChangeStreamPostAsyncWithHttpInfo(options);
return localVarResponse.Data;
}
/// <summary>
/// Create a change stream.
/// </summary>
/// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="options"> (optional)</param>
/// <returns>Task of ApiResponse (System.IO.Stream)</returns>
public async System.Threading.Tasks.Task<ApiResponse<System.IO.Stream>> ProductTypesChangeStreamPostAsyncWithHttpInfo (string options = null)
{
var localVarPath = "/ProductTypes/change-stream";
var localVarPathParams = new Dictionary<String, String>();
var localVarQueryParams = new Dictionary<String, String>();
var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader);
var localVarFormParams = new Dictionary<String, String>();
var localVarFileParams = new Dictionary<String, FileParameter>();
Object localVarPostBody = null;
// to determine the Content-Type header
String[] localVarHttpContentTypes = new String[] {
"application/json",
"application/x-www-form-urlencoded",
"application/xml",
"text/xml"
};
String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes);
// to determine the Accept header
String[] localVarHttpHeaderAccepts = new String[] {
"application/json",
"application/xml",
"text/xml",
"application/javascript",
"text/javascript"
};
String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts);
if (localVarHttpHeaderAccept != null)
localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept);
// set "format" to json by default
// e.g. /pet/{petId}.{format} becomes /pet/{petId}.json
localVarPathParams.Add("format", "json");
if (options != null) localVarFormParams.Add("options", Configuration.ApiClient.ParameterToString(options)); // form parameter
// authentication (access_token) required
if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("access_token")))
{
localVarQueryParams["access_token"] = Configuration.GetApiKeyWithPrefix("access_token");
}
// make the HTTP request
IRestResponse localVarResponse = (IRestResponse) await Configuration.ApiClient.CallApiAsync(localVarPath,
Method.POST, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams,
localVarPathParams, localVarHttpContentType);
int localVarStatusCode = (int) localVarResponse.StatusCode;
if (ExceptionFactory != null)
{
Exception exception = ExceptionFactory("ProductTypesChangeStreamPost", localVarResponse);
if (exception != null) throw exception;
}
return new ApiResponse<System.IO.Stream>(localVarStatusCode,
localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()),
(System.IO.Stream) Configuration.ApiClient.Deserialize(localVarResponse, typeof(System.IO.Stream)));
}
/// <summary>
/// Count instances of the model matched by where from the data source.
/// </summary>
/// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="where">Criteria to match model instances (optional)</param>
/// <returns>InlineResponse2001</returns>
public InlineResponse2001 ProductTypesCountGet (string where = null)
{
ApiResponse<InlineResponse2001> localVarResponse = ProductTypesCountGetWithHttpInfo(where);
return localVarResponse.Data;
}
/// <summary>
/// Count instances of the model matched by where from the data source.
/// </summary>
/// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="where">Criteria to match model instances (optional)</param>
/// <returns>ApiResponse of InlineResponse2001</returns>
public ApiResponse< InlineResponse2001 > ProductTypesCountGetWithHttpInfo (string where = null)
{
var localVarPath = "/ProductTypes/count";
var localVarPathParams = new Dictionary<String, String>();
var localVarQueryParams = new Dictionary<String, String>();
var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader);
var localVarFormParams = new Dictionary<String, String>();
var localVarFileParams = new Dictionary<String, FileParameter>();
Object localVarPostBody = null;
// to determine the Content-Type header
String[] localVarHttpContentTypes = new String[] {
"application/json",
"application/x-www-form-urlencoded",
"application/xml",
"text/xml"
};
String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes);
// to determine the Accept header
String[] localVarHttpHeaderAccepts = new String[] {
"application/json",
"application/xml",
"text/xml",
"application/javascript",
"text/javascript"
};
String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts);
if (localVarHttpHeaderAccept != null)
localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept);
// set "format" to json by default
// e.g. /pet/{petId}.{format} becomes /pet/{petId}.json
localVarPathParams.Add("format", "json");
if (where != null) localVarQueryParams.Add("where", Configuration.ApiClient.ParameterToString(where)); // query parameter
// authentication (access_token) required
if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("access_token")))
{
localVarQueryParams["access_token"] = Configuration.GetApiKeyWithPrefix("access_token");
}
// make the HTTP request
IRestResponse localVarResponse = (IRestResponse) Configuration.ApiClient.CallApi(localVarPath,
Method.GET, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams,
localVarPathParams, localVarHttpContentType);
int localVarStatusCode = (int) localVarResponse.StatusCode;
if (ExceptionFactory != null)
{
Exception exception = ExceptionFactory("ProductTypesCountGet", localVarResponse);
if (exception != null) throw exception;
}
return new ApiResponse<InlineResponse2001>(localVarStatusCode,
localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()),
(InlineResponse2001) Configuration.ApiClient.Deserialize(localVarResponse, typeof(InlineResponse2001)));
}
/// <summary>
/// Count instances of the model matched by where from the data source.
/// </summary>
/// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="where">Criteria to match model instances (optional)</param>
/// <returns>Task of InlineResponse2001</returns>
public async System.Threading.Tasks.Task<InlineResponse2001> ProductTypesCountGetAsync (string where = null)
{
ApiResponse<InlineResponse2001> localVarResponse = await ProductTypesCountGetAsyncWithHttpInfo(where);
return localVarResponse.Data;
}
/// <summary>
/// Count instances of the model matched by where from the data source.
/// </summary>
/// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="where">Criteria to match model instances (optional)</param>
/// <returns>Task of ApiResponse (InlineResponse2001)</returns>
public async System.Threading.Tasks.Task<ApiResponse<InlineResponse2001>> ProductTypesCountGetAsyncWithHttpInfo (string where = null)
{
var localVarPath = "/ProductTypes/count";
var localVarPathParams = new Dictionary<String, String>();
var localVarQueryParams = new Dictionary<String, String>();
var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader);
var localVarFormParams = new Dictionary<String, String>();
var localVarFileParams = new Dictionary<String, FileParameter>();
Object localVarPostBody = null;
// to determine the Content-Type header
String[] localVarHttpContentTypes = new String[] {
"application/json",
"application/x-www-form-urlencoded",
"application/xml",
"text/xml"
};
String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes);
// to determine the Accept header
String[] localVarHttpHeaderAccepts = new String[] {
"application/json",
"application/xml",
"text/xml",
"application/javascript",
"text/javascript"
};
String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts);
if (localVarHttpHeaderAccept != null)
localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept);
// set "format" to json by default
// e.g. /pet/{petId}.{format} becomes /pet/{petId}.json
localVarPathParams.Add("format", "json");
if (where != null) localVarQueryParams.Add("where", Configuration.ApiClient.ParameterToString(where)); // query parameter
// authentication (access_token) required
if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("access_token")))
{
localVarQueryParams["access_token"] = Configuration.GetApiKeyWithPrefix("access_token");
}
// make the HTTP request
IRestResponse localVarResponse = (IRestResponse) await Configuration.ApiClient.CallApiAsync(localVarPath,
Method.GET, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams,
localVarPathParams, localVarHttpContentType);
int localVarStatusCode = (int) localVarResponse.StatusCode;
if (ExceptionFactory != null)
{
Exception exception = ExceptionFactory("ProductTypesCountGet", localVarResponse);
if (exception != null) throw exception;
}
return new ApiResponse<InlineResponse2001>(localVarStatusCode,
localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()),
(InlineResponse2001) Configuration.ApiClient.Deserialize(localVarResponse, typeof(InlineResponse2001)));
}
/// <summary>
/// Find first instance of the model matched by filter from the data source.
/// </summary>
/// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="filter">Filter defining fields, where, include, order, offset, and limit - must be a JSON-encoded string ({\"something\":\"value\"}) (optional)</param>
/// <returns>ProductType</returns>
public ProductType ProductTypesFindOneGet (string filter = null)
{
ApiResponse<ProductType> localVarResponse = ProductTypesFindOneGetWithHttpInfo(filter);
return localVarResponse.Data;
}
/// <summary>
/// Find first instance of the model matched by filter from the data source.
/// </summary>
/// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="filter">Filter defining fields, where, include, order, offset, and limit - must be a JSON-encoded string ({\"something\":\"value\"}) (optional)</param>
/// <returns>ApiResponse of ProductType</returns>
public ApiResponse< ProductType > ProductTypesFindOneGetWithHttpInfo (string filter = null)
{
var localVarPath = "/ProductTypes/findOne";
var localVarPathParams = new Dictionary<String, String>();
var localVarQueryParams = new Dictionary<String, String>();
var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader);
var localVarFormParams = new Dictionary<String, String>();
var localVarFileParams = new Dictionary<String, FileParameter>();
Object localVarPostBody = null;
// to determine the Content-Type header
String[] localVarHttpContentTypes = new String[] {
"application/json",
"application/x-www-form-urlencoded",
"application/xml",
"text/xml"
};
String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes);
// to determine the Accept header
String[] localVarHttpHeaderAccepts = new String[] {
"application/json",
"application/xml",
"text/xml",
"application/javascript",
"text/javascript"
};
String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts);
if (localVarHttpHeaderAccept != null)
localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept);
// set "format" to json by default
// e.g. /pet/{petId}.{format} becomes /pet/{petId}.json
localVarPathParams.Add("format", "json");
if (filter != null) localVarQueryParams.Add("filter", Configuration.ApiClient.ParameterToString(filter)); // query parameter
// authentication (access_token) required
if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("access_token")))
{
localVarQueryParams["access_token"] = Configuration.GetApiKeyWithPrefix("access_token");
}
// make the HTTP request
IRestResponse localVarResponse = (IRestResponse) Configuration.ApiClient.CallApi(localVarPath,
Method.GET, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams,
localVarPathParams, localVarHttpContentType);
int localVarStatusCode = (int) localVarResponse.StatusCode;
if (ExceptionFactory != null)
{
Exception exception = ExceptionFactory("ProductTypesFindOneGet", localVarResponse);
if (exception != null) throw exception;
}
return new ApiResponse<ProductType>(localVarStatusCode,
localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()),
(ProductType) Configuration.ApiClient.Deserialize(localVarResponse, typeof(ProductType)));
}
/// <summary>
/// Find first instance of the model matched by filter from the data source.
/// </summary>
/// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="filter">Filter defining fields, where, include, order, offset, and limit - must be a JSON-encoded string ({\"something\":\"value\"}) (optional)</param>
/// <returns>Task of ProductType</returns>
public async System.Threading.Tasks.Task<ProductType> ProductTypesFindOneGetAsync (string filter = null)
{
ApiResponse<ProductType> localVarResponse = await ProductTypesFindOneGetAsyncWithHttpInfo(filter);
return localVarResponse.Data;
}
/// <summary>
/// Find first instance of the model matched by filter from the data source.
/// </summary>
/// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="filter">Filter defining fields, where, include, order, offset, and limit - must be a JSON-encoded string ({\"something\":\"value\"}) (optional)</param>
/// <returns>Task of ApiResponse (ProductType)</returns>
public async System.Threading.Tasks.Task<ApiResponse<ProductType>> ProductTypesFindOneGetAsyncWithHttpInfo (string filter = null)
{
var localVarPath = "/ProductTypes/findOne";
var localVarPathParams = new Dictionary<String, String>();
var localVarQueryParams = new Dictionary<String, String>();
var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader);
var localVarFormParams = new Dictionary<String, String>();
var localVarFileParams = new Dictionary<String, FileParameter>();
Object localVarPostBody = null;
// to determine the Content-Type header
String[] localVarHttpContentTypes = new String[] {
"application/json",
"application/x-www-form-urlencoded",
"application/xml",
"text/xml"
};
String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes);
// to determine the Accept header
String[] localVarHttpHeaderAccepts = new String[] {
"application/json",
"application/xml",
"text/xml",
"application/javascript",
"text/javascript"
};
String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts);
if (localVarHttpHeaderAccept != null)
localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept);
// set "format" to json by default
// e.g. /pet/{petId}.{format} becomes /pet/{petId}.json
localVarPathParams.Add("format", "json");
if (filter != null) localVarQueryParams.Add("filter", Configuration.ApiClient.ParameterToString(filter)); // query parameter
// authentication (access_token) required
if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("access_token")))
{
localVarQueryParams["access_token"] = Configuration.GetApiKeyWithPrefix("access_token");
}
// make the HTTP request
IRestResponse localVarResponse = (IRestResponse) await Configuration.ApiClient.CallApiAsync(localVarPath,
Method.GET, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams,
localVarPathParams, localVarHttpContentType);
int localVarStatusCode = (int) localVarResponse.StatusCode;
if (ExceptionFactory != null)
{
Exception exception = ExceptionFactory("ProductTypesFindOneGet", localVarResponse);
if (exception != null) throw exception;
}
return new ApiResponse<ProductType>(localVarStatusCode,
localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()),
(ProductType) Configuration.ApiClient.Deserialize(localVarResponse, typeof(ProductType)));
}
/// <summary>
/// Find all instances of the model matched by filter from the data source.
/// </summary>
/// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="filter">Filter defining fields, where, include, order, offset, and limit - must be a JSON-encoded string ({\"something\":\"value\"}) (optional)</param>
/// <returns>List<ProductType></returns>
public List<ProductType> ProductTypesGet (string filter = null)
{
ApiResponse<List<ProductType>> localVarResponse = ProductTypesGetWithHttpInfo(filter);
return localVarResponse.Data;
}
/// <summary>
/// Find all instances of the model matched by filter from the data source.
/// </summary>
/// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="filter">Filter defining fields, where, include, order, offset, and limit - must be a JSON-encoded string ({\"something\":\"value\"}) (optional)</param>
/// <returns>ApiResponse of List<ProductType></returns>
public ApiResponse< List<ProductType> > ProductTypesGetWithHttpInfo (string filter = null)
{
var localVarPath = "/ProductTypes";
var localVarPathParams = new Dictionary<String, String>();
var localVarQueryParams = new Dictionary<String, String>();
var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader);
var localVarFormParams = new Dictionary<String, String>();
var localVarFileParams = new Dictionary<String, FileParameter>();
Object localVarPostBody = null;
// to determine the Content-Type header
String[] localVarHttpContentTypes = new String[] {
"application/json",
"application/x-www-form-urlencoded",
"application/xml",
"text/xml"
};
String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes);
// to determine the Accept header
String[] localVarHttpHeaderAccepts = new String[] {
"application/json",
"application/xml",
"text/xml",
"application/javascript",
"text/javascript"
};
String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts);
if (localVarHttpHeaderAccept != null)
localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept);
// set "format" to json by default
// e.g. /pet/{petId}.{format} becomes /pet/{petId}.json
localVarPathParams.Add("format", "json");
if (filter != null) localVarQueryParams.Add("filter", Configuration.ApiClient.ParameterToString(filter)); // query parameter
// authentication (access_token) required
if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("access_token")))
{
localVarQueryParams["access_token"] = Configuration.GetApiKeyWithPrefix("access_token");
}
// make the HTTP request
IRestResponse localVarResponse = (IRestResponse) Configuration.ApiClient.CallApi(localVarPath,
Method.GET, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams,
localVarPathParams, localVarHttpContentType);
int localVarStatusCode = (int) localVarResponse.StatusCode;
if (ExceptionFactory != null)
{
Exception exception = ExceptionFactory("ProductTypesGet", localVarResponse);
if (exception != null) throw exception;
}
return new ApiResponse<List<ProductType>>(localVarStatusCode,
localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()),
(List<ProductType>) Configuration.ApiClient.Deserialize(localVarResponse, typeof(List<ProductType>)));
}
/// <summary>
/// Find all instances of the model matched by filter from the data source.
/// </summary>
/// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="filter">Filter defining fields, where, include, order, offset, and limit - must be a JSON-encoded string ({\"something\":\"value\"}) (optional)</param>
/// <returns>Task of List<ProductType></returns>
public async System.Threading.Tasks.Task<List<ProductType>> ProductTypesGetAsync (string filter = null)
{
ApiResponse<List<ProductType>> localVarResponse = await ProductTypesGetAsyncWithHttpInfo(filter);
return localVarResponse.Data;
}
/// <summary>
/// Find all instances of the model matched by filter from the data source.
/// </summary>
/// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="filter">Filter defining fields, where, include, order, offset, and limit - must be a JSON-encoded string ({\"something\":\"value\"}) (optional)</param>
/// <returns>Task of ApiResponse (List<ProductType>)</returns>
public async System.Threading.Tasks.Task<ApiResponse<List<ProductType>>> ProductTypesGetAsyncWithHttpInfo (string filter = null)
{
var localVarPath = "/ProductTypes";
var localVarPathParams = new Dictionary<String, String>();
var localVarQueryParams = new Dictionary<String, String>();
var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader);
var localVarFormParams = new Dictionary<String, String>();
var localVarFileParams = new Dictionary<String, FileParameter>();
Object localVarPostBody = null;
// to determine the Content-Type header
String[] localVarHttpContentTypes = new String[] {
"application/json",
"application/x-www-form-urlencoded",
"application/xml",
"text/xml"
};
String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes);
// to determine the Accept header
String[] localVarHttpHeaderAccepts = new String[] {
"application/json",
"application/xml",
"text/xml",
"application/javascript",
"text/javascript"
};
String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts);
if (localVarHttpHeaderAccept != null)
localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept);
// set "format" to json by default
// e.g. /pet/{petId}.{format} becomes /pet/{petId}.json
localVarPathParams.Add("format", "json");
if (filter != null) localVarQueryParams.Add("filter", Configuration.ApiClient.ParameterToString(filter)); // query parameter
// authentication (access_token) required
if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("access_token")))
{
localVarQueryParams["access_token"] = Configuration.GetApiKeyWithPrefix("access_token");
}
// make the HTTP request
IRestResponse localVarResponse = (IRestResponse) await Configuration.ApiClient.CallApiAsync(localVarPath,
Method.GET, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams,
localVarPathParams, localVarHttpContentType);
int localVarStatusCode = (int) localVarResponse.StatusCode;
if (ExceptionFactory != null)
{
Exception exception = ExceptionFactory("ProductTypesGet", localVarResponse);
if (exception != null) throw exception;
}
return new ApiResponse<List<ProductType>>(localVarStatusCode,
localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()),
(List<ProductType>) Configuration.ApiClient.Deserialize(localVarResponse, typeof(List<ProductType>)));
}
/// <summary>
/// Delete a model instance by {{id}} from the data source.
/// </summary>
/// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="id">Model id</param>
/// <returns>Object</returns>
public Object ProductTypesIdDelete (string id)
{
ApiResponse<Object> localVarResponse = ProductTypesIdDeleteWithHttpInfo(id);
return localVarResponse.Data;
}
/// <summary>
/// Delete a model instance by {{id}} from the data source.
/// </summary>
/// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="id">Model id</param>
/// <returns>ApiResponse of Object</returns>
public ApiResponse< Object > ProductTypesIdDeleteWithHttpInfo (string id)
{
// verify the required parameter 'id' is set
if (id == null)
throw new ApiException(400, "Missing required parameter 'id' when calling ProductTypeApi->ProductTypesIdDelete");
var localVarPath = "/ProductTypes/{id}";
var localVarPathParams = new Dictionary<String, String>();
var localVarQueryParams = new Dictionary<String, String>();
var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader);
var localVarFormParams = new Dictionary<String, String>();
var localVarFileParams = new Dictionary<String, FileParameter>();
Object localVarPostBody = null;
// to determine the Content-Type header
String[] localVarHttpContentTypes = new String[] {
"application/json",
"application/x-www-form-urlencoded",
"application/xml",
"text/xml"
};
String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes);
// to determine the Accept header
String[] localVarHttpHeaderAccepts = new String[] {
"application/json",
"application/xml",
"text/xml",
"application/javascript",
"text/javascript"
};
String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts);
if (localVarHttpHeaderAccept != null)
localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept);
// set "format" to json by default
// e.g. /pet/{petId}.{format} becomes /pet/{petId}.json
localVarPathParams.Add("format", "json");
if (id != null) localVarPathParams.Add("id", Configuration.ApiClient.ParameterToString(id)); // path parameter
// authentication (access_token) required
if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("access_token")))
{
localVarQueryParams["access_token"] = Configuration.GetApiKeyWithPrefix("access_token");
}
// make the HTTP request
IRestResponse localVarResponse = (IRestResponse) Configuration.ApiClient.CallApi(localVarPath,
Method.DELETE, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams,
localVarPathParams, localVarHttpContentType);
int localVarStatusCode = (int) localVarResponse.StatusCode;
if (ExceptionFactory != null)
{
Exception exception = ExceptionFactory("ProductTypesIdDelete", localVarResponse);
if (exception != null) throw exception;
}
return new ApiResponse<Object>(localVarStatusCode,
localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()),
(Object) Configuration.ApiClient.Deserialize(localVarResponse, typeof(Object)));
}
/// <summary>
/// Delete a model instance by {{id}} from the data source.
/// </summary>
/// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="id">Model id</param>
/// <returns>Task of Object</returns>
public async System.Threading.Tasks.Task<Object> ProductTypesIdDeleteAsync (string id)
{
ApiResponse<Object> localVarResponse = await ProductTypesIdDeleteAsyncWithHttpInfo(id);
return localVarResponse.Data;
}
/// <summary>
/// Delete a model instance by {{id}} from the data source.
/// </summary>
/// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="id">Model id</param>
/// <returns>Task of ApiResponse (Object)</returns>
public async System.Threading.Tasks.Task<ApiResponse<Object>> ProductTypesIdDeleteAsyncWithHttpInfo (string id)
{
// verify the required parameter 'id' is set
if (id == null)
throw new ApiException(400, "Missing required parameter 'id' when calling ProductTypeApi->ProductTypesIdDelete");
var localVarPath = "/ProductTypes/{id}";
var localVarPathParams = new Dictionary<String, String>();
var localVarQueryParams = new Dictionary<String, String>();
var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader);
var localVarFormParams = new Dictionary<String, String>();
var localVarFileParams = new Dictionary<String, FileParameter>();
Object localVarPostBody = null;
// to determine the Content-Type header
String[] localVarHttpContentTypes = new String[] {
"application/json",
"application/x-www-form-urlencoded",
"application/xml",
"text/xml"
};
String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes);
// to determine the Accept header
String[] localVarHttpHeaderAccepts = new String[] {
"application/json",
"application/xml",
"text/xml",
"application/javascript",
"text/javascript"
};
String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts);
if (localVarHttpHeaderAccept != null)
localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept);
// set "format" to json by default
// e.g. /pet/{petId}.{format} becomes /pet/{petId}.json
localVarPathParams.Add("format", "json");
if (id != null) localVarPathParams.Add("id", Configuration.ApiClient.ParameterToString(id)); // path parameter
// authentication (access_token) required
if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("access_token")))
{
localVarQueryParams["access_token"] = Configuration.GetApiKeyWithPrefix("access_token");
}
// make the HTTP request
IRestResponse localVarResponse = (IRestResponse) await Configuration.ApiClient.CallApiAsync(localVarPath,
Method.DELETE, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams,
localVarPathParams, localVarHttpContentType);
int localVarStatusCode = (int) localVarResponse.StatusCode;
if (ExceptionFactory != null)
{
Exception exception = ExceptionFactory("ProductTypesIdDelete", localVarResponse);
if (exception != null) throw exception;
}
return new ApiResponse<Object>(localVarStatusCode,
localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()),
(Object) Configuration.ApiClient.Deserialize(localVarResponse, typeof(Object)));
}
/// <summary>
/// Check whether a model instance exists in the data source.
/// </summary>
/// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="id">Model id</param>
/// <returns>InlineResponse2002</returns>
public InlineResponse2002 ProductTypesIdExistsGet (string id)
{
ApiResponse<InlineResponse2002> localVarResponse = ProductTypesIdExistsGetWithHttpInfo(id);
return localVarResponse.Data;
}
/// <summary>
/// Check whether a model instance exists in the data source.
/// </summary>
/// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="id">Model id</param>
/// <returns>ApiResponse of InlineResponse2002</returns>
public ApiResponse< InlineResponse2002 > ProductTypesIdExistsGetWithHttpInfo (string id)
{
// verify the required parameter 'id' is set
if (id == null)
throw new ApiException(400, "Missing required parameter 'id' when calling ProductTypeApi->ProductTypesIdExistsGet");
var localVarPath = "/ProductTypes/{id}/exists";
var localVarPathParams = new Dictionary<String, String>();
var localVarQueryParams = new Dictionary<String, String>();
var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader);
var localVarFormParams = new Dictionary<String, String>();
var localVarFileParams = new Dictionary<String, FileParameter>();
Object localVarPostBody = null;
// to determine the Content-Type header
String[] localVarHttpContentTypes = new String[] {
"application/json",
"application/x-www-form-urlencoded",
"application/xml",
"text/xml"
};
String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes);
// to determine the Accept header
String[] localVarHttpHeaderAccepts = new String[] {
"application/json",
"application/xml",
"text/xml",
"application/javascript",
"text/javascript"
};
String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts);
if (localVarHttpHeaderAccept != null)
localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept);
// set "format" to json by default
// e.g. /pet/{petId}.{format} becomes /pet/{petId}.json
localVarPathParams.Add("format", "json");
if (id != null) localVarPathParams.Add("id", Configuration.ApiClient.ParameterToString(id)); // path parameter
// authentication (access_token) required
if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("access_token")))
{
localVarQueryParams["access_token"] = Configuration.GetApiKeyWithPrefix("access_token");
}
// make the HTTP request
IRestResponse localVarResponse = (IRestResponse) Configuration.ApiClient.CallApi(localVarPath,
Method.GET, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams,
localVarPathParams, localVarHttpContentType);
int localVarStatusCode = (int) localVarResponse.StatusCode;
if (ExceptionFactory != null)
{
Exception exception = ExceptionFactory("ProductTypesIdExistsGet", localVarResponse);
if (exception != null) throw exception;
}
return new ApiResponse<InlineResponse2002>(localVarStatusCode,
localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()),
(InlineResponse2002) Configuration.ApiClient.Deserialize(localVarResponse, typeof(InlineResponse2002)));
}
/// <summary>
/// Check whether a model instance exists in the data source.
/// </summary>
/// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="id">Model id</param>
/// <returns>Task of InlineResponse2002</returns>
public async System.Threading.Tasks.Task<InlineResponse2002> ProductTypesIdExistsGetAsync (string id)
{
ApiResponse<InlineResponse2002> localVarResponse = await ProductTypesIdExistsGetAsyncWithHttpInfo(id);
return localVarResponse.Data;
}
/// <summary>
/// Check whether a model instance exists in the data source.
/// </summary>
/// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="id">Model id</param>
/// <returns>Task of ApiResponse (InlineResponse2002)</returns>
public async System.Threading.Tasks.Task<ApiResponse<InlineResponse2002>> ProductTypesIdExistsGetAsyncWithHttpInfo (string id)
{
// verify the required parameter 'id' is set
if (id == null)
throw new ApiException(400, "Missing required parameter 'id' when calling ProductTypeApi->ProductTypesIdExistsGet");
var localVarPath = "/ProductTypes/{id}/exists";
var localVarPathParams = new Dictionary<String, String>();
var localVarQueryParams = new Dictionary<String, String>();
var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader);
var localVarFormParams = new Dictionary<String, String>();
var localVarFileParams = new Dictionary<String, FileParameter>();
Object localVarPostBody = null;
// to determine the Content-Type header
String[] localVarHttpContentTypes = new String[] {
"application/json",
"application/x-www-form-urlencoded",
"application/xml",
"text/xml"
};
String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes);
// to determine the Accept header
String[] localVarHttpHeaderAccepts = new String[] {
"application/json",
"application/xml",
"text/xml",
"application/javascript",
"text/javascript"
};
String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts);
if (localVarHttpHeaderAccept != null)
localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept);
// set "format" to json by default
// e.g. /pet/{petId}.{format} becomes /pet/{petId}.json
localVarPathParams.Add("format", "json");
if (id != null) localVarPathParams.Add("id", Configuration.ApiClient.ParameterToString(id)); // path parameter
// authentication (access_token) required
if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("access_token")))
{
localVarQueryParams["access_token"] = Configuration.GetApiKeyWithPrefix("access_token");
}
// make the HTTP request
IRestResponse localVarResponse = (IRestResponse) await Configuration.ApiClient.CallApiAsync(localVarPath,
Method.GET, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams,
localVarPathParams, localVarHttpContentType);
int localVarStatusCode = (int) localVarResponse.StatusCode;
if (ExceptionFactory != null)
{
Exception exception = ExceptionFactory("ProductTypesIdExistsGet", localVarResponse);
if (exception != null) throw exception;
}
return new ApiResponse<InlineResponse2002>(localVarStatusCode,
localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()),
(InlineResponse2002) Configuration.ApiClient.Deserialize(localVarResponse, typeof(InlineResponse2002)));
}
/// <summary>
/// Find a model instance by {{id}} from the data source.
/// </summary>
/// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="id">Model id</param>
/// <param name="filter">Filter defining fields and include - must be a JSON-encoded string ({\"something\":\"value\"}) (optional)</param>
/// <returns>ProductType</returns>
public ProductType ProductTypesIdGet (string id, string filter = null)
{
ApiResponse<ProductType> localVarResponse = ProductTypesIdGetWithHttpInfo(id, filter);
return localVarResponse.Data;
}
/// <summary>
/// Find a model instance by {{id}} from the data source.
/// </summary>
/// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="id">Model id</param>
/// <param name="filter">Filter defining fields and include - must be a JSON-encoded string ({\"something\":\"value\"}) (optional)</param>
/// <returns>ApiResponse of ProductType</returns>
public ApiResponse< ProductType > ProductTypesIdGetWithHttpInfo (string id, string filter = null)
{
// verify the required parameter 'id' is set
if (id == null)
throw new ApiException(400, "Missing required parameter 'id' when calling ProductTypeApi->ProductTypesIdGet");
var localVarPath = "/ProductTypes/{id}";
var localVarPathParams = new Dictionary<String, String>();
var localVarQueryParams = new Dictionary<String, String>();
var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader);
var localVarFormParams = new Dictionary<String, String>();
var localVarFileParams = new Dictionary<String, FileParameter>();
Object localVarPostBody = null;
// to determine the Content-Type header
String[] localVarHttpContentTypes = new String[] {
"application/json",
"application/x-www-form-urlencoded",
"application/xml",
"text/xml"
};
String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes);
// to determine the Accept header
String[] localVarHttpHeaderAccepts = new String[] {
"application/json",
"application/xml",
"text/xml",
"application/javascript",
"text/javascript"
};
String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts);
if (localVarHttpHeaderAccept != null)
localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept);
// set "format" to json by default
// e.g. /pet/{petId}.{format} becomes /pet/{petId}.json
localVarPathParams.Add("format", "json");
if (id != null) localVarPathParams.Add("id", Configuration.ApiClient.ParameterToString(id)); // path parameter
if (filter != null) localVarQueryParams.Add("filter", Configuration.ApiClient.ParameterToString(filter)); // query parameter
// authentication (access_token) required
if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("access_token")))
{
localVarQueryParams["access_token"] = Configuration.GetApiKeyWithPrefix("access_token");
}
// make the HTTP request
IRestResponse localVarResponse = (IRestResponse) Configuration.ApiClient.CallApi(localVarPath,
Method.GET, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams,
localVarPathParams, localVarHttpContentType);
int localVarStatusCode = (int) localVarResponse.StatusCode;
if (ExceptionFactory != null)
{
Exception exception = ExceptionFactory("ProductTypesIdGet", localVarResponse);
if (exception != null) throw exception;
}
return new ApiResponse<ProductType>(localVarStatusCode,
localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()),
(ProductType) Configuration.ApiClient.Deserialize(localVarResponse, typeof(ProductType)));
}
/// <summary>
/// Find a model instance by {{id}} from the data source.
/// </summary>
/// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="id">Model id</param>
/// <param name="filter">Filter defining fields and include - must be a JSON-encoded string ({\"something\":\"value\"}) (optional)</param>
/// <returns>Task of ProductType</returns>
public async System.Threading.Tasks.Task<ProductType> ProductTypesIdGetAsync (string id, string filter = null)
{
ApiResponse<ProductType> localVarResponse = await ProductTypesIdGetAsyncWithHttpInfo(id, filter);
return localVarResponse.Data;
}
/// <summary>
/// Find a model instance by {{id}} from the data source.
/// </summary>
/// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="id">Model id</param>
/// <param name="filter">Filter defining fields and include - must be a JSON-encoded string ({\"something\":\"value\"}) (optional)</param>
/// <returns>Task of ApiResponse (ProductType)</returns>
public async System.Threading.Tasks.Task<ApiResponse<ProductType>> ProductTypesIdGetAsyncWithHttpInfo (string id, string filter = null)
{
// verify the required parameter 'id' is set
if (id == null)
throw new ApiException(400, "Missing required parameter 'id' when calling ProductTypeApi->ProductTypesIdGet");
var localVarPath = "/ProductTypes/{id}";
var localVarPathParams = new Dictionary<String, String>();
var localVarQueryParams = new Dictionary<String, String>();
var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader);
var localVarFormParams = new Dictionary<String, String>();
var localVarFileParams = new Dictionary<String, FileParameter>();
Object localVarPostBody = null;
// to determine the Content-Type header
String[] localVarHttpContentTypes = new String[] {
"application/json",
"application/x-www-form-urlencoded",
"application/xml",
"text/xml"
};
String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes);
// to determine the Accept header
String[] localVarHttpHeaderAccepts = new String[] {
"application/json",
"application/xml",
"text/xml",
"application/javascript",
"text/javascript"
};
String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts);
if (localVarHttpHeaderAccept != null)
localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept);
// set "format" to json by default
// e.g. /pet/{petId}.{format} becomes /pet/{petId}.json
localVarPathParams.Add("format", "json");
if (id != null) localVarPathParams.Add("id", Configuration.ApiClient.ParameterToString(id)); // path parameter
if (filter != null) localVarQueryParams.Add("filter", Configuration.ApiClient.ParameterToString(filter)); // query parameter
// authentication (access_token) required
if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("access_token")))
{
localVarQueryParams["access_token"] = Configuration.GetApiKeyWithPrefix("access_token");
}
// make the HTTP request
IRestResponse localVarResponse = (IRestResponse) await Configuration.ApiClient.CallApiAsync(localVarPath,
Method.GET, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams,
localVarPathParams, localVarHttpContentType);
int localVarStatusCode = (int) localVarResponse.StatusCode;
if (ExceptionFactory != null)
{
Exception exception = ExceptionFactory("ProductTypesIdGet", localVarResponse);
if (exception != null) throw exception;
}
return new ApiResponse<ProductType>(localVarStatusCode,
localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()),
(ProductType) Configuration.ApiClient.Deserialize(localVarResponse, typeof(ProductType)));
}
/// <summary>
/// Fetches belongsTo relation group.
/// </summary>
/// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="id">ProductType id</param>
/// <param name="refresh"> (optional)</param>
/// <returns>ProductGroup</returns>
public ProductGroup ProductTypesIdGroupGet (string id, bool? refresh = null)
{
ApiResponse<ProductGroup> localVarResponse = ProductTypesIdGroupGetWithHttpInfo(id, refresh);
return localVarResponse.Data;
}
/// <summary>
/// Fetches belongsTo relation group.
/// </summary>
/// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="id">ProductType id</param>
/// <param name="refresh"> (optional)</param>
/// <returns>ApiResponse of ProductGroup</returns>
public ApiResponse< ProductGroup > ProductTypesIdGroupGetWithHttpInfo (string id, bool? refresh = null)
{
// verify the required parameter 'id' is set
if (id == null)
throw new ApiException(400, "Missing required parameter 'id' when calling ProductTypeApi->ProductTypesIdGroupGet");
var localVarPath = "/ProductTypes/{id}/group";
var localVarPathParams = new Dictionary<String, String>();
var localVarQueryParams = new Dictionary<String, String>();
var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader);
var localVarFormParams = new Dictionary<String, String>();
var localVarFileParams = new Dictionary<String, FileParameter>();
Object localVarPostBody = null;
// to determine the Content-Type header
String[] localVarHttpContentTypes = new String[] {
"application/json",
"application/x-www-form-urlencoded",
"application/xml",
"text/xml"
};
String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes);
// to determine the Accept header
String[] localVarHttpHeaderAccepts = new String[] {
"application/json",
"application/xml",
"text/xml",
"application/javascript",
"text/javascript"
};
String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts);
if (localVarHttpHeaderAccept != null)
localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept);
// set "format" to json by default
// e.g. /pet/{petId}.{format} becomes /pet/{petId}.json
localVarPathParams.Add("format", "json");
if (id != null) localVarPathParams.Add("id", Configuration.ApiClient.ParameterToString(id)); // path parameter
if (refresh != null) localVarQueryParams.Add("refresh", Configuration.ApiClient.ParameterToString(refresh)); // query parameter
// authentication (access_token) required
if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("access_token")))
{
localVarQueryParams["access_token"] = Configuration.GetApiKeyWithPrefix("access_token");
}
// make the HTTP request
IRestResponse localVarResponse = (IRestResponse) Configuration.ApiClient.CallApi(localVarPath,
Method.GET, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams,
localVarPathParams, localVarHttpContentType);
int localVarStatusCode = (int) localVarResponse.StatusCode;
if (ExceptionFactory != null)
{
Exception exception = ExceptionFactory("ProductTypesIdGroupGet", localVarResponse);
if (exception != null) throw exception;
}
return new ApiResponse<ProductGroup>(localVarStatusCode,
localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()),
(ProductGroup) Configuration.ApiClient.Deserialize(localVarResponse, typeof(ProductGroup)));
}
/// <summary>
/// Fetches belongsTo relation group.
/// </summary>
/// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="id">ProductType id</param>
/// <param name="refresh"> (optional)</param>
/// <returns>Task of ProductGroup</returns>
public async System.Threading.Tasks.Task<ProductGroup> ProductTypesIdGroupGetAsync (string id, bool? refresh = null)
{
ApiResponse<ProductGroup> localVarResponse = await ProductTypesIdGroupGetAsyncWithHttpInfo(id, refresh);
return localVarResponse.Data;
}
/// <summary>
/// Fetches belongsTo relation group.
/// </summary>
/// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="id">ProductType id</param>
/// <param name="refresh"> (optional)</param>
/// <returns>Task of ApiResponse (ProductGroup)</returns>
public async System.Threading.Tasks.Task<ApiResponse<ProductGroup>> ProductTypesIdGroupGetAsyncWithHttpInfo (string id, bool? refresh = null)
{
// verify the required parameter 'id' is set
if (id == null)
throw new ApiException(400, "Missing required parameter 'id' when calling ProductTypeApi->ProductTypesIdGroupGet");
var localVarPath = "/ProductTypes/{id}/group";
var localVarPathParams = new Dictionary<String, String>();
var localVarQueryParams = new Dictionary<String, String>();
var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader);
var localVarFormParams = new Dictionary<String, String>();
var localVarFileParams = new Dictionary<String, FileParameter>();
Object localVarPostBody = null;
// to determine the Content-Type header
String[] localVarHttpContentTypes = new String[] {
"application/json",
"application/x-www-form-urlencoded",
"application/xml",
"text/xml"
};
String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes);
// to determine the Accept header
String[] localVarHttpHeaderAccepts = new String[] {
"application/json",
"application/xml",
"text/xml",
"application/javascript",
"text/javascript"
};
String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts);
if (localVarHttpHeaderAccept != null)
localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept);
// set "format" to json by default
// e.g. /pet/{petId}.{format} becomes /pet/{petId}.json
localVarPathParams.Add("format", "json");
if (id != null) localVarPathParams.Add("id", Configuration.ApiClient.ParameterToString(id)); // path parameter
if (refresh != null) localVarQueryParams.Add("refresh", Configuration.ApiClient.ParameterToString(refresh)); // query parameter
// authentication (access_token) required
if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("access_token")))
{
localVarQueryParams["access_token"] = Configuration.GetApiKeyWithPrefix("access_token");
}
// make the HTTP request
IRestResponse localVarResponse = (IRestResponse) await Configuration.ApiClient.CallApiAsync(localVarPath,
Method.GET, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams,
localVarPathParams, localVarHttpContentType);
int localVarStatusCode = (int) localVarResponse.StatusCode;
if (ExceptionFactory != null)
{
Exception exception = ExceptionFactory("ProductTypesIdGroupGet", localVarResponse);
if (exception != null) throw exception;
}
return new ApiResponse<ProductGroup>(localVarStatusCode,
localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()),
(ProductGroup) Configuration.ApiClient.Deserialize(localVarResponse, typeof(ProductGroup)));
}
/// <summary>
/// Check whether a model instance exists in the data source.
/// </summary>
/// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="id">Model id</param>
/// <returns>InlineResponse2002</returns>
public InlineResponse2002 ProductTypesIdHead (string id)
{
ApiResponse<InlineResponse2002> localVarResponse = ProductTypesIdHeadWithHttpInfo(id);
return localVarResponse.Data;
}
/// <summary>
/// Check whether a model instance exists in the data source.
/// </summary>
/// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="id">Model id</param>
/// <returns>ApiResponse of InlineResponse2002</returns>
public ApiResponse< InlineResponse2002 > ProductTypesIdHeadWithHttpInfo (string id)
{
// verify the required parameter 'id' is set
if (id == null)
throw new ApiException(400, "Missing required parameter 'id' when calling ProductTypeApi->ProductTypesIdHead");
var localVarPath = "/ProductTypes/{id}";
var localVarPathParams = new Dictionary<String, String>();
var localVarQueryParams = new Dictionary<String, String>();
var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader);
var localVarFormParams = new Dictionary<String, String>();
var localVarFileParams = new Dictionary<String, FileParameter>();
Object localVarPostBody = null;
// to determine the Content-Type header
String[] localVarHttpContentTypes = new String[] {
"application/json",
"application/x-www-form-urlencoded",
"application/xml",
"text/xml"
};
String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes);
// to determine the Accept header
String[] localVarHttpHeaderAccepts = new String[] {
"application/json",
"application/xml",
"text/xml",
"application/javascript",
"text/javascript"
};
String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts);
if (localVarHttpHeaderAccept != null)
localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept);
// set "format" to json by default
// e.g. /pet/{petId}.{format} becomes /pet/{petId}.json
localVarPathParams.Add("format", "json");
if (id != null) localVarPathParams.Add("id", Configuration.ApiClient.ParameterToString(id)); // path parameter
// authentication (access_token) required
if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("access_token")))
{
localVarQueryParams["access_token"] = Configuration.GetApiKeyWithPrefix("access_token");
}
// make the HTTP request
IRestResponse localVarResponse = (IRestResponse) Configuration.ApiClient.CallApi(localVarPath,
Method.HEAD, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams,
localVarPathParams, localVarHttpContentType);
int localVarStatusCode = (int) localVarResponse.StatusCode;
if (ExceptionFactory != null)
{
Exception exception = ExceptionFactory("ProductTypesIdHead", localVarResponse);
if (exception != null) throw exception;
}
return new ApiResponse<InlineResponse2002>(localVarStatusCode,
localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()),
(InlineResponse2002) Configuration.ApiClient.Deserialize(localVarResponse, typeof(InlineResponse2002)));
}
/// <summary>
/// Check whether a model instance exists in the data source.
/// </summary>
/// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="id">Model id</param>
/// <returns>Task of InlineResponse2002</returns>
public async System.Threading.Tasks.Task<InlineResponse2002> ProductTypesIdHeadAsync (string id)
{
ApiResponse<InlineResponse2002> localVarResponse = await ProductTypesIdHeadAsyncWithHttpInfo(id);
return localVarResponse.Data;
}
/// <summary>
/// Check whether a model instance exists in the data source.
/// </summary>
/// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="id">Model id</param>
/// <returns>Task of ApiResponse (InlineResponse2002)</returns>
public async System.Threading.Tasks.Task<ApiResponse<InlineResponse2002>> ProductTypesIdHeadAsyncWithHttpInfo (string id)
{
// verify the required parameter 'id' is set
if (id == null)
throw new ApiException(400, "Missing required parameter 'id' when calling ProductTypeApi->ProductTypesIdHead");
var localVarPath = "/ProductTypes/{id}";
var localVarPathParams = new Dictionary<String, String>();
var localVarQueryParams = new Dictionary<String, String>();
var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader);
var localVarFormParams = new Dictionary<String, String>();
var localVarFileParams = new Dictionary<String, FileParameter>();
Object localVarPostBody = null;
// to determine the Content-Type header
String[] localVarHttpContentTypes = new String[] {
"application/json",
"application/x-www-form-urlencoded",
"application/xml",
"text/xml"
};
String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes);
// to determine the Accept header
String[] localVarHttpHeaderAccepts = new String[] {
"application/json",
"application/xml",
"text/xml",
"application/javascript",
"text/javascript"
};
String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts);
if (localVarHttpHeaderAccept != null)
localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept);
// set "format" to json by default
// e.g. /pet/{petId}.{format} becomes /pet/{petId}.json
localVarPathParams.Add("format", "json");
if (id != null) localVarPathParams.Add("id", Configuration.ApiClient.ParameterToString(id)); // path parameter
// authentication (access_token) required
if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("access_token")))
{
localVarQueryParams["access_token"] = Configuration.GetApiKeyWithPrefix("access_token");
}
// make the HTTP request
IRestResponse localVarResponse = (IRestResponse) await Configuration.ApiClient.CallApiAsync(localVarPath,
Method.HEAD, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams,
localVarPathParams, localVarHttpContentType);
int localVarStatusCode = (int) localVarResponse.StatusCode;
if (ExceptionFactory != null)
{
Exception exception = ExceptionFactory("ProductTypesIdHead", localVarResponse);
if (exception != null) throw exception;
}
return new ApiResponse<InlineResponse2002>(localVarStatusCode,
localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()),
(InlineResponse2002) Configuration.ApiClient.Deserialize(localVarResponse, typeof(InlineResponse2002)));
}
/// <summary>
/// Patch attributes for a model instance and persist it into the data source.
/// </summary>
/// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="id">ProductType id</param>
/// <param name="data">An object of model property name/value pairs (optional)</param>
/// <returns>ProductType</returns>
public ProductType ProductTypesIdPatch (string id, ProductType data = null)
{
ApiResponse<ProductType> localVarResponse = ProductTypesIdPatchWithHttpInfo(id, data);
return localVarResponse.Data;
}
/// <summary>
/// Patch attributes for a model instance and persist it into the data source.
/// </summary>
/// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="id">ProductType id</param>
/// <param name="data">An object of model property name/value pairs (optional)</param>
/// <returns>ApiResponse of ProductType</returns>
public ApiResponse< ProductType > ProductTypesIdPatchWithHttpInfo (string id, ProductType data = null)
{
// verify the required parameter 'id' is set
if (id == null)
throw new ApiException(400, "Missing required parameter 'id' when calling ProductTypeApi->ProductTypesIdPatch");
var localVarPath = "/ProductTypes/{id}";
var localVarPathParams = new Dictionary<String, String>();
var localVarQueryParams = new Dictionary<String, String>();
var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader);
var localVarFormParams = new Dictionary<String, String>();
var localVarFileParams = new Dictionary<String, FileParameter>();
Object localVarPostBody = null;
// to determine the Content-Type header
String[] localVarHttpContentTypes = new String[] {
"application/json",
"application/x-www-form-urlencoded",
"application/xml",
"text/xml"
};
String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes);
// to determine the Accept header
String[] localVarHttpHeaderAccepts = new String[] {
"application/json",
"application/xml",
"text/xml",
"application/javascript",
"text/javascript"
};
String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts);
if (localVarHttpHeaderAccept != null)
localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept);
// set "format" to json by default
// e.g. /pet/{petId}.{format} becomes /pet/{petId}.json
localVarPathParams.Add("format", "json");
if (id != null) localVarPathParams.Add("id", Configuration.ApiClient.ParameterToString(id)); // path parameter
if (data != null && data.GetType() != typeof(byte[]))
{
localVarPostBody = Configuration.ApiClient.Serialize(data); // http body (model) parameter
}
else
{
localVarPostBody = data; // byte array
}
// authentication (access_token) required
if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("access_token")))
{
localVarQueryParams["access_token"] = Configuration.GetApiKeyWithPrefix("access_token");
}
// make the HTTP request
IRestResponse localVarResponse = (IRestResponse) Configuration.ApiClient.CallApi(localVarPath,
Method.PATCH, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams,
localVarPathParams, localVarHttpContentType);
int localVarStatusCode = (int) localVarResponse.StatusCode;
if (ExceptionFactory != null)
{
Exception exception = ExceptionFactory("ProductTypesIdPatch", localVarResponse);
if (exception != null) throw exception;
}
return new ApiResponse<ProductType>(localVarStatusCode,
localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()),
(ProductType) Configuration.ApiClient.Deserialize(localVarResponse, typeof(ProductType)));
}
/// <summary>
/// Patch attributes for a model instance and persist it into the data source.
/// </summary>
/// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="id">ProductType id</param>
/// <param name="data">An object of model property name/value pairs (optional)</param>
/// <returns>Task of ProductType</returns>
public async System.Threading.Tasks.Task<ProductType> ProductTypesIdPatchAsync (string id, ProductType data = null)
{
ApiResponse<ProductType> localVarResponse = await ProductTypesIdPatchAsyncWithHttpInfo(id, data);
return localVarResponse.Data;
}
/// <summary>
/// Patch attributes for a model instance and persist it into the data source.
/// </summary>
/// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="id">ProductType id</param>
/// <param name="data">An object of model property name/value pairs (optional)</param>
/// <returns>Task of ApiResponse (ProductType)</returns>
public async System.Threading.Tasks.Task<ApiResponse<ProductType>> ProductTypesIdPatchAsyncWithHttpInfo (string id, ProductType data = null)
{
// verify the required parameter 'id' is set
if (id == null)
throw new ApiException(400, "Missing required parameter 'id' when calling ProductTypeApi->ProductTypesIdPatch");
var localVarPath = "/ProductTypes/{id}";
var localVarPathParams = new Dictionary<String, String>();
var localVarQueryParams = new Dictionary<String, String>();
var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader);
var localVarFormParams = new Dictionary<String, String>();
var localVarFileParams = new Dictionary<String, FileParameter>();
Object localVarPostBody = null;
// to determine the Content-Type header
String[] localVarHttpContentTypes = new String[] {
"application/json",
"application/x-www-form-urlencoded",
"application/xml",
"text/xml"
};
String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes);
// to determine the Accept header
String[] localVarHttpHeaderAccepts = new String[] {
"application/json",
"application/xml",
"text/xml",
"application/javascript",
"text/javascript"
};
String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts);
if (localVarHttpHeaderAccept != null)
localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept);
// set "format" to json by default
// e.g. /pet/{petId}.{format} becomes /pet/{petId}.json
localVarPathParams.Add("format", "json");
if (id != null) localVarPathParams.Add("id", Configuration.ApiClient.ParameterToString(id)); // path parameter
if (data != null && data.GetType() != typeof(byte[]))
{
localVarPostBody = Configuration.ApiClient.Serialize(data); // http body (model) parameter
}
else
{
localVarPostBody = data; // byte array
}
// authentication (access_token) required
if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("access_token")))
{
localVarQueryParams["access_token"] = Configuration.GetApiKeyWithPrefix("access_token");
}
// make the HTTP request
IRestResponse localVarResponse = (IRestResponse) await Configuration.ApiClient.CallApiAsync(localVarPath,
Method.PATCH, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams,
localVarPathParams, localVarHttpContentType);
int localVarStatusCode = (int) localVarResponse.StatusCode;
if (ExceptionFactory != null)
{
Exception exception = ExceptionFactory("ProductTypesIdPatch", localVarResponse);
if (exception != null) throw exception;
}
return new ApiResponse<ProductType>(localVarStatusCode,
localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()),
(ProductType) Configuration.ApiClient.Deserialize(localVarResponse, typeof(ProductType)));
}
/// <summary>
/// Replace attributes for a model instance and persist it into the data source.
/// </summary>
/// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="id">Model id</param>
/// <param name="data">Model instance data (optional)</param>
/// <returns>ProductType</returns>
public ProductType ProductTypesIdPut (string id, ProductType data = null)
{
ApiResponse<ProductType> localVarResponse = ProductTypesIdPutWithHttpInfo(id, data);
return localVarResponse.Data;
}
/// <summary>
/// Replace attributes for a model instance and persist it into the data source.
/// </summary>
/// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="id">Model id</param>
/// <param name="data">Model instance data (optional)</param>
/// <returns>ApiResponse of ProductType</returns>
public ApiResponse< ProductType > ProductTypesIdPutWithHttpInfo (string id, ProductType data = null)
{
// verify the required parameter 'id' is set
if (id == null)
throw new ApiException(400, "Missing required parameter 'id' when calling ProductTypeApi->ProductTypesIdPut");
var localVarPath = "/ProductTypes/{id}";
var localVarPathParams = new Dictionary<String, String>();
var localVarQueryParams = new Dictionary<String, String>();
var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader);
var localVarFormParams = new Dictionary<String, String>();
var localVarFileParams = new Dictionary<String, FileParameter>();
Object localVarPostBody = null;
// to determine the Content-Type header
String[] localVarHttpContentTypes = new String[] {
"application/json",
"application/x-www-form-urlencoded",
"application/xml",
"text/xml"
};
String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes);
// to determine the Accept header
String[] localVarHttpHeaderAccepts = new String[] {
"application/json",
"application/xml",
"text/xml",
"application/javascript",
"text/javascript"
};
String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts);
if (localVarHttpHeaderAccept != null)
localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept);
// set "format" to json by default
// e.g. /pet/{petId}.{format} becomes /pet/{petId}.json
localVarPathParams.Add("format", "json");
if (id != null) localVarPathParams.Add("id", Configuration.ApiClient.ParameterToString(id)); // path parameter
if (data != null && data.GetType() != typeof(byte[]))
{
localVarPostBody = Configuration.ApiClient.Serialize(data); // http body (model) parameter
}
else
{
localVarPostBody = data; // byte array
}
// authentication (access_token) required
if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("access_token")))
{
localVarQueryParams["access_token"] = Configuration.GetApiKeyWithPrefix("access_token");
}
// make the HTTP request
IRestResponse localVarResponse = (IRestResponse) Configuration.ApiClient.CallApi(localVarPath,
Method.PUT, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams,
localVarPathParams, localVarHttpContentType);
int localVarStatusCode = (int) localVarResponse.StatusCode;
if (ExceptionFactory != null)
{
Exception exception = ExceptionFactory("ProductTypesIdPut", localVarResponse);
if (exception != null) throw exception;
}
return new ApiResponse<ProductType>(localVarStatusCode,
localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()),
(ProductType) Configuration.ApiClient.Deserialize(localVarResponse, typeof(ProductType)));
}
/// <summary>
/// Replace attributes for a model instance and persist it into the data source.
/// </summary>
/// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="id">Model id</param>
/// <param name="data">Model instance data (optional)</param>
/// <returns>Task of ProductType</returns>
public async System.Threading.Tasks.Task<ProductType> ProductTypesIdPutAsync (string id, ProductType data = null)
{
ApiResponse<ProductType> localVarResponse = await ProductTypesIdPutAsyncWithHttpInfo(id, data);
return localVarResponse.Data;
}
/// <summary>
/// Replace attributes for a model instance and persist it into the data source.
/// </summary>
/// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="id">Model id</param>
/// <param name="data">Model instance data (optional)</param>
/// <returns>Task of ApiResponse (ProductType)</returns>
public async System.Threading.Tasks.Task<ApiResponse<ProductType>> ProductTypesIdPutAsyncWithHttpInfo (string id, ProductType data = null)
{
// verify the required parameter 'id' is set
if (id == null)
throw new ApiException(400, "Missing required parameter 'id' when calling ProductTypeApi->ProductTypesIdPut");
var localVarPath = "/ProductTypes/{id}";
var localVarPathParams = new Dictionary<String, String>();
var localVarQueryParams = new Dictionary<String, String>();
var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader);
var localVarFormParams = new Dictionary<String, String>();
var localVarFileParams = new Dictionary<String, FileParameter>();
Object localVarPostBody = null;
// to determine the Content-Type header
String[] localVarHttpContentTypes = new String[] {
"application/json",
"application/x-www-form-urlencoded",
"application/xml",
"text/xml"
};
String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes);
// to determine the Accept header
String[] localVarHttpHeaderAccepts = new String[] {
"application/json",
"application/xml",
"text/xml",
"application/javascript",
"text/javascript"
};
String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts);
if (localVarHttpHeaderAccept != null)
localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept);
// set "format" to json by default
// e.g. /pet/{petId}.{format} becomes /pet/{petId}.json
localVarPathParams.Add("format", "json");
if (id != null) localVarPathParams.Add("id", Configuration.ApiClient.ParameterToString(id)); // path parameter
if (data != null && data.GetType() != typeof(byte[]))
{
localVarPostBody = Configuration.ApiClient.Serialize(data); // http body (model) parameter
}
else
{
localVarPostBody = data; // byte array
}
// authentication (access_token) required
if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("access_token")))
{
localVarQueryParams["access_token"] = Configuration.GetApiKeyWithPrefix("access_token");
}
// make the HTTP request
IRestResponse localVarResponse = (IRestResponse) await Configuration.ApiClient.CallApiAsync(localVarPath,
Method.PUT, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams,
localVarPathParams, localVarHttpContentType);
int localVarStatusCode = (int) localVarResponse.StatusCode;
if (ExceptionFactory != null)
{
Exception exception = ExceptionFactory("ProductTypesIdPut", localVarResponse);
if (exception != null) throw exception;
}
return new ApiResponse<ProductType>(localVarStatusCode,
localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()),
(ProductType) Configuration.ApiClient.Deserialize(localVarResponse, typeof(ProductType)));
}
/// <summary>
/// Replace attributes for a model instance and persist it into the data source.
/// </summary>
/// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="id">Model id</param>
/// <param name="data">Model instance data (optional)</param>
/// <returns>ProductType</returns>
public ProductType ProductTypesIdReplacePost (string id, ProductType data = null)
{
ApiResponse<ProductType> localVarResponse = ProductTypesIdReplacePostWithHttpInfo(id, data);
return localVarResponse.Data;
}
/// <summary>
/// Replace attributes for a model instance and persist it into the data source.
/// </summary>
/// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="id">Model id</param>
/// <param name="data">Model instance data (optional)</param>
/// <returns>ApiResponse of ProductType</returns>
public ApiResponse< ProductType > ProductTypesIdReplacePostWithHttpInfo (string id, ProductType data = null)
{
// verify the required parameter 'id' is set
if (id == null)
throw new ApiException(400, "Missing required parameter 'id' when calling ProductTypeApi->ProductTypesIdReplacePost");
var localVarPath = "/ProductTypes/{id}/replace";
var localVarPathParams = new Dictionary<String, String>();
var localVarQueryParams = new Dictionary<String, String>();
var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader);
var localVarFormParams = new Dictionary<String, String>();
var localVarFileParams = new Dictionary<String, FileParameter>();
Object localVarPostBody = null;
// to determine the Content-Type header
String[] localVarHttpContentTypes = new String[] {
"application/json",
"application/x-www-form-urlencoded",
"application/xml",
"text/xml"
};
String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes);
// to determine the Accept header
String[] localVarHttpHeaderAccepts = new String[] {
"application/json",
"application/xml",
"text/xml",
"application/javascript",
"text/javascript"
};
String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts);
if (localVarHttpHeaderAccept != null)
localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept);
// set "format" to json by default
// e.g. /pet/{petId}.{format} becomes /pet/{petId}.json
localVarPathParams.Add("format", "json");
if (id != null) localVarPathParams.Add("id", Configuration.ApiClient.ParameterToString(id)); // path parameter
if (data != null && data.GetType() != typeof(byte[]))
{
localVarPostBody = Configuration.ApiClient.Serialize(data); // http body (model) parameter
}
else
{
localVarPostBody = data; // byte array
}
// authentication (access_token) required
if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("access_token")))
{
localVarQueryParams["access_token"] = Configuration.GetApiKeyWithPrefix("access_token");
}
// make the HTTP request
IRestResponse localVarResponse = (IRestResponse) Configuration.ApiClient.CallApi(localVarPath,
Method.POST, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams,
localVarPathParams, localVarHttpContentType);
int localVarStatusCode = (int) localVarResponse.StatusCode;
if (ExceptionFactory != null)
{
Exception exception = ExceptionFactory("ProductTypesIdReplacePost", localVarResponse);
if (exception != null) throw exception;
}
return new ApiResponse<ProductType>(localVarStatusCode,
localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()),
(ProductType) Configuration.ApiClient.Deserialize(localVarResponse, typeof(ProductType)));
}
/// <summary>
/// Replace attributes for a model instance and persist it into the data source.
/// </summary>
/// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="id">Model id</param>
/// <param name="data">Model instance data (optional)</param>
/// <returns>Task of ProductType</returns>
public async System.Threading.Tasks.Task<ProductType> ProductTypesIdReplacePostAsync (string id, ProductType data = null)
{
ApiResponse<ProductType> localVarResponse = await ProductTypesIdReplacePostAsyncWithHttpInfo(id, data);
return localVarResponse.Data;
}
/// <summary>
/// Replace attributes for a model instance and persist it into the data source.
/// </summary>
/// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="id">Model id</param>
/// <param name="data">Model instance data (optional)</param>
/// <returns>Task of ApiResponse (ProductType)</returns>
public async System.Threading.Tasks.Task<ApiResponse<ProductType>> ProductTypesIdReplacePostAsyncWithHttpInfo (string id, ProductType data = null)
{
// verify the required parameter 'id' is set
if (id == null)
throw new ApiException(400, "Missing required parameter 'id' when calling ProductTypeApi->ProductTypesIdReplacePost");
var localVarPath = "/ProductTypes/{id}/replace";
var localVarPathParams = new Dictionary<String, String>();
var localVarQueryParams = new Dictionary<String, String>();
var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader);
var localVarFormParams = new Dictionary<String, String>();
var localVarFileParams = new Dictionary<String, FileParameter>();
Object localVarPostBody = null;
// to determine the Content-Type header
String[] localVarHttpContentTypes = new String[] {
"application/json",
"application/x-www-form-urlencoded",
"application/xml",
"text/xml"
};
String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes);
// to determine the Accept header
String[] localVarHttpHeaderAccepts = new String[] {
"application/json",
"application/xml",
"text/xml",
"application/javascript",
"text/javascript"
};
String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts);
if (localVarHttpHeaderAccept != null)
localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept);
// set "format" to json by default
// e.g. /pet/{petId}.{format} becomes /pet/{petId}.json
localVarPathParams.Add("format", "json");
if (id != null) localVarPathParams.Add("id", Configuration.ApiClient.ParameterToString(id)); // path parameter
if (data != null && data.GetType() != typeof(byte[]))
{
localVarPostBody = Configuration.ApiClient.Serialize(data); // http body (model) parameter
}
else
{
localVarPostBody = data; // byte array
}
// authentication (access_token) required
if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("access_token")))
{
localVarQueryParams["access_token"] = Configuration.GetApiKeyWithPrefix("access_token");
}
// make the HTTP request
IRestResponse localVarResponse = (IRestResponse) await Configuration.ApiClient.CallApiAsync(localVarPath,
Method.POST, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams,
localVarPathParams, localVarHttpContentType);
int localVarStatusCode = (int) localVarResponse.StatusCode;
if (ExceptionFactory != null)
{
Exception exception = ExceptionFactory("ProductTypesIdReplacePost", localVarResponse);
if (exception != null) throw exception;
}
return new ApiResponse<ProductType>(localVarStatusCode,
localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()),
(ProductType) Configuration.ApiClient.Deserialize(localVarResponse, typeof(ProductType)));
}
/// <summary>
/// Counts sizes of ProductType.
/// </summary>
/// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="id">ProductType id</param>
/// <param name="where">Criteria to match model instances (optional)</param>
/// <returns>InlineResponse2001</returns>
public InlineResponse2001 ProductTypesIdSizesCountGet (string id, string where = null)
{
ApiResponse<InlineResponse2001> localVarResponse = ProductTypesIdSizesCountGetWithHttpInfo(id, where);
return localVarResponse.Data;
}
/// <summary>
/// Counts sizes of ProductType.
/// </summary>
/// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="id">ProductType id</param>
/// <param name="where">Criteria to match model instances (optional)</param>
/// <returns>ApiResponse of InlineResponse2001</returns>
public ApiResponse< InlineResponse2001 > ProductTypesIdSizesCountGetWithHttpInfo (string id, string where = null)
{
// verify the required parameter 'id' is set
if (id == null)
throw new ApiException(400, "Missing required parameter 'id' when calling ProductTypeApi->ProductTypesIdSizesCountGet");
var localVarPath = "/ProductTypes/{id}/sizes/count";
var localVarPathParams = new Dictionary<String, String>();
var localVarQueryParams = new Dictionary<String, String>();
var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader);
var localVarFormParams = new Dictionary<String, String>();
var localVarFileParams = new Dictionary<String, FileParameter>();
Object localVarPostBody = null;
// to determine the Content-Type header
String[] localVarHttpContentTypes = new String[] {
"application/json",
"application/x-www-form-urlencoded",
"application/xml",
"text/xml"
};
String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes);
// to determine the Accept header
String[] localVarHttpHeaderAccepts = new String[] {
"application/json",
"application/xml",
"text/xml",
"application/javascript",
"text/javascript"
};
String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts);
if (localVarHttpHeaderAccept != null)
localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept);
// set "format" to json by default
// e.g. /pet/{petId}.{format} becomes /pet/{petId}.json
localVarPathParams.Add("format", "json");
if (id != null) localVarPathParams.Add("id", Configuration.ApiClient.ParameterToString(id)); // path parameter
if (where != null) localVarQueryParams.Add("where", Configuration.ApiClient.ParameterToString(where)); // query parameter
// authentication (access_token) required
if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("access_token")))
{
localVarQueryParams["access_token"] = Configuration.GetApiKeyWithPrefix("access_token");
}
// make the HTTP request
IRestResponse localVarResponse = (IRestResponse) Configuration.ApiClient.CallApi(localVarPath,
Method.GET, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams,
localVarPathParams, localVarHttpContentType);
int localVarStatusCode = (int) localVarResponse.StatusCode;
if (ExceptionFactory != null)
{
Exception exception = ExceptionFactory("ProductTypesIdSizesCountGet", localVarResponse);
if (exception != null) throw exception;
}
return new ApiResponse<InlineResponse2001>(localVarStatusCode,
localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()),
(InlineResponse2001) Configuration.ApiClient.Deserialize(localVarResponse, typeof(InlineResponse2001)));
}
/// <summary>
/// Counts sizes of ProductType.
/// </summary>
/// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="id">ProductType id</param>
/// <param name="where">Criteria to match model instances (optional)</param>
/// <returns>Task of InlineResponse2001</returns>
public async System.Threading.Tasks.Task<InlineResponse2001> ProductTypesIdSizesCountGetAsync (string id, string where = null)
{
ApiResponse<InlineResponse2001> localVarResponse = await ProductTypesIdSizesCountGetAsyncWithHttpInfo(id, where);
return localVarResponse.Data;
}
/// <summary>
/// Counts sizes of ProductType.
/// </summary>
/// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="id">ProductType id</param>
/// <param name="where">Criteria to match model instances (optional)</param>
/// <returns>Task of ApiResponse (InlineResponse2001)</returns>
public async System.Threading.Tasks.Task<ApiResponse<InlineResponse2001>> ProductTypesIdSizesCountGetAsyncWithHttpInfo (string id, string where = null)
{
// verify the required parameter 'id' is set
if (id == null)
throw new ApiException(400, "Missing required parameter 'id' when calling ProductTypeApi->ProductTypesIdSizesCountGet");
var localVarPath = "/ProductTypes/{id}/sizes/count";
var localVarPathParams = new Dictionary<String, String>();
var localVarQueryParams = new Dictionary<String, String>();
var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader);
var localVarFormParams = new Dictionary<String, String>();
var localVarFileParams = new Dictionary<String, FileParameter>();
Object localVarPostBody = null;
// to determine the Content-Type header
String[] localVarHttpContentTypes = new String[] {
"application/json",
"application/x-www-form-urlencoded",
"application/xml",
"text/xml"
};
String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes);
// to determine the Accept header
String[] localVarHttpHeaderAccepts = new String[] {
"application/json",
"application/xml",
"text/xml",
"application/javascript",
"text/javascript"
};
String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts);
if (localVarHttpHeaderAccept != null)
localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept);
// set "format" to json by default
// e.g. /pet/{petId}.{format} becomes /pet/{petId}.json
localVarPathParams.Add("format", "json");
if (id != null) localVarPathParams.Add("id", Configuration.ApiClient.ParameterToString(id)); // path parameter
if (where != null) localVarQueryParams.Add("where", Configuration.ApiClient.ParameterToString(where)); // query parameter
// authentication (access_token) required
if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("access_token")))
{
localVarQueryParams["access_token"] = Configuration.GetApiKeyWithPrefix("access_token");
}
// make the HTTP request
IRestResponse localVarResponse = (IRestResponse) await Configuration.ApiClient.CallApiAsync(localVarPath,
Method.GET, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams,
localVarPathParams, localVarHttpContentType);
int localVarStatusCode = (int) localVarResponse.StatusCode;
if (ExceptionFactory != null)
{
Exception exception = ExceptionFactory("ProductTypesIdSizesCountGet", localVarResponse);
if (exception != null) throw exception;
}
return new ApiResponse<InlineResponse2001>(localVarStatusCode,
localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()),
(InlineResponse2001) Configuration.ApiClient.Deserialize(localVarResponse, typeof(InlineResponse2001)));
}
/// <summary>
/// Delete a related item by id for sizes.
/// </summary>
/// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="id">ProductType id</param>
/// <param name="fk">Foreign key for sizes</param>
/// <returns></returns>
public void ProductTypesIdSizesFkDelete (string id, string fk)
{
ProductTypesIdSizesFkDeleteWithHttpInfo(id, fk);
}
/// <summary>
/// Delete a related item by id for sizes.
/// </summary>
/// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="id">ProductType id</param>
/// <param name="fk">Foreign key for sizes</param>
/// <returns>ApiResponse of Object(void)</returns>
public ApiResponse<Object> ProductTypesIdSizesFkDeleteWithHttpInfo (string id, string fk)
{
// verify the required parameter 'id' is set
if (id == null)
throw new ApiException(400, "Missing required parameter 'id' when calling ProductTypeApi->ProductTypesIdSizesFkDelete");
// verify the required parameter 'fk' is set
if (fk == null)
throw new ApiException(400, "Missing required parameter 'fk' when calling ProductTypeApi->ProductTypesIdSizesFkDelete");
var localVarPath = "/ProductTypes/{id}/sizes/{fk}";
var localVarPathParams = new Dictionary<String, String>();
var localVarQueryParams = new Dictionary<String, String>();
var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader);
var localVarFormParams = new Dictionary<String, String>();
var localVarFileParams = new Dictionary<String, FileParameter>();
Object localVarPostBody = null;
// to determine the Content-Type header
String[] localVarHttpContentTypes = new String[] {
"application/json",
"application/x-www-form-urlencoded",
"application/xml",
"text/xml"
};
String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes);
// to determine the Accept header
String[] localVarHttpHeaderAccepts = new String[] {
"application/json",
"application/xml",
"text/xml",
"application/javascript",
"text/javascript"
};
String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts);
if (localVarHttpHeaderAccept != null)
localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept);
// set "format" to json by default
// e.g. /pet/{petId}.{format} becomes /pet/{petId}.json
localVarPathParams.Add("format", "json");
if (id != null) localVarPathParams.Add("id", Configuration.ApiClient.ParameterToString(id)); // path parameter
if (fk != null) localVarPathParams.Add("fk", Configuration.ApiClient.ParameterToString(fk)); // path parameter
// authentication (access_token) required
if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("access_token")))
{
localVarQueryParams["access_token"] = Configuration.GetApiKeyWithPrefix("access_token");
}
// make the HTTP request
IRestResponse localVarResponse = (IRestResponse) Configuration.ApiClient.CallApi(localVarPath,
Method.DELETE, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams,
localVarPathParams, localVarHttpContentType);
int localVarStatusCode = (int) localVarResponse.StatusCode;
if (ExceptionFactory != null)
{
Exception exception = ExceptionFactory("ProductTypesIdSizesFkDelete", localVarResponse);
if (exception != null) throw exception;
}
return new ApiResponse<Object>(localVarStatusCode,
localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()),
null);
}
/// <summary>
/// Delete a related item by id for sizes.
/// </summary>
/// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="id">ProductType id</param>
/// <param name="fk">Foreign key for sizes</param>
/// <returns>Task of void</returns>
public async System.Threading.Tasks.Task ProductTypesIdSizesFkDeleteAsync (string id, string fk)
{
await ProductTypesIdSizesFkDeleteAsyncWithHttpInfo(id, fk);
}
/// <summary>
/// Delete a related item by id for sizes.
/// </summary>
/// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="id">ProductType id</param>
/// <param name="fk">Foreign key for sizes</param>
/// <returns>Task of ApiResponse</returns>
public async System.Threading.Tasks.Task<ApiResponse<Object>> ProductTypesIdSizesFkDeleteAsyncWithHttpInfo (string id, string fk)
{
// verify the required parameter 'id' is set
if (id == null)
throw new ApiException(400, "Missing required parameter 'id' when calling ProductTypeApi->ProductTypesIdSizesFkDelete");
// verify the required parameter 'fk' is set
if (fk == null)
throw new ApiException(400, "Missing required parameter 'fk' when calling ProductTypeApi->ProductTypesIdSizesFkDelete");
var localVarPath = "/ProductTypes/{id}/sizes/{fk}";
var localVarPathParams = new Dictionary<String, String>();
var localVarQueryParams = new Dictionary<String, String>();
var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader);
var localVarFormParams = new Dictionary<String, String>();
var localVarFileParams = new Dictionary<String, FileParameter>();
Object localVarPostBody = null;
// to determine the Content-Type header
String[] localVarHttpContentTypes = new String[] {
"application/json",
"application/x-www-form-urlencoded",
"application/xml",
"text/xml"
};
String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes);
// to determine the Accept header
String[] localVarHttpHeaderAccepts = new String[] {
"application/json",
"application/xml",
"text/xml",
"application/javascript",
"text/javascript"
};
String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts);
if (localVarHttpHeaderAccept != null)
localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept);
// set "format" to json by default
// e.g. /pet/{petId}.{format} becomes /pet/{petId}.json
localVarPathParams.Add("format", "json");
if (id != null) localVarPathParams.Add("id", Configuration.ApiClient.ParameterToString(id)); // path parameter
if (fk != null) localVarPathParams.Add("fk", Configuration.ApiClient.ParameterToString(fk)); // path parameter
// authentication (access_token) required
if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("access_token")))
{
localVarQueryParams["access_token"] = Configuration.GetApiKeyWithPrefix("access_token");
}
// make the HTTP request
IRestResponse localVarResponse = (IRestResponse) await Configuration.ApiClient.CallApiAsync(localVarPath,
Method.DELETE, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams,
localVarPathParams, localVarHttpContentType);
int localVarStatusCode = (int) localVarResponse.StatusCode;
if (ExceptionFactory != null)
{
Exception exception = ExceptionFactory("ProductTypesIdSizesFkDelete", localVarResponse);
if (exception != null) throw exception;
}
return new ApiResponse<Object>(localVarStatusCode,
localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()),
null);
}
/// <summary>
/// Find a related item by id for sizes.
/// </summary>
/// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="id">ProductType id</param>
/// <param name="fk">Foreign key for sizes</param>
/// <returns>ProductSize</returns>
public ProductSize ProductTypesIdSizesFkGet (string id, string fk)
{
ApiResponse<ProductSize> localVarResponse = ProductTypesIdSizesFkGetWithHttpInfo(id, fk);
return localVarResponse.Data;
}
/// <summary>
/// Find a related item by id for sizes.
/// </summary>
/// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="id">ProductType id</param>
/// <param name="fk">Foreign key for sizes</param>
/// <returns>ApiResponse of ProductSize</returns>
public ApiResponse< ProductSize > ProductTypesIdSizesFkGetWithHttpInfo (string id, string fk)
{
// verify the required parameter 'id' is set
if (id == null)
throw new ApiException(400, "Missing required parameter 'id' when calling ProductTypeApi->ProductTypesIdSizesFkGet");
// verify the required parameter 'fk' is set
if (fk == null)
throw new ApiException(400, "Missing required parameter 'fk' when calling ProductTypeApi->ProductTypesIdSizesFkGet");
var localVarPath = "/ProductTypes/{id}/sizes/{fk}";
var localVarPathParams = new Dictionary<String, String>();
var localVarQueryParams = new Dictionary<String, String>();
var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader);
var localVarFormParams = new Dictionary<String, String>();
var localVarFileParams = new Dictionary<String, FileParameter>();
Object localVarPostBody = null;
// to determine the Content-Type header
String[] localVarHttpContentTypes = new String[] {
"application/json",
"application/x-www-form-urlencoded",
"application/xml",
"text/xml"
};
String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes);
// to determine the Accept header
String[] localVarHttpHeaderAccepts = new String[] {
"application/json",
"application/xml",
"text/xml",
"application/javascript",
"text/javascript"
};
String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts);
if (localVarHttpHeaderAccept != null)
localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept);
// set "format" to json by default
// e.g. /pet/{petId}.{format} becomes /pet/{petId}.json
localVarPathParams.Add("format", "json");
if (id != null) localVarPathParams.Add("id", Configuration.ApiClient.ParameterToString(id)); // path parameter
if (fk != null) localVarPathParams.Add("fk", Configuration.ApiClient.ParameterToString(fk)); // path parameter
// authentication (access_token) required
if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("access_token")))
{
localVarQueryParams["access_token"] = Configuration.GetApiKeyWithPrefix("access_token");
}
// make the HTTP request
IRestResponse localVarResponse = (IRestResponse) Configuration.ApiClient.CallApi(localVarPath,
Method.GET, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams,
localVarPathParams, localVarHttpContentType);
int localVarStatusCode = (int) localVarResponse.StatusCode;
if (ExceptionFactory != null)
{
Exception exception = ExceptionFactory("ProductTypesIdSizesFkGet", localVarResponse);
if (exception != null) throw exception;
}
return new ApiResponse<ProductSize>(localVarStatusCode,
localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()),
(ProductSize) Configuration.ApiClient.Deserialize(localVarResponse, typeof(ProductSize)));
}
/// <summary>
/// Find a related item by id for sizes.
/// </summary>
/// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="id">ProductType id</param>
/// <param name="fk">Foreign key for sizes</param>
/// <returns>Task of ProductSize</returns>
public async System.Threading.Tasks.Task<ProductSize> ProductTypesIdSizesFkGetAsync (string id, string fk)
{
ApiResponse<ProductSize> localVarResponse = await ProductTypesIdSizesFkGetAsyncWithHttpInfo(id, fk);
return localVarResponse.Data;
}
/// <summary>
/// Find a related item by id for sizes.
/// </summary>
/// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="id">ProductType id</param>
/// <param name="fk">Foreign key for sizes</param>
/// <returns>Task of ApiResponse (ProductSize)</returns>
public async System.Threading.Tasks.Task<ApiResponse<ProductSize>> ProductTypesIdSizesFkGetAsyncWithHttpInfo (string id, string fk)
{
// verify the required parameter 'id' is set
if (id == null)
throw new ApiException(400, "Missing required parameter 'id' when calling ProductTypeApi->ProductTypesIdSizesFkGet");
// verify the required parameter 'fk' is set
if (fk == null)
throw new ApiException(400, "Missing required parameter 'fk' when calling ProductTypeApi->ProductTypesIdSizesFkGet");
var localVarPath = "/ProductTypes/{id}/sizes/{fk}";
var localVarPathParams = new Dictionary<String, String>();
var localVarQueryParams = new Dictionary<String, String>();
var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader);
var localVarFormParams = new Dictionary<String, String>();
var localVarFileParams = new Dictionary<String, FileParameter>();
Object localVarPostBody = null;
// to determine the Content-Type header
String[] localVarHttpContentTypes = new String[] {
"application/json",
"application/x-www-form-urlencoded",
"application/xml",
"text/xml"
};
String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes);
// to determine the Accept header
String[] localVarHttpHeaderAccepts = new String[] {
"application/json",
"application/xml",
"text/xml",
"application/javascript",
"text/javascript"
};
String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts);
if (localVarHttpHeaderAccept != null)
localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept);
// set "format" to json by default
// e.g. /pet/{petId}.{format} becomes /pet/{petId}.json
localVarPathParams.Add("format", "json");
if (id != null) localVarPathParams.Add("id", Configuration.ApiClient.ParameterToString(id)); // path parameter
if (fk != null) localVarPathParams.Add("fk", Configuration.ApiClient.ParameterToString(fk)); // path parameter
// authentication (access_token) required
if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("access_token")))
{
localVarQueryParams["access_token"] = Configuration.GetApiKeyWithPrefix("access_token");
}
// make the HTTP request
IRestResponse localVarResponse = (IRestResponse) await Configuration.ApiClient.CallApiAsync(localVarPath,
Method.GET, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams,
localVarPathParams, localVarHttpContentType);
int localVarStatusCode = (int) localVarResponse.StatusCode;
if (ExceptionFactory != null)
{
Exception exception = ExceptionFactory("ProductTypesIdSizesFkGet", localVarResponse);
if (exception != null) throw exception;
}
return new ApiResponse<ProductSize>(localVarStatusCode,
localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()),
(ProductSize) Configuration.ApiClient.Deserialize(localVarResponse, typeof(ProductSize)));
}
/// <summary>
/// Update a related item by id for sizes.
/// </summary>
/// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="id">ProductType id</param>
/// <param name="fk">Foreign key for sizes</param>
/// <param name="data"> (optional)</param>
/// <returns>ProductSize</returns>
public ProductSize ProductTypesIdSizesFkPut (string id, string fk, ProductSize data = null)
{
ApiResponse<ProductSize> localVarResponse = ProductTypesIdSizesFkPutWithHttpInfo(id, fk, data);
return localVarResponse.Data;
}
/// <summary>
/// Update a related item by id for sizes.
/// </summary>
/// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="id">ProductType id</param>
/// <param name="fk">Foreign key for sizes</param>
/// <param name="data"> (optional)</param>
/// <returns>ApiResponse of ProductSize</returns>
public ApiResponse< ProductSize > ProductTypesIdSizesFkPutWithHttpInfo (string id, string fk, ProductSize data = null)
{
// verify the required parameter 'id' is set
if (id == null)
throw new ApiException(400, "Missing required parameter 'id' when calling ProductTypeApi->ProductTypesIdSizesFkPut");
// verify the required parameter 'fk' is set
if (fk == null)
throw new ApiException(400, "Missing required parameter 'fk' when calling ProductTypeApi->ProductTypesIdSizesFkPut");
var localVarPath = "/ProductTypes/{id}/sizes/{fk}";
var localVarPathParams = new Dictionary<String, String>();
var localVarQueryParams = new Dictionary<String, String>();
var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader);
var localVarFormParams = new Dictionary<String, String>();
var localVarFileParams = new Dictionary<String, FileParameter>();
Object localVarPostBody = null;
// to determine the Content-Type header
String[] localVarHttpContentTypes = new String[] {
"application/json",
"application/x-www-form-urlencoded",
"application/xml",
"text/xml"
};
String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes);
// to determine the Accept header
String[] localVarHttpHeaderAccepts = new String[] {
"application/json",
"application/xml",
"text/xml",
"application/javascript",
"text/javascript"
};
String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts);
if (localVarHttpHeaderAccept != null)
localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept);
// set "format" to json by default
// e.g. /pet/{petId}.{format} becomes /pet/{petId}.json
localVarPathParams.Add("format", "json");
if (id != null) localVarPathParams.Add("id", Configuration.ApiClient.ParameterToString(id)); // path parameter
if (fk != null) localVarPathParams.Add("fk", Configuration.ApiClient.ParameterToString(fk)); // path parameter
if (data != null && data.GetType() != typeof(byte[]))
{
localVarPostBody = Configuration.ApiClient.Serialize(data); // http body (model) parameter
}
else
{
localVarPostBody = data; // byte array
}
// authentication (access_token) required
if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("access_token")))
{
localVarQueryParams["access_token"] = Configuration.GetApiKeyWithPrefix("access_token");
}
// make the HTTP request
IRestResponse localVarResponse = (IRestResponse) Configuration.ApiClient.CallApi(localVarPath,
Method.PUT, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams,
localVarPathParams, localVarHttpContentType);
int localVarStatusCode = (int) localVarResponse.StatusCode;
if (ExceptionFactory != null)
{
Exception exception = ExceptionFactory("ProductTypesIdSizesFkPut", localVarResponse);
if (exception != null) throw exception;
}
return new ApiResponse<ProductSize>(localVarStatusCode,
localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()),
(ProductSize) Configuration.ApiClient.Deserialize(localVarResponse, typeof(ProductSize)));
}
/// <summary>
/// Update a related item by id for sizes.
/// </summary>
/// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="id">ProductType id</param>
/// <param name="fk">Foreign key for sizes</param>
/// <param name="data"> (optional)</param>
/// <returns>Task of ProductSize</returns>
public async System.Threading.Tasks.Task<ProductSize> ProductTypesIdSizesFkPutAsync (string id, string fk, ProductSize data = null)
{
ApiResponse<ProductSize> localVarResponse = await ProductTypesIdSizesFkPutAsyncWithHttpInfo(id, fk, data);
return localVarResponse.Data;
}
/// <summary>
/// Update a related item by id for sizes.
/// </summary>
/// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="id">ProductType id</param>
/// <param name="fk">Foreign key for sizes</param>
/// <param name="data"> (optional)</param>
/// <returns>Task of ApiResponse (ProductSize)</returns>
public async System.Threading.Tasks.Task<ApiResponse<ProductSize>> ProductTypesIdSizesFkPutAsyncWithHttpInfo (string id, string fk, ProductSize data = null)
{
// verify the required parameter 'id' is set
if (id == null)
throw new ApiException(400, "Missing required parameter 'id' when calling ProductTypeApi->ProductTypesIdSizesFkPut");
// verify the required parameter 'fk' is set
if (fk == null)
throw new ApiException(400, "Missing required parameter 'fk' when calling ProductTypeApi->ProductTypesIdSizesFkPut");
var localVarPath = "/ProductTypes/{id}/sizes/{fk}";
var localVarPathParams = new Dictionary<String, String>();
var localVarQueryParams = new Dictionary<String, String>();
var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader);
var localVarFormParams = new Dictionary<String, String>();
var localVarFileParams = new Dictionary<String, FileParameter>();
Object localVarPostBody = null;
// to determine the Content-Type header
String[] localVarHttpContentTypes = new String[] {
"application/json",
"application/x-www-form-urlencoded",
"application/xml",
"text/xml"
};
String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes);
// to determine the Accept header
String[] localVarHttpHeaderAccepts = new String[] {
"application/json",
"application/xml",
"text/xml",
"application/javascript",
"text/javascript"
};
String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts);
if (localVarHttpHeaderAccept != null)
localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept);
// set "format" to json by default
// e.g. /pet/{petId}.{format} becomes /pet/{petId}.json
localVarPathParams.Add("format", "json");
if (id != null) localVarPathParams.Add("id", Configuration.ApiClient.ParameterToString(id)); // path parameter
if (fk != null) localVarPathParams.Add("fk", Configuration.ApiClient.ParameterToString(fk)); // path parameter
if (data != null && data.GetType() != typeof(byte[]))
{
localVarPostBody = Configuration.ApiClient.Serialize(data); // http body (model) parameter
}
else
{
localVarPostBody = data; // byte array
}
// authentication (access_token) required
if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("access_token")))
{
localVarQueryParams["access_token"] = Configuration.GetApiKeyWithPrefix("access_token");
}
// make the HTTP request
IRestResponse localVarResponse = (IRestResponse) await Configuration.ApiClient.CallApiAsync(localVarPath,
Method.PUT, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams,
localVarPathParams, localVarHttpContentType);
int localVarStatusCode = (int) localVarResponse.StatusCode;
if (ExceptionFactory != null)
{
Exception exception = ExceptionFactory("ProductTypesIdSizesFkPut", localVarResponse);
if (exception != null) throw exception;
}
return new ApiResponse<ProductSize>(localVarStatusCode,
localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()),
(ProductSize) Configuration.ApiClient.Deserialize(localVarResponse, typeof(ProductSize)));
}
/// <summary>
/// Queries sizes of ProductType.
/// </summary>
/// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="id">ProductType id</param>
/// <param name="filter"> (optional)</param>
/// <returns>List<ProductSize></returns>
public List<ProductSize> ProductTypesIdSizesGet (string id, string filter = null)
{
ApiResponse<List<ProductSize>> localVarResponse = ProductTypesIdSizesGetWithHttpInfo(id, filter);
return localVarResponse.Data;
}
/// <summary>
/// Queries sizes of ProductType.
/// </summary>
/// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="id">ProductType id</param>
/// <param name="filter"> (optional)</param>
/// <returns>ApiResponse of List<ProductSize></returns>
public ApiResponse< List<ProductSize> > ProductTypesIdSizesGetWithHttpInfo (string id, string filter = null)
{
// verify the required parameter 'id' is set
if (id == null)
throw new ApiException(400, "Missing required parameter 'id' when calling ProductTypeApi->ProductTypesIdSizesGet");
var localVarPath = "/ProductTypes/{id}/sizes";
var localVarPathParams = new Dictionary<String, String>();
var localVarQueryParams = new Dictionary<String, String>();
var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader);
var localVarFormParams = new Dictionary<String, String>();
var localVarFileParams = new Dictionary<String, FileParameter>();
Object localVarPostBody = null;
// to determine the Content-Type header
String[] localVarHttpContentTypes = new String[] {
"application/json",
"application/x-www-form-urlencoded",
"application/xml",
"text/xml"
};
String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes);
// to determine the Accept header
String[] localVarHttpHeaderAccepts = new String[] {
"application/json",
"application/xml",
"text/xml",
"application/javascript",
"text/javascript"
};
String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts);
if (localVarHttpHeaderAccept != null)
localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept);
// set "format" to json by default
// e.g. /pet/{petId}.{format} becomes /pet/{petId}.json
localVarPathParams.Add("format", "json");
if (id != null) localVarPathParams.Add("id", Configuration.ApiClient.ParameterToString(id)); // path parameter
if (filter != null) localVarQueryParams.Add("filter", Configuration.ApiClient.ParameterToString(filter)); // query parameter
// authentication (access_token) required
if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("access_token")))
{
localVarQueryParams["access_token"] = Configuration.GetApiKeyWithPrefix("access_token");
}
// make the HTTP request
IRestResponse localVarResponse = (IRestResponse) Configuration.ApiClient.CallApi(localVarPath,
Method.GET, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams,
localVarPathParams, localVarHttpContentType);
int localVarStatusCode = (int) localVarResponse.StatusCode;
if (ExceptionFactory != null)
{
Exception exception = ExceptionFactory("ProductTypesIdSizesGet", localVarResponse);
if (exception != null) throw exception;
}
return new ApiResponse<List<ProductSize>>(localVarStatusCode,
localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()),
(List<ProductSize>) Configuration.ApiClient.Deserialize(localVarResponse, typeof(List<ProductSize>)));
}
/// <summary>
/// Queries sizes of ProductType.
/// </summary>
/// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="id">ProductType id</param>
/// <param name="filter"> (optional)</param>
/// <returns>Task of List<ProductSize></returns>
public async System.Threading.Tasks.Task<List<ProductSize>> ProductTypesIdSizesGetAsync (string id, string filter = null)
{
ApiResponse<List<ProductSize>> localVarResponse = await ProductTypesIdSizesGetAsyncWithHttpInfo(id, filter);
return localVarResponse.Data;
}
/// <summary>
/// Queries sizes of ProductType.
/// </summary>
/// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="id">ProductType id</param>
/// <param name="filter"> (optional)</param>
/// <returns>Task of ApiResponse (List<ProductSize>)</returns>
public async System.Threading.Tasks.Task<ApiResponse<List<ProductSize>>> ProductTypesIdSizesGetAsyncWithHttpInfo (string id, string filter = null)
{
// verify the required parameter 'id' is set
if (id == null)
throw new ApiException(400, "Missing required parameter 'id' when calling ProductTypeApi->ProductTypesIdSizesGet");
var localVarPath = "/ProductTypes/{id}/sizes";
var localVarPathParams = new Dictionary<String, String>();
var localVarQueryParams = new Dictionary<String, String>();
var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader);
var localVarFormParams = new Dictionary<String, String>();
var localVarFileParams = new Dictionary<String, FileParameter>();
Object localVarPostBody = null;
// to determine the Content-Type header
String[] localVarHttpContentTypes = new String[] {
"application/json",
"application/x-www-form-urlencoded",
"application/xml",
"text/xml"
};
String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes);
// to determine the Accept header
String[] localVarHttpHeaderAccepts = new String[] {
"application/json",
"application/xml",
"text/xml",
"application/javascript",
"text/javascript"
};
String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts);
if (localVarHttpHeaderAccept != null)
localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept);
// set "format" to json by default
// e.g. /pet/{petId}.{format} becomes /pet/{petId}.json
localVarPathParams.Add("format", "json");
if (id != null) localVarPathParams.Add("id", Configuration.ApiClient.ParameterToString(id)); // path parameter
if (filter != null) localVarQueryParams.Add("filter", Configuration.ApiClient.ParameterToString(filter)); // query parameter
// authentication (access_token) required
if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("access_token")))
{
localVarQueryParams["access_token"] = Configuration.GetApiKeyWithPrefix("access_token");
}
// make the HTTP request
IRestResponse localVarResponse = (IRestResponse) await Configuration.ApiClient.CallApiAsync(localVarPath,
Method.GET, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams,
localVarPathParams, localVarHttpContentType);
int localVarStatusCode = (int) localVarResponse.StatusCode;
if (ExceptionFactory != null)
{
Exception exception = ExceptionFactory("ProductTypesIdSizesGet", localVarResponse);
if (exception != null) throw exception;
}
return new ApiResponse<List<ProductSize>>(localVarStatusCode,
localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()),
(List<ProductSize>) Configuration.ApiClient.Deserialize(localVarResponse, typeof(List<ProductSize>)));
}
/// <summary>
/// Creates a new instance in sizes of this model.
/// </summary>
/// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="id">ProductType id</param>
/// <param name="data"> (optional)</param>
/// <returns>ProductSize</returns>
public ProductSize ProductTypesIdSizesPost (string id, ProductSize data = null)
{
ApiResponse<ProductSize> localVarResponse = ProductTypesIdSizesPostWithHttpInfo(id, data);
return localVarResponse.Data;
}
/// <summary>
/// Creates a new instance in sizes of this model.
/// </summary>
/// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="id">ProductType id</param>
/// <param name="data"> (optional)</param>
/// <returns>ApiResponse of ProductSize</returns>
public ApiResponse< ProductSize > ProductTypesIdSizesPostWithHttpInfo (string id, ProductSize data = null)
{
// verify the required parameter 'id' is set
if (id == null)
throw new ApiException(400, "Missing required parameter 'id' when calling ProductTypeApi->ProductTypesIdSizesPost");
var localVarPath = "/ProductTypes/{id}/sizes";
var localVarPathParams = new Dictionary<String, String>();
var localVarQueryParams = new Dictionary<String, String>();
var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader);
var localVarFormParams = new Dictionary<String, String>();
var localVarFileParams = new Dictionary<String, FileParameter>();
Object localVarPostBody = null;
// to determine the Content-Type header
String[] localVarHttpContentTypes = new String[] {
"application/json",
"application/x-www-form-urlencoded",
"application/xml",
"text/xml"
};
String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes);
// to determine the Accept header
String[] localVarHttpHeaderAccepts = new String[] {
"application/json",
"application/xml",
"text/xml",
"application/javascript",
"text/javascript"
};
String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts);
if (localVarHttpHeaderAccept != null)
localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept);
// set "format" to json by default
// e.g. /pet/{petId}.{format} becomes /pet/{petId}.json
localVarPathParams.Add("format", "json");
if (id != null) localVarPathParams.Add("id", Configuration.ApiClient.ParameterToString(id)); // path parameter
if (data != null && data.GetType() != typeof(byte[]))
{
localVarPostBody = Configuration.ApiClient.Serialize(data); // http body (model) parameter
}
else
{
localVarPostBody = data; // byte array
}
// authentication (access_token) required
if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("access_token")))
{
localVarQueryParams["access_token"] = Configuration.GetApiKeyWithPrefix("access_token");
}
// make the HTTP request
IRestResponse localVarResponse = (IRestResponse) Configuration.ApiClient.CallApi(localVarPath,
Method.POST, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams,
localVarPathParams, localVarHttpContentType);
int localVarStatusCode = (int) localVarResponse.StatusCode;
if (ExceptionFactory != null)
{
Exception exception = ExceptionFactory("ProductTypesIdSizesPost", localVarResponse);
if (exception != null) throw exception;
}
return new ApiResponse<ProductSize>(localVarStatusCode,
localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()),
(ProductSize) Configuration.ApiClient.Deserialize(localVarResponse, typeof(ProductSize)));
}
/// <summary>
/// Creates a new instance in sizes of this model.
/// </summary>
/// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="id">ProductType id</param>
/// <param name="data"> (optional)</param>
/// <returns>Task of ProductSize</returns>
public async System.Threading.Tasks.Task<ProductSize> ProductTypesIdSizesPostAsync (string id, ProductSize data = null)
{
ApiResponse<ProductSize> localVarResponse = await ProductTypesIdSizesPostAsyncWithHttpInfo(id, data);
return localVarResponse.Data;
}
/// <summary>
/// Creates a new instance in sizes of this model.
/// </summary>
/// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="id">ProductType id</param>
/// <param name="data"> (optional)</param>
/// <returns>Task of ApiResponse (ProductSize)</returns>
public async System.Threading.Tasks.Task<ApiResponse<ProductSize>> ProductTypesIdSizesPostAsyncWithHttpInfo (string id, ProductSize data = null)
{
// verify the required parameter 'id' is set
if (id == null)
throw new ApiException(400, "Missing required parameter 'id' when calling ProductTypeApi->ProductTypesIdSizesPost");
var localVarPath = "/ProductTypes/{id}/sizes";
var localVarPathParams = new Dictionary<String, String>();
var localVarQueryParams = new Dictionary<String, String>();
var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader);
var localVarFormParams = new Dictionary<String, String>();
var localVarFileParams = new Dictionary<String, FileParameter>();
Object localVarPostBody = null;
// to determine the Content-Type header
String[] localVarHttpContentTypes = new String[] {
"application/json",
"application/x-www-form-urlencoded",
"application/xml",
"text/xml"
};
String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes);
// to determine the Accept header
String[] localVarHttpHeaderAccepts = new String[] {
"application/json",
"application/xml",
"text/xml",
"application/javascript",
"text/javascript"
};
String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts);
if (localVarHttpHeaderAccept != null)
localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept);
// set "format" to json by default
// e.g. /pet/{petId}.{format} becomes /pet/{petId}.json
localVarPathParams.Add("format", "json");
if (id != null) localVarPathParams.Add("id", Configuration.ApiClient.ParameterToString(id)); // path parameter
if (data != null && data.GetType() != typeof(byte[]))
{
localVarPostBody = Configuration.ApiClient.Serialize(data); // http body (model) parameter
}
else
{
localVarPostBody = data; // byte array
}
// authentication (access_token) required
if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("access_token")))
{
localVarQueryParams["access_token"] = Configuration.GetApiKeyWithPrefix("access_token");
}
// make the HTTP request
IRestResponse localVarResponse = (IRestResponse) await Configuration.ApiClient.CallApiAsync(localVarPath,
Method.POST, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams,
localVarPathParams, localVarHttpContentType);
int localVarStatusCode = (int) localVarResponse.StatusCode;
if (ExceptionFactory != null)
{
Exception exception = ExceptionFactory("ProductTypesIdSizesPost", localVarResponse);
if (exception != null) throw exception;
}
return new ApiResponse<ProductSize>(localVarStatusCode,
localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()),
(ProductSize) Configuration.ApiClient.Deserialize(localVarResponse, typeof(ProductSize)));
}
/// <summary>
/// Create a new instance of the model and persist it into the data source.
/// </summary>
/// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="data">Model instance data (optional)</param>
/// <returns>ProductType</returns>
public ProductType ProductTypesPost (ProductType data = null)
{
ApiResponse<ProductType> localVarResponse = ProductTypesPostWithHttpInfo(data);
return localVarResponse.Data;
}
/// <summary>
/// Create a new instance of the model and persist it into the data source.
/// </summary>
/// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="data">Model instance data (optional)</param>
/// <returns>ApiResponse of ProductType</returns>
public ApiResponse< ProductType > ProductTypesPostWithHttpInfo (ProductType data = null)
{
var localVarPath = "/ProductTypes";
var localVarPathParams = new Dictionary<String, String>();
var localVarQueryParams = new Dictionary<String, String>();
var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader);
var localVarFormParams = new Dictionary<String, String>();
var localVarFileParams = new Dictionary<String, FileParameter>();
Object localVarPostBody = null;
// to determine the Content-Type header
String[] localVarHttpContentTypes = new String[] {
"application/json",
"application/x-www-form-urlencoded",
"application/xml",
"text/xml"
};
String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes);
// to determine the Accept header
String[] localVarHttpHeaderAccepts = new String[] {
"application/json",
"application/xml",
"text/xml",
"application/javascript",
"text/javascript"
};
String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts);
if (localVarHttpHeaderAccept != null)
localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept);
// set "format" to json by default
// e.g. /pet/{petId}.{format} becomes /pet/{petId}.json
localVarPathParams.Add("format", "json");
if (data != null && data.GetType() != typeof(byte[]))
{
localVarPostBody = Configuration.ApiClient.Serialize(data); // http body (model) parameter
}
else
{
localVarPostBody = data; // byte array
}
// authentication (access_token) required
if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("access_token")))
{
localVarQueryParams["access_token"] = Configuration.GetApiKeyWithPrefix("access_token");
}
// make the HTTP request
IRestResponse localVarResponse = (IRestResponse) Configuration.ApiClient.CallApi(localVarPath,
Method.POST, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams,
localVarPathParams, localVarHttpContentType);
int localVarStatusCode = (int) localVarResponse.StatusCode;
if (ExceptionFactory != null)
{
Exception exception = ExceptionFactory("ProductTypesPost", localVarResponse);
if (exception != null) throw exception;
}
return new ApiResponse<ProductType>(localVarStatusCode,
localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()),
(ProductType) Configuration.ApiClient.Deserialize(localVarResponse, typeof(ProductType)));
}
/// <summary>
/// Create a new instance of the model and persist it into the data source.
/// </summary>
/// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="data">Model instance data (optional)</param>
/// <returns>Task of ProductType</returns>
public async System.Threading.Tasks.Task<ProductType> ProductTypesPostAsync (ProductType data = null)
{
ApiResponse<ProductType> localVarResponse = await ProductTypesPostAsyncWithHttpInfo(data);
return localVarResponse.Data;
}
/// <summary>
/// Create a new instance of the model and persist it into the data source.
/// </summary>
/// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="data">Model instance data (optional)</param>
/// <returns>Task of ApiResponse (ProductType)</returns>
public async System.Threading.Tasks.Task<ApiResponse<ProductType>> ProductTypesPostAsyncWithHttpInfo (ProductType data = null)
{
var localVarPath = "/ProductTypes";
var localVarPathParams = new Dictionary<String, String>();
var localVarQueryParams = new Dictionary<String, String>();
var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader);
var localVarFormParams = new Dictionary<String, String>();
var localVarFileParams = new Dictionary<String, FileParameter>();
Object localVarPostBody = null;
// to determine the Content-Type header
String[] localVarHttpContentTypes = new String[] {
"application/json",
"application/x-www-form-urlencoded",
"application/xml",
"text/xml"
};
String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes);
// to determine the Accept header
String[] localVarHttpHeaderAccepts = new String[] {
"application/json",
"application/xml",
"text/xml",
"application/javascript",
"text/javascript"
};
String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts);
if (localVarHttpHeaderAccept != null)
localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept);
// set "format" to json by default
// e.g. /pet/{petId}.{format} becomes /pet/{petId}.json
localVarPathParams.Add("format", "json");
if (data != null && data.GetType() != typeof(byte[]))
{
localVarPostBody = Configuration.ApiClient.Serialize(data); // http body (model) parameter
}
else
{
localVarPostBody = data; // byte array
}
// authentication (access_token) required
if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("access_token")))
{
localVarQueryParams["access_token"] = Configuration.GetApiKeyWithPrefix("access_token");
}
// make the HTTP request
IRestResponse localVarResponse = (IRestResponse) await Configuration.ApiClient.CallApiAsync(localVarPath,
Method.POST, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams,
localVarPathParams, localVarHttpContentType);
int localVarStatusCode = (int) localVarResponse.StatusCode;
if (ExceptionFactory != null)
{
Exception exception = ExceptionFactory("ProductTypesPost", localVarResponse);
if (exception != null) throw exception;
}
return new ApiResponse<ProductType>(localVarStatusCode,
localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()),
(ProductType) Configuration.ApiClient.Deserialize(localVarResponse, typeof(ProductType)));
}
}
}
| 50.012998 | 196 | 0.617936 | [
"Apache-2.0"
] | tweak-com-public/tweak-api-client-csharp | src/TweakApi/Api/ProductTypeApi.cs | 227,009 | C# |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Dynamic;
using System.IO;
using System.Web;
using System.Web.Script.Serialization;
using CsQuery.ExtensionMethods.Internal;
using CsQuery.Utility;
using CsQuery.Engine;
using CsQuery.Web;
using CsQuery.Promises;
using CsQuery.HtmlParser;
using CsQuery.Implementation;
namespace CsQuery
{
public partial class CQ
{
/// <summary>
/// Creates a new DOM from an HTML file.
/// </summary>
///
/// <param name="url">
/// The URL of the remote server.
/// </param>
/// <param name="options">
/// The options to use when creating the reqest.
/// </param>
///
/// <returns>
/// A CQ object composed from the HTML response from the server.
/// </returns>
public static CQ CreateFromUrl(string url, ServerConfig options=null)
{
CsqWebRequest request = new CsqWebRequest(url);
request.Options = options;
var httpRequest = request.GetWebRequest();
var response = httpRequest.GetResponse();
var responseStream = response.GetResponseStream();
var encoding = CsqWebRequest.GetEncoding(response);
return CQ.CreateDocument(responseStream,encoding);
}
/// <summary>
/// Start an asynchronous request to an HTTP server, returning a promise that will resolve when
/// the request is completed or rejected.
/// </summary>
///
/// <param name="url">
/// The URL of the remote server
/// </param>
/// <param name="options">
/// The options to use when creating the reqest
/// </param>
///
/// <returns>
/// A promise that resolves when the request completes
/// </returns>
public static IPromise<ICsqWebResponse> CreateFromUrlAsync(string url, ServerConfig options = null)
{
var deferred = When.Deferred<ICsqWebResponse>();
int uniqueID = AsyncWebRequestManager.StartAsyncWebRequest(url, deferred.Resolve, deferred.Reject, options);
return deferred;
}
/// <summary>
/// Start an asynchronous request to an HTTP server.
/// </summary>
///
/// <param name="url">
/// The URL of the remote server.
/// </param>
/// <param name="callbackSuccess">
/// A delegate to invoke upon successful completion of the request.
/// </param>
/// <param name="callbackFail">
/// A delegate to invoke upon failure.
/// </param>
/// <param name="options">
/// Options to use when creating the request.
/// </param>
///
/// <returns>
/// A unique identifier which will be passed through to the response and can be used to assocate
/// a response with this request.
/// </returns>
public static int CreateFromUrlAsync(string url, Action<ICsqWebResponse> callbackSuccess, Action<ICsqWebResponse> callbackFail=null, ServerConfig options = null)
{
return AsyncWebRequestManager.StartAsyncWebRequest(url,callbackSuccess,callbackFail,options);
}
/// <summary>
/// Start an asynchronous request to an HTTP server.
/// </summary>
///
/// <param name="url">
/// The URL of the remote server.
/// </param>
/// <param name="id">
/// An identifier that will be passed through to the response.
/// </param>
/// <param name="callbackSuccess">
/// A delegate to invoke upon successful completion of the request.
/// </param>
/// <param name="callbackFail">
/// A delegate to invoke upon failure.
/// </param>
/// <param name="options">
/// Options to use when creating the request.
/// </param>
public static void CreateFromUrlAsync(string url, int id, Action<ICsqWebResponse> callbackSuccess, Action<ICsqWebResponse> callbackFail = null, ServerConfig options = null)
{
AsyncWebRequestManager.StartAsyncWebRequest(url, callbackSuccess, callbackFail,id, options);
}
/// <summary>
/// Waits until all async events have completed. Use for testing primarily as a web app should
/// not stop normally.
/// </summary>
///
/// <param name="timeout">
/// The maximum number of milliseconds to wait.
/// </param>
///
/// <returns>
/// true if all events were cleared in the allotted time, false if not.
/// </returns>
public static bool WaitForAsyncEvents(int timeout = -1)
{
return AsyncWebRequestManager.WaitForAsyncEvents(timeout);
}
/// <summary>
/// Return a new promise that resolves when all the promises passed in are resolved.
/// </summary>
///
/// <param name="promises">
/// One or more promises
/// </param>
///
/// <returns>
/// A new promise
/// </returns>
public static IPromise WhenAll(params IPromise[] promises)
{
return When.All(promises);
}
}
}
| 32.686747 | 180 | 0.574641 | [
"MIT"
] | dturkenk/CsQuery | source/CsQuery/CQ_CsQuery/CreateFromUrl.cs | 5,428 | C# |
using Microsoft.Toolkit.Parsers.Markdown;
using Microsoft.Toolkit.Parsers.Markdown.Blocks;
using Microsoft.Toolkit.Parsers.Markdown.Helpers;
using Microsoft.Toolkit.Parsers.Markdown.Inlines;
using MigraDoc.DocumentObjectModel;
using MigraDoc.DocumentObjectModel.Tables;
using System;
using System.Collections.Generic;
namespace Parsers
{
public class WorkerCostBlock : WorkerBlock
{
public IList<uint> WorkerCosts { get; set; }
protected override int Count => this.WorkerCosts.Count;
protected override void GetString(int index, Paragraph paragraph)
{
paragraph.AddText(this.WorkerCosts[index].ToString());
}
public new class Parser : Parser<WorkerCostBlock>
{
protected override BlockParseResult<WorkerCostBlock> ParseInternal(LineBlock markdown, int startLine, bool lineStartsNewParagraph, MarkdownDocument document)
{
var line = markdown[startLine].Trim();
if (line.Length == 0 || line[0] != '>')
return null;
line = line.Slice(1).TrimStart();
var list = new List<uint>();
uint currentCost = 0;
while (line.Length != 0)
{
var end = line.IndexOfNexWhiteSpace();
if (end == -1)
end = line.Length;
var current = line.Slice(0, end).Trim();
var splitter = current.IndexOf(':');
if (splitter == -1)
return null;
var first = current.Slice(0, splitter);
var scccond = current.Slice(splitter + 1);
if (!uint.TryParse(first, out var count))
return null;
if (!uint.TryParse(scccond, out var cost))
return null;
for (var i = 0; i < count; i++)
{
currentCost += cost;
list.Add(currentCost);
}
line = line.Slice(end).Trim();
}
if (list.Count == 0)
return null;
var result = new WorkerCostBlock()
{
WorkerCosts = list.AsReadOnly()
};
return BlockParseResult.Create(result, startLine, 1);
}
}
}
public abstract class WorkerBlock : MarkdownBlock
{
protected abstract int Count { get; }
protected abstract void GetString(int index, Paragraph paragraph);
public void MakeWorkerTable(Document document, Unit? blockSize = null)
{
blockSize ??= Unit.FromCentimeter(1.5);
var numberOfColumns = Math.Min(6, this.Count);
var table = new Table
{
Style = "table"
};
table.Format.Alignment = ParagraphAlignment.Center;
table.Format.SpaceAfter = new Unit(1, UnitType.Centimeter);
table.Format.WidowControl = true;
//table.BottomPadding = new Unit(1, UnitType.Centimeter);
table.Borders.Width = 0.75;
for (var i = 0; i < numberOfColumns; i++)
{
var column = table.AddColumn(blockSize.Value);
column.Format.Alignment = ParagraphAlignment.Center;
}
Row row = null;
for (var i = 0; i < this.Count; i++)
{
if (row is null)
{
row = table.AddRow();
row.Height = blockSize.Value;
row.HeightRule = RowHeightRule.Exactly;
}
var cell = row.Cells[i % numberOfColumns];
var p = cell.AddParagraph();
this.GetString(i, p);
if (i % numberOfColumns == numberOfColumns - 1)
row = null;
}
if (row != null)
for (int i = 0; i < numberOfColumns - (this.Count % numberOfColumns); i++)
{
var cell = row.Cells[numberOfColumns - 1 - i];
cell.Shading.Color = Colors.Black;
}
table.SetEdge(0, 0, numberOfColumns, table.Rows.Count, Edge.Box, BorderStyle.Single, 1.5, Colors.Black);
document.LastSection.Add(table);
}
}
public class WorkerTextBlock : WorkerBlock
{
protected override int Count => this.WorkerText.Count;
protected override void GetString(int index, Paragraph paragraph)
{
this.WorkerText[index].FillInlines(paragraph);
}
public IList<IEnumerable<MarkdownInline>> WorkerText { get; set; }
public new class Parser : Parser<WorkerTextBlock>
{
protected override BlockParseResult<WorkerTextBlock> ParseInternal(LineBlock markdown, int startLine, bool lineStartsNewParagraph, MarkdownDocument document)
{
var line = markdown[startLine].Trim();
if (line.Length == 0 || line[0] != '>')
return null;
line = line.Slice(2).TrimStart();
var list = new List<IEnumerable<MarkdownInline>>();
while (line.Length != 0)
{
var current = line;
var splitter = current.IndexOf(":<");
if (splitter == -1)
return null;
var currentEnd = current.Slice(splitter + 1).FindClosingBrace() + splitter + 1;
if (currentEnd < splitter + 1)
return null;
current = current.Slice(0, currentEnd + 1);
var first = current.Slice(0, splitter);
var scccond = current.Slice(splitter + 1);
// remove the <>
scccond = scccond.Slice(1, scccond.Length - 2);
if (!uint.TryParse(first, out var count))
return null;
for (var i = 0; i < count; i++)
{
list.Add(document.ParseInlineChildren(scccond, true, true));
}
line = line.Slice(current.Length).Trim();
}
if (list.Count == 0)
return null;
var result = new WorkerTextBlock()
{
WorkerText = list.AsReadOnly()
};
return BlockParseResult.Create(result, startLine, 1);
}
}
}
}
| 30.106195 | 169 | 0.49177 | [
"Unlicense"
] | LokiMidgard/KarthagoCharacterGeneratorTool | Parsers/WorkerCostBlock.cs | 6,806 | C# |
///////////////////////////////////////////////////////////////////////////////////////////////
//
// This File is Part of the CallButler Open Source PBX (http://www.codeplex.com/callbutler
//
// Copyright (c) 2005-2008, Jim Heising
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation and/or
// other materials provided with the distribution.
//
// * Neither the name of Jim Heising nor the names of its contributors may be
// used to endorse or promote products derived from this software without specific prior
// written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
// IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
// INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
// NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//
///////////////////////////////////////////////////////////////////////////////////////////////
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using CallButler.ExceptionManagement;
namespace CallButler.Manager
{
class RemotingExceptionManager
{
public static event EventHandler ConnectionError;
public static event EventHandler AuthenticationError;
public static event EventHandler RemoteManagementError;
public static void ProcessException(Exception e)
{
global::Controls.LoadingDialog.HideDialog();
if ((e is System.Runtime.Remoting.RemotingException || e is Exception) && e.Message.Contains("Failed to authenticate") && AuthenticationError != null)
{
AuthenticationError(null, EventArgs.Empty);
return;
}
else if ((e is System.Runtime.Remoting.RemotingException || e is Exception) && e.Message.Contains("Remote Management not allowed") && RemoteManagementError != null)
{
RemoteManagementError(null, EventArgs.Empty);
return;
}
else if (e is System.Runtime.Remoting.RemotingException || e is System.Net.Sockets.SocketException)
{
if (ConnectionError != null)
{
ConnectionError(null, EventArgs.Empty);
return;
}
}
string licenseKey = "";
string licenseName = "";
try
{
licenseKey = ManagementInterfaceClient.ManagementInterface.LicenseKey;
licenseName = ManagementInterfaceClient.ManagementInterface.LicenseName;
}
catch { }
ErrorCaptureUtils.SendError(e, licenseKey, licenseName, Application.ProductVersion, true);
}
}
}
| 44.264368 | 177 | 0.617502 | [
"BSD-3-Clause"
] | cetin01/callbutler-in-vs2008 | CallButler Manager/RemotingExceptionManager.cs | 3,851 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Slowsharp
{
public class TimeoutException : SSRuntimeException
{
public TimeoutException() :
base ("Execution has timed out")
{
}
}
}
| 18.235294 | 54 | 0.658065 | [
"MIT"
] | pjc0247/SlowSharp | Slowsharp/Exception/TimeoutException.cs | 312 | C# |
using System.Collections.Generic;
namespace Melanchall.DryWetMidi.Smf.Interaction
{
internal sealed class PatternActionResult
{
#region Constants
public static readonly PatternActionResult DoNothing = new PatternActionResult();
#endregion
#region Constructor
public PatternActionResult()
{
}
public PatternActionResult(long? time)
: this(time, null, null)
{
}
public PatternActionResult(long? time, IEnumerable<Note> notes)
: this(time, notes, null)
{
}
public PatternActionResult(long? time, IEnumerable<TimedEvent> events)
: this(time, null, events)
{
}
public PatternActionResult(long? time, IEnumerable<Note> notes, IEnumerable<TimedEvent> events)
{
Time = time;
Notes = notes;
Events = events;
}
#endregion
#region Properties
public long? Time { get; }
public IEnumerable<Note> Notes { get; }
public IEnumerable<TimedEvent> Events { get; }
#endregion
}
}
| 21.481481 | 103 | 0.576724 | [
"MIT"
] | FabioZumbi12/drywetmidi | DryWetMidi/Smf.Interaction/Pattern/PatternActionResult.cs | 1,162 | C# |
using MasterDevs.ChromeDevTools;
using Newtonsoft.Json;
using System.Collections.Generic;
namespace MasterDevs.ChromeDevTools.Protocol.Page
{
/// <summary>
/// Overrides the Device Orientation.
/// </summary>
[CommandResponse(ProtocolName.Page.SetDeviceOrientationOverride)]
public class SetDeviceOrientationOverrideCommandResponse
{
}
}
| 23.066667 | 66 | 0.803468 | [
"MIT"
] | brewdente/AutoWebPerf | MasterDevs.ChromeDevTools/Protocol/Page/SetDeviceOrientationOverrideCommandResponse.cs | 346 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Messaging.Sharedlib.Commands
{
public interface IRegisterOrderCommand
{
public Guid OrderId { get; set; }
public string PictureUrl { get; set; }
public string UserEmail { get; set; }
public byte[] ImageData { get; set; }
}
}
| 23.352941 | 46 | 0.677582 | [
"MIT"
] | mvpnaresh/Assignment2 | Faces.SharedLib/Messaging.Sharedlib/Commands/IRegisterOrderCommand.cs | 399 | C# |
using AutoFixture;
using EntityFrameworkCore.AutoFixture.Tests.Common.SpecimenBuilders;
namespace EntityFrameworkCore.AutoFixture.Tests.Common.Customizations
{
public class IgnoredVirtualMembersCustomization : ICustomization
{
public void Customize(IFixture fixture)
{
fixture.Customizations.Add(new IgnoredVirtualMembersSpecimenBuilder());
}
}
}
| 28.357143 | 83 | 0.75063 | [
"MIT"
] | ccpu/EntityFrameworkCore.AutoFixture | src/EntityFrameworkCore.AutoFixture.Tests/Common/Customizations/IgnoredVirtualMembersCustomization.cs | 399 | C# |
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using War3Api.Object.Abilities;
using War3Api.Object.Enums;
using War3Net.Build.Object;
using War3Net.Common.Extensions;
namespace War3Api.Object.Abilities
{
public sealed class SacrificeAcolyte : Ability
{
public SacrificeAcolyte(): base(1835101249)
{
}
public SacrificeAcolyte(int newId): base(1835101249, newId)
{
}
public SacrificeAcolyte(string newRawcode): base(1835101249, newRawcode)
{
}
public SacrificeAcolyte(ObjectDatabaseBase db): base(1835101249, db)
{
}
public SacrificeAcolyte(int newId, ObjectDatabaseBase db): base(1835101249, newId, db)
{
}
public SacrificeAcolyte(string newRawcode, ObjectDatabaseBase db): base(1835101249, newRawcode, db)
{
}
}
} | 24.605263 | 107 | 0.664171 | [
"MIT"
] | YakaryBovine/AzerothWarsCSharp | src/War3Api.Object/Generated/1.32.10.17734/Abilities/SacrificeAcolyte.cs | 935 | C# |
using System;
using System.Collections.Generic;
namespace ImageMetaExtractor
{
public static class ExposureApexAv
{
private static readonly double Log2 = Math.Log(2.0);
/// <summary>
/// F値 / AV値 テーブル (ジャスト1/3刻みにしたいので計算で求めない)
/// </summary>
private static readonly IReadOnlyDictionary<double, double> DictionaryFval2Av =
new Dictionary<double, double>()
{
{ 1.0, 0 },
{ 1.1, 0 + 1 / 3.0 },
{ 1.2, 0 + 2 / 3.0 },
{ 1.4, 1 },
{ 1.6, 1 + 1 / 3.0 },
{ 1.8, 1 + 2 / 3.0 },
{ 2.0, 2 },
{ 2.2, 2 + 1 / 3.0 },
{ 2.5, 2 + 2 / 3.0 },
{ 2.8, 3 },
{ 3.2, 3 + 1 / 3.0 },
{ 3.5, 3 + 2 / 3.0 },
{ 4.0, 4 },
{ 4.5, 4 + 1 / 3.0 },
{ 5.0, 4 + 2 / 3.0 },
{ 5.6, 5 },
{ 6.3, 5 + 1 / 3.0 },
{ 7.1, 5 + 2 / 3.0 },
{ 8.0, 6 },
{ 9.0, 6 + 1 / 3.0 },
{ 10.0, 6 + 2 / 3.0 },
{ 11.0, 7 },
{ 13.0, 7 + 1 / 3.0 },
{ 14.0, 7 + 2 / 3.0 },
{ 16.0, 8 },
{ 18.0, 8 + 1 / 3.0 },
{ 20.0, 8 + 2 / 3.0 },
{ 22.0, 9 },
{ 25.0, 9 + 1 / 3.0 },
{ 28.0, 9 + 2 / 3.0 },
{ 29.0, 9 + 2 / 3.0 }, // Sony
{ 32.0, 10 },
};
/// <summary>
/// F値(string)からAV値(double)を返す
/// </summary>
public static double Fval2Av(string src)
{
string s = src.ToUpper().Replace("F", "");
if (double.TryParse(s, out double fval))
return Fval2Av(fval);
return default;
}
/// <summary>
/// F値(double)からAV値(double)を返す
/// </summary>
public static double Fval2Av(double fval)
{
if (!DictionaryFval2Av.TryGetValue(fval, out double apex))
apex = Math.Log(fval * fval) / Log2;
//Console.WriteLine($"{fval:f2} -> {apex:f3}");
return apex;
}
}
}
| 30.64 | 87 | 0.342037 | [
"MIT"
] | hsytkm/ImageCompareViewer | 10_ImageMeta/ImageMetaExtractor/Interface/ExposureApexAv.cs | 2,378 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
namespace Microsoft.Psi.Visualization.Data
{
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Threading;
using Microsoft.Psi.Visualization.Adapters;
using Microsoft.Psi.Visualization.Collections;
using Microsoft.Psi.Visualization.Windows;
/// <summary>
/// Provides cached-controlled read access to data stores used by the visualization runtime.
/// Manages underlying sets of <see cref="DataStoreReader"/>s and <see cref="StreamSummaryManager"/>s.
/// </summary>
public class DataManager : IDisposable
{
/// <summary>
/// The singleton instance of the <see cref="DataManager"/>.
/// </summary>
public static readonly DataManager Instance = new DataManager();
/// <summary>
/// The collection of data store readers. The keys are a tuple of store name and store path.
/// </summary>
private Dictionary<(string storeName, string storePath), DataStoreReader> dataStoreReaders = new Dictionary<(string storeName, string storePath), DataStoreReader>();
private StreamSummaryManagers streamSummaryManagers = new StreamSummaryManagers();
/// <summary>
/// The task that identifies the current read operation for instant
/// data, or null if no operation is currently in progress.
/// </summary>
private Task instantDataReadTask = null;
/// <summary>
/// The cursor time which should be used for the next read of instant data after the
/// current read operation finishes, or null if there are no read requests outstanding.
/// </summary>
private DateTime? nextInstantReadTaskCursorTime;
/// <summary>
/// The lock used to control access to nextInstantReadTaskCursorTime.
/// </summary>
private object instantReadLock = new object();
private DispatcherTimer dataDispatchTimer;
private bool disposed;
private DataManager()
{
this.disposed = false;
this.nextInstantReadTaskCursorTime = null;
this.dataDispatchTimer = new DispatcherTimer(
TimeSpan.FromSeconds(1.0 / 30.0), DispatcherPriority.Background, (s, e) => this.DoBatchProcessing(), Dispatcher.CurrentDispatcher);
this.dataDispatchTimer.Start();
}
/// <summary>
/// Finalizes an instance of the <see cref="DataManager"/> class.
/// </summary>
~DataManager()
{
this.Dispose(false);
}
/// <summary>
/// Event that fires when a data store's dirty/clean status has changed.
/// </summary>
public event EventHandler<DataStoreStatusChangedEventArgs> DataStoreStatusChanged;
/// <inheritdoc />
public void Dispose()
{
this.Dispose(true);
}
/// <summary>
/// Registers an instant data target to be notified when new data for a stream is available.
/// </summary>
/// <typeparam name="TTarget">The type of data the target requires.</typeparam>
/// <param name="streamSource">Information about the stream source and the required stream adapter.</param>
/// <param name="cursorEpsilon">The epsilon window to use when reading data at a given time.</param>
/// <param name="callback">The method to call when new data is available.</param>
/// <param name="viewRange">The initial time range over which data is expected.</param>
/// <returns>A registration token that must be used by the target to unregister from updates or to modify the read epsilon.</returns>
public Guid RegisterInstantDataTarget<TTarget>(StreamSource streamSource, RelativeTimeInterval cursorEpsilon, Action<object, StreamCacheEntry> callback, TimeInterval viewRange)
{
// Create the instant data target
InstantDataTarget target = new InstantDataTarget(
streamSource.StreamName,
streamSource.StreamAdapter != null ? streamSource.StreamAdapter : new PassthroughAdapter<TTarget>(),
cursorEpsilon,
callback);
// Get the appropriate data store reader
DataStoreReader dataStoreReader = this.GetOrCreateDataStoreReader(streamSource.StoreName, streamSource.StorePath, streamSource.StreamReaderType);
// Create the registration method
MethodInfo method = typeof(DataStoreReader).GetMethod(nameof(DataStoreReader.GetOrCreateStreamCache), BindingFlags.NonPublic | BindingFlags.Instance);
MethodInfo genericMethod = method.MakeGenericMethod(target.StreamAdapter.SourceType, target.StreamAdapter.DestinationType);
// Register the target the data store reader
genericMethod.Invoke(dataStoreReader, new object[] { target, viewRange });
// Pass the registration token back to the caller so he can use it to unregister later
return target.RegistrationToken;
}
/// <summary>
/// Unregisters instant data target from being notified when the current value of a stream changes.
/// </summary>
/// <param name="registrationToken">The registration token that the target was given when it was initially registered.</param>
public void UnregisterInstantDataTarget(Guid registrationToken)
{
foreach (DataStoreReader dataStoreReader in this.dataStoreReaders.Values.ToList())
{
dataStoreReader.UnregisterInstantDataTarget(registrationToken);
}
}
/// <summary>
/// Updates the cursor epsilon for a registered instant visualization object.
/// </summary>
/// <param name="registrationToken">The registration token that the target was given when it was initially registered.</param>
/// <param name="epsilon">A relative time interval specifying the window around a message time that may be considered a match.</param>
public void UpdateInstantDataTargetEpsilon(Guid registrationToken, RelativeTimeInterval epsilon)
{
foreach (DataStoreReader dataStoreReader in this.dataStoreReaders.Values.ToList())
{
dataStoreReader.UpdateInstantDataTargetEpsilon(registrationToken, epsilon);
}
}
/// <summary>
/// Reads the data for all instant data targets and calls them back
/// when the data is ready. This method is only called by the UI thread.
/// </summary>
/// <param name="cursorTime">The time of the visualization container's cursor.</param>
public void ReadInstantData(DateTime cursorTime)
{
// Update the cursor time where the next read should occur
lock (this.instantReadLock)
{
this.nextInstantReadTaskCursorTime = cursorTime;
}
// If the instant read task is not running, start it.
if ((this.instantDataReadTask == null) || this.instantDataReadTask.IsCompleted)
{
this.instantDataReadTask = Task.Run(this.RunReadInstantDataTask);
}
}
/// <summary>
/// Notifies the data manager that the possible range of data that may be read has changed.
/// </summary>
/// <param name="viewRange">The new view range of the navigator.</param>
public void OnInstantViewRangeChanged(TimeInterval viewRange)
{
foreach (DataStoreReader dataStoreReader in this.GetDataStoreReaderList())
{
dataStoreReader.OnInstantViewRangeChanged(viewRange);
}
}
/// <summary>
/// Creates a view of the messages identified by the matching start and end times and asynchronously fills it in.
/// </summary>
/// <typeparam name="T">The type of the message to read.</typeparam>
/// <param name="streamSource">The stream source indicating which stream to read from.</param>
/// <param name="startTime">Start time of messages to read.</param>
/// <param name="endTime">End time of messages to read.</param>
/// <returns>Observable view of data.</returns>
public ObservableKeyedCache<DateTime, Message<T>>.ObservableKeyedView ReadStream<T>(StreamSource streamSource, DateTime startTime, DateTime endTime)
{
if (endTime < startTime)
{
throw new ArgumentException("End time must be greater than or equal to start time.", nameof(endTime));
}
var dataStoreReader = this.GetOrCreateDataStoreReader(streamSource.StoreName, streamSource.StorePath, streamSource.StreamReaderType);
return dataStoreReader.ReadStream(streamSource, ObservableKeyedCache<DateTime, Message<T>>.ObservableKeyedView.ViewMode.Fixed, startTime, endTime, 0, null);
}
/// <summary>
/// Creates a view of the messages identified by the matching tail count and asynchronously fills it in.
/// </summary>
/// <typeparam name="T">The type of the message to read.</typeparam>
/// <param name="streamSource">The stream source indicating which stream to read from.</param>
/// <param name="tailCount">Number of messages to included in tail.</param>
/// <returns>Observable view of data.</returns>
public ObservableKeyedCache<DateTime, Message<T>>.ObservableKeyedView ReadStream<T>(StreamSource streamSource, uint tailCount)
{
if (tailCount == 0)
{
throw new ArgumentException("Tail count must be greater than 0", nameof(tailCount));
}
var dataStoreReader = this.GetOrCreateDataStoreReader(streamSource.StoreName, streamSource.StorePath, streamSource.StreamReaderType);
return dataStoreReader.ReadStream(streamSource, ObservableKeyedCache<DateTime, Message<T>>.ObservableKeyedView.ViewMode.TailCount, DateTime.MinValue, DateTime.MaxValue, tailCount, null);
}
/// <summary>
/// Creates a view of the messages identified by the matching tail range and asynchronously fills it in.
/// </summary>
/// <typeparam name="T">The type of the message to read.</typeparam>
/// <param name="streamSource">The stream source indicating which stream to read from.</param>
/// <param name="tailRange">Function to determine range included in tail.</param>
/// <returns>Observable view of data.</returns>
public ObservableKeyedCache<DateTime, Message<T>>.ObservableKeyedView ReadStream<T>(StreamSource streamSource, Func<DateTime, DateTime> tailRange)
{
if (tailRange == null)
{
throw new ArgumentNullException(nameof(tailRange));
}
var dataStoreReader = this.GetOrCreateDataStoreReader(streamSource.StoreName, streamSource.StorePath, streamSource.StreamReaderType);
return dataStoreReader.ReadStream(streamSource, ObservableKeyedCache<DateTime, Message<T>>.ObservableKeyedView.ViewMode.TailRange, DateTime.MinValue, DateTime.MaxValue, 0, tailRange);
}
/// <summary>
/// Registers a consumer of summary data.
/// </summary>
/// <param name="streamSource">A stream source that indicates the store and stream summary data that the client consumes.</param>
/// <returns>A unique consumer id that should be provided when the consumer unregisters from the stream summary manager.</returns>
public Guid RegisterSummaryDataConsumer(StreamSource streamSource)
{
lock (this.streamSummaryManagers)
{
return this.GetOrCreateStreamSummaryManager(streamSource).RegisterConsumer();
}
}
/// <summary>
/// Unregisters a consumer of summary data.
/// </summary>
/// <param name="consumerId">The id that was returned to the consumer when it registered as a summary data consumer.</param>
public void UnregisterSummaryDataConsumer(Guid consumerId)
{
lock (this.streamSummaryManagers)
{
this.streamSummaryManagers.FirstOrDefault(ssm => ssm.ContainsConsumer(consumerId)).UnregisterConsumer(consumerId);
}
}
/// <summary>
/// Gets a view over the specified time range of the cached summary data.
/// </summary>
/// <typeparam name="T">The summary data type.</typeparam>
/// <param name="streamSource">The stream source indicating which stream to read from.</param>
/// <param name="startTime">The start time of the view range.</param>
/// <param name="endTime">The end time of the view range.</param>
/// <param name="interval">The time interval each summary value should cover.</param>
/// <returns>A view over the cached summary data that covers the specified time range.</returns>
public ObservableKeyedCache<DateTime, IntervalData<T>>.ObservableKeyedView ReadSummary<T>(StreamSource streamSource, DateTime startTime, DateTime endTime, TimeSpan interval)
{
var viewMode = ObservableKeyedCache<DateTime, IntervalData<T>>.ObservableKeyedView.ViewMode.Fixed;
lock (this.streamSummaryManagers)
{
return this.GetStreamSummaryManager(streamSource).ReadSummary(streamSource, viewMode, startTime, endTime, interval, 0, null);
}
}
/// <summary>
/// Gets a view over the specified time range of the cached summary data.
/// </summary>
/// <typeparam name="T">The summary data type.</typeparam>
/// <param name="streamSource">The stream source indicating which stream to read from.</param>
/// <param name="interval">The time interval each summary value should cover.</param>
/// <param name="tailCount">Number of items to include in view.</param>
/// <returns>A view over the cached summary data that covers the specified time range.</returns>
public ObservableKeyedCache<DateTime, IntervalData<T>>.ObservableKeyedView ReadSummary<T>(StreamSource streamSource, TimeSpan interval, uint tailCount)
{
var viewMode = ObservableKeyedCache<DateTime, IntervalData<T>>.ObservableKeyedView.ViewMode.TailCount;
lock (this.streamSummaryManagers)
{
return this.GetStreamSummaryManager(streamSource).ReadSummary(streamSource, viewMode, DateTime.MinValue, DateTime.MaxValue, interval, tailCount, null);
}
}
/// <summary>
/// Gets a view over the specified time range of the cached summary data.
/// </summary>
/// <typeparam name="T">The summary data type.</typeparam>
/// <param name="streamSource">The stream source indicating which stream to read from.</param>
/// <param name="interval">The time interval each summary value should cover.</param>
/// <param name="tailRange">Tail duration function. Computes the view range start time given an end time. Applies to live view mode only.</param>
/// <returns>A view over the cached summary data that covers the specified time range.</returns>
public ObservableKeyedCache<DateTime, IntervalData<T>>.ObservableKeyedView ReadSummary<T>(StreamSource streamSource, TimeSpan interval, Func<DateTime, DateTime> tailRange)
{
var viewMode = ObservableKeyedCache<DateTime, IntervalData<T>>.ObservableKeyedView.ViewMode.TailRange;
lock (this.streamSummaryManagers)
{
return this.GetStreamSummaryManager(streamSource).ReadSummary(streamSource, viewMode, DateTime.MinValue, DateTime.MaxValue, interval, 0, tailRange);
}
}
/// <summary>
/// Gets the supplemental metadata for a stream.
/// </summary>
/// <typeparam name="TSupplementalMetadata">The type of the supplemental metadata.</typeparam>
/// <param name="streamSource">The stream source indicating which stream to read from.</param>
/// <returns>The supplemental metadata for the stream.</returns>
public TSupplementalMetadata GetSupplementalMetadata<TSupplementalMetadata>(StreamSource streamSource)
{
DataStoreReader dataStoreReader = this.GetOrCreateDataStoreReader(streamSource.StoreName, streamSource.StorePath, streamSource.StreamReaderType);
return dataStoreReader.GetSupplementalMetadata<TSupplementalMetadata>(streamSource);
}
/// <summary>
/// Performs a series of updates to the messages in a stream. Stream bindings that use
/// either a stream adapter or a stream summarizer are not permitted to update a stream.
/// </summary>
/// <typeparam name="T">The type of the message to read.</typeparam>
/// <param name="streamSource">The stream source indicating which stream to read from.</param>
/// <param name="updates">A collection of updates to perform.</param>
public void UpdateStream<T>(StreamSource streamSource, IEnumerable<StreamUpdate<T>> updates)
{
if ((streamSource.StreamAdapter != null) || (streamSource.Summarizer != null))
{
throw new InvalidOperationException("StreamSources that use either a StreamAdapter or a Summarizer are not permitted to update streams.");
}
DataStoreReader dataStoreReader = this.GetDataStoreReader(streamSource.StoreName, streamSource.StorePath);
dataStoreReader.UpdateStream(streamSource, updates);
// Notify listeners that the store and stream are now dirty
this.DataStoreStatusChanged?.Invoke(this, new DataStoreStatusChangedEventArgs(streamSource.StoreName, true, streamSource.StreamName));
}
/// <summary>
/// Saves all changes to a store to disk.
/// </summary>
/// <param name="storeName">The name of the store to save.</param>
/// <param name="storePath">The path to the store to save.</param>
/// <param name="progress">A progress interface to report back to.</param>
public void SaveStore(string storeName, string storePath, IProgress<double> progress)
{
DataStoreReader dataStoreReader = this.GetDataStoreReader(storeName, storePath);
string[] savedStreams = dataStoreReader.SaveChanges(progress);
// Notify listeners that the store is now clean
this.DataStoreStatusChanged?.Invoke(this, new DataStoreStatusChangedEventArgs(storeName, false, savedStreams));
}
/// <summary>
/// Closes all readers on a store to allow the store to be moved or updated.
/// </summary>
/// <param name="storeName">The name of the store to close.</param>
/// <param name="storePath">The path to the store to close.</param>
public void CloseStore(string storeName, string storePath)
{
DataStoreReader dataStoreReader = this.GetDataStoreReader(storeName, storePath);
if (dataStoreReader != null)
{
dataStoreReader.Dispose();
this.RemoveDataStoreReader(storeName, storePath);
}
}
/// <summary>
/// Gets originating time of the message in a stream that's closest to a given time.
/// </summary>
/// <param name="streamSource">The stream source indicating which stream to read from.</param>
/// <param name="time">The time for which to return the message with the closest originating time.</param>
/// <returns>The originating time of the message closest to time.</returns>
public DateTime? GetOriginatingTimeOfNearestInstantMessage(StreamSource streamSource, DateTime time)
{
return this.GetOrCreateDataStoreReader(streamSource.StoreName, streamSource.StorePath, streamSource.StreamReaderType).GetOriginatingTimeOfNearestInstantMessage(streamSource, time);
}
/// <summary>
/// Runs a task to read instant data, and continues to run read tasks until there are no read requests left.
/// </summary>
private void RunReadInstantDataTask()
{
DateTime? taskCursorTime;
while (true)
{
// Get the cursor time for the next read request and then null it out
lock (this.instantReadLock)
{
taskCursorTime = this.nextInstantReadTaskCursorTime;
this.nextInstantReadTaskCursorTime = null;
}
// If there's a cursor time, initiate an instant read request on each data store reader, otherwise we're done.
if (taskCursorTime.HasValue)
{
try
{
Parallel.ForEach(this.GetDataStoreReaderList(), dataStoreReader => dataStoreReader.ReadInstantData(taskCursorTime.Value));
}
catch (Exception ex)
{
new MessageBoxWindow(
Application.Current.MainWindow,
"Instant Data Push Error",
$"An error occurred while attempting to push instant data to the visualization objects{Environment.NewLine}{Environment.NewLine}{ex.Message}",
"Close",
null).ShowDialog();
}
}
else
{
return;
}
}
}
/// <summary>
/// Disposes of an instance of the <see cref="DataManager"/> class.
/// </summary>
/// <param name="disposing">Indicates whether the method call comes from a Dispose method (its value is true) or from its destructor (its value is false).</param>
private void Dispose(bool disposing)
{
if (this.disposed)
{
return;
}
if (disposing)
{
// Free any managed objects here.
}
// Free any unmanaged objects here.
foreach (var dataStoreReader in this.dataStoreReaders.Values)
{
dataStoreReader.Dispose();
}
this.dataStoreReaders = null;
this.disposed = true;
GC.SuppressFinalize(this);
}
private void DoBatchProcessing()
{
// Iterate over a copy of the collection as it may be modified by a
// viz object while iterating. Same goes for the streamSummaryManagers below.
foreach (var dataStoreReader in this.GetDataStoreReaderList())
{
// run data store readers
dataStoreReader.Run();
// dispatch data for data stream readers
dataStoreReader.DispatchData();
}
List<StreamSummaryManager> streamSummaryManagerList;
lock (this.streamSummaryManagers)
{
streamSummaryManagerList = this.streamSummaryManagers.ToList();
}
foreach (var streamSummaryManager in streamSummaryManagerList)
{
// dispatch data for stream summary managers
streamSummaryManager.DispatchData();
}
}
private DataStoreReader GetOrCreateDataStoreReader(string storeName, string storePath, Type streamReaderType)
{
if (string.IsNullOrWhiteSpace(storeName))
{
throw new ArgumentNullException(nameof(storeName));
}
if (string.IsNullOrWhiteSpace(storePath))
{
throw new ArgumentNullException(nameof(storePath));
}
lock (this.dataStoreReaders)
{
ValueTuple<string, string> key = (storeName, storePath);
if (this.dataStoreReaders.ContainsKey(key))
{
return this.dataStoreReaders[key];
}
else
{
DataStoreReader dataStoreReader = new DataStoreReader(storeName, storePath, streamReaderType);
this.dataStoreReaders[key] = dataStoreReader;
return dataStoreReader;
}
}
}
private DataStoreReader GetDataStoreReader(string storeName, string storePath)
{
ValueTuple<string, string> key = (storeName, storePath);
lock (this.dataStoreReaders)
{
if (this.dataStoreReaders.ContainsKey(key))
{
return this.dataStoreReaders[key];
}
}
return null;
}
private void RemoveDataStoreReader(string storeName, string storePath)
{
ValueTuple<string, string> key = (storeName, storePath);
this.dataStoreReaders.Remove(key);
}
private List<DataStoreReader> GetDataStoreReaderList()
{
// Locks the data store reader collection and then extracts the list.
lock (this.dataStoreReaders)
{
return this.dataStoreReaders.Values.ToList();
}
}
private StreamSummaryManager GetStreamSummaryManager(StreamSource streamSource)
{
if (streamSource == null)
{
throw new ArgumentNullException(nameof(streamSource));
}
if (string.IsNullOrWhiteSpace(streamSource.StoreName))
{
throw new ArgumentNullException(nameof(streamSource.StoreName));
}
if (string.IsNullOrWhiteSpace(streamSource.StorePath))
{
throw new ArgumentNullException(nameof(streamSource.StorePath));
}
if (string.IsNullOrWhiteSpace(streamSource.StreamName))
{
throw new ArgumentNullException(nameof(streamSource.StreamName));
}
var key = Tuple.Create(streamSource.StoreName, streamSource.StorePath, streamSource.StreamName, streamSource.StreamAdapter);
if (this.streamSummaryManagers.Contains(key))
{
return this.streamSummaryManagers[key];
}
else
{
return null;
}
}
private StreamSummaryManager GetOrCreateStreamSummaryManager(StreamSource streamSource)
{
StreamSummaryManager streamSummaryManager = this.GetStreamSummaryManager(streamSource);
if (streamSummaryManager == null)
{
streamSummaryManager = new StreamSummaryManager(streamSource);
streamSummaryManager.NoRemainingConsumers += this.StreamSummaryManager_NoRemainingConsumers;
this.streamSummaryManagers.Add(streamSummaryManager);
}
return streamSummaryManager;
}
private void StreamSummaryManager_NoRemainingConsumers(object sender, EventArgs e)
{
// If there's no remaining consumers on a stream summary manager, run a task to wait a short
// while and then check if there's still no consumers before removing it from the collection.
Task.Run(() => this.CheckNoRemainingStreamSummaryManagerConsumers(sender as StreamSummaryManager));
}
private void CheckNoRemainingStreamSummaryManagerConsumers(StreamSummaryManager streamSummaryManager)
{
// When we switch layouts the old and new layouts may both reference visualization objects that have the same stream source, but the visualization
// object in the old layout needs to unregister as a consumer from the stream summary manager before the visualization object in the new layout
// registers as a listener. In order to avoid disposing of a stream summary manager and all of its cached data, and then immediately having
// to create it all again when the visualization object in the new layout registers as a listener, we instead wait a short while after the last
// listener has unregistered before removing and disposing of the stream summary manager.
Thread.Sleep(2000);
// Create the key for the stream summary manager.
var key = Tuple.Create(
streamSummaryManager.StoreName,
streamSummaryManager.StorePath,
streamSummaryManager.StreamName,
streamSummaryManager.StreamAdapter);
// If the stream summary manager still has no consumers, remove it from the collection and dispose of it.
lock (this.streamSummaryManagers)
{
if (this.streamSummaryManagers[key].ConsumerCount == 0)
{
this.streamSummaryManagers.Remove(key);
streamSummaryManager.Dispose();
}
}
}
private class StreamSummaryManagers : KeyedCollection<Tuple<string, string, string, IStreamAdapter>, StreamSummaryManager>
{
protected override Tuple<string, string, string, IStreamAdapter> GetKeyForItem(StreamSummaryManager streamSummaryManager)
{
return Tuple.Create(streamSummaryManager.StoreName, streamSummaryManager.StorePath, streamSummaryManager.StreamName, streamSummaryManager.StreamAdapter);
}
}
}
} | 49.377814 | 199 | 0.62117 | [
"MIT"
] | danbohus/psi | Sources/Visualization/Microsoft.Psi.Visualization.Windows/Data/DataManager.cs | 30,715 | C# |
using System;
using System.Web.Mvc;
using DotNet;
namespace Refiddle.Controllers
{
public class RegexController : Controller
{
[HttpPost]
[ValidateInput(false)]
public object Evaluate( string pattern, string corpus_text )
{
var fiddleRunner = new FiddleRunner();
object result;
try
{
var data = fiddleRunner.Match( pattern, corpus_text );
result = base.Json( data, JsonRequestBehavior.AllowGet );
}
catch( Exception ex )
{
result = base.Json( new {
error = ex.Message
}, JsonRequestBehavior.AllowGet );
}
return result;
}
[HttpPost]
[ValidateInput(false)]
public object Replace( string pattern, string corpus_text, string replace_text )
{
var fiddleRunner = new FiddleRunner();
object result;
try
{
var data = fiddleRunner.Replace( pattern, corpus_text, replace_text );
result = base.Json( data, JsonRequestBehavior.AllowGet );
}
catch( Exception ex )
{
result = base.Json( new {
error = ex.Message
}, JsonRequestBehavior.AllowGet );
}
return result;
}
}
} | 24.918367 | 83 | 0.591319 | [
"MIT"
] | FelisPhasma/refiddle-com | runners/DotNet/DotNet/Controllers/RegexController.cs | 1,221 | C# |
#pragma warning disable 108 // new keyword hiding
#pragma warning disable 114 // new keyword hiding
namespace Windows.Media.Core
{
#if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __MACOS__
[global::Uno.NotImplemented]
#endif
public partial struct TimedTextSize
{
// Forced skipping of method Windows.Media.Core.TimedTextSize.TimedTextSize()
#if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __MACOS__
public double Height;
#endif
#if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __MACOS__
public double Width;
#endif
#if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __MACOS__
public global::Windows.Media.Core.TimedTextUnit Unit;
#endif
}
}
| 31.090909 | 79 | 0.722222 | [
"Apache-2.0"
] | 06needhamt/uno | src/Uno.UWP/Generated/3.0.0.0/Windows.Media.Core/TimedTextSize.cs | 684 | C# |
// Copyright (c) 2015 Abel Cheng <abelcys@gmail.com> and other contributors.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
// Repository: https://github.com/DataBooster/DbWebApi
using System;
using System.Text;
using System.Net.Http;
using System.Collections;
namespace DataBooster.DbWebApi.Client
{
public class HttpResponseClientException : HttpRequestException
{
private HttpErrorClient _ErrorDictionary;
private string _DetailMessage;
public HttpResponseClientException(HttpErrorClient errorFromServer)
{
if (errorFromServer == null)
throw new ArgumentNullException("errorFromServer");
_ErrorDictionary = errorFromServer;
_DetailMessage = BuildMessage(_ErrorDictionary);
}
private string BuildMessage(HttpErrorClient errorDictionary)
{
StringBuilder detailMessage = new StringBuilder(errorDictionary.Message);
if (!string.IsNullOrEmpty(errorDictionary.ExceptionMessage))
detailMessage.AppendFormat(" ({0})", errorDictionary.ExceptionMessage);
if (!string.IsNullOrEmpty(errorDictionary.MessageDetail))
{
detailMessage.AppendLine();
detailMessage.Append(errorDictionary.MessageDetail);
}
return detailMessage.ToString();
}
public override IDictionary Data
{
get { return _ErrorDictionary; }
}
public override string Message
{
get { return _DetailMessage; }
}
public override string Source
{
get { return _ErrorDictionary.ExceptionType; }
}
public override string StackTrace
{
get { return _ErrorDictionary.StackTrace; }
}
}
}
| 25.31746 | 101 | 0.760502 | [
"MIT"
] | DataBooster/DbWebApi | Client/Net/DataBooster.DbWebApi.Client/HttpResponseClientException.cs | 1,597 | C# |
//---------------------------------------------------------------------
// <copyright file="EntityTypeAttribute.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//
// @owner [....]
// @backupOwner [....]
//---------------------------------------------------------------------
using System;
namespace System.Data.Objects.DataClasses
{
/// <summary>
/// Attribute identifying the Edm base class
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Edm")]
[AttributeUsage(AttributeTargets.Class, AllowMultiple = false)]
public sealed class EdmEntityTypeAttribute : EdmTypeAttribute
{
/// <summary>
/// Attribute identifying the Edm base class
/// </summary>
public EdmEntityTypeAttribute()
{
}
}
}
| 33.25 | 138 | 0.554243 | [
"Apache-2.0"
] | 295007712/295007712.github.io | sourceCode/dotNet4.6/ndp/fx/src/DataEntity/System/Data/Objects/DataClasses/EdmEntityTypeAttribute.cs | 931 | C# |
namespace LangageBrainFuck
{
public interface IInterpreteur
{
void ChargerProgramme(string codeDuProgramme);
void Executer();
}
} | 20.625 | 55 | 0.642424 | [
"CC0-1.0"
] | Gabt88/420-W30-SF | random/LangageBrainFuck/LangageBrainFuck/IInterpreteur.cs | 201 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
namespace AdvocacyPlatformInstaller.Contracts
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
/// <summary>
/// Interface for a client with logging functionality.
/// </summary>
public interface ILoggedClient
{
/// <summary>
/// Sets the logger instance.
/// </summary>
/// <param name="logger">The logger instance.</param>
void SetLogger(ILogger logger);
}
}
| 26.608696 | 61 | 0.643791 | [
"MIT"
] | Bhaskers-Blu-Org2/AdvocacyPlatform | Installer/AdvocacyPlatformInstaller.Contracts/Interface/ILoggedClient.cs | 614 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using KonacniProjekat.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.EntityFrameworkCore;
namespace KonacniProjekat
{
public class ZnamenitostJednaModel : PageModel
{
public int? SessionId {get; set;}
public readonly OrganizacijaContext dbContext;
public ZnamenitostJednaModel(OrganizacijaContext db)
{
dbContext = db;
}
[BindProperty]
public Znamenitosti TrenutnaZnamenitost{get;set;}
[BindProperty]
public IList<Slike> Slike{get;set;}
public async Task<IActionResult> OnGetAsync(int? id){
SessionId = SessionClass.SessionId;
TrenutnaZnamenitost=await dbContext.Znamenitosti.Where(x=>x.IdZnamenitosti==id).FirstOrDefaultAsync();
Slike = await dbContext.Slike.Where(x=>x.IdZnamenitost==id).ToListAsync();
if(TrenutnaZnamenitost==null){
return NotFound();
}
return Page();
}
}
}
| 28.390244 | 114 | 0.646907 | [
"MIT"
] | aleksija16/ONT | Aplikacija/KonacniProjekat/Pages/ZnamenitostJedna.cshtml.cs | 1,164 | 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/codecapi.h in the Windows SDK for Windows 10.0.20348.0
// Original source is Copyright © Microsoft. All rights reserved.
namespace TerraFX.Interop.Windows;
/// <include file='eAVDecVideoInputScanType.xml' path='doc/member[@name="eAVDecVideoInputScanType"]/*' />
public enum eAVDecVideoInputScanType
{
/// <include file='eAVDecVideoInputScanType.xml' path='doc/member[@name="eAVDecVideoInputScanType.eAVDecVideoInputScan_Unknown"]/*' />
eAVDecVideoInputScan_Unknown = 0,
/// <include file='eAVDecVideoInputScanType.xml' path='doc/member[@name="eAVDecVideoInputScanType.eAVDecVideoInputScan_Progressive"]/*' />
eAVDecVideoInputScan_Progressive = 1,
/// <include file='eAVDecVideoInputScanType.xml' path='doc/member[@name="eAVDecVideoInputScanType.eAVDecVideoInputScan_Interlaced_UpperFieldFirst"]/*' />
eAVDecVideoInputScan_Interlaced_UpperFieldFirst = 2,
/// <include file='eAVDecVideoInputScanType.xml' path='doc/member[@name="eAVDecVideoInputScanType.eAVDecVideoInputScan_Interlaced_LowerFieldFirst"]/*' />
eAVDecVideoInputScan_Interlaced_LowerFieldFirst = 3,
}
| 55 | 157 | 0.78419 | [
"MIT"
] | IngmarBitter/terrafx.interop.windows | sources/Interop/Windows/Windows/um/codecapi/eAVDecVideoInputScanType.cs | 1,267 | C# |
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Reflection.Emit;
namespace Natty.Utility.Reflection.Emit
{
public sealed class EmitUtils
{
private EmitUtils() { }
public static void LoadInt32(ILGenerator gen, int value)
{
if (gen == null)
{
throw new ArgumentNullException("gen");
}
switch (value)
{
case -1:
gen.Emit(OpCodes.Ldc_I4_M1);
break;
case 0:
gen.Emit(OpCodes.Ldc_I4_0);
break;
case 1:
gen.Emit(OpCodes.Ldc_I4_1);
break;
case 2:
gen.Emit(OpCodes.Ldc_I4_2);
break;
case 3:
gen.Emit(OpCodes.Ldc_I4_3);
break;
case 4:
gen.Emit(OpCodes.Ldc_I4_4);
break;
case 5:
gen.Emit(OpCodes.Ldc_I4_5);
break;
case 6:
gen.Emit(OpCodes.Ldc_I4_6);
break;
case 7:
gen.Emit(OpCodes.Ldc_I4_7);
break;
case 8:
gen.Emit(OpCodes.Ldc_I4_8);
break;
default:
if (value > -129 && value < 128)
{
gen.Emit(OpCodes.Ldc_I4_S, (SByte)value);
}
else
{
gen.Emit(OpCodes.Ldc_I4, value);
}
break;
}
}
public static void StoreLocal(ILGenerator gen, int index)
{
if (gen == null)
{
throw new ArgumentNullException("gen");
}
switch (index)
{
case 0:
gen.Emit(OpCodes.Stloc_0);
break;
case 1:
gen.Emit(OpCodes.Stloc_1);
break;
case 2:
gen.Emit(OpCodes.Stloc_2);
break;
case 3:
gen.Emit(OpCodes.Stloc_3);
break;
default:
if (index < 256)
{
gen.Emit(OpCodes.Stloc_S, index);
}
else
{
gen.Emit(OpCodes.Stloc, index);
}
break;
}
}
public static void LoadLocal(ILGenerator gen, int index)
{
if (gen == null)
{
throw new ArgumentNullException("gen");
}
switch (index)
{
case 0:
gen.Emit(OpCodes.Ldloc_0);
break;
case 1:
gen.Emit(OpCodes.Ldloc_1);
break;
case 2:
gen.Emit(OpCodes.Ldloc_2);
break;
case 3:
gen.Emit(OpCodes.Ldloc_3);
break;
default:
if (index < 256)
{
gen.Emit(OpCodes.Ldloc_S, index);
}
else
{
gen.Emit(OpCodes.Ldloc, index);
}
break;
}
}
public static void LoadLocalAddress(ILGenerator gen, int index)
{
if (gen == null)
{
throw new ArgumentNullException("gen");
}
if (index < 256)
gen.Emit(OpCodes.Ldloca_S, (byte)index);
else
gen.Emit(OpCodes.Ldloca, index);
}
public static void LoadArgument(ILGenerator gen, int index)
{
if (gen == null)
{
throw new ArgumentNullException("gen");
}
switch (index)
{
case 0:
gen.Emit(OpCodes.Ldarg_0);
break;
case 1:
gen.Emit(OpCodes.Ldarg_1);
break;
case 2:
gen.Emit(OpCodes.Ldarg_2);
break;
case 3:
gen.Emit(OpCodes.Ldarg_3);
break;
default:
if (index < 256)
gen.Emit(OpCodes.Ldarg_S, (byte)index);
else
gen.Emit(OpCodes.Ldarg, index);
break;
}
}
public static void LoadArgumentAddress(ILGenerator gen, int index)
{
if (gen == null)
{
throw new ArgumentNullException("gen");
}
if (index < 256)
gen.Emit(OpCodes.Ldarga_S, (byte)index);
else
gen.Emit(OpCodes.Ldarga, index);
}
public static void LoadArgument(ILGenerator gen, bool targetIsValueType, int index)
{
if (gen == null)
{
throw new ArgumentNullException("gen");
}
if (targetIsValueType)
{
LoadArgumentAddress(gen, index);
}
else
{
LoadArgument(gen, index);
}
}
public static void Call(ILGenerator gen, MethodInfo method)
{
if (gen == null)
{
throw new ArgumentNullException("gen");
}
if (method == null)
{
throw new ArgumentNullException("method");
}
if (method.IsFinal || !method.IsVirtual)
{
gen.EmitCall(OpCodes.Call, method, null);
}
else
{
gen.EmitCall(OpCodes.Callvirt, method, null);
}
}
}
}
| 27.881579 | 91 | 0.367154 | [
"Apache-2.0"
] | wanglei0803/PrintBarCode | Natty.Utility/Reflection/Emit/EmitUtils.cs | 6,357 | 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>
//------------------------------------------------------------------------------
namespace DPSF {
using System;
using System.Reflection;
/// <summary>
/// A strongly-typed resource class, for looking up localized strings, etc.
/// </summary>
// This class was auto-generated by the StronglyTypedResourceBuilder
// class via a tool like ResGen or Visual Studio.
// To add or remove a member, edit your .ResX file then rerun ResGen
// with the /str option, or rebuild your VS project.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class DPSFResources {
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal DPSFResources() {
}
/// <summary>
/// Returns the cached ResourceManager instance used by this class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager {
get {
if (object.ReferenceEquals(resourceMan, null)) {
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("DPSF.DPSFResources", typeof(DPSFResources).GetTypeInfo().Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// Overrides the current thread's CurrentUICulture property for all
/// resource lookups using this strongly typed resource class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture {
get {
return resourceCulture;
}
set {
resourceCulture = value;
}
}
/// <summary>
/// Looks up a localized resource of type System.Byte[].
/// </summary>
internal static byte[] DPSFDefaultEffectWindowsHiDef {
get {
object obj = ResourceManager.GetObject("DPSFDefaultEffectWindowsHiDef", resourceCulture);
return ((byte[])(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Byte[].
/// </summary>
internal static byte[] DPSFDefaultEffectWindowsReach {
get {
object obj = ResourceManager.GetObject("DPSFDefaultEffectWindowsReach", resourceCulture);
return ((byte[])(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Byte[].
/// </summary>
internal static byte[] DPSFDefaultEffectXbox360HiDef {
get {
object obj = ResourceManager.GetObject("DPSFDefaultEffectXbox360HiDef", resourceCulture);
return ((byte[])(obj));
}
}
}
}
| 41.305263 | 181 | 0.58792 | [
"MIT"
] | deadlydog/DPSF | src/DPSF/DPSFResources.Designer.cs | 3,926 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SelfInjectiveQuiversWithPotential.Plane
{
public class OrientedLineSegment
{
public Point Start { get; }
public Point End { get; }
public OrientedLineSegment(Point start, Point end)
{
Start = start;
End = end;
}
public static bool operator ==(OrientedLineSegment lineSegment1, OrientedLineSegment lineSegment2)
{
return lineSegment1.Start == lineSegment2.Start && lineSegment1.End == lineSegment2.End;
}
public static bool operator !=(OrientedLineSegment lineSegment1, OrientedLineSegment lineSegment2)
{
return lineSegment1.Start != lineSegment2.Start || lineSegment1.End != lineSegment2.End;
}
public void Deconstruct(out Point start, out Point end)
{
start = Start;
end = End;
}
public OrientedLineSegment Reverse()
{
return new OrientedLineSegment(End, Start);
}
public bool IsEqualToAsUnorientedLineSegments(OrientedLineSegment otherLineSegment)
{
return this == otherLineSegment || this == otherLineSegment.Reverse();
}
public bool Intersects(OrientedLineSegment otherLineSegment)
{
if (otherLineSegment is null) throw new ArgumentNullException(nameof(otherLineSegment));
return Intersect(this, otherLineSegment);
}
/// <summary>
/// Determines whether two line segments intersect.
/// </summary>
/// <param name="lineSegment1">The first line segment.</param>
/// <param name="lineSegment2">The second line segment.</param>
/// <returns></returns>
/// <remarks>
/// <para>See <see href="https://www.cdn.geeksforgeeks.org/check-if-two-given-line-segments-intersect/"/>
/// for the inner workings of this method (details which I have not worked out myself).</para></remarks>
public static bool Intersect(OrientedLineSegment lineSegment1, OrientedLineSegment lineSegment2)
{
if (lineSegment1 is null) throw new ArgumentNullException(nameof(lineSegment1));
if (lineSegment2 is null) throw new ArgumentNullException(nameof(lineSegment2));
if (lineSegment1.Start == lineSegment1.End) throw new NotImplementedException(); // Haven't checked that the method works in this case
if (lineSegment2.Start == lineSegment2.End) throw new NotImplementedException(); // Haven't checked that the method works in this case
var ls1 = lineSegment1;
var ls2 = lineSegment2;
var o1 = PlaneUtility.GetOrientation(ls1.Start, ls1.End, ls2.Start);
var o2 = PlaneUtility.GetOrientation(ls1.Start, ls1.End, ls2.End);
var o3 = PlaneUtility.GetOrientation(ls2.Start, ls2.End, ls1.Start);
var o4 = PlaneUtility.GetOrientation(ls2.Start, ls2.End, ls1.End);
if (o1 != o2 && o3 != o4) return true;
if (o1 == TripletOrientation.Collinear && LineSegmentContainsPoint(ls1, ls2.Start)) return true;
if (o2 == TripletOrientation.Collinear && LineSegmentContainsPoint(ls1, ls2.End)) return true;
if (o3 == TripletOrientation.Collinear && LineSegmentContainsPoint(ls2, ls1.Start)) return true;
if (o4 == TripletOrientation.Collinear && LineSegmentContainsPoint(ls2, ls1.End)) return true;
return false;
// Idea (obsolete in favor of the above I guess):
// Look at the common range of, say, the x-coordinates
// If empty, then return false
// If equal at either endpoint, return true (because they intersect in the endpoint)
// If the first line segment is below/above the other in one endpoint and above/below the other in the other, return true
// Else return false
// The above doesn't work when one of the lines is vertical though
// Assumes that p is on the line determined by ls (this assumes that ls is non-degenerate)
bool LineSegmentContainsPoint(OrientedLineSegment ls, Point p)
{
return Math.Min(ls.Start.X, ls.End.X) <= p.X
&& p.X <= Math.Max(ls.Start.X, ls.End.X)
&& Math.Min(ls.Start.Y, ls.End.Y) <= p.Y
&& p.Y <= Math.Max(ls.Start.Y, ls.End.Y);
}
}
/// <summary>
/// Determines whether the line segment intersects the specified line segment properly, in
/// the sense that the interiors of the line segments intersect.
/// </summary>
/// <param name="otherLineSegment">The other line segment.</param>
/// <returns>A boolean value indicating whether the line segments intersect properly.</returns>
public bool IntersectsProperly(OrientedLineSegment otherLineSegment)
{
if (otherLineSegment is null) throw new ArgumentNullException(nameof(otherLineSegment));
return IntersectProperly(this, otherLineSegment);
}
/// <summary>
/// Determines whether two line segments intersect properly, in the sense that the
/// interiors of the line segments intersect.
/// </summary>
/// <param name="lineSegment1">The first line segment.</param>
/// <param name="lineSegment2">The second line segment.</param>
/// <returns></returns>
public static bool IntersectProperly(OrientedLineSegment lineSegment1, OrientedLineSegment lineSegment2)
{
if (lineSegment1 is null) throw new ArgumentNullException(nameof(lineSegment1));
if (lineSegment2 is null) throw new ArgumentNullException(nameof(lineSegment2));
if (lineSegment1.Start == lineSegment1.End) return false; // The interior of a degenerate line segment is empty
if (lineSegment2.Start == lineSegment2.End) return false; // The interior of a degenerate line segment is empty
var ls1 = lineSegment1;
var ls2 = lineSegment2;
var o1 = PlaneUtility.GetOrientation(ls1.Start, ls1.End, ls2.Start);
var o2 = PlaneUtility.GetOrientation(ls1.Start, ls1.End, ls2.End);
var o3 = PlaneUtility.GetOrientation(ls2.Start, ls2.End, ls1.Start);
var o4 = PlaneUtility.GetOrientation(ls2.Start, ls2.End, ls1.End);
// The line segments are collinear
if (o1 == TripletOrientation.Collinear && o2 == TripletOrientation.Collinear)
{
return ls1.IsEqualToAsUnorientedLineSegments(ls2)
|| LineSegmentInteriorContainsPoint(ls1, ls2.Start)
|| LineSegmentInteriorContainsPoint(ls1, ls2.End)
|| LineSegmentInteriorContainsPoint(ls2, ls1.Start)
|| LineSegmentInteriorContainsPoint(ls2, ls1.End);
}
// The line segments are not collinear, so if any three points are collinear, the line segments just "touch"
// each other, which does not constitute a proper intersection
if (o1 == TripletOrientation.Collinear || o2 == TripletOrientation.Collinear || o3 == TripletOrientation.Collinear || o4 == TripletOrientation.Collinear)
return false;
// Then just do "the usual" check
return (o1 != o2 && o3 != o4);
// Assumes that p is on the line determined by ls (this assumes that ls is non-degenerate)
bool LineSegmentContainsPoint(OrientedLineSegment ls, Point p)
{
return Math.Min(ls.Start.X, ls.End.X) <= p.X
&& p.X <= Math.Max(ls.Start.X, ls.End.X)
&& Math.Min(ls.Start.Y, ls.End.Y) <= p.Y
&& p.Y <= Math.Max(ls.Start.Y, ls.End.Y);
}
// Assumes that p is on the line determined by ls (this assumes that ls is non-degenerate)
bool LineSegmentInteriorContainsPoint(OrientedLineSegment ls, Point p)
{
return LineSegmentContainsPoint(ls, p) && p != ls.Start && p != ls.End;
}
}
public override bool Equals(object obj)
{
var segment = obj as OrientedLineSegment;
return segment != null &&
EqualityComparer<Point>.Default.Equals(Start, segment.Start) &&
EqualityComparer<Point>.Default.Equals(End, segment.End);
}
public override int GetHashCode()
{
var hashCode = -1676728671;
hashCode = hashCode * -1521134295 + EqualityComparer<Point>.Default.GetHashCode(Start);
hashCode = hashCode * -1521134295 + EqualityComparer<Point>.Default.GetHashCode(End);
return hashCode;
}
public override string ToString()
{
return $"{Start} to {End}";
}
}
}
| 45.653266 | 165 | 0.618382 | [
"MIT"
] | Samuel-Q/SelfInjectiveQuiversWithPotential | SelfInjectiveQuiversWithPotential/Plane/OrientedLineSegment.cs | 9,087 | C# |
using System;
namespace SnowLeopard.FastDFS
{
/// <summary>
/// query which storage server to store file
///
/// Reqeust
/// Cmd: TRACKER_PROTO_CMD_SERVICE_QUERY_STORE_WITH_GROUP_ALL 107
/// Body:
/// @ FDFS_GROUP_NAME_MAX_LEN bytes: group name
/// Response
/// Cmd: TRACKER_PROTO_CMD_RESP
/// Status: 0 right other wrong
/// Body:
/// @ FDFS_GROUP_NAME_MAX_LEN bytes: group name
/// @ IP_ADDRESS_SIZE - 1 bytes: storage server ip address
/// @ FDFS_PROTO_PKG_LEN_SIZE bytes: storage server port
/// @ 1 byte: store path index on the storage server
/// </summary>
public class QUERY_STORE_WITH_GROUP_ALL : FDFSRequest
{
private QUERY_STORE_WITH_GROUP_ALL()
{
}
public override FDFSRequest GetRequest(params object[] paramList)
{
throw new NotImplementedException();
}
public class Response
{
}
}
}
| 25.846154 | 73 | 0.595238 | [
"MIT"
] | alienwow/SnowLeopard | src/SnowLeopard.FastDFS/Tracker/QUERY_STORE_WITH_GROUP_ALL.cs | 1,010 | C# |
namespace Altsoft.PDFO
{
using System;
public class SignatureLock : Resource
{
// Methods
public SignatureLock(PDFDict dict) : base(dict)
{
}
public static Resource Factory(PDFDirect direct)
{
return new SignatureLock((direct as PDFDict));
}
// Properties
public EAction Action
{
get
{
string text1 = (this.Dict["Action"] as PDFName).Value;
if (text1 == null)
{
goto Label_0056;
}
text1 = string.IsInterned(text1);
if (text1 != "All")
{
if (text1 == "Include")
{
goto Label_0052;
}
if (text1 == "Exclude")
{
goto Label_0054;
}
goto Label_0056;
}
return EAction.All;
Label_0052:
return EAction.Include;
Label_0054:
return EAction.Exclude;
Label_0056:
throw new Exception("Unknown Action value");
}
set
{
string text1 = "";
EAction action1 = value;
switch (action1)
{
case EAction.All:
{
text1 = "All";
goto Label_0032;
}
case EAction.Include:
{
text1 = "Include";
goto Label_0032;
}
case EAction.Exclude:
{
goto Label_002C;
}
}
goto Label_0032;
Label_002C:
text1 = "Exclude";
Label_0032:
this.Dict["Action"] = Library.CreateName(text1);
}
}
public StringList Fields
{
get
{
if (this.mFields != null)
{
return this.mFields;
}
return new StringList(this.Dict, "Fields", false);
}
set
{
this.mFields = value;
}
}
public string Type
{
get
{
return "SigFieldLock";
}
}
// Fields
private StringList mFields;
}
}
| 24.796296 | 70 | 0.348394 | [
"MIT"
] | silvath/siscobras | mdlPDF/Xml2PDF/Source/Altsoft/PDFO/SignatureLock.cs | 2,678 | C# |
using ExpandedContent.Config;
using ExpandedContent.Extensions;
using ExpandedContent.Utilities;
using Kingmaker.Blueprints;
using Kingmaker.Blueprints.Classes;
using Kingmaker.Blueprints.Classes.Prerequisites;
using Kingmaker.Blueprints.Items;
using Kingmaker.Designers.Mechanics.Facts;
using Kingmaker.UnitLogic.Alignments;
using Kingmaker.UnitLogic.FactLogic;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ExpandedContent.Tweaks.Archdevils {
internal class Mephistopheles {
private static readonly BlueprintFeature RuneDomainAllowed = Resources.GetBlueprint<BlueprintFeature>("77637f81d6aa33b4f82873d7934e8c4b");
private static readonly BlueprintFeature EvilDomainAllowed = Resources.GetBlueprint<BlueprintFeature>("351235ac5fc2b7e47801f63d117b656c");
private static readonly BlueprintFeature KnowledgeDomainAllowed = Resources.GetBlueprint<BlueprintFeature>("443d44b3e0ea84046a9bf304c82a0425");
private static readonly BlueprintFeature LawDomainAllowed = Resources.GetBlueprint<BlueprintFeature>("092714336606cfc45a37d2ab39fabfa8");
private static readonly BlueprintFeature CrusaderSpellbook = Resources.GetBlueprint<BlueprintFeature>("673d39f7da699aa408cdda6282e7dcc0");
private static readonly BlueprintFeature ClericSpellbook = Resources.GetBlueprint<BlueprintFeature>("4673d19a0cf2fab4f885cc4d1353da33");
private static readonly BlueprintFeature InquisitorSpellbook = Resources.GetBlueprint<BlueprintFeature>("57fab75111f377248810ece84193a5a5");
private static readonly BlueprintFeature ChannelNegativeAllowed = Resources.GetBlueprint<BlueprintFeature>("dab5255d809f77c4395afc2b713e9cd6");
private static readonly BlueprintCharacterClass ClericClass = Resources.GetBlueprint<BlueprintCharacterClass>("67819271767a9dd4fbfd4ae700befea0");
private static readonly BlueprintCharacterClass InquistorClass = Resources.GetBlueprint<BlueprintCharacterClass>("f1a70d9e1b0b41e49874e1fa9052a1ce");
private static readonly BlueprintCharacterClass WarpriestClass = Resources.GetBlueprint<BlueprintCharacterClass>("30b5e47d47a0e37438cc5a80c96cfb99");
public static void AddMephistopheles() {
if (ModSettings.AddedContent.Archdevils.IsDisabled("Mephistopheles")) { return; }
BlueprintFeature TridentProficiency = Resources.GetBlueprint<BlueprintFeature>("f9565a97342ac594e9b6a495368c1a57");
BlueprintArchetype FeralChampionArchetype = Resources.GetBlueprint<BlueprintArchetype>("f68ca492c9c15e241ab73735fbd0fb9f");
BlueprintArchetype PriestOfBalance = Resources.GetBlueprint<BlueprintArchetype>("a4560e3fb5d247d68fb1a2738fcc0855");
BlueprintItem ColdIronTrident = Resources.GetBlueprint<BlueprintItem>("fed59d344fe866d42a51c128dc1cc86b");
var MephistophelesIcon = AssetLoader.LoadInternal("Deities", "Icon_Mephistopheles.jpg");
var MephistophelesFeature = Helpers.CreateBlueprint<BlueprintFeature>("MephistophelesFeature", (bp => {
bp.SetName("Mephistopheles");
bp.SetDescription("\nTitles: Crimson Son, Devil King, Lord of the Eighth, Merchant of Souls, Seneschal of Hell " +
"\nRealm: Caina, Hell " +
"\nAlignment: Lawful Evil " +
"\nAreas of Concern: Contracts, Devils, Secrets " +
"\nDomains: Evil, Knowledge, Law, Rune " +
"\nSubdomains: Devil, Language, Memory, Thought " +
"\nFavoured Weapon: Trident " +
"\nProfane Symbol: Trident and Ring " +
"\nProfane Animal: Mockingbird " +
"\nProfane Colours: Red and Yellow " +
"\nThe archdevil Mephistopheles is the ruler of Caina, the Eighth Layer of Hell, where he keeps many of Hell's greatest secrets and contracts. " +
"Mephistopheles' official and true unholy symbol is, in essence, a crimson trident piercing a golden ring, with the three prongs of the trident alluding " +
"to the spires of Caina. His symbols are rarely seen, however, as owing one's allegiance to Mephistopheles is most often kept secret. " +
"Simpler, alternative versions of his unholy symbol exist, including a red sun eclipsed by three mountains; a tongue pierced with three studs; and a " +
"scale surmounted with a feather, topped by a bone. The latter evokes Mephistopheles' three sets of wings. Mephistopheles originated as the consciousness of " +
"Hell itself, predating Asmodeus' discovery of the plane. When Asmodeus and his followers entered Hell following their Exodus from Heaven, Asmodeus traveled " +
"into Caina and tore Hell's very flesh from its bones, reshaping it into a being he named Mephistopheles. The newly formed entity, the first true devil, pledged " +
"to oppose Asmodeus' enemies as if they were its own, and became one of Asmodeus' closest lieutenants. This story is recorded in the " +
"Book of the Damned.");
bp.m_Icon = MephistophelesIcon;
bp.Ranks = 1;
bp.IsClassFeature = true;
bp.HideInCharacterSheetAndLevelUp = false;
bp.AddComponent<PrerequisiteNoArchetype>(c => {
c.m_CharacterClass = ClericClass.ToReference<BlueprintCharacterClassReference>();
c.m_Archetype = PriestOfBalance.ToReference<BlueprintArchetypeReference>();
});
bp.AddComponent<PrerequisiteNoArchetype>(c => {
c.m_CharacterClass = WarpriestClass.ToReference<BlueprintCharacterClassReference>();
c.m_Archetype = FeralChampionArchetype.ToReference<BlueprintArchetypeReference>();
});
bp.Groups = new FeatureGroup[] { FeatureGroup.Deities };
bp.AddComponent<PrerequisiteAlignment>(c => {
c.Alignment = AlignmentMaskType.LawfulEvil | AlignmentMaskType.NeutralEvil | AlignmentMaskType.LawfulNeutral | AlignmentMaskType.TrueNeutral;
});
bp.AddComponent<AddFacts>(c => {
c.m_Facts = new BlueprintUnitFactReference[1] { ChannelNegativeAllowed.ToReference<BlueprintUnitFactReference>() };
});
bp.AddComponent<AddFacts>(c => {
c.m_Facts = new BlueprintUnitFactReference[1] { EvilDomainAllowed.ToReference<BlueprintUnitFactReference>() };
});
bp.AddComponent<AddFacts>(c => {
c.m_Facts = new BlueprintUnitFactReference[1] { LawDomainAllowed.ToReference<BlueprintUnitFactReference>() };
});
bp.AddComponent<AddFacts>(c => {
c.m_Facts = new BlueprintUnitFactReference[1] { RuneDomainAllowed.ToReference<BlueprintUnitFactReference>() };
});
bp.AddComponent<AddFacts>(c => {
c.m_Facts = new BlueprintUnitFactReference[1] { KnowledgeDomainAllowed.ToReference<BlueprintUnitFactReference>() };
});
bp.AddComponent<ForbidSpellbookOnAlignmentDeviation>(c => {
c.m_Spellbooks = new BlueprintSpellbookReference[1] { CrusaderSpellbook.ToReference<BlueprintSpellbookReference>() };
c.m_Spellbooks = new BlueprintSpellbookReference[1] { ClericSpellbook.ToReference<BlueprintSpellbookReference>() };
c.m_Spellbooks = new BlueprintSpellbookReference[1] { InquisitorSpellbook.ToReference<BlueprintSpellbookReference>() };
});
bp.AddComponent<AddFeatureOnClassLevel>(c => {
c.m_Class = ClericClass.ToReference<BlueprintCharacterClassReference>();
c.m_Feature = TridentProficiency.ToReference<BlueprintFeatureReference>();
c.Level = 1;
c.m_Archetypes = null;
c.m_AdditionalClasses = new BlueprintCharacterClassReference[2] {
InquistorClass.ToReference<BlueprintCharacterClassReference>(),
WarpriestClass.ToReference<BlueprintCharacterClassReference>() };
});
bp.AddComponent<AddStartingEquipment>(c => {
c.m_BasicItems = new BlueprintItemReference[1] { ColdIronTrident.ToReference<BlueprintItemReference>() };
c.m_RestrictedByClass = new BlueprintCharacterClassReference[3] {
ClericClass.ToReference<BlueprintCharacterClassReference>(),
InquistorClass.ToReference<BlueprintCharacterClassReference>(),
WarpriestClass.ToReference<BlueprintCharacterClassReference>()
};
});
}));
}
}
}
| 69.564885 | 184 | 0.673872 | [
"MIT"
] | bittercranberry/ExpandedContent | ExpandedContent/Tweaks/Archdevils/Mephistopheles.cs | 9,115 | C# |
// OData .NET Libraries ver. 5.6.3
// Copyright (c) Microsoft Corporation
// All rights reserved.
// MIT License
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
// Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
using System.Collections.Generic;
namespace Microsoft.Data.Edm
{
/// <summary>
/// Common base interface for definitions of EDM structured types.
/// </summary>
public interface IEdmStructuredType : IEdmType
{
/// <summary>
/// Gets a value indicating whether this type is abstract.
/// </summary>
bool IsAbstract { get; }
/// <summary>
/// Gets a value indicating whether this type is open.
/// </summary>
bool IsOpen { get; }
/// <summary>
/// Gets the base type of this type.
/// </summary>
IEdmStructuredType BaseType { get; }
/// <summary>
/// Gets the properties declared immediately within this type.
/// </summary>
IEnumerable<IEdmProperty> DeclaredProperties { get; }
/// <summary>
/// Searches for a structural or navigation property with the given name in this type and all base types and returns null if no such property exists.
/// </summary>
/// <param name="name">The name of the property being found.</param>
/// <returns>The requested property, or null if no such property exists.</returns>
IEdmProperty FindProperty(string name);
}
}
| 42.898305 | 158 | 0.657843 | [
"Apache-2.0"
] | tapika/choco | lib/Microsoft.Data.Services.Client/ODataLib/EdmLib/Desktop/.Net4.0/Microsoft/Data/Edm/Interfaces/IEdmStructuredType.cs | 2,531 | C# |
using System;
using ChartDirector;
namespace CSharpChartExplorer
{
public class surface : DemoModule
{
//Name of demo module
public string getName() { return "Surface Chart (1)"; }
//Number of charts produced in this demo module
public int getNoOfCharts() { return 1; }
//Main code for creating chart.
//Note: the argument chartIndex is unused because this demo only has 1 chart.
public void createChart(WinChartViewer viewer, int chartIndex)
{
// The x and y coordinates of the grid
double[] dataX = {-10, -9, -8, -7, -6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
10};
double[] dataY = {-10, -9, -8, -7, -6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
10};
// The values at the grid points. In this example, we will compute the values using the
// formula z = x * sin(y) + y * sin(x).
double[] dataZ = new double[dataX.Length * dataY.Length];
for(int yIndex = 0; yIndex < dataY.Length; ++yIndex) {
double y = dataY[yIndex];
for(int xIndex = 0; xIndex < dataX.Length; ++xIndex) {
double x = dataX[xIndex];
dataZ[yIndex * dataX.Length + xIndex] = x * Math.Sin(y) + y * Math.Sin(x);
}
}
// Create a SurfaceChart object of size 720 x 600 pixels
SurfaceChart c = new SurfaceChart(720, 600);
// Add a title to the chart using 20 points Times New Roman Italic font
c.addTitle("Surface Energy Density ", "Times New Roman Italic", 20);
// Set the center of the plot region at (350, 280), and set width x depth x height to
// 360 x 360 x 270 pixels
c.setPlotRegion(350, 280, 360, 360, 270);
// Set the data to use to plot the chart
c.setData(dataX, dataY, dataZ);
// Spline interpolate data to a 80 x 80 grid for a smooth surface
c.setInterpolation(80, 80);
// Add a color axis (the legend) in which the left center is anchored at (645, 270). Set
// the length to 200 pixels and the labels on the right side.
c.setColorAxis(645, 270, Chart.Left, 200, Chart.Right);
// Set the x, y and z axis titles using 10 points Arial Bold font
c.xAxis().setTitle("X (nm)", "Arial Bold", 10);
c.yAxis().setTitle("Y (nm)", "Arial Bold", 10);
c.zAxis().setTitle("Energy Density (J/m<*font,super*>2<*/font*>)", "Arial Bold", 10);
// Output the chart
viewer.Chart = c;
}
}
}
| 41.166667 | 100 | 0.54067 | [
"Apache-2.0"
] | jojogreen/Orbital-Mechanix-Suite | NetWinCharts/CSharpWinCharts/surface.cs | 2,717 | C# |
using System.Collections.Generic;
using System.Linq;
using FluentAssertions;
using SheddingCardGames.Domain;
namespace SheddingCardGames.Tests.EndToEnd
{
public class OlsenOlsenVariantVerifier
{
private readonly Game sut;
private readonly Dictionary<int, CardCollection> playerHands;
private readonly Card discardCard;
private readonly CardCollection stockPile;
public OlsenOlsenVariantVerifier(Game sut, Dictionary<int, CardCollection> playerHands, Card discardCard,
CardCollection stockPile)
{
this.sut = sut;
this.playerHands = playerHands;
this.discardCard = discardCard;
this.stockPile = stockPile;
}
public void VerifySetup(int numberOfPlayer)
{
sut.GameState.CurrentStateOfTurn.TurnNumber.Should().Be(1);
for (var i = 0; i < numberOfPlayer; i++)
sut.GameState.CurrentTable.Players[i].Hand.Cards.Should().Equal(playerHands[i + 1].Cards);
sut.GameState.CurrentTable.DiscardPile.CardToMatch.Should().Be(discardCard);
sut.GameState.CurrentTable.StockPile.Cards.Should().Equal(stockPile.Cards);
}
public void VerifyTake(int playerNumber, CommandExecutionResult takeResult, int turnNumber,
Card takenCard,
params Card[] hand)
{
takeResult.IsSuccess.Should().BeTrue();
sut.GameState.CurrentStateOfTurn.TakenCard.Should().Be(takenCard);
sut.GameState.CurrentStateOfTurn.TurnNumber.Should().Be(turnNumber);
sut.GameState.CurrentTable.Players[playerNumber - 1].Hand.Cards.Should().Equal(hand);
}
public void VerifyWon(int playerNumber, CommandExecutionResult result, int turnNumber,
Card[] cardsPlayed)
{
result.IsSuccess.Should().BeTrue();
sut.GameState.CurrentStateOfTurn.TurnNumber.Should().Be(turnNumber);
sut.GameState.CurrentTable.Players[playerNumber - 1].Hand.Cards.Should().BeEmpty();
sut.GameState.CurrentStateOfPlay.HasWinner.Should().BeTrue();
sut.GameState.CurrentStateOfPlay.Winner.Number.Should().Be(playerNumber);
sut.GameState.CurrentTable.DiscardPile.CardToMatch.Should().Be(cardsPlayed.Last());
var cardsPlayedExceptLast = cardsPlayed.SkipLast(1);
var cardsAddedToDiscardPile = sut.GameState.CurrentTable.DiscardPile.RestOfCards.Cards.SkipLast(1)
.Take(cardsPlayedExceptLast.Count());
cardsAddedToDiscardPile.Should().Equal(cardsPlayedExceptLast.Reverse());
}
public void VerifySelectSuit(CommandExecutionResult result, int turnNumber, Suit selectedSuit)
{
result.IsSuccess.Should().BeTrue();
sut.GameState.CurrentStateOfTurn.TurnNumber.Should().Be(turnNumber);
sut.GameState.CurrentStateOfTurn.SelectedSuit.Should().Be(selectedSuit);
}
public void VerifyPlayMultiple(int playerNumber, CommandExecutionResult result, int turnNumber,
Card[] cardsPlayed, params Card[] hand)
{
result.IsSuccess.Should().BeTrue();
sut.GameState.CurrentStateOfTurn.TurnNumber.Should().Be(turnNumber);
sut.GameState.CurrentTable.Players[playerNumber - 1].Hand.Cards.Should().Equal(hand);
sut.GameState.CurrentTable.DiscardPile.CardToMatch.Should().Be(cardsPlayed.Last());
var cardsPlayedExceptLast = cardsPlayed.SkipLast(1);
var cardsAddedToDiscardPile = sut.GameState.CurrentTable.DiscardPile.RestOfCards.Cards.SkipLast(1)
.Take(cardsPlayedExceptLast.Count());
cardsAddedToDiscardPile.Should().Equal(cardsPlayedExceptLast.Reverse());
}
}
} | 47.074074 | 113 | 0.67401 | [
"MIT"
] | JonQuxBurton/CardGames | SheddingCardGames/SheddingCardGames.Tests/EndToEnd/OlsenOlsenVariantVerifier.cs | 3,815 | C# |
#region copyright
// ******************************************************************
// Copyright (c) Microsoft. All rights reserved.
// This code is licensed under the MIT License (MIT).
// THE CODE 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 CODE OR THE USE OR OTHER DEALINGS IN THE CODE.
// ******************************************************************
#endregion
using System;
using System.IO;
using Windows.Storage;
using Windows.ApplicationModel;
using Inventory.Services;
namespace Inventory
{
public class AppSettings
{
const string DB_NAME = "VanArsdel";
const string DB_VERSION = "1.01";
const string DB_BASEURL = "https://vanarsdelinventory.blob.core.windows.net/database";
static AppSettings()
{
Current = new AppSettings();
}
static public AppSettings Current { get; }
static public readonly string AppLogPath = "AppLog";
static public readonly string AppLogName = $"AppLog.1.0.db";
static public readonly string AppLogFileName = Path.Combine(AppLogPath, AppLogName);
public readonly string AppLogConnectionString = $"Data Source={AppLogFileName}";
static public readonly string DatabasePath = "Database";
static public readonly string DatabaseName = $"{DB_NAME}.{DB_VERSION}.db";
static public readonly string DatabasePattern = $"{DB_NAME}.{DB_VERSION}.pattern.db";
static public readonly string DatabaseFileName = Path.Combine(DatabasePath, DatabaseName);
static public readonly string DatabasePatternFileName = Path.Combine(DatabasePath, DatabasePattern);
static public readonly string DatabaseUrl = $"{DB_BASEURL}/{DatabaseName}";
public readonly string SQLiteConnectionString = $"Data Source={DatabaseFileName}";
public ApplicationDataContainer LocalSettings => ApplicationData.Current.LocalSettings;
public string Version
{
get
{
var ver = Package.Current.Id.Version;
return $"{ver.Major}.{ver.Minor}.{ver.Build}.{ver.Revision}";
}
}
public string DbVersion => DB_VERSION;
public string UserName
{
get => GetSettingsValue("UserName", default(String));
set => LocalSettings.Values["UserName"] = value;
}
public string WindowsHelloPublicKeyHint
{
get => GetSettingsValue("WindowsHelloPublicKeyHint", default(String));
set => LocalSettings.Values["WindowsHelloPublicKeyHint"] = value;
}
public DataProviderType DataProvider
{
get => (DataProviderType)GetSettingsValue("DataProvider", (int)DataProviderType.SQLite);
set => LocalSettings.Values["DataProvider"] = (int)value;
}
public string SQLServerConnectionString
{
get => GetSettingsValue("SQLServerConnectionString", @"Data Source=.\SQLExpress;Initial Catalog=VanArsdelDb;Integrated Security=SSPI");
set => SetSettingsValue("SQLServerConnectionString", value);
}
public bool IsRandomErrorsEnabled
{
get => GetSettingsValue("IsRandomErrorsEnabled", false);
set => LocalSettings.Values["IsRandomErrorsEnabled"] = value;
}
private TResult GetSettingsValue<TResult>(string name, TResult defaultValue)
{
try
{
if (!LocalSettings.Values.ContainsKey(name))
{
LocalSettings.Values[name] = defaultValue;
}
return (TResult)LocalSettings.Values[name];
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex.Message);
return defaultValue;
}
}
private void SetSettingsValue(string name, object value)
{
LocalSettings.Values[name] = value;
}
}
}
| 37.016949 | 147 | 0.619734 | [
"MIT"
] | AgneLukoseviciute/react-native-windows-samples | samples/TodosFeed/InventorySample/Inventory.App/Configuration/AppSettings.cs | 4,370 | C# |
// *** WARNING: this file was generated by the Pulumi SDK Generator. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.AzureNative.Storage.V20190601
{
/// <summary>
/// The Get Storage Account ManagementPolicies operation response.
/// </summary>
[AzureNativeResourceType("azure-native:storage/v20190601:ManagementPolicy")]
public partial class ManagementPolicy : Pulumi.CustomResource
{
/// <summary>
/// Returns the date and time the ManagementPolicies was last modified.
/// </summary>
[Output("lastModifiedTime")]
public Output<string> LastModifiedTime { get; private set; } = null!;
/// <summary>
/// The name of the resource
/// </summary>
[Output("name")]
public Output<string> Name { get; private set; } = null!;
/// <summary>
/// The Storage Account ManagementPolicy, in JSON format. See more details in: https://docs.microsoft.com/en-us/azure/storage/common/storage-lifecycle-managment-concepts.
/// </summary>
[Output("policy")]
public Output<Outputs.ManagementPolicySchemaResponse> Policy { get; private set; } = null!;
/// <summary>
/// The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts"
/// </summary>
[Output("type")]
public Output<string> Type { get; private set; } = null!;
/// <summary>
/// Create a ManagementPolicy resource with the given unique name, arguments, and options.
/// </summary>
///
/// <param name="name">The unique name of the resource</param>
/// <param name="args">The arguments used to populate this resource's properties</param>
/// <param name="options">A bag of options that control this resource's behavior</param>
public ManagementPolicy(string name, ManagementPolicyArgs args, CustomResourceOptions? options = null)
: base("azure-native:storage/v20190601:ManagementPolicy", name, args ?? new ManagementPolicyArgs(), MakeResourceOptions(options, ""))
{
}
private ManagementPolicy(string name, Input<string> id, CustomResourceOptions? options = null)
: base("azure-native:storage/v20190601:ManagementPolicy", name, null, MakeResourceOptions(options, id))
{
}
private static CustomResourceOptions MakeResourceOptions(CustomResourceOptions? options, Input<string>? id)
{
var defaultOptions = new CustomResourceOptions
{
Version = Utilities.Version,
Aliases =
{
new Pulumi.Alias { Type = "azure-nextgen:storage/v20190601:ManagementPolicy"},
new Pulumi.Alias { Type = "azure-native:storage:ManagementPolicy"},
new Pulumi.Alias { Type = "azure-nextgen:storage:ManagementPolicy"},
new Pulumi.Alias { Type = "azure-native:storage/latest:ManagementPolicy"},
new Pulumi.Alias { Type = "azure-nextgen:storage/latest:ManagementPolicy"},
new Pulumi.Alias { Type = "azure-native:storage/v20180301preview:ManagementPolicy"},
new Pulumi.Alias { Type = "azure-nextgen:storage/v20180301preview:ManagementPolicy"},
new Pulumi.Alias { Type = "azure-native:storage/v20181101:ManagementPolicy"},
new Pulumi.Alias { Type = "azure-nextgen:storage/v20181101:ManagementPolicy"},
new Pulumi.Alias { Type = "azure-native:storage/v20190401:ManagementPolicy"},
new Pulumi.Alias { Type = "azure-nextgen:storage/v20190401:ManagementPolicy"},
new Pulumi.Alias { Type = "azure-native:storage/v20200801preview:ManagementPolicy"},
new Pulumi.Alias { Type = "azure-nextgen:storage/v20200801preview:ManagementPolicy"},
new Pulumi.Alias { Type = "azure-native:storage/v20210101:ManagementPolicy"},
new Pulumi.Alias { Type = "azure-nextgen:storage/v20210101:ManagementPolicy"},
},
};
var merged = CustomResourceOptions.Merge(defaultOptions, options);
// Override the ID if one was specified for consistency with other language SDKs.
merged.Id = id ?? merged.Id;
return merged;
}
/// <summary>
/// Get an existing ManagementPolicy resource's state with the given name, ID, and optional extra
/// properties used to qualify the lookup.
/// </summary>
///
/// <param name="name">The unique name of the resulting resource.</param>
/// <param name="id">The unique provider ID of the resource to lookup.</param>
/// <param name="options">A bag of options that control this resource's behavior</param>
public static ManagementPolicy Get(string name, Input<string> id, CustomResourceOptions? options = null)
{
return new ManagementPolicy(name, id, options);
}
}
public sealed class ManagementPolicyArgs : Pulumi.ResourceArgs
{
/// <summary>
/// The name of the storage account within the specified resource group. Storage account names must be between 3 and 24 characters in length and use numbers and lower-case letters only.
/// </summary>
[Input("accountName", required: true)]
public Input<string> AccountName { get; set; } = null!;
/// <summary>
/// The name of the Storage Account Management Policy. It should always be 'default'
/// </summary>
[Input("managementPolicyName")]
public Input<string>? ManagementPolicyName { get; set; }
/// <summary>
/// The Storage Account ManagementPolicy, in JSON format. See more details in: https://docs.microsoft.com/en-us/azure/storage/common/storage-lifecycle-managment-concepts.
/// </summary>
[Input("policy", required: true)]
public Input<Inputs.ManagementPolicySchemaArgs> Policy { get; set; } = null!;
/// <summary>
/// The name of the resource group within the user's subscription. The name is case insensitive.
/// </summary>
[Input("resourceGroupName", required: true)]
public Input<string> ResourceGroupName { get; set; } = null!;
public ManagementPolicyArgs()
{
}
}
}
| 49.738806 | 193 | 0.630908 | [
"Apache-2.0"
] | pulumi-bot/pulumi-azure-native | sdk/dotnet/Storage/V20190601/ManagementPolicy.cs | 6,665 | C# |
using System;
using System.Collections.Generic;
using System.Text;
namespace MQTTnet.TestApp
{
public class TopicGenerator
{
public void Generate(
int numPublishers, int numTopicsPerPublisher,
out Dictionary<string, List<string>> topicsByPublisher,
out Dictionary<string, List<string>> singleWildcardTopicsByPublisher,
out Dictionary<string, List<string>> multiWildcardTopicsByPublisher
)
{
topicsByPublisher = new Dictionary<string, List<string>>();
singleWildcardTopicsByPublisher = new Dictionary<string, List<string>>();
multiWildcardTopicsByPublisher = new Dictionary<string, List<string>>();
// Find some reasonable distribution across three topic levels
var topicsPerLevel = (int)Math.Pow(numTopicsPerPublisher, (1.0 / 3.0));
int numLevel1Topics = topicsPerLevel;
if (numLevel1Topics <= 0)
{
numLevel1Topics = 1;
}
int numLevel2Topics = topicsPerLevel;
if (numLevel2Topics <= 0)
{
numLevel2Topics = 1;
}
var maxNumLevel3Topics = 1 + (int)((double)numTopicsPerPublisher / numLevel1Topics / numLevel2Topics);
if (maxNumLevel3Topics <= 0)
{
maxNumLevel3Topics = 1;
}
for (var p = 0; p < numPublishers; ++p)
{
int publisherTopicCount = 0;
var publisherName = "pub" + p;
for (var l1 = 0; l1 < numLevel1Topics; ++l1)
{
for (var l2 = 0; l2 < numLevel2Topics; ++l2)
{
for (var l3 = 0; l3 < maxNumLevel3Topics; ++l3)
{
if (publisherTopicCount >= numTopicsPerPublisher)
break;
var topic = string.Format("{0}/building{1}/level{2}/sensor{3}", publisherName, l1 + 1, l2 + 1, l3 + 1);
AddPublisherTopic(publisherName, topic, topicsByPublisher);
if (l2 == 0)
{
var singleWildcardTopic = string.Format("{0}/building{1}/+/sensor{2}", publisherName, l1 + 1, l3 + 1);
AddPublisherTopic(publisherName, singleWildcardTopic, singleWildcardTopicsByPublisher);
if (l1 == 0)
{
var multiWildcardTopic = string.Format("{0}/+/level{1}/+", publisherName, l3 + 1);
AddPublisherTopic(publisherName, multiWildcardTopic, multiWildcardTopicsByPublisher);
}
}
++publisherTopicCount;
}
}
}
}
}
void AddPublisherTopic(string publisherName, string topic, Dictionary<string, List<string>> topicsByPublisher)
{
List<string> topicList;
if (!topicsByPublisher.TryGetValue(publisherName, out topicList))
{
topicList = new List<string>();
topicsByPublisher.Add(publisherName, topicList);
}
topicList.Add(topic);
}
}
}
| 40.658824 | 134 | 0.5 | [
"MIT"
] | 76541727/MQTTnet | Source/MQTTnet.TestApp/TopicGenerator.cs | 3,456 | C# |
using System;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Net.Security;
using System.Net.Sockets;
using System.Security.Authentication;
using System.Security.Cryptography.X509Certificates;
using System.Threading;
using System.Threading.Tasks;
using QuickDeploy.Common;
namespace QuickDeploy.Server
{
public class QuickDeployTcpSslServer
{
private readonly StreamHelper streamHelper = new StreamHelper();
private readonly int port;
private string serverCertificateFilename;
private string serverCertificatePassword;
private X509Certificate2 serverCertificate;
private string expectedClientCertificateFilename;
private X509Certificate2 expectedClientCertificate;
private bool isRunning;
private TcpListener tcpListener;
public QuickDeployTcpSslServer(
int port,
string serverCertificateFilename,
string serverCertificatePassword,
string expectedClientCertificateFilename)
{
this.port = port;
this.serverCertificateFilename = serverCertificateFilename;
this.serverCertificatePassword = serverCertificatePassword;
this.expectedClientCertificateFilename = expectedClientCertificateFilename;
}
public SslProtocols EnabledSslProtocols { get; set; } = SslProtocols.Tls12;
public void Start()
{
try
{
if (this.isRunning)
{
throw new InvalidOperationException("Server is already running.");
}
if (!File.Exists(this.serverCertificateFilename))
{
this.serverCertificateFilename = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, this.serverCertificateFilename);
}
if (!File.Exists(this.serverCertificateFilename))
{
throw new InvalidOperationException($"Server certificate file '{this.serverCertificateFilename}' not found.");
}
if (!File.Exists(this.expectedClientCertificateFilename))
{
this.expectedClientCertificateFilename = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, this.expectedClientCertificateFilename);
}
if (!File.Exists(this.expectedClientCertificateFilename))
{
throw new InvalidOperationException($"Expected client certificate file '{this.expectedClientCertificateFilename}' not found.");
}
this.serverCertificate = new X509Certificate2(this.serverCertificateFilename, this.serverCertificatePassword, X509KeyStorageFlags.Exportable);
this.expectedClientCertificate = new X509Certificate2(this.expectedClientCertificateFilename);
this.tcpListener = new TcpListener(IPAddress.Any, this.port);
this.tcpListener.Start();
this.isRunning = true;
Task.Run(() =>
{
while (this.isRunning)
{
var newClient = this.tcpListener.AcceptTcpClient();
if (newClient == null)
{
continue;
}
ThreadPool.QueueUserWorkItem(state =>
{
var client = (TcpClient)state;
this.HandleClient(client);
}, newClient);
}
});
}
catch (Exception ex)
{
Trace.TraceError(ex.ToString());
throw;
}
}
public void Stop()
{
try
{
this.isRunning = false;
this.tcpListener.Stop();
}
catch (Exception ex)
{
Trace.TraceError(ex.ToString());
}
}
private void HandleClient(TcpClient client)
{
try
{
using (client)
using (var sslStream = new SslStream(client.GetStream(), false, this.VerifyClientCertificate))
{
try
{
sslStream.AuthenticateAsServer(this.serverCertificate, true, this.EnabledSslProtocols, true);
var lockObject = new object();
var hasResponseAlreadyBeenSent = false;
var request = this.streamHelper.Receive(sslStream);
var statusMessageSender = new StatusMessageSender(m =>
{
lock (lockObject)
{
if (!hasResponseAlreadyBeenSent)
{
this.streamHelper.Send(sslStream, m);
}
}
});
var controller = new Controller(statusMessageSender);
var response = controller.Handle(request);
lock (lockObject)
{
this.streamHelper.Send(sslStream, response);
hasResponseAlreadyBeenSent = true;
}
}
catch (AuthenticationException ex)
{
Trace.TraceWarning("SSL error: " + ex);
}
catch (Exception ex)
{
Trace.TraceError("Error during request: " + ex);
}
}
}
catch (Exception ex)
{
Trace.TraceError(ex.ToString());
throw;
}
}
private bool VerifyClientCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
{
var other = certificate as X509Certificate2;
return this.expectedClientCertificate.SerialNumber == other?.SerialNumber
&& this.expectedClientCertificate.Thumbprint == other?.Thumbprint;
}
}
}
| 34.844086 | 158 | 0.516741 | [
"MIT"
] | mbiandiek/QuickDeploy | QuickDeploy.Server/QuickDeployTcpSslServer.cs | 6,483 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using Foundation;
using UIKit;
namespace BrowseStorageXamarinForm.iOS
{
// The UIApplicationDelegate for the application. This class is responsible for launching the
// User Interface of the application, as well as listening (and optionally responding) to
// application events from iOS.
[Register("AppDelegate")]
public partial class AppDelegate : global::Xamarin.Forms.Platform.iOS.FormsApplicationDelegate
{
//
// This method is invoked when the application has loaded and is ready to run. In this
// method you should instantiate the window, load the UI into it and then make the window
// visible.
//
// You have 17 seconds to return from this method, or iOS will terminate your application.
//
public override bool FinishedLaunching(UIApplication app, NSDictionary options)
{
global::Xamarin.Forms.Forms.Init();
LoadApplication(new App());
return base.FinishedLaunching(app, options);
}
}
}
| 34.84375 | 98 | 0.681614 | [
"MIT"
] | SiasbRadvarZanganeh/Xamarin-Samples | BrowseStorageXamarinForm/BrowseStorageXamarinForm.iOS/AppDelegate.cs | 1,117 | C# |
// CoinsData
#define UNITY_ASSERTIONS
using ClubPenguin;
using Disney.Kelowna.Common.DataModel;
using System;
using UnityEngine;
[Serializable]
public class CoinsData : ScopedData
{
[SerializeField]
private int coins = 0;
public int Coins
{
get
{
return coins;
}
internal set
{
sendCoinEvents(value);
coins = value;
}
}
protected override string scopeID => CPDataScopes.Session.ToString();
protected override Type monoBehaviourType => typeof(CoinsDataMonoBehaviour);
public event Action<int, bool> OnCoinsAdded;
public event Action<int> OnCoinsRemoved;
public event Action<int> OnCoinsChanged;
public event Action<int> OnCoinsSet;
protected override void notifyWillBeDestroyed()
{
this.OnCoinsAdded = null;
this.OnCoinsRemoved = null;
this.OnCoinsChanged = null;
}
public void SetInitialCoins(int coins)
{
this.coins = coins;
if (this.OnCoinsChanged != null)
{
this.OnCoinsChanged(coins);
}
if (this.OnCoinsSet != null)
{
this.OnCoinsSet(coins);
}
}
public void AddCoins(int coins, bool isCollectible = false, bool show = true)
{
Debug.Assert(coins >= 0);
this.coins += coins;
if (show && this.OnCoinsAdded != null)
{
this.OnCoinsAdded(coins, isCollectible);
}
}
public void RemoveCoins(int coins)
{
Debug.Assert(coins >= 0);
Coins = this.coins - coins;
}
private void sendCoinEvents(int newCount)
{
if (newCount > coins && this.OnCoinsAdded != null)
{
this.OnCoinsAdded(newCount - coins, arg2: false);
}
if (newCount < coins && this.OnCoinsRemoved != null)
{
this.OnCoinsRemoved(coins - newCount);
}
if (newCount != coins && this.OnCoinsChanged != null)
{
this.OnCoinsChanged(newCount);
}
}
}
| 18.945055 | 78 | 0.695476 | [
"MIT"
] | smdx24/CPI-Source-Code | ClubPenguin/CoinsData.cs | 1,724 | C# |
using System.Linq;
using Xunit;
namespace Cake.Tools.ReadyAPI.TestEngine.Tests
{
public partial class TestEngineRunnerTests
{
[Fact]
public void GetArguments_SecurityTestProvidedHasArgument()
{
var settings = new TestEngineSettings
{
SecurityTest = "SecurityTest1"
};
var args = TestEngineRunner.GetArguments(string.Empty, settings);
Assert.Equal(1, args.Count(argument => argument.Render() == "securitytest=SecurityTest1"));
}
[Fact]
public void GetArguments_EmptySecurityTestNoArgument()
{
var settings = new TestEngineSettings
{
SecurityTest = string.Empty
};
var args = TestEngineRunner.GetArguments(string.Empty, settings);
Assert.Equal(0, args.Count(argument => argument.Render().StartsWith("securitytest")));
}
[Fact]
public void GetArguments_NullSecurityTestNoArgument()
{
var settings = new TestEngineSettings
{
SecurityTest = null
};
var args = TestEngineRunner.GetArguments(string.Empty, settings);
Assert.Equal(0, args.Count(argument => argument.Render().StartsWith("securitytest")));
}
}
}
| 29.0625 | 104 | 0.566308 | [
"MIT"
] | waxtell/Cake.Tools.ReadyAPI.TestEngine | Cake.Tools.ReadyAPI.TestEngine.Tests/TestEngineRunnerTests_SecurityTest.cs | 1,395 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SharperArchitecture.Common.Exceptions
{
public class SharperArchitectureException : Exception
{
public SharperArchitectureException(string message) : base(message)
{
}
public SharperArchitectureException(string message, params object[] args) : base(string.Format(message, args))
{
}
public SharperArchitectureException(string message, Exception innerException)
: base(message, innerException)
{
}
}
}
| 23.740741 | 118 | 0.670827 | [
"MIT"
] | maca88/PowerArhitecture | Source/SharperArchitecture.Common/Exceptions/SharperArchitectureException.cs | 643 | C# |
using Gtk;
using Ryujinx.HLE.FileSystem;
using Ryujinx.HLE.HOS.Services.Account.Acc;
using Ryujinx.Ui.Common.Configuration;
using Ryujinx.Ui.Widgets;
using SixLabors.ImageSharp;
using SixLabors.ImageSharp.Processing;
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using Image = SixLabors.ImageSharp.Image;
using UserId = Ryujinx.HLE.HOS.Services.Account.Acc.UserId;
namespace Ryujinx.Ui.Windows
{
public partial class UserProfilesManagerWindow : Window
{
private const uint MaxProfileNameLength = 0x20;
private readonly AccountManager _accountManager;
private readonly ContentManager _contentManager;
private byte[] _bufferImageProfile;
private string _tempNewProfileName;
private Gdk.RGBA _selectedColor;
private ManualResetEvent _avatarsPreloadingEvent = new ManualResetEvent(false);
public UserProfilesManagerWindow(AccountManager accountManager, ContentManager contentManager, VirtualFileSystem virtualFileSystem) : base($"Ryujinx {Program.Version} - Manage User Profiles")
{
Icon = new Gdk.Pixbuf(Assembly.GetAssembly(typeof(ConfigurationState)), "Ryujinx.Ui.Common.Resources.Logo_Ryujinx.png");
InitializeComponent();
_selectedColor.Red = 0.212;
_selectedColor.Green = 0.843;
_selectedColor.Blue = 0.718;
_selectedColor.Alpha = 1;
_accountManager = accountManager;
_contentManager = contentManager;
CellRendererToggle userSelectedToggle = new CellRendererToggle();
userSelectedToggle.Toggled += UserSelectedToggle_Toggled;
// NOTE: Uncomment following line when multiple selection of user profiles is supported.
//_usersTreeView.AppendColumn("Selected", userSelectedToggle, "active", 0);
_usersTreeView.AppendColumn("User Icon", new CellRendererPixbuf(), "pixbuf", 1);
_usersTreeView.AppendColumn("User Info", new CellRendererText(), "text", 2, "background-rgba", 3);
_tableStore.SetSortColumnId(0, SortType.Descending);
RefreshList();
if (_contentManager.GetCurrentFirmwareVersion() != null)
{
Task.Run(() =>
{
AvatarWindow.PreloadAvatars(contentManager, virtualFileSystem);
_avatarsPreloadingEvent.Set();
});
}
}
public void RefreshList()
{
_tableStore.Clear();
foreach (UserProfile userProfile in _accountManager.GetAllUsers())
{
_tableStore.AppendValues(userProfile.AccountState == AccountState.Open, new Gdk.Pixbuf(userProfile.Image, 96, 96), $"{userProfile.Name}\n{userProfile.UserId}", Gdk.RGBA.Zero);
if (userProfile.AccountState == AccountState.Open)
{
_selectedUserImage.Pixbuf = new Gdk.Pixbuf(userProfile.Image, 96, 96);
_selectedUserIdLabel.Text = userProfile.UserId.ToString();
_selectedUserNameEntry.Text = userProfile.Name;
_deleteButton.Sensitive = userProfile.UserId != AccountManager.DefaultUserId;
_usersTreeView.Model.GetIterFirst(out TreeIter firstIter);
_tableStore.SetValue(firstIter, 3, _selectedColor);
}
}
}
//
// Events
//
private void UsersTreeView_Activated(object o, RowActivatedArgs args)
{
SelectUserTreeView();
}
private void UserSelectedToggle_Toggled(object o, ToggledArgs args)
{
SelectUserTreeView();
}
private void SelectUserTreeView()
{
// Get selected item informations.
_usersTreeView.Selection.GetSelected(out TreeIter selectedIter);
Gdk.Pixbuf userPicture = (Gdk.Pixbuf)_tableStore.GetValue(selectedIter, 1);
string userName = _tableStore.GetValue(selectedIter, 2).ToString().Split("\n")[0];
string userId = _tableStore.GetValue(selectedIter, 2).ToString().Split("\n")[1];
// Unselect the first user.
_usersTreeView.Model.GetIterFirst(out TreeIter firstIter);
_tableStore.SetValue(firstIter, 0, false);
_tableStore.SetValue(firstIter, 3, Gdk.RGBA.Zero);
// Set new informations.
_tableStore.SetValue(selectedIter, 0, true);
_selectedUserImage.Pixbuf = userPicture;
_selectedUserNameEntry.Text = userName;
_selectedUserIdLabel.Text = userId;
_saveProfileNameButton.Sensitive = false;
// Open the selected one.
_accountManager.OpenUser(new UserId(userId));
_deleteButton.Sensitive = userId != AccountManager.DefaultUserId.ToString();
_tableStore.SetValue(selectedIter, 3, _selectedColor);
}
private void SelectedUserNameEntry_KeyReleaseEvent(object o, KeyReleaseEventArgs args)
{
if (_saveProfileNameButton.Sensitive == false)
{
_saveProfileNameButton.Sensitive = true;
}
}
private void AddButton_Pressed(object sender, EventArgs e)
{
_tempNewProfileName = GtkDialog.CreateInputDialog(this, "Choose the Profile Name", "Please Enter a Profile Name", MaxProfileNameLength);
if (_tempNewProfileName != "")
{
SelectProfileImage(true);
if (_bufferImageProfile != null)
{
AddUser();
}
}
}
private void DeleteButton_Pressed(object sender, EventArgs e)
{
if (GtkDialog.CreateChoiceDialog("Delete User Profile", "Are you sure you want to delete the profile ?", "Deleting this profile will also delete all associated save data."))
{
_accountManager.DeleteUser(GetSelectedUserId());
RefreshList();
}
}
private void EditProfileNameButton_Pressed(object sender, EventArgs e)
{
_saveProfileNameButton.Sensitive = false;
_accountManager.SetUserName(GetSelectedUserId(), _selectedUserNameEntry.Text);
RefreshList();
}
private void ProcessProfileImage(byte[] buffer)
{
using (Image image = Image.Load(buffer))
{
image.Mutate(x => x.Resize(256, 256));
using (MemoryStream streamJpg = new MemoryStream())
{
image.SaveAsJpeg(streamJpg);
_bufferImageProfile = streamJpg.ToArray();
}
}
}
private void ProfileImageFileChooser()
{
FileChooserNative fileChooser = new FileChooserNative("Import Custom Profile Image", this, FileChooserAction.Open, "Import", "Cancel")
{
SelectMultiple = false
};
FileFilter filter = new FileFilter()
{
Name = "Custom Profile Images"
};
filter.AddPattern("*.jpg");
filter.AddPattern("*.jpeg");
filter.AddPattern("*.png");
filter.AddPattern("*.bmp");
fileChooser.AddFilter(filter);
if (fileChooser.Run() == (int)ResponseType.Accept)
{
ProcessProfileImage(File.ReadAllBytes(fileChooser.Filename));
}
fileChooser.Dispose();
}
private void SelectProfileImage(bool newUser = false)
{
if (_contentManager.GetCurrentFirmwareVersion() == null)
{
ProfileImageFileChooser();
}
else
{
Dictionary<int, string> buttons = new Dictionary<int, string>()
{
{ 0, "Import Image File" },
{ 1, "Select Firmware Avatar" }
};
ResponseType responseDialog = GtkDialog.CreateCustomDialog("Profile Image Selection",
"Choose a Profile Image",
"You may import a custom profile image, or select an avatar from the system firmware.",
buttons, MessageType.Question);
if (responseDialog == 0)
{
ProfileImageFileChooser();
}
else if (responseDialog == (ResponseType)1)
{
AvatarWindow avatarWindow = new AvatarWindow()
{
NewUser = newUser
};
avatarWindow.DeleteEvent += AvatarWindow_DeleteEvent;
avatarWindow.SetSizeRequest((int)(avatarWindow.DefaultWidth * Program.WindowScaleFactor), (int)(avatarWindow.DefaultHeight * Program.WindowScaleFactor));
avatarWindow.Show();
}
}
}
private void ChangeProfileImageButton_Pressed(object sender, EventArgs e)
{
if (_contentManager.GetCurrentFirmwareVersion() != null)
{
_avatarsPreloadingEvent.WaitOne();
}
SelectProfileImage();
if (_bufferImageProfile != null)
{
SetUserImage();
}
}
private void AvatarWindow_DeleteEvent(object sender, DeleteEventArgs args)
{
_bufferImageProfile = ((AvatarWindow)sender).SelectedProfileImage;
if (_bufferImageProfile != null)
{
if (((AvatarWindow)sender).NewUser)
{
AddUser();
}
else
{
SetUserImage();
}
}
}
private void AddUser()
{
_accountManager.AddUser(_tempNewProfileName, _bufferImageProfile);
_bufferImageProfile = null;
_tempNewProfileName = "";
RefreshList();
}
private void SetUserImage()
{
_accountManager.SetUserImage(GetSelectedUserId(), _bufferImageProfile);
_bufferImageProfile = null;
RefreshList();
}
private UserId GetSelectedUserId()
{
if (_usersTreeView.Model.GetIterFirst(out TreeIter iter))
{
do
{
if ((bool)_tableStore.GetValue(iter, 0))
{
break;
}
}
while (_usersTreeView.Model.IterNext(ref iter));
}
return new UserId(_tableStore.GetValue(iter, 2).ToString().Split("\n")[1]);
}
private void CloseButton_Pressed(object sender, EventArgs e)
{
Close();
}
}
} | 34.384848 | 199 | 0.556535 | [
"MIT"
] | vdavalon01/Ryujinx | Ryujinx/Ui/Windows/UserProfilesManagerWindow.cs | 11,349 | C# |
#nullable disable
namespace NadekoBot.Modules.Utility.Common.Exceptions;
public class StreamRoleNotFoundException : Exception
{
public StreamRoleNotFoundException()
: base("Stream role wasn't found.")
{
}
public StreamRoleNotFoundException(string message)
: base(message)
{
}
public StreamRoleNotFoundException(string message, Exception innerException)
: base(message, innerException)
{
}
} | 22.65 | 80 | 0.701987 | [
"MIT"
] | StefanPuia/nadeko | src/NadekoBot/Modules/Utility/_Common/Exceptions/StreamRoleNotFoundException.cs | 453 | C# |
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
namespace Microsoft.VisualStudio.UserNotifications.Interop
{
[ComImport, TypeIdentifier, InterfaceType(ComInterfaceType.InterfaceIsIUnknown), Guid("791A7AEF-BFFD-45E8-B164-FC8CDD423D69"), CompilerGenerated]
public interface IVsUserNotification
{
Guid Provider { get; }
string Identifier { [return: MarshalAs(UnmanagedType.BStr)] get; }
string Title { [return: MarshalAs(UnmanagedType.BStr)] get; [param: In, MarshalAs(UnmanagedType.BStr)] set; }
string Description { [return: MarshalAs(UnmanagedType.BStr)] get; [param: In, MarshalAs(UnmanagedType.BStr)] set; }
uint Severity { get; }
object Context { [return: MarshalAs(UnmanagedType.Struct)] get; [param: In, MarshalAs(UnmanagedType.Struct)] set; }
DateTime Creation { get; }
DateTime Expiration { get; }
uint State { get; }
}
} | 49 | 150 | 0.694898 | [
"MIT"
] | kevfromireland/visual-studio-2013-notifications-example | UserNotificationDemo/Interop/IVsUserNotification.cs | 982 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerCollision : MonoBehaviour {
private Rigidbody rb;
private PlayerController player;
// Use this for initialization
void Start () {
rb = GetComponent<Rigidbody>();
player = GetComponent<PlayerController>();
}
// Update is called once per frame
void Update () {
}
private void OnTriggerEnter(Collider other)
{
if (other.CompareTag("Skill"))
{
Debug.Log("Player got hit by Skill!");
player.health -= other.gameObject.GetComponent<Fireball>().damage;
}
}
}
| 21 | 78 | 0.643625 | [
"MIT"
] | Cheeryo/MageSmashBros | Mage Smash Bros/Assets/Scripts/Player/PlayerCollision.cs | 653 | C# |
using Microsoft.Extensions.Configuration;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Lti.Web.Services
{
public class ConfigService
{
private readonly IConfiguration config;
public ConfigService(IConfiguration config)
{
this.config = config;
}
public string PlatformId => this.config.GetValue<string>("auth:openid:platformid");
public string ClientId => this.config.GetValue<string>("auth:openid:clientid");
public string Audience => this.config.GetValue<string>("auth:openid:audience");
public string Authority => this.config.GetValue<string>("auth:openid:authority");
public string PlatformKey => this.config.GetValue<string>("auth:openid:platformkey");
public string ToolPrivateKey => this.config.GetValue<string>("auth:openid:toolprivatekey");
public string PlatformTokenEndpoint => this.config.GetValue<string>("auth:openid:platformtokenendpoint");
}
}
| 38.407407 | 113 | 0.711668 | [
"MIT"
] | toddlindsey/lti-playground | LtiPlayground/Lti.Web/Services/ConfigService.cs | 1,039 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
namespace bm_rest_webapi
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc()
.SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseMvc();
}
}
}
| 29.763158 | 106 | 0.70557 | [
"Apache-2.0"
] | colinsteffen/ba-xamarin-android | bm_rest_webapi/bm_rest_webapi/Startup.cs | 1,133 | C# |
using System;
using System.Collections.Generic;
using System.Text;
using System.Web;
using System.Web.UI;
using Geomethod;
namespace Geomethod.Web
{
/* public class WebLogInformer : ILogInformer
{
public WebLogInformer()
{
}
#region ILogInformer Members
public void Show(Exception ex, object obj)
{
this.Show(LogType.Exception, ex.GetType().Name, ex.ToString(), obj);
}
public void Show(LogType logType, string subType, string msg, object obj)
{
HttpResponse response = null;
if (obj is Control) response = (obj as Control).Page.Response;
else if (obj is HttpApplication) response = (obj as HttpApplication).Response;
if (response != null)
{
response.Write(msg);
response.End();
}
}
#endregion
#region ILogInformer Members
public void Show(LogRecord lr)
{
lr.
}
#endregion
}*/
}
| 19.042553 | 81 | 0.656983 | [
"MIT"
] | AlexAbramov/geomethod | Geomethod.Web/WebLogInformer.cs | 895 | C# |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace System.Text.Http.SingleSegment
{
public struct HttpHeaderBuffer
{
//TODO: Issue #390: Switch HttpHeaderBuffer to use Slices.Span.
private Span<byte> _bytes;
private readonly TextEncoder _encoder;
public HttpHeaderBuffer(Span<byte> bytes, TextEncoder encoder)
{
_bytes = bytes;
_encoder = encoder;
}
public void UpdateValue(string newValue)
{
if (newValue.Length > _bytes.Length)
{
throw new ArgumentException("newValue");
}
int bytesWritten;
_encoder.TryEncode(newValue, _bytes, out bytesWritten);
_bytes.SetFromRestOfSpanToEmpty(newValue.Length);
}
}
public static class SpanExtensions
{
private const byte EmptyCharacter = 32;
public static void SetFromRestOfSpanToEmpty(this Span<byte> span, int startingFrom)
{
for (var i = startingFrom; i < span.Length; i++)
{
span[i] = EmptyCharacter;
}
}
internal static ReadOnlySpan<byte> SliceTo(this ReadOnlySpan<byte> buffer, char terminator, out int consumedBytes)
{
return buffer.SliceTo((byte)terminator, out consumedBytes);
}
internal static ReadOnlySpan<byte> SliceTo(this ReadOnlySpan<byte> buffer, int start, char terminator, out int consumedBytes)
{
return buffer.SliceTo(start, (byte)terminator, out consumedBytes);
}
internal static ReadOnlySpan<byte> SliceTo(this ReadOnlySpan<byte> buffer, byte terminator, out int consumedBytes)
{
return buffer.SliceTo(0, terminator, out consumedBytes);
}
internal static ReadOnlySpan<byte> SliceTo(this ReadOnlySpan<byte> buffer, int start, byte terminator, out int consumedBytes)
{
var slice = buffer.Slice(start);
var index = System.SpanExtensions.IndexOf(slice, terminator);
if (index == -1) {
consumedBytes = 0;
return Span<byte>.Empty;
}
consumedBytes = index;
return slice.Slice(0, index);
}
internal static ReadOnlySpan<byte> SliceTo(this ReadOnlySpan<byte> buffer, char terminatorFirst, char terminatorSecond, out int consumedBytes)
{
return buffer.SliceTo((byte)terminatorFirst, (byte)terminatorSecond, out consumedBytes);
}
internal static ReadOnlySpan<byte> SliceTo(this ReadOnlySpan<byte> buffer, int start, char terminatorFirst, char terminatorSecond, out int consumedBytes)
{
return buffer.SliceTo(start, (byte)terminatorFirst, (byte)terminatorSecond, out consumedBytes);
}
internal static ReadOnlySpan<byte> SliceTo(this ReadOnlySpan<byte> buffer, byte terminatorFirst, byte terminatorSecond, out int consumedBytes)
{
return buffer.SliceTo(0, terminatorFirst, terminatorSecond, out consumedBytes);
}
internal static ReadOnlySpan<byte> SliceTo(this ReadOnlySpan<byte> buffer, int start, byte terminatorFirst, byte terminatorSecond, out int consumedBytes)
{
int offset = 0;
while (true)
{
var slice = buffer.Slice(start + offset);
var index = System.SpanExtensions.IndexOf(slice, terminatorFirst);
if (index == -1 || index == slice.Length - 1)
{
consumedBytes = 0;
return Span<byte>.Empty;
}
if (slice[index + 1] == terminatorSecond)
{
consumedBytes = index;
return slice.Slice(0, index + offset);
}
else
{
offset += index;
}
}
}
}
}
| 37.135135 | 161 | 0.588307 | [
"MIT"
] | crummel/dotnet_corefxlab | src/System.Text.Http/System/Text/Http/Obsolete/HttpHeaderBuffer.cs | 4,124 | C# |
using UnityEngine;
public class TapToPlaceParent : MonoBehaviour {
bool placing = false;
void OnSelect()
{
placing = !placing;
if (placing)
{
SpatialMapping.Instance.DrawVisualMeshes = true;
}
else
{
SpatialMapping.Instance.DrawVisualMeshes = false;
}
}
// Update is called once per frame
void Update () {
if (placing)
{
var headPosition = Camera.main.transform.position;
var gazeDirection = Camera.main.transform.forward;
RaycastHit hitInfo;
if (Physics.Raycast(headPosition, gazeDirection, out hitInfo, 30.0f, SpatialMapping.PhysicsRaycastMask))
{
this.transform.parent.position = hitInfo.point;
Quaternion toQuat = Camera.main.transform.localRotation;
toQuat.x = 0;
toQuat.z = 0;
this.transform.parent.rotation = toQuat;
}
}
}
}
| 23.204545 | 116 | 0.553379 | [
"MIT"
] | YoungxHelsinki/Aalto-hololens | code/HolographicAcademy-Holograms-101/Origami/Assets/Scripts/TapToPlaceParent.cs | 1,023 | C# |
#region Copyright
//
<<<<<<< HEAD
<<<<<<< HEAD
=======
=======
>>>>>>> update form orginal repo
// DotNetNuke® - https://www.dnnsoftware.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
<<<<<<< HEAD
>>>>>>> Merges latest changes from release/9.4.x into development (#3178)
=======
>>>>>>> update form orginal repo
using System.Net.Http;
using System.Threading;
using DotNetNuke.HttpModules.Membership;
namespace DotNetNuke.Web.Api.Internal.Auth
{
public class WebFormsAuthMessageHandler : MessageProcessingHandler
{
public string AuthScheme => "Forms";
protected override HttpRequestMessage ProcessRequest(HttpRequestMessage request, CancellationToken cancellationToken)
{
MembershipModule.AuthenticateRequest(request.GetHttpContext(), allowUnknownExtensions: true);
return request;
}
protected override HttpResponseMessage ProcessResponse(HttpResponseMessage response, CancellationToken cancellationToken)
{
return response;
}
}
} | 40.320755 | 129 | 0.728591 | [
"MIT"
] | DnnSoftwarePersian/Dnn.Platform | DNN Platform/DotNetNuke.Web/Api/Internal/Auth/WebFormsAuthMessageHandler.cs | 2,138 | C# |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Threading.Tasks;
using Amazon.CloudFormation;
using Amazon.CloudFormation.Model;
using Amazon.Runtime;
using Calamari.Aws.Exceptions;
using Calamari.Aws.Integration;
using Calamari.Aws.Integration.CloudFormation;
using Calamari.Aws.Integration.CloudFormation.Templates;
using Calamari.Aws.Util;
using Calamari.CloudAccounts;
using Calamari.Common.Commands;
using Calamari.Common.Plumbing;
using Calamari.Common.Plumbing.Logging;
using Calamari.Deployment;
using Calamari.Util;
using Octopus.CoreUtilities;
using Octopus.CoreUtilities.Extensions;
namespace Calamari.Aws.Deployment.Conventions
{
/// <summary>
/// Describes the state of the stack
/// </summary>
public enum StackStatus
{
DoesNotExist,
Completed,
InProgress
}
public class DeployAwsCloudFormationConvention : CloudFormationInstallationConventionBase
{
readonly Func<IAmazonCloudFormation> clientFactory;
readonly Func<ICloudFormationRequestBuilder> templateFactory;
readonly Func<RunningDeployment, StackArn> stackProvider;
readonly Func<RunningDeployment, string> roleArnProvider;
readonly bool waitForComplete;
readonly string stackName;
readonly AwsEnvironmentGeneration awsEnvironmentGeneration;
public DeployAwsCloudFormationConvention(
Func<IAmazonCloudFormation> clientFactory,
Func<ICloudFormationRequestBuilder> templateFactory,
StackEventLogger logger,
Func<RunningDeployment, StackArn> stackProvider,
Func<RunningDeployment, string> roleArnProvider,
bool waitForComplete,
string stackName,
AwsEnvironmentGeneration awsEnvironmentGeneration) : base(logger)
{
this.clientFactory = clientFactory;
this.templateFactory = templateFactory;
this.stackProvider = stackProvider;
this.roleArnProvider = roleArnProvider;
this.waitForComplete = waitForComplete;
this.stackName = stackName;
this.awsEnvironmentGeneration = awsEnvironmentGeneration;
}
public override void Install(RunningDeployment deployment)
{
InstallAsync(deployment).GetAwaiter().GetResult();
}
private async Task InstallAsync(RunningDeployment deployment)
{
Guard.NotNull(deployment, "deployment can not be null");
var stack = stackProvider(deployment);
Guard.NotNull(stack, "Stack can not be null");
var template = templateFactory();
Guard.NotNull(template, "CloudFormation template can not be null.");
await DeployCloudFormation(deployment, stack, template);
}
private async Task DeployCloudFormation(RunningDeployment deployment, StackArn stack, ICloudFormationRequestBuilder template)
{
Guard.NotNull(deployment, "deployment can not be null");
var deploymentStartTime = DateTime.Now;
await clientFactory.WaitForStackToComplete(CloudFormationDefaults.StatusWaitPeriod, stack, LogAndThrowRollbacks(clientFactory, stack, false, filter: FilterStackEventsSince(deploymentStartTime)));
await DeployStack(deployment, stack, template, deploymentStartTime);
}
/// <summary>
/// Update or create the stack
/// </summary>
/// <param name="deployment">The current deployment</param>
/// <param name="stack"></param>
/// <param name="template"></param>
private async Task DeployStack(RunningDeployment deployment, StackArn stack, ICloudFormationRequestBuilder template, DateTime deploymentStartTime)
{
Guard.NotNull(deployment, "deployment can not be null");
var stackId = await template.Inputs
// Use the parameters to either create or update the stack
.Map(async parameters => await StackExists(stack, StackStatus.DoesNotExist) != StackStatus.DoesNotExist
? await UpdateCloudFormation(deployment, stack, template)
: await CreateCloudFormation(deployment, template));
if (waitForComplete)
{
await clientFactory.WaitForStackToComplete(CloudFormationDefaults.StatusWaitPeriod, stack, LogAndThrowRollbacks(clientFactory, stack, filter: FilterStackEventsSince(deploymentStartTime)));
}
// Take the stack ID returned by the create or update events, and save it as an output variable
Log.SetOutputVariable("AwsOutputs[StackId]", stackId ?? "", deployment.Variables);
Log.Info(
$"Saving variable \"Octopus.Action[{deployment.Variables["Octopus.Action.Name"]}].Output.AwsOutputs[StackId]\"");
}
/// <summary>
/// Gets the last stack event by timestamp, optionally filtered by a predicate
/// </summary>
/// <param name="predicate">The optional predicate used to filter events</param>
/// <returns>The stack event</returns>
private Task<Maybe<StackEvent>> StackEvent(StackArn stack, Func<StackEvent, bool> predicate = null)
{
return WithAmazonServiceExceptionHandling(
async () => await clientFactory.GetLastStackEvent(stack, predicate));
}
/// <summary>
/// Check to see if the stack name exists.
/// </summary>
/// <param name="defaultValue">The return value when the user does not have the permissions to query the stacks</param>
/// <returns>The current status of the stack</returns>
async Task<StackStatus> StackExists(StackArn stack, StackStatus defaultValue)
{
return await WithAmazonServiceExceptionHandling(async () => await clientFactory.StackExistsAsync(stack, defaultValue));
}
/// <summary>
/// Creates the stack and returns the stack ID
/// </summary>
/// <param name="deployment">The running deployment</param>
/// <returns>The stack id</returns>
private Task<string> CreateCloudFormation(RunningDeployment deployment, ICloudFormationRequestBuilder template)
{
Guard.NotNull(template, "template can not be null");
return WithAmazonServiceExceptionHandling(async () =>
{
var stackId = await clientFactory.CreateStackAsync(template.BuildCreateStackRequest());
Log.Info($"Created stack {stackId} in region {awsEnvironmentGeneration.AwsRegion.SystemName}");
return stackId;
});
}
/// <summary>
/// Deletes the stack
/// </summary>
private Task DeleteCloudFormation(StackArn stack)
{
return WithAmazonServiceExceptionHandling(async () =>
{
await clientFactory.DeleteStackAsync(stack);
Log.Info($"Deleted stack called {stackName} in region {awsEnvironmentGeneration.AwsRegion.SystemName}");
});
}
/// <summary>
/// Updates the stack and returns the stack ID
/// </summary>
/// <param name="stack">The stack name or id</param>
/// <param name="deployment">The current deployment</param>
/// <param name="template">The CloudFormation template</param>
/// <returns>stackId</returns>
private async Task<string> UpdateCloudFormation(
RunningDeployment deployment,
StackArn stack,
ICloudFormationRequestBuilder template)
{
Guard.NotNull(deployment, "deployment can not be null");
var deploymentStartTime = DateTime.Now;
try
{
var result = await ClientHelpers.CreateCloudFormationClient(awsEnvironmentGeneration)
.UpdateStackAsync(template.BuildUpdateStackRequest());
Log.Info(
$"Updated stack with id {result.StackId} in region {awsEnvironmentGeneration.AwsRegion.SystemName}");
return result.StackId;
}
catch (AmazonCloudFormationException ex)
{
// Some stack states indicate that we can delete the stack and start again. Otherwise we have some other
// exception that needs to be dealt with.
if (!(await StackMustBeDeleted(stack)).SelectValueOrDefault(x => x))
{
// Is this an unrecoverable state, or just a stack that has nothing to update?
if (DealWithUpdateException(ex))
{
// There was nothing to update, but we return the id for consistency anyway
var result = await QueryStackAsync(clientFactory, stack);
return result.StackId;
}
}
// If the stack exists, is in a ROLLBACK_COMPLETE state, and was never successfully
// created in the first place, we can end up here. In this case we try to create
// the stack from scratch.
await DeleteCloudFormation(stack);
await clientFactory.WaitForStackToComplete(CloudFormationDefaults.StatusWaitPeriod, stack, LogAndThrowRollbacks(clientFactory, stack, false, filter: FilterStackEventsSince(deploymentStartTime)));
return await CreateCloudFormation(deployment, template);
}
catch (AmazonServiceException ex)
{
LogAmazonServiceException(ex);
throw;
}
}
/// <summary>
/// Not all exceptions are bad. Some just mean there is nothing to do, which is fine.
/// This method will ignore expected exceptions, and rethrow any that are really issues.
/// </summary>
/// <param name="ex">The exception we need to deal with</param>
/// <exception cref="AmazonCloudFormationException">The supplied exception if it really is an error</exception>
private bool DealWithUpdateException(AmazonCloudFormationException ex)
{
Guard.NotNull(ex, "ex can not be null");
// Unfortunately there are no better fields in the exception to use to determine the
// kind of error than the message. We are forced to match message strings.
if (ex.Message.Contains("No updates are to be performed"))
{
Log.Info("No updates are to be performed");
return true;
}
if (ex.ErrorCode == "AccessDenied")
{
throw new PermissionException(
"The AWS account used to perform the operation does not have the required permissions to update the stack.\n" + "Please ensure the current account has permission to perfrom action 'cloudformation:UpdateStack'.\n" + ex.Message);
}
throw new UnknownException("An unrecognised exception was thrown while updating a CloudFormation stack.\n", ex);
}
/// <summary>
/// Check whether the stack must be deleted in order to recover.
/// </summary>
/// <param name="stack">The stack id or name</param>
/// <returns>true if this status indicates that the stack has to be deleted, and false otherwise</returns>
private async Task<Maybe<bool>> StackMustBeDeleted(StackArn stack)
{
try
{
return (await StackEvent(stack)).Select(x => x.StackIsUnrecoverable());
}
catch (PermissionException)
{
// If we can't get the stack status, assume it is not in a state that we can recover from
return Maybe<bool>.None;
}
}
}
} | 46.855019 | 273 | 0.606236 | [
"Apache-2.0"
] | OctopusDeploy/Calamari | source/Calamari.Aws/Deployment/Conventions/DeployAwsCloudFormationConvention.cs | 12,606 | C# |
namespace People_Recognizer
{
partial class Form1
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.Text = "Form1";
}
#endregion
}
}
| 28.5 | 107 | 0.558772 | [
"Apache-2.0"
] | akshays2112/People-Recognizer | People Recognizer/Form1.Designer.cs | 1,142 | C# |
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using Microsoft.AspNet.Identity;
using Microsoft.Owin.Security;
namespace JWPush.Web.Models
{
public class IndexViewModel
{
public bool HasPassword { get; set; }
public IList<UserLoginInfo> Logins { get; set; }
public string PhoneNumber { get; set; }
public bool TwoFactor { get; set; }
public bool BrowserRemembered { get; set; }
}
public class ManageLoginsViewModel
{
public IList<UserLoginInfo> CurrentLogins { get; set; }
public IList<AuthenticationDescription> OtherLogins { get; set; }
}
public class FactorViewModel
{
public string Purpose { get; set; }
}
public class SetPasswordViewModel
{
[Required]
[StringLength(100, ErrorMessage = "{0}은(는) {2}자 이상이어야 합니다.", MinimumLength = 6)]
[DataType(DataType.Password)]
[Display(Name = "새 암호")]
public string NewPassword { get; set; }
[DataType(DataType.Password)]
[Display(Name = "새 암호 확인")]
[Compare("NewPassword", ErrorMessage = "새 암호와 확인 암호가 일치하지 않습니다.")]
public string ConfirmPassword { get; set; }
}
public class ChangePasswordViewModel
{
[Required]
[DataType(DataType.Password)]
[Display(Name = "현재 암호")]
public string OldPassword { get; set; }
[Required]
[StringLength(100, ErrorMessage = "{0}은(는) {2}자 이상이어야 합니다.", MinimumLength = 6)]
[DataType(DataType.Password)]
[Display(Name = "새 암호")]
public string NewPassword { get; set; }
[DataType(DataType.Password)]
[Display(Name = "새 암호 확인")]
[Compare("NewPassword", ErrorMessage = "새 암호와 확인 암호가 일치하지 않습니다.")]
public string ConfirmPassword { get; set; }
}
public class AddPhoneNumberViewModel
{
[Required]
[Phone]
[Display(Name = "전화 번호")]
public string Number { get; set; }
}
public class VerifyPhoneNumberViewModel
{
[Required]
[Display(Name = "코드")]
public string Code { get; set; }
[Required]
[Phone]
[Display(Name = "전화 번호")]
public string PhoneNumber { get; set; }
}
public class ConfigureTwoFactorViewModel
{
public string SelectedProvider { get; set; }
public ICollection<System.Web.Mvc.SelectListItem> Providers { get; set; }
}
} | 28.77907 | 88 | 0.603232 | [
"Unlicense"
] | GuyFawkesFromKorea/JWPushR | JWPush.Web/Models/ManageViewModels.cs | 2,649 | C# |
namespace LINGYUN.Abp.MessageService.Subscriptions
{
public class UserSubscriptionsResult
{
public bool IsSubscribed { get; }
public UserSubscriptionsResult(bool isSubscribed)
{
IsSubscribed = isSubscribed;
}
public static UserSubscriptionsResult Subscribed()
{
return new UserSubscriptionsResult(true);
}
public static UserSubscriptionsResult UnSubscribed()
{
return new UserSubscriptionsResult(false);
}
}
}
| 23.565217 | 60 | 0.625461 | [
"MIT"
] | FanShiYou/abp-vue-admin-element-typescript | aspnet-core/modules/message/LINGYUN.Abp.MessageService.Application.Contracts/LINGYUN/Abp/MessageService/Subscriptions/Dto/UserSubscriptionsResult.cs | 544 | C# |
// *** WARNING: this file was generated by crd2pulumi. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.Kubernetes.Types.Inputs.Certmanager.V1Alpha3
{
/// <summary>
/// Vault configures this issuer to sign certificates using a HashiCorp Vault PKI backend.
/// </summary>
public class IssuerSpecVaultArgs : Pulumi.ResourceArgs
{
/// <summary>
/// Auth configures how cert-manager authenticates with the Vault server.
/// </summary>
[Input("auth", required: true)]
public Input<Pulumi.Kubernetes.Types.Inputs.Certmanager.V1Alpha3.IssuerSpecVaultAuthArgs> Auth { get; set; } = null!;
/// <summary>
/// PEM encoded CA bundle used to validate Vault server certificate. Only used if the Server URL is using HTTPS protocol. This parameter is ignored for plain HTTP protocol connection. If not set the system root certificates are used to validate the TLS connection.
/// </summary>
[Input("caBundle")]
public Input<string>? CaBundle { get; set; }
/// <summary>
/// Name of the vault namespace. Namespaces is a set of features within Vault Enterprise that allows Vault environments to support Secure Multi-tenancy. e.g: "ns1" More about namespaces can be found here https://www.vaultproject.io/docs/enterprise/namespaces
/// </summary>
[Input("namespace")]
public Input<string>? Namespace { get; set; }
/// <summary>
/// Path is the mount path of the Vault PKI backend's `sign` endpoint, e.g: "my_pki_mount/sign/my-role-name".
/// </summary>
[Input("path", required: true)]
public Input<string> Path { get; set; } = null!;
/// <summary>
/// Server is the connection address for the Vault server, e.g: "https://vault.example.com:8200".
/// </summary>
[Input("server", required: true)]
public Input<string> Server { get; set; } = null!;
public IssuerSpecVaultArgs()
{
}
}
}
| 41.811321 | 272 | 0.651173 | [
"MIT"
] | WhereIsMyTransport/Pulumi.Crds.CertManager | crd/dotnet/Certmanager/V1Alpha3/Inputs/IssuerSpecVaultArgs.cs | 2,216 | 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 gamelift-2015-10-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.GameLift.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using ThirdParty.Json.LitJson;
namespace Amazon.GameLift.Model.Internal.MarshallTransformations
{
/// <summary>
/// Response Unmarshaller for GameSessionQueueDestination Object
/// </summary>
public class GameSessionQueueDestinationUnmarshaller : IUnmarshaller<GameSessionQueueDestination, XmlUnmarshallerContext>, IUnmarshaller<GameSessionQueueDestination, JsonUnmarshallerContext>
{
/// <summary>
/// Unmarshaller the response from the service to the response class.
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
GameSessionQueueDestination IUnmarshaller<GameSessionQueueDestination, 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 GameSessionQueueDestination Unmarshall(JsonUnmarshallerContext context)
{
context.Read();
if (context.CurrentTokenType == JsonToken.Null)
return null;
GameSessionQueueDestination unmarshalledObject = new GameSessionQueueDestination();
int targetDepth = context.CurrentDepth;
while (context.ReadAtDepth(targetDepth))
{
if (context.TestExpression("DestinationArn", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
unmarshalledObject.DestinationArn = unmarshaller.Unmarshall(context);
continue;
}
}
return unmarshalledObject;
}
private static GameSessionQueueDestinationUnmarshaller _instance = new GameSessionQueueDestinationUnmarshaller();
/// <summary>
/// Gets the singleton.
/// </summary>
public static GameSessionQueueDestinationUnmarshaller Instance
{
get
{
return _instance;
}
}
}
} | 36.206522 | 195 | 0.640348 | [
"Apache-2.0"
] | philasmar/aws-sdk-net | sdk/src/Services/GameLift/Generated/Model/Internal/MarshallTransformations/GameSessionQueueDestinationUnmarshaller.cs | 3,331 | C# |
namespace Capgemini.PowerApps.PackageDeployerTemplate.UnitTests.Services
{
using System;
using System.Collections.Generic;
using System.Linq;
using Capgemini.PowerApps.PackageDeployerTemplate.Adapters;
using Capgemini.PowerApps.PackageDeployerTemplate.Services;
using FluentAssertions;
using Microsoft.Extensions.Logging;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Messages;
using Microsoft.Xrm.Sdk.Query;
using Moq;
using Xunit;
public class ConnectionReferenceDeploymentServiceTests
{
private readonly Mock<ILogger> loggerMock;
private readonly Mock<ICrmServiceAdapter> crmSvc;
private readonly ConnectionReferenceDeploymentService connectionReferenceSvc;
public ConnectionReferenceDeploymentServiceTests()
{
this.loggerMock = new Mock<ILogger>();
this.crmSvc = new Mock<ICrmServiceAdapter>();
this.connectionReferenceSvc = new ConnectionReferenceDeploymentService(this.loggerMock.Object, this.crmSvc.Object);
}
[Fact]
public void ConnectConnectionReferences_NullConnectionMap_DoesNotThrow()
{
Action callingConnectConnectionReferencesWithNullConnectionMap = () => this.connectionReferenceSvc.ConnectConnectionReferences(null);
callingConnectConnectionReferencesWithNullConnectionMap.Should().NotThrow<ArgumentNullException>();
}
[Fact]
public void ConnectConnectionReferences_EmptyConnectionMap_DoesNotThrow()
{
Action callingConnectConnectionReferencesWithNullConnectionMap = () => this.connectionReferenceSvc.ConnectConnectionReferences(new Dictionary<string, string>());
callingConnectConnectionReferencesWithNullConnectionMap.Should().NotThrow<ArgumentNullException>();
}
[Fact]
public void ConnectConnectionReferences_ConnectionMappingPassed_UpdatesConnectionReferences()
{
var connectionMap = new Dictionary<string, string>
{
{ "pdt_sharedapprovals_d7dcb", "12038109da0wud01" },
};
var connectionReferences = this.MockConnectionReferencesForConnectionMap(connectionMap);
this.MockUpdateConnectionReferencesResponse(new ExecuteMultipleResponse { Results = { { "IsFaulted", false } } });
this.connectionReferenceSvc.ConnectConnectionReferences(connectionMap);
this.crmSvc.Verify(
svc => svc.Execute(
It.Is<ExecuteMultipleRequest>(
execMultiReq => execMultiReq.Requests.Cast<UpdateRequest>().Any(
req =>
req.Target.GetAttributeValue<string>(Constants.ConnectionReference.Fields.ConnectionId) == connectionMap.Values.First() &&
req.Target.Id == connectionReferences.Entities.First().Id))));
}
[Fact]
public void ConnectConnectionReferences_WithConnectionOwner_UpdatesAsConnectionOwner()
{
var connectionOwner = "licenseduser@domaincom";
var connectionMap = new Dictionary<string, string>
{
{ "pdt_sharedapprovals_d7dcb", "12038109da0wud01" },
};
this.MockConnectionReferencesForConnectionMap(connectionMap);
this.MockUpdateConnectionReferencesResponse(new ExecuteMultipleResponse { Results = { { "IsFaulted", false } } });
this.connectionReferenceSvc.ConnectConnectionReferences(connectionMap, connectionOwner);
this.crmSvc.Verify(svc => svc.Execute<ExecuteMultipleResponse>(It.IsAny<OrganizationRequest>(), connectionOwner, true));
}
[Fact]
public void ConnectConnectionReferences_WithErrorUpdating_Continues()
{
var connectionMap = new Dictionary<string, string>
{
{ "pdt_sharedapprovals_d7dcb", "12038109da0wud01" },
};
this.MockConnectionReferencesForConnectionMap(connectionMap);
var response = new ExecuteMultipleResponse
{
Results =
{
{
"IsFaulted",
true
},
{
"Responses",
new ExecuteMultipleResponseItemCollection()
{
new ExecuteMultipleResponseItem
{
Fault = new OrganizationServiceFault(),
},
}
},
},
};
this.MockUpdateConnectionReferencesResponse(response);
this.connectionReferenceSvc.ConnectConnectionReferences(connectionMap);
this.loggerMock.VerifyLog(l => l.LogError(It.IsAny<string>()));
}
private void MockUpdateConnectionReferencesResponse(ExecuteMultipleResponse response)
{
this.crmSvc.Setup(svc => svc.Execute(It.IsAny<ExecuteMultipleRequest>())).Returns(response);
this.crmSvc.Setup(svc => svc.Execute<ExecuteMultipleResponse>(It.IsAny<ExecuteMultipleRequest>(), It.IsAny<string>(), true)).Returns(response);
}
private EntityCollection MockConnectionReferencesForConnectionMap(Dictionary<string, string> connectionMap)
{
var connectionReferences = new EntityCollection(
connectionMap.Keys.Select(k =>
{
var entity = new Entity(Constants.ConnectionReference.LogicalName, Guid.NewGuid());
entity.Attributes.Add(Constants.ConnectionReference.Fields.ConnectionReferenceLogicalName, k);
return entity;
}).ToList());
this.crmSvc.Setup(
c => c.RetrieveMultipleByAttribute(
Constants.ConnectionReference.LogicalName,
Constants.ConnectionReference.Fields.ConnectionReferenceLogicalName,
connectionMap.Keys,
It.IsAny<ColumnSet>()))
.Returns(connectionReferences);
return connectionReferences;
}
}
}
| 42.655405 | 173 | 0.623792 | [
"MIT"
] | Capgemini/powerapps-packagedeployer-template | tests/Capgemini.PowerApps.PackageDeployerTemplate.UnitTests/Services/ConnectionReferenceDeploymentServiceTests.cs | 6,313 | C# |
// Copyright 2004-2011 Castle Project - http://www.castleproject.org/
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
namespace Castle.Windsor.Diagnostics
{
/// <summary>
/// Exposes diagnostics about itself to the <see cref = "IDiagnosticsInspector{TData,TContext}" />.
/// </summary>
/// <typeparam name = "TData">Usually simple type containing information provided to the <see
/// cref = "IDiagnosticsInspector{TData,TContext}" />.</typeparam>
/// <remarks>
/// Can be implemented by any type constituting part of container infrastructure. Should have a matching <see
/// cref = "IDiagnosticsInspector{TData,TContext}" /> registred in the container that knows
/// how to find it and that prepares information from it for consumption.
/// </remarks>
public interface IExposeDiagnostics<out TData>
{
/// <summary>
/// Collects <typeparamref name = "TData" /> for the <paramref name = "inspector" /> and calls <see
/// cref = "IDiagnosticsInspector{TData,TContext}.Inspect" /> if any data available.
/// </summary>
/// <param name = "inspector"></param>
/// <param name = "context">pass-through context. Used by the inspector.</param>
void Visit<TContext>(IDiagnosticsInspector<TData, TContext> inspector, TContext context);
}
} | 49.243243 | 113 | 0.701976 | [
"Apache-2.0"
] | castleproject-deprecated/Castle.Windsor-READONLY | src/Castle.Windsor/Windsor/Diagnostics/IExposeDiagnostics.cs | 1,822 | C# |
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;
namespace IS.OAuth
{
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
}
}
| 24.52381 | 70 | 0.572816 | [
"MIT"
] | Amitpnk/IdentityServerDemo | IS/IS.OAuth/Program.cs | 515 | C# |
using System;
namespace Rightek.HttpClient.Dtos
{
public class CallbackArgs
{
public Settings Settings { get; set; }
public Exception Exception { get; set; }
public string ExceptionType { get; set; }
public DateTimeOffset StartAt { get; set; }
public DateTimeOffset EndAt { get; set; }
}
} | 26.384615 | 51 | 0.632653 | [
"MIT"
] | rightek/rightek.httpclient | src/Rightek.HttpClient/Dtos/CallbackArgs.cs | 345 | C# |
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Management.Automation.Runspaces;
namespace SharePointPnP.PowerShell.Tests.Publishing
{
[TestClass]
public class AddPublishingPageTests
{
#region Test Setup/CleanUp
[ClassInitialize]
public static void Initialize(TestContext testContext)
{
// This runs on class level once before all tests run
//using (var ctx = TestCommon.CreateClientContext())
//{
//}
}
[ClassCleanup]
public static void Cleanup(TestContext testContext)
{
// This runs on class level once
//using (var ctx = TestCommon.CreateClientContext())
//{
//}
}
[TestInitialize]
public void Initialize()
{
using (var scope = new PSTestScope())
{
// Example
// scope.ExecuteCommand("cmdlet", new CommandParameter("param1", prop));
}
}
[TestCleanup]
public void Cleanup()
{
using (var scope = new PSTestScope())
{
try
{
// Do Test Setup - Note, this runs PER test
}
catch (Exception)
{
// Describe Exception
}
}
}
#endregion
#region Scaffolded Cmdlet Tests
//TODO: This is a scaffold of the cmdlet - complete the unit test
//[TestMethod]
public void AddPnPPublishingPageTest()
{
using (var scope = new PSTestScope(true))
{
// Complete writing cmd parameters
// This is a mandatory parameter
// From Cmdlet Help: The name of the page to be added as an aspx file
var pageName = "";
// From Cmdlet Help: The site relative folder path of the page to be added
var folderPath = "";
// This is a mandatory parameter
// From Cmdlet Help: The name of the page layout you want to use. Specify without the .aspx extension. So 'ArticleLeft' or 'BlankWebPartPage'
var pageTemplateName = "";
// From Cmdlet Help: The title of the page
var title = "";
// From Cmdlet Help: Publishes the page. Also Approves it if moderation is enabled on the Pages library.
var publish = "";
var results = scope.ExecuteCommand("Add-PnPPublishingPage",
new CommandParameter("PageName", pageName),
new CommandParameter("FolderPath", folderPath),
new CommandParameter("PageTemplateName", pageTemplateName),
new CommandParameter("Title", title),
new CommandParameter("Publish", publish));
Assert.IsNotNull(results);
}
}
#endregion
}
}
| 31.648352 | 145 | 0.559028 | [
"MIT"
] | Ashikpaul/PnP-PowerShell | Tests/Publishing/AddPnPPublishingPageTests.cs | 2,880 | C# |
using TechTalk.SpecFlow;
using BoDi;
using RaaLabs.Edge.Modules.EventHub.Specs.Drivers;
using Azure.Messaging.EventHubs;
namespace RaaLabs.Edge.Modules.EventHub.Specs.Steps
{
[Binding]
class EventHubBridgeSteps
{
private readonly IObjectContainer _container;
public EventHubBridgeSteps(IObjectContainer container)
{
_container = container;
}
[BeforeScenario]
public void SetupEventFactories()
{
_container.RegisterTypeAs<SomeEventHubIncomingEventInstanceFactory, IEventInstanceFactory<SomeEventHubIncomingEvent>>();
_container.RegisterTypeAs<SomeEventHubOutgoingEventInstanceFactory, IEventInstanceFactory<SomeEventHubOutgoingEvent>>();
_container.RegisterTypeAs<EventDataInstanceFactory, IEventInstanceFactory<EventData>>();
_container.RegisterTypeAs<SomeEventHubIncomingEventVerifier, IProducedEventVerifier<SomeEventHubIncomingEvent>>();
_container.RegisterTypeAs<EventDataVerifier, IProducedEventVerifier<EventData>>();
}
}
}
| 36.233333 | 132 | 0.73965 | [
"MIT"
] | RaaLabs/Edge | Edge.Modules.EventHub.Specs/Steps/EventHubBridgeSteps.cs | 1,089 | C# |
using System;
using System.Security.Cryptography;
using System.Text;
namespace SecureJaroWinkler
{
public class Hash
{
public Hash() { }
public enum HashType : int
{
MD5,
SHA1,
SHA256,
SHA512,
}
public static string GetHash(string text, HashType hashType)
{
string hashString;
switch (hashType)
{
case HashType.MD5:
hashString = GetMD5(text);
break;
case HashType.SHA1:
hashString = GetSHA1(text);
break;
case HashType.SHA256:
hashString = GetSHA256(text);
break;
case HashType.SHA512:
hashString = GetSHA512(text);
break;
default:
hashString = "Invalid Hash Type";
break;
}
return hashString;
}
public static bool CheckHash(string original, string hashString, HashType hashType)
{
string originalHash = GetHash(original, hashType);
return (originalHash == hashString);
}
private static string GetMD5(string text)
{
UnicodeEncoding UE = new UnicodeEncoding();
byte[] hashValue;
byte[] message = UE.GetBytes(text);
MD5 hashString = new MD5CryptoServiceProvider();
string hex = "";
hashValue = hashString.ComputeHash(message);
foreach (byte x in hashValue)
{
hex += String.Format("{0:x2}", x);
}
return hex;
}
private static string GetSHA1(string text)
{
UnicodeEncoding UE = new UnicodeEncoding();
byte[] hashValue;
byte[] message = UE.GetBytes(text);
SHA1Managed hashString = new SHA1Managed();
string hex = "";
hashValue = hashString.ComputeHash(message);
//System.Collections.BitArray bits = new System.Collections.BitArray(hashValue);
foreach (byte x in hashValue)
{
hex += String.Format("{0:x2}", x);
}
return hex;
}
private static string GetSHA256(string text)
{
UnicodeEncoding UE = new UnicodeEncoding();
byte[] hashValue;
byte[] message = UE.GetBytes(text);
SHA256Managed hashString = new SHA256Managed();
string hex = "";
hashValue = hashString.ComputeHash(message);
foreach (byte x in hashValue)
{
hex += String.Format("{0:x2}", x);
}
return hex;
}
private static string GetSHA512(string text)
{
UnicodeEncoding UE = new UnicodeEncoding();
byte[] hashValue;
byte[] message = UE.GetBytes(text);
SHA512Managed hashString = new SHA512Managed();
string hex = "";
hashValue = hashString.ComputeHash(message);
foreach (byte x in hashValue)
{
hex += String.Format("{0:x2}", x);
}
return hex;
}
public static string GetHMACSHA1(string text, byte[] salt)
{
UnicodeEncoding UE = new UnicodeEncoding();
byte[] hashValue;
byte[] message = UE.GetBytes(text);
HMACSHA1 hashString = new HMACSHA1(salt);
string hex = "";
hashValue = hashString.ComputeHash(message);
foreach (byte x in hashValue)
{
hex += String.Format("{0:x2}", x);
}
return hex;
}
public static string GetHMACMD5(string text, byte[] salt)
{
UnicodeEncoding UE = new UnicodeEncoding();
byte[] hashValue;
byte[] message = UE.GetBytes(text);
HMACMD5 hashString = new HMACMD5(salt);
string hex = "";
hashValue = hashString.ComputeHash(message);
foreach (byte x in hashValue)
{
hex += String.Format("{0:x2}", x);
}
return hex;
}
}
}
| 28.63522 | 93 | 0.4698 | [
"MIT"
] | uva-bi-sdad/secure_jaro_winkler_cs | SecureJaroWinkler/Hash.cs | 4,555 | C# |
using Microsoft.CodeAnalysis.CSharp.Syntax;
using System.Collections.Generic;
using System.Linq;
using Soothsharp.Translation.Trees.CSharp.Statements;
using Soothsharp.Translation.Trees.Silver;
namespace Soothsharp.Translation.Trees.CSharp
{
internal class BlockSharpnode : StatementSharpnode
{
private BlockSyntax BlockSyntax;
private List<StatementSharpnode> Statements;
public BlockSharpnode(BlockSyntax originalNode) : base(originalNode)
{
this.BlockSyntax = originalNode;
this.Statements = originalNode.Statements.Select(RoslynToSharpnode.MapStatement).ToList();
}
public override TranslationResult Translate(TranslationContext context)
{
var statements = new List<StatementSilvernode>();
var contracts = new List<ContractSilvernode>();
var diagnostics = new List<Error>();
bool inFunctionOrPredicateBlockReturnStatementAlreadyOccured = false;
foreach(var statement in this.Statements)
{
var statementResult = statement.Translate(context);
// Prepending statements (part 1)
if (statementResult.PrependTheseSilvernodes.Any())
{
statements.AddRange(statementResult.PrependTheseSilvernodes);
}
if (statementResult.Silvernode != null)
{
// Report an error is a contract is in an invalid block
if (statementResult.Silvernode.IsContract())
{
contracts.Add(statementResult.Silvernode as ContractSilvernode);
if (statementResult.Silvernode is RequiresSilvernode ||
statementResult.Silvernode is EnsuresSilvernode)
{
if (this.BlockSyntax.Parent is MethodDeclarationSyntax ||
this.BlockSyntax.Parent is ConstructorDeclarationSyntax)
{
}
else
{
diagnostics.Add(new Translation.Error(
Diagnostics.SSIL129_MethodContractsAreOnlyForMethods,
statementResult.Silvernode.OriginalNode));
}
}
if (statementResult.Silvernode is InvariantSilvernode)
{
if (this.BlockSyntax.Parent is ForStatementSyntax ||
this.BlockSyntax.Parent is WhileStatementSyntax ||
this.BlockSyntax.Parent is DoStatementSyntax)
{
}
else
{
diagnostics.Add(new Translation.Error(
Diagnostics.SSIL130_InvariantsAreOnlyForLoops,
statementResult.Silvernode.OriginalNode));
}
}
}
else
{
// Translate body
if (context.IsFunctionOrPredicateBlock)
{
if (statement.GetType() == typeof(ReturnStatementSharpnode))
{
if (inFunctionOrPredicateBlockReturnStatementAlreadyOccured)
{
diagnostics.Add(new Error(Diagnostics.SSIL122_FunctionsAndPredicatesCannotHaveMoreThanOneReturnStatement,
statement.OriginalNode));
}
else
{
inFunctionOrPredicateBlockReturnStatementAlreadyOccured = true;
}
}
else
{
diagnostics.Add(new Error(Diagnostics.SSIL121_FunctionsAndPredicatesCannotHaveStatements,
statement.OriginalNode));
}
}
StatementSilvernode statementSilvernode;
if ((statementResult.Silvernode is StatementSilvernode))
{
statementSilvernode = (StatementSilvernode)statementResult.Silvernode;
}
else
{
statementSilvernode = new ExpressionStatementSilvernode(statementResult.Silvernode, statementResult.Silvernode.OriginalNode);
}
statements.Add(statementSilvernode);
}
}
diagnostics.AddRange(statementResult.Errors);
}
BlockSilvernode block = new BlockSilvernode(this.BlockSyntax, statements);
contracts.Sort();
return new TranslationResult
{
Silvernode = block,
Errors = diagnostics,
Contracts = contracts
};
}
}
} | 43.864 | 153 | 0.4793 | [
"MIT"
] | Soothsilver/cs2sil | Soothsharp.Translation/Trees/CSharp/Statements/BlockSharpnode.cs | 5,485 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Zokma.Libs.Audio
{
/// <summary>
/// Exception for invalid state;
/// </summary>
public class InvalidAudioEngineStateException : Exception
{
/// <summary>
/// Creates Exception
/// </summary>
/// <param name="message">Error message.</param>
public InvalidAudioEngineStateException(string message)
: base(message)
{
}
}
}
| 22.541667 | 63 | 0.615527 | [
"MIT"
] | zokma/live-sounds | LiveSoundsSolution/Zokma.Libs/Audio/InvalidAudioEngineStateException.cs | 543 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by \generate-code.bat.
//
// Changes to this file will be lost when the code is regenerated.
// The build server regenerates the code before each build and a pre-build
// step will regenerate the code on each local build.
//
// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units.
//
// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities.
// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities.
//
// </auto-generated>
//------------------------------------------------------------------------------
// Licensed under MIT No Attribution, see LICENSE file at the root.
// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet.
using System;
using System.Globalization;
using System.Linq;
using System.Runtime.Serialization;
using JetBrains.Annotations;
using UnitsNet.InternalHelpers;
using UnitsNet.Units;
#nullable enable
// ReSharper disable once CheckNamespace
namespace UnitsNet
{
/// <inheritdoc />
/// <summary>
/// Lapse rate is the rate at which Earth's atmospheric temperature decreases with an increase in altitude, or increases with the decrease in altitude.
/// </summary>
[Obsolete("Use TemperatureGradient instead.")]
[DataContract]
public partial struct LapseRate : IQuantity<LapseRateUnit>, IEquatable<LapseRate>, IComparable, IComparable<LapseRate>, IConvertible, IFormattable
{
/// <summary>
/// The numeric value this quantity was constructed with.
/// </summary>
[DataMember(Name = "Value", Order = 0)]
private readonly double _value;
/// <summary>
/// The unit this quantity was constructed with.
/// </summary>
[DataMember(Name = "Unit", Order = 1)]
private readonly LapseRateUnit? _unit;
static LapseRate()
{
BaseDimensions = new BaseDimensions(-1, 0, 0, 0, 1, 0, 0);
BaseUnit = LapseRateUnit.DegreeCelsiusPerKilometer;
MaxValue = new LapseRate(double.MaxValue, BaseUnit);
MinValue = new LapseRate(double.MinValue, BaseUnit);
QuantityType = QuantityType.LapseRate;
Units = Enum.GetValues(typeof(LapseRateUnit)).Cast<LapseRateUnit>().Except(new LapseRateUnit[]{ LapseRateUnit.Undefined }).ToArray();
Zero = new LapseRate(0, BaseUnit);
Info = new QuantityInfo<LapseRateUnit>("LapseRate",
new UnitInfo<LapseRateUnit>[]
{
new UnitInfo<LapseRateUnit>(LapseRateUnit.DegreeCelsiusPerKilometer, "DegreesCelciusPerKilometer", BaseUnits.Undefined),
},
BaseUnit, Zero, BaseDimensions, QuantityType.LapseRate);
DefaultConversionFunctions = new UnitConverter();
RegisterDefaultConversions(DefaultConversionFunctions);
}
/// <summary>
/// Creates the quantity with the given numeric value and unit.
/// </summary>
/// <param name="value">The numeric value to construct this quantity with.</param>
/// <param name="unit">The unit representation to construct this quantity with.</param>
/// <exception cref="ArgumentException">If value is NaN or Infinity.</exception>
public LapseRate(double value, LapseRateUnit unit)
{
if (unit == LapseRateUnit.Undefined)
throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit));
_value = Guard.EnsureValidNumber(value, nameof(value));
_unit = unit;
}
/// <summary>
/// Creates an instance of the quantity with the given numeric value in units compatible with the given <see cref="UnitSystem"/>.
/// If multiple compatible units were found, the first match is used.
/// </summary>
/// <param name="value">The numeric value to construct this quantity with.</param>
/// <param name="unitSystem">The unit system to create the quantity with.</param>
/// <exception cref="ArgumentNullException">The given <see cref="UnitSystem"/> is null.</exception>
/// <exception cref="ArgumentException">No unit was found for the given <see cref="UnitSystem"/>.</exception>
public LapseRate(double value, UnitSystem unitSystem)
{
if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem));
var unitInfos = Info.GetUnitInfosFor(unitSystem.BaseUnits);
var firstUnitInfo = unitInfos.FirstOrDefault();
_value = Guard.EnsureValidNumber(value, nameof(value));
_unit = firstUnitInfo?.Value ?? throw new ArgumentException("No units were found for the given UnitSystem.", nameof(unitSystem));
}
#region Static Properties
/// <summary>
/// The <see cref="UnitConverter" /> containing the default generated conversion functions for <see cref="LapseRate" /> instances.
/// </summary>
public static UnitConverter DefaultConversionFunctions { get; }
/// <inheritdoc cref="IQuantity.QuantityInfo"/>
public static QuantityInfo<LapseRateUnit> Info { get; }
/// <summary>
/// The <see cref="BaseDimensions" /> of this quantity.
/// </summary>
public static BaseDimensions BaseDimensions { get; }
/// <summary>
/// The base unit of LapseRate, which is DegreeCelsiusPerKilometer. All conversions go via this value.
/// </summary>
public static LapseRateUnit BaseUnit { get; }
/// <summary>
/// Represents the largest possible value of LapseRate
/// </summary>
[Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")]
public static LapseRate MaxValue { get; }
/// <summary>
/// Represents the smallest possible value of LapseRate
/// </summary>
[Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")]
public static LapseRate MinValue { get; }
/// <summary>
/// The <see cref="QuantityType" /> of this quantity.
/// </summary>
[Obsolete("QuantityType will be removed in the future. Use the Info property instead.")]
public static QuantityType QuantityType { get; }
/// <summary>
/// All units of measurement for the LapseRate quantity.
/// </summary>
public static LapseRateUnit[] Units { get; }
/// <summary>
/// Gets an instance of this quantity with a value of 0 in the base unit DegreeCelsiusPerKilometer.
/// </summary>
public static LapseRate Zero { get; }
#endregion
#region Properties
/// <summary>
/// The numeric value this quantity was constructed with.
/// </summary>
public double Value => _value;
Enum IQuantity.Unit => Unit;
/// <inheritdoc />
public LapseRateUnit Unit => _unit.GetValueOrDefault(BaseUnit);
/// <inheritdoc />
public QuantityInfo<LapseRateUnit> QuantityInfo => Info;
/// <inheritdoc cref="IQuantity.QuantityInfo"/>
QuantityInfo IQuantity.QuantityInfo => Info;
/// <summary>
/// The <see cref="QuantityType" /> of this quantity.
/// </summary>
[Obsolete("QuantityType will be removed in the future. Use the Info property instead.")]
public QuantityType Type => QuantityType.LapseRate;
/// <summary>
/// The <see cref="BaseDimensions" /> of this quantity.
/// </summary>
public BaseDimensions Dimensions => LapseRate.BaseDimensions;
#endregion
#region Conversion Properties
/// <summary>
/// Gets a <see cref="double"/> value of this quantity converted into <see cref="LapseRateUnit.DegreeCelsiusPerKilometer"/>
/// </summary>
public double DegreesCelciusPerKilometer => As(LapseRateUnit.DegreeCelsiusPerKilometer);
#endregion
#region Static Methods
/// <summary>
/// Registers the default conversion functions in the given <see cref="UnitConverter"/> instance.
/// </summary>
/// <param name="unitConverter">The <see cref="UnitConverter"/> to register the default conversion functions in.</param>
internal static void RegisterDefaultConversions(UnitConverter unitConverter)
{
// Register in unit converter: BaseUnit -> LapseRateUnit
// Register in unit converter: BaseUnit <-> BaseUnit
unitConverter.SetConversionFunction<LapseRate>(LapseRateUnit.DegreeCelsiusPerKilometer, LapseRateUnit.DegreeCelsiusPerKilometer, quantity => quantity);
// Register in unit converter: LapseRateUnit -> BaseUnit
}
internal static void MapGeneratedLocalizations(UnitAbbreviationsCache unitAbbreviationsCache)
{
unitAbbreviationsCache.PerformAbbreviationMapping(LapseRateUnit.DegreeCelsiusPerKilometer, new CultureInfo("en-US"), false, true, new string[]{"∆°C/km"});
}
/// <summary>
/// Get unit abbreviation string.
/// </summary>
/// <param name="unit">Unit to get abbreviation for.</param>
/// <returns>Unit abbreviation string.</returns>
public static string GetAbbreviation(LapseRateUnit unit)
{
return GetAbbreviation(unit, null);
}
/// <summary>
/// Get unit abbreviation string.
/// </summary>
/// <param name="unit">Unit to get abbreviation for.</param>
/// <returns>Unit abbreviation string.</returns>
/// <param name="provider">Format to use for localization. Defaults to <see cref="CultureInfo.CurrentUICulture" /> if null.</param>
public static string GetAbbreviation(LapseRateUnit unit, IFormatProvider? provider)
{
return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider);
}
#endregion
#region Static Factory Methods
/// <summary>
/// Creates a <see cref="LapseRate"/> from <see cref="LapseRateUnit.DegreeCelsiusPerKilometer"/>.
/// </summary>
/// <exception cref="ArgumentException">If value is NaN or Infinity.</exception>
public static LapseRate FromDegreesCelciusPerKilometer(QuantityValue degreescelciusperkilometer)
{
double value = (double) degreescelciusperkilometer;
return new LapseRate(value, LapseRateUnit.DegreeCelsiusPerKilometer);
}
/// <summary>
/// Dynamically convert from value and unit enum <see cref="LapseRateUnit" /> to <see cref="LapseRate" />.
/// </summary>
/// <param name="value">Value to convert from.</param>
/// <param name="fromUnit">Unit to convert from.</param>
/// <returns>LapseRate unit value.</returns>
public static LapseRate From(QuantityValue value, LapseRateUnit fromUnit)
{
return new LapseRate((double)value, fromUnit);
}
#endregion
#region Static Parse Methods
/// <summary>
/// Parse a string with one or two quantities of the format "<quantity> <unit>".
/// </summary>
/// <param name="str">String to parse. Typically in the form: {number} {unit}</param>
/// <example>
/// Length.Parse("5.5 m", new CultureInfo("en-US"));
/// </example>
/// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception>
/// <exception cref="ArgumentException">
/// Expected string to have one or two pairs of quantity and unit in the format
/// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in"
/// </exception>
/// <exception cref="AmbiguousUnitParseException">
/// More than one unit is represented by the specified unit abbreviation.
/// Example: Volume.Parse("1 cup") will throw, because it can refer to any of
/// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />.
/// </exception>
/// <exception cref="UnitsNetException">
/// If anything else goes wrong, typically due to a bug or unhandled case.
/// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish
/// Units.NET exceptions from other exceptions.
/// </exception>
public static LapseRate Parse(string str)
{
return Parse(str, null);
}
/// <summary>
/// Parse a string with one or two quantities of the format "<quantity> <unit>".
/// </summary>
/// <param name="str">String to parse. Typically in the form: {number} {unit}</param>
/// <example>
/// Length.Parse("5.5 m", new CultureInfo("en-US"));
/// </example>
/// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception>
/// <exception cref="ArgumentException">
/// Expected string to have one or two pairs of quantity and unit in the format
/// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in"
/// </exception>
/// <exception cref="AmbiguousUnitParseException">
/// More than one unit is represented by the specified unit abbreviation.
/// Example: Volume.Parse("1 cup") will throw, because it can refer to any of
/// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />.
/// </exception>
/// <exception cref="UnitsNetException">
/// If anything else goes wrong, typically due to a bug or unhandled case.
/// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish
/// Units.NET exceptions from other exceptions.
/// </exception>
/// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentUICulture" /> if null.</param>
public static LapseRate Parse(string str, IFormatProvider? provider)
{
return QuantityParser.Default.Parse<LapseRate, LapseRateUnit>(
str,
provider,
From);
}
/// <summary>
/// Try to parse a string with one or two quantities of the format "<quantity> <unit>".
/// </summary>
/// <param name="str">String to parse. Typically in the form: {number} {unit}</param>
/// <param name="result">Resulting unit quantity if successful.</param>
/// <example>
/// Length.Parse("5.5 m", new CultureInfo("en-US"));
/// </example>
public static bool TryParse(string? str, out LapseRate result)
{
return TryParse(str, null, out result);
}
/// <summary>
/// Try to parse a string with one or two quantities of the format "<quantity> <unit>".
/// </summary>
/// <param name="str">String to parse. Typically in the form: {number} {unit}</param>
/// <param name="result">Resulting unit quantity if successful.</param>
/// <returns>True if successful, otherwise false.</returns>
/// <example>
/// Length.Parse("5.5 m", new CultureInfo("en-US"));
/// </example>
/// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentUICulture" /> if null.</param>
public static bool TryParse(string? str, IFormatProvider? provider, out LapseRate result)
{
return QuantityParser.Default.TryParse<LapseRate, LapseRateUnit>(
str,
provider,
From,
out result);
}
/// <summary>
/// Parse a unit string.
/// </summary>
/// <param name="str">String to parse. Typically in the form: {number} {unit}</param>
/// <example>
/// Length.ParseUnit("m", new CultureInfo("en-US"));
/// </example>
/// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception>
/// <exception cref="UnitsNetException">Error parsing string.</exception>
public static LapseRateUnit ParseUnit(string str)
{
return ParseUnit(str, null);
}
/// <summary>
/// Parse a unit string.
/// </summary>
/// <param name="str">String to parse. Typically in the form: {number} {unit}</param>
/// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentUICulture" /> if null.</param>
/// <example>
/// Length.ParseUnit("m", new CultureInfo("en-US"));
/// </example>
/// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception>
/// <exception cref="UnitsNetException">Error parsing string.</exception>
public static LapseRateUnit ParseUnit(string str, IFormatProvider? provider)
{
return UnitParser.Default.Parse<LapseRateUnit>(str, provider);
}
/// <inheritdoc cref="TryParseUnit(string,IFormatProvider,out UnitsNet.Units.LapseRateUnit)"/>
public static bool TryParseUnit(string str, out LapseRateUnit unit)
{
return TryParseUnit(str, null, out unit);
}
/// <summary>
/// Parse a unit string.
/// </summary>
/// <param name="str">String to parse. Typically in the form: {number} {unit}</param>
/// <param name="unit">The parsed unit if successful.</param>
/// <returns>True if successful, otherwise false.</returns>
/// <example>
/// Length.TryParseUnit("m", new CultureInfo("en-US"));
/// </example>
/// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentUICulture" /> if null.</param>
public static bool TryParseUnit(string str, IFormatProvider? provider, out LapseRateUnit unit)
{
return UnitParser.Default.TryParse<LapseRateUnit>(str, provider, out unit);
}
#endregion
#region Arithmetic Operators
/// <summary>Negate the value.</summary>
public static LapseRate operator -(LapseRate right)
{
return new LapseRate(-right.Value, right.Unit);
}
/// <summary>Get <see cref="LapseRate"/> from adding two <see cref="LapseRate"/>.</summary>
public static LapseRate operator +(LapseRate left, LapseRate right)
{
return new LapseRate(left.Value + right.GetValueAs(left.Unit), left.Unit);
}
/// <summary>Get <see cref="LapseRate"/> from subtracting two <see cref="LapseRate"/>.</summary>
public static LapseRate operator -(LapseRate left, LapseRate right)
{
return new LapseRate(left.Value - right.GetValueAs(left.Unit), left.Unit);
}
/// <summary>Get <see cref="LapseRate"/> from multiplying value and <see cref="LapseRate"/>.</summary>
public static LapseRate operator *(double left, LapseRate right)
{
return new LapseRate(left * right.Value, right.Unit);
}
/// <summary>Get <see cref="LapseRate"/> from multiplying value and <see cref="LapseRate"/>.</summary>
public static LapseRate operator *(LapseRate left, double right)
{
return new LapseRate(left.Value * right, left.Unit);
}
/// <summary>Get <see cref="LapseRate"/> from dividing <see cref="LapseRate"/> by value.</summary>
public static LapseRate operator /(LapseRate left, double right)
{
return new LapseRate(left.Value / right, left.Unit);
}
/// <summary>Get ratio value from dividing <see cref="LapseRate"/> by <see cref="LapseRate"/>.</summary>
public static double operator /(LapseRate left, LapseRate right)
{
return left.DegreesCelciusPerKilometer / right.DegreesCelciusPerKilometer;
}
#endregion
#region Equality / IComparable
/// <summary>Returns true if less or equal to.</summary>
public static bool operator <=(LapseRate left, LapseRate right)
{
return left.Value <= right.GetValueAs(left.Unit);
}
/// <summary>Returns true if greater than or equal to.</summary>
public static bool operator >=(LapseRate left, LapseRate right)
{
return left.Value >= right.GetValueAs(left.Unit);
}
/// <summary>Returns true if less than.</summary>
public static bool operator <(LapseRate left, LapseRate right)
{
return left.Value < right.GetValueAs(left.Unit);
}
/// <summary>Returns true if greater than.</summary>
public static bool operator >(LapseRate left, LapseRate right)
{
return left.Value > right.GetValueAs(left.Unit);
}
/// <summary>Returns true if exactly equal.</summary>
/// <remarks>Consider using <see cref="Equals(LapseRate, double, ComparisonType)"/> for safely comparing floating point values.</remarks>
public static bool operator ==(LapseRate left, LapseRate right)
{
return left.Equals(right);
}
/// <summary>Returns true if not exactly equal.</summary>
/// <remarks>Consider using <see cref="Equals(LapseRate, double, ComparisonType)"/> for safely comparing floating point values.</remarks>
public static bool operator !=(LapseRate left, LapseRate right)
{
return !(left == right);
}
/// <inheritdoc />
public int CompareTo(object obj)
{
if (obj is null) throw new ArgumentNullException(nameof(obj));
if (!(obj is LapseRate objLapseRate)) throw new ArgumentException("Expected type LapseRate.", nameof(obj));
return CompareTo(objLapseRate);
}
/// <inheritdoc />
public int CompareTo(LapseRate other)
{
return _value.CompareTo(other.GetValueAs(this.Unit));
}
/// <inheritdoc />
/// <remarks>Consider using <see cref="Equals(LapseRate, double, ComparisonType)"/> for safely comparing floating point values.</remarks>
public override bool Equals(object obj)
{
if (obj is null || !(obj is LapseRate objLapseRate))
return false;
return Equals(objLapseRate);
}
/// <inheritdoc />
/// <remarks>Consider using <see cref="Equals(LapseRate, double, ComparisonType)"/> for safely comparing floating point values.</remarks>
public bool Equals(LapseRate other)
{
return _value.Equals(other.GetValueAs(this.Unit));
}
/// <summary>
/// <para>
/// Compare equality to another LapseRate within the given absolute or relative tolerance.
/// </para>
/// <para>
/// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and
/// <paramref name="other"/> as a percentage of this quantity's value. <paramref name="other"/> will be converted into
/// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of
/// this quantity's value to be considered equal.
/// <example>
/// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm).
/// <code>
/// var a = Length.FromMeters(2.0);
/// var b = Length.FromInches(50.0);
/// a.Equals(b, 0.01, ComparisonType.Relative);
/// </code>
/// </example>
/// </para>
/// <para>
/// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and
/// <paramref name="other"/> as a fixed number in this quantity's unit. <paramref name="other"/> will be converted into
/// this quantity's unit for comparison.
/// <example>
/// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm).
/// <code>
/// var a = Length.FromMeters(2.0);
/// var b = Length.FromInches(50.0);
/// a.Equals(b, 0.01, ComparisonType.Absolute);
/// </code>
/// </example>
/// </para>
/// <para>
/// Note that it is advised against specifying zero difference, due to the nature
/// of floating point operations and using System.Double internally.
/// </para>
/// </summary>
/// <param name="other">The other quantity to compare to.</param>
/// <param name="tolerance">The absolute or relative tolerance value. Must be greater than or equal to 0.</param>
/// <param name="comparisonType">The comparison type: either relative or absolute.</param>
/// <returns>True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance.</returns>
public bool Equals(LapseRate other, double tolerance, ComparisonType comparisonType)
{
if (tolerance < 0)
throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0.");
double thisValue = (double)this.Value;
double otherValueInThisUnits = other.As(this.Unit);
return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType);
}
/// <summary>
/// Returns the hash code for this instance.
/// </summary>
/// <returns>A hash code for the current LapseRate.</returns>
public override int GetHashCode()
{
return new { Info.Name, Value, Unit }.GetHashCode();
}
#endregion
#region Conversion Methods
/// <summary>
/// Convert to the unit representation <paramref name="unit" />.
/// </summary>
/// <returns>Value converted to the specified unit.</returns>
public double As(LapseRateUnit unit)
{
if (Unit == unit)
return Convert.ToDouble(Value);
var converted = GetValueAs(unit);
return Convert.ToDouble(converted);
}
/// <inheritdoc cref="IQuantity.As(UnitSystem)"/>
public double As(UnitSystem unitSystem)
{
if (unitSystem is null)
throw new ArgumentNullException(nameof(unitSystem));
var unitInfos = Info.GetUnitInfosFor(unitSystem.BaseUnits);
var firstUnitInfo = unitInfos.FirstOrDefault();
if (firstUnitInfo == null)
throw new ArgumentException("No units were found for the given UnitSystem.", nameof(unitSystem));
return As(firstUnitInfo.Value);
}
/// <inheritdoc />
double IQuantity.As(Enum unit)
{
if (!(unit is LapseRateUnit unitAsLapseRateUnit))
throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(LapseRateUnit)} is supported.", nameof(unit));
return As(unitAsLapseRateUnit);
}
/// <summary>
/// Converts this LapseRate to another LapseRate with the unit representation <paramref name="unit" />.
/// </summary>
/// <param name="unit">The unit to convert to.</param>
/// <returns>A LapseRate with the specified unit.</returns>
public LapseRate ToUnit(LapseRateUnit unit)
{
return ToUnit(unit, DefaultConversionFunctions);
}
/// <summary>
/// Converts this LapseRate to another LapseRate using the given <paramref name="unitConverter"/> with the unit representation <paramref name="unit" />.
/// </summary>
/// <param name="unit">The unit to convert to.</param>
/// <param name="unitConverter">The <see cref="UnitConverter"/> to use for the conversion.</param>
/// <returns>A LapseRate with the specified unit.</returns>
public LapseRate ToUnit(LapseRateUnit unit, UnitConverter unitConverter)
{
if (Unit == unit)
{
// Already in requested units.
return this;
}
else if (unitConverter.TryGetConversionFunction((typeof(LapseRate), Unit, typeof(LapseRate), unit), out var conversionFunction))
{
// Direct conversion to requested unit found. Return the converted quantity.
var converted = conversionFunction(this);
return (LapseRate)converted;
}
else if (Unit != BaseUnit)
{
// Direct conversion to requested unit NOT found. Convert to BaseUnit, and then from BaseUnit to requested unit.
var inBaseUnits = ToUnit(BaseUnit);
return inBaseUnits.ToUnit(unit);
}
else
{
throw new NotImplementedException($"Can not convert {Unit} to {unit}.");
}
}
/// <inheritdoc />
IQuantity IQuantity.ToUnit(Enum unit)
{
if (!(unit is LapseRateUnit unitAsLapseRateUnit))
throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(LapseRateUnit)} is supported.", nameof(unit));
return ToUnit(unitAsLapseRateUnit, DefaultConversionFunctions);
}
/// <inheritdoc cref="IQuantity.ToUnit(UnitSystem)"/>
public LapseRate ToUnit(UnitSystem unitSystem)
{
if (unitSystem is null)
throw new ArgumentNullException(nameof(unitSystem));
var unitInfos = Info.GetUnitInfosFor(unitSystem.BaseUnits);
var firstUnitInfo = unitInfos.FirstOrDefault();
if (firstUnitInfo == null)
throw new ArgumentException("No units were found for the given UnitSystem.", nameof(unitSystem));
return ToUnit(firstUnitInfo.Value);
}
/// <inheritdoc />
IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem);
/// <inheritdoc />
IQuantity<LapseRateUnit> IQuantity<LapseRateUnit>.ToUnit(LapseRateUnit unit) => ToUnit(unit);
/// <inheritdoc />
IQuantity<LapseRateUnit> IQuantity<LapseRateUnit>.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem);
private double GetValueAs(LapseRateUnit unit)
{
var converted = ToUnit(unit);
return (double)converted.Value;
}
#endregion
#region ToString Methods
/// <summary>
/// Gets the default string representation of value and unit.
/// </summary>
/// <returns>String representation.</returns>
public override string ToString()
{
return ToString("g");
}
/// <summary>
/// Gets the default string representation of value and unit using the given format provider.
/// </summary>
/// <returns>String representation.</returns>
/// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentUICulture" /> if null.</param>
public string ToString(IFormatProvider? provider)
{
return ToString("g", provider);
}
/// <summary>
/// Get string representation of value and unit.
/// </summary>
/// <param name="significantDigitsAfterRadix">The number of significant digits after the radix point.</param>
/// <returns>String representation.</returns>
/// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentUICulture" /> if null.</param>
[Obsolete(@"This method is deprecated and will be removed at a future release. Please use ToString(""s2"") or ToString(""s2"", provider) where 2 is an example of the number passed to significantDigitsAfterRadix.")]
public string ToString(IFormatProvider? provider, int significantDigitsAfterRadix)
{
var value = Convert.ToDouble(Value);
var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix);
return ToString(provider, format);
}
/// <summary>
/// Get string representation of value and unit.
/// </summary>
/// <param name="format">String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively."</param>
/// <param name="args">Arguments for string format. Value and unit are implicitly included as arguments 0 and 1.</param>
/// <returns>String representation.</returns>
/// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentUICulture" /> if null.</param>
[Obsolete("This method is deprecated and will be removed at a future release. Please use string.Format().")]
public string ToString(IFormatProvider? provider, [NotNull] string format, [NotNull] params object[] args)
{
if (format == null) throw new ArgumentNullException(nameof(format));
if (args == null) throw new ArgumentNullException(nameof(args));
provider = provider ?? CultureInfo.CurrentUICulture;
var value = Convert.ToDouble(Value);
var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args);
return string.Format(provider, format, formatArgs);
}
/// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/>
/// <summary>
/// Gets the string representation of this instance in the specified format string using <see cref="CultureInfo.CurrentUICulture" />.
/// </summary>
/// <param name="format">The format string.</param>
/// <returns>The string representation.</returns>
public string ToString(string format)
{
return ToString(format, CultureInfo.CurrentUICulture);
}
/// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/>
/// <summary>
/// Gets the string representation of this instance in the specified format string using the specified format provider, or <see cref="CultureInfo.CurrentUICulture" /> if null.
/// </summary>
/// <param name="format">The format string.</param>
/// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentUICulture" /> if null.</param>
/// <returns>The string representation.</returns>
public string ToString(string format, IFormatProvider? provider)
{
return QuantityFormatter.Format<LapseRateUnit>(this, format, provider);
}
#endregion
#region IConvertible Methods
TypeCode IConvertible.GetTypeCode()
{
return TypeCode.Object;
}
bool IConvertible.ToBoolean(IFormatProvider provider)
{
throw new InvalidCastException($"Converting {typeof(LapseRate)} to bool is not supported.");
}
byte IConvertible.ToByte(IFormatProvider provider)
{
return Convert.ToByte(_value);
}
char IConvertible.ToChar(IFormatProvider provider)
{
throw new InvalidCastException($"Converting {typeof(LapseRate)} to char is not supported.");
}
DateTime IConvertible.ToDateTime(IFormatProvider provider)
{
throw new InvalidCastException($"Converting {typeof(LapseRate)} to DateTime is not supported.");
}
decimal IConvertible.ToDecimal(IFormatProvider provider)
{
return Convert.ToDecimal(_value);
}
double IConvertible.ToDouble(IFormatProvider provider)
{
return Convert.ToDouble(_value);
}
short IConvertible.ToInt16(IFormatProvider provider)
{
return Convert.ToInt16(_value);
}
int IConvertible.ToInt32(IFormatProvider provider)
{
return Convert.ToInt32(_value);
}
long IConvertible.ToInt64(IFormatProvider provider)
{
return Convert.ToInt64(_value);
}
sbyte IConvertible.ToSByte(IFormatProvider provider)
{
return Convert.ToSByte(_value);
}
float IConvertible.ToSingle(IFormatProvider provider)
{
return Convert.ToSingle(_value);
}
string IConvertible.ToString(IFormatProvider provider)
{
return ToString("g", provider);
}
object IConvertible.ToType(Type conversionType, IFormatProvider provider)
{
if (conversionType == typeof(LapseRate))
return this;
else if (conversionType == typeof(LapseRateUnit))
return Unit;
else if (conversionType == typeof(QuantityType))
return LapseRate.QuantityType;
else if (conversionType == typeof(QuantityInfo))
return LapseRate.Info;
else if (conversionType == typeof(BaseDimensions))
return LapseRate.BaseDimensions;
else
throw new InvalidCastException($"Converting {typeof(LapseRate)} to {conversionType} is not supported.");
}
ushort IConvertible.ToUInt16(IFormatProvider provider)
{
return Convert.ToUInt16(_value);
}
uint IConvertible.ToUInt32(IFormatProvider provider)
{
return Convert.ToUInt32(_value);
}
ulong IConvertible.ToUInt64(IFormatProvider provider)
{
return Convert.ToUInt64(_value);
}
#endregion
}
}
| 43.909295 | 222 | 0.610339 | [
"MIT-feh"
] | AIKICo/UnitsNet | UnitsNet/GeneratedCode/Quantities/LapseRate.g.cs | 39,214 | C# |
//Problem 5. Maximal increasing sequence
//Write a program that finds the maximal increasing sequence in an array.
//Example:
//input result
//3, 2, 3, 4, 2, 2, 4 2, 3, 4
using System;
using System.Linq;
class MaximalIncreasingSequence
{
static void Main()
{
string task = "Problem 5. Maximal increasing sequence\n\nWrite a program that finds the maximal increasing sequence in an array.\nExample:\ninput result\n3, 2, 3, 4, 2, 2, 4 2, 3, 4\n";
string separator = new string('*', Console.WindowWidth);
Console.WriteLine(task);
Console.WriteLine(separator);
Console.WriteLine("Enter array(1, 2, 3, 4): ");
int[] numbers = GetsArrayFromConsole();
int maxSequence = 0;
int startIndex = 0;
int endIndex = 0;
for (int i = 0; i < numbers.Length - 1; i++)
{
int currentSequence = 1;
while (i < numbers.Length -1 && numbers[i] < numbers[i + 1])
{
currentSequence++;
i++;
}
if (currentSequence > maxSequence)
{
maxSequence = currentSequence;
endIndex = i;
startIndex = currentSequence > 1 ? endIndex - (maxSequence - 1) : endIndex;
}
}
Console.Write("Maximal sequence: ");
for (int i = startIndex; i <= endIndex; i++)
{
Console.Write("{0} ", numbers[i]);
}
Console.WriteLine();
}
private static int[] GetsArrayFromConsole()
{
string input = Console.ReadLine();
char[] separators = { ' ', ',' };
return input.Split(separators, StringSplitOptions.RemoveEmptyEntries).Select(x => int.Parse(x)).ToArray();
}
}
| 23.059701 | 203 | 0.633657 | [
"MIT"
] | SHAMMY1/Telerik-Academy | Homeworks/CSharpPartTwo/01.Arrays/Arrays-Homework/05.MaximalIncreasingSequence/MaximalIncreasingSequence.cs | 1,547 | C# |
/*
* File: MethodInfoMixin.cs
*
* Author: Akira Sugiura (urasandesu@gmail.com)
*
*
* Copyright (c) 2016 Akira Sugiura
*
* This software is MIT License.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
using System.Linq;
using System.Reflection;
namespace Urasandesu.AutoFixture.AutoMoqPrig.Mixins.System.Reflection
{
static class MethodInfoMixin
{
public static bool IsVoid(this MethodInfo method)
{
return method.ReturnType == typeof(void);
}
public static bool HasOutParameters(this MethodInfo method)
{
return method.GetParameters().Any(_ => _.IsOut);
}
public static bool HasRefParameters(this MethodInfo method)
{
return method.GetParameters().Any(_ => _.ParameterType.IsByRef && !_.IsOut);
}
}
}
| 36.055556 | 89 | 0.681561 | [
"MIT"
] | urasandesu/AutoFixture.AutoMoqPrig | AutoFixture.AutoMoqPrig/Mixins/System/Reflection/MethodInfoMixin.cs | 1,949 | C# |
using UAlbion.Api;
namespace UAlbion.Core.Events
{
[Event("e:run_renderdoc")] public class RunRenderDocEvent : EngineEvent { }
}
| 19.285714 | 79 | 0.733333 | [
"MIT"
] | BenjaminRi/ualbion | src/Core/Events/RunRenderDocEvent.cs | 137 | C# |
[CompilerGeneratedAttribute] // RVA: 0xFD850 Offset: 0xFD951 VA: 0xFD850
private sealed class TerrainUtility.TerrainMap.<>c__DisplayClass4_0 // TypeDefIndex: 3672
{
// Fields
public int groupID; // 0x10
// Methods
// RVA: 0x1B47E90 Offset: 0x1B47F91 VA: 0x1B47E90
public void .ctor() { }
// RVA: 0x1B494C0 Offset: 0x1B495C1 VA: 0x1B494C0
internal bool <CreateFromPlacement>b__0(Terrain x) { }
}
| 25.375 | 89 | 0.738916 | [
"MIT"
] | SinsofSloth/RF5-global-metadata | _no_namespace/TerrainUtility.TerrainMap.----c__DisplayClass4_0.cs | 406 | C# |
using UnityEngine;
namespace ZoroDex.SimpleCard.Data.Character
{
[CreateAssetMenu(menuName = "Data/Character")]
public class CharacterData : ScriptableObject,ICharacterData
{
[SerializeField] private Sprite artwork;
[Range(1, 16)] [SerializeField] private int attack;
[Range(1, 16)] [SerializeField] private int attacksTurn = 1;
[SerializeField] private string characterName;
[Range(1, 16)] [SerializeField] private int defense;
[SerializeField] private string description;
[SerializeField] private bool hasTaunt;
[Range(1, 16)] [SerializeField] private int health = 1;
[SerializeField] private CharacterId id;
// ------------------------------------------------------------
public int Defense => defense;
public CharacterId Id => id;
public string Name => characterName;
public string Description => description;
public Sprite Artwork => artwork;
public int Health => health;
public int Attack => attack;
public int AttacksTurn => attacksTurn;
public bool HasTaunt => hasTaunt;
}
} | 36.65625 | 71 | 0.610401 | [
"MIT"
] | led0warlpl/SimpleCard | Assets/Scripts/ZoroDex/SimpleCard/Battle/StaticData/CharacterData/CharacterData.cs | 1,175 | C# |
using System;
using System.Linq;
using Base.Core;
using Base.Defs;
using Harmony;
using PhoenixPoint.Common.Core;
using PhoenixPoint.Geoscape.Entities;
using PhoenixPoint.Geoscape.Entities.Sites;
namespace AssortedAdjustments.Patches
{
internal static class DifficultyOverrides
{
public static void Apply()
{
DefRepository defRepository = GameUtl.GameComponent<DefRepository>();
foreach (GameDifficultyLevelDef def in defRepository.DefRepositoryDef.AllDefs.OfType<GameDifficultyLevelDef>())
{
def.StartingSupplies = AssortedAdjustments.Settings.DifficultyOverrideStartingSupplies;
def.StartingMaterials = AssortedAdjustments.Settings.DifficultyOverrideStartingMaterials;
def.StartingTech = AssortedAdjustments.Settings.DifficultyOverrideStartingTech;
def.SoldierSkillPointsPerMission = AssortedAdjustments.Settings.DifficultyOverrideSoldierSkillPointsPerMission;
def.ExpConvertedToSkillpoints = AssortedAdjustments.Settings.DifficultyOverrideExpConvertedToSkillpoints;
def.MinPopulationThreshold = AssortedAdjustments.Settings.DifficultyOverrideMinPopulationThreshold;
Logger.Info($"[DifficultyOverrides_Apply] def: {def.name}, GUID: {def.Guid}, StartingSupplies: {def.StartingSupplies}, StartingMaterials: {def.StartingMaterials}, StartingTech: {def.StartingTech}, SoldierSkillPointsPerMission: {def.SoldierSkillPointsPerMission}, ExpConvertedToSkillpoints: {def.ExpConvertedToSkillpoints}, MinPopulationThreshold: {def.MinPopulationThreshold}");
}
foreach (GeoHavenDef def in defRepository.DefRepositoryDef.AllDefs.OfType<GeoHavenDef>())
{
def.StarvationDeathsPart = AssortedAdjustments.Settings.DifficultyOverrideStarvationDeathsPart;
def.StarvationMistDeathsPart = AssortedAdjustments.Settings.DifficultyOverrideStarvationMistDeathsPart;
def.StarvationDeathsFlat = AssortedAdjustments.Settings.DifficultyOverrideStarvationDeathsFlat;
def.StarvationMistDeathsFlat = AssortedAdjustments.Settings.DifficultyOverrideStarvationMistDeathsFlat;
Logger.Info($"[DifficultyOverrides_Apply] def: {def.name}, GUID: {def.Guid}, StarvationDeathsPart: {def.StarvationDeathsPart}, StarvationMistDeathsPart: {def.StarvationMistDeathsPart}, StarvationDeathsFlat: {def.StarvationDeathsFlat}, StarvationMistDeathsFlat: {def.StarvationMistDeathsFlat}");
}
foreach (GeoMistGeneratorDef def in defRepository.DefRepositoryDef.AllDefs.OfType<GeoMistGeneratorDef>())
{
def.KmPerHour = AssortedAdjustments.Settings.DifficultyOverrideMistExpansionRate;
Logger.Info($"[DifficultyOverrides_Apply] def: {def.name}, GUID: {def.Guid}, KmPerHour: {def.KmPerHour}");
}
}
// Havens don't lose population at all (essentially stopping the population census apart from destroying havens)
[HarmonyPatch(typeof(GeoHaven), "GetDyingPopulation")]
public static class GeoHaven_GetDyingPopulation_Patch
{
public static bool Prepare()
{
return AssortedAdjustments.Settings.EnableDifficultyOverrides && AssortedAdjustments.Settings.DifficultyOverrideDisableDeathByStarvation;
}
public static void Postfix(GeoHaven __instance, HavenZonesStats.HavenOnlyOutput output, ref int __result)
{
try
{
Logger.Debug($"[GeoHaven_GetDyingPopulation_POSTFIX] Disable death by starvation.");
Logger.Info($"[GeoHaven_GetDyingPopulation_POSTFIX] Haven: {__instance.Site.LocalizedSiteName}, Population: {__instance.Population}, Food: {output.Food}");
Logger.Info($"[GeoHaven_GetDyingPopulation_POSTFIX] Saving {__result} people");
__result = 0;
}
catch (Exception e)
{
Logger.Error(e);
}
}
}
}
}
| 54.24359 | 395 | 0.688253 | [
"MIT"
] | Mad-Mods-Phoenix-Point/AssortedAdjustments | Source/AssortedAdjustments/Patches/EnableDifficultyOverrides.cs | 4,233 | C# |
using System;
namespace Project
{
public class MultiparameterCalculatorAdapter : CalculatorAdapter
{
private int[] _values;
public MultiparameterCalculatorAdapter(Calculator calculator, params int[] values)
: base(calculator)
{
_values = values;
}
public override int Sum()
{
int result = _values[0];
for (int i = 1; i < _values.Length; i++)
result = _calculator.Sum(result, _values[i]);
return result;
}
public override int Sub()
{
int result = _values[0];
for (int i = 1; i < _values.Length; i++)
result = _calculator.Sub(result, _values[i]);
return result;
}
}
}
| 22.055556 | 90 | 0.521411 | [
"MIT"
] | danieldeveloper001/csharp_design_patterns | src/structural/adapter/002_concrete_internal_services/Adapter/MultiparameterCalculatorAdapter.cs | 794 | C# |
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Application.Interfaces;
using Persistence.RelationalDb;
namespace Persistence {
public static class DependencyInjection {
public static IServiceCollection AddPersistenceServices(this IServiceCollection services, IConfiguration configuration) {
services.AddDbContext<AlzaDbContext>(options => options.UseSqlServer(configuration.GetConnectionString("AlzaDb")))
.AddScoped<IDbContext>(provider => provider.GetRequiredService<AlzaDbContext>());
return services;
}
}
}
| 29.571429 | 123 | 0.819646 | [
"CC0-1.0"
] | vitptosek/AlzaCaseStudy | Src/Infrastructure/Persistence/DependencyInjection.cs | 623 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.Extensions.Logging;
namespace RolaltyCardProject.Pages
{
public class IndexModel : PageModel
{
private readonly ILogger<IndexModel> _logger;
public IndexModel(ILogger<IndexModel> logger)
{
_logger = logger;
}
public void OnGet()
{
}
}
}
| 19.615385 | 53 | 0.672549 | [
"MIT"
] | pedroesli/RoyaltyCardProject | RolaltyCardProject/RolaltyCardProject/Pages/Index.cshtml.cs | 512 | C# |
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using System;
using Chatter.CQRS;
namespace Chatter.MessageBrokers.Recovery.CircuitBreaker
{
public class CircuitBreakerOptionsBuilder
{
private int _openToHalfOpenWaitTimeInSeconds = 15;
private int _concurrentHalfOpenAttempts = 1;
private int _numberOfFailuresBeforeOpen = 5;
private int _numberOfHalfOpenSuccessesToClose = 3;
private int _secondsOpenBeforeCriticalFailureNotification = 1800;
public const string CircuitBreakerOptionsSectionName = "Chatter:MessageBrokers:Recovery:CircuitBreaker";
private readonly IServiceCollection _services;
private readonly IConfiguration _configuration;
private readonly IConfigurationSection _circuitBreakerOptionsSection;
public static CircuitBreakerOptionsBuilder Create(IServiceCollection services)
=> new CircuitBreakerOptionsBuilder(services);
private CircuitBreakerOptionsBuilder(IServiceCollection services) : this(services, null, null) { }
private CircuitBreakerOptionsBuilder(IServiceCollection services, IConfiguration configuration, IConfigurationSection circuitBreakerOptionsSection)
{
_services = services ?? throw new ArgumentNullException(nameof(services));
_configuration = configuration;
_circuitBreakerOptionsSection = circuitBreakerOptionsSection;
}
public static CircuitBreakerOptions FromConfig(IServiceCollection services, IConfiguration configuration, string circuitBreakerOptionsSectionName = CircuitBreakerOptionsSectionName)
{
var section = configuration?.GetSection(circuitBreakerOptionsSectionName);
var builder = new CircuitBreakerOptionsBuilder(services, configuration, section);
return builder.Build();
}
/// <summary>
/// Sets the time to wait in seconds before the circuit breaker can enter the half-open state from the open state. Default is 15 seconds.
/// </summary>
/// <param name="timeInSeconds">The time to wait in seconds</param>
/// <returns><see cref="CircuitBreakerOptionsBuilder"/></returns>
public CircuitBreakerOptionsBuilder SetOpenToHalfOpenWaitTime(int timeInSeconds)
{
_openToHalfOpenWaitTimeInSeconds = timeInSeconds;
return this;
}
/// <summary>
/// Sets the number of consumers allowed to enter the half-open state. Default is 1.
/// </summary>
/// <param name="numberOfAttempts">The number of concurrent consumers that can enter the half-open state</param>
/// <returns><see cref="CircuitBreakerOptionsBuilder"/></returns>
public CircuitBreakerOptionsBuilder SetConcurrentHalfOpenAttempts(int numberOfAttempts)
{
_concurrentHalfOpenAttempts = numberOfAttempts;
return this;
}
/// <summary>
/// Sets the number of failures allowed before the circuit breaker enters the open state. Default is 5.
/// </summary>
/// <param name="numberOfFailures">The number of consecutive failures allowed before circuit breaker enters the open state</param>
/// <returns><see cref="CircuitBreakerOptionsBuilder"/></returns>
public CircuitBreakerOptionsBuilder SetNumberOfFailuresBeforeOpen(int numberOfFailures)
{
_numberOfFailuresBeforeOpen = numberOfFailures;
return this;
}
/// <summary>
/// Sets the number of successes are required while the circuit breaker is in the half-open state before the circuit can be closed. This
/// ensures that services recovering from a recent failure are not overwhelmed. Default is 3.
/// </summary>
/// <param name="numberOfSuccessfulAttempts">The number of sucesses required while half-open to close the circuit</param>
/// <returns><see cref="CircuitBreakerOptionsBuilder"/></returns>
public CircuitBreakerOptionsBuilder SetNumberOfHalfOpenSuccessesBeforeClose(int numberOfSuccessfulAttempts)
{
_numberOfHalfOpenSuccessesToClose = numberOfSuccessfulAttempts;
return this;
}
/// <summary>
/// Sets the time the circuit can remain open before a <see cref="CriticalFailureEvent"/> is raised by the circuit breaker. Critical failure logic
/// should be consumer specific and defined in <see cref="IMessageHandler{CriticalFailureEvent}"/>. Default is 1800 (30 minutes).
/// </summary>
/// <param name="timeInSeconds">The time in seconds before a <see cref="CriticalFailureEvent"/> is dispatched</param>
/// <returns><see cref="CircuitBreakerOptionsBuilder"/></returns>
public CircuitBreakerOptionsBuilder SetTimeOpenBeforeRaisingCriticalFailureEvent(int timeInSeconds)
{
_secondsOpenBeforeCriticalFailureNotification = timeInSeconds;
return this;
}
public CircuitBreakerOptions Build()
{
var circuitBreakerOptions = new CircuitBreakerOptions();
if (_circuitBreakerOptionsSection != null && _circuitBreakerOptionsSection.Exists())
{
circuitBreakerOptions = _circuitBreakerOptionsSection.Get<CircuitBreakerOptions>();
_services.Configure<CircuitBreakerOptions>(_circuitBreakerOptionsSection);
}
else
{
circuitBreakerOptions.OpenToHalfOpenWaitTimeInSeconds = _openToHalfOpenWaitTimeInSeconds;
circuitBreakerOptions.ConcurrentHalfOpenAttempts = _concurrentHalfOpenAttempts;
circuitBreakerOptions.NumberOfFailuresBeforeOpen = _numberOfFailuresBeforeOpen;
circuitBreakerOptions.NumberOfHalfOpenSuccessesToClose = _numberOfHalfOpenSuccessesToClose;
circuitBreakerOptions.SecondsOpenBeforeCriticalFailureNotification = _secondsOpenBeforeCriticalFailureNotification;
}
_services.AddSingleton(circuitBreakerOptions);
return circuitBreakerOptions;
}
}
}
| 52.058824 | 189 | 0.70573 | [
"MIT"
] | brenpike/Chatter | src/Chatter.MessageBrokers/src/Chatter.MessageBrokers/Recovery/CircuitBreaker/CircuitBreakerOptionsBuilder.cs | 6,197 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using WinForms.Common.Tests;
using Xunit;
using static Interop;
using static Interop.Mshtml;
namespace System.Windows.Forms.Tests
{
[Collection("Sequential")] // workaround for WebBrowser control corrupting memory when run on multiple UI threads
public class HtmlElementTests : IClassFixture<ThreadExceptionFixture>
{
[WinFormsFact]
public async Task HtmlElement_All_Get_ReturnsExpected()
{
using var parent = new Control();
using var control = new WebBrowser
{
Parent = parent
};
const string Html = "<html><body><div id=\"id\"><h1>Header1 <strong>Strong</strong></h1><h2>Header2</h2></div></body></html>";
HtmlDocument document = await GetDocument(control, Html);
HtmlElement element = document.GetElementById("id");
HtmlElementCollection collection = element.All;
Assert.NotSame(collection, element.All);
Assert.Equal(3, collection.Count);
Assert.Equal("H1", collection[0].TagName);
Assert.Equal("STRONG", collection[1].TagName);
Assert.Equal("H2", collection[2].TagName);
}
[WinFormsFact]
public async Task HtmlElement_All_GetEmpty_ReturnsExpected()
{
using var parent = new Control();
using var control = new WebBrowser
{
Parent = parent
};
const string Html = "<html><body><div id=\"id\"></div></body></html>";
HtmlDocument document = await GetDocument(control, Html);
HtmlElement element = document.GetElementById("id");
HtmlElementCollection collection = element.All;
Assert.NotSame(collection, element.All);
Assert.Empty(collection);
}
[WinFormsFact]
public async Task HtmlElement_Document_Get_ReturnsExpected()
{
using var parent = new Control();
using var control = new WebBrowser
{
Parent = parent
};
const string Html = "<html><body><div id=\"id\"><h1>Header1 <strong>Strong</strong></h1><h2>Header2</h2></div></body></html>";
HtmlDocument document = await GetDocument(control, Html);
HtmlElement element = document.GetElementById("id");
HtmlDocument result = element.Document;
Assert.NotSame(result, element.Document);
Assert.NotSame(document, result);
Assert.Equal(document.Body.InnerHtml, result.Body.InnerHtml);
}
[WinFormsFact]
public async Task HtmlElement_CanHaveChildren_Get_ReturnsExpected()
{
using var parent = new Control();
using var control = new WebBrowser
{
Parent = parent
};
const string Html = "<html><body><div id=\"id\"></div></body></html>";
HtmlDocument document = await GetDocument(control, Html);
HtmlElement element = document.GetElementById("id");
Assert.True(element.CanHaveChildren);
}
[WinFormsFact]
public async Task HtmlElement_CanHaveChildren_GetCantHave_ReturnsExpected()
{
using var parent = new Control();
using var control = new WebBrowser
{
Parent = parent
};
const string Html = "<html><body><img id=\"id\" /></body></html>";
HtmlDocument document = await GetDocument(control, Html);
HtmlElement element = document.GetElementById("id");
Assert.False(element.CanHaveChildren);
}
[WinFormsFact]
public async Task HtmlElement_ClientRectangle_Get_ReturnsExpected()
{
using var parent = new Control();
using var control = new WebBrowser
{
Parent = parent
};
const string Html = "<html><body><div id=\"id\"></div></body></html>";
HtmlDocument document = await GetDocument(control, Html);
HtmlElement element = document.GetElementById("id");
Rectangle result = element.ClientRectangle;
Assert.Equal(Rectangle.Empty, result);
}
[WinFormsFact]
public async Task HtmlElement_Children_Get_ReturnsExpected()
{
using var parent = new Control();
using var control = new WebBrowser
{
Parent = parent
};
const string Html = "<html><body><div id=\"id\"><h1>Header1 <strong>Strong</strong></h1><h2>Header2</h2></div></body></html>";
HtmlDocument document = await GetDocument(control, Html);
HtmlElement element = document.GetElementById("id");
HtmlElementCollection collection = element.Children;
Assert.NotSame(collection, element.Children);
Assert.Equal(2, collection.Count);
Assert.Equal("H1", collection[0].TagName);
Assert.Equal("H2", collection[1].TagName);
}
[WinFormsFact]
public async Task HtmlElement_Children_GetEmpty_ReturnsExpected()
{
using var parent = new Control();
using var control = new WebBrowser
{
Parent = parent
};
const string Html = "<html><body><div id=\"id\"></div></body></html>";
HtmlDocument document = await GetDocument(control, Html);
HtmlElement element = document.GetElementById("id");
HtmlElementCollection collection = element.Children;
Assert.NotSame(collection, element.Children);
Assert.Empty(collection);
}
[WinFormsFact]
public async Task HtmlElement_DomElement_Get_ReturnsExpected()
{
using var parent = new Control();
using var control = new WebBrowser
{
Parent = parent
};
const string Html = "<html><body><div id=\"id\"></div></body></html>";
HtmlDocument document = await GetDocument(control, Html);
HtmlElement element = document.GetElementById("id");
object domElement = element.DomElement;
Assert.Same(domElement, element.DomElement);
Assert.True(domElement.GetType().IsCOMObject);
Assert.True(domElement is IHTMLDOMNode);
Assert.True(domElement is IHTMLElement);
Assert.True(domElement is IHTMLElement2);
Assert.True(domElement is IHTMLElement3);
}
[WinFormsFact]
public async Task HtmlElement_Enabled_Get_ReturnsExpected()
{
using var parent = new Control();
using var control = new WebBrowser
{
Parent = parent
};
const string Html = "<html><body><div id=\"id\"></div></body></html>";
HtmlDocument document = await GetDocument(control, Html);
HtmlElement element = document.GetElementById("id");
Assert.True(element.Enabled);
}
[WinFormsTheory]
[InlineData("true", false)]
[InlineData("false", false)]
[InlineData("Nothing", false)]
public async Task HtmlElement_Enabled_GetCustomValueOnAttribute_ReturnsExpected(string value, bool expected)
{
using var parent = new Control();
using var control = new WebBrowser
{
Parent = parent
};
string html = $"<html><body><div disabled={value} id=\"id\"></div></body></html>";
HtmlDocument document = await GetDocument(control, html);
HtmlElement element = document.GetElementById("id");
Assert.Equal(expected, element.Enabled);
}
[WinFormsTheory]
[CommonMemberData(nameof(CommonTestHelper.GetBoolTheoryData))]
public async Task HtmlElement_Enabled_GetCustomValueSet_ReturnsExpected(bool disabled)
{
using var parent = new Control();
using var control = new WebBrowser
{
Parent = parent
};
const string Html = "<html><body><div id=\"id\"></div></body></html>";
HtmlDocument document = await GetDocument(control, Html);
HtmlElement element = document.GetElementById("id");
IHTMLElement3 iHTMLElement3 = (IHTMLElement3)element.DomElement;
iHTMLElement3.SetDisabled(disabled);
Assert.Equal(!disabled, element.Enabled);
}
[WinFormsTheory]
[CommonMemberData(nameof(CommonTestHelper.GetBoolTheoryData))]
public async Task HtmlElement_Enabled_Set_GetReturnsExpected(bool value)
{
using var parent = new Control();
using var control = new WebBrowser
{
Parent = parent
};
string html = $"<html><body><div disabled={value} id=\"id\"></div></body></html>";
HtmlDocument document = await GetDocument(control, html);
HtmlElement element = document.GetElementById("id");
IHTMLElement3 iHTMLElement3 = (IHTMLElement3)element.DomElement;
element.Enabled = value;
Assert.Equal(value, element.Enabled);
Assert.Equal(!value, iHTMLElement3.GetDisabled());
// Set same.
element.Enabled = value;
Assert.Equal(value, element.Enabled);
Assert.Equal(!value, iHTMLElement3.GetDisabled());
// Set different.
element.Enabled = !value;
Assert.Equal(!value, element.Enabled);
Assert.Equal(value, iHTMLElement3.GetDisabled());
}
[WinFormsFact]
public async Task HtmlElement_FirstChild_GetEmpty_ReturnsExpected()
{
using var parent = new Control();
using var control = new WebBrowser
{
Parent = parent
};
const string Html = "<html><body><div id=\"id\"></div></body></html>";
HtmlDocument document = await GetDocument(control, Html);
HtmlElement element = document.GetElementById("id");
Assert.Null(element.FirstChild);
}
[WinFormsFact]
public async Task HtmlElement_FirstChild_Get_ReturnsExpected()
{
using var parent = new Control();
using var control = new WebBrowser
{
Parent = parent
};
const string Html = "<html><body><div id=\"id\"><h1>Header1 <strong>Strong</strong></h1><h2>Header2</h2><h3>Header3</h3></div></body></html>";
HtmlDocument document = await GetDocument(control, Html);
HtmlElement element = document.GetElementById("id");
HtmlElement result = element.FirstChild;
Assert.NotSame(result, element.FirstChild);
Assert.Equal("H1", result.TagName);
}
[WinFormsFact]
public async Task HtmlElement_Id_GetWithoutId_ReturnsExpected()
{
using var parent = new Control();
using var control = new WebBrowser
{
Parent = parent
};
const string Html = "<html><body><div id=\"id\"></div></body></html>";
HtmlDocument document = await GetDocument(control, Html);
HtmlElement element = document.Body;
Assert.Null(element.Id);
}
[WinFormsFact]
public async Task HtmlElement_Id_GetOnAttribute_ReturnsExpected()
{
using var parent = new Control();
using var control = new WebBrowser
{
Parent = parent
};
const string Html = "<html><body><div id=\"id\"></div></body></html>";
HtmlDocument document = await GetDocument(control, Html);
HtmlElement element = document.GetElementById("id");
Assert.Equal("id", element.Id);
}
[WinFormsTheory]
[InlineData(null, null)]
[InlineData("", null)]
[InlineData("id", "id")]
public async Task HtmlElement_Id_GetCustomValueSet_ReturnsExpected(string id, string expected)
{
using var parent = new Control();
using var control = new WebBrowser
{
Parent = parent
};
const string Html = "<html><body><div id=\"id\"></div></body></html>";
HtmlDocument document = await GetDocument(control, Html);
HtmlElement element = document.GetElementById("id");
IHTMLElement iHTMLElement = (IHTMLElement)element.DomElement;
iHTMLElement.SetId(id);
Assert.Equal(expected, element.Id);
}
[WinFormsTheory]
[InlineData(null, null)]
[InlineData("", null)]
[InlineData("id", "id")]
public async Task HtmlElement_Id_Set_GetReturnsExpected(string value, string expected)
{
using var parent = new Control();
using var control = new WebBrowser
{
Parent = parent
};
const string Html = "<html><body><div id=\"id\"></div></body></html>";
HtmlDocument document = await GetDocument(control, Html);
HtmlElement element = document.GetElementById("id");
IHTMLElement iHTMLElement = (IHTMLElement)element.DomElement;
element.Id = value;
Assert.Equal(expected, element.Id);
Assert.Equal(expected, iHTMLElement.GetId());
// Set same.
element.Id = value;
Assert.Equal(expected, element.Id);
Assert.Equal(expected, iHTMLElement.GetId());
}
[WinFormsFact]
public async Task HtmlElement_InnerHtml_GetEmpty_ReturnsExpected()
{
using var parent = new Control();
using var control = new WebBrowser
{
Parent = parent
};
const string Html = "<html><body><div id=\"id\"></div></body></html>";
HtmlDocument document = await GetDocument(control, Html);
HtmlElement element = document.GetElementById("id");
Assert.Null(element.InnerHtml);
}
[WinFormsFact]
public async Task HtmlElement_InnerHtml_GetOnAttribute_ReturnsExpected()
{
using var parent = new Control();
using var control = new WebBrowser
{
Parent = parent
};
const string Html = "<html><body><div id=\"id\"><p>InnerText</p></div></body></html>";
HtmlDocument document = await GetDocument(control, Html);
HtmlElement element = document.GetElementById("id");
Assert.Equal("<P>InnerText</P>", element.InnerHtml);
}
[WinFormsTheory]
[InlineData(null, null)]
[InlineData("", null)]
[InlineData("InnerText", "InnerText")]
[InlineData("<p>InnerText</p>", "<P>InnerText</P>")]
public async Task HtmlElement_InnerHtml_GetCustomValueSet_ReturnsExpected(string value, string expected)
{
using var parent = new Control();
using var control = new WebBrowser
{
Parent = parent
};
const string Html = "<html><body><div id=\"id\"></div></body></html>";
HtmlDocument document = await GetDocument(control, Html);
HtmlElement element = document.GetElementById("id");
IHTMLElement iHTMLElement = (IHTMLElement)element.DomElement;
iHTMLElement.SetInnerHTML(value);
Assert.Equal(expected, element.InnerHtml);
}
[WinFormsTheory]
[InlineData(null, null)]
[InlineData("", null)]
[InlineData("InnerText", "InnerText")]
[InlineData("<p>InnerText</p>", "<P>InnerText</P>")]
public async Task HtmlElement_InnerHtml_Set_GetReturnsExpected(string value, string expected)
{
using var parent = new Control();
using var control = new WebBrowser
{
Parent = parent
};
const string Html = "<html><body><div id=\"id\"></div></body></html>";
HtmlDocument document = await GetDocument(control, Html);
HtmlElement element = document.GetElementById("id");
IHTMLElement iHTMLElement = (IHTMLElement)element.DomElement;
element.InnerHtml = value;
Assert.Equal(expected, element.InnerHtml);
Assert.Equal(expected, iHTMLElement.GetInnerHTML());
// Set same.
element.InnerHtml = value;
Assert.Equal(expected, element.InnerHtml);
Assert.Equal(expected, iHTMLElement.GetInnerHTML());
}
[WinFormsFact]
public async Task HtmlElement_InnerHtml_SetCantHaveChildren_ThrowsNotSupportedException()
{
using var parent = new Control();
using var control = new WebBrowser
{
Parent = parent
};
const string Html = "<html><body><img id=\"id\" /></body></html>";
HtmlDocument document = await GetDocument(control, Html);
HtmlElement element = document.GetElementById("id");
Assert.Throws<NotSupportedException>(() => element.InnerHtml = "InnerText");
}
[WinFormsFact]
public async Task HtmlElement_InnerHtml_SetDocumentElement_ThrowsNotSupportedException()
{
using var parent = new Control();
using var control = new WebBrowser
{
Parent = parent
};
const string Html = "<html><body></body></html>";
HtmlDocument document = await GetDocument(control, Html);
HtmlElement element = document.Body.Parent;
Assert.Throws<NotSupportedException>(() => element.InnerHtml = "InnerHtml");
}
[WinFormsFact]
public async Task HtmlElement_InnerText_GetEmpty_ReturnsExpected()
{
using var parent = new Control();
using var control = new WebBrowser
{
Parent = parent
};
const string Html = "<html><body><div id=\"id\"></div></body></html>";
HtmlDocument document = await GetDocument(control, Html);
HtmlElement element = document.GetElementById("id");
Assert.Null(element.InnerText);
}
[WinFormsFact]
public async Task HtmlElement_InnerText_GetWithInnerText_ReturnsExpected()
{
using var parent = new Control();
using var control = new WebBrowser
{
Parent = parent
};
const string Html = "<html><body><div id=\"id\"><p>InnerText</p> <h1>MoreText</h1></div></body></html>";
HtmlDocument document = await GetDocument(control, Html);
HtmlElement element = document.GetElementById("id");
Assert.Equal($"InnerText{Environment.NewLine}MoreText", element.InnerText);
}
[WinFormsTheory]
[InlineData(null, null)]
[InlineData("", null)]
[InlineData("InnerText", "InnerText")]
[InlineData("<p>InnerText</p>", "InnerText")]
public async Task HtmlElement_InnerText_GetCustomValueSet_ReturnsExpected(string value, string expected)
{
using var parent = new Control();
using var control = new WebBrowser
{
Parent = parent
};
const string Html = "<html><body><div id=\"id\"></div></body></html>";
HtmlDocument document = await GetDocument(control, Html);
HtmlElement element = document.GetElementById("id");
IHTMLElement iHTMLElement = (IHTMLElement)element.DomElement;
iHTMLElement.SetInnerHTML(value);
Assert.Equal(expected, element.InnerText);
}
[WinFormsTheory]
[InlineData(null, null)]
[InlineData("", null)]
[InlineData("InnerText", "InnerText")]
[InlineData("<p>InnerText</p>", "<p>InnerText</p>")]
public async Task HtmlElement_InnerText_Set_GetReturnsExpected(string value, string expected)
{
using var parent = new Control();
using var control = new WebBrowser
{
Parent = parent
};
const string Html = "<html><body><div id=\"id\"></div></body></html>";
HtmlDocument document = await GetDocument(control, Html);
HtmlElement element = document.GetElementById("id");
IHTMLElement iHTMLElement = (IHTMLElement)element.DomElement;
element.InnerText = value;
Assert.Equal(expected, element.InnerText);
Assert.Equal(expected, iHTMLElement.GetInnerText());
// Set same.
element.InnerText = value;
Assert.Equal(expected, element.InnerText);
Assert.Equal(expected, iHTMLElement.GetInnerText());
}
[WinFormsFact]
public async Task HtmlElement_InnerText_SetCantHaveChildren_ThrowsNotSupportedException()
{
using var parent = new Control();
using var control = new WebBrowser
{
Parent = parent
};
const string Html = "<html><body><img id=\"id\" /></body></html>";
HtmlDocument document = await GetDocument(control, Html);
HtmlElement element = document.GetElementById("id");
Assert.Throws<NotSupportedException>(() => element.InnerText = "InnerText");
}
[WinFormsFact]
public async Task HtmlElement_InnerText_SetDocumentElement_ThrowsNotSupportedException()
{
using var parent = new Control();
using var control = new WebBrowser
{
Parent = parent
};
const string Html = "<html><body></body></html>";
HtmlDocument document = await GetDocument(control, Html);
HtmlElement element = document.Body.Parent;
Assert.Throws<NotSupportedException>(() => element.InnerText = "InnerText");
}
[WinFormsFact]
public async Task HtmlElement_Name_GetWithoutName_ReturnsExpected()
{
using var parent = new Control();
using var control = new WebBrowser
{
Parent = parent
};
const string Html = "<html><body><div id=\"id\"></div></body></html>";
HtmlDocument document = await GetDocument(control, Html);
HtmlElement element = document.Body;
Assert.Empty(element.Name);
}
[WinFormsFact]
public async Task HtmlElement_Name_GetOnAttribute_ReturnsExpected()
{
using var parent = new Control();
using var control = new WebBrowser
{
Parent = parent
};
const string Html = "<html><body><div id=\"id\" name=\"name\"></div></body></html>";
HtmlDocument document = await GetDocument(control, Html);
HtmlElement element = document.GetElementById("id");
Assert.Equal("name", element.Name);
}
[WinFormsTheory]
[CommonMemberData(nameof(CommonTestHelper.GetStringNormalizedTheoryData))]
public async Task HtmlElement_Name_GetCustomValueSet_ReturnsExpected(string id, string expected)
{
using var parent = new Control();
using var control = new WebBrowser
{
Parent = parent
};
const string Html = "<html><body><div id=\"id\"></div></body></html>";
HtmlDocument document = await GetDocument(control, Html);
HtmlElement element = document.GetElementById("id");
IHTMLElement iHTMLElement = (IHTMLElement)element.DomElement;
iHTMLElement.SetAttribute("name", id, 0);
Assert.Equal(expected, element.Name);
}
[WinFormsTheory]
[InlineData(null, "", null)]
[InlineData("", "", null)]
[InlineData("value", "value", "value")]
public async Task HtmlElement_Name_Set_GetReturnsExpected(string value, string expected, string expectedNative)
{
using var parent = new Control();
using var control = new WebBrowser
{
Parent = parent
};
const string Html = "<html><body><div id=\"id\"></div></body></html>";
HtmlDocument document = await GetDocument(control, Html);
HtmlElement element = document.GetElementById("id");
IHTMLElement iHTMLElement = (IHTMLElement)element.DomElement;
element.Name = value;
Assert.Equal(expected, element.Name);
Assert.Equal(expectedNative, iHTMLElement.GetAttribute("name", 0));
// Set same.
element.Name = value;
Assert.Equal(expected, element.Name);
Assert.Equal(expectedNative, iHTMLElement.GetAttribute("name", 0));
}
[WinFormsFact]
public async Task HtmlElement_NextSibling_GetEmpty_ReturnsExpected()
{
using var parent = new Control();
using var control = new WebBrowser
{
Parent = parent
};
const string Html = "<html><body><div id=\"id\"></div></body></html>";
HtmlDocument document = await GetDocument(control, Html);
HtmlElement element = document.GetElementById("id");
Assert.Null(element.NextSibling);
}
[WinFormsFact]
public async Task HtmlElement_NextSibling_Get_ReturnsExpected()
{
using var parent = new Control();
using var control = new WebBrowser
{
Parent = parent
};
const string Html = "<html><body><div><h1 id=\"id\">Header1 <strong>Strong</strong></h1><h2>Header2</h2><h3>Header3</h3></div></body></html>";
HtmlDocument document = await GetDocument(control, Html);
HtmlElement element = document.GetElementById("id");
HtmlElement result = element.NextSibling;
Assert.NotSame(result, element.NextSibling);
Assert.Equal("H2", result.TagName);
}
[WinFormsFact]
public async Task HtmlElement_OffsetParent_GetEmpty_ReturnsExpected()
{
using var parent = new Control();
using var control = new WebBrowser
{
Parent = parent
};
const string Html = "<html><body><div id=\"id\"></div></body></html>";
HtmlDocument document = await GetDocument(control, Html);
HtmlElement element = document.GetElementById("id");
HtmlElement result = element.OffsetParent;
Assert.NotSame(result, element.OffsetParent);
Assert.Equal("BODY", result.TagName);
Assert.Null(result.OffsetParent);
}
[WinFormsFact]
public async Task HtmlElement_OffsetParent_Get_ReturnsExpected()
{
using var parent = new Control();
using var control = new WebBrowser
{
Parent = parent
};
const string Html = "<html><body><div id=\"id\"><h1>Header1 <strong>Strong</strong></h1><h2>Header2</h2><h3>Header3</h3></div></body></html>";
HtmlDocument document = await GetDocument(control, Html);
HtmlElement element = document.GetElementById("id");
HtmlElement result = element.OffsetParent;
Assert.NotSame(result, element.OffsetParent);
Assert.Equal("BODY", result.TagName);
}
[WinFormsFact]
public async Task HtmlElement_OffsetRectangle_Get_ReturnsExpected()
{
using var parent = new Control();
using var control = new WebBrowser
{
Parent = parent
};
const string Html = "<html><body><div id=\"id\"></div></body></html>";
HtmlDocument document = await GetDocument(control, Html);
HtmlElement element = document.GetElementById("id");
Rectangle result = element.OffsetRectangle;
Assert.NotEqual(Rectangle.Empty, result);
}
[WinFormsFact]
public async Task HtmlElement_OuterHtml_GetEmpty_ReturnsExpected()
{
using var parent = new Control();
using var control = new WebBrowser
{
Parent = parent
};
const string Html = "<html><body><div id=\"id\"></div></body></html>";
HtmlDocument document = await GetDocument(control, Html);
HtmlElement element = document.GetElementById("id");
Assert.Equal($"{Environment.NewLine}<DIV id=id></DIV>", element.OuterHtml);
}
[WinFormsFact]
public async Task HtmlElement_OuterHtml_GetOnAttribute_ReturnsExpected()
{
using var parent = new Control();
using var control = new WebBrowser
{
Parent = parent
};
const string Html = "<html><body><div id=\"id\"><p>OuterText</p></div></body></html>";
HtmlDocument document = await GetDocument(control, Html);
HtmlElement element = document.GetElementById("id");
Assert.Equal($"{Environment.NewLine}<DIV id=id><P>OuterText</P></DIV>", element.OuterHtml);
}
public static IEnumerable<object[]> OuterHtml_CustomValueSet_TestData()
{
yield return new object[] { null, $"{Environment.NewLine}<DIV id=id></DIV>" };
yield return new object[] { "", $"{Environment.NewLine}<DIV id=id></DIV>" };
yield return new object[] { "OuterText", $"{Environment.NewLine}<DIV id=id>OuterText</DIV>" };
yield return new object[] { "<p>OuterText</p>", $"{Environment.NewLine}<DIV id=id><P>OuterText</P></DIV>" };
}
[WinFormsTheory]
[MemberData(nameof(OuterHtml_CustomValueSet_TestData))]
public async Task HtmlElement_OuterHtml_GetCustomValueSet_ReturnsExpected(string value, string expected)
{
using var parent = new Control();
using var control = new WebBrowser
{
Parent = parent
};
const string Html = "<html><body><div id=\"id\"></div></body></html>";
HtmlDocument document = await GetDocument(control, Html);
HtmlElement element = document.GetElementById("id");
IHTMLElement iHTMLElement = (IHTMLElement)element.DomElement;
iHTMLElement.SetInnerHTML(value);
Assert.Equal(expected, element.OuterHtml);
}
public static IEnumerable<object[]> OuterHtml_Set_TestData()
{
yield return new object[] { null, $"{Environment.NewLine}<DIV id=id></DIV>" };
yield return new object[] { "", $"{Environment.NewLine}<DIV id=id></DIV>" };
yield return new object[] { "OuterText", $"{Environment.NewLine}<DIV id=id></DIV>" };
yield return new object[] { "<p>OuterText</p>", $"{Environment.NewLine}<DIV id=id></DIV>" };
}
[WinFormsTheory]
[MemberData(nameof(OuterHtml_Set_TestData))]
public async Task HtmlElement_OuterHtml_Set_GetReturnsExpected(string value, string expected)
{
using var parent = new Control();
using var control = new WebBrowser
{
Parent = parent
};
const string Html = "<html><body><div id=\"id\"></div></body></html>";
HtmlDocument document = await GetDocument(control, Html);
HtmlElement element = document.GetElementById("id");
IHTMLElement iHTMLElement = (IHTMLElement)element.DomElement;
element.OuterHtml = value;
Assert.Equal(expected, element.OuterHtml);
Assert.Equal(expected, iHTMLElement.GetOuterHTML());
// Set same.
element.OuterHtml = value;
Assert.Equal(expected, element.OuterHtml);
Assert.Equal(expected, iHTMLElement.GetOuterHTML());
}
[WinFormsFact]
public async Task HtmlElement_OuterHtml_SetDocumentElement_ThrowsNotSupportedException()
{
using var parent = new Control();
using var control = new WebBrowser
{
Parent = parent
};
const string Html = "<html><body></body></html>";
HtmlDocument document = await GetDocument(control, Html);
HtmlElement element = document.Body.Parent;
Assert.Throws<NotSupportedException>(() => element.OuterHtml = "OuterHtml");
}
[WinFormsFact]
public async Task HtmlElement_OuterText_GetEmpty_ReturnsExpected()
{
using var parent = new Control();
using var control = new WebBrowser
{
Parent = parent
};
const string Html = "<html><body><div id=\"id\"></div></body></html>";
HtmlDocument document = await GetDocument(control, Html);
HtmlElement element = document.GetElementById("id");
Assert.Null(element.OuterText);
}
[WinFormsFact]
public async Task HtmlElement_OuterText_GetWithOuterText_ReturnsExpected()
{
using var parent = new Control();
using var control = new WebBrowser
{
Parent = parent
};
const string Html = "<html><body><div id=\"id\"><p>OuterText</p> <h1>MoreText</h1></div></body></html>";
HtmlDocument document = await GetDocument(control, Html);
HtmlElement element = document.GetElementById("id");
Assert.Equal($"OuterText{Environment.NewLine}MoreText", element.OuterText);
}
[WinFormsTheory]
[InlineData(null, null)]
[InlineData("", null)]
[InlineData("OuterText", "OuterText")]
[InlineData("<p>OuterText</p>", "OuterText")]
public async Task HtmlElement_OuterText_GetCustomValueSet_ReturnsExpected(string value, string expected)
{
using var parent = new Control();
using var control = new WebBrowser
{
Parent = parent
};
const string Html = "<html><body><div id=\"id\"></div></body></html>";
HtmlDocument document = await GetDocument(control, Html);
HtmlElement element = document.GetElementById("id");
IHTMLElement iHTMLElement = (IHTMLElement)element.DomElement;
iHTMLElement.SetInnerHTML(value);
Assert.Equal(expected, element.OuterText);
}
[WinFormsTheory]
[InlineData(null, null)]
[InlineData("", null)]
[InlineData("OuterText", null)]
[InlineData("<p>OuterText</p>", null)]
public async Task HtmlElement_OuterText_Set_GetReturnsExpected(string value, string expected)
{
using var parent = new Control();
using var control = new WebBrowser
{
Parent = parent
};
const string Html = "<html><body><div id=\"id\"></div></body></html>";
HtmlDocument document = await GetDocument(control, Html);
HtmlElement element = document.GetElementById("id");
IHTMLElement iHTMLElement = (IHTMLElement)element.DomElement;
element.OuterText = value;
Assert.Equal(expected, element.OuterText);
Assert.Equal(expected, iHTMLElement.GetOuterText());
// Set same.
element.OuterText = value;
Assert.Equal(expected, element.OuterText);
Assert.Equal(expected, iHTMLElement.GetOuterText());
}
[WinFormsFact]
public async Task HtmlElement_OuterText_SetDocumentElement_ThrowsNotSupportedException()
{
using var parent = new Control();
using var control = new WebBrowser
{
Parent = parent
};
const string Html = "<html><body></body></html>";
HtmlDocument document = await GetDocument(control, Html);
HtmlElement element = document.Body.Parent;
Assert.Throws<NotSupportedException>(() => element.OuterText = "OuterText");
}
[WinFormsFact]
public async Task HtmlElement_Parent_GetEmpty_ReturnsExpected()
{
using var parent = new Control();
using var control = new WebBrowser
{
Parent = parent
};
const string Html = "<html><body><div id=\"id\"></div></body></html>";
HtmlDocument document = await GetDocument(control, Html);
HtmlElement element = document.GetElementById("id");
HtmlElement result = element.Parent;
Assert.NotSame(result, element.Parent);
Assert.Equal("BODY", result.TagName);
HtmlElement resultParent = result.Parent;
Assert.Equal("HTML", resultParent.TagName);
Assert.Null(resultParent.Parent);
}
[WinFormsFact]
public async Task HtmlElement_Parent_Get_ReturnsExpected()
{
using var parent = new Control();
using var control = new WebBrowser
{
Parent = parent
};
const string Html = "<html><body><div id=\"id\"><h1>Header1 <strong>Strong</strong></h1><h2>Header2</h2><h3>Header3</h3></div></body></html>";
HtmlDocument document = await GetDocument(control, Html);
HtmlElement element = document.GetElementById("id");
HtmlElement result = element.Parent;
Assert.NotSame(result, element.Parent);
Assert.Equal("BODY", result.TagName);
}
[WinFormsFact]
public async Task HtmlElement_ScrollLeft_Get_ReturnsExpected()
{
using var parent = new Control();
using var control = new WebBrowser
{
Parent = parent
};
const string Html = "<html><body><div id=\"id\"></div></body></html>";
HtmlDocument document = await GetDocument(control, Html);
HtmlElement element = document.GetElementById("id");
Assert.Equal(0, element.ScrollLeft);
}
[WinFormsTheory]
[InlineData(-1)]
[InlineData(0)]
[InlineData(1)]
public async Task HtmlElement_ScrollLeft_GetCustomValueSet_ReturnsExpected(int value)
{
using var parent = new Control();
using var control = new WebBrowser
{
Parent = parent
};
const string Html = "<html><body><div id=\"id\"></div></body></html>";
HtmlDocument document = await GetDocument(control, Html);
HtmlElement element = document.GetElementById("id");
IHTMLElement2 iHTMLElement2 = (IHTMLElement2)element.DomElement;
iHTMLElement2.SetScrollLeft(value);
Assert.Equal(0, element.ScrollLeft);
}
[WinFormsTheory]
[InlineData(-1)]
[InlineData(0)]
[InlineData(1)]
public async Task HtmlElement_ScrollLeft_Set_GetReturnsExpected(int value)
{
using var parent = new Control();
using var control = new WebBrowser
{
Parent = parent
};
const string Html = "<html><body><div id=\"id\"></div></body></html>";
HtmlDocument document = await GetDocument(control, Html);
HtmlElement element = document.GetElementById("id");
IHTMLElement2 iHTMLElement2 = (IHTMLElement2)element.DomElement;
element.ScrollLeft = value;
Assert.Equal(0, element.ScrollLeft);
Assert.Equal(0, iHTMLElement2.GetScrollLeft());
// Set same.
element.ScrollLeft = value;
Assert.Equal(0, element.ScrollLeft);
Assert.Equal(0, iHTMLElement2.GetScrollLeft());
}
[WinFormsFact]
public async Task HtmlElement_ScrollRectangle_Get_ReturnsExpected()
{
using var parent = new Control();
using var control = new WebBrowser
{
Parent = parent
};
const string Html = "<html><body><div id=\"id\"></div></body></html>";
HtmlDocument document = await GetDocument(control, Html);
HtmlElement element = document.GetElementById("id");
Rectangle result = element.ScrollRectangle;
Assert.NotEqual(Rectangle.Empty, result);
Assert.Equal(element.ScrollLeft, result.X);
Assert.Equal(element.ScrollTop, result.Y);
}
[WinFormsFact]
public async Task HtmlElement_ScrollTop_Get_ReturnsExpected()
{
using var parent = new Control();
using var control = new WebBrowser
{
Parent = parent
};
const string Html = "<html><body><div id=\"id\"></div></body></html>";
HtmlDocument document = await GetDocument(control, Html);
HtmlElement element = document.GetElementById("id");
Assert.Equal(0, element.ScrollTop);
}
[WinFormsTheory]
[InlineData(-1)]
[InlineData(0)]
[InlineData(1)]
public async Task HtmlElement_ScrollTop_GetCustomValueSet_ReturnsExpected(int value)
{
using var parent = new Control();
using var control = new WebBrowser
{
Parent = parent
};
const string Html = "<html><body><div id=\"id\"></div></body></html>";
HtmlDocument document = await GetDocument(control, Html);
HtmlElement element = document.GetElementById("id");
IHTMLElement2 iHTMLElement2 = (IHTMLElement2)element.DomElement;
iHTMLElement2.SetScrollTop(value);
Assert.Equal(0, element.ScrollTop);
}
[WinFormsTheory]
[InlineData(-1)]
[InlineData(0)]
[InlineData(1)]
public async Task HtmlElement_ScrollTop_Set_GetReturnsExpected(int value)
{
using var parent = new Control();
using var control = new WebBrowser
{
Parent = parent
};
const string Html = "<html><body><div id=\"id\"></div></body></html>";
HtmlDocument document = await GetDocument(control, Html);
HtmlElement element = document.GetElementById("id");
IHTMLElement2 iHTMLElement2 = (IHTMLElement2)element.DomElement;
element.ScrollTop = value;
Assert.Equal(0, element.ScrollTop);
Assert.Equal(0, iHTMLElement2.GetScrollTop());
// Set same.
element.ScrollTop = value;
Assert.Equal(0, element.ScrollTop);
Assert.Equal(0, iHTMLElement2.GetScrollTop());
}
[WinFormsFact]
public async Task HtmlElement_Style_GetWithoutStyle_ReturnsExpected()
{
using var parent = new Control();
using var control = new WebBrowser
{
Parent = parent
};
const string Html = "<html><body><div id=\"id\"></div></body></html>";
HtmlDocument document = await GetDocument(control, Html);
HtmlElement element = document.Body;
Assert.Null(element.Style);
}
[WinFormsTheory]
[InlineData("", null)]
[InlineData("style", null)]
[InlineData("name:value", "name: value")]
[InlineData("name1:value1;name2:value2", "name1: value1; name2: value2")]
public async Task HtmlElement_Style_GetOnAttribute_ReturnsExpected(string style, string expected)
{
using var parent = new Control();
using var control = new WebBrowser
{
Parent = parent
};
string html = $"<html><body><div id=\"id\" style=\"{style}\"></div></body></html>";
HtmlDocument document = await GetDocument(control, html);
HtmlElement element = document.GetElementById("id");
Assert.Equal(expected, element.Style);
}
[WinFormsTheory]
[InlineData("", null)]
[InlineData("style", null)]
[InlineData("name:value", "name: value")]
[InlineData("name1:value1;name2:value2", "name1: value1; name2: value2")]
public async Task HtmlElement_Style_GetCustomValueSet_ReturnsExpected(string style, string expected)
{
using var parent = new Control();
using var control = new WebBrowser
{
Parent = parent
};
const string Html = "<html><body><div id=\"id\"></div></body></html>";
HtmlDocument document = await GetDocument(control, Html);
HtmlElement element = document.GetElementById("id");
IHTMLElement iHTMLElement = (IHTMLElement)element.DomElement;
iHTMLElement.GetStyle().SetCssText(style);
Assert.Equal(expected, element.Style);
}
[WinFormsTheory]
[InlineData(null, null)]
[InlineData("", null)]
[InlineData("value", null)]
[InlineData("name:value", "name: value")]
[InlineData("name1:value1;name2:value2", "name1: value1; name2: value2")]
public async Task HtmlElement_Style_Set_GetReturnsExpected(string value, string expected)
{
using var parent = new Control();
using var control = new WebBrowser
{
Parent = parent
};
const string Html = "<html><body><div id=\"id\"></div></body></html>";
HtmlDocument document = await GetDocument(control, Html);
HtmlElement element = document.GetElementById("id");
IHTMLElement iHTMLElement = (IHTMLElement)element.DomElement;
element.Style = value;
Assert.Equal(expected, element.Style);
Assert.Equal(expected, iHTMLElement.GetStyle().GetCssText());
// Set same.
element.Style = value;
Assert.Equal(expected, element.Style);
Assert.Equal(expected, iHTMLElement.GetStyle().GetCssText());
}
[WinFormsFact]
public async Task HtmlElement_TabIndex_Get_ReturnsExpected()
{
using var parent = new Control();
using var control = new WebBrowser
{
Parent = parent
};
const string Html = "<html><body><div id=\"id\"></div></body></html>";
HtmlDocument document = await GetDocument(control, Html);
HtmlElement element = document.GetElementById("id");
Assert.Equal(0, element.TabIndex);
}
[WinFormsTheory]
[InlineData(-1)]
[InlineData(0)]
[InlineData(1)]
public async Task HtmlElement_TabIndex_GetCustomValueSet_ReturnsExpected(short value)
{
using var parent = new Control();
using var control = new WebBrowser
{
Parent = parent
};
const string Html = "<html><body><div id=\"id\"></div></body></html>";
HtmlDocument document = await GetDocument(control, Html);
HtmlElement element = document.GetElementById("id");
IHTMLElement2 iHTMLElement2 = (IHTMLElement2)element.DomElement;
iHTMLElement2.SetTabIndex(value);
Assert.Equal(value, element.TabIndex);
}
[WinFormsTheory]
[InlineData(-1)]
[InlineData(0)]
[InlineData(1)]
public async Task HtmlElement_TabIndex_Set_GetReturnsExpected(short value)
{
using var parent = new Control();
using var control = new WebBrowser
{
Parent = parent
};
const string Html = "<html><body><div id=\"id\"></div></body></html>";
HtmlDocument document = await GetDocument(control, Html);
HtmlElement element = document.GetElementById("id");
IHTMLElement2 iHTMLElement2 = (IHTMLElement2)element.DomElement;
element.TabIndex = value;
Assert.Equal(value, element.TabIndex);
Assert.Equal(value, iHTMLElement2.GetTabIndex());
// Set same.
element.TabIndex = value;
Assert.Equal(value, element.TabIndex);
Assert.Equal(value, iHTMLElement2.GetTabIndex());
}
[WinFormsFact]
public async Task HtmlElement_TagName_Get_ReturnsExpected()
{
using var parent = new Control();
using var control = new WebBrowser
{
Parent = parent
};
const string Html = "<html><body><div id=\"id\"></div></body></html>";
HtmlDocument document = await GetDocument(control, Html);
HtmlElement element = document.GetElementById("id");
Assert.Equal("DIV", element.TagName);
}
[WinFormsFact]
public async Task HtmlElement_AppendChild_InvokeEmpty_Success()
{
using var parent = new Control();
using var control = new WebBrowser
{
Parent = parent
};
const string Html = "<html><body><div id=\"id\"></div></body></html>";
HtmlDocument document = await GetDocument(control, Html);
HtmlElement element = document.GetElementById("id");
HtmlElement newElement1 = document.CreateElement("h1");
HtmlElement newElement2 = document.CreateElement("h2");
HtmlElement newElement3 = document.CreateElement("h3");
element.AppendChild(newElement1);
Assert.Single(element.All);
Assert.Equal("H1", element.All[0].TagName);
element.AppendChild(newElement2);
Assert.Equal(2, element.All.Count);
Assert.Equal("H1", element.All[0].TagName);
Assert.Equal("H2", element.All[1].TagName);
element.AppendChild(newElement3);
Assert.Equal(3, element.All.Count);
Assert.Equal("H1", element.All[0].TagName);
Assert.Equal("H2", element.All[1].TagName);
Assert.Equal("H3", element.All[2].TagName);
}
[WinFormsFact]
public async Task HtmlElement_AppendChild_InvokeNotEmptyEmpty_Success()
{
using var parent = new Control();
using var control = new WebBrowser
{
Parent = parent
};
const string Html = "<html><body><div id=\"id\"><p>InnerText</p><strong>StrongText</strong></div></body></html>";
HtmlDocument document = await GetDocument(control, Html);
HtmlElement element = document.GetElementById("id");
HtmlElement newElement1 = document.CreateElement("h1");
HtmlElement newElement2 = document.CreateElement("h2");
HtmlElement newElement3 = document.CreateElement("h3");
element.AppendChild(newElement1);
Assert.Equal(3, element.All.Count);
Assert.Equal("P", element.All[0].TagName);
Assert.Equal("STRONG", element.All[1].TagName);
Assert.Equal("H1", element.All[2].TagName);
element.AppendChild(newElement2);
Assert.Equal(4, element.All.Count);
Assert.Equal("P", element.All[0].TagName);
Assert.Equal("STRONG", element.All[1].TagName);
Assert.Equal("H1", element.All[2].TagName);
Assert.Equal("H2", element.All[3].TagName);
element.AppendChild(newElement3);
Assert.Equal(5, element.All.Count);
Assert.Equal("P", element.All[0].TagName);
Assert.Equal("STRONG", element.All[1].TagName);
Assert.Equal("H1", element.All[2].TagName);
Assert.Equal("H2", element.All[3].TagName);
Assert.Equal("H3", element.All[4].TagName);
}
[WinFormsFact]
public async Task HtmlElement_AppendChild_NullNewElement_ThrowsNullReferenceException()
{
using var parent = new Control();
using var control = new WebBrowser
{
Parent = parent
};
const string Html = "<html><body><div id=\"id\"><h1>Header1 <strong>Strong</strong></h1><h2>Header2</h2></div></body></html>";
HtmlDocument document = await GetDocument(control, Html);
HtmlElement element = document.GetElementById("id");
Assert.Throws<NullReferenceException>(() => element.AppendChild(null));
}
[WinFormsTheory]
[InlineData("eventName")]
[InlineData("onclick")]
public async Task HtmlElement_AttachEventHandler_AttachDetach_Success(string eventName)
{
using var parent = new Control();
using var control = new WebBrowser
{
Parent = parent
};
const string Html = "<html><body><div id=\"id\"><h1>Header1 <strong>Strong</strong></h1><h2>Header2</h2></div></body></html>";
HtmlDocument document = await GetDocument(control, Html);
HtmlElement element = document.GetElementById("id");
int callCount = 0;
void handler(object sender, EventArgs e) => callCount++;
element.AttachEventHandler(eventName, handler);
Assert.Equal(0, callCount);
// Attach again.
element.AttachEventHandler(eventName, handler);
Assert.Equal(0, callCount);
document.DetachEventHandler(eventName, handler);
Assert.Equal(0, callCount);
}
[WinFormsTheory]
[InlineData("onclick", true)]
[InlineData("ondblclick", true)]
[InlineData("onkeypress", true)]
[InlineData("onkeydown", true)]
[InlineData("onkeyup", true)]
[InlineData("onmouseover", false)]
[InlineData("onmousemove", true)]
[InlineData("onmousedown", true)]
[InlineData("onmouseup", true)]
[InlineData("onmouseenter", true)]
[InlineData("onmouseleave", true)]
[InlineData("onerrorupdate", true)]
[InlineData("onfocus", true)]
[InlineData("ondrag", true)]
[InlineData("ondragend", true)]
[InlineData("ondragleave", true)]
[InlineData("ondragover", true)]
[InlineData("onfocusin", true)]
[InlineData("onfocusout", true)]
[InlineData("onblur", true)]
[InlineData("onresizestart", true)]
[InlineData("onhelp", true)]
[InlineData("onselectstart", true)]
[InlineData("ondragstart", true)]
[InlineData("onbeforeupdate", true)]
[InlineData("onrowexit", true)]
[InlineData("ondragenter", true)]
[InlineData("ondrop", true)]
[InlineData("onbeforecut", true)]
[InlineData("oncut", true)]
[InlineData("onbeforecopy", true)]
[InlineData("oncopy", true)]
[InlineData("onbeforepaste", true)]
[InlineData("onpaste", true)]
[InlineData("oncontextmenu", true)]
[InlineData("onbeforedeactivate", true)]
[InlineData("onbeforeactivate", true)]
[InlineData("oncontrolselect", true)]
[InlineData("onmovestart", true)]
[InlineData("onmousewheel", true)]
public async Task HtmlElement_AttachEventHandler_InvokeNormalElement_Success(string eventName, bool expectedResult)
{
using var parent = new Control();
using var control = new WebBrowser
{
Parent = parent
};
const string Html = "<html><body><div id=\"id\"></div></body></html>";
HtmlDocument document = await GetDocument(control, Html);
HtmlElement element = document.GetElementById("id");
IHTMLElement3 iHTMLElement3 = (IHTMLElement3)element.DomElement;
int callCount = 0;
void handler(object sender, EventArgs e)
{
Assert.NotSame(document, sender);
Assert.Same(EventArgs.Empty, e);
callCount++;
}
element.AttachEventHandler(eventName, handler);
Assert.Equal(0, callCount);
Assert.Equal(expectedResult, iHTMLElement3.FireEvent(eventName, IntPtr.Zero));
Assert.Equal(1, callCount);
document.DetachEventHandler(eventName, handler);
Assert.Equal(1, callCount);
}
[WinFormsTheory]
[InlineData("onsubmit")]
[InlineData("onreset")]
public async Task HtmlElement_AttachEventHandler_InvokeForm_Success(string eventName)
{
using var parent = new Control();
using var control = new WebBrowser
{
Parent = parent
};
const string Html = "<html><body><form id=\"id\"></form></body></html>";
HtmlDocument document = await GetDocument(control, Html);
HtmlElement element = document.GetElementById("id");
IHTMLElement3 iHTMLElement3 = (IHTMLElement3)element.DomElement;
int callCount = 0;
void handler(object sender, EventArgs e)
{
Assert.NotSame(document, sender);
Assert.Same(EventArgs.Empty, e);
callCount++;
}
element.AttachEventHandler(eventName, handler);
Assert.Equal(0, callCount);
Assert.True(iHTMLElement3.FireEvent(eventName, IntPtr.Zero));
Assert.Equal(1, callCount);
document.DetachEventHandler(eventName, handler);
Assert.Equal(1, callCount);
}
[WinFormsTheory]
[InlineData("onchange")]
public async Task HtmlElement_AttachEventHandler_InvokeSelect_Success(string eventName)
{
using var parent = new Control();
using var control = new WebBrowser
{
Parent = parent
};
const string Html = "<html><body><select id=\"id\"></select></body></html>";
HtmlDocument document = await GetDocument(control, Html);
HtmlElement element = document.GetElementById("id");
IHTMLElement3 iHTMLElement3 = (IHTMLElement3)element.DomElement;
int callCount = 0;
void handler(object sender, EventArgs e)
{
Assert.NotSame(document, sender);
Assert.Same(EventArgs.Empty, e);
callCount++;
}
element.AttachEventHandler(eventName, handler);
Assert.Equal(0, callCount);
Assert.True(iHTMLElement3.FireEvent(eventName, IntPtr.Zero));
Assert.Equal(1, callCount);
document.DetachEventHandler(eventName, handler);
Assert.Equal(1, callCount);
}
[WinFormsFact]
public async Task HtmlElement_AttachEventHandler_EmptyEventName_ThrowsCOMException()
{
using var parent = new Control();
using var control = new WebBrowser
{
Parent = parent
};
const string Html = "<html><body><div id=\"id\"></div></body></html>";
HtmlDocument document = await GetDocument(control, Html);
HtmlElement element = document.GetElementById("id");
int callCount = 0;
void handler(object sender, EventArgs e) => callCount++;
COMException ex = Assert.Throws<COMException>(() => element.AttachEventHandler(string.Empty, handler));
Assert.Equal(HRESULT.DISP_E_UNKNOWNNAME, (HRESULT)ex.HResult);
Assert.Equal(0, callCount);
}
[WinFormsFact]
public async Task HtmlElement_AttachEventHandler_NullEventName_ThrowsArgumentException()
{
using var parent = new Control();
using var control = new WebBrowser
{
Parent = parent
};
const string Html = "<html><body><div id=\"id\"></div></body></html>";
HtmlDocument document = await GetDocument(control, Html);
HtmlElement element = document.GetElementById("id");
int callCount = 0;
void handler(object sender, EventArgs e) => callCount++;
element.AttachEventHandler(null, handler);
Assert.Equal(0, callCount);
}
[WinFormsTheory]
[InlineData("eventName")]
[InlineData("onclick")]
public async Task HtmlElement_DetachEventHandler_AttachDetach_Success(string eventName)
{
using var parent = new Control();
using var control = new WebBrowser
{
Parent = parent
};
const string Html = "<html><body><div id=\"id\"></div></body></html>";
HtmlDocument document = await GetDocument(control, Html);
HtmlElement element = document.GetElementById("id");
int callCount = 0;
void handler(object sender, EventArgs e) => callCount++;
element.DetachEventHandler(eventName, handler);
Assert.Equal(0, callCount);
element.DetachEventHandler(eventName, handler);
Assert.Equal(0, callCount);
element.DetachEventHandler(eventName, handler);
Assert.Equal(0, callCount);
// Detach again.
element.DetachEventHandler(eventName, handler);
Assert.Equal(0, callCount);
}
[WinFormsFact]
public async Task HtmlElement_DetachEventHandler_EmptyEventName_ThrowsCOMException()
{
using var parent = new Control();
using var control = new WebBrowser
{
Parent = parent
};
const string Html = "<html><body><div id=\"id\"></div></body></html>";
HtmlDocument document = await GetDocument(control, Html);
HtmlElement element = document.GetElementById("id");
int callCount = 0;
void handler(object sender, EventArgs e) => callCount++;
element.DetachEventHandler(string.Empty, handler);
Assert.Equal(0, callCount);
}
[WinFormsFact]
public async Task HtmlElement_DetachEventHandler_NullEventName_ThrowsArgumentException()
{
using var parent = new Control();
using var control = new WebBrowser
{
Parent = parent
};
const string Html = "<html><body><div id=\"id\"></div></body></html>";
HtmlDocument document = await GetDocument(control, Html);
HtmlElement element = document.GetElementById("id");
int callCount = 0;
void handler(object sender, EventArgs e) => callCount++;
element.DetachEventHandler(null, handler);
Assert.Equal(0, callCount);
}
[WinFormsFact]
public async Task HtmlElement_Equals_Invoke_ReturnsExpected()
{
using var parent = new Control();
using var control = new WebBrowser
{
Parent = parent
};
const string Html = "<html><body><div id=\"id1\"></div><div id=\"id2\"></div></body></html>";
HtmlDocument document = await GetDocument(control, Html);
HtmlElement element1 = document.GetElementById("id1");
HtmlElement element2 = document.GetElementById("id1");
HtmlElement element3 = document.GetElementById("id2");
Assert.True(element1.Equals(element1));
Assert.True(element1.Equals(element2));
Assert.False(element1.Equals(element3));
Assert.False(element1.Equals(new object()));
Assert.False(element1.Equals(null));
}
[WinFormsFact]
public async Task HtmlElement_Focus_Invoke_Success()
{
using var parent = new Control();
using var control = new WebBrowser
{
Parent = parent
};
const string Html = "<html><body><div id=\"id\"><h1>Header1 <strong>Strong</strong></h1><h2>Header2</h2></div></body></html>";
HtmlDocument document = await GetDocument(control, Html);
HtmlElement element = document.GetElementById("id");
element.Focus();
// Call again.
element.Focus();
}
[WinFormsFact]
public async Task HtmlElement_GetAttribute_InvokeEmpty_ReturnsExpected()
{
using var parent = new Control();
using var control = new WebBrowser
{
Parent = parent
};
const string Html = "<html><body></body></html>";
HtmlDocument document = await GetDocument(control, Html);
HtmlElement element = document.Body;
Assert.Empty(element.GetAttribute("NoSuchAttribute"));
Assert.Empty(element.GetAttribute(""));
}
[WinFormsFact]
public async Task HtmlElement_GetAttribute_InvokeCustomAttributeSet_ReturnsExpected()
{
using var parent = new Control();
using var control = new WebBrowser
{
Parent = parent
};
const string Html = "<html><body></body></html>";
HtmlDocument document = await GetDocument(control, Html);
HtmlElement element = document.Body;
IHTMLElement iHTMLElement = (IHTMLElement)element.DomElement;
iHTMLElement.SetAttribute("id", "id", 1);
iHTMLElement.SetAttribute("customAttribute", "value", 1);
Assert.Equal("id", element.GetAttribute("id"));
Assert.Equal("value", element.GetAttribute("customAttribute"));
Assert.Equal("value", element.GetAttribute("CUSTOMATTRIBUTE"));
Assert.Empty(element.GetAttribute("noValue"));
Assert.Empty(element.GetAttribute("NoSuchAttribute"));
Assert.Empty(element.GetAttribute(""));
}
[WinFormsFact]
public async Task HtmlElement_GetAttribute_InvokeWithAttributes_ReturnsExpected()
{
using var parent = new Control();
using var control = new WebBrowser
{
Parent = parent
};
const string Html = "<html><body><div id=\"id\" customAttribute=\"value\" noValue=\"\"></div></body></html>";
HtmlDocument document = await GetDocument(control, Html);
HtmlElement element = document.GetElementById("id");
Assert.Equal("id", element.GetAttribute("id"));
Assert.Equal("value", element.GetAttribute("customAttribute"));
Assert.Equal("value", element.GetAttribute("CUSTOMATTRIBUTE"));
Assert.Empty(element.GetAttribute("noValue"));
Assert.Empty(element.GetAttribute("NoSuchAttribute"));
Assert.Empty(element.GetAttribute(""));
}
[WinFormsFact]
public async Task HtmlElement_GetAttribute_NullAttributeName_ThrowsArgumentException()
{
using var parent = new Control();
using var control = new WebBrowser
{
Parent = parent
};
const string Html = "<html><body><div id=\"id\"></div></body></html>";
HtmlDocument document = await GetDocument(control, Html);
HtmlElement element = document.GetElementById("id");
Assert.Throws<ArgumentException>(null, () => element.GetAttribute(null));
}
[WinFormsFact]
public async Task HtmlElement_GetElementsByTagName_Invoke_ReturnsExpected()
{
using var parent = new Control();
using var control = new WebBrowser
{
Parent = parent
};
const string Html = "<html><body><div id=\"id\"><img id=\"img1\" /><img id=\"img2\" /><a id=\"link1\">Href</a><a id=\"link2\">Href</a><form id=\"form1\"></form><form id=\"form2\"></form></div><form id=\"form3\"></form></body></html>";
HtmlDocument document = await GetDocument(control, Html);
HtmlElement element = document.GetElementById("id");
HtmlElementCollection collection = element.GetElementsByTagName("form");
Assert.NotSame(collection, element.GetElementsByTagName("form"));
Assert.Equal(2, collection.Count);
Assert.Equal("FORM", collection[0].TagName);
Assert.Equal("form1", collection[0].GetAttribute("id"));
Assert.Equal("FORM", collection[1].TagName);
Assert.Equal("form2", collection[1].GetAttribute("id"));
Assert.Empty(element.GetElementsByTagName("NoSuchTagName"));
Assert.Empty(element.GetElementsByTagName(""));
}
[WinFormsFact]
public async Task HtmlElement_GetElementsByTagName_NullTagName_ThrowsArgumentException()
{
using var parent = new Control();
using var control = new WebBrowser
{
Parent = parent
};
const string Html = "<html><body><div id=\"id\"></div></body></html>";
HtmlDocument document = await GetDocument(control, Html);
HtmlElement element = document.GetElementById("id");
Assert.Throws<ArgumentException>(null, () => element.GetElementsByTagName(null));
}
[WinFormsFact]
public async Task HtmlElement_GetHashCode_Invoke_ReturnsExpected()
{
using var parent = new Control();
using var control = new WebBrowser
{
Parent = parent
};
const string Html = "<html><body><div id=\"id1\"></div><div id=\"id2\"></div></body></html>";
HtmlDocument document = await GetDocument(control, Html);
HtmlElement element1 = document.GetElementById("id1");
HtmlElement element2 = document.GetElementById("id1");
HtmlElement element3 = document.GetElementById("id2");
Assert.NotEqual(0, element1.GetHashCode());
Assert.Equal(element1.GetHashCode(), element1.GetHashCode());
Assert.Equal(element1.GetHashCode(), element2.GetHashCode());
Assert.NotEqual(element1.GetHashCode(), element3.GetHashCode());
}
[WinFormsFact]
public async Task HtmlElement_InsertAdjacentElement_InvokeEmptyBeforeBegin_Success()
{
using var parent = new Control();
using var control = new WebBrowser
{
Parent = parent
};
const string Html = "<html><body><div id=\"id\"></div></body></html>";
HtmlDocument document = await GetDocument(control, Html);
HtmlElement element = document.GetElementById("id");
HtmlElement newElement1 = document.CreateElement("h1");
HtmlElement newElement2 = document.CreateElement("h2");
HtmlElement newElement3 = document.CreateElement("h3");
element.InsertAdjacentElement(HtmlElementInsertionOrientation.BeforeBegin, newElement1);
Assert.Empty(element.All);
Assert.Equal(2, element.Parent.Children.Count);
Assert.Equal("H1", element.Parent.Children[0].TagName);
Assert.Equal("DIV", element.Parent.Children[1].TagName);
element.InsertAdjacentElement(HtmlElementInsertionOrientation.BeforeBegin, newElement2);
Assert.Empty(element.All);
Assert.Equal(3, element.Parent.Children.Count);
Assert.Equal("H1", element.Parent.Children[0].TagName);
Assert.Equal("H2", element.Parent.Children[1].TagName);
Assert.Equal("DIV", element.Parent.Children[2].TagName);
element.InsertAdjacentElement(HtmlElementInsertionOrientation.BeforeBegin, newElement3);
Assert.Empty(element.All);
Assert.Equal(4, element.Parent.Children.Count);
Assert.Equal("H1", element.Parent.Children[0].TagName);
Assert.Equal("H2", element.Parent.Children[1].TagName);
Assert.Equal("H3", element.Parent.Children[2].TagName);
Assert.Equal("DIV", element.Parent.Children[3].TagName);
}
[WinFormsFact]
public async Task HtmlElement_InsertAdjacentElement_InvokeNotEmptyBeforeBegin_Success()
{
using var parent = new Control();
using var control = new WebBrowser
{
Parent = parent
};
const string Html = "<html><body><div id=\"id\"><p>InnerText</p><strong>StrongText</strong></div></body></html>";
HtmlDocument document = await GetDocument(control, Html);
HtmlElement element = document.GetElementById("id");
HtmlElement newElement1 = document.CreateElement("h1");
HtmlElement newElement2 = document.CreateElement("h2");
HtmlElement newElement3 = document.CreateElement("h3");
element.InsertAdjacentElement(HtmlElementInsertionOrientation.BeforeBegin, newElement1);
Assert.Equal(2, element.All.Count);
Assert.Equal("P", element.All[0].TagName);
Assert.Equal("STRONG", element.All[1].TagName);
Assert.Equal(2, element.Parent.Children.Count);
Assert.Equal("H1", element.Parent.Children[0].TagName);
Assert.Equal("DIV", element.Parent.Children[1].TagName);
element.InsertAdjacentElement(HtmlElementInsertionOrientation.BeforeBegin, newElement2);
Assert.Equal(2, element.All.Count);
Assert.Equal("P", element.All[0].TagName);
Assert.Equal("STRONG", element.All[1].TagName);
Assert.Equal(3, element.Parent.Children.Count);
Assert.Equal("H1", element.Parent.Children[0].TagName);
Assert.Equal("H2", element.Parent.Children[1].TagName);
Assert.Equal("DIV", element.Parent.Children[2].TagName);
element.InsertAdjacentElement(HtmlElementInsertionOrientation.BeforeBegin, newElement3);
Assert.Equal(2, element.All.Count);
Assert.Equal("P", element.All[0].TagName);
Assert.Equal("STRONG", element.All[1].TagName);
Assert.Equal(4, element.Parent.Children.Count);
Assert.Equal("H1", element.Parent.Children[0].TagName);
Assert.Equal("H2", element.Parent.Children[1].TagName);
Assert.Equal("H3", element.Parent.Children[2].TagName);
Assert.Equal("DIV", element.Parent.Children[3].TagName);
}
[WinFormsFact]
public async Task HtmlElement_InsertAdjacentElement_InvokeEmptyBeforeEnd_Success()
{
using var parent = new Control();
using var control = new WebBrowser
{
Parent = parent
};
const string Html = "<html><body><div id=\"id\"></div></body></html>";
HtmlDocument document = await GetDocument(control, Html);
HtmlElement element = document.GetElementById("id");
HtmlElement newElement1 = document.CreateElement("h1");
HtmlElement newElement2 = document.CreateElement("h2");
HtmlElement newElement3 = document.CreateElement("h3");
element.InsertAdjacentElement(HtmlElementInsertionOrientation.BeforeEnd, newElement1);
Assert.Single(element.All);
Assert.Equal("H1", element.All[0].TagName);
Assert.Single(element.Parent.Children);
Assert.Equal("DIV", element.Parent.Children[0].TagName);
element.InsertAdjacentElement(HtmlElementInsertionOrientation.BeforeEnd, newElement2);
Assert.Equal(2, element.All.Count);
Assert.Equal("H1", element.All[0].TagName);
Assert.Equal("H2", element.All[1].TagName);
Assert.Single(element.Parent.Children);
Assert.Equal("DIV", element.Parent.Children[0].TagName);
element.InsertAdjacentElement(HtmlElementInsertionOrientation.BeforeEnd, newElement3);
Assert.Equal(3, element.All.Count);
Assert.Equal("H1", element.All[0].TagName);
Assert.Equal("H2", element.All[1].TagName);
Assert.Equal("H3", element.All[2].TagName);
Assert.Single(element.Parent.Children);
Assert.Equal("DIV", element.Parent.Children[0].TagName);
}
[WinFormsFact]
public async Task HtmlElement_InsertAdjacentElement_InvokeNotEmptyBeforeEnd_Success()
{
using var parent = new Control();
using var control = new WebBrowser
{
Parent = parent
};
const string Html = "<html><body><div id=\"id\"><p>InnerText</p><strong>StrongText</strong></div></body></html>";
HtmlDocument document = await GetDocument(control, Html);
HtmlElement element = document.GetElementById("id");
HtmlElement newElement1 = document.CreateElement("h1");
HtmlElement newElement2 = document.CreateElement("h2");
HtmlElement newElement3 = document.CreateElement("h3");
element.InsertAdjacentElement(HtmlElementInsertionOrientation.BeforeEnd, newElement1);
Assert.Equal(3, element.All.Count);
Assert.Equal("P", element.All[0].TagName);
Assert.Equal("STRONG", element.All[1].TagName);
Assert.Equal("H1", element.All[2].TagName);
Assert.Single(element.Parent.Children);
Assert.Equal("DIV", element.Parent.Children[0].TagName);
element.InsertAdjacentElement(HtmlElementInsertionOrientation.BeforeEnd, newElement2);
Assert.Equal(4, element.All.Count);
Assert.Equal("P", element.All[0].TagName);
Assert.Equal("STRONG", element.All[1].TagName);
Assert.Equal("H1", element.All[2].TagName);
Assert.Equal("H2", element.All[3].TagName);
Assert.Single(element.Parent.Children);
Assert.Equal("DIV", element.Parent.Children[0].TagName);
element.InsertAdjacentElement(HtmlElementInsertionOrientation.BeforeEnd, newElement3);
Assert.Equal(5, element.All.Count);
Assert.Equal("P", element.All[0].TagName);
Assert.Equal("STRONG", element.All[1].TagName);
Assert.Equal("H1", element.All[2].TagName);
Assert.Equal("H2", element.All[3].TagName);
Assert.Equal("H3", element.All[4].TagName);
Assert.Single(element.Parent.Children);
Assert.Equal("DIV", element.Parent.Children[0].TagName);
}
[WinFormsFact]
public async Task HtmlElement_InsertAdjacentElement_InvokeEmptyAfterBegin_Success()
{
using var parent = new Control();
using var control = new WebBrowser
{
Parent = parent
};
const string Html = "<html><body><div id=\"id\"></div></body></html>";
HtmlDocument document = await GetDocument(control, Html);
HtmlElement element = document.GetElementById("id");
HtmlElement newElement1 = document.CreateElement("h1");
HtmlElement newElement2 = document.CreateElement("h2");
HtmlElement newElement3 = document.CreateElement("h3");
element.InsertAdjacentElement(HtmlElementInsertionOrientation.AfterBegin, newElement1);
Assert.Single(element.All);
Assert.Equal("H1", element.All[0].TagName);
element.InsertAdjacentElement(HtmlElementInsertionOrientation.AfterBegin, newElement2);
Assert.Equal(2, element.All.Count);
Assert.Equal("H2", element.All[0].TagName);
Assert.Equal("H1", element.All[1].TagName);
Assert.Single(element.Parent.Children);
Assert.Equal("DIV", element.Parent.Children[0].TagName);
element.InsertAdjacentElement(HtmlElementInsertionOrientation.AfterBegin, newElement3);
Assert.Equal(3, element.All.Count);
Assert.Equal("H3", element.All[0].TagName);
Assert.Equal("H2", element.All[1].TagName);
Assert.Equal("H1", element.All[2].TagName);
Assert.Single(element.Parent.Children);
Assert.Equal("DIV", element.Parent.Children[0].TagName);
}
[WinFormsFact]
public async Task HtmlElement_InsertAdjacentElement_InvokeNotEmptyAfterBegin_Success()
{
using var parent = new Control();
using var control = new WebBrowser
{
Parent = parent
};
const string Html = "<html><body><div id=\"id\"><p>InnerText</p><strong>StrongText</strong></div></body></html>";
HtmlDocument document = await GetDocument(control, Html);
HtmlElement element = document.GetElementById("id");
HtmlElement newElement1 = document.CreateElement("h1");
HtmlElement newElement2 = document.CreateElement("h2");
HtmlElement newElement3 = document.CreateElement("h3");
element.InsertAdjacentElement(HtmlElementInsertionOrientation.AfterBegin, newElement1);
Assert.Equal(3, element.All.Count);
Assert.Equal("H1", element.All[0].TagName);
Assert.Equal("P", element.All[1].TagName);
Assert.Equal("STRONG", element.All[2].TagName);
Assert.Single(element.Parent.Children);
Assert.Equal("DIV", element.Parent.Children[0].TagName);
element.InsertAdjacentElement(HtmlElementInsertionOrientation.AfterBegin, newElement2);
Assert.Equal(4, element.All.Count);
Assert.Equal("H2", element.All[0].TagName);
Assert.Equal("H1", element.All[1].TagName);
Assert.Equal("P", element.All[2].TagName);
Assert.Equal("STRONG", element.All[3].TagName);
Assert.Single(element.Parent.Children);
Assert.Equal("DIV", element.Parent.Children[0].TagName);
element.InsertAdjacentElement(HtmlElementInsertionOrientation.AfterBegin, newElement3);
Assert.Equal(5, element.All.Count);
Assert.Equal("H3", element.All[0].TagName);
Assert.Equal("H2", element.All[1].TagName);
Assert.Equal("H1", element.All[2].TagName);
Assert.Equal("P", element.All[3].TagName);
Assert.Equal("STRONG", element.All[4].TagName);
Assert.Single(element.Parent.Children);
Assert.Equal("DIV", element.Parent.Children[0].TagName);
}
[WinFormsFact]
public async Task HtmlElement_InsertAdjacentElement_InvokeEmptyAfterEnd_Success()
{
using var parent = new Control();
using var control = new WebBrowser
{
Parent = parent
};
const string Html = "<html><body><div id=\"id\"></div></body></html>";
HtmlDocument document = await GetDocument(control, Html);
HtmlElement element = document.GetElementById("id");
HtmlElement newElement1 = document.CreateElement("h1");
HtmlElement newElement2 = document.CreateElement("h2");
HtmlElement newElement3 = document.CreateElement("h3");
element.InsertAdjacentElement(HtmlElementInsertionOrientation.AfterEnd, newElement1);
Assert.Equal(2, element.Parent.Children.Count);
Assert.Equal("DIV", element.Parent.Children[0].TagName);
Assert.Equal("H1", element.Parent.Children[1].TagName);
element.InsertAdjacentElement(HtmlElementInsertionOrientation.AfterEnd, newElement2);
Assert.Equal(3, element.Parent.Children.Count);
Assert.Equal("DIV", element.Parent.Children[0].TagName);
Assert.Equal("H2", element.Parent.Children[1].TagName);
Assert.Equal("H1", element.Parent.Children[2].TagName);
element.InsertAdjacentElement(HtmlElementInsertionOrientation.AfterEnd, newElement3);
Assert.Equal(4, element.Parent.Children.Count);
Assert.Equal("DIV", element.Parent.Children[0].TagName);
Assert.Equal("H3", element.Parent.Children[1].TagName);
Assert.Equal("H2", element.Parent.Children[2].TagName);
Assert.Equal("H1", element.Parent.Children[3].TagName);
}
[WinFormsFact]
public async Task HtmlElement_InsertAdjacentElement_InvokeNotEmptyAfterEnd_Success()
{
using var parent = new Control();
using var control = new WebBrowser
{
Parent = parent
};
const string Html = "<html><body><div id=\"id\"><p>InnerText</p><strong>StrongText</strong></div></body></html>";
HtmlDocument document = await GetDocument(control, Html);
HtmlElement element = document.GetElementById("id");
HtmlElement newElement1 = document.CreateElement("h1");
HtmlElement newElement2 = document.CreateElement("h2");
HtmlElement newElement3 = document.CreateElement("h3");
element.InsertAdjacentElement(HtmlElementInsertionOrientation.AfterEnd, newElement1);
Assert.Equal(2, element.All.Count);
Assert.Equal("P", element.All[0].TagName);
Assert.Equal("STRONG", element.All[1].TagName);
Assert.Equal(2, element.Parent.Children.Count);
Assert.Equal("DIV", element.Parent.Children[0].TagName);
Assert.Equal("H1", element.Parent.Children[1].TagName);
element.InsertAdjacentElement(HtmlElementInsertionOrientation.AfterEnd, newElement2);
Assert.Equal(2, element.All.Count);
Assert.Equal("P", element.All[0].TagName);
Assert.Equal("STRONG", element.All[1].TagName);
Assert.Equal(3, element.Parent.Children.Count);
Assert.Equal("DIV", element.Parent.Children[0].TagName);
Assert.Equal("H2", element.Parent.Children[1].TagName);
Assert.Equal("H1", element.Parent.Children[2].TagName);
element.InsertAdjacentElement(HtmlElementInsertionOrientation.AfterEnd, newElement3);
Assert.Equal(2, element.All.Count);
Assert.Equal("P", element.All[0].TagName);
Assert.Equal("STRONG", element.All[1].TagName);
Assert.Equal(4, element.Parent.Children.Count);
Assert.Equal("DIV", element.Parent.Children[0].TagName);
Assert.Equal("H3", element.Parent.Children[1].TagName);
Assert.Equal("H2", element.Parent.Children[2].TagName);
Assert.Equal("H1", element.Parent.Children[3].TagName);
}
[WinFormsFact]
public async Task HtmlElement_InsertAdjacentElement_NullNewElement_ThrowsNullReferenceException()
{
using var parent = new Control();
using var control = new WebBrowser
{
Parent = parent
};
const string Html = "<html><body><div id=\"id\"><h1>Header1 <strong>Strong</strong></h1><h2>Header2</h2></div></body></html>";
HtmlDocument document = await GetDocument(control, Html);
HtmlElement element = document.GetElementById("id");
Assert.Throws<NullReferenceException>(() => element.InsertAdjacentElement(HtmlElementInsertionOrientation.BeforeEnd, null));
}
[WinFormsTheory]
[CommonMemberData(nameof(CommonTestHelper.GetEnumTypeTheoryDataInvalid), typeof(HtmlElementInsertionOrientation))]
public async Task HtmlElement_InsertAdjacentElement_InvalidOrient_ThrowsArgumentException(HtmlElementInsertionOrientation orient)
{
using var parent = new Control();
using var control = new WebBrowser
{
Parent = parent
};
const string Html = "<html><body><div id=\"id\"></div></body></html>";
HtmlDocument document = await GetDocument(control, Html);
HtmlElement element = document.GetElementById("id");
HtmlElement newElement = document.CreateElement("H1");
Assert.Throws<ArgumentException>(null, () => element.InsertAdjacentElement(orient, newElement));
}
[WinFormsFact]
public async Task HtmlElement_InvokeMember_MemberExists_ReturnsExpected()
{
using var parent = new Control();
using var control = new WebBrowser
{
Parent = parent
};
const string Html = "<html><body><p id=\"target\" attribute=\"value\">Paragraph</p></body></html>";
HtmlDocument document = await GetDocument(control, Html);
HtmlElement element = document.GetElementById("target");
Assert.NotNull(element);
Assert.Equal("value", element.InvokeMember("getAttribute", "attribute"));
Assert.Equal("value", element.InvokeMember("getAttribute", "attribute", 1));
Assert.Equal(Convert.DBNull, element.InvokeMember("getAttribute", "ATTRIBUTE", 1));
Assert.Equal(Convert.DBNull, element.InvokeMember("getAttribute", "NoSuchAttribute"));
Assert.Null(element.InvokeMember("getAttribute", new TimeSpan()));
}
[WinFormsFact]
public async Task HtmlElement_InvokeMember_NoSuchMember_ReturnsNull()
{
using var parent = new Control();
using var control = new WebBrowser
{
Parent = parent
};
const string Html = "<html><body><p id=\"target\" attribute=\"value\">Paragraph</p></body></html>";
HtmlDocument document = await GetDocument(control, Html);
HtmlElement element = document.GetElementById("target");
Assert.NotNull(element);
Assert.Null(element.InvokeMember("NoSuchMember"));
Assert.Null(element.InvokeMember("NoSuchMember", null));
Assert.Null(element.InvokeMember("NoSuchMember", Array.Empty<object>()));
Assert.Null(element.InvokeMember("NoSuchMember", new object[] { 1 }));
}
[WinFormsFact]
public async Task HtmlElement_RemoveFocus_Invoke_Success()
{
using var parent = new Control();
using var control = new WebBrowser
{
Parent = parent
};
const string Html = "<html><body><div id=\"id\"></div></body></html>";
HtmlDocument document = await GetDocument(control, Html);
HtmlElement element = document.GetElementById("id");
element.RemoveFocus();
// Call again.
element.RemoveFocus();
}
[WinFormsFact]
public async Task HtmlElement_RemoveFocus_InvokeFocused_Success()
{
using var parent = new Control();
using var control = new WebBrowser
{
Parent = parent
};
const string Html = "<html><body><div id=\"id\"></div></body></html>";
HtmlDocument document = await GetDocument(control, Html);
HtmlElement element = document.GetElementById("id");
element.Focus();
element.RemoveFocus();
// Call again.
element.RemoveFocus();
}
[WinFormsTheory]
[CommonMemberData(nameof(CommonTestHelper.GetBoolTheoryData))]
public async Task HtmlElement_ScrollIntoView_Invoke_Success(bool alignWithTop)
{
using var parent = new Control();
using var control = new WebBrowser
{
Parent = parent
};
const string Html = "<html><body><div id=\"id\"></div></body></html>";
HtmlDocument document = await GetDocument(control, Html);
HtmlElement element = document.GetElementById("id");
element.ScrollIntoView(alignWithTop);
// Call again.
element.ScrollIntoView(alignWithTop);
}
[WinFormsTheory]
[CommonMemberData(nameof(CommonTestHelper.GetStringTheoryData))]
public async Task HtmlElement_SetAttribute_Invoke_GetAttributeReturnsExpected(string value)
{
using var parent = new Control();
using var control = new WebBrowser
{
Parent = parent
};
const string Html = "<html><body><div id=\"id\"></div></body></html>";
HtmlDocument document = await GetDocument(control, Html);
HtmlElement element = document.GetElementById("id");
element.SetAttribute("customAttribute", value);
Assert.Equal(value, element.GetAttribute("customAttribute"));
// Set same.
element.SetAttribute("customAttribute", value);
Assert.Equal(value, element.GetAttribute("customAttribute"));
// Override.
element.SetAttribute("customAttribute", "newValue");
Assert.Equal("newValue", element.GetAttribute("customAttribute"));
}
[WinFormsFact]
public async Task HtmlElement_SetAttribute_NullAttributeName_ThrowsArgumentException()
{
using var parent = new Control();
using var control = new WebBrowser
{
Parent = parent
};
const string Html = "<html><body><div id=\"id\"></div></body></html>";
HtmlDocument document = await GetDocument(control, Html);
HtmlElement element = document.GetElementById("id");
Assert.Throws<ArgumentException>(null, () => element.SetAttribute(null, "value"));
}
[WinFormsFact]
public async Task HtmlElement_SetAttribute_EmptyAttributeName_ThrowsArgumentException()
{
using var parent = new Control();
using var control = new WebBrowser
{
Parent = parent
};
const string Html = "<html><body><div id=\"id\"></div></body></html>";
HtmlDocument document = await GetDocument(control, Html);
HtmlElement element = document.GetElementById("id");
COMException ex = Assert.Throws<COMException>(() => element.SetAttribute(string.Empty, "value"));
Assert.Equal(HRESULT.DISP_E_UNKNOWNNAME, (HRESULT)ex.HResult);
}
#pragma warning disable CS1718 // Disable "Comparison made to same variable" warning.
[WinFormsFact]
public async Task HtmlElement_OperatorEquals_Invoke_ReturnsExpected()
{
using var parent = new Control();
using var control = new WebBrowser
{
Parent = parent
};
const string Html = "<html><body><div id=\"id1\"></div><div id=\"id2\"></div></body></html>";
HtmlDocument document = await GetDocument(control, Html);
HtmlElement element1 = document.GetElementById("id1");
HtmlElement element2 = document.GetElementById("id1");
HtmlElement element3 = document.GetElementById("id2");
Assert.True(element1 == element1);
Assert.True(element1 == element2);
Assert.False(element1 == element3);
Assert.False((HtmlElement)null == element1);
Assert.False(element1 == (HtmlElement)null);
Assert.True((HtmlElement)null == (HtmlElement)null);
}
[WinFormsFact]
public async Task HtmlElement_OperatorNotEquals_Invoke_ReturnsExpected()
{
using var parent = new Control();
using var control = new WebBrowser
{
Parent = parent
};
const string Html = "<html><body><div id=\"id1\"></div><div id=\"id2\"></div></body></html>";
HtmlDocument document = await GetDocument(control, Html);
HtmlElement element1 = document.GetElementById("id1");
HtmlElement element2 = document.GetElementById("id1");
HtmlElement element3 = document.GetElementById("id2");
Assert.False(element1 != element1);
Assert.False(element1 != element2);
Assert.True(element1 != element3);
Assert.True((HtmlElement)null != element1);
Assert.True(element1 != (HtmlElement)null);
Assert.False((HtmlElement)null != (HtmlElement)null);
}
#pragma warning restore CS1718
[WinFormsFact]
public async Task HtmlElement_Click_InvokeEvent_Success()
{
using var parent = new Control();
using var control = new WebBrowser
{
Parent = parent
};
const string Html = "<html><body><div id=\"id\"></div></body></html>";
HtmlDocument document = await GetDocument(control, Html);
HtmlElement element = document.GetElementById("id");
IHTMLElement3 iHTMLElement3 = (IHTMLElement3)element.DomElement;
int callCount = 0;
void handler(object sender, EventArgs e)
{
Assert.Same(element, sender);
Assert.IsType<HtmlElementEventArgs>(e);
callCount++;
}
element.Click += handler;
Assert.True(iHTMLElement3.FireEvent("onclick", IntPtr.Zero));
Assert.Equal(1, callCount);
// Remove handler.
element.Click -= handler;
Assert.True(iHTMLElement3.FireEvent("onclick", IntPtr.Zero));
Assert.Equal(1, callCount);
}
[WinFormsFact]
public async Task HtmlElement_DoubleClick_InvokeEvent_Success()
{
using var parent = new Control();
using var control = new WebBrowser
{
Parent = parent
};
const string Html = "<html><body><div id=\"id\"></div></body></html>";
HtmlDocument document = await GetDocument(control, Html);
HtmlElement element = document.GetElementById("id");
IHTMLElement3 iHTMLElement3 = (IHTMLElement3)element.DomElement;
int callCount = 0;
void handler(object sender, EventArgs e)
{
Assert.Same(element, sender);
Assert.IsType<HtmlElementEventArgs>(e);
callCount++;
}
element.DoubleClick += handler;
Assert.True(iHTMLElement3.FireEvent("ondblclick", IntPtr.Zero));
Assert.Equal(1, callCount);
// Remove handler.
element.DoubleClick -= handler;
Assert.True(iHTMLElement3.FireEvent("ondblclick", IntPtr.Zero));
Assert.Equal(1, callCount);
}
[WinFormsFact]
public async Task HtmlElement_Drag_InvokeEvent_Success()
{
using var parent = new Control();
using var control = new WebBrowser
{
Parent = parent
};
const string Html = "<html><body><div id=\"id\"></div></body></html>";
HtmlDocument document = await GetDocument(control, Html);
HtmlElement element = document.GetElementById("id");
IHTMLElement3 iHTMLElement3 = (IHTMLElement3)element.DomElement;
int callCount = 0;
void handler(object sender, EventArgs e)
{
Assert.Same(element, sender);
Assert.IsType<HtmlElementEventArgs>(e);
callCount++;
}
element.Drag += handler;
Assert.True(iHTMLElement3.FireEvent("ondrag", IntPtr.Zero));
Assert.Equal(1, callCount);
// Remove handler.
element.Drag -= handler;
Assert.True(iHTMLElement3.FireEvent("ondrag", IntPtr.Zero));
Assert.Equal(1, callCount);
}
[WinFormsFact]
public async Task HtmlElement_DragEnd_InvokeEvent_Success()
{
using var parent = new Control();
using var control = new WebBrowser
{
Parent = parent
};
const string Html = "<html><body><div id=\"id\"></div></body></html>";
HtmlDocument document = await GetDocument(control, Html);
HtmlElement element = document.GetElementById("id");
IHTMLElement3 iHTMLElement3 = (IHTMLElement3)element.DomElement;
int callCount = 0;
void handler(object sender, EventArgs e)
{
Assert.Same(element, sender);
Assert.IsType<HtmlElementEventArgs>(e);
callCount++;
}
element.DragEnd += handler;
Assert.True(iHTMLElement3.FireEvent("ondragend", IntPtr.Zero));
Assert.Equal(1, callCount);
// Remove handler.
element.DragEnd -= handler;
Assert.True(iHTMLElement3.FireEvent("ondragend", IntPtr.Zero));
Assert.Equal(1, callCount);
}
[WinFormsFact]
public async Task HtmlElement_DragLeave_InvokeEvent_Success()
{
using var parent = new Control();
using var control = new WebBrowser
{
Parent = parent
};
const string Html = "<html><body><div id=\"id\"></div></body></html>";
HtmlDocument document = await GetDocument(control, Html);
HtmlElement element = document.GetElementById("id");
IHTMLElement3 iHTMLElement3 = (IHTMLElement3)element.DomElement;
int callCount = 0;
void handler(object sender, EventArgs e)
{
Assert.Same(element, sender);
Assert.IsType<HtmlElementEventArgs>(e);
callCount++;
}
element.DragLeave += handler;
Assert.True(iHTMLElement3.FireEvent("ondragleave", IntPtr.Zero));
Assert.Equal(1, callCount);
// Remove handler.
element.DragLeave -= handler;
Assert.True(iHTMLElement3.FireEvent("ondragleave", IntPtr.Zero));
Assert.Equal(1, callCount);
}
[WinFormsFact]
public async Task HtmlElement_DragOver_InvokeEvent_Success()
{
using var parent = new Control();
using var control = new WebBrowser
{
Parent = parent
};
const string Html = "<html><body><div id=\"id\"></div></body></html>";
HtmlDocument document = await GetDocument(control, Html);
HtmlElement element = document.GetElementById("id");
IHTMLElement3 iHTMLElement3 = (IHTMLElement3)element.DomElement;
int callCount = 0;
void handler(object sender, EventArgs e)
{
Assert.Same(element, sender);
Assert.IsType<HtmlElementEventArgs>(e);
callCount++;
}
element.DragOver += handler;
Assert.True(iHTMLElement3.FireEvent("ondragover", IntPtr.Zero));
Assert.Equal(1, callCount);
// Remove handler.
element.DragOver -= handler;
Assert.True(iHTMLElement3.FireEvent("ondragover", IntPtr.Zero));
Assert.Equal(1, callCount);
}
[WinFormsFact]
public async Task HtmlElement_GotFocus_InvokeEvent_Success()
{
using var parent = new Control();
using var control = new WebBrowser
{
Parent = parent
};
const string Html = "<html><body><div id=\"id\"></div></body></html>";
HtmlDocument document = await GetDocument(control, Html);
HtmlElement element = document.GetElementById("id");
IHTMLElement3 iHTMLElement3 = (IHTMLElement3)element.DomElement;
int callCount = 0;
void handler(object sender, EventArgs e)
{
Assert.Same(element, sender);
Assert.IsType<HtmlElementEventArgs>(e);
callCount++;
}
element.GotFocus += handler;
Assert.True(iHTMLElement3.FireEvent("onfocus", IntPtr.Zero));
Assert.Equal(1, callCount);
// Remove handler.
element.GotFocus -= handler;
Assert.True(iHTMLElement3.FireEvent("onfocus", IntPtr.Zero));
Assert.Equal(1, callCount);
}
[WinFormsFact]
public async Task HtmlElement_Focusing_InvokeEvent_Success()
{
using var parent = new Control();
using var control = new WebBrowser
{
Parent = parent
};
const string Html = "<html><body><div id=\"id\"></div></body></html>";
HtmlDocument document = await GetDocument(control, Html);
HtmlElement element = document.GetElementById("id");
IHTMLElement3 iHTMLElement3 = (IHTMLElement3)element.DomElement;
int callCount = 0;
void handler(object sender, EventArgs e)
{
Assert.Same(element, sender);
Assert.IsType<HtmlElementEventArgs>(e);
callCount++;
}
element.Focusing += handler;
Assert.True(iHTMLElement3.FireEvent("onfocusin", IntPtr.Zero));
Assert.Equal(1, callCount);
// Remove handler.
element.Focusing -= handler;
Assert.True(iHTMLElement3.FireEvent("onfocusin", IntPtr.Zero));
Assert.Equal(1, callCount);
}
[WinFormsFact]
public async Task HtmlElement_LosingFocus_InvokeEvent_Success()
{
using var parent = new Control();
using var control = new WebBrowser
{
Parent = parent
};
const string Html = "<html><body><div id=\"id\"></div></body></html>";
HtmlDocument document = await GetDocument(control, Html);
HtmlElement element = document.GetElementById("id");
IHTMLElement3 iHTMLElement3 = (IHTMLElement3)element.DomElement;
int callCount = 0;
void handler(object sender, EventArgs e)
{
Assert.Same(element, sender);
Assert.IsType<HtmlElementEventArgs>(e);
callCount++;
}
element.LosingFocus += handler;
Assert.True(iHTMLElement3.FireEvent("onfocusout", IntPtr.Zero));
Assert.Equal(1, callCount);
// Remove handler.
element.LosingFocus -= handler;
Assert.True(iHTMLElement3.FireEvent("onfocusout", IntPtr.Zero));
Assert.Equal(1, callCount);
}
[WinFormsFact]
public async Task HtmlElement_LostFocus_InvokeEvent_Success()
{
using var parent = new Control();
using var control = new WebBrowser
{
Parent = parent
};
const string Html = "<html><body><div id=\"id\"></div></body></html>";
HtmlDocument document = await GetDocument(control, Html);
HtmlElement element = document.GetElementById("id");
IHTMLElement3 iHTMLElement3 = (IHTMLElement3)element.DomElement;
int callCount = 0;
void handler(object sender, EventArgs e)
{
Assert.Same(element, sender);
Assert.IsType<HtmlElementEventArgs>(e);
callCount++;
}
element.LostFocus += handler;
Assert.True(iHTMLElement3.FireEvent("onblur", IntPtr.Zero));
Assert.Equal(1, callCount);
// Remove handler.
element.LostFocus -= handler;
Assert.True(iHTMLElement3.FireEvent("onblur", IntPtr.Zero));
Assert.Equal(1, callCount);
}
[WinFormsFact]
public async Task HtmlElement_KeyDown_InvokeEvent_Success()
{
using var parent = new Control();
using var control = new WebBrowser
{
Parent = parent
};
const string Html = "<html><body><div id=\"id\"></div></body></html>";
HtmlDocument document = await GetDocument(control, Html);
HtmlElement element = document.GetElementById("id");
IHTMLElement3 iHTMLElement3 = (IHTMLElement3)element.DomElement;
int callCount = 0;
void handler(object sender, EventArgs e)
{
Assert.Same(element, sender);
Assert.IsType<HtmlElementEventArgs>(e);
callCount++;
}
element.KeyDown += handler;
Assert.True(iHTMLElement3.FireEvent("onkeydown", IntPtr.Zero));
Assert.Equal(1, callCount);
// Remove handler.
element.KeyDown -= handler;
Assert.True(iHTMLElement3.FireEvent("onkeydown", IntPtr.Zero));
Assert.Equal(1, callCount);
}
[WinFormsFact]
public async Task HtmlElement_KeyPress_InvokeEvent_Success()
{
using var parent = new Control();
using var control = new WebBrowser
{
Parent = parent
};
const string Html = "<html><body><div id=\"id\"></div></body></html>";
HtmlDocument document = await GetDocument(control, Html);
HtmlElement element = document.GetElementById("id");
IHTMLElement3 iHTMLElement3 = (IHTMLElement3)element.DomElement;
int callCount = 0;
void handler(object sender, EventArgs e)
{
Assert.Same(element, sender);
Assert.IsType<HtmlElementEventArgs>(e);
callCount++;
}
element.KeyPress += handler;
Assert.True(iHTMLElement3.FireEvent("onkeypress", IntPtr.Zero));
Assert.Equal(1, callCount);
// Remove handler.
element.KeyPress -= handler;
Assert.True(iHTMLElement3.FireEvent("onkeypress", IntPtr.Zero));
Assert.Equal(1, callCount);
}
[WinFormsFact]
public async Task HtmlElement_KeyUp_InvokeEvent_Success()
{
using var parent = new Control();
using var control = new WebBrowser
{
Parent = parent
};
const string Html = "<html><body><div id=\"id\"></div></body></html>";
HtmlDocument document = await GetDocument(control, Html);
HtmlElement element = document.GetElementById("id");
IHTMLElement3 iHTMLElement3 = (IHTMLElement3)element.DomElement;
int callCount = 0;
void handler(object sender, EventArgs e)
{
Assert.Same(element, sender);
Assert.IsType<HtmlElementEventArgs>(e);
callCount++;
}
element.KeyUp += handler;
Assert.True(iHTMLElement3.FireEvent("onkeyup", IntPtr.Zero));
Assert.Equal(1, callCount);
// Remove handler.
element.KeyUp -= handler;
Assert.True(iHTMLElement3.FireEvent("onkeyup", IntPtr.Zero));
Assert.Equal(1, callCount);
}
[WinFormsFact]
public async Task HtmlElement_MouseDown_InvokeEvent_Success()
{
using var parent = new Control();
using var control = new WebBrowser
{
Parent = parent
};
const string Html = "<html><body><div id=\"id\"></div></body></html>";
HtmlDocument document = await GetDocument(control, Html);
HtmlElement element = document.GetElementById("id");
IHTMLElement3 iHTMLElement3 = (IHTMLElement3)element.DomElement;
int callCount = 0;
void handler(object sender, EventArgs e)
{
Assert.Same(element, sender);
Assert.IsType<HtmlElementEventArgs>(e);
callCount++;
}
element.MouseDown += handler;
Assert.True(iHTMLElement3.FireEvent("onmousedown", IntPtr.Zero));
Assert.Equal(1, callCount);
// Remove handler.
element.MouseDown -= handler;
Assert.True(iHTMLElement3.FireEvent("onmousedown", IntPtr.Zero));
Assert.Equal(1, callCount);
}
[WinFormsFact]
public async Task HtmlElement_MouseEnter_InvokeEvent_Success()
{
using var parent = new Control();
using var control = new WebBrowser
{
Parent = parent
};
const string Html = "<html><body><div id=\"id\"></div></body></html>";
HtmlDocument document = await GetDocument(control, Html);
HtmlElement element = document.GetElementById("id");
IHTMLElement3 iHTMLElement3 = (IHTMLElement3)element.DomElement;
int callCount = 0;
void handler(object sender, EventArgs e)
{
Assert.Same(element, sender);
Assert.IsType<HtmlElementEventArgs>(e);
callCount++;
}
element.MouseEnter += handler;
Assert.True(iHTMLElement3.FireEvent("onmouseenter", IntPtr.Zero));
Assert.Equal(1, callCount);
// Remove handler.
element.MouseEnter -= handler;
Assert.True(iHTMLElement3.FireEvent("onmouseenter", IntPtr.Zero));
Assert.Equal(1, callCount);
}
[WinFormsFact]
public async Task HtmlElement_MouseLeave_InvokeEvent_Success()
{
using var parent = new Control();
using var control = new WebBrowser
{
Parent = parent
};
const string Html = "<html><body><div id=\"id\"></div></body></html>";
HtmlDocument document = await GetDocument(control, Html);
HtmlElement element = document.GetElementById("id");
IHTMLElement3 iHTMLElement3 = (IHTMLElement3)element.DomElement;
int callCount = 0;
void handler(object sender, EventArgs e)
{
Assert.Same(element, sender);
Assert.IsType<HtmlElementEventArgs>(e);
callCount++;
}
element.MouseLeave += handler;
Assert.True(iHTMLElement3.FireEvent("onmouseleave", IntPtr.Zero));
Assert.Equal(1, callCount);
// Remove handler.
element.MouseLeave -= handler;
Assert.True(iHTMLElement3.FireEvent("onmouseleave", IntPtr.Zero));
Assert.Equal(1, callCount);
}
[WinFormsFact]
public async Task HtmlElement_MouseMove_InvokeEvent_Success()
{
using var parent = new Control();
using var control = new WebBrowser
{
Parent = parent
};
const string Html = "<html><body><div id=\"id\"></div></body></html>";
HtmlDocument document = await GetDocument(control, Html);
HtmlElement element = document.GetElementById("id");
IHTMLElement3 iHTMLElement3 = (IHTMLElement3)element.DomElement;
int callCount = 0;
void handler(object sender, EventArgs e)
{
Assert.Same(element, sender);
Assert.IsType<HtmlElementEventArgs>(e);
callCount++;
}
element.MouseMove += handler;
Assert.True(iHTMLElement3.FireEvent("onmousemove", IntPtr.Zero));
Assert.Equal(1, callCount);
// Remove handler.
element.MouseMove -= handler;
Assert.True(iHTMLElement3.FireEvent("onmousemove", IntPtr.Zero));
Assert.Equal(1, callCount);
}
[WinFormsFact]
public async Task HtmlElement_MouseOver_InvokeEvent_Success()
{
using var parent = new Control();
using var control = new WebBrowser
{
Parent = parent
};
const string Html = "<html><body><div id=\"id\"></div></body></html>";
HtmlDocument document = await GetDocument(control, Html);
HtmlElement element = document.GetElementById("id");
IHTMLElement3 iHTMLElement3 = (IHTMLElement3)element.DomElement;
int callCount = 0;
void handler(object sender, EventArgs e)
{
Assert.Same(element, sender);
Assert.IsType<HtmlElementEventArgs>(e);
callCount++;
}
element.MouseOver += handler;
Assert.False(iHTMLElement3.FireEvent("onmouseover", IntPtr.Zero));
Assert.Equal(1, callCount);
// Remove handler.
element.MouseOver -= handler;
Assert.False(iHTMLElement3.FireEvent("onmouseover", IntPtr.Zero));
Assert.Equal(1, callCount);
}
[WinFormsFact]
public async Task HtmlElement_MouseUp_InvokeEvent_Success()
{
using var parent = new Control();
using var control = new WebBrowser
{
Parent = parent
};
const string Html = "<html><body><div id=\"id\"></div></body></html>";
HtmlDocument document = await GetDocument(control, Html);
HtmlElement element = document.GetElementById("id");
IHTMLElement3 iHTMLElement3 = (IHTMLElement3)element.DomElement;
int callCount = 0;
void handler(object sender, EventArgs e)
{
Assert.Same(element, sender);
Assert.IsType<HtmlElementEventArgs>(e);
callCount++;
}
element.MouseUp += handler;
Assert.True(iHTMLElement3.FireEvent("onmouseup", IntPtr.Zero));
Assert.Equal(1, callCount);
// Remove handler.
element.MouseUp -= handler;
Assert.True(iHTMLElement3.FireEvent("onmouseup", IntPtr.Zero));
Assert.Equal(1, callCount);
}
private async static Task<HtmlDocument> GetDocument(WebBrowser control, string html)
{
var source = new TaskCompletionSource<bool>();
control.DocumentCompleted += (sender, e) => source.SetResult(true);
using var file = CreateTempFile(html);
await Task.Run(() => control.Navigate(file.Path));
Assert.True(await source.Task);
return control.Document;
}
private static TempFile CreateTempFile(string html)
{
byte[] data = Encoding.UTF8.GetBytes(html);
return TempFile.Create(data);
}
}
}
| 40.257839 | 246 | 0.576802 | [
"MIT"
] | Amy-Li03/winforms | src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/HtmlElementTests.cs | 120,695 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
using Microsoft.Extensions.Logging;
using Serilog;
using ILogger = Microsoft.Extensions.Logging.ILogger;
namespace TPP.Api
{
public static class AppLogging
{
public static ILoggerFactory LoggerFactory { get; } = new LoggerFactory()
.AddConsole()
.AddDebug()
.AddSerilog();
public static ILogger CreateLogger<T>() => LoggerFactory.CreateLogger<T>();
}
} | 28.105263 | 84 | 0.649813 | [
"MIT"
] | Bhaskers-Blu-Org2/SPP_Public | src/api/Web/TPP.Web.Api/AppLogging.cs | 536 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using DG.Tweening;
using UnityEngine.SceneManagement;
public class PilotTesting_Question : MonoBehaviour
{
[Header("UI")]
public Image continueTip;
public RectTransform bg;
public Text _text;
[Header("Level")]
public int nextLevelId = 0;
public bool ExitGameAfterLevel = false;
bool canPass = false;
Sequence startSequence;
// Start is called before the first frame update
void Start()
{
StartCoroutine("SkipIEnumerator");
startSequence = DOTween.Sequence();
startSequence.AppendInterval(0.5f);
startSequence.Append(bg.DOScaleY(2f, 0.4f));
startSequence.Join(_text.DOFade(1, 0.8f));
}
// Update is called once per frame
void Update()
{
if (canPass && Input.GetButtonDown("Enter"))
{
if (ExitGameAfterLevel) Application.Quit();
else StartCoroutine("NextLevelIEnumerator");
}
}
IEnumerator SkipIEnumerator()
{
yield return new WaitForSeconds(1.7f);
continueTip.DOFade(1, 0.5f);
yield return new WaitForSeconds(0.35f);
canPass = true;
}
IEnumerator NextLevelIEnumerator()
{
startSequence.Append(bg.DOScaleY(0f, 0.4f));
startSequence.Join(continueTip.DOFade(0f,0.6f));
startSequence.AppendInterval(0.3f);
startSequence.Append(_text.DOFade(0, 0.5f));
yield return new WaitForSeconds(1.3f);
SceneManager.LoadScene(nextLevelId);
}
}
| 27.465517 | 56 | 0.650973 | [
"MIT"
] | neil841004/Cube-Adventure | Assets/Scripts/PilotTesting_Question.cs | 1,595 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CleanArchitecture.Infrastructure.Caching
{
/// <summary>
/// This class includes cache options for Redis Cache.
/// </summary>
internal class RedisCacheOption
{
/// <summary>
/// For Example : localhost
/// </summary>
public string Configuration { get; set; }
/// <summary>
/// Instance name For Example : CleanArchitecture
/// </summary>
public string InstanceName { get; set; }
}
}
| 24.04 | 58 | 0.622296 | [
"MIT"
] | furkandeveloper/CleanArchitecture | src/Infrastructure/Caching/RedisCacheOption.cs | 603 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FMC.EFRepository
{
public interface IRepository<T>
{
void Create(T entity);
T Read(Guid id);
void Update(T entity);
void Delete(T entity);
IEnumerable<T> FindAll();
}
}
| 16.045455 | 35 | 0.643059 | [
"Apache-2.0"
] | zcs0228/FMC | FMC/FMC/EFRepository/IRepository.cs | 355 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Composition;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.VisualStudio.LanguageServer.Protocol;
namespace Microsoft.CodeAnalysis.LanguageServer.Handler
{
[ExportLspRequestHandlerProvider, Shared]
[ProvidesMethod(Methods.TextDocumentRangeFormattingName)]
internal class FormatDocumentRangeHandler : AbstractFormatDocumentHandlerBase<DocumentRangeFormattingParams, TextEdit[]>
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public FormatDocumentRangeHandler()
{
}
public override string Method => Methods.TextDocumentRangeFormattingName;
public override TextDocumentIdentifier? GetTextDocumentIdentifier(DocumentRangeFormattingParams request) => request.TextDocument;
public override Task<TextEdit[]> HandleRequestAsync(
DocumentRangeFormattingParams request,
RequestContext context,
CancellationToken cancellationToken)
=> GetTextEditsAsync(context, request.Options, cancellationToken, range: request.Range);
}
}
| 39.742857 | 137 | 0.76348 | [
"MIT"
] | 333fred/roslyn | src/Features/LanguageServer/Protocol/Handler/Formatting/FormatDocumentRangeHandler.cs | 1,393 | C# |
//----------------------------------------------
// MeshBaker
// Copyright © 2011-2012 Ian Deane
//----------------------------------------------
using UnityEngine;
using System.Collections;
using System.IO;
using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;
/*
Test different texture packers
Test lots of multiple material configs
Try using on Coast scene
*/
/*
Notes on Normal Maps in Unity3d
Unity stores normal maps in a non standard format for some platforms. Think of the standard format as being english, unity's as being
french. The raw image files in the project folder are in english, the AssetImporter converts them to french. Texture2D.GetPixels returns
french. This is a problem when we build an atlas from Texture2D objects and save the result in the project folder.
Unity wants us to flag this file as a normal map but if we do it is effectively translated twice.
Solutions:
1) convert the normal map to english just before saving to project. Then set the normal flag and let the Importer do translation.
This was rejected because Unity doesn't translate for all platforms. I would need to check with every version of Unity which platforms
use which format.
2) Uncheck "normal map" on importer before bake and re-check after bake. This is the solution I am using.
*/
namespace DigitalOpus.MB.Core
{
public class MB3_TextureCombinerPipeline
{
public struct CreateAtlasForProperty
{
public bool allTexturesAreNull;
public bool allTexturesAreSame;
public bool allNonTexturePropsAreSame;
public override string ToString()
{
return String.Format("AllTexturesNull={0} areSame={1} nonTexPropsAreSame={2}",allTexturesAreNull,allTexturesAreSame,allNonTexturePropsAreSame);
}
}
public static ShaderTextureProperty[] shaderTexPropertyNames = new ShaderTextureProperty[] {
new ShaderTextureProperty("_MainTex",false),
new ShaderTextureProperty("_BumpMap",true),
new ShaderTextureProperty("_Normal",true),
new ShaderTextureProperty("_BumpSpecMap",false),
new ShaderTextureProperty("_DecalTex",false),
new ShaderTextureProperty("_Detail",false),
new ShaderTextureProperty("_GlossMap",false),
new ShaderTextureProperty("_Illum",false),
new ShaderTextureProperty("_LightTextureB0",false),
new ShaderTextureProperty("_ParallaxMap",false),
new ShaderTextureProperty("_ShadowOffset",false),
new ShaderTextureProperty("_TranslucencyMap",false),
new ShaderTextureProperty("_SpecMap",false),
new ShaderTextureProperty("_SpecGlossMap",false),
new ShaderTextureProperty("_TranspMap",false),
new ShaderTextureProperty("_MetallicGlossMap",false),
new ShaderTextureProperty("_OcclusionMap",false),
new ShaderTextureProperty("_EmissionMap",false),
new ShaderTextureProperty("_DetailMask",false),
// new ShaderTextureProperty("_DetailAlbedoMap",false),
// new ShaderTextureProperty("_DetailNormalMap",true),
};
internal class TexturePipelineData
{
internal MB2_TextureBakeResults _textureBakeResults;
internal int _atlasPadding = 1;
internal int _maxAtlasSize = 1;
internal bool _resizePowerOfTwoTextures = false;
internal bool _fixOutOfBoundsUVs = false;
internal int _maxTilingBakeSize = 1024;
internal bool _saveAtlasesAsAssets = false;
internal MB2_PackingAlgorithmEnum _packingAlgorithm = MB2_PackingAlgorithmEnum.UnitysPackTextures;
internal bool _meshBakerTexturePackerForcePowerOfTwo = true;
internal List<ShaderTextureProperty> _customShaderPropNames = new List<ShaderTextureProperty>();
internal bool _normalizeTexelDensity = false;
internal bool _considerNonTextureProperties = false;
internal MB3_TextureCombinerNonTextureProperties nonTexturePropertyBlender;
internal List<MB_TexSet> distinctMaterialTextures;
internal List<GameObject> allObjsToMesh;
internal List<Material> allowedMaterialsFilter;
internal List<ShaderTextureProperty> texPropertyNames;
internal CreateAtlasForProperty[] allTexturesAreNullAndSameColor;
internal int numAtlases;
internal Material resultMaterial;
}
internal static bool _ShouldWeCreateAtlasForThisProperty(int propertyIndex, bool considerNonTextureProperties, CreateAtlasForProperty[] allTexturesAreNullAndSameColor)
{
CreateAtlasForProperty v = allTexturesAreNullAndSameColor[propertyIndex];
if (considerNonTextureProperties)
{
if (!v.allNonTexturePropsAreSame || !v.allTexturesAreNull)
{
return true;
}
else
{
return false;
}
}
else
{
if (!v.allTexturesAreNull)
{
return true;
}
else
{
return false;
}
}
}
internal static bool _CollectPropertyNames(TexturePipelineData data, MB2_LogLevel LOG_LEVEL)
{
//try custom properties remove duplicates
for (int i = 0; i < data.texPropertyNames.Count; i++)
{
ShaderTextureProperty s = data._customShaderPropNames.Find(x => x.name.Equals(data.texPropertyNames[i].name));
if (s != null)
{
data._customShaderPropNames.Remove(s);
}
}
Material m = data.resultMaterial;
if (m == null)
{
Debug.LogError("Please assign a result material. The combined mesh will use this material.");
return false;
}
//Collect the property names for the textures
string shaderPropStr = "";
for (int i = 0; i < shaderTexPropertyNames.Length; i++)
{
if (m.HasProperty(shaderTexPropertyNames[i].name))
{
shaderPropStr += ", " + shaderTexPropertyNames[i].name;
if (!data.texPropertyNames.Contains(shaderTexPropertyNames[i])) data.texPropertyNames.Add(shaderTexPropertyNames[i]);
if (m.GetTextureOffset(shaderTexPropertyNames[i].name) != new Vector2(0f, 0f))
{
if (LOG_LEVEL >= MB2_LogLevel.warn) Debug.LogWarning("Result material has non-zero offset. This is may be incorrect.");
}
if (m.GetTextureScale(shaderTexPropertyNames[i].name) != new Vector2(1f, 1f))
{
if (LOG_LEVEL >= MB2_LogLevel.warn) Debug.LogWarning("Result material should have tiling of 1,1");
}
}
}
for (int i = 0; i < data._customShaderPropNames.Count; i++)
{
if (m.HasProperty(data._customShaderPropNames[i].name))
{
shaderPropStr += ", " + data._customShaderPropNames[i].name;
data.texPropertyNames.Add(data._customShaderPropNames[i]);
if (m.GetTextureOffset(data._customShaderPropNames[i].name) != new Vector2(0f, 0f))
{
if (LOG_LEVEL >= MB2_LogLevel.warn) Debug.LogWarning("Result material has non-zero offset. This is probably incorrect.");
}
if (m.GetTextureScale(data._customShaderPropNames[i].name) != new Vector2(1f, 1f))
{
if (LOG_LEVEL >= MB2_LogLevel.warn) Debug.LogWarning("Result material should probably have tiling of 1,1.");
}
}
else
{
if (LOG_LEVEL >= MB2_LogLevel.warn) Debug.LogWarning("Result material shader does not use property " + data._customShaderPropNames[i].name + " in the list of custom shader property names");
}
}
return true;
}
internal static bool _ShouldWeCreateAtlasForThisProperty(int propertyIndex, CreateAtlasForProperty[] allTexturesAreNullAndSameColor, TexturePipelineData data)
{
CreateAtlasForProperty v = allTexturesAreNullAndSameColor[propertyIndex];
if (data._considerNonTextureProperties)
{
if (!v.allNonTexturePropsAreSame || !v.allTexturesAreNull)
{
return true;
} else
{
return false;
}
} else
{
if (!v.allTexturesAreNull)
{
return true;
} else
{
return false;
}
}
}
//Fills distinctMaterialTextures (a list of TexSets) and usedObjsToMesh. Each TexSet is a rectangle in the set of atlases.
//If allowedMaterialsFilter is empty then all materials on allObjsToMesh will be collected and usedObjsToMesh will be same as allObjsToMesh
//else only materials in allowedMaterialsFilter will be included and usedObjsToMesh will be objs that use those materials.
//bool __step1_CollectDistinctMatTexturesAndUsedObjects;
internal static IEnumerator __Step1_CollectDistinctMatTexturesAndUsedObjects(ProgressUpdateDelegate progressInfo,
MB3_TextureCombiner.CombineTexturesIntoAtlasesCoroutineResult result,
TexturePipelineData data,
MB3_TextureCombiner combiner,
MB2_EditorMethodsInterface textureEditorMethods,
List<GameObject> usedObjsToMesh,
MB2_LogLevel LOG_LEVEL
) //Will be populated, is a subset of allObjsToMesh
{
System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
sw.Start();
// Collect distinct list of textures to combine from the materials on objsToCombine
bool outOfBoundsUVs = false;
Dictionary<int, MB_Utility.MeshAnalysisResult[]> meshAnalysisResultsCache = new Dictionary<int, MB_Utility.MeshAnalysisResult[]>(); //cache results
for (int i = 0; i < data.allObjsToMesh.Count; i++)
{
GameObject obj = data.allObjsToMesh[i];
if (progressInfo != null) progressInfo("Collecting textures for " + obj, ((float)i) / data.allObjsToMesh.Count / 2f);
if (LOG_LEVEL >= MB2_LogLevel.debug) Debug.Log("Collecting textures for object " + obj);
if (obj == null)
{
Debug.LogError("The list of objects to mesh contained nulls.");
result.success = false;
yield break;
}
Mesh sharedMesh = MB_Utility.GetMesh(obj);
if (sharedMesh == null)
{
Debug.LogError("Object " + obj.name + " in the list of objects to mesh has no mesh.");
result.success = false;
yield break;
}
Material[] sharedMaterials = MB_Utility.GetGOMaterials(obj);
if (sharedMaterials.Length == 0)
{
Debug.LogError("Object " + obj.name + " in the list of objects has no materials.");
result.success = false;
yield break;
}
//analyze mesh or grab cached result of previous analysis, stores one result for each submesh
MB_Utility.MeshAnalysisResult[] mar;
if (!meshAnalysisResultsCache.TryGetValue(sharedMesh.GetInstanceID(), out mar))
{
mar = new MB_Utility.MeshAnalysisResult[sharedMesh.subMeshCount];
for (int j = 0; j < sharedMesh.subMeshCount; j++)
{
MB_Utility.hasOutOfBoundsUVs(sharedMesh, ref mar[j], j);
if (data._normalizeTexelDensity)
{
mar[j].submeshArea = GetSubmeshArea(sharedMesh, j);
}
if (data._fixOutOfBoundsUVs && !mar[j].hasUVs)
{
//assume UVs will be generated if this feature is being used and generated UVs will be 0,0,1,1
mar[j].uvRect = new Rect(0, 0, 1, 1);
Debug.LogWarning("Mesh for object " + obj + " has no UV channel but 'consider UVs' is enabled. Assuming UVs will be generated filling 0,0,1,1 rectangle.");
}
}
meshAnalysisResultsCache.Add(sharedMesh.GetInstanceID(), mar);
}
if (data._fixOutOfBoundsUVs && LOG_LEVEL >= MB2_LogLevel.trace)
{
Debug.Log("Mesh Analysis for object " + obj + " numSubmesh=" + mar.Length + " HasOBUV=" + mar[0].hasOutOfBoundsUVs + " UVrectSubmesh0=" + mar[0].uvRect);
}
for (int matIdx = 0; matIdx < sharedMaterials.Length; matIdx++)
{ //for each submesh
if (progressInfo != null) progressInfo(String.Format("Collecting textures for {0} submesh {1}", obj, matIdx), ((float)i) / data.allObjsToMesh.Count / 2f);
Material mat = sharedMaterials[matIdx];
//check if this material is in the list of source materaials
if (data.allowedMaterialsFilter != null && !data.allowedMaterialsFilter.Contains(mat))
{
continue;
}
//Rect uvBounds = mar[matIdx].sourceUVRect;
outOfBoundsUVs = outOfBoundsUVs || mar[matIdx].hasOutOfBoundsUVs;
if (mat.name.Contains("(Instance)"))
{
Debug.LogError("The sharedMaterial on object " + obj.name + " has been 'Instanced'. This was probably caused by a script accessing the meshRender.material property in the editor. " +
" The material to UV Rectangle mapping will be incorrect. To fix this recreate the object from its prefab or re-assign its material from the correct asset.");
result.success = false;
yield break;
}
if (data._fixOutOfBoundsUVs)
{
if (!MB_Utility.AreAllSharedMaterialsDistinct(sharedMaterials))
{
if (LOG_LEVEL >= MB2_LogLevel.warn) Debug.LogWarning("Object " + obj.name + " uses the same material on multiple submeshes. This may generate strange resultAtlasesAndRects especially when used with fix out of bounds uvs. Try duplicating the material.");
}
}
//need to set up procedural material before converting its texs to texture2D
if (mat is ProceduralMaterial)
{
combiner._addProceduralMaterial((ProceduralMaterial)mat);
}
//collect textures scale and offset for each texture in objects material
MeshBakerMaterialTexture[] mts = new MeshBakerMaterialTexture[data.texPropertyNames.Count];
for (int j = 0; j < data.texPropertyNames.Count; j++)
{
Texture tx = null;
Vector2 scale = Vector2.one;
Vector2 offset = Vector2.zero;
float texelDensity = 0f;
if (mat.HasProperty(data.texPropertyNames[j].name))
{
Texture txx = mat.GetTexture(data.texPropertyNames[j].name);
if (txx != null)
{
if (txx is Texture2D)
{
tx = txx;
TextureFormat f = ((Texture2D)tx).format;
bool isNormalMap = false;
if (!Application.isPlaying && textureEditorMethods != null) isNormalMap = textureEditorMethods.IsNormalMap((Texture2D)tx);
if ((f == TextureFormat.ARGB32 ||
f == TextureFormat.RGBA32 ||
f == TextureFormat.BGRA32 ||
f == TextureFormat.RGB24 ||
f == TextureFormat.Alpha8) && !isNormalMap) //DXT5 does not work
{
//good
}
else
{
//TRIED to copy texture using tex2.SetPixels(tex1.GetPixels()) but bug in 3.5 means DTX1 and 5 compressed textures come out skewe
if (Application.isPlaying && data._packingAlgorithm != MB2_PackingAlgorithmEnum.MeshBakerTexturePacker_Fast)
{
Debug.LogError("Object " + obj.name + " in the list of objects to mesh uses Texture " + tx.name + " uses format " + f + " that is not in: ARGB32, RGBA32, BGRA32, RGB24, Alpha8 or DXT. These textures cannot be resized at runtime. Try changing texture format. If format says 'compressed' try changing it to 'truecolor'");
result.success = false;
yield break;
}
else
{
tx = (Texture2D)mat.GetTexture(data.texPropertyNames[j].name);
}
}
}
else if (txx is ProceduralTexture)
{
//if (!MBVersion.IsTextureFormatRaw(((ProceduralTexture)txx).format))
//{
// Debug.LogError("Object " + obj.name + " in the list of objects to mesh uses a ProceduarlTexture that is not in a RAW format. Convert textures to RAW.");
// result.success = false;
// yield break;
//}
tx = txx;
}
else
{
Debug.LogError("Object " + obj.name + " in the list of objects to mesh uses a Texture that is not a Texture2D. Cannot build atlases.");
result.success = false;
yield break;
}
}
if (tx != null && data._normalizeTexelDensity)
{
//todo this doesn't take into account tiling and out of bounds UV sampling
if (mar[j].submeshArea == 0)
{
texelDensity = 0f;
}
else
{
texelDensity = (tx.width * tx.height) / (mar[j].submeshArea);
}
}
scale = mat.GetTextureScale(data.texPropertyNames[j].name);
offset = mat.GetTextureOffset(data.texPropertyNames[j].name);
}
mts[j] = new MeshBakerMaterialTexture(tx, offset, scale, texelDensity);
}
Vector2 obUVscale = new Vector2(mar[matIdx].uvRect.width, mar[matIdx].uvRect.height);
Vector2 obUVoffset = new Vector2(mar[matIdx].uvRect.x, mar[matIdx].uvRect.y);
//Add to distinct set of textures if not already there
MB_TexSet setOfTexs = new MB_TexSet(mts, obUVoffset, obUVscale); //one of these per submesh
MatAndTransformToMerged matt = new MatAndTransformToMerged(mat);
setOfTexs.matsAndGOs.mats.Add(matt);
MB_TexSet setOfTexs2 = data.distinctMaterialTextures.Find(x => x.IsEqual(setOfTexs, data._fixOutOfBoundsUVs, data._considerNonTextureProperties, data.nonTexturePropertyBlender));
if (setOfTexs2 != null)
{
setOfTexs = setOfTexs2;
}
else
{
data.distinctMaterialTextures.Add(setOfTexs);
}
if (!setOfTexs.matsAndGOs.mats.Contains(matt))
{
setOfTexs.matsAndGOs.mats.Add(matt);
}
if (!setOfTexs.matsAndGOs.gos.Contains(obj))
{
setOfTexs.matsAndGOs.gos.Add(obj);
if (!usedObjsToMesh.Contains(obj)) usedObjsToMesh.Add(obj);
}
}
}
if (LOG_LEVEL >= MB2_LogLevel.debug) Debug.Log(String.Format("Step1_CollectDistinctTextures collected {0} sets of textures fixOutOfBoundsUV={1} considerNonTextureProperties={2}", data.distinctMaterialTextures.Count, data._fixOutOfBoundsUVs, data._considerNonTextureProperties));
if (data.distinctMaterialTextures.Count == 0)
{
Debug.LogError("None of the source object materials matched any of the allowed materials for this submesh.");
result.success = false;
yield break;
}
MB3_TextureCombinerMerging merger = new MB3_TextureCombinerMerging(data._considerNonTextureProperties, data.nonTexturePropertyBlender, data._fixOutOfBoundsUVs);
merger.MergeOverlappingDistinctMaterialTexturesAndCalcMaterialSubrects(data.distinctMaterialTextures);
if (LOG_LEVEL >= MB2_LogLevel.debug) Debug.Log("Total time Step1_CollectDistinctTextures " + (sw.ElapsedMilliseconds).ToString("f5"));
yield break;
}
//Textures in each material (_mainTex, Bump, Spec ect...) must be same size
//Calculate the best sized to use. Takes into account tiling
//if only one texture in atlas re-uses original sizes
internal static IEnumerator CalculateIdealSizesForTexturesInAtlasAndPadding(ProgressUpdateDelegate progressInfo,
MB3_TextureCombiner.CombineTexturesIntoAtlasesCoroutineResult result,
MB3_TextureCombinerPipeline.TexturePipelineData data,
MB3_TextureCombiner combiner,
MB2_EditorMethodsInterface textureEditorMethods,
MB2_LogLevel LOG_LEVEL)
{
System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
sw.Start();
MeshBakerMaterialTexture.readyToBuildAtlases = true;
// check if all textures are null and use same color for each atlas
// will not generate an atlas if so
for (int propIdx = 0; propIdx < data.texPropertyNames.Count; propIdx++)
{
MeshBakerMaterialTexture firstTexture = data.distinctMaterialTextures[0].ts[propIdx];
Color firstColor = Color.black;
if (data._considerNonTextureProperties)
{
firstColor = data.nonTexturePropertyBlender.GetColorIfNoTexture(data.distinctMaterialTextures[0].matsAndGOs.mats[0].mat, data.texPropertyNames[propIdx]);
}
int numTexturesExisting = 0;
int numTexturesMatchinFirst = 0;
int numNonTexturePropertiesMatchingFirst = 0;
for (int j = 0; j < data.distinctMaterialTextures.Count; j++)
{
if (!data.distinctMaterialTextures[j].ts[propIdx].isNull)
{
numTexturesExisting++;
}
if (firstTexture.AreTexturesEqual(data.distinctMaterialTextures[j].ts[propIdx]))
{
numTexturesMatchinFirst++;
}
if (data._considerNonTextureProperties)
{
Color colJ = data.nonTexturePropertyBlender.GetColorIfNoTexture(data.distinctMaterialTextures[j].matsAndGOs.mats[0].mat, data.texPropertyNames[propIdx]);
if (colJ == firstColor)
{
numNonTexturePropertiesMatchingFirst++;
}
}
}
data.allTexturesAreNullAndSameColor[propIdx].allTexturesAreNull = numTexturesExisting == 0;
data.allTexturesAreNullAndSameColor[propIdx].allTexturesAreSame = numTexturesMatchinFirst == data.distinctMaterialTextures.Count;
data.allTexturesAreNullAndSameColor[propIdx].allNonTexturePropsAreSame = numNonTexturePropertiesMatchingFirst == data.distinctMaterialTextures.Count;
if (LOG_LEVEL >= MB2_LogLevel.trace) Debug.Log(String.Format("AllTexturesAreNullAndSameColor prop: {0} createAtlas:{1} val:{2}", data.texPropertyNames[propIdx].name, MB3_TextureCombinerPipeline._ShouldWeCreateAtlasForThisProperty(propIdx, data._considerNonTextureProperties, data.allTexturesAreNullAndSameColor), data.allTexturesAreNullAndSameColor[propIdx]));
}
//calculate size of rectangles in atlas
int _padding = data._atlasPadding;
if (data.distinctMaterialTextures.Count == 1 && data._fixOutOfBoundsUVs == false)
{
if (LOG_LEVEL >= MB2_LogLevel.info) Debug.Log("All objects use the same textures in this set of atlases. Original textures will be reused instead of creating atlases.");
_padding = 0;
}
else
{
if (data.allTexturesAreNullAndSameColor.Length != data.texPropertyNames.Count)
{
Debug.LogError("allTexturesAreNullAndSameColor array must be the same length of texPropertyNames.");
}
for (int i = 0; i < data.distinctMaterialTextures.Count; i++)
{
if (LOG_LEVEL >= MB2_LogLevel.debug) Debug.Log("Calculating ideal sizes for texSet TexSet " + i + " of " + data.distinctMaterialTextures.Count);
MB_TexSet txs = data.distinctMaterialTextures[i];
txs.idealWidth = 1;
txs.idealHeight = 1;
int tWidth = 1;
int tHeight = 1;
if (txs.ts.Length != data.texPropertyNames.Count)
{
Debug.LogError("length of arrays in each element of distinctMaterialTextures must be texPropertyNames.Count");
}
//get the best size all textures in a TexSet must be the same size.
for (int propIdx = 0; propIdx < data.texPropertyNames.Count; propIdx++)
{
MeshBakerMaterialTexture matTex = txs.ts[propIdx];
if (!matTex.matTilingRect.size.Equals(Vector2.one) && data.distinctMaterialTextures.Count > 1)
{
if (LOG_LEVEL >= MB2_LogLevel.warn) Debug.LogWarning("Texture " + matTex.GetTexName() + "is tiled by " + matTex.matTilingRect.size + " tiling will be baked into a texture with maxSize:" + data._maxTilingBakeSize);
}
if (!txs.obUVscale.Equals(Vector2.one) && data.distinctMaterialTextures.Count > 1 && data._fixOutOfBoundsUVs)
{
if (LOG_LEVEL >= MB2_LogLevel.warn) Debug.LogWarning("Texture " + matTex.GetTexName() + "has out of bounds UVs that effectively tile by " + txs.obUVscale + " tiling will be baked into a texture with maxSize:" + data._maxTilingBakeSize);
}
if (MB3_TextureCombinerPipeline._ShouldWeCreateAtlasForThisProperty(propIdx, data._considerNonTextureProperties, data.allTexturesAreNullAndSameColor) && matTex.isNull)
{
//create a small 16 x 16 texture to use in the atlas
if (LOG_LEVEL >= MB2_LogLevel.trace) Debug.Log("No source texture creating a 16x16 texture for " + data.texPropertyNames[propIdx].name);
matTex.t = combiner._createTemporaryTexture(16, 16, TextureFormat.ARGB32, true);
if (data._considerNonTextureProperties && data.nonTexturePropertyBlender != null)
{
Color col = data.nonTexturePropertyBlender.GetColorIfNoTexture(txs.matsAndGOs.mats[0].mat, data.texPropertyNames[propIdx]);
if (LOG_LEVEL >= MB2_LogLevel.trace) Debug.Log("Setting texture to solid color " + col);
MB_Utility.setSolidColor(matTex.GetTexture2D(), col);
}
else
{
Color col = MB3_TextureCombinerNonTextureProperties.GetColorIfNoTexture(data.texPropertyNames[propIdx]);
MB_Utility.setSolidColor(matTex.GetTexture2D(), col);
}
if (data._fixOutOfBoundsUVs)
{
matTex.encapsulatingSamplingRect = txs.obUVrect;
}
else
{
matTex.encapsulatingSamplingRect = new DRect(0, 0, 1, 1);
}
}
if (!matTex.isNull)
{
Vector2 dim = MB3_TextureCombinerPipeline.GetAdjustedForScaleAndOffset2Dimensions(matTex, txs.obUVoffset, txs.obUVscale, data, LOG_LEVEL);
if ((int)(dim.x * dim.y) > tWidth * tHeight)
{
if (LOG_LEVEL >= MB2_LogLevel.trace) Debug.Log(" matTex " + matTex.GetTexName() + " " + dim + " has a bigger size than " + tWidth + " " + tHeight);
tWidth = (int)dim.x;
tHeight = (int)dim.y;
}
}
}
if (data._resizePowerOfTwoTextures)
{
if (tWidth <= _padding * 5)
{
Debug.LogWarning(String.Format("Some of the textures have widths close to the size of the padding. It is not recommended to use _resizePowerOfTwoTextures with widths this small.", txs.ToString()));
}
if (tHeight <= _padding * 5)
{
Debug.LogWarning(String.Format("Some of the textures have heights close to the size of the padding. It is not recommended to use _resizePowerOfTwoTextures with heights this small.", txs.ToString()));
}
if (IsPowerOfTwo(tWidth))
{
tWidth -= _padding * 2;
}
if (IsPowerOfTwo(tHeight))
{
tHeight -= _padding * 2;
}
if (tWidth < 1) tWidth = 1;
if (tHeight < 1) tHeight = 1;
}
if (LOG_LEVEL >= MB2_LogLevel.trace) Debug.Log(" Ideal size is " + tWidth + " " + tHeight);
txs.idealWidth = tWidth;
txs.idealHeight = tHeight;
}
}
if (LOG_LEVEL >= MB2_LogLevel.debug) Debug.Log("Total time Step2 Calculate Ideal Sizes part1: " + sw.Elapsed.ToString());
//convert textures to readable formats here.
if (data.distinctMaterialTextures.Count > 1)
{
//make procedural materials readable
for (int i = 0; i < combiner._proceduralMaterials.Count; i++)
{
if (!combiner._proceduralMaterials[i].proceduralMat.isReadable)
{
combiner._proceduralMaterials[i].originalIsReadableVal = combiner._proceduralMaterials[i].proceduralMat.isReadable;
combiner._proceduralMaterials[i].proceduralMat.isReadable = true;
//textureEditorMethods.AddProceduralMaterialFormat(_proceduralMaterials[i].proceduralMat);
combiner._proceduralMaterials[i].proceduralMat.RebuildTexturesImmediately();
}
}
//convert procedural textures to RAW format
/*
for (int i = 0; i < distinctMaterialTextures.Count; i++)
{
for (int j = 0; j < texPropertyNames.Count; j++)
{
if (distinctMaterialTextures[i].ts[j].IsProceduralTexture())
{
if (LOG_LEVEL >= MB2_LogLevel.debug) Debug.Log("Converting procedural texture to Textur2D:" + distinctMaterialTextures[i].ts[j].GetTexName() + " property:" + texPropertyNames[i]);
Texture2D txx = distinctMaterialTextures[i].ts[j].ConvertProceduralToTexture2D(_temporaryTextures);
distinctMaterialTextures[i].ts[j].t = txx;
}
}
}
*/
if (data._packingAlgorithm != MB2_PackingAlgorithmEnum.MeshBakerTexturePacker_Fast)
{
for (int i = 0; i < data.distinctMaterialTextures.Count; i++)
{
for (int j = 0; j < data.texPropertyNames.Count; j++)
{
Texture tx = data.distinctMaterialTextures[i].ts[j].GetTexture2D();
if (tx != null)
{
if (textureEditorMethods != null)
{
if (progressInfo != null) progressInfo(String.Format("Convert texture {0} to readable format ", tx), .5f);
textureEditorMethods.AddTextureFormat((Texture2D)tx, data.texPropertyNames[j].isNormalMap);
}
}
}
}
}
}
if (LOG_LEVEL >= MB2_LogLevel.debug) Debug.Log("Total time Step2 Calculate Ideal Sizes part2: " + sw.Elapsed.ToString());
data._atlasPadding = _padding;
yield break;
}
internal static AtlasPackingResult[] __Step3_RunTexturePacker(TexturePipelineData data, MB2_LogLevel LOG_LEVEL)
{
AtlasPackingResult[] apr = __RuntTexturePackerOnly(data, LOG_LEVEL);
//copy materials PackingResults
for (int i = 0; i < apr.Length; i++)
{
List<MatsAndGOs> matsList = new List<MatsAndGOs>();
apr[i].data = matsList;
for (int j = 0; j < apr[i].srcImgIdxs.Length; j++)
{
MB_TexSet ts = data.distinctMaterialTextures[apr[i].srcImgIdxs[j]];
matsList.Add(ts.matsAndGOs);
}
}
return apr;
}
internal static MB_ITextureCombinerPacker CreatePacker(MB2_PackingAlgorithmEnum packingAlgorithm) {
if (packingAlgorithm == MB2_PackingAlgorithmEnum.UnitysPackTextures)
{
return new MB3_TextureCombinerPackerUnity();
}
else if (packingAlgorithm == MB2_PackingAlgorithmEnum.MeshBakerTexturePacker || packingAlgorithm == MB2_PackingAlgorithmEnum.MeshBakerTexturePacker_Horizontal || packingAlgorithm == MB2_PackingAlgorithmEnum.MeshBakerTexturePacker_Vertical)
{
return new MB3_TextureCombinerPackerMeshBaker();
}
else
{
return new MB3_TextureCombinerPackerMeshBakerFast();
}
}
internal static IEnumerator __Step3_BuildAndSaveAtlasesAndStoreResults(MB3_TextureCombiner.CombineTexturesIntoAtlasesCoroutineResult result,
ProgressUpdateDelegate progressInfo,
TexturePipelineData data,
MB3_TextureCombiner combiner,
MB_ITextureCombinerPacker packer,
AtlasPackingResult atlasPackingResult,
MB2_EditorMethodsInterface textureEditorMethods, MB_AtlasesAndRects resultAtlasesAndRects,
StringBuilder report,
MB2_LogLevel LOG_LEVEL)
{
System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
sw.Start();
// note that we may not create some of the atlases because all textures are null
data.numAtlases = data.texPropertyNames.Count;
//run the garbage collector to free up as much memory as possible before bake to reduce MissingReferenceException problems
GC.Collect();
Texture2D[] atlases = new Texture2D[data.numAtlases];
if (LOG_LEVEL >= MB2_LogLevel.debug) Debug.Log("time Step 3 Create And Save Atlases part 1 " + sw.Elapsed.ToString());
yield return packer.CreateAtlases(progressInfo, data, combiner, atlasPackingResult, atlases, textureEditorMethods, LOG_LEVEL);
float t3 = sw.ElapsedMilliseconds;
if (data.nonTexturePropertyBlender != null)
{
data.nonTexturePropertyBlender.AdjustNonTextureProperties(data.resultMaterial, data.texPropertyNames, data.distinctMaterialTextures, data._considerNonTextureProperties, textureEditorMethods);
}
if (progressInfo != null) progressInfo("Building Report", .7f);
//report on atlases created
StringBuilder atlasMessage = new StringBuilder();
atlasMessage.AppendLine("---- Atlases ------");
for (int i = 0; i < data.numAtlases; i++)
{
if (atlases[i] != null)
{
atlasMessage.AppendLine("Created Atlas For: " + data.texPropertyNames[i].name + " h=" + atlases[i].height + " w=" + atlases[i].width);
}
else if (!_ShouldWeCreateAtlasForThisProperty(i, data._considerNonTextureProperties, data.allTexturesAreNullAndSameColor))
{
atlasMessage.AppendLine("Did not create atlas for " + data.texPropertyNames[i].name + " because all source textures were null.");
}
}
report.Append(atlasMessage.ToString());
List<MB_MaterialAndUVRect> mat2rect_map = new List<MB_MaterialAndUVRect>();
for (int i = 0; i < data.distinctMaterialTextures.Count; i++)
{
List<MatAndTransformToMerged> mats = data.distinctMaterialTextures[i].matsAndGOs.mats;
Rect fullSamplingRect = new Rect(0, 0, 1, 1);
if (data.distinctMaterialTextures[i].ts.Length > 0)
{
if (data.distinctMaterialTextures[i].allTexturesUseSameMatTiling)
{
fullSamplingRect = data.distinctMaterialTextures[i].ts[0].encapsulatingSamplingRect.GetRect();
}
else
{
fullSamplingRect = data.distinctMaterialTextures[i].obUVrect.GetRect();
}
}
for (int j = 0; j < mats.Count; j++)
{
MB_MaterialAndUVRect key = new MB_MaterialAndUVRect(mats[j].mat, atlasPackingResult.rects[i], mats[j].samplingRectMatAndUVTiling.GetRect(), mats[j].materialTiling.GetRect(), fullSamplingRect, mats[j].objName);
if (!mat2rect_map.Contains(key))
{
mat2rect_map.Add(key);
}
}
}
resultAtlasesAndRects.atlases = atlases; // one per texture on result shader
resultAtlasesAndRects.texPropertyNames = ShaderTextureProperty.GetNames(data.texPropertyNames); // one per texture on source shader
resultAtlasesAndRects.mat2rect_map = mat2rect_map;
if (progressInfo != null) progressInfo("Restoring Texture Formats & Read Flags", .8f);
combiner._destroyTemporaryTextures();
if (textureEditorMethods != null) textureEditorMethods.RestoreReadFlagsAndFormats(progressInfo);
if (report != null && LOG_LEVEL >= MB2_LogLevel.info) Debug.Log(report.ToString());
if (LOG_LEVEL >= MB2_LogLevel.debug) Debug.Log("Time Step 3 Create And Save Atlases part 3 " + (sw.ElapsedMilliseconds - t3).ToString("f5"));
if (LOG_LEVEL >= MB2_LogLevel.debug) Debug.Log("Total time Step 3 Create And Save Atlases " + sw.Elapsed.ToString());
yield break;
}
internal static StringBuilder GenerateReport(MB3_TextureCombinerPipeline.TexturePipelineData data)
{
//generate report want to do this before
StringBuilder report = new StringBuilder();
if (data.numAtlases > 0)
{
report = new StringBuilder();
report.AppendLine("Report");
for (int i = 0; i < data.distinctMaterialTextures.Count; i++)
{
MB_TexSet txs = data.distinctMaterialTextures[i];
report.AppendLine("----------");
report.Append("This set of textures will be resized to:" + txs.idealWidth + "x" + txs.idealHeight + "\n");
for (int j = 0; j < txs.ts.Length; j++)
{
if (!txs.ts[j].isNull)
{
report.Append(" [" + data.texPropertyNames[j].name + " " + txs.ts[j].GetTexName() + " " + txs.ts[j].width + "x" + txs.ts[j].height + "]");
if (txs.ts[j].matTilingRect.size != Vector2.one || txs.ts[j].matTilingRect.min != Vector2.zero) report.AppendFormat(" material scale {0} offset{1} ", txs.ts[j].matTilingRect.size.ToString("G4"), txs.ts[j].matTilingRect.min.ToString("G4"));
if (txs.obUVscale != Vector2.one || txs.obUVoffset != Vector2.zero) report.AppendFormat(" obUV scale {0} offset{1} ", txs.obUVscale.ToString("G4"), txs.obUVoffset.ToString("G4"));
report.AppendLine("");
}
else
{
report.Append(" [" + data.texPropertyNames[j].name + " null ");
if (!MB3_TextureCombinerPipeline._ShouldWeCreateAtlasForThisProperty(j, data._considerNonTextureProperties, data.allTexturesAreNullAndSameColor))
{
report.Append("no atlas will be created all textures null]\n");
}
else
{
report.AppendFormat("a 16x16 texture will be created]\n");
}
}
}
report.AppendLine("");
report.Append("Materials using:");
for (int j = 0; j < txs.matsAndGOs.mats.Count; j++)
{
report.Append(txs.matsAndGOs.mats[j].mat.name + ", ");
}
report.AppendLine("");
}
}
return report;
}
internal static AtlasPackingResult[] __RuntTexturePackerOnly(TexturePipelineData data, MB2_LogLevel LOG_LEVEL)
{
AtlasPackingResult[] packerRects;
if (data.distinctMaterialTextures.Count == 1 && data._fixOutOfBoundsUVs == false)
{
if (LOG_LEVEL >= MB2_LogLevel.debug) Debug.Log("Only one image per atlas. Will re-use original texture");
packerRects = new AtlasPackingResult[1];
AtlasPadding[] paddings = new AtlasPadding[] { new AtlasPadding(data._atlasPadding) };
packerRects[0] = new AtlasPackingResult(paddings);
packerRects[0].rects = new Rect[1];
packerRects[0].srcImgIdxs = new int[] { 0 };
packerRects[0].rects[0] = new Rect(0f, 0f, 1f, 1f);
MeshBakerMaterialTexture dmt = null;
if (data.distinctMaterialTextures[0].ts.Length > 0)
{
dmt = data.distinctMaterialTextures[0].ts[0];
}
packerRects[0].atlasX = dmt.isNull ? 16 : dmt.width;
packerRects[0].atlasY = dmt.isNull ? 16 : dmt.height;
packerRects[0].usedW = dmt.isNull ? 16 : dmt.width;
packerRects[0].usedH = dmt.isNull ? 16 : dmt.height;
}
else
{
List<Vector2> imageSizes = new List<Vector2>();
List<AtlasPadding> paddings = new List<AtlasPadding>();
for (int i = 0; i < data.distinctMaterialTextures.Count; i++)
{
imageSizes.Add(new Vector2(data.distinctMaterialTextures[i].idealWidth, data.distinctMaterialTextures[i].idealHeight));
paddings.Add(new AtlasPadding(data._atlasPadding));
}
MB2_TexturePacker tp = CreateTexturePacker(data._packingAlgorithm);
tp.atlasMustBePowerOfTwo = data._meshBakerTexturePackerForcePowerOfTwo;
packerRects = tp.GetRects(imageSizes, paddings, data._maxAtlasSize, data._maxAtlasSize, true);
//Debug.Assert(packerRects.Length != 0);
}
return packerRects;
}
internal static MB2_TexturePacker CreateTexturePacker(MB2_PackingAlgorithmEnum _packingAlgorithm)
{
if (_packingAlgorithm == MB2_PackingAlgorithmEnum.MeshBakerTexturePacker)
{
return new MB2_TexturePackerRegular();
}
else if (_packingAlgorithm == MB2_PackingAlgorithmEnum.MeshBakerTexturePacker_Fast)
{
return new MB2_TexturePackerRegular();
}
else if (_packingAlgorithm == MB2_PackingAlgorithmEnum.MeshBakerTexturePacker_Horizontal)
{
MB2_TexturePackerHorizontalVert tp = new MB2_TexturePackerHorizontalVert();
tp.packingOrientation = MB2_TexturePackerHorizontalVert.TexturePackingOrientation.horizontal;
return tp;
}
else if (_packingAlgorithm == MB2_PackingAlgorithmEnum.MeshBakerTexturePacker_Vertical)
{
MB2_TexturePackerHorizontalVert tp = new MB2_TexturePackerHorizontalVert();
tp.packingOrientation = MB2_TexturePackerHorizontalVert.TexturePackingOrientation.vertical;
return tp;
}
else
{
Debug.LogError("packing algorithm must be one of the MeshBaker options to create a Texture Packer");
}
return null;
}
internal static Vector2 GetAdjustedForScaleAndOffset2Dimensions(MeshBakerMaterialTexture source, Vector2 obUVoffset, Vector2 obUVscale, TexturePipelineData data, MB2_LogLevel LOG_LEVEL)
{
if (source.matTilingRect.x == 0f && source.matTilingRect.y == 0f && source.matTilingRect.width == 1f && source.matTilingRect.height == 1f)
{
if (data._fixOutOfBoundsUVs)
{
if (obUVoffset.x == 0f && obUVoffset.y == 0f && obUVscale.x == 1f && obUVscale.y == 1f)
{
return new Vector2(source.width, source.height); //no adjustment necessary
}
}
else
{
return new Vector2(source.width, source.height); //no adjustment necessary
}
}
if (LOG_LEVEL >= MB2_LogLevel.debug) Debug.Log("GetAdjustedForScaleAndOffset2Dimensions: " + source.GetTexName() + " " + obUVoffset + " " + obUVscale);
float newWidth = (float)source.encapsulatingSamplingRect.width * source.width;
float newHeight = (float)source.encapsulatingSamplingRect.height * source.height;
if (newWidth > data._maxTilingBakeSize) newWidth = data._maxTilingBakeSize;
if (newHeight > data._maxTilingBakeSize) newHeight = data._maxTilingBakeSize;
if (newWidth < 1f) newWidth = 1f;
if (newHeight < 1f) newHeight = 1f;
return new Vector2(newWidth, newHeight);
}
internal static DRect GetSourceSamplingRect(MeshBakerMaterialTexture source, Vector2 obUVoffset, Vector2 obUVscale)
{
DRect rMatTiling = source.matTilingRect;
DRect rUVTiling = new DRect(obUVoffset, obUVscale);
DRect r = MB3_UVTransformUtility.CombineTransforms(ref rMatTiling, ref rUVTiling);
return r;
}
/*
Unity uses a non-standard format for storing normals for some platforms. Imagine the standard format is English, Unity's is French
When the normal-map checkbox is ticked on the asset importer the normal map is translated into french. When we build the normal atlas
we are reading the french. When we save and click the normal map tickbox we are translating french -> french. A double transladion that
breaks the normal map. To fix this we need to "unconvert" the normal map to english when saving the atlas as a texture so that unity importer
can do its thing properly.
*/
internal static Color32 ConvertNormalFormatFromUnity_ToStandard(Color32 c)
{
Vector3 n = Vector3.zero;
n.x = c.a * 2f - 1f;
n.y = c.g * 2f - 1f;
n.z = Mathf.Sqrt(1 - n.x * n.x - n.y * n.y);
//now repack in the regular format
Color32 cc = new Color32();
cc.a = 1;
cc.r = (byte)((n.x + 1f) * .5f);
cc.g = (byte)((n.y + 1f) * .5f);
cc.b = (byte)((n.z + 1f) * .5f);
return cc;
}
internal static float GetSubmeshArea(Mesh m, int submeshIdx)
{
if (submeshIdx >= m.subMeshCount || submeshIdx < 0)
{
return 0f;
}
Vector3[] vs = m.vertices;
int[] tris = m.GetIndices(submeshIdx);
float area = 0f;
for (int i = 0; i < tris.Length; i += 3)
{
Vector3 v0 = vs[tris[i]];
Vector3 v1 = vs[tris[i + 1]];
Vector3 v2 = vs[tris[i + 2]];
Vector3 cross = Vector3.Cross(v1 - v0, v2 - v0);
area += cross.magnitude / 2f;
}
return area;
}
internal static bool IsPowerOfTwo(int x)
{
return (x & (x - 1)) == 0;
}
}
}
| 55.629857 | 378 | 0.527626 | [
"Apache-2.0"
] | lmj921/PerformanceExample | PerformanceExample/Assets/MeshBaker/scripts/core/TextureCombiner/MB3_TextureCombinerPipeline.cs | 54,407 | C# |
namespace CHUSHKA.Service
{
using CHUSHKA.Data;
using CHUSHKA.Models;
using CHUSHKA.Service.Contracts;
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.EntityFrameworkCore;
public class OrdersService : IOrdersService
{
private readonly ChushkaDbContext db;
public OrdersService(ChushkaDbContext db)
{
this.db = db;
}
public IEnumerable<Order> AllOrders()
{
return this.db.Orders
.Include(x => x.Client)
.Include(x => x.Product)
.ToList();
}
public Order GetOrderById(int id)
{
throw new NotImplementedException();
}
public void MakeOrder(Order order)
{
if (order == null)
{
return;
}
this.db.Orders.AddAsync(order).Wait();
this.db.SaveChanges();
}
}
} | 22.681818 | 50 | 0.527054 | [
"MIT"
] | SonicTheCat/ASP.NET-Core | 02.Introduction to Razor - Views and Layouts/CHUSHKA/CHUSHKA.Service/OrdersService.cs | 1,000 | C# |
using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
namespace Multiverse.ToolBox
{
public class valueItem
{
public string value = "";
public string type = "";
public List<string> enumList = new List<string>();
}
public class NameValueObject : IEnumerable<valueItem>
{
public Dictionary<string, valueItem> nameValuePairs;
public NameValueObject()
{
nameValuePairs = new Dictionary<string, valueItem>();
}
public NameValueObject(XmlReader r)
{
nameValuePairs = new Dictionary<string, valueItem>();
parseNameValuePairs(r);
return;
}
public NameValueObject(NameValueObject nvo)
{
this.nameValuePairs = new Dictionary<string, valueItem>();
foreach (string name in nvo.NameValuePairKeyList())
{
valueItem value = new valueItem();
nvo.nameValuePairs.TryGetValue(name, out value);
if (value.type == "Enum" && value.enumList.Count > 0)
{
this.AddNameValuePair(name, value.value, value.enumList);
}
else
{
this.AddNameValuePair(name, value.value, value.type);
}
}
}
public int Count
{
get
{
return nameValuePairs.Count;
}
}
protected void parseNameValuePair(XmlReader r)
{
string valName = "";
valueItem value = new valueItem();
for (int i = 0; i < r.AttributeCount; i++)
{
r.MoveToAttribute(i);
switch (r.Name)
{
case "Name":
valName = r.Value;
break;
case "Value":
value.value = r.Value;
break;
case "Type":
value.type = r.Value;
break;
}
}
if (String.Equals(value.type, "Enum"))
{
r.MoveToElement();
value.enumList = parseEnumList(r);
}
this.AddNameValuePair(valName, value);
r.MoveToElement();
}
protected List<string> parseEnumList(XmlReader r)
{
List<string> enumList = null;
while (r.Read())
{
if (r.NodeType == XmlNodeType.Whitespace)
{
continue;
}
if (r.NodeType == XmlNodeType.EndElement)
{
break;
}
if (r.NodeType == XmlNodeType.Element)
{
switch (r.Name)
{
case "Enum":
enumList = parseEnumItems(r);
break;
}
}
}
return enumList;
}
protected List<string> parseEnumItems(XmlReader r)
{
List<string> enumList = new List<string>();
while (r.Read())
{
if (r.NodeType == XmlNodeType.Whitespace)
{
continue;
}
if (r.NodeType == XmlNodeType.EndElement)
{
break;
}
if (r.NodeType == XmlNodeType.Element)
{
switch (r.Name)
{
case "EnumItem":
string item = parseEnumItem(r);
enumList.Add(item);
break;
}
}
}
return enumList;
}
protected string parseEnumItem(XmlReader r)
{
string enumItem = "";
while (r.Read())
{
if (r.NodeType == XmlNodeType.Whitespace)
{
continue;
}
if (r.NodeType == XmlNodeType.Text)
{
enumItem = r.Value;
}
if (r.NodeType == XmlNodeType.EndElement)
{
break;
}
}
return enumItem;
}
protected void parseNameValuePairs(XmlReader r)
{
while (r.Read())
{
if (r.NodeType == XmlNodeType.Whitespace)
{
continue;
}
if (r.NodeType == XmlNodeType.EndElement)
{
break;
}
if (r.NodeType == XmlNodeType.Element)
{
switch (r.Name)
{
case "NameValuePair":
parseNameValuePair(r);
break;
}
}
}
}
public void AddNameValuePair(string name, string value, List<string> enumList)
{
valueItem item = new valueItem();
item.type = "Enum";
foreach (string eitem in enumList)
{
item.enumList.Add(eitem);
}
item.value = value;
this.nameValuePairs.Add(name, item);
}
public void AddNameValuePair(string name, string value, string type)
{
valueItem item = new valueItem();
item.type = type;
item.value = value;
this.nameValuePairs.Add(name, item);
}
public void AddNameValuePair(string name, string value)
{
valueItem item = new valueItem();
item.type = "String";
item.value = value;
this.nameValuePairs.Add(name, item);
}
public void AddNameValuePair(string name, valueItem value)
{
this.nameValuePairs.Add(name, value);
}
public valueItem LookUp(string name)
{
valueItem value = new valueItem();
if (this.nameValuePairs.TryGetValue(name, out value))
{
return value;
}
return null;
}
public Dictionary<string, valueItem> CopyNameValueObject()
{
NameValueObject dest = new NameValueObject();
foreach(string name in this.NameValuePairKeyList())
{
valueItem value = new valueItem();
this.nameValuePairs.TryGetValue(name, out value);
dest.AddNameValuePair(name, value.value, value.enumList);
}
return dest.nameValuePairs;
}
public void SetNameValueObject(Dictionary<string,valueItem> source)
{
this.nameValuePairs.Clear();
foreach (string name in source.Keys)
{
valueItem value = new valueItem();
source.TryGetValue(name, out value);
this.nameValuePairs.Add(name, value);
}
return;
}
public void EditNameValuePair(string oldName, string newName, string newValue, string type, List<string> enumList)
{
this.nameValuePairs.Remove(oldName);
valueItem value = new valueItem();
value.value = newValue;
value.type = type;
if (enumList != null)
{
value.enumList = new List<string>(enumList);
}
this.nameValuePairs.Add(newName, value);
}
public void RemoveNameValuePair(string delName)
{
this.nameValuePairs.Remove(delName);
}
public void ToXml(XmlWriter w)
{
if (nameValuePairs.Count > 0)
{
w.WriteStartElement("NameValuePairs");
foreach (string namekey in nameValuePairs.Keys)
{
w.WriteStartElement("NameValuePair");
w.WriteAttributeString("Name", namekey);
valueItem value = new valueItem();
nameValuePairs.TryGetValue(namekey, out value);
w.WriteAttributeString("Value", value.value);
w.WriteAttributeString("Type", value.type);
if (String.Equals(value.type, "Enum") && value.enumList != null && value.enumList.Count != 0)
{
w.WriteStartElement("Enum");
foreach (string enumElement in value.enumList)
{
w.WriteElementString("EnumItem", enumElement);
}
w.WriteEndElement();
}
w.WriteEndElement();
}
w.WriteEndElement();
}
}
public List<string> NameValuePairKeyList()
{
List<string> list = new List<string>();
if (this.nameValuePairs != null)
{
foreach (string key in this.nameValuePairs.Keys)
{
{
list.Add(key);
}
}
}
return list;
}
#region IEnumerable<valueItem> Members
public IEnumerator<valueItem> GetEnumerator()
{
return nameValuePairs.Values.GetEnumerator();
}
#endregion
#region IEnumerable Members
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return this.nameValuePairs.Values.GetEnumerator();
}
#endregion
}
}
| 26.546784 | 116 | 0.490583 | [
"MIT"
] | AustralianDisabilityLimited/MultiversePlatform | lib/NameValuePairs/NameValuePairs/NameValueObject.cs | 9,079 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using AutoMapper;
using LightXun.Study.FakeXiecheng.API.Services;
using LightXun.Study.FakeXiecheng.API.Dtos;
using LightXun.Study.FakeXiecheng.API.Models;
namespace LightXun.Study.FakeXiecheng.API.Controllers
{
[Route("api/touristRoutes/{touristRouteId}/pictures")]
[ApiController]
public class TouristRoutePicturesController: ControllerBase
{
private ITouristRouteRepository _touristRouteRepository;
private readonly IMapper _mapper;
public TouristRoutePicturesController(
ITouristRouteRepository touristRouteRepository,
IMapper mapper)
{
_touristRouteRepository = touristRouteRepository;
_mapper = mapper;
}
[HttpGet(Name = "GetPictureListForTouristRoute")]
public async Task<IActionResult> GetPictureListForTouristRoute(Guid touristRouteId)
{
if (!( await _touristRouteRepository.TouristRouteExistsAsync(touristRouteId)))
{
return NotFound("旅游路线不存在");
}
var picturesFromRepo = await _touristRouteRepository.GetPicturesByTouristRouteIdAsync(touristRouteId);
if(picturesFromRepo == null || picturesFromRepo.Count() <= 0)
{
return NotFound("图片不存在");
}
return Ok(_mapper.Map<IEnumerable<TouristRoutePictureDto>>(picturesFromRepo));
}
[HttpGet("{pictureId}", Name = "GetPicture")]
public async Task<IActionResult> GetPicture(Guid touristRouteId, int pictureId)
{
if (!(await _touristRouteRepository.TouristRouteExistsAsync(touristRouteId)))
{
return NotFound("旅游路线不存在");
}
var pictureFromRepo = await _touristRouteRepository.GetPictureAsync(pictureId);
if(pictureFromRepo == null)
{
return NotFound("图片不存在");
}
return Ok(_mapper.Map<TouristRoutePictureDto>(pictureFromRepo));
}
[HttpPost(Name = "CreateTouristRoutePicture")]
public async Task<IActionResult> CreateTouristRoutePicture(
[FromRoute] Guid touristRouteId,
[FromBody] TouristRoutePictureForCreationDto touristRoutePictureForCreationDto)
{
if (!(await _touristRouteRepository.TouristRouteExistsAsync(touristRouteId)))
{
return NotFound("旅游路线不存在");
}
var pictureModel = _mapper.Map<TouristRoutePicture>(touristRoutePictureForCreationDto);
_touristRouteRepository.AddTouristRoutePicture(touristRouteId, pictureModel);
await _touristRouteRepository.SaveAsync();
var pictureToReturn = _mapper.Map<TouristRoutePictureDto>(pictureModel);
return CreatedAtRoute(
"GetPicture",
new { touristRouteId = pictureModel.TouristRouteId, pictureId = pictureModel.Id },
pictureToReturn
);
}
[HttpDelete("{pictureId}")]
public async Task<IActionResult> DeletePicture(
[FromRoute]Guid touristRouteId,
[FromRoute]int pictureId)
{
if(!(await _touristRouteRepository.TouristRouteExistsAsync(touristRouteId)))
{
return NotFound("旅游路线不存在");
}
var picture = await _touristRouteRepository.GetPictureAsync(pictureId);
_touristRouteRepository.DeleteTouristRoutePicture(picture);
await _touristRouteRepository.SaveAsync();
return NoContent();
}
}
}
| 36.300971 | 114 | 0.644825 | [
"MIT"
] | lightxun/LXDP | 91.Code/LightXun.Study.FakeXiecheng.API/Controllers/TouristRoutePicturesController.cs | 3,817 | C# |
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using WalkingTec.Mvvm.Core;
using WalkingTec.Mvvm.Core.Extensions;
using WalkingTec.Mvvm.Mvc;
using WalkingTec.Mvvm.Mvc.Admin.ViewModels.DataPrivilegeVMs;
namespace WalkingTec.Mvvm.Admin.Api
{
[ActionDescription("数据权限")]
[ApiController]
[Route("api/_DataPrivilege")]
public class DataPrivilegeController : BaseApiController
{
[ActionDescription("搜索")]
[HttpPost("Search")]
public string Search(DataPrivilegeSearcher searcher)
{
var vm = CreateVM<DataPrivilegeListVM>();
vm.Searcher = searcher;
return vm.GetJson();
}
[ActionDescription("获取")]
[HttpGet("Get")]
public DataPrivilegeVM Get(string TableName, Guid TargetId, DpTypeEnum DpType)
{
DataPrivilegeVM vm = null;
if (DpType == DpTypeEnum.User)
{
vm = CreateVM<DataPrivilegeVM>(values: x => x.Entity.TableName == TableName && x.Entity.UserId == TargetId && x.DpType == DpType);
vm.UserItCode = DC.Set<FrameworkUserBase>().Where(x => x.ID == TargetId).Select(x => x.ITCode).FirstOrDefault();
}
else
{
vm = CreateVM<DataPrivilegeVM>(values: x => x.Entity.TableName == TableName && x.Entity.GroupId == TargetId && x.DpType == DpType);
}
return vm;
}
[ActionDescription("新建")]
[HttpPost("Add")]
public IActionResult Add(DataPrivilegeVM vm)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState.GetErrorJson());
}
else
{
vm.DoAdd();
if (!ModelState.IsValid)
{
return BadRequest(ModelState.GetErrorJson());
}
else
{
return Ok(vm.Entity);
}
}
}
[ActionDescription("修改")]
[HttpPut("Edit")]
public IActionResult Edit(DataPrivilegeVM vm)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState.GetErrorJson());
}
else
{
vm.DoEdit(true);
if (!ModelState.IsValid)
{
return BadRequest(ModelState.GetErrorJson());
}
else
{
return Ok(vm.Entity);
}
}
}
[ActionDescription("删除")]
[HttpGet("Delete/{id}")]
public IActionResult Delete(Guid id)
{
var vm = CreateVM<DataPrivilegeVM>(id);
vm.DoDelete();
if (!ModelState.IsValid)
{
return BadRequest(ModelState.GetErrorJson());
}
else
{
return Ok(vm.Entity);
}
}
[HttpPost("BatchDelete")]
[ActionDescription("批量删除")]
public IActionResult BatchDelete(Guid[] ids)
{
var vm = CreateVM<DataPrivilegeBatchVM>();
if (ids != null && ids.Count() > 0)
{
vm.Ids = ids;
}
else
{
return Ok();
}
if (!ModelState.IsValid || !vm.DoBatchDelete())
{
return BadRequest(ModelState.GetErrorJson());
}
else
{
return Ok(ids.Count());
}
}
[AllRights]
[HttpGet("GetPrivilegeByTableName")]
public ActionResult GetPrivilegeByTableName(string table)
{
var AllItems = new List<ComboSelectListItem>();
var dps = ConfigInfo.DataPrivilegeSettings.Where(x => x.ModelName == table).SingleOrDefault();
if (dps != null)
{
AllItems = dps.GetItemList(DC, LoginUserInfo);
}
return Ok(AllItems);
}
[AllRights]
[HttpGet("GetPrivileges")]
public ActionResult GetPrivileges()
{
var rv = ConfigInfo.DataPrivilegeSettings.ToListItems(x => x.PrivillegeName, x => x.ModelName);
return Ok(rv);
}
[AllRights]
[HttpGet("GetUserGroups")]
public ActionResult GetUserGroups()
{
var rv = DC.Set<FrameworkGroup>().GetSelectListItems(LoginUserInfo.DataPrivileges, null, x => x.GroupName);
return Ok(rv);
}
}
}
| 29.446541 | 147 | 0.496796 | [
"MIT"
] | huangdongqin/WTM | src/WalkingTec.Mvvm.Mvc.Admin/DataPrivilegeController.cs | 4,720 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using RazorPagesMovie.Models;
namespace RazorPagesMovie
{
public class Program
{
public static void Main(string[] args)
{
var host = CreateHostBuilder(args).Build();
using (var scope = host.Services.CreateScope())
{
var services = scope.ServiceProvider;
try
{
SeedData.Initialize(services);
}
catch (Exception ex)
{
var logger = services.GetRequiredService<ILogger<Program>>();
logger.LogError(ex, "An error occurred seeding the DB.");
}
}
host.Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
}
}
| 27.446809 | 81 | 0.569767 | [
"MIT"
] | teodragoi/TSP.NET | Asp_Dragoi_Teodor_Rp/RazorPagesMovie/RazorPagesMovie/Program.cs | 1,290 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.