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.Windows.Controls;
namespace BlankApp.Contracts.Views
{
public interface IShellDialogWindow
{
Frame GetDialogFrame();
}
}
| 15.6 | 39 | 0.698718 | [
"MIT"
] | sibille/WTS.WPF.GeneratedApps | BlankApp/BlankApp/Contracts/Views/IShellDialogWindow.cs | 158 | C# |
using System;
namespace Spring.Expressions.Parser.antlr
{
/*ANTLR Translator Generator
* Project led by Terence Parr at http://www.jGuru.com
* Software rights: http://www.antlr.org/license.html
*
* $Id:$
*/
//
// ANTLR C# Code Generator by Micheal Jordan
// Kunle Odutola : kunle UNDERSCORE odutola AT hotmail DOT com
// Anthony Oguntimehin
//
// With many thanks to Eric V. Smith from the ANTLR list.
//
/*
* Aborted recognition of current token. Try to get one again.
* Used by TokenStreamSelector.retry() to force nextToken()
* of stream to re-enter and retry.
*/
[Serializable]
public class TokenStreamRetryException : TokenStreamException
{
public TokenStreamRetryException() {}
}
} | 25 | 96 | 0.664516 | [
"Apache-2.0"
] | 18502079446/cusss | Sys.Expression/Expressions/Parser/antlr/TokenStreamRetryException.cs | 775 | C# |
// Copyright (c) Cratis. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Microsoft.Extensions.Logging;
namespace Cratis.Events.Projections.Pipelines.JobSteps
{
/// <summary>
/// Holds log messages for <see cref="Rewind"/>.
/// </summary>
public static partial class RewindLogMessages
{
[LoggerMessage(0, LogLevel.Debug, "Rewinding projection '{Projection}' for configuration '{Configuration}'")]
internal static partial void Rewinding(this ILogger logger, ProjectionId projection, ProjectionResultStoreConfigurationId configuration);
}
}
| 38.882353 | 145 | 0.738275 | [
"MIT"
] | Cratis/cratis | Source/Kernel/Projections/Engine/Pipelines/JobSteps/RewindLogMessages.cs | 661 | C# |
namespace GDShrapt.Reader
{
public abstract class GDDataToken : GDSimpleSyntaxToken
{
}
}
| 14.714286 | 59 | 0.699029 | [
"MIT"
] | elamaunt/GDShrapt | src/GDShrapt.Reader/Basics/GDDataToken.cs | 105 | C# |
// NPP plugin platform for .Net v0.93.96 by Kasper B. Graversen etc.
using System;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using NppPlugin.DllExport;
namespace NppNetInf
{
class UnmanagedExports
{
private static IntPtr _ptrPluginName = IntPtr.Zero;
private static PluginMain _main;
static UnmanagedExports()
{
Type pluginMain = Assembly.GetExecutingAssembly().GetTypes()
.FirstOrDefault(type => type.IsSubclassOf(typeof(PluginMain)));
_main = (PluginMain)Activator.CreateInstance(pluginMain);
}
[DllExport(CallingConvention = CallingConvention.Cdecl)]
private static bool isUnicode()
{
return true;
}
[DllExport(CallingConvention = CallingConvention.Cdecl)]
private static void setInfo(NppData notepadPlusData)
{
PluginBase.NppData = notepadPlusData;
var version = (int) Win32.SendMessage(PluginBase.NppData._nppHandle, (uint) NppMsg.NPPM_GETNPPVERSION,
IntPtr.Zero, out _);
PluginBase.NppVersion = new NppVersion(version >> 16, version & 0xFFFF);
_main.CommandMenuInit();
}
[DllExport(CallingConvention = CallingConvention.Cdecl)]
private static IntPtr getFuncsArray(ref int nbF)
{
nbF = PluginBase.FuncItems.Items.Count;
return PluginBase.FuncItems.NativePointer;
}
[DllExport(CallingConvention = CallingConvention.Cdecl)]
private static uint messageProc(uint Message, IntPtr wParam, IntPtr lParam)
{
return 1;
}
[DllExport(CallingConvention = CallingConvention.Cdecl)]
private static IntPtr getName()
{
if (_ptrPluginName == IntPtr.Zero)
_ptrPluginName = Marshal.StringToHGlobalUni(_main.PluginName ?? "unknown");
return _ptrPluginName;
}
[DllExport(CallingConvention = CallingConvention.Cdecl)]
private static void beNotified(IntPtr notifyCode)
{
ScNotification notification = (ScNotification)Marshal.PtrToStructure(notifyCode, typeof(ScNotification));
if (notification.Header.Code == (uint)NppMsg.NPPN_TBMODIFICATION)
{
PluginBase.FuncItems.RefreshItems();
_main.SetToolBarIcon();
}
else if (notification.Header.Code == (uint)NppMsg.NPPN_SHUTDOWN)
{
_main.PluginCleanUp();
Marshal.FreeHGlobal(_ptrPluginName);
}
else
{
_main.OnNotification(notification);
}
}
}
}
| 32.845238 | 117 | 0.614353 | [
"Apache-2.0"
] | KvanTTT/NppNetInf | src/UnmanagedExports.cs | 2,761 | 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 pinpoint-2016-12-01.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
using System.Xml.Serialization;
using Amazon.Pinpoint.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using ThirdParty.Json.LitJson;
namespace Amazon.Pinpoint.Model.Internal.MarshallTransformations
{
/// <summary>
/// AttributeDimension Marshaller
/// </summary>
public class AttributeDimensionMarshaller : IRequestMarshaller<AttributeDimension, JsonMarshallerContext>
{
/// <summary>
/// Unmarshaller the response from the service to the response class.
/// </summary>
/// <param name="requestObject"></param>
/// <param name="context"></param>
/// <returns></returns>
public void Marshall(AttributeDimension requestObject, JsonMarshallerContext context)
{
if(requestObject.IsSetAttributeType())
{
context.Writer.WritePropertyName("AttributeType");
context.Writer.Write(requestObject.AttributeType);
}
if(requestObject.IsSetValues())
{
context.Writer.WritePropertyName("Values");
context.Writer.WriteArrayStart();
foreach(var requestObjectValuesListValue in requestObject.Values)
{
context.Writer.Write(requestObjectValuesListValue);
}
context.Writer.WriteArrayEnd();
}
}
/// <summary>
/// Singleton Marshaller.
/// </summary>
public readonly static AttributeDimensionMarshaller Instance = new AttributeDimensionMarshaller();
}
} | 35.150685 | 111 | 0.642245 | [
"Apache-2.0"
] | philasmar/aws-sdk-net | sdk/src/Services/Pinpoint/Generated/Model/Internal/MarshallTransformations/AttributeDimensionMarshaller.cs | 2,566 | 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.KeyVault.V20210401Preview.Inputs
{
/// <summary>
/// An object that represents the approval state of the private link connection.
/// </summary>
public sealed class PrivateLinkServiceConnectionStateArgs : Pulumi.ResourceArgs
{
/// <summary>
/// A message indicating if changes on the service provider require any updates on the consumer.
/// </summary>
[Input("actionsRequired")]
public InputUnion<string, Pulumi.AzureNative.KeyVault.V20210401Preview.ActionsRequired>? ActionsRequired { get; set; }
/// <summary>
/// The reason for approval or rejection.
/// </summary>
[Input("description")]
public Input<string>? Description { get; set; }
/// <summary>
/// Indicates whether the connection has been approved, rejected or removed by the key vault owner.
/// </summary>
[Input("status")]
public InputUnion<string, Pulumi.AzureNative.KeyVault.V20210401Preview.PrivateEndpointServiceConnectionStatus>? Status { get; set; }
public PrivateLinkServiceConnectionStateArgs()
{
}
}
}
| 36 | 140 | 0.674797 | [
"Apache-2.0"
] | polivbr/pulumi-azure-native | sdk/dotnet/KeyVault/V20210401Preview/Inputs/PrivateLinkServiceConnectionStateArgs.cs | 1,476 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
namespace Microsoft.Psi.Interop.Serialization
{
using System;
/// <summary>
/// Format deserializer interface.
/// </summary>
public interface IFormatDeserializer
{
/// <summary>
/// Deserialize single message and originating time stamp payload.
/// </summary>
/// <param name="payload">Payload bytes.</param>
/// <param name="index">Starting index of message data.</param>
/// <param name="count">Number of bytes constituting message data.</param>
/// <returns>Dynamic of primitive or IEnumerable/ExpandoObject of primitive as well as originating time stamp.</returns>
(dynamic, DateTime) DeserializeMessage(byte[] payload, int index, int count);
}
} | 38.272727 | 128 | 0.662708 | [
"MIT"
] | DANCEcollaborative/PSI | Sources/Runtime/Microsoft.Psi.Interop/Serialization/IFormatDeserializer.cs | 844 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.IO;
using System.Threading;
namespace System.Net.WebSockets
{
public static class WebSocketProtocol
{
public static WebSocket CreateFromStream(
Stream stream,
bool isServer,
string? subProtocol,
TimeSpan keepAliveInterval)
{
if (stream == null)
{
throw new ArgumentNullException(nameof(stream));
}
if (!stream.CanRead || !stream.CanWrite)
{
throw new ArgumentException(!stream.CanRead ? SR.NotReadableStream : SR.NotWriteableStream, nameof(stream));
}
if (subProtocol != null)
{
WebSocketValidate.ValidateSubprotocol(subProtocol);
}
if (keepAliveInterval != Timeout.InfiniteTimeSpan && keepAliveInterval < TimeSpan.Zero)
{
throw new ArgumentOutOfRangeException(nameof(keepAliveInterval), keepAliveInterval,
SR.Format(SR.net_WebSockets_ArgumentOutOfRange_TooSmall,
0));
}
return ManagedWebSocket.CreateFromConnectedStream(stream, isServer, subProtocol, keepAliveInterval);
}
}
}
| 32.046512 | 124 | 0.599419 | [
"MIT"
] | 2m0nd/runtime | src/libraries/System.Net.WebSockets.WebSocketProtocol/src/System/Net/WebSockets/WebSocketProtocol.cs | 1,378 | C# |
using System;
using System.Collections;
using System.Collections.Generic;
namespace Eve.Collections
{
/// <description> Unstable </description>
public class NamedList<T> : IEnumerable<KeyValuePair<string, T>>
{
public NamedList()
{
Data = new DynamicArray<KeyValuePair<string, T>>();
}
DynamicArray<KeyValuePair<string, T>> Data;
private int BinarySearch(string name)
{
int min = 0, max = Data.Length - 1, mid = 0;
while (min <= max)
{
mid = (min + max) / 2;
var cp = name.CompareTo(Data[mid].Key);
// Check if x is present at mid
if (cp == 0)
return mid;
// If x greater, ignore left half
if (cp > 0)
{
min = mid + 1;
}
// If x is smaller, ignore right half
else
{
if (min == max)
return min;
max = mid - 1;
}
}
// if we reach here, then element was
// not present
return min;
}
public bool ContainsKey(string name)
{
var index = BinarySearch(name);
return index < Data.Length && Data[index].Key == name;
}
public T this[string name]
{
get
{
if (Data.Count == 0)
throw new KeyNotFoundException();
var index = BinarySearch(name);
if (index >= Data.Count)
throw new KeyNotFoundException();
var tmp = Data[index];
if (tmp.Key != name)
throw new KeyNotFoundException();
return tmp.Value;
}
}
public void Add(string name, T value)
{
if (Data.Count == 0)
Data.Add(new KeyValuePair<string, T>(name, value));
else
{
Data.Insert(BinarySearch(name), new KeyValuePair<string, T>(name, value));
}
}
public IEnumerator<KeyValuePair<string, T>> GetEnumerator()
{
return this.Data.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return this.Data.GetEnumerator();
}
}
}
| 22.384615 | 82 | 0.541973 | [
"BSD-3-Clause"
] | Yeganloo/CommonLib | Eve.Collections/Collections/NamedList.cs | 2,039 | C# |
using EurekaAPI.Models;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.OpenApi.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace EurekaAPI
{
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.AddDbContext<CardContext>(options =>
options.UseInMemoryDatabase("Card"));
services.AddControllers();
services.AddCors(options =>
{
options.AddDefaultPolicy(builder =>
{
builder.WithOrigins("http://localhost:5500")
.AllowAnyHeader()
.AllowAnyMethod();
});
});
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseCors();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
}
| 27.847222 | 106 | 0.594514 | [
"MIT"
] | symalik/Eureka | EurekaAPI/Startup.cs | 2,005 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class UpgradeItemPanel : MonoBehaviour
{
[Header("참조용")]
public GameObject materialItemSlotPanel;
public ItemSlotUI upgradeItemSlotUI;
public GameObject itemSlotUI;
[Header("읽기용")]
public List<ItemSlotData> materialInventory;
private ItemSlotData upgradeItemSlotData;
public ItemSlotData UpgradeItemSlotData
{
get { return upgradeItemSlotData; }
set
{
upgradeItemSlotData = value;
upgradeItemSlotUI.ItemSlotData = upgradeItemSlotData;
FindMaterialItemSlot();
Debug.Log("업글레이트 아이템 등록");
}
}
public void Close()
{
foreach (Transform child in materialItemSlotPanel.transform)
{
Destroy(child.gameObject);
}
transform.Find("Panel").transform.Find("ItemSlotUI").GetComponent<ItemSlotUI>().ItemSlotData = null;
gameObject.SetActive(false);
}
public void FindMaterialItemSlot()
{
Debug.Log("재료 아이템 찾기");
// 초기화
AdventurePlayerController playerController = AdventureModeManager.Instance.playerController;
materialInventory.Clear();
// 배틀 인벤토리에서 찾기
foreach(ItemSlotData itemSlotData in playerController.battleInventory)
{
if (upgradeItemSlotData == itemSlotData)
continue;
if (upgradeItemSlotData.itemData == itemSlotData.itemData)
{
materialInventory.Add(itemSlotData);
}
}
// 수집 인벤토리에서 찾기
foreach (ItemSlotData itemSlotData in playerController.collectInventory)
{
if (upgradeItemSlotData == itemSlotData)
continue;
if (upgradeItemSlotData.itemData == itemSlotData.itemData)
{
materialInventory.Add(itemSlotData);
}
}
RefreshInventory();
}
public void RefreshInventory()
{
// 재료 슬롯 리스트 출력
foreach (Transform child in materialItemSlotPanel.transform)
{
Destroy(child.gameObject);
}
foreach (ItemSlotData itemSlotData in materialInventory)
{
ItemSlotUI _itemSlotUI = Instantiate(itemSlotUI, materialItemSlotPanel.transform).GetComponent<ItemSlotUI>();
_itemSlotUI.ItemSlotData = itemSlotData;
_itemSlotUI.ItemSlotData.itemSlotUI = _itemSlotUI;
_itemSlotUI.slotType = SlotType.materialSlot;
_itemSlotUI.RefreshSlot();
}
}
}
| 30.37931 | 121 | 0.615588 | [
"MIT"
] | Bluebug404/MonsterBattleSimulator | Assets/Scripts/Instance/UI/UpgradeItemPanel.cs | 2,755 | C# |
using System;
namespace TensorSharp
{
[Serializable]
public abstract class Storage : RefCounted
{
public Storage(IAllocator allocator, DType elementType, long elementCount)
{
Allocator = allocator;
ElementType = elementType;
ElementCount = elementCount;
}
/// <summary>
/// Gets a reference to the allocator that constructed this Storage object.
/// </summary>
public IAllocator Allocator { get; private set; }
public DType ElementType { get; private set; }
public long ElementCount { get; private set; }
public long ByteLength => ElementCount * ElementType.Size();
public bool IsOwnerExclusive()
{
return GetCurrentRefCount() == 1;
}
public abstract int[] GetElementsAsInt(long index, int length);
public abstract void SetElementsAsInt(long index, int[] value);
public abstract string LocationDescription();
public abstract float GetElementAsFloat(long index);
public abstract float[] GetElementsAsFloat(long index, int length);
public abstract void SetElementAsFloat(long index, float value);
public abstract void SetElementsAsFloat(long index, float[] value);
public abstract void CopyToStorage(long storageIndex, IntPtr src, long byteCount);
public abstract void CopyFromStorage(IntPtr dst, long storageIndex, long byteCount);
}
}
| 31.659574 | 92 | 0.656586 | [
"BSD-3-Clause"
] | SciSharp/Seq2SeqSharp | TensorSharp/Storage.cs | 1,490 | C# |
using NSubstitute;
using NUnit.Framework;
using PullRequestMonitor.Model;
using PullRequestMonitor.ViewModel;
namespace PullRequestMonitor.UnitTest.ViewModel
{
[TestFixture]
public class RepositoryViewModelTest
{
[Test]
public void TestNameGetter_ReturnsModelName()
{
const string testName = "Any name here";
var repository = Substitute.For<ITfGitRepository>();
repository.Name.Returns(testName);
var systemUnderTest = new RepositoryViewModel(repository);
Assert.That(systemUnderTest.Name, Is.EqualTo(testName));
}
}
} | 28.590909 | 70 | 0.677266 | [
"MIT"
] | jornletnes/pull-request-monitor | PullRequestMonitor.UnitTest/ViewModel/RepositoryViewModelTest.cs | 631 | C# |
using System;
using System.Linq;
using UnityEngine;
using UnityEngine.UI;
namespace MyCraft.UI
{
public class Hotbar : MonoBehaviour
{
[SerializeField] private RectTransform highlightTransform;
World world;
Player player;
Inventory inventory;
public HotbarItemSlot[] ItemSlots => inventory.InventorySlots;
public HotbarItemSlot SelectedSlot => ItemSlots[SlotIndex];
public int SlotIndex
{
get { return _slotIndex; }
protected set
{
if (value > ItemSlots.Length - 1)
_slotIndex = ItemSlots.Length - 1;
else if (value < 0)
_slotIndex = 0;
else
_slotIndex = value;
var slotContainers = transform.GetChild(0);
highlightTransform.position = slotContainers.GetChild(SlotIndex).transform.position;
}
}
private int _slotIndex = 0;
private void Start()
{
world = GameObject.Find("World").GetComponent<World>();
player = world.player.GetComponent<Player>();
inventory = GameObject.Find("Inventory").GetComponent<Inventory>();
ItemSlots[0].Set(world.BlockTable[1], ItemSlot.MAX_AMOUNT);
ItemSlots[1].Set(world.BlockTable[5], ItemSlot.MAX_AMOUNT);
ItemSlots[2].Set(world.BlockTable[12], ItemSlot.MAX_AMOUNT);
}
private void Update()
{
float scroll = Input.GetAxis("Mouse ScrollWheel");
if (scroll != 0)
SlotIndex += scroll > 0 ? -1 : 1;
}
}
}
| 29.473684 | 100 | 0.560714 | [
"MIT"
] | curaai00/MyCraft | Assets/Scripts/UI/Hotbar.cs | 1,680 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using NUnit.Framework;
using UnityEngine;
using UnityEditor.ShaderGraph;
namespace UnityEditor.Graphing.UnitTests
{
[TestFixture]
public class BaseMaterialGraphTests
{
[OneTimeSetUp]
public void RunBeforeAnyTests()
{
Debug.unityLogger.logHandler = new ConsoleLogHandler();
}
[Test]
public void TestCanCreateBaseMaterialGraph()
{
var graph = new GraphData();
Assert.AreEqual(0, graph.edges.Count());
Assert.AreEqual(0, graph.GetNodes<AbstractMaterialNode>().Count());
}
[Test]
public void TestCanAddNodeToBaseMaterialGraph()
{
var graph = new GraphData();
var node = new TestNode();
node.name = "Test Node";
graph.AddNode(node);
Assert.AreEqual(1, graph.GetNodes<AbstractMaterialNode>().Count());
Assert.AreEqual("Test Node", graph.GetNodes<AbstractMaterialNode>().FirstOrDefault().name);
Assert.AreEqual(graph, node.owner);
}
[Test]
public void TestCanRemoveNodeFromBaseMaterialGraph()
{
var graph = new GraphData();
var node = new TestNode();
node.name = "Test Node";
graph.AddNode(node);
Assert.AreEqual(1, graph.GetNodes<AbstractMaterialNode>().Count());
graph.RemoveNode(graph.GetNodes<AbstractMaterialNode>().FirstOrDefault());
Assert.AreEqual(0, graph.GetNodes<AbstractMaterialNode>().Count());
}
[Test]
public void TestCanModifyNodeDrawState()
{
var node = new TestNode();
node.name = "Test Node";
var drawState = node.drawState;
var newPos = new Rect(10, 10, 0, 0);
drawState.position = newPos;
drawState.expanded = false;
node.drawState = drawState;
Assert.AreEqual(drawState, node.drawState);
Assert.AreEqual(newPos, node.drawState.position);
Assert.IsFalse(node.drawState.expanded);
}
class SetErrorNode : TestNode
{
public void SetError()
{
hasError = true;
}
public void ClearError()
{
hasError = false;
}
}
[Test]
public void TestChildClassCanModifyErrorState()
{
var node = new SetErrorNode();
node.SetError();
Assert.IsTrue(node.hasError);
node.ClearError();
Assert.IsFalse(node.hasError);
}
[Test]
public void TestNodeGUIDCanBeRewritten()
{
var node = new TestNode();
var guid = node.guid;
var newGuid = node.RewriteGuid();
Assert.AreNotEqual(guid, newGuid);
}
class TestableNode : TestNode
{
public const int Input0 = 0;
public const int Input1 = 1;
public const int Input2 = 2;
public const int Output0 = 3;
public const int Output1 = 4;
public const int Output2 = 5;
public TestableNode()
{
AddSlot(new TestSlot(Input0, "Input", SlotType.Input));
AddSlot(new TestSlot(Input1, "Input", SlotType.Input));
AddSlot(new TestSlot(Input2, "Input", SlotType.Input));
AddSlot(new TestSlot(Output0, "Output", SlotType.Output));
AddSlot(new TestSlot(Output1, "Output", SlotType.Output));
AddSlot(new TestSlot(Output2, "Output", SlotType.Output));
}
}
[Test]
public void TestRemoveNodeFromBaseMaterialGraphCleansEdges()
{
var graph = new GraphData();
var outputNode = new TestableNode();
graph.AddNode(outputNode);
var inputNode = new TestableNode();
graph.AddNode(inputNode);
Assert.AreEqual(2, graph.GetNodes<AbstractMaterialNode>().Count());
var createdEdge = graph.Connect(outputNode.GetSlotReference(TestableNode.Output0), inputNode.GetSlotReference(TestableNode.Input0));
Assert.AreEqual(1, graph.edges.Count());
var edge = graph.edges.FirstOrDefault();
Assert.AreEqual(createdEdge, edge);
graph.RemoveNode(outputNode);
Assert.AreEqual(1, graph.GetNodes<AbstractMaterialNode>().Count());
Assert.AreEqual(0, graph.edges.Count());
Assert.AreEqual(inputNode, graph.GetNodes<AbstractMaterialNode>().FirstOrDefault());
}
private class NoDeleteNode : TestNode
{
public override bool canDeleteNode { get { return false; } }
}
[Test]
public void TestCanNotRemoveNoDeleteNodeFromBaseMaterialGraph()
{
var graph = new GraphData();
var node = new NoDeleteNode();
node.name = "Test Node";
graph.AddNode(node);
Assert.AreEqual(1, graph.GetNodes<AbstractMaterialNode>().Count());
Assert.Catch<InvalidOperationException>(() => graph.RemoveNode(node));
Assert.AreEqual(1, graph.GetNodes<AbstractMaterialNode>().Count());
}
private class OnEnableNode : TestNode, IOnAssetEnabled
{
public bool called = false;
public void OnEnable()
{
called = true;
}
}
[Test]
public void TestSerializedGraphDelegatesOnEnableCalls()
{
var graph = new GraphData();
var node = new OnEnableNode();
node.name = "Test Node";
graph.AddNode(node);
Assert.IsFalse(node.called);
graph.OnEnable();
Assert.IsTrue(node.called);
}
[Test]
public void TestCanFindNodeInBaseMaterialGraph()
{
var graph = new GraphData();
var node = new TestNode();
graph.AddNode(node);
Assert.AreEqual(1, graph.GetNodes<AbstractMaterialNode>().Count());
Assert.IsNotNull(graph.GetNodeFromGuid(node.guid));
Assert.IsNull(graph.GetNodeFromGuid(Guid.NewGuid()));
}
[Test]
public void TestCanAddSlotToTestNode()
{
var graph = new GraphData();
var node = new TestNode();
node.AddSlot(new TestSlot(0, "output", SlotType.Output));
node.AddSlot(new TestSlot(1, "input", SlotType.Input));
node.name = "Test Node";
graph.AddNode(node);
Assert.AreEqual(1, graph.GetNodes<AbstractMaterialNode>().Count());
var found = graph.GetNodes<AbstractMaterialNode>().FirstOrDefault();
Assert.AreEqual(1, found.GetInputSlots<ISlot>().Count());
Assert.AreEqual(1, found.GetInputSlots<ISlot>().FirstOrDefault().id);
Assert.AreEqual(1, found.GetOutputSlots<ISlot>().Count());
Assert.AreEqual(0, found.GetOutputSlots<ISlot>().FirstOrDefault().id);
Assert.AreEqual(2, found.GetSlots<ISlot>().Count());
}
[Test]
public void TestCanNotAddNullSlotToTestNode()
{
var node = new TestNode();
Assert.Throws<ArgumentException>(() => node.AddSlot(null));
}
[Test]
public void TestCanRemoveSlotFromTestNode()
{
var graph = new GraphData();
var node = new TestNode();
node.AddSlot(new TestSlot(0, "output", SlotType.Output));
node.AddSlot(new TestSlot(1, "input", SlotType.Input));
graph.AddNode(node);
Assert.AreEqual(2, node.GetSlots<ISlot>().Count());
Assert.AreEqual(1, node.GetInputSlots<ISlot>().Count());
Assert.AreEqual(1, node.GetOutputSlots<ISlot>().Count());
node.RemoveSlot(1);
Assert.AreEqual(1, node.GetSlots<ISlot>().Count());
Assert.AreEqual(0, node.GetInputSlots<ISlot>().Count());
Assert.AreEqual(1, node.GetOutputSlots<ISlot>().Count());
}
[Test]
public void TestCanRemoveSlotsWithNonMathingNameFromTestNode()
{
var graph = new GraphData();
var node = new TestableNode();
graph.AddNode(node);
Assert.AreEqual(6, node.GetSlots<ISlot>().Count());
Assert.AreEqual(3, node.GetInputSlots<ISlot>().Count());
Assert.AreEqual(3, node.GetOutputSlots<ISlot>().Count());
node.RemoveSlotsNameNotMatching(new[] {TestableNode.Input1});
Assert.AreEqual(1, node.GetSlots<ISlot>().Count());
Assert.AreEqual(1, node.GetInputSlots<ISlot>().Count());
Assert.AreEqual(0, node.GetOutputSlots<ISlot>().Count());
Assert.IsNull(node.FindInputSlot<ISlot>(TestableNode.Input0));
Assert.IsNotNull(node.FindInputSlot<ISlot>(TestableNode.Input1));
Assert.IsNull(node.FindInputSlot<ISlot>(TestableNode.Input2));
}
[Test]
public void TestCanNotAddDuplicateSlotToTestNode()
{
var graph = new GraphData();
var node = new TestNode();
node.AddSlot(new TestSlot(0, "output", SlotType.Output));
node.AddSlot(new TestSlot(0, "output", SlotType.Output));
node.name = "Test Node";
graph.AddNode(node);
Assert.AreEqual(1, graph.GetNodes<AbstractMaterialNode>().Count());
var found = graph.GetNodes<AbstractMaterialNode>().FirstOrDefault();
Assert.AreEqual(0, found.GetInputSlots<ISlot>().Count());
Assert.AreEqual(1, found.GetOutputSlots<ISlot>().Count());
Assert.AreEqual(1, found.GetSlots<ISlot>().Count());
}
[Test]
public void TestCanUpdateDisplaynameByReaddingSlotToTestNode()
{
var graph = new GraphData();
var node = new TestNode();
node.AddSlot(new TestSlot(0, "output", SlotType.Output));
node.AddSlot(new TestSlot(0, "output_updated", SlotType.Output));
node.name = "Test Node";
graph.AddNode(node);
Assert.AreEqual(1, graph.GetNodes<AbstractMaterialNode>().Count());
var found = graph.GetNodes<AbstractMaterialNode>().FirstOrDefault();
Assert.AreEqual(0, found.GetInputSlots<ISlot>().Count());
Assert.AreEqual(1, found.GetOutputSlots<ISlot>().Count());
Assert.AreEqual(1, found.GetSlots<ISlot>().Count());
var slot = found.GetOutputSlots<ISlot>().FirstOrDefault();
Assert.AreEqual("output_updated(4)", slot.displayName);
}
[Test]
public void TestCanUpdateSlotPriority()
{
var graph = new GraphData();
var node = new TestNode();
node.AddSlot(new TestSlot(0, "output", SlotType.Output, 0));
node.name = "Test Node";
graph.AddNode(node);
Assert.AreEqual(1, graph.GetNodes<AbstractMaterialNode>().Count());
var found = graph.GetNodes<AbstractMaterialNode>().FirstOrDefault();
Assert.AreEqual(0, found.GetInputSlots<ISlot>().Count());
Assert.AreEqual(1, found.GetOutputSlots<ISlot>().Count());
Assert.AreEqual(1, found.GetSlots<ISlot>().Count());
var slot = found.GetOutputSlots<ISlot>().FirstOrDefault();
Assert.AreEqual(0, slot.priority);
slot.priority = 2;
Assert.AreEqual(2, slot.priority);
}
[Test]
public void TestCanUpdateSlotPriorityByReaddingSlotToTestNode()
{
var graph = new GraphData();
var node = new TestNode();
node.AddSlot(new TestSlot(0, "output", SlotType.Output, 0));
node.AddSlot(new TestSlot(0, "output", SlotType.Output, 5));
node.name = "Test Node";
graph.AddNode(node);
Assert.AreEqual(1, graph.GetNodes<AbstractMaterialNode>().Count());
var found = graph.GetNodes<AbstractMaterialNode>().FirstOrDefault();
Assert.AreEqual(0, found.GetInputSlots<ISlot>().Count());
Assert.AreEqual(1, found.GetOutputSlots<ISlot>().Count());
Assert.AreEqual(1, found.GetSlots<ISlot>().Count());
var slot = found.GetOutputSlots<ISlot>().FirstOrDefault();
Assert.AreEqual(5, slot.priority);
}
[Test]
public void TestCanUpdateSlotDisplayName()
{
var node = new TestNode();
node.AddSlot(new TestSlot(0, "output", SlotType.Output));
node.name = "Test Node";
Assert.AreEqual(0, node.GetInputSlots<ISlot>().Count());
Assert.AreEqual(1, node.GetOutputSlots<ISlot>().Count());
Assert.AreEqual(1, node.GetSlots<ISlot>().Count());
var slot = node.GetOutputSlots<ISlot>().FirstOrDefault();
Assert.IsNotNull(slot);
Assert.AreEqual("output(4)", slot.displayName);
slot.displayName = "test";
Assert.AreEqual("test(4)", slot.displayName);
}
[Test]
public void TestCanFindSlotOnTestNode()
{
var node = new TestableNode();
Assert.AreEqual(6, node.GetSlots<ISlot>().Count());
Assert.IsNotNull(node.FindInputSlot<ISlot>(TestableNode.Input0));
Assert.IsNull(node.FindInputSlot<ISlot>(TestableNode.Output0));
Assert.IsNotNull(node.FindOutputSlot<ISlot>(TestableNode.Output0));
Assert.IsNull(node.FindOutputSlot<ISlot>(TestableNode.Input0));
Assert.IsNotNull(node.FindSlot<ISlot>(TestableNode.Input0));
Assert.IsNotNull(node.FindSlot<ISlot>(TestableNode.Output0));
Assert.IsNull(node.FindSlot<ISlot>(555));
}
[Test]
public void TestCanFindSlotReferenceOnTestNode()
{
var node = new TestableNode();
Assert.AreEqual(6, node.GetSlots<ISlot>().Count());
Assert.IsNotNull(node.GetSlotReference(TestableNode.Input0));
Assert.IsNotNull(node.GetSlotReference(TestableNode.Output0));
Assert.Throws<ArgumentException>(() => node.GetSlotReference(555));
}
[Test]
public void TestCanConnectAndTraverseTwoNodesOnBaseMaterialGraph()
{
var graph = new GraphData();
var outputNode = new TestableNode();
graph.AddNode(outputNode);
var inputNode = new TestableNode();
graph.AddNode(inputNode);
Assert.AreEqual(2, graph.GetNodes<AbstractMaterialNode>().Count());
var createdEdge = graph.Connect(outputNode.GetSlotReference(TestableNode.Output0), inputNode.GetSlotReference(TestableNode.Input0));
Assert.AreEqual(1, graph.edges.Count());
var edge = graph.edges.FirstOrDefault();
Assert.AreEqual(createdEdge, edge);
var foundOutputNode = graph.GetNodeFromGuid(edge.outputSlot.nodeGuid);
var foundOutputSlot = foundOutputNode.FindOutputSlot<ISlot>(edge.outputSlot.slotId);
Assert.AreEqual(outputNode, foundOutputNode);
Assert.IsNotNull(foundOutputSlot);
var foundInputNode = graph.GetNodeFromGuid(edge.inputSlot.nodeGuid);
var foundInputSlot = foundInputNode.FindInputSlot<ISlot>(edge.inputSlot.slotId);
Assert.AreEqual(inputNode, foundInputNode);
Assert.IsNotNull(foundInputSlot);
}
[Test]
public void TestCanConnectAndTraverseThreeNodesOnBaseMaterialGraph()
{
var graph = new GraphData();
var outputNode = new TestableNode();
graph.AddNode(outputNode);
var middleNode = new TestableNode();
graph.AddNode(middleNode);
var inputNode = new TestableNode();
graph.AddNode(inputNode);
Assert.AreEqual(3, graph.GetNodes<AbstractMaterialNode>().Count());
graph.Connect(outputNode.GetSlotReference(TestableNode.Output0), middleNode.GetSlotReference(TestableNode.Input0));
Assert.AreEqual(1, graph.edges.Count());
graph.Connect(middleNode.GetSlotReference(TestableNode.Output0), inputNode.GetSlotReference(TestableNode.Input0));
Assert.AreEqual(2, graph.edges.Count());
var edgesOnMiddleNode = NodeUtils.GetAllEdges(middleNode);
Assert.AreEqual(2, edgesOnMiddleNode.Count());
List<AbstractMaterialNode> result = new List<AbstractMaterialNode>();
NodeUtils.DepthFirstCollectNodesFromNode(result, inputNode);
Assert.AreEqual(3, result.Count);
result.Clear();
NodeUtils.DepthFirstCollectNodesFromNode(result, inputNode, NodeUtils.IncludeSelf.Exclude);
Assert.AreEqual(2, result.Count);
result.Clear();
NodeUtils.DepthFirstCollectNodesFromNode(result, null);
Assert.AreEqual(0, result.Count);
}
[Test]
public void TestExceptionIfBadNodeConfigurationWorks()
{
var node = new TestableNode();
Assert.DoesNotThrow(
() =>
NodeUtils.SlotConfigurationExceptionIfBadConfiguration(
node,
new[] {TestableNode.Input0, TestableNode.Input1, TestableNode.Input2},
new[] {TestableNode.Output0, TestableNode.Output1, TestableNode.Output2, })
);
Assert.Throws<SlotConfigurationException>(
() =>
NodeUtils.SlotConfigurationExceptionIfBadConfiguration(
node,
new[] {666, TestableNode.Input1, TestableNode.Input2},
new[] {TestableNode.Output0, TestableNode.Output1, TestableNode.Output2, })
);
Assert.Throws<SlotConfigurationException>(
() =>
NodeUtils.SlotConfigurationExceptionIfBadConfiguration(
node,
new[] {TestableNode.Input0, TestableNode.Input1, TestableNode.Input2},
new[] {666, TestableNode.Output1, TestableNode.Output2, })
);
Assert.DoesNotThrow(
() =>
NodeUtils.SlotConfigurationExceptionIfBadConfiguration(
node,
new[] {TestableNode.Input0},
new[] {TestableNode.Output0})
);
}
[Test]
public void TestConectionToSameInputReplacesOldInput()
{
var graph = new GraphData();
var outputNode = new TestableNode();
graph.AddNode(outputNode);
var inputNode = new TestableNode();
graph.AddNode(inputNode);
Assert.AreEqual(2, graph.GetNodes<AbstractMaterialNode>().Count());
var createdEdge = graph.Connect(outputNode.GetSlotReference(TestableNode.Output0), inputNode.GetSlotReference(TestableNode.Input0));
Assert.AreEqual(1, graph.edges.Count());
var edge = graph.edges.FirstOrDefault();
Assert.AreEqual(createdEdge, edge);
var createdEdge2 = graph.Connect(outputNode.GetSlotReference(TestableNode.Output0), inputNode.GetSlotReference(TestableNode.Input0));
Assert.AreEqual(1, graph.edges.Count());
var edge2 = graph.edges.FirstOrDefault();
Assert.AreEqual(createdEdge2, edge2);
}
[Test]
public void TestRemovingSlotRemovesConnectedEdges()
{
var graph = new GraphData();
var outputNode = new TestableNode();
graph.AddNode(outputNode);
var inputNode = new TestableNode();
graph.AddNode(inputNode);
Assert.AreEqual(2, graph.GetNodes<AbstractMaterialNode>().Count());
graph.Connect(outputNode.GetSlotReference(TestableNode.Output0), inputNode.GetSlotReference(TestableNode.Input0));
Assert.AreEqual(1, graph.edges.Count());
outputNode.RemoveSlot(TestableNode.Output0);
Assert.AreEqual(0, graph.edges.Count());
}
[Test]
public void TestCanNotConnectToNullSlot()
{
var graph = new GraphData();
var outputNode = new TestableNode();
graph.AddNode(outputNode);
var inputNode = new TestNode();
graph.AddNode(inputNode);
Assert.AreEqual(2, graph.GetNodes<AbstractMaterialNode>().Count());
var createdEdge2 = graph.Connect(outputNode.GetSlotReference(TestableNode.Output0), new SlotReference(Guid.NewGuid(), 666));
Assert.AreEqual(0, graph.edges.Count());
Assert.IsNull(createdEdge2);
}
[Test]
public void TestCanNotConnectTwoOuputSlotsOnBaseMaterialGraph()
{
var graph = new GraphData();
var outputNode = new TestableNode();
graph.AddNode(outputNode);
var outputNode2 = new TestableNode();
graph.AddNode(outputNode2);
Assert.AreEqual(2, graph.GetNodes<AbstractMaterialNode>().Count());
var createdEdge = graph.Connect(outputNode.GetSlotReference(TestableNode.Output0), outputNode2.GetSlotReference(TestableNode.Output0));
Assert.IsNull(createdEdge);
Assert.AreEqual(0, graph.edges.Count());
}
[Test]
public void TestCanNotConnectTwoInputSlotsOnBaseMaterialGraph()
{
var graph = new GraphData();
var inputNode = new TestableNode();
graph.AddNode(inputNode);
var inputNode2 = new TestableNode();
graph.AddNode(inputNode2);
Assert.AreEqual(2, graph.GetNodes<AbstractMaterialNode>().Count());
var createdEdge = graph.Connect(inputNode.GetSlotReference(TestableNode.Input0), inputNode2.GetSlotReference(TestableNode.Input0));
Assert.IsNull(createdEdge);
Assert.AreEqual(0, graph.edges.Count());
}
[Test]
public void TestRemovingNodeRemovesConectedEdgesOnBaseMaterialGraph()
{
var graph = new GraphData();
var outputNode = new TestableNode();
graph.AddNode(outputNode);
var inputNode = new TestableNode();
graph.AddNode(inputNode);
Assert.AreEqual(2, graph.GetNodes<AbstractMaterialNode>().Count());
graph.Connect(outputNode.GetSlotReference(TestableNode.Output0), inputNode.GetSlotReference(TestableNode.Input0));
Assert.AreEqual(1, graph.edges.Count());
graph.RemoveNode(graph.GetNodes<AbstractMaterialNode>().FirstOrDefault());
Assert.AreEqual(1, graph.GetNodes<AbstractMaterialNode>().Count());
Assert.AreEqual(0, graph.edges.Count());
}
[Test]
public void TestRemovingEdgeOnBaseMaterialGraph()
{
var graph = new GraphData();
var outputNode = new TestableNode();
graph.AddNode(outputNode);
var inputNode = new TestableNode();
graph.AddNode(inputNode);
Assert.AreEqual(2, graph.GetNodes<AbstractMaterialNode>().Count());
graph.Connect(outputNode.GetSlotReference(TestableNode.Output0), inputNode.GetSlotReference(TestableNode.Input0));
Assert.AreEqual(1, graph.edges.Count());
graph.RemoveEdge(graph.edges.FirstOrDefault());
Assert.AreEqual(2, graph.GetNodes<AbstractMaterialNode>().Count());
Assert.AreEqual(0, graph.edges.Count());
}
[Test]
public void TestRemovingElementsFromBaseMaterialGraph()
{
var graph = new GraphData();
var outputNode = new TestableNode();
graph.AddNode(outputNode);
var inputNode = new TestableNode();
graph.AddNode(inputNode);
Assert.AreEqual(2, graph.GetNodes<AbstractMaterialNode>().Count());
graph.Connect(outputNode.GetSlotReference(TestableNode.Output0), inputNode.GetSlotReference(TestableNode.Input0));
Assert.AreEqual(1, graph.edges.Count());
graph.RemoveElements(graph.GetNodes<AbstractMaterialNode>(), graph.edges, Enumerable.Empty<GroupData>());
Assert.AreEqual(0, graph.GetNodes<AbstractMaterialNode>().Count());
Assert.AreEqual(0, graph.edges.Count());
}
[Test]
public void TestCanGetEdgesOnBaseMaterialGraphFromSlotReference()
{
var graph = new GraphData();
var outputNode = new TestableNode();
graph.AddNode(outputNode);
var inputNode = new TestableNode();
graph.AddNode(inputNode);
Assert.AreEqual(2, graph.GetNodes<AbstractMaterialNode>().Count());
graph.Connect(outputNode.GetSlotReference(TestableNode.Output0), inputNode.GetSlotReference(TestableNode.Input0));
Assert.AreEqual(1, graph.edges.Count());
Assert.AreEqual(1, graph.GetEdges(inputNode.GetSlotReference(TestableNode.Input0)).Count());
Assert.AreEqual(1, graph.GetEdges(outputNode.GetSlotReference(TestableNode.Output0)).Count());
Assert.Throws<ArgumentException>(() => outputNode.GetSlotReference(666));
}
[Test]
public void TestGetInputsWithNoConnection()
{
var graph = new GraphData();
var outputNode = new TestableNode();
graph.AddNode(outputNode);
var inputNode = new TestableNode();
graph.AddNode(inputNode);
Assert.AreEqual(2, graph.GetNodes<AbstractMaterialNode>().Count());
graph.Connect(outputNode.GetSlotReference(TestableNode.Output0), inputNode.GetSlotReference(TestableNode.Input0));
Assert.AreEqual(1, graph.edges.Count());
var slots = inputNode.GetInputsWithNoConnection();
Assert.AreEqual(2, slots.Count());
CollectionAssert.AreEqual(new[] { TestableNode.Input1, TestableNode.Input2 }, slots.Select(x => x.id));
}
[Test]
public void TestCyclicConnectionsAreNotAllowedOnGraph()
{
var graph = new GraphData();
var nodeA = new TestableNode();
graph.AddNode(nodeA);
var nodeB = new TestableNode();
graph.AddNode(nodeB);
Assert.AreEqual(2, graph.GetNodes<AbstractMaterialNode>().Count());
graph.Connect(nodeA.GetSlotReference(TestableNode.Output0), nodeB.GetSlotReference(TestableNode.Input0));
Assert.AreEqual(1, graph.edges.Count());
var edge = graph.Connect(nodeB.GetSlotReference(TestableNode.Output0), nodeA.GetSlotReference(TestableNode.Input0));
Assert.IsNull(edge);
Assert.AreEqual(1, graph.edges.Count());
}
}
}
| 39.047486 | 148 | 0.580871 | [
"Apache-2.0"
] | DPRuin/LearnShader | LearnShader/Library/PackageCache/com.unity.shadergraph@6.9.2/Tests/Editor/UnitTests/SerializedGraphTests.cs | 27,958 | C# |
#if NET40
namespace System.Collections.Generic
{
/// <summary>
/// 表示可按照索引进行访问的元素的只读集合。
/// </summary>
/// <typeparam name="T">只读列表中元素的类型</typeparam>
public interface IReadOnlyList<out T> : IReadOnlyCollection<T>, IEnumerable<T>, IEnumerable
{
/// <summary>
/// 获取位于只读列表中指定索引处的元素。
/// </summary>
/// <param name="index">要获取的元素的索引(索引从零开始)。</param>
/// <returns>在只读列表中指定索引处的元素。</returns>
T this[int index] { get; }
}
}
#endif | 27.777778 | 95 | 0.59 | [
"MIT"
] | lejiebianlidian/codearts | src/CodeArts/Collections/Generic/IReadOnlyList.cs | 660 | 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.Reflection;
public class Map<K,D> {}
public class C
{
public static int Main()
{
Type t = Type.GetType("Map`2[System.Int32,System.Int32]");
Console.WriteLine("PASS");
return 100;
}
}
| 21.7 | 71 | 0.705069 | [
"MIT"
] | 06needhamt/runtime | src/coreclr/tests/src/Loader/classloader/generics/regressions/433497/vsw433497.cs | 434 | C# |
using System.Windows.Forms;
using System.Xml;
namespace LiveSplit.StardewValley
{
public partial class Settings : UserControl
{
private const string RemoveSave_name = "RemoveSave";
public bool RemoveSave
{
get { return RemoveSave_box.Checked; }
set { RemoveSave_box.Checked = value; }
}
private const string RemoveRebuildGraphics_name = "RemoveRebuildGraphics";
public bool RemoveRebuildGraphics
{
get { return RemoveRebuildGraphics_box.Checked; }
set { RemoveRebuildGraphics_box.Checked = value; }
}
#region SettingsOverride
private const string EnableSettingsOverride_name = "EnableSettingsOverride";
public bool EnableSettingsOverride
{
get { return EnableSettingsOverride_box.Checked; }
set { EnableSettingsOverride_box.Checked = value; }
}
private const string MusicVolume_name = "MusicVolume";
public int MusicVolumeLevel
{
get { return MusicVolume.Value; }
set { MusicVolume.Value = value; }
}
private const string SoundVolume_name = "SoundVolume";
public int SoundVolumeLevel
{
get { return SoundVolume.Value; }
set { SoundVolume.Value = value; }
}
private const string FootstepVolume_name = "FootstepVolume";
public int FootstepVolumeLevel
{
get { return FootstepVolume.Value; }
set { FootstepVolume.Value = value; }
}
private const string AmbientVolume_name = "AmbientVolume";
public int AmbientVolumeLevel
{
get { return AmbientVolume.Value; }
set { AmbientVolume.Value = value; }
}
private const string UnbindEmoteButton_name = "UnbindEmoteButton";
public bool UnbindEmoteButton
{
get { return UnbindEmoteButton_box.Checked; }
set { UnbindEmoteButton_box.Checked = value; }
}
private const string UnbindChatButton_name = "UnbindChatButton";
public bool UnbindChatButton
{
get { return UnbindChatButton_box.Checked; }
set { UnbindChatButton_box.Checked = value; }
}
private const string EnableZoomButton_name = "EnableZoomButton";
public bool EnableZoomButton
{
get { return EnableZoomButtons_box.Checked; }
set { EnableZoomButtons_box.Checked = value; }
}
private const string ToolHitButton_name = "ToolHitButton";
public bool ToolHitButton
{
get { return ToolHitLocations_box.Checked; }
set { ToolHitLocations_box.Checked = value; }
}
private const string AdvancedCrafting_name = "AdvancedCrafting";
public bool AdvancedCrafting
{
get { return AdvancedCrafting_box.Checked; }
set { AdvancedCrafting_box.Checked = value; }
}
private const string SlingshotMode_name = "SlingshotMode";
private const int LEGACY_MODE = 1;
public int SlingshotMode
{
get { return SlingshotMode_dropdown.SelectedIndex; }
set { SlingshotMode_dropdown.SelectedIndex = value; }
}
#endregion
public Settings()
{
InitializeComponent();
RemoveSave = true;
RemoveRebuildGraphics = true;
EnableSettingsOverride = true;
MusicVolumeLevel = 0;
SoundVolumeLevel = 0;
AmbientVolumeLevel = 0;
FootstepVolumeLevel = 0;
UnbindEmoteButton = false;
UnbindChatButton = false;
EnableZoomButton = true;
AdvancedCrafting = false;
ToolHitButton = false;
SlingshotMode = LEGACY_MODE;
}
public void WriteXml(XmlElement element)
{
WriteBool(element, RemoveSave_name, RemoveSave);
WriteBool(element, RemoveRebuildGraphics_name, RemoveRebuildGraphics);
WriteBool(element, EnableSettingsOverride_name, EnableSettingsOverride);
WriteInt(element, MusicVolume_name, MusicVolumeLevel);
WriteInt(element, SoundVolume_name, SoundVolumeLevel);
WriteInt(element, AmbientVolume_name, AmbientVolumeLevel);
WriteInt(element, FootstepVolume_name, FootstepVolumeLevel);
WriteBool(element, UnbindEmoteButton_name, UnbindEmoteButton);
WriteBool(element, UnbindChatButton_name, UnbindChatButton);
WriteBool(element, EnableZoomButton_name, EnableZoomButton);
WriteBool(element, AdvancedCrafting_name, AdvancedCrafting);
WriteBool(element, ToolHitButton_name, ToolHitButton);
WriteInt(element, SlingshotMode_name, SlingshotMode);
}
public void ReadXml(XmlElement element)
{
RemoveSave = ReadBool(element, RemoveSave_name, RemoveSave);
RemoveRebuildGraphics = ReadBool(element, RemoveRebuildGraphics_name, RemoveRebuildGraphics);
EnableSettingsOverride = ReadBool(element, EnableSettingsOverride_name, EnableSettingsOverride);
MusicVolumeLevel = ReadInt(element, MusicVolume_name, MusicVolumeLevel);
SoundVolumeLevel = ReadInt(element, SoundVolume_name, SoundVolumeLevel);
AmbientVolumeLevel = ReadInt(element, AmbientVolume_name, AmbientVolumeLevel);
FootstepVolumeLevel = ReadInt(element, FootstepVolume_name, FootstepVolumeLevel);
UnbindEmoteButton = ReadBool(element, UnbindEmoteButton_name, UnbindEmoteButton);
UnbindChatButton = ReadBool(element, UnbindChatButton_name, UnbindChatButton);
EnableZoomButton = ReadBool(element, EnableZoomButton_name, EnableZoomButton);
AdvancedCrafting = ReadBool(element, AdvancedCrafting_name, AdvancedCrafting);
ToolHitButton = ReadBool(element, ToolHitButton_name, ToolHitButton);
SlingshotMode = ReadInt(element, SlingshotMode_name, SlingshotMode);
}
#region Write XML Methods
private static void WriteBool(XmlElement parent, string name, bool value)
{
WriteString(parent, name, value.ToString());
}
private static void WriteInt(XmlElement parent, string name, int value)
{
WriteString(parent, name, value.ToString());
}
private static void WriteString(XmlElement parent, string name, string value)
{
XmlElement child = parent.OwnerDocument.CreateElement(name);
child.InnerText = value;
parent.AppendChild(child);
}
#endregion
#region Read XML Methods
private static bool ReadBool(XmlElement parent, string name, bool default_)
{
string str = ReadString(parent, name, null);
if (str != null && bool.TryParse(str, out bool value)) return value;
return default_;
}
private static int ReadInt(XmlElement parent, string name, int default_)
{
string str = ReadString(parent, name, null);
if (str != null && int.TryParse(str, out int value)) return value;
return default_;
}
private static string ReadString(XmlElement parent, string name, string default_)
{
XmlElement child = parent[name];
if (child != null) return child.InnerText;
return default_;
}
#endregion
public bool Override(MemoryModel memory)
{
if (memory.IsTitleMenu) return true;
memory.SetMusicVolume(MusicVolumeLevel);
memory.SetSoundVolume(SoundVolumeLevel);
memory.SetFootstepVolume(FootstepVolumeLevel);
memory.SetAmbientVolume(AmbientVolumeLevel);
if (!(memory is MemoryModels.MemoryModel_5_5 || memory is MemoryModels.MemoryModel_5_6))
{
if (UnbindEmoteButton) memory.UnbindEmoteButton();
if (UnbindChatButton) memory.UnbindChatButton();
}
if (EnableZoomButton) memory.EnableZoomButton();
if (AdvancedCrafting) memory.AdvancedCrafting();
if (ToolHitButton) memory.ToolHitIndicator();
memory.SlingshotMode(SlingshotMode == LEGACY_MODE);
return false;
}
}
}
| 36.874459 | 108 | 0.63043 | [
"MIT"
] | Underscore76/LiveSplit.StardewValley | Settings.cs | 8,520 | C# |
/*
* Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the health-2016-08-04.normal.json service model.
*/
using System;
using System.IO;
using System.Text;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Amazon.AWSHealth;
using Amazon.AWSHealth.Model;
using Amazon.AWSHealth.Model.Internal.MarshallTransformations;
using Amazon.Runtime.Internal.Transform;
using ServiceClientGenerator;
using AWSSDK_DotNet35.UnitTests.TestTools;
namespace AWSSDK_DotNet35.UnitTests.Marshalling
{
[TestClass]
public class AWSHealthMarshallingTests
{
static readonly ServiceModel service_model = Utils.LoadServiceModel("health");
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Json")]
[TestCategory("AWSHealth")]
public void DescribeAffectedEntitiesMarshallTest()
{
var request = InstantiateClassGenerator.Execute<DescribeAffectedEntitiesRequest>();
var marshaller = new DescribeAffectedEntitiesRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content);
Comparer.CompareObjectToJson<DescribeAffectedEntitiesRequest>(request,jsonRequest);
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"}
}
};
var jsonResponse = new JsonSampleGenerator(service_model, service_model.FindOperation("DescribeAffectedEntities").ResponseStructure).Execute();
webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString());
UnmarshallerContext context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), false, webResponse);
var response = DescribeAffectedEntitiesResponseUnmarshaller.Instance.Unmarshall(context)
as DescribeAffectedEntitiesResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Json")]
[TestCategory("AWSHealth")]
public void DescribeEntityAggregatesMarshallTest()
{
var request = InstantiateClassGenerator.Execute<DescribeEntityAggregatesRequest>();
var marshaller = new DescribeEntityAggregatesRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content);
Comparer.CompareObjectToJson<DescribeEntityAggregatesRequest>(request,jsonRequest);
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"}
}
};
var jsonResponse = new JsonSampleGenerator(service_model, service_model.FindOperation("DescribeEntityAggregates").ResponseStructure).Execute();
webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString());
UnmarshallerContext context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), false, webResponse);
var response = DescribeEntityAggregatesResponseUnmarshaller.Instance.Unmarshall(context)
as DescribeEntityAggregatesResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Json")]
[TestCategory("AWSHealth")]
public void DescribeEventAggregatesMarshallTest()
{
var request = InstantiateClassGenerator.Execute<DescribeEventAggregatesRequest>();
var marshaller = new DescribeEventAggregatesRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content);
Comparer.CompareObjectToJson<DescribeEventAggregatesRequest>(request,jsonRequest);
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"}
}
};
var jsonResponse = new JsonSampleGenerator(service_model, service_model.FindOperation("DescribeEventAggregates").ResponseStructure).Execute();
webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString());
UnmarshallerContext context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), false, webResponse);
var response = DescribeEventAggregatesResponseUnmarshaller.Instance.Unmarshall(context)
as DescribeEventAggregatesResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Json")]
[TestCategory("AWSHealth")]
public void DescribeEventDetailsMarshallTest()
{
var request = InstantiateClassGenerator.Execute<DescribeEventDetailsRequest>();
var marshaller = new DescribeEventDetailsRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content);
Comparer.CompareObjectToJson<DescribeEventDetailsRequest>(request,jsonRequest);
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"}
}
};
var jsonResponse = new JsonSampleGenerator(service_model, service_model.FindOperation("DescribeEventDetails").ResponseStructure).Execute();
webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString());
UnmarshallerContext context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), false, webResponse);
var response = DescribeEventDetailsResponseUnmarshaller.Instance.Unmarshall(context)
as DescribeEventDetailsResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Json")]
[TestCategory("AWSHealth")]
public void DescribeEventsMarshallTest()
{
var request = InstantiateClassGenerator.Execute<DescribeEventsRequest>();
var marshaller = new DescribeEventsRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content);
Comparer.CompareObjectToJson<DescribeEventsRequest>(request,jsonRequest);
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"}
}
};
var jsonResponse = new JsonSampleGenerator(service_model, service_model.FindOperation("DescribeEvents").ResponseStructure).Execute();
webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString());
UnmarshallerContext context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), false, webResponse);
var response = DescribeEventsResponseUnmarshaller.Instance.Unmarshall(context)
as DescribeEventsResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Json")]
[TestCategory("AWSHealth")]
public void DescribeEventTypesMarshallTest()
{
var request = InstantiateClassGenerator.Execute<DescribeEventTypesRequest>();
var marshaller = new DescribeEventTypesRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content);
Comparer.CompareObjectToJson<DescribeEventTypesRequest>(request,jsonRequest);
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"}
}
};
var jsonResponse = new JsonSampleGenerator(service_model, service_model.FindOperation("DescribeEventTypes").ResponseStructure).Execute();
webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString());
UnmarshallerContext context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), false, webResponse);
var response = DescribeEventTypesResponseUnmarshaller.Instance.Unmarshall(context)
as DescribeEventTypesResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
}
} | 47.666667 | 155 | 0.659674 | [
"Apache-2.0"
] | Bio2hazard/aws-sdk-net | sdk/test/Services/AWSHealth/UnitTests/Generated/Marshalling/AWSHealthMarshallingTests.cs | 10,296 | C# |
using System;
namespace NefitEasyDotNet
{
class NefitEasyHttpResponse
{
public int Code { get; }
public string[] HeaderData { get; }
public string Payload { get; }
public NefitEasyHttpResponse(string result)
{
var res = result.Split('\n');
if (res.Length > 0)
{
if (res[0].StartsWith("HTTP"))
{
var resCode = res[0].Split(' ');
Code = Convert.ToInt32(resCode[1]);
}
}
HeaderData = new string[res.Length-4];
for (var i = 1; i < res.Length - 3; i++)
{
HeaderData[i - 1] = res[i];
}
Payload = res[res.Length - 1];
}
}
} | 26.6 | 55 | 0.429825 | [
"MIT"
] | larscom/nefit-easy-dotnet | src/NefitEasyDotNet/NefitEasyHTTPResponse.cs | 798 | C# |
using System;
using System.Linq;
class C2
{
static int[] Read() => Array.ConvertAll(Console.ReadLine().Split(), int.Parse);
static (int, int) Read2() { var a = Read(); return (a[0], a[1]); }
static void Main()
{
var (h, w) = Read2();
var s = Array.ConvertAll(new bool[h], _ => Console.ReadLine());
var q =
from i in Enumerable.Range(0, h - 1)
from j in Enumerable.Range(0, w - 1)
select new[] { s[i][j], s[i][j + 1], s[i + 1][j], s[i + 1][j + 1] }.Count(c => c == '#') % 2 == 1;
Console.WriteLine(q.Count(b => b));
}
}
| 28.15 | 102 | 0.538188 | [
"MIT"
] | sakapon/AtCoder-Contests | CSharp/Contests2021/ABC191/C2.cs | 565 | C# |
using Ray2Mod.Components.Types;
using Ray2Mod.Game.Functions;
using Ray2Mod.Game.Structs;
using System.Globalization;
namespace Ray2Mod.Utils
{
public static class TextUtils
{
#region Formatting
public static string Red(this string s) => "/O200:" + s + "/O0:";
public static string Yellow(this string s) => "/O400:" + s + "/O0:";
public static string Special(this string s) => "/O800:" + s + "/O0:";
public static string Center(this string s) => "/c:" + s;
public static string NL(this string s) => s + "/l:";
public static string Arrow = "\\";
public static string D3(this float f) => f.ToString("0.000", CultureInfo.InvariantCulture);
public static string D3(this double d) => d.ToString("0.000", CultureInfo.InvariantCulture);
public static string KeyValue(this string k, string v) => k.Red() + Arrow + v;
#endregion
//TODO: phase these out, use TextOverlay class instead?
internal static void TextOverlay(string text, float size, float x, float y, byte alpha = 255)
{
Text2D textStruct = new Text2D
{
text = text,
size = size,
positionX = x,
positionY = y,
alphaByte = alpha
};
TextOverlay(textStruct);
}
internal static void TextOverlay(Text2D textStruct)
{
using (StructPtr textPtr = new StructPtr(textStruct))
{
TextFunctions.DrawText.Call(0x5004D4, textPtr);
}
}
}
} | 33.040816 | 101 | 0.569487 | [
"MIT"
] | raytools/Ray2Mod | Ray2Mod/Utils/TextUtils.cs | 1,621 | C# |
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Text;
using Newtonsoft.Json.Linq;
namespace FineUI.Examples.grid
{
public partial class grid_lockcolumn_summary_scrollbar : PageBase
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindGrid();
OutputSummaryData();
}
}
#region BindGrid
private void OutputSummaryData()
{
DataTable source = DataSourceUtil.GetDataTable2();
float donateTotal = 0.0f;
float feeTotal = 0.0f;
foreach (DataRow row in source.Rows)
{
donateTotal += Convert.ToInt32(row["Donate"]);
feeTotal += Convert.ToInt32(row["Fee"]);
}
JObject summary = new JObject();
//summary.Add("major", "全部合计");
summary.Add("fee", feeTotal.ToString("F2"));
summary.Add("donate", donateTotal.ToString("F2"));
Grid1.SummaryData = summary;
}
private void BindGrid()
{
// 1.设置总项数(特别注意:数据库分页一定要设置总记录数RecordCount)
Grid1.RecordCount = GetTotalCount();
// 2.获取当前分页数据
DataTable table = GetPagedDataTable(Grid1.PageIndex, Grid1.PageSize);
// 3.绑定到Grid
Grid1.DataSource = table;
Grid1.DataBind();
}
/// <summary>
/// 模拟返回总项数
/// </summary>
/// <returns></returns>
private int GetTotalCount()
{
return DataSourceUtil.GetDataTable2().Rows.Count;
}
/// <summary>
/// 模拟数据库分页
/// </summary>
/// <returns></returns>
private DataTable GetPagedDataTable(int pageIndex, int pageSize)
{
DataTable source = DataSourceUtil.GetDataTable2();
DataTable paged = source.Clone();
int rowbegin = pageIndex * pageSize;
int rowend = (pageIndex + 1) * pageSize;
if (rowend > source.Rows.Count)
{
rowend = source.Rows.Count;
}
for (int i = rowbegin; i < rowend; i++)
{
paged.ImportRow(source.Rows[i]);
}
return paged;
}
#endregion
#region Events
protected void Button1_Click(object sender, EventArgs e)
{
labResult.Text = HowManyRowsAreSelected(Grid1);
}
protected void Grid1_PageIndexChange(object sender, GridPageEventArgs e)
{
//Grid1.PageIndex = e.NewPageIndex;
BindGrid();
}
#endregion
}
}
| 24.92437 | 82 | 0.500674 | [
"Apache-2.0"
] | JesterWang/FineUI | FineUI.Examples/grid/grid_lockcolumn_summary_scrollbar.aspx.cs | 3,078 | C# |
// ------------------------------------------------------------------------------
// <auto-generated>
// Generated by Xsd2Code. Version 3.4.0.18239 Microsoft Reciprocal License (Ms-RL)
// <NameSpace>Mim.V6301</NameSpace><Collection>Array</Collection><codeType>CSharp</codeType><EnableDataBinding>False</EnableDataBinding><EnableLazyLoading>False</EnableLazyLoading><TrackingChangesEnable>False</TrackingChangesEnable><GenTrackingClasses>False</GenTrackingClasses><HidePrivateFieldInIDE>False</HidePrivateFieldInIDE><EnableSummaryComment>True</EnableSummaryComment><VirtualProp>False</VirtualProp><IncludeSerializeMethod>True</IncludeSerializeMethod><UseBaseClass>False</UseBaseClass><GenBaseClass>False</GenBaseClass><GenerateCloneMethod>True</GenerateCloneMethod><GenerateDataContracts>False</GenerateDataContracts><CodeBaseTag>Net35</CodeBaseTag><SerializeMethodName>Serialize</SerializeMethodName><DeserializeMethodName>Deserialize</DeserializeMethodName><SaveToFileMethodName>SaveToFile</SaveToFileMethodName><LoadFromFileMethodName>LoadFromFile</LoadFromFileMethodName><GenerateXMLAttributes>True</GenerateXMLAttributes><OrderXMLAttrib>False</OrderXMLAttrib><EnableEncoding>False</EnableEncoding><AutomaticProperties>False</AutomaticProperties><GenerateShouldSerialize>False</GenerateShouldSerialize><DisableDebug>False</DisableDebug><PropNameSpecified>Default</PropNameSpecified><Encoder>UTF8</Encoder><CustomUsings></CustomUsings><ExcludeIncludedTypes>True</ExcludeIncludedTypes><EnableInitializeFields>False</EnableInitializeFields>
// </auto-generated>
// ------------------------------------------------------------------------------
namespace Mim.V6301 {
using System;
using System.Diagnostics;
using System.Xml.Serialization;
using System.Collections;
using System.Xml.Schema;
using System.ComponentModel;
using System.IO;
using System.Text;
[System.CodeDom.Compiler.GeneratedCodeAttribute("Xsd2Code", "3.4.0.18239")]
[System.SerializableAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(TypeName="PRPA_MT000002UK03.AdviceAndGuidanceRequest", Namespace="urn:hl7-org:v3")]
[System.Xml.Serialization.XmlRootAttribute("PRPA_MT000002UK03.AdviceAndGuidanceRequest", Namespace="urn:hl7-org:v3")]
public partial class PRPA_MT000002UK03AdviceAndGuidanceRequest {
private II idField;
private CV codeField;
private TS effectiveTimeField;
private TS activityTimeField;
private CV priorityCodeField;
private PRPA_MT000002UK03Component[] component10Field;
private PRPA_MT000002UK03Subject1 subjectField;
private PRPA_MT000002UK03Referrer[] referrerField;
private PRPA_MT000002UK03Component11 component2Field;
private PRPA_MT000002UK03Component21 component6Field;
private PRPA_MT000002UK03Component25 component3Field;
private PRPA_MT000002UK03Component32 component5Field;
private PRPA_MT000002UK03Component38 component4Field;
private PRPA_MT000002UK03Component6 component1Field;
private PRPA_MT000002UK03PertinentInformation pertinentInformation6Field;
private PRPA_MT000002UK03PertinentInformation12[] pertinentInformation9Field;
private PRPA_MT000002UK03PertinentInformation13[] pertinentInformation2Field;
private PRPA_MT000002UK03PertinentInformation16[] pertinentInformation1Field;
private PRPA_MT000002UK03PertinentInformation17[] pertinentInformation4Field;
private PRPA_MT000002UK03PertinentInformation21 pertinentInformation5Field;
private PRPA_MT000002UK03PertinentInformation22 pertinentInformation7Field;
private PRPA_MT000002UK03PertinentInformation23[] pertinentInformation8Field;
private PRPA_MT000002UK03PertinentInformation9 pertinentInformation3Field;
private string typeField;
private string classCodeField;
private string moodCodeField;
private string[] typeIDField;
private string[] realmCodeField;
private string nullFlavorField;
private static System.Xml.Serialization.XmlSerializer serializer;
public PRPA_MT000002UK03AdviceAndGuidanceRequest() {
this.typeField = "ActHeir";
this.classCodeField = "INFRM";
this.moodCodeField = "RQO";
}
public II id {
get {
return this.idField;
}
set {
this.idField = value;
}
}
public CV code {
get {
return this.codeField;
}
set {
this.codeField = value;
}
}
public TS effectiveTime {
get {
return this.effectiveTimeField;
}
set {
this.effectiveTimeField = value;
}
}
public TS activityTime {
get {
return this.activityTimeField;
}
set {
this.activityTimeField = value;
}
}
public CV priorityCode {
get {
return this.priorityCodeField;
}
set {
this.priorityCodeField = value;
}
}
[System.Xml.Serialization.XmlElementAttribute("component10")]
public PRPA_MT000002UK03Component[] component10 {
get {
return this.component10Field;
}
set {
this.component10Field = value;
}
}
public PRPA_MT000002UK03Subject1 subject {
get {
return this.subjectField;
}
set {
this.subjectField = value;
}
}
[System.Xml.Serialization.XmlElementAttribute("referrer")]
public PRPA_MT000002UK03Referrer[] referrer {
get {
return this.referrerField;
}
set {
this.referrerField = value;
}
}
public PRPA_MT000002UK03Component11 component2 {
get {
return this.component2Field;
}
set {
this.component2Field = value;
}
}
public PRPA_MT000002UK03Component21 component6 {
get {
return this.component6Field;
}
set {
this.component6Field = value;
}
}
public PRPA_MT000002UK03Component25 component3 {
get {
return this.component3Field;
}
set {
this.component3Field = value;
}
}
public PRPA_MT000002UK03Component32 component5 {
get {
return this.component5Field;
}
set {
this.component5Field = value;
}
}
public PRPA_MT000002UK03Component38 component4 {
get {
return this.component4Field;
}
set {
this.component4Field = value;
}
}
public PRPA_MT000002UK03Component6 component1 {
get {
return this.component1Field;
}
set {
this.component1Field = value;
}
}
public PRPA_MT000002UK03PertinentInformation pertinentInformation6 {
get {
return this.pertinentInformation6Field;
}
set {
this.pertinentInformation6Field = value;
}
}
[System.Xml.Serialization.XmlElementAttribute("pertinentInformation9")]
public PRPA_MT000002UK03PertinentInformation12[] pertinentInformation9 {
get {
return this.pertinentInformation9Field;
}
set {
this.pertinentInformation9Field = value;
}
}
[System.Xml.Serialization.XmlElementAttribute("pertinentInformation2")]
public PRPA_MT000002UK03PertinentInformation13[] pertinentInformation2 {
get {
return this.pertinentInformation2Field;
}
set {
this.pertinentInformation2Field = value;
}
}
[System.Xml.Serialization.XmlElementAttribute("pertinentInformation1")]
public PRPA_MT000002UK03PertinentInformation16[] pertinentInformation1 {
get {
return this.pertinentInformation1Field;
}
set {
this.pertinentInformation1Field = value;
}
}
[System.Xml.Serialization.XmlElementAttribute("pertinentInformation4")]
public PRPA_MT000002UK03PertinentInformation17[] pertinentInformation4 {
get {
return this.pertinentInformation4Field;
}
set {
this.pertinentInformation4Field = value;
}
}
public PRPA_MT000002UK03PertinentInformation21 pertinentInformation5 {
get {
return this.pertinentInformation5Field;
}
set {
this.pertinentInformation5Field = value;
}
}
public PRPA_MT000002UK03PertinentInformation22 pertinentInformation7 {
get {
return this.pertinentInformation7Field;
}
set {
this.pertinentInformation7Field = value;
}
}
[System.Xml.Serialization.XmlElementAttribute("pertinentInformation8")]
public PRPA_MT000002UK03PertinentInformation23[] pertinentInformation8 {
get {
return this.pertinentInformation8Field;
}
set {
this.pertinentInformation8Field = value;
}
}
public PRPA_MT000002UK03PertinentInformation9 pertinentInformation3 {
get {
return this.pertinentInformation3Field;
}
set {
this.pertinentInformation3Field = value;
}
}
[System.Xml.Serialization.XmlAttributeAttribute(DataType="token")]
public string type {
get {
return this.typeField;
}
set {
this.typeField = value;
}
}
[System.Xml.Serialization.XmlAttributeAttribute()]
public string classCode {
get {
return this.classCodeField;
}
set {
this.classCodeField = value;
}
}
[System.Xml.Serialization.XmlAttributeAttribute()]
public string moodCode {
get {
return this.moodCodeField;
}
set {
this.moodCodeField = value;
}
}
[System.Xml.Serialization.XmlAttributeAttribute()]
public string[] typeID {
get {
return this.typeIDField;
}
set {
this.typeIDField = value;
}
}
[System.Xml.Serialization.XmlAttributeAttribute(DataType="token")]
public string[] realmCode {
get {
return this.realmCodeField;
}
set {
this.realmCodeField = value;
}
}
[System.Xml.Serialization.XmlAttributeAttribute(DataType="token")]
public string nullFlavor {
get {
return this.nullFlavorField;
}
set {
this.nullFlavorField = value;
}
}
private static System.Xml.Serialization.XmlSerializer Serializer {
get {
if ((serializer == null)) {
serializer = new System.Xml.Serialization.XmlSerializer(typeof(PRPA_MT000002UK03AdviceAndGuidanceRequest));
}
return serializer;
}
}
#region Serialize/Deserialize
/// <summary>
/// Serializes current PRPA_MT000002UK03AdviceAndGuidanceRequest object into an XML document
/// </summary>
/// <returns>string XML value</returns>
public virtual string Serialize() {
System.IO.StreamReader streamReader = null;
System.IO.MemoryStream memoryStream = null;
try {
memoryStream = new System.IO.MemoryStream();
Serializer.Serialize(memoryStream, this);
memoryStream.Seek(0, System.IO.SeekOrigin.Begin);
streamReader = new System.IO.StreamReader(memoryStream);
return streamReader.ReadToEnd();
}
finally {
if ((streamReader != null)) {
streamReader.Dispose();
}
if ((memoryStream != null)) {
memoryStream.Dispose();
}
}
}
/// <summary>
/// Deserializes workflow markup into an PRPA_MT000002UK03AdviceAndGuidanceRequest object
/// </summary>
/// <param name="xml">string workflow markup to deserialize</param>
/// <param name="obj">Output PRPA_MT000002UK03AdviceAndGuidanceRequest object</param>
/// <param name="exception">output Exception value if deserialize failed</param>
/// <returns>true if this XmlSerializer can deserialize the object; otherwise, false</returns>
public static bool Deserialize(string xml, out PRPA_MT000002UK03AdviceAndGuidanceRequest obj, out System.Exception exception) {
exception = null;
obj = default(PRPA_MT000002UK03AdviceAndGuidanceRequest);
try {
obj = Deserialize(xml);
return true;
}
catch (System.Exception ex) {
exception = ex;
return false;
}
}
public static bool Deserialize(string xml, out PRPA_MT000002UK03AdviceAndGuidanceRequest obj) {
System.Exception exception = null;
return Deserialize(xml, out obj, out exception);
}
public static PRPA_MT000002UK03AdviceAndGuidanceRequest Deserialize(string xml) {
System.IO.StringReader stringReader = null;
try {
stringReader = new System.IO.StringReader(xml);
return ((PRPA_MT000002UK03AdviceAndGuidanceRequest)(Serializer.Deserialize(System.Xml.XmlReader.Create(stringReader))));
}
finally {
if ((stringReader != null)) {
stringReader.Dispose();
}
}
}
/// <summary>
/// Serializes current PRPA_MT000002UK03AdviceAndGuidanceRequest object into file
/// </summary>
/// <param name="fileName">full path of outupt xml file</param>
/// <param name="exception">output Exception value if failed</param>
/// <returns>true if can serialize and save into file; otherwise, false</returns>
public virtual bool SaveToFile(string fileName, out System.Exception exception) {
exception = null;
try {
SaveToFile(fileName);
return true;
}
catch (System.Exception e) {
exception = e;
return false;
}
}
public virtual void SaveToFile(string fileName) {
System.IO.StreamWriter streamWriter = null;
try {
string xmlString = Serialize();
System.IO.FileInfo xmlFile = new System.IO.FileInfo(fileName);
streamWriter = xmlFile.CreateText();
streamWriter.WriteLine(xmlString);
streamWriter.Close();
}
finally {
if ((streamWriter != null)) {
streamWriter.Dispose();
}
}
}
/// <summary>
/// Deserializes xml markup from file into an PRPA_MT000002UK03AdviceAndGuidanceRequest object
/// </summary>
/// <param name="fileName">string xml file to load and deserialize</param>
/// <param name="obj">Output PRPA_MT000002UK03AdviceAndGuidanceRequest object</param>
/// <param name="exception">output Exception value if deserialize failed</param>
/// <returns>true if this XmlSerializer can deserialize the object; otherwise, false</returns>
public static bool LoadFromFile(string fileName, out PRPA_MT000002UK03AdviceAndGuidanceRequest obj, out System.Exception exception) {
exception = null;
obj = default(PRPA_MT000002UK03AdviceAndGuidanceRequest);
try {
obj = LoadFromFile(fileName);
return true;
}
catch (System.Exception ex) {
exception = ex;
return false;
}
}
public static bool LoadFromFile(string fileName, out PRPA_MT000002UK03AdviceAndGuidanceRequest obj) {
System.Exception exception = null;
return LoadFromFile(fileName, out obj, out exception);
}
public static PRPA_MT000002UK03AdviceAndGuidanceRequest LoadFromFile(string fileName) {
System.IO.FileStream file = null;
System.IO.StreamReader sr = null;
try {
file = new System.IO.FileStream(fileName, FileMode.Open, FileAccess.Read);
sr = new System.IO.StreamReader(file);
string xmlString = sr.ReadToEnd();
sr.Close();
file.Close();
return Deserialize(xmlString);
}
finally {
if ((file != null)) {
file.Dispose();
}
if ((sr != null)) {
sr.Dispose();
}
}
}
#endregion
#region Clone method
/// <summary>
/// Create a clone of this PRPA_MT000002UK03AdviceAndGuidanceRequest object
/// </summary>
public virtual PRPA_MT000002UK03AdviceAndGuidanceRequest Clone() {
return ((PRPA_MT000002UK03AdviceAndGuidanceRequest)(this.MemberwiseClone()));
}
#endregion
}
}
| 36.304924 | 1,358 | 0.562001 | [
"MIT"
] | Kusnaditjung/MimDms | src/Mim.V6301/Generated/PRPA_MT000002UK03AdviceAndGuidanceRequest.cs | 19,169 | C# |
//using Microsoft.Unity.VisualStudio.Editor;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Achivements : MonoBehaviour
{
public static Achivements instance;
private void Awake()
{
if (instance == null) { instance = this; }
}
[SerializeField] private GameObject[] doneImage; // Картинки с галочками
public GameObject StarAch1;
public GameObject StarAch2;
public GameObject StarAch3;
private int numberOfFinishedLvlS=0;
//private int countFinishedLVLs;
private int requirement_FinithFirstLVL = 1;
private int requirement_20_FinishedLvls=20;
private int requirement_100_FinishedLvls = 100;
private void Start()
{
}
private void Update()
{
CheckAchInPanel();
}
public void CheckAchInPanel()
{
if (numberOfFinishedLvlS == requirement_FinithFirstLVL) { StarAch1.gameObject.SetActive(true); }
else { StarAch1.gameObject.SetActive(false); }
if (numberOfFinishedLvlS > requirement_20_FinishedLvls) { StarAch2.gameObject.SetActive(true); }
else { StarAch2.gameObject.SetActive(false); }
if (numberOfFinishedLvlS > requirement_100_FinishedLvls) { StarAch3.gameObject.SetActive(true); }
else { StarAch3.gameObject.SetActive(false); }
}
public void AddFinishedLvl(int i) { numberOfFinishedLvlS += i; }
//public void OnTakeBonus(string bonusName)
//{
// if (bonusName=="Shield" && doneImage[3].activeSelf == false)
// doneImage[3].SetActive(true);
// if (bonusName == "Time" && doneImage[4].activeSelf == false)
// doneImage[4].SetActive(true);
// if (bonusName == "Heart" && doneImage[5].activeSelf == false)
// doneImage[5].SetActive(true);
//}
}
| 30.33871 | 106 | 0.645933 | [
"Apache-2.0"
] | the-Nem/Fujion | C#/Achivements.cs | 1,901 | C# |
/*
MIT License
Copyright (c) 2017 Jeiel Aranal
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using SubjectNerd.PsdImporter.FullSerializer;
using SubjectNerd.PsdImporter.Reconstructor;
using UnityEditor;
using UnityEngine;
using Object = UnityEngine.Object;
namespace SubjectNerd.PsdImporter
{
public class PsdImportWindow : EditorWindow
{
private const string PrefKeyAdvancedMode = "SubjectNerdAgreement.Psd.Advanced";
#region Static
private const string MENU_ASSET_IMPORT = "Assets/Import PSD Layers";
private static PsdImportWindow OpenWindow()
{
var win = GetWindow<PsdImportWindow>();
win.titleContent = new GUIContent("PSD Importer");
win.Show(true);
win.minSize = new Vector2(350, 400);
win.autoRepaintOnSceneChange = true;
return win;
}
[MenuItem(MENU_ASSET_IMPORT)]
private static void ImportPsdAsset()
{
var win = OpenWindow();
Object[] selectionArray = Selection.objects;
if (selectionArray.Length < 1)
return;
for (int i = 0; i < selectionArray.Length; i++)
{
var file = selectionArray[i];
var path = AssetDatabase.GetAssetPath(file);
if (path.ToLower().EndsWith(".psd"))
{
win.OpenFile(file);
return;
}
}
}
public static bool OpenLayerImporter(Object file)
{
var win = OpenWindow();
if (file == null)
return false;
var path = AssetDatabase.GetAssetPath(file);
if (string.IsNullOrEmpty(path))
return false;
if (path.ToLower().EndsWith(".psd") == false)
return false;
win.OpenFile(file);
return true;
}
#endregion
private bool isOpeningFile;
private float importPPU = 100;
private Object importFile;
private string importPath;
private ImportUserData importSettings;
private DisplayLayerData importDisplay;
private Texture2D importPreview;
private bool settingsChanged;
private readonly List<int[]> importLayersList = new List<int[]>();
private readonly List<int[]> quickSelect = new List<int[]>();
private int selectionCount = 0;
fsSerializer serializer;
private Type typeImportUserData;
private bool showImportSettings;
private int[] lastSelectedLayer;
private readonly Dictionary<int[], Rect> layerRectLookup = new Dictionary<int[], Rect>();
private bool isChangingSelection;
private bool selectionChangeState;
private string searchFilter = "";
private bool showHeader = true;
private bool isAdvancedMode = false;
private IReconstructor[] reconstructors;
#region UI fields
private readonly GUIContent labelHeader = new GUIContent("Import PSD Layers");
private readonly GUIContent labelAdvanced = new GUIContent("Advanced");
private readonly GUIContent labelFileNaming = new GUIContent("File Names");
private readonly GUIContent labelGrpMode = new GUIContent("Group Mode");
private readonly GUIContent labelPackTag = new GUIContent("Packing Tag");
private readonly GUIContent labelPixelUnit = new GUIContent("Pixels Per Unit");
private readonly GUIContent labelAlignment = new GUIContent("Default Pivot");
private readonly GUIContent labelFile = new GUIContent("Import PSD");
private readonly GUIContent labelShowImport = new GUIContent("Import Settings");
private readonly GUIContent labelScale = new GUIContent("Default Scale");
private readonly GUIContent labelPath = new GUIContent("Import Folder");
private readonly GUIContent labelPickPath = new GUIContent("Open");
//private readonly GUIContent labelAutoImport = new GUIContent("Auto Import");
private readonly GUIContent labelUseConstructor = new GUIContent("Reconstructor");
private readonly GUIContent labelSelConstructor = new GUIContent("Construct As");
private readonly GUIContent labelDocAlign = new GUIContent("Document Alignment");
private readonly GUIContent labelDocPivot = new GUIContent("Document Pivot");
private readonly GUIContent labelLoadBoxEmpty = new GUIContent("No PSD File Loaded");
private int selectedReconstructor;
private GUIContent[] dropdownReconstruct;
private bool stylesLoaded = false;
private GUIStyle styleHeader, styleBoldFoldout,
styleLayerEntry, styleLayerSelected,
styleVisOn, styleVisOff, styleLoader,
styleToolbar, styleToolSearch, styleToolCancel,
styleLoadBoxEmpty;
private Texture2D icnFolder, icnTexture;
private GUILayoutOption layerHeight;
private GUILayoutOption noExpandW;
private GUILayoutOption bigButton;
// Column widths
private Rect rImportToggle, rVisible, rLayerDisplay, rPivot, rScaling, rMakeDefault;
private Vector2 rTableSize;
private bool tableWillScroll;
private float layerEntryYMax;
private Vector2 scrollPos;
private int indentLevel = 0;
private const float indentWidth = 20;
private void LoadStyles()
{
if (stylesLoaded)
return;
layerHeight = GUILayout.Height(EditorGUIUtility.singleLineHeight + 5);
noExpandW = GUILayout.ExpandWidth(false);
bigButton = GUILayout.Height(30);
icnFolder = EditorGUIUtility.FindTexture("Folder Icon");
icnTexture = EditorGUIUtility.FindTexture("Texture Icon");
styleHeader = new GUIStyle(GUI.skin.label)
{
alignment = TextAnchor.MiddleCenter,
fontStyle = FontStyle.Bold
};
var tempStyle = GUI.skin.FindStyle("EyeDropperHorizontalLine");
styleLayerEntry = new GUIStyle(GUI.skin.box)
{
margin = new RectOffset(0, 0, 0, 0),
padding = new RectOffset(0, 0, 0, 0),
contentOffset = new Vector2(0, 0),
normal = new GUIStyleState() { background = tempStyle.normal.background }
};
tempStyle = GUI.skin.FindStyle("HelpBox");
styleLayerSelected = new GUIStyle(GUI.skin.box)
{
margin = new RectOffset(0, 0, 0, 0),
padding = new RectOffset(0, 0, 0, 0),
contentOffset = new Vector2(0, 0),
normal = new GUIStyleState() { background = tempStyle.normal.background }
};
styleLoader = new GUIStyle(GUI.skin.FindStyle("ObjectFieldThumb"))
{
margin = new RectOffset(5, 5, 5, 5),
padding = new RectOffset(2, 2, 2, 2),
alignment = TextAnchor.MiddleCenter,
fixedHeight = 100,
stretchWidth = true
};
styleLoadBoxEmpty = new GUIStyle()
{
padding = new RectOffset(5, 5, 5, 5),
alignment = TextAnchor.MiddleCenter,
wordWrap = true
};
styleBoldFoldout = new GUIStyle(EditorStyles.foldout)
{
fontStyle = FontStyle.Bold
};
tempStyle = GUI.skin.FindStyle("Toggle");
styleVisOff = new GUIStyle(tempStyle)
{
margin = new RectOffset(10, 10, 3, 3)
};
styleVisOn = new GUIStyle(tempStyle)
{
normal = new GUIStyleState() { background = tempStyle.onNormal.background },
margin = new RectOffset(10, 10, 3, 3)
};
styleToolbar = GUI.skin.FindStyle("Toolbar");
styleToolSearch = GUI.skin.FindStyle("ToolbarSeachTextField");
styleToolCancel = GUI.skin.FindStyle("ToolbarSeachCancelButton");
stylesLoaded = true;
}
#endregion
private void OnEnable()
{
Selection.selectionChanged -= HandleSelectionChange;
Selection.selectionChanged += HandleSelectionChange;
stylesLoaded = false;
isAdvancedMode = EditorPrefs.GetBool(PrefKeyAdvancedMode, false);
typeImportUserData = typeof(ImportUserData);
serializer = new fsSerializer();
// Find implementations of IReconstructor
var type = typeof(IReconstructor);
var types = AppDomain.CurrentDomain.GetAssemblies()
.SelectMany(s => s.GetTypes())
.Where(p => p != type && type.IsAssignableFrom(p));
List<IReconstructor> constructor_list = new List<IReconstructor>();
List<GUIContent> constructor_dropdown = new List<GUIContent>();
foreach (Type type_constructor in types)
{
var instance = Activator.CreateInstance(type_constructor);
var r_instance = (IReconstructor)instance;
if (r_instance != null)
{
constructor_list.Add(r_instance);
constructor_dropdown.Add(new GUIContent(r_instance.DisplayName));
}
}
reconstructors = constructor_list.ToArray();
dropdownReconstruct = constructor_dropdown.ToArray();
importSettings = new ImportUserData();
}
private void OnDestroy()
{
Selection.selectionChanged -= HandleSelectionChange;
reconstructors = null;
dropdownReconstruct = null;
}
private void HandleSelectionChange()
{
Repaint();
}
public void OpenFile(Object fileObject)
{
if (isOpeningFile)
return;
importFile = null;
importPath = string.Empty;
importPreview = null;
importPPU = 100;
importSettings = new ImportUserData() {DocAlignment = SpriteAlignment.Center};
importDisplay = null;
selectionCount = 0;
quickSelect.Clear();
lastSelectedLayer = null;
var filePath = AssetDatabase.GetAssetPath(fileObject);
if (filePath.ToLower().EndsWith(".psd") == false)
{
return;
}
importFile = fileObject;
importPath = filePath;
importPreview = AssetDatabase.LoadAssetAtPath<Texture2D>(importPath);
// Read the texture import settings of the asset file
TextureImporter textureImporter = (TextureImporter)AssetImporter.GetAtPath(importPath);
TextureImporterSettings unityImportSettings = new TextureImporterSettings();
textureImporter.ReadTextureSettings(unityImportSettings);
importPPU = unityImportSettings.spritePixelsPerUnit;
// Attempt to deserialize
string json = textureImporter.userData;
bool didGetUserData = false;
if (string.IsNullOrEmpty(json) == false)
{
fsData data = fsJsonParser.Parse(json);
object deserialObj = null;
if (serializer.TryDeserialize(data, typeImportUserData, ref deserialObj)
.AssertSuccessWithoutWarnings()
.Succeeded)
{
importSettings = (ImportUserData)deserialObj;
if (importSettings == null)
importSettings = new ImportUserData();
else
didGetUserData = true;
}
}
if (didGetUserData)
{
settingsChanged = false;
}
else
{
settingsChanged = true;
showImportSettings = true;
}
isOpeningFile = true;
PsdImporter.BuildImportLayerData(importFile, importSettings, (layerData, displayData) =>
{
importSettings.DocRoot = ResolveData(importSettings.DocRoot, layerData);
importDisplay = displayData;
isOpeningFile = false;
CollateImportList();
Repaint();
});
}
/// <summary>
/// Resolve setting differences from stored data and built data
/// </summary>
/// <param name="storedData"></param>
/// <param name="builtData"></param>
/// <returns></returns>
private ImportLayerData ResolveData(ImportLayerData storedData, ImportLayerData builtData)
{
// Nothing was stored, used built data
if (storedData == null)
return builtData;
// Flatten out stored to a dictionary, using the path as keys
Dictionary<string, ImportLayerData> storedIndex = new Dictionary<string, ImportLayerData>();
storedData.Iterate(
layerCallback: layer =>
{
if (storedIndex.ContainsKey(layer.path) == false)
storedIndex.Add(layer.path, layer);
else
storedIndex[layer.path] = layer;
}
);
// Iterate through the built data now, checking for settings from storedIndex
builtData.Iterate(
layerCallback: layer =>
{
ImportLayerData existingSettings;
if (storedIndex.TryGetValue(layer.path, out existingSettings))
{
layer.useDefaults = existingSettings.useDefaults;
layer.Alignment = existingSettings.Alignment;
layer.Pivot = existingSettings.Pivot;
layer.ScaleFactor = existingSettings.ScaleFactor;
layer.import = existingSettings.import;
}
}
);
return builtData;
}
private void OnGUI()
{
LoadStyles();
switch (Event.current.commandName)
{
case "ObjectSelectorUpdated":
case "ObjectSelectorClosed":
OpenFile(EditorGUIUtility.GetObjectPickerObject());
Repaint();
break;
}
DrawLayerTable();
using (new EditorGUILayout.HorizontalScope())
{
EditorGUILayout.Space();
using (new EditorGUILayout.VerticalScope())
{
DrawReconstructor();
}
EditorGUILayout.Space();
using (new EditorGUILayout.VerticalScope(noExpandW))
{
DrawPsdOperations();
}
EditorGUILayout.Space();
}
EditorGUILayout.Space();
DrawImportSettings();
EditorGUILayout.Space();
}
private float CalculateColumns()
{
// Calculate the sizes for the columns
var width = EditorGUIUtility.currentViewWidth;
var height = EditorGUIUtility.singleLineHeight + 10;
int padTop = 4;
int padBetween = 3;
rImportToggle = new Rect(10, padTop, 16, height);
rVisible = new Rect(rImportToggle.xMax + padBetween, padTop + 2, 10, height);
rMakeDefault = new Rect(0, padTop, 20, EditorGUIUtility.singleLineHeight);
var distWidth = width - rMakeDefault.width - rVisible.xMax;
distWidth -= tableWillScroll ? 40 : 25;
var pivotWidth = Mathf.Clamp(distWidth * 0.2f, 95, 120);
var scaleWidth = Mathf.Clamp(distWidth * 0.2f, 65, 120);
var layerWidth = Mathf.Max(distWidth - pivotWidth - scaleWidth, 150);
rLayerDisplay = new Rect(rVisible.xMax + 10, 2, layerWidth, height - 4);
rPivot = new Rect(rLayerDisplay.xMax + padBetween, padTop, pivotWidth, height);
rScaling = new Rect(rPivot.xMax + padBetween, padTop, scaleWidth, height);
rMakeDefault.x = rScaling.xMax + padBetween;
rTableSize = new Vector2(rMakeDefault.xMax, height);
if (isAdvancedMode == false)
{
rTableSize.x = width;
if (tableWillScroll)
rTableSize.x -= 20;
}
return width;
}
private void DrawLayerTable()
{
using (new EditorGUILayout.HorizontalScope(styleToolbar))
{
searchFilter = EditorGUILayout.TextField(searchFilter, styleToolSearch, GUILayout.ExpandWidth(true));
if (GUILayout.Button(GUIContent.none, styleToolCancel))
{
searchFilter = string.Empty;
GUI.FocusControl(null);
}
if (showHeader)
EditorGUILayout.LabelField(labelHeader, styleHeader, noExpandW);
using (var check = new EditorGUI.ChangeCheckScope())
{
isAdvancedMode = GUILayout.Toggle(isAdvancedMode, labelAdvanced, EditorStyles.miniButton, noExpandW);
if (check.changed)
EditorPrefs.SetBool(PrefKeyAdvancedMode, isAdvancedMode);
}
if (Event.current.type == EventType.Repaint)
{
showHeader = string.IsNullOrEmpty(searchFilter);
if (showHeader == false)
showHeader = EditorGUIUtility.currentViewWidth > 400;
}
}
var width = CalculateColumns();
var rHeader = GUILayoutUtility.GetRect(width, rTableSize.x, EditorGUIUtility.singleLineHeight, EditorGUIUtility.singleLineHeight);
GUI.Box(rHeader, GUIContent.none, styleToolbar);
GUI.Label(new Rect(rLayerDisplay) { y = rHeader.y, x = rLayerDisplay.x - scrollPos.x }, "Layer");
if (isAdvancedMode)
{
GUI.Label(new Rect(rPivot) {y = rHeader.y, x = rPivot.x - scrollPos.x}, "Pivot");
GUI.Label(new Rect(rScaling) {y = rHeader.y, x = rScaling.x - scrollPos.x}, "Scale");
}
using (var scrollView = new EditorGUILayout.ScrollViewScope(scrollPos))
{
scrollPos = scrollView.scrollPosition;
DrawLayerContents();
}
if (Event.current.type == EventType.Repaint)
{
var scrollArea = GUILayoutUtility.GetLastRect();
var newWillScroll = layerEntryYMax > scrollArea.yMax;
if (newWillScroll != tableWillScroll)
{
tableWillScroll = newWillScroll;
Repaint();
}
}
using (new EditorGUI.DisabledGroupScope(importFile == null))
{
var btnW = GUILayout.MaxWidth(EditorGUIUtility.currentViewWidth / 2f);
using (new EditorGUILayout.HorizontalScope())
{
if (GUILayout.Button("Save Selection", btnW))
{
AddQuickSelect();
Repaint();
WriteImportSettings();
}
if (GUILayout.Button("Clear Selection", btnW))
{
quickSelect.Clear();
selectionCount = 0;
lastSelectedLayer = null;
}
}
using (new EditorGUILayout.HorizontalScope())
{
string textImport = string.Format("Import Saved ({0})", importLayersList.Count);
string textQuickImport = string.Format("Import Selected ({0})", selectionCount);
if (GUILayout.Button(textImport, bigButton, btnW))
PsdImporter.ImportLayersUI(importFile, importSettings, importLayersList);
if (GUILayout.Button(textQuickImport, bigButton, btnW))
PsdImporter.ImportLayersUI(importFile, importSettings, quickSelect);
}
}
GUILayout.Box(GUIContent.none, GUILayout.Height(4f), GUILayout.ExpandWidth(true));
}
private void DrawLayerContents()
{
if (importFile == null)
{
EditorGUILayout.HelpBox("No PSD file loaded", MessageType.Error, true);
return;
}
if (importSettings == null || importSettings.DocRoot == null || importDisplay == null)
{
if (importFile != null)
OpenFile(importFile);
return;
}
DrawIterateLayers(importSettings.DocRoot);
}
private void DrawIterateLayers(ImportLayerData layerData)
{
layerRectLookup.Clear();
layerEntryYMax = 0;
layerData.Iterate(
layerCallback: layer =>
{
var display = GetDisplayData(layer.indexId);
if (display == null)
return;
if (string.IsNullOrEmpty(searchFilter) == false)
{
if (layer.name.ToLower().Contains(searchFilter.ToLower()) == false)
return;
}
DrawLayerEntry(layer, display);
},
canEnterGroup: layer =>
{
var display = GetDisplayData(layer.indexId);
if (display == null)
return true;
if (string.IsNullOrEmpty(searchFilter) == false)
return true;
return display.isOpen;
},
enterGroupCallback: data => indentLevel++,
exitGroupCallback: data => indentLevel--
);
// Process mouse events
var evt = Event.current;
bool willChangeSelection = false;
int[] targetLayer = null;
foreach (var kvp in layerRectLookup)
{
if (kvp.Value.Contains(evt.mousePosition))
{
var checkLayer = GetLayerData(kvp.Key);
if (checkLayer == null || checkLayer.Childs == null)
continue;
bool layerIsGroup = checkLayer.Childs.Count > 0;
if (evt.type == EventType.MouseDown)
{
willChangeSelection = layerIsGroup == false;
bool willAddSelect = quickSelect.Contains(kvp.Key) == false;
if (willAddSelect)
lastSelectedLayer = kvp.Key;
if (willChangeSelection)
{
isChangingSelection = true;
targetLayer = kvp.Key;
selectionChangeState = willAddSelect;
}
else
{
RecursiveQuickSelect(checkLayer, willAddSelect);
if (willAddSelect == false)
lastSelectedLayer = null;
Repaint();
}
evt.Use();
}
if (evt.type == EventType.MouseUp)
{
isChangingSelection = false;
}
if (isChangingSelection && evt.type == EventType.MouseDrag && layerIsGroup == false)
{
willChangeSelection = true;
targetLayer = kvp.Key;
}
break;
}
}
if (willChangeSelection && targetLayer != null)
{
SetQuickSelect(targetLayer, selectionChangeState);
GetSelectCount();
Repaint();
}
}
private void DrawLayerEntry(ImportLayerData layer, DisplayLayerData display)
{
bool isGroup = display.isGroup;
bool isSelected = quickSelect.Contains(layer.indexId);
GUIStyle entryStyle = isSelected ? styleLayerSelected : styleLayerEntry;
using (new GUILayout.HorizontalScope(entryStyle, layerHeight))
{
Rect rEntry = GUILayoutUtility.GetRect(rTableSize.x, rTableSize.x, rTableSize.y, rTableSize.y);
Rect rToggle = new Rect(rImportToggle);
Rect rVis = new Rect(rVisible);
Rect rLayer = new Rect(rLayerDisplay);
Rect rPiv = new Rect(rPivot);
Rect rScale = new Rect(rScaling);
Rect rReset = new Rect(rMakeDefault);
rToggle.y += rEntry.y;
rVis.y += rEntry.y;
rLayer.y += rEntry.y;
rPiv.y += rEntry.y;
rScale.y += rEntry.y;
rReset.y += rEntry.y;
bool parentWillImport = ParentWillImport(layer.indexId);
using (new EditorGUI.DisabledScope(parentWillImport == false))
{
var displayImport = layer.import && parentWillImport;
EditorGUI.BeginChangeCheck();
displayImport = GUI.Toggle(rToggle, displayImport, GUIContent.none);
if (EditorGUI.EndChangeCheck() && parentWillImport)
{
layer.import = displayImport;
CollateImportList();
quickSelect.Clear();
selectionCount = 0;
lastSelectedLayer = null;
}
}
using (new EditorGUI.DisabledScope(true))
{
var visStyle = display.isVisible ? styleVisOn : styleVisOff;
GUI.Label(rVis, GUIContent.none, visStyle);
}
rLayer.xMin += indentLevel*indentWidth;
GUIContent layerContent = new GUIContent()
{
image = isGroup ? icnFolder : icnTexture,
text = layer.name
};
if (isGroup)
{
float min, max;
EditorStyles.popup.CalcMinMaxWidth(layerContent, out min, out max);
rLayer.width = min;
display.isOpen = EditorGUI.Foldout(rLayer, display.isOpen, layerContent);
}
else
{
EditorGUI.LabelField(rLayer, layerContent);
if (isAdvancedMode)
{
DrawLayerAdvanced(layer, rPiv, rScale, rReset);
}
}
}
Rect layerRect = GUILayoutUtility.GetLastRect();
layerRect.xMin += 40;
layerRectLookup.Add(layer.indexId, layerRect);
layerEntryYMax = Mathf.Max(layerEntryYMax, layerRect.yMax);
}
private void DrawLayerAdvanced(ImportLayerData layer, Rect rPiv, Rect rScale, Rect rReset)
{
using (var check = new EditorGUI.ChangeCheckScope())
{
layer.Alignment = (SpriteAlignment)EditorGUI.EnumPopup(rPiv, GUIContent.none, layer.Alignment);
layer.ScaleFactor = (ScaleFactor)EditorGUI.EnumPopup(rScale, GUIContent.none, layer.ScaleFactor);
if (check.changed)
{
layer.useDefaults = false;
settingsChanged = true;
}
}
using (new EditorGUI.DisabledGroupScope(layer.useDefaults))
{
if (GUI.Button(rReset, "R", EditorStyles.miniButton))
{
settingsChanged = true;
layer.useDefaults = true;
layer.Pivot = importSettings.DefaultPivot;
layer.Alignment = importSettings.DefaultAlignment;
layer.ScaleFactor = importSettings.ScaleFactor;
}
}
}
private void DrawPsdOperations()
{
bool noFile = importFile == null;
GUIContent fileLabel = noFile ? labelFile : new GUIContent(importFile.name);
GUILayout.Label(fileLabel, EditorStyles.boldLabel, noExpandW);
GUILayout.Label(importPreview, styleLoader, GUILayout.MaxHeight(100f), noExpandW, GUILayout.MinWidth(100));
Rect rLabel = GUILayoutUtility.GetLastRect();
if (noFile)
{
GUI.Label(rLabel, labelLoadBoxEmpty, styleLoadBoxEmpty);
}
Rect rPing = new Rect(rLabel) {yMax = rLabel.yMax - 15};
Rect rSelect = new Rect(rLabel)
{
yMin = rLabel.yMax - 15,
xMin = rLabel.xMax - 50
};
if (GUI.Button(rPing, GUIContent.none, new GUIStyle()))
{
EditorGUIUtility.PingObject(importFile);
}
if (GUI.Button(rSelect, "Select", EditorStyles.miniButton))
{
int controlID = GUIUtility.GetControlID(FocusType.Passive);
EditorGUIUtility.ShowObjectPicker<Texture2D>(importFile, false, string.Empty, controlID);
}
var evt = Event.current;
bool isDrag = evt.type == EventType.DragUpdated || evt.type == EventType.DragPerform;
if (isDrag && rLabel.Contains(evt.mousePosition))
{
DragAndDrop.visualMode = DragAndDropVisualMode.Copy;
if (evt.type == EventType.DragPerform)
{
DragAndDrop.AcceptDrag();
foreach (Object obj in DragAndDrop.objectReferences)
{
Texture2D objTexture = obj as Texture2D;
if (objTexture == null)
continue;
string path = AssetDatabase.GetAssetPath(obj);
if (path.ToLower().EndsWith(".psd") == false)
continue;
OpenFile(obj);
}
}
}
}
private void DrawReconstructor()
{
if (importSettings == null)
return;
EditorGUILayout.LabelField(labelUseConstructor, EditorStyles.boldLabel);
ImportLayerData reconstructLayer = null;
if (lastSelectedLayer != null)
{
reconstructLayer = GetLayerData(lastSelectedLayer);
if (reconstructLayer != null && reconstructLayer.Childs.Count == 0)
{
reconstructLayer = null;
}
}
selectedReconstructor = EditorGUILayout.Popup(labelSelConstructor,
selectedReconstructor,
dropdownReconstruct);
SpriteAlignUI.DrawGUILayout(labelDocAlign, importSettings.DocAlignment,
alignment =>
{
importSettings.DocAlignment = alignment;
if (alignment != SpriteAlignment.Custom)
importSettings.DocPivot = PsdImporter.AlignmentToPivot(alignment);
Repaint();
});
if (importSettings.DocAlignment == SpriteAlignment.Custom)
{
EditorGUI.indentLevel++;
importSettings.DocPivot = EditorGUILayout.Vector2Field(labelDocPivot, importSettings.DocPivot);
EditorGUI.indentLevel--;
}
bool canReconstruct = reconstructLayer != null;
IReconstructor reconstructorInstance = null;
if (canReconstruct)
{
if (selectedReconstructor > -1 && selectedReconstructor < reconstructors.Length)
{
reconstructorInstance = reconstructors[selectedReconstructor];
canReconstruct = reconstructorInstance.CanReconstruct(Selection.activeGameObject);
}
else
{
canReconstruct = false;
}
}
if (canReconstruct)
{
string strButton = string.Format("Build {0} as {1}", reconstructLayer.name, reconstructorInstance.DisplayName);
if (GUILayout.Button(strButton, bigButton))
{
GetLayerData(lastSelectedLayer);
PsdImporter.Reconstruct(importFile, importSettings, reconstructLayer,
importSettings.DocPivot, reconstructorInstance);
}
}
else
{
string helpMessage = "Select a layer group";
if (reconstructLayer != null && reconstructorInstance != null)
helpMessage = reconstructorInstance.HelpMessage;
EditorGUILayout.HelpBox(helpMessage, MessageType.Info);
}
}
private void DrawImportSettings()
{
using (var check = new EditorGUI.ChangeCheckScope())
{
showImportSettings = EditorGUILayout.Foldout(showImportSettings, labelShowImport, styleBoldFoldout);
if (check.changed)
{
Rect window = position;
int expand = 165;
window.yMax += showImportSettings ? expand : -expand;
position = window;
}
}
if (showImportSettings == false)
return;
EditorGUI.indentLevel++;
EditorGUI.BeginDisabledGroup(importFile == null);
EditorGUILayout.Space();
EditorGUI.BeginChangeCheck();
DrawPathPicker();
importSettings.fileNaming = (NamingConvention)EditorGUILayout.EnumPopup(labelFileNaming, importSettings.fileNaming);
if (importSettings.fileNaming != NamingConvention.LayerNameOnly)
{
EditorGUI.indentLevel++;
importSettings.groupMode = (GroupMode) EditorGUILayout.EnumPopup(labelGrpMode, importSettings.groupMode);
EditorGUI.indentLevel--;
}
EditorGUILayout.Space();
importSettings.PackingTag = EditorGUILayout.TextField(labelPackTag, importSettings.PackingTag);
importPPU = EditorGUILayout.FloatField(labelPixelUnit, importPPU);
SpriteAlignUI.DrawGUILayout(labelAlignment, importSettings.DefaultAlignment, newAlign =>
{
importSettings.DefaultAlignment = newAlign;
settingsChanged = true;
ApplyDefaultSettings();
});
if (importSettings.DefaultAlignment == SpriteAlignment.Custom)
{
using (new EditorGUILayout.HorizontalScope())
{
GUILayout.Space(EditorGUIUtility.labelWidth);
importSettings.DefaultPivot = EditorGUILayout.Vector2Field(GUIContent.none, importSettings.DefaultPivot);
}
}
importSettings.ScaleFactor = (ScaleFactor)EditorGUILayout.EnumPopup(labelScale, importSettings.ScaleFactor);
//importSettings.AutoImport = EditorGUILayout.Toggle(labelAutoImport, importSettings.AutoImport);
if (EditorGUI.EndChangeCheck())
{
settingsChanged = true;
importSettings.DefaultPivot.x = Mathf.Clamp01(importSettings.DefaultPivot.x);
importSettings.DefaultPivot.y = Mathf.Clamp01(importSettings.DefaultPivot.y);
ApplyDefaultSettings();
}
using (new EditorGUI.DisabledGroupScope(settingsChanged == false))
{
if (GUILayout.Button("Apply"))
WriteImportSettings();
}
EditorGUI.EndDisabledGroup();
EditorGUI.indentLevel--;
}
private void QuickSelectApplySettings(SpriteAlignment alignment, Vector2 pivot, ScaleFactor scale, bool defaults)
{
if (defaults)
{
alignment = importSettings.DefaultAlignment;
pivot = importSettings.DefaultPivot;
scale = importSettings.ScaleFactor;
}
foreach (int[] layerIdx in quickSelect)
{
var layer = GetLayerData(layerIdx);
if (layer == null || layer.Childs.Count > 0)
continue;
layer.useDefaults = defaults;
layer.Alignment = alignment;
layer.Pivot = pivot;
layer.ScaleFactor = scale;
}
}
private void ApplyDefaultSettings()
{
importSettings.DocRoot.Iterate(
layerCallback: layer =>
{
if (layer.useDefaults)
{
layer.Alignment = importSettings.DefaultAlignment;
layer.Pivot = importSettings.DefaultPivot;
layer.ScaleFactor = importSettings.ScaleFactor;
}
}
);
Repaint();
}
private void DrawPathPicker()
{
using (new GUILayout.HorizontalScope())
{
//EditorGUILayout.PrefixLabel("Import Path");
string displayPath = importSettings.TargetDirectory;
EditorGUI.BeginChangeCheck();
string userPath = EditorGUILayout.DelayedTextField(labelPath, displayPath, GUILayout.ExpandWidth(true));
if (EditorGUI.EndChangeCheck())
{
if (string.IsNullOrEmpty(userPath) == false)
userPath = string.Format("Assets/{0}", userPath);
else
userPath = importPath.Substring(0, importPath.LastIndexOf("/"));
if (AssetDatabase.IsValidFolder(userPath))
importSettings.TargetDirectory = userPath;
}
if (GUILayout.Button(labelPickPath, EditorStyles.miniButtonRight, noExpandW))
{
GUI.FocusControl(null);
string openPath = importSettings.TargetDirectory;
if (string.IsNullOrEmpty(openPath))
openPath = importPath.Substring(0, importPath.LastIndexOf("/"));
openPath = EditorUtility.SaveFolderPanel("Export Path", openPath, "");
int inPath = openPath.IndexOf(Application.dataPath);
if (inPath < 0 || Application.dataPath.Length == openPath.Length)
openPath = string.Empty;
else
openPath = openPath.Substring(Application.dataPath.LastIndexOf("/") + 1);
importSettings.TargetDirectory = openPath;
}
}
}
private void RecursiveQuickSelect(ImportLayerData layer, bool inSelection)
{
SetQuickSelect(layer.indexId, inSelection);
layer.Iterate(
childLayer =>
{
if (layer.Childs == null)
return;
if (childLayer.import)
SetQuickSelect(childLayer.indexId, inSelection);
}
);
GetSelectCount();
}
private void SetQuickSelect(int[] layerIdx, bool inSelection)
{
bool layerInSelection = quickSelect.Contains(layerIdx);
if (inSelection)
{
if (layerInSelection == false)
quickSelect.Add(layerIdx);
}
else
{
if (layerInSelection)
quickSelect.Remove(layerIdx);
}
}
private void AddQuickSelect()
{
foreach (int[] layerIdx in quickSelect)
{
var setLayer = GetLayerData(layerIdx);
if (setLayer == null)
continue;
setLayer.import = true;
}
quickSelect.Clear();
}
private bool ParentWillImport(int[] layerIdx)
{
bool willImport = true;
ImportLayerData currentLayer = importSettings.DocRoot;
for (int i = 0; i < layerIdx.Length - 1; i++)
{
int idx = layerIdx[i];
currentLayer = currentLayer.Childs[idx];
willImport &= currentLayer.import;
if (willImport == false)
break;
}
return willImport;
}
private void CollateImportList()
{
importLayersList.Clear();
importSettings.DocRoot.Iterate(
layerCallback: layer =>
{
if (layer.import && layer.Childs.Count == 0)
importLayersList.Add(layer.indexId);
},
canEnterGroup: layer => layer.import
);
}
private void GetSelectCount()
{
selectionCount = 0;
foreach (int[] layerIdx in quickSelect)
{
var layer = GetLayerData(layerIdx);
if (layer == null)
continue;
if (layer.Childs.Count == 0)
selectionCount++;
}
}
private DisplayLayerData GetDisplayData(int[] layerIdx)
{
if (importDisplay == null || layerIdx == null)
return null;
DisplayLayerData currentLayer = importDisplay;
foreach (int idx in layerIdx)
{
if (idx < 0 || idx >= currentLayer.Childs.Count)
return null;
currentLayer = currentLayer.Childs[idx];
}
return currentLayer;
}
private ImportLayerData GetLayerData(int[] layerIdx)
{
if (importSettings == null || layerIdx == null)
return null;
return importSettings.GetLayerData(layerIdx);
}
private void WriteImportSettings()
{
// Read the texture import settings of the asset file
TextureImporter textureImporter = (TextureImporter)AssetImporter.GetAtPath(importPath);
TextureImporterSettings settings = new TextureImporterSettings();
textureImporter.ReadTextureSettings(settings);
settings.spritePixelsPerUnit = importPPU;
textureImporter.SetTextureSettings(settings);
fsData data;
if (serializer.TrySerialize(typeImportUserData, importSettings, out data)
.AssertSuccessWithoutWarnings()
.Succeeded)
{
textureImporter.userData = fsJsonPrinter.CompressedJson(data);
}
EditorUtility.SetDirty(importFile);
AssetDatabase.WriteImportSettingsIfDirty(importPath);
AssetDatabase.ImportAsset(importPath, ImportAssetOptions.ForceUpdate);
settingsChanged = false;
CollateImportList();
}
}
} | 30.04754 | 134 | 0.675715 | [
"MIT"
] | Zionch/Psd2UnityImporter | Editor/PsdImportWindow.cs | 36,029 | C# |
/*
* Copyright (c) 2018, Firely (info@fire.ly) and contributors
* See the file CONTRIBUTORS for details.
*
* This file is licensed under the BSD 3-Clause license
* available at https://github.com/FirelyTeam/fhir-net-api/blob/master/LICENSE
*/
using Hl7.Fhir.ElementModel;
using Hl7.Fhir.Specification;
using Hl7.Fhir.Utility;
using System;
using System.Linq;
using System.Xml;
using System.Xml.Linq;
namespace Hl7.Fhir.Serialization
{
internal class FhirXmlBuilder : IExceptionSource
{
internal FhirXmlBuilder(FhirXmlSerializationSettings settings = null)
{
_settings = settings?.Clone() ?? new FhirXmlSerializationSettings();
}
private FhirXmlSerializationSettings _settings;
private bool _roundtripMode;
public ExceptionNotificationHandler ExceptionHandler { get; set; }
public XDocument Build(ITypedElement source) =>
buildInternal(source);
public XDocument Build(ISourceNode source)
{
bool hasXmlSource = source.Annotation<FhirXmlNode>() != null;
// We can only work with an untyped source if we're doing a roundtrip,
// so we have all serialization details available.
if (hasXmlSource)
{
_roundtripMode = true;
#pragma warning disable CS0618 // Type or member is obsolete
return buildInternal(source.ToTypedElement());
#pragma warning restore CS0618 // Type or member is obsolete
}
else
{
throw Error.NotSupported($"The {nameof(FhirXmlBuilder)} will only work correctly on an untyped " +
$"source if the source is a {nameof(FhirXmlNode)}.");
}
}
public XDocument buildInternal(ITypedElement source)
{
var dest = new XDocument();
if (source is IExceptionSource)
{
using (source.Catch((o, a) => ExceptionHandler.NotifyOrThrow(o, a)))
{
build(source, dest);
}
}
else
build(source, dest);
return dest;
}
internal bool MustSerializeMember(ITypedElement source, out IElementDefinitionSummary info)
{
info = source.Definition;
if (info == null && !_roundtripMode)
{
var message = $"Element '{source.Location}' is missing type information.";
if (_settings.IgnoreUnknownElements)
{
ExceptionHandler.NotifyOrThrow(source, ExceptionNotification.Warning(
new MissingTypeInformationException(message)));
}
else
{
ExceptionHandler.NotifyOrThrow(source, ExceptionNotification.Error(
new MissingTypeInformationException(message)));
}
return false;
}
return true;
}
private void build(ITypedElement source, XContainer parent)
{
var xmlDetails = source.GetXmlSerializationDetails();
var sourceComments = (source as IAnnotated)?.Annotation<SourceComments>();
if (!MustSerializeMember(source, out var serializationInfo)) return;
bool hasTypeInfo = serializationInfo != null;
var value = source.Value != null ?
PrimitiveTypeConverter.ConvertTo<string>(source.Value) : null;
if(_settings.TrimWhitespaces)
{
value = value?.Trim();
}
// xhtml children require special treament:
// - They don't use an xml "value" attribute to represent the value, instead their Value is inserted verbatim into the parent
// - They cannot have child nodes - the "Value" on the node contains all children as raw xml text
var isXhtml = source.InstanceType == "xhtml" ||
serializationInfo?.Representation == XmlRepresentation.XHtml ||
xmlDetails?.Namespace?.GetName("div") == XmlNs.XHTMLDIV;
if (isXhtml && !String.IsNullOrWhiteSpace(value))
{
// The value *should* be valid xhtml - however if people just provide a plain
// string, lets add a <div> around it.
if (!value.TrimStart().StartsWith("<div"))
value = $"<div xmlns='http://www.w3.org/1999/xhtml'>{value}</div>";
var sanitized = SerializationUtil.SanitizeXml(value);
XElement xe = XElement.Parse(sanitized);
// The div should be in the XHTMLNS namespace, correct if it
// is not the case.
xe.Name = XmlNs.XHTMLNS + xe.Name.LocalName;
parent.Add(xe);
//using (var divWriter = parent.CreateWriter())
//using (var nodeReader = SerializationUtil.XmlReaderFromXmlText(value))
// divWriter.WriteNode(nodeReader, false);
return;
}
var usesAttribute = serializationInfo?.Representation == XmlRepresentation.XmlAttr ||
(xmlDetails?.NodeType == XmlNodeType.Attribute);
var ns = serializationInfo?.NonDefaultNamespace ??
xmlDetails?.Namespace.NamespaceName ??
(usesAttribute ? "" : XmlNs.FHIR);
bool atRoot = parent is XDocument;
var localName = serializationInfo?.IsChoiceElement == true ?
source.Name + source.InstanceType.Capitalize() : source.Name;
// If the node is represented by an attribute (e.g. an "id" child), write
// an attribute with the child's name + the child's Value into the parent
if (usesAttribute && !String.IsNullOrWhiteSpace(value) && !atRoot)
{
parent.Add(new XAttribute(XName.Get(localName, ns), value));
return;
}
// else: fall through - value will be serialized as an element
var me = new XElement(XName.Get(localName, ns));
if (xmlDetails?.SchemaLocation != null)
me.Add(new XAttribute(XmlNs.XSCHEMALOCATION, xmlDetails.SchemaLocation));
// If the node has a value, add the standard FHIR value attribute
if (value != null)
me.Add(new XAttribute("value", value));
// If this needs to be serialized as a contained resource, do so
var containedResourceType = atRoot ? null :
(serializationInfo?.IsResource == true ?
source.InstanceType :
source.Annotation<IResourceTypeSupplier>()?.ResourceType);
XElement containedResource = null;
if (containedResourceType != null)
containedResource = new XElement(XName.Get(containedResourceType, ns));
var childParent = containedResource ?? me;
// Now, do the same for the children
// xml requires a certain order, so let's make sure we serialize in the right order
var orderedChildren = source.Children().OrderBy(c => c.Definition?.Order ?? 0);
foreach (var child in orderedChildren)
build(child, childParent);
if (serializationInfo?.Representation == XmlRepresentation.XmlText || xmlDetails?.NodeText != null)
{
childParent.Add(new XText(value ?? xmlDetails.NodeText));
}
if (sourceComments?.ClosingComments != null)
writeComments(sourceComments.ClosingComments, me);
// Only really add this contained resource to me when it has contents
if (containedResource != null && (containedResource.HasAttributes || containedResource.HasElements))
me.Add(containedResource);
// Only add myself to my parent if I have content, or I am the root
if (value != null || me.HasElements || atRoot)
{
if (sourceComments?.CommentsBefore != null)
writeComments(sourceComments.CommentsBefore, parent);
parent.Add(me);
}
if (atRoot && parent.Elements().Any() && sourceComments?.DocumentEndComments != null)
writeComments(sourceComments.DocumentEndComments, parent);
}
private void writeComments(string[] comments, XContainer parent)
{
if (comments?.Any() == true)
{
foreach (var comment in comments)
parent.Add(new XComment(comment));
}
}
}
}
| 39.986486 | 137 | 0.570688 | [
"BSD-3-Clause"
] | GinoCanessa/fhir-net-common | src/Hl7.Fhir.Serialization/FhirXmlBuilder.cs | 8,879 | C# |
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using RecipeApp.Shared.Models;
namespace RecipeApp.Repository.Interfaces
{
public interface IRecipeRepository
{
Task<IEnumerable<Recipe>> GetRecipesAsync();
/// <summary>
/// Adds a new recipe to the database
/// </summary>
/// <param name="recipe">The recipe to add</param>
/// <param name="cancellationToken">A token to cancel the action</param>
Task CreateRecipeAsync(Recipe recipe, CancellationToken cancellationToken);
}
}
| 28.181818 | 83 | 0.690323 | [
"MIT"
] | godzillar/RecipeApp | RecipeApp.Repository/Interfaces/IRecipeRepository.cs | 622 | C# |
//
// Copyright (c) 2017 The nanoFramework project contributors
// Portions Copyright (c) Microsoft Corporation. All rights reserved.
// See LICENSE file in the project root for full license information.
//
namespace nanoFramework.Tools.Debugger
{
public class RuntimeValue_Internal : RuntimeValue
{
protected internal RuntimeValue_Internal(Engine eng, WireProtocol.Commands.Debugging_Value handle) : base(eng, handle)
{
}
public override bool IsReference { get { return false; } }
public override bool IsNull { get { return false; } }
public override bool IsPrimitive { get { return false; } }
public override bool IsValueType { get { return false; } }
public override bool IsArray { get { return false; } }
public override bool IsReflection { get { return false; } }
}
}
| 37.434783 | 126 | 0.684088 | [
"Apache-2.0"
] | CSAEngineeringAG/2g-nf-debugger | source/nanoFramework.Tools.DebugLibrary.Shared/Runtime/RuntimeValue_Internal.cs | 863 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("SilverlightClassLibrary1")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("SilverlightClassLibrary1")]
[assembly: AssemblyCopyright("Copyright © 2012")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("ae5e2044-a06c-4c5f-968a-bbfa3f494e52")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Revision and Build Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("1.0")]
[assembly: AssemblyFileVersion("1.0")]
[assembly: AssemblyInformationalVersion("1.0-SNAPSHOT")]
| 38.648649 | 84 | 0.756643 | [
"Apache-2.0"
] | NPanday/npanday | dotnet/assemblies/NPanday.ProjectImporter/Engine/src/test/resource/SilverlightApplication1/SilverlightClassLibrary1/Properties/AssemblyInfo.cs | 1,433 | C# |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Reflection;
using System.Threading.Tasks;
using Microsoft.OData.Client;
using Microsoft.OData.Core;
namespace Microsoft.OData.ProxyExtensions
{
public partial class DataServiceContextWrapper : DataServiceContext
{
private object _syncLock = new object();
private string _accessToken;
private readonly Func<Task<string>> _accessTokenGetter;
private readonly HashSet<EntityBase> _modifiedEntities = new HashSet<EntityBase>();
public void UpdateObject(EntityBase entity)
{
if (GetEntityDescriptor(entity) != null)
{
_modifiedEntities.Add(entity);
base.UpdateObject(entity);
}
}
private async Task SetToken()
{
var token = await _accessTokenGetter();
lock (_syncLock)
{
_accessToken = token;
}
}
public DataServiceContextWrapper(Uri serviceRoot, ODataProtocolVersion maxProtocolVersion, Func<Task<string>> accessTokenGetter)
: base(serviceRoot, maxProtocolVersion)
{
_accessTokenGetter = accessTokenGetter;
IgnoreMissingProperties = true;
BuildingRequest += (sender, args) => args.Headers.Add("Authorization", "Bearer " + _accessToken);
Configurations.RequestPipeline.OnEntryStarting(args =>
{
var entity = (EntityBase)args.Entity;
if ((!entity.ChangedProperties.IsValueCreated || entity.ChangedProperties.Value.Count == 0))
{
args.Entry.Properties = new ODataProperty[0];
return;
}
if (!_modifiedEntities.Contains(entity))
{
_modifiedEntities.Add(entity);
}
IEnumerable<ODataProperty> properties = new ODataProperty[0];
if (entity.ChangedProperties.IsValueCreated)
{
properties = properties.Concat(args.Entry.Properties.Where(i => entity.ChangedProperties.Value.Contains(i.Name)));
}
args.Entry.Properties = properties;
});
Configurations.ResponsePipeline.OnEntityMaterialized(args =>
{
var entity = (EntityBase)args.Entity;
entity.ResetChanges();
});
OnCreated();
}
partial void OnCreated();
public Type DefaultResolveTypeInternal(string typeName, string fullNamespace, string languageDependentNamespace)
{
return DefaultResolveType(typeName, fullNamespace, languageDependentNamespace);
}
public string DefaultResolveNameInternal(Type clientType, string fullNamespace, string languageDependentNamespace)
{
if (clientType.Namespace.Equals(languageDependentNamespace, StringComparison.Ordinal))
{
return string.Concat(fullNamespace, ".", clientType.Name);
}
return string.Empty;
}
public async Task<TInterface> ExecuteSingleAsync<TSource, TInterface>(DataServiceQuery<TSource> inner)
{
try
{
await SetToken();
return await Task.Factory.FromAsync(
inner.BeginExecute,
i => inner.EndExecute(i).Cast<TInterface>().SingleOrDefault(),
TaskCreationOptions.None);
}
catch (Exception ex)
{
var newException = ProcessException(ex);
if (newException != null)
{
throw newException;
}
throw;
}
}
public async Task<IBatchElementResult[]> ExecuteBatchAsync(params IReadOnlyQueryableSetBase[] queries)
{
try
{
var requests = (from i in queries select (DataServiceRequest)i.Query).ToArray();
await SetToken();
var responses = await Task.Factory.FromAsync<DataServiceRequest[], DataServiceResponse>(
(q, callback, state) => BeginExecuteBatch(callback, state, q), // need to reorder parameters
EndExecuteBatch,
requests,
null);
var retVal = new IBatchElementResult[queries.Length];
var index = 0;
foreach (var response in responses)
{
Type tConcrete = ((IConcreteTypeAccessor)queries[index]).ConcreteType;
Type tInterface = ((IConcreteTypeAccessor)queries[index]).ElementType;
var pcType = typeof(PagedCollection<,>).MakeGenericType(tInterface, tConcrete);
var pcTypeInfo = pcType.GetTypeInfo();
var pcCreator = pcTypeInfo.GetDeclaredMethod("Create");
// Handle an error response.
// from http://msdn.microsoft.com/en-us/library/dd744838(v=vs.110).aspx
if (response.StatusCode > 299 || response.StatusCode < 200)
{
retVal[index] = new BatchElementResult(ProcessException(response.Error) ?? response.Error);
}
else
{
retVal[index] = new BatchElementResult((IPagedCollection)pcCreator.Invoke(null, new object[] { this, response }));
}
index++;
}
return retVal;
}
catch (Exception ex)
{
var newException = ProcessException(ex);
if (newException != null)
{
throw newException;
}
throw;
}
}
public async Task<Stream> GetStreamAsync(Uri requestUriTmp, IDictionary<string, string> headers)
{
using (var client = new HttpClient())
{
using (var request = new HttpRequestMessage(HttpMethod.Get, requestUriTmp))
{
request.Headers.Add("Authorization", "Bearer " + await _accessTokenGetter());
request.Headers.Add("Accept", "*/*");
request.Headers.Add("Accept-Charset", "UTF-8");
if (headers != null)
{
foreach (var header in headers)
{
request.Headers.Add(header.Key, header.Value);
}
}
// Do not dispose the response. If disposed, it will also dispose the
// stream we are returning
var response = await client.SendAsync(request);
if (response.IsSuccessStatusCode)
{
return await response.Content.ReadAsStreamAsync();
}
var newException = await ProcessErrorAsync(response);
if (newException != null)
{
throw newException;
}
response.EnsureSuccessStatusCode();
// unreachable
return null;
}
}
}
public async Task<DataServiceStreamResponse> GetReadStreamAsync(EntityBase entity, string streamName, string contentType)
{
try
{
if (!string.IsNullOrEmpty(streamName))
{
await SetToken();
var resp = await Task.Factory.FromAsync<object, string, DataServiceRequestArgs, DataServiceStreamResponse>(
BeginGetReadStream,
EndGetReadStream,
entity,
streamName,
new DataServiceRequestArgs { ContentType = contentType /*, Headers = {todo}*/ },
null);
return resp;
}
else
{
var resp = await Task.Factory.FromAsync<object, DataServiceRequestArgs, DataServiceStreamResponse>(
BeginGetReadStream,
EndGetReadStream,
entity,
new DataServiceRequestArgs { ContentType = contentType /*, Headers = {todo}*/ },
null);
return resp;
}
}
catch (Exception ex)
{
var newException = ProcessException(ex);
if (newException != null)
{
throw newException;
}
throw;
}
}
public async Task<IPagedCollection<TInterface>> ExecuteAsync<TSource, TInterface>(DataServiceQuery<TSource> inner) where TSource : TInterface
{
try
{
await SetToken();
return await Task.Factory.FromAsync(
inner.BeginExecute,
new Func<IAsyncResult, IPagedCollection<TInterface>>(
r =>
new PagedCollection<TInterface, TSource>(
this,
(QueryOperationResponse<TSource>) inner.EndExecute(r))),
TaskCreationOptions.None);
}
catch (Exception ex)
{
var newException = ProcessException(ex);
if (newException != null)
{
throw newException;
}
throw;
}
}
public new Task<IEnumerable<T>> ExecuteAsync<T>(Uri uri, string httpMethod, bool singleResult, params OperationParameter[] operationParameters)
{
return ExecuteAsyncInternal<T>(uri, httpMethod, singleResult, null, operationParameters);
}
public Task<IEnumerable<T>> ExecuteAsync<T>(Uri uri, string httpMethod, bool singleResult, Stream stream, params OperationParameter[] operationParameters)
{
return ExecuteAsyncInternal<T>(uri, httpMethod, singleResult, stream ?? new MemoryStream(), operationParameters);
}
public async Task<IEnumerable<T>> ExecuteAsyncInternal<T>(Uri uri, string httpMethod, bool singleResult, Stream stream, params OperationParameter[] operationParameters)
{
try
{
if (stream != null)
{
Configurations.RequestPipeline.OnMessageCreating = args =>
{
args.Headers.Remove("Content-Length");
var msg = new HttpWebRequestMessage(args);
Task.Factory.FromAsync<Stream>(msg.BeginGetRequestStream, msg.EndGetRequestStream, null)
.ContinueWith(s => stream.CopyTo(s.Result))
.Wait();
return msg;
};
}
return await Task.Factory.FromAsync<IEnumerable<T>>(
(callback, state) =>
BeginExecute<T>(uri, callback, state, httpMethod, singleResult, operationParameters),
EndExecute<T>,
TaskCreationOptions.None);
}
catch (Exception ex)
{
var newException = ProcessException(ex);
if (newException != null)
{
throw newException;
}
throw;
}
finally
{
if (stream != null)
{
Configurations.RequestPipeline.OnMessageCreating = null;
}
}
}
public new Task ExecuteAsync(Uri uri, string httpMethod, params OperationParameter[] operationParameters)
{
return ExecuteAsync(uri, httpMethod, null, operationParameters);
}
public async Task ExecuteAsync(Uri uri, string httpMethod, Stream stream, params OperationParameter[] operationParameters)
{
try
{
if (stream != null)
{
Configurations.RequestPipeline.OnMessageCreating = args =>
{
args.Headers.Remove("Content-Length");
var msg = new HttpWebRequestMessage(args);
Task.Factory.FromAsync<Stream>(msg.BeginGetRequestStream, msg.EndGetRequestStream, null)
.ContinueWith(s => stream.CopyTo(s.Result))
.Wait();
return msg;
};
}
await Task.Factory.FromAsync(
(callback, state) => BeginExecute(uri, callback, state, httpMethod, operationParameters),
new Action<IAsyncResult>(i => EndExecute(i)),
TaskCreationOptions.None);
}
catch (Exception ex)
{
var newException = ProcessException(ex);
if (newException != null)
{
throw newException;
}
throw;
}
finally
{
if (stream != null)
{
Configurations.RequestPipeline.OnMessageCreating = null;
}
}
}
public async Task<QueryOperationResponse<TSource>> ExecuteAsync<TSource, TInterface>(DataServiceQueryContinuation<TSource> token)
{
try
{
await SetToken();
return await Task.Factory.FromAsync(
(callback, state) => BeginExecute(token, callback, state),
i => (QueryOperationResponse<TSource>)EndExecute<TSource>(i),
TaskCreationOptions.None);
}
catch (Exception ex)
{
var newException = ProcessException(ex);
if (newException != null)
{
throw newException;
}
throw;
}
}
public async new Task<DataServiceResponse> SaveChangesAsync(SaveChangesOptions options)
{
try
{
await SetToken();
var result = await Task.Factory.FromAsync(
BeginSaveChanges,
new Func<IAsyncResult, DataServiceResponse>(EndSaveChanges),
options,
null,
TaskCreationOptions.None);
foreach (var i in _modifiedEntities)
{
i.ResetChanges();
}
_modifiedEntities.Clear();
return result;
}
catch (Exception ex)
{
var newException = ProcessException(ex);
if (newException != null)
{
throw newException;
}
throw;
}
}
public new Task<DataServiceResponse> SaveChangesAsync()
{
return SaveChangesAsync(SaveChangesOptions.None);
}
#if NOTYET
public async Task<IPagedCollection<TInterface>> LoadPropertyAsync<TSource, TInterface>(string path, object entity) where TSource : TInterface
{
try
{
await SetToken();
return await Task.Factory.FromAsync(
(callback, state) => BeginLoadProperty(entity, path, callback, state),
new Func<IAsyncResult, IPagedCollection<TInterface>>(
r => new PagedCollection<TInterface, TSource>(this, (QueryOperationResponse<TSource>) EndLoadProperty(r))),
TaskCreationOptions.None);
}
catch (Exception ex)
{
var newException = ProcessException(ex);
if (newException != null)
{
throw newException;
}
throw;
}
}
#endif
public static Exception ProcessException(Exception ex)
{
var dataServiceRequestException = ex as DataServiceRequestException;
if (dataServiceRequestException != null)
{
var response = dataServiceRequestException.Response.FirstOrDefault();
if (response != null)
{
return ProcessError(dataServiceRequestException, dataServiceRequestException.InnerException as DataServiceClientException, response.Headers);
}
}
var dataServiceQueryException = ex as DataServiceQueryException;
if (dataServiceQueryException != null)
{
return ProcessError(dataServiceQueryException, dataServiceQueryException.InnerException as DataServiceClientException,
dataServiceQueryException.Response.Headers);
}
var dataServiceClientException = ex as DataServiceClientException;
if (dataServiceClientException != null)
{
return ProcessError(dataServiceClientException, dataServiceClientException,
new Dictionary<string, string>
{
{"Content-Type", dataServiceClientException.Message.StartsWith("<") ? "application/xml" : "application/json"}
});
}
return null;
}
private static Exception ProcessError(Exception outer, DataServiceClientException inner, IDictionary<string, string> headers)
{
if (inner == null)
{
return null;
}
using (var writer = WriteToStream(inner.Message))
{
var httpMessage = new HttpWebResponseMessage(
headers,
inner.StatusCode,
() => writer.BaseStream);
var reader = new ODataMessageReader(httpMessage);
try
{
var error = reader.ReadError();
return new ODataErrorException(error.Message, outer, error);
}
catch
{
}
}
return null;
}
private static async Task<Exception> ProcessErrorAsync(HttpResponseMessage response)
{
if (response.Content == null)
{
return null;
}
if (response.Content.Headers.ContentType == null)
{
return new HttpRequestException(await response.Content.ReadAsStringAsync());
}
using (var stream = await response.Content.ReadAsStreamAsync())
{
var headers = response.Content.Headers.ToDictionary(i => i.Key, i => i.Value.FirstOrDefault());
var httpMessage = new HttpWebResponseMessage(
headers,
(int)response.StatusCode,
() => stream);
var reader = new ODataMessageReader(httpMessage);
try
{
var error = reader.ReadError();
return new ODataErrorException(error.Message, null, error);
}
catch
{
}
}
return null;
}
private static StreamWriter WriteToStream(string contents)
{
var stream = new MemoryStream();
var writer = new StreamWriter(stream);
writer.Write(contents);
writer.Flush();
stream.Seek(0, SeekOrigin.Begin);
return writer;
}
}
}
| 34.602349 | 176 | 0.503855 | [
"MIT"
] | OfficeDev/Vipr | src/ProxyExtensions/Microsoft.OData.ProxyExtensions/DataServiceContextWrapper.cs | 20,623 | C# |
using FastMember;
using GameEstate.Red.Formats.Red.CR2W;
using GameEstate.Red.Formats.Red.Types.Arrays;
using System.IO;
using System.Runtime.Serialization;
using static GameEstate.Red.Formats.Red.Types.Enums;
namespace GameEstate.Red.Formats.Red.Types
{
[DataContract(Namespace = ""), REDMeta]
public partial class CParticleEmitter : IParticleModule
{
[Ordinal(1), RED("modules", 2, 0)] public CArray<CPtr<IParticleModule>> Modules { get; set; }
[Ordinal(2), RED("positionX")] public CInt32 PositionX { get; set; }
[Ordinal(3), RED("positionY")] public CInt32 PositionY { get; set; }
[Ordinal(4), RED("material")] public CHandle<IMaterial> Material { get; set; }
[Ordinal(5), RED("maxParticles")] public CUInt32 MaxParticles { get; set; }
[Ordinal(6), RED("emitterLoops")] public CInt32 EmitterLoops { get; set; }
[Ordinal(7), RED("particleDrawer")] public CPtr<IParticleDrawer> ParticleDrawer { get; set; }
[Ordinal(8), RED("decalSpawner")] public CPtr<CDecalSpawner> DecalSpawner { get; set; }
[Ordinal(9), RED("collisionDecalSpawner")] public CPtr<CDecalSpawner> CollisionDecalSpawner { get; set; }
[Ordinal(10), RED("motionDecalSpawner")] public CPtr<CDecalSpawner> MotionDecalSpawner { get; set; }
[Ordinal(11), RED("useSubFrameEmission")] public CBool UseSubFrameEmission { get; set; }
[Ordinal(12), RED("keepSimulationLocal")] public CBool KeepSimulationLocal { get; set; }
[Ordinal(13), RED("envColorGroup")] public CEnum<EEnvColorGroup> EnvColorGroup { get; set; }
[Ordinal(14), RED("windInfluence")] public CFloat WindInfluence { get; set; }
[Ordinal(15), RED("useOnlyWindInfluence")] public CBool UseOnlyWindInfluence { get; set; }
[Ordinal(16), RED("modifierSetMask")] public CUInt32 ModifierSetMask { get; set; }
[Ordinal(17), RED("numModifiers")] public CUInt32 NumModifiers { get; set; }
[Ordinal(18), RED("initializerSetMask")] public CUInt32 InitializerSetMask { get; set; }
[Ordinal(19), RED("numInitializers")] public CUInt32 NumInitializers { get; set; }
[Ordinal(20), RED("seeds", 2, 0)] public CArray<SSeedKeyValue> Seeds { get; set; }
[Ordinal(21), RED("internalPriority")] public CUInt8 InternalPriority { get; set; }
[Ordinal(22), RED("lods", 2, 0)] public CArray<SParticleEmitterLODLevel> Lods { get; set; }
public CParticleEmitter(CR2WFile cr2w, CVariable parent, string name) : base(cr2w, parent, name) { }
public static new CVariable Create(CR2WFile cr2w, CVariable parent, string name) => new CParticleEmitter(cr2w, parent, name);
public override void Read(BinaryReader file, uint size) => base.Read(file, size);
public override void Write(BinaryWriter file) => base.Write(file);
}
} | 65.590909 | 134 | 0.673943 | [
"MIT"
] | bclnet/GameEstate | src/Estates/Red/GameEstate.Red.Format/Red/W3/Partial/CParticleEmitter.cs | 2,886 | C# |
using System;
using System.Collections.Generic;
using GeoAPI.Geometries;
namespace NetTopologySuite.Geometries.Implementation
{
/// <summary>
/// A coordinate sequence that follows the dotspatial shape range
/// </summary>
#if HAS_SYSTEM_SERIALIZABLEATTRIBUTE
[Serializable]
#endif
public class DotSpatialAffineCoordinateSequence :
ICoordinateSequence
//IMeasuredCoordinateSequence
{
private readonly double[] _xy;
private readonly double[] _z;
private readonly double[] _m;
private readonly Ordinates _ordinates;
#if HAS_SYSTEM_SERIALIZABLEATTRIBUTE
[NonSerialized]
#endif
private WeakReference _coordinateArrayRef;
/// <summary>
/// Creates an instance of this class
/// </summary>
/// <param name="coordinates">The coordinates</param>
/// <param name="ordinates"></param>
public DotSpatialAffineCoordinateSequence(IList<Coordinate> coordinates, Ordinates ordinates)
{
// Set ordinates
_ordinates = ordinates;
if (coordinates == null)
{
_xy = new double[0];
return;
}
_xy = new double[2 * coordinates.Count];
int j = 0;
for (int i = 0; i < coordinates.Count; i++)
{
XY[j++] = coordinates[i].X;
XY[j++] = coordinates[i].Y;
}
if ((ordinates & Ordinates.Z) == Ordinates.Z)
{
_z = new double[coordinates.Count];
for (int i = 0; i < coordinates.Count; i++)
Z[i] = coordinates[i].Z;
}
if ((ordinates & Ordinates.M) == Ordinates.M)
{
_m = new double[coordinates.Count];
for (int i = 0; i < coordinates.Count; i++)
M[i] = Coordinate.NullOrdinate;
}
_ordinates = ordinates;
}
/// <summary>
/// Constructs a sequence of a given size, populated with new Coordinates.
/// </summary>
/// <param name="size">The size of the sequence to create.</param>
/// <param name="dimension">The number of dimensions.</param>
public DotSpatialAffineCoordinateSequence(int size, int dimension)
{
_xy = new double[2 * size];
if (dimension <= 2) return;
_z = new double[size];
for (int i = 0; i < size; i++)
_z[i] = double.NaN;
_m = new double[size];
for (int i = 0; i < size; i++)
_m[i] = double.NaN;
}
/// <summary>
/// Constructs a sequence of a given size, populated with new Coordinates.
/// </summary>
/// <param name="size">The size of the sequence to create.</param>
/// <param name="ordinates">The kind of ordinates.</param>
public DotSpatialAffineCoordinateSequence(int size, Ordinates ordinates)
{
_xy = new double[2 * size];
_ordinates = ordinates;
if ((ordinates & Ordinates.Z) == Ordinates.Z)
{
_z = new double[size];
for (int i = 0; i < size; i++)
_z[i] = Coordinate.NullOrdinate;
}
if ((ordinates & Ordinates.M) == Ordinates.M)
{
_m = new double[size];
for (int i = 0; i < size; i++)
_m[i] = Coordinate.NullOrdinate;
}
}
/// <summary>
/// Creates a sequence based on the given coordinate sequence.
/// </summary>
/// <param name="coordSeq">The coordinate sequence.</param>
/// <param name="ordinates">The ordinates to copy</param>
public DotSpatialAffineCoordinateSequence(ICoordinateSequence coordSeq, Ordinates ordinates)
{
int count = coordSeq.Count;
_xy = new double[2 * count];
if ((ordinates & Ordinates.Z) == Ordinates.Z)
_z = new double[count];
if ((ordinates & Ordinates.M) == Ordinates.M)
_m = new double[count];
var dsCoordSeq = coordSeq as DotSpatialAffineCoordinateSequence;
if (dsCoordSeq != null)
{
double[] nullOrdinateArray = null;
Buffer.BlockCopy(dsCoordSeq._xy, 0, _xy, 0, 16 * count);
if ((ordinates & Ordinates.Z) == Ordinates.Z)
{
double[] copyOrdinateArray = dsCoordSeq.Z != null
? dsCoordSeq.Z
: nullOrdinateArray = NullOrdinateArray(count);
Buffer.BlockCopy(copyOrdinateArray, 0, _z, 0, 8 * count);
}
if ((ordinates & Ordinates.M) == Ordinates.M)
{
double[] copyOrdinateArray = dsCoordSeq.M != null
? dsCoordSeq.M
: nullOrdinateArray ?? NullOrdinateArray(count);
Buffer.BlockCopy(copyOrdinateArray, 0, _m, 0, 8*count);
}
_ordinates = ordinates;
return;
}
int j = 0;
for (int i = 0; i < coordSeq.Count; i++)
{
_xy[j++] = coordSeq.GetX(i);
_xy[j++] = coordSeq.GetY(i);
if (_z != null) _z[i] = coordSeq.GetOrdinate(i, Ordinate.Z);
if (_m != null) _m[i] = coordSeq.GetOrdinate(i, Ordinate.M);
}
}
private static double[] NullOrdinateArray(int size)
{
double[] res = new double[size];
for (int i = 0; i < size; i++)
res[i] = Coordinate.NullOrdinate;
return res;
}
/// <summary>
///
/// </summary>
/// <param name="xy"></param>
/// <param name="z"></param>
public DotSpatialAffineCoordinateSequence(double[] xy, double[] z)
{
_xy = xy;
_z = z;
_ordinates = Ordinates.XY;
if (_z != null) _ordinates |= Ordinates.Z;
}
/// <summary>
///
/// </summary>
/// <param name="xy"></param>
/// <param name="z"></param>
/// <param name="m"></param>
public DotSpatialAffineCoordinateSequence(double[] xy, double[] z, double[] m)
: this(xy, z)
{
_m = m;
_ordinates = Ordinates.XYZM;
}
[Obsolete]
public object Clone()
{
return Copy();
}
/// <inheritdoc cref="ICoordinateSequence.Copy"/>
public ICoordinateSequence Copy()
{
return new DotSpatialAffineCoordinateSequence(this, Ordinates);
}
public Coordinate GetCoordinate(int i)
{
int j = 2 * i;
return _z == null
? new Coordinate(_xy[j++], _xy[j])
: new Coordinate(_xy[j++], _xy[j], _z[i]);
}
public Coordinate GetCoordinateCopy(int i)
{
return GetCoordinate(i);
}
public void GetCoordinate(int index, Coordinate coord)
{
coord.X = _xy[2 * index];
coord.Y = _xy[2 * index + 1];
coord.Z = _z != null ? _z[index] : Coordinate.NullOrdinate;
}
public double GetX(int index)
{
return _xy[2 * index];
}
public double GetY(int index)
{
return _xy[2 * index + 1];
}
public double GetOrdinate(int index, Ordinate ordinate)
{
switch (ordinate)
{
case Ordinate.X:
return _xy[index * 2];
case Ordinate.Y:
return _xy[index * 2 + 1];
case Ordinate.Z:
return _z != null ? _z[index] : Coordinate.NullOrdinate;
case Ordinate.M:
return _m != null ? _m[index] : Coordinate.NullOrdinate;
default:
throw new NotSupportedException();
}
}
public void SetOrdinate(int index, Ordinate ordinate, double value)
{
switch (ordinate)
{
case Ordinate.X:
_xy[index * 2] = value;
break;
case Ordinate.Y:
_xy[index * 2 + 1] = value;
break;
case Ordinate.Z:
if (_z != null) _z[index] = value;
break;
case Ordinate.M:
if (_m != null) _m[index] = value;
break;
default:
throw new NotSupportedException();
}
_coordinateArrayRef = null;
}
/// <summary>
///
/// </summary>
/// <returns></returns>
private Coordinate[] GetCachedCoords()
{
var localCoordinateArrayRef = _coordinateArrayRef;
if (localCoordinateArrayRef != null && localCoordinateArrayRef.IsAlive)
{
var arr = (Coordinate[])localCoordinateArrayRef.Target;
if (arr != null)
return arr;
_coordinateArrayRef = null;
return null;
}
return null;
}
public Coordinate[] ToCoordinateArray()
{
var ret = GetCachedCoords();
if (ret != null) return ret;
int j = 0;
int count = Count;
ret = new Coordinate[count];
if (_z != null)
{
for (int i = 0; i < count; i++)
ret[i] = new Coordinate(_xy[j++], _xy[j++], _z[i]);
}
else
{
for (int i = 0; i < count; i++)
ret[i] = new Coordinate(_xy[j++], _xy[j++]);
}
_coordinateArrayRef = new WeakReference(ret);
return ret;
}
public Envelope ExpandEnvelope(Envelope env)
{
int j = 0;
for (int i = 0; i < Count; i++)
env.ExpandToInclude(_xy[j++], _xy[j++]);
return env;
}
/// <summary>
/// Creates a reversed version of this coordinate sequence with cloned <see cref="Coordinate"/>s
/// </summary>
/// <returns>A reversed version of this sequence</returns>
public ICoordinateSequence Reversed()
{
double[] xy = new double[_xy.Length];
double[] z = null, m = null;
if (_z != null) z = new double[_z.Length];
if (_m != null) m = new double[_m.Length];
int j = 2* Count;
int k = Count;
for (int i = 0; i < Count; i++)
{
xy[--j] = _xy[2 * i + 1];
xy[--j] = _xy[2 * i];
k--;
if (_z != null) z[k] = _z[i];
if (_m != null) m[k] = _m[i];
}
return new DotSpatialAffineCoordinateSequence(xy, z, m);
}
public int Dimension
{
get
{
int res = 2;
if (_z != null) res++;
if (_m != null) res++;
return res;
}
}
public Ordinates Ordinates => _ordinates;
public int Count => XY.Length / 2;
/// <summary>
/// Gets the vector with x- and y-ordinate values;
/// </summary>
/// <remarks>If you modify the values of this vector externally, you need to call <see cref="ReleaseCoordinateArray"/>!</remarks>
public double[] XY => _xy;
/// <summary>
/// Gets the vector with z-ordinate values
/// </summary>
/// <remarks>If you modify the values of this vector externally, you need to call <see cref="ReleaseCoordinateArray"/>!</remarks>
public double[] Z => _z;
/// <summary>
/// Gets the vector with measure values
/// </summary>
/// <remarks>If you modify the values of this vector externally, you need to call <see cref="ReleaseCoordinateArray"/>!</remarks>
public double[] M => _m;
/// <summary>
/// Releases the weak reference to the weak referenced coordinate array
/// </summary>
/// <remarks>This is necessary if you modify the values of the <see cref="XY"/>, <see cref="Z"/>, <see cref="M"/> arrays externally.</remarks>
public void ReleaseCoordinateArray()
{
_coordinateArrayRef = null;
}
}
} | 32.411616 | 150 | 0.47799 | [
"EPL-1.0"
] | ChaplinMarchais/NetTopologySuite | NetTopologySuite/Geometries/Implementation/DotSpatialAffineCoordinateSequence.cs | 12,835 | C# |
/*
* MIT License
*
* Copyright (c) 2022 Derek Goslin https://github.com/DerekGn
*
* 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 MCP2221IO.Commands;
using MCP2221IO.Exceptions;
using MCP2221IO.Gpio;
using MCP2221IO.Responses;
using MCP2221IO.Settings;
using MCP2221IO.Usb;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Runtime.CompilerServices;
namespace MCP2221IO
{
/// <summary>
/// A MCP2221 device
/// </summary>
public class Device : IDevice
{
internal bool _gpioPortsRead = false;
private readonly ILogger<IDevice> _logger;
private string _factorySerialNumber;
private IHidDevice _hidDevice;
private int _speed = 100000;
public Device(ILogger<IDevice> logger, IHidDevice hidDevice)
{
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
_hidDevice = hidDevice ?? throw new ArgumentNullException(nameof(hidDevice));
}
// <inheritdoc/>
public DeviceStatus Status { get; internal set; }
// <inheritdoc/>
public ChipSettings ChipSettings { get; internal set; }
// <inheritdoc/>
public GpSettings GpSettings { get; internal set; }
// <inheritdoc/>
public SramSettings SramSettings { get; internal set; }
// <inheritdoc/>
public GpioPort GpioPort0 { get; internal set; }
// <inheritdoc/>
public GpioPort GpioPort1 { get; internal set; }
// <inheritdoc/>
public GpioPort GpioPort2 { get; internal set; }
// <inheritdoc/>
public GpioPort GpioPort3 { get; internal set; }
// <inheritdoc/>
public string UsbManufacturerDescriptor
{
get => HandleOperationExecution(
nameof(Device),
() =>
{
return ExecuteCommand<ReadFlashStringResponse>(new ReadUsbManufacturerDescriptorCommand()).Value;
});
set =>
HandleOperationExecution(
nameof(Device),
() =>
{
ExecuteCommand<WriteFlashDataResponse>(new WriteUsbManufacturerDescriptorCommand(value));
});
}
// <inheritdoc/>
public string UsbProductDescriptor
{
get => HandleOperationExecution(
nameof(Device),
() =>
{
return ExecuteCommand<ReadFlashStringResponse>(new ReadUsbProductDescriptorCommand()).Value;
});
set => HandleOperationExecution(
nameof(Device),
() =>
{
ExecuteCommand<WriteFlashDataResponse>(new WriteUsbProductDescriptorCommand(value));
});
}
// <inheritdoc/>
public string UsbSerialNumberDescriptor
{
get => HandleOperationExecution(
nameof(Device),
() =>
{
return ExecuteCommand<ReadFlashStringResponse>(new ReadUsbSerialNumberDescriptorCommand()).Value;
});
set => HandleOperationExecution(
nameof(Device),
() =>
{
ExecuteCommand<WriteFlashDataResponse>(new WriteUsbSerialNumberCommand(value));
});
}
// <inheritdoc/>
public string FactorySerialNumber => GetFactorySerialNumber();
// <inheritdoc/>
public void UnlockFlash(Password password)
{
HandleOperationExecution(
nameof(Device),
() =>
{
ExecuteCommand<UnlockFlashResponse>(new UnlockFlashCommand(password));
});
}
// <inheritdoc/>
public void ReadDeviceStatus()
{
HandleOperationExecution(
nameof(Device),
() =>
{
Status = ExecuteCommand<StatusSetParametersResponse>(new ReadStatusSetParametersCommand()).DeviceStatus;
});
}
// <inheritdoc/>
public void ReadChipSettings()
{
HandleOperationExecution(
nameof(Device),
() =>
{
ChipSettings = ExecuteCommand<ReadChipSettingsResponse>(new ReadChipSettingsCommand()).ChipSettings;
});
}
// <inheritdoc/>
public void ReadGpSettings()
{
HandleOperationExecution(
nameof(Device),
() =>
{
GpSettings = ExecuteCommand<ReadGpSettingsResponse>(new ReadGpSettingsCommand()).GpSettings;
});
}
// <inheritdoc/>
public void ReadSramSettings()
{
HandleOperationExecution(
nameof(Device),
() =>
{
SramSettings = ExecuteCommand<ReadSramSettingsResponse>(new ReadSramSettingsCommand()).SramSettings;
});
}
// <inheritdoc/>
public void ReadGpioPorts()
{
HandleOperationExecution(
nameof(Device),
() =>
{
var response = ExecuteCommand<ReadGpioPortsResponse>(new ReadGpioPortsCommand());
GpioPort0 = response.GpioPort0;
GpioPort1 = response.GpioPort1;
GpioPort2 = response.GpioPort2;
GpioPort3 = response.GpioPort3;
_gpioPortsRead = true;
});
}
// <inheritdoc/>
public void WriteChipSettings(Password password)
{
HandleOperationExecution(
nameof(Device),
() =>
{
if (ChipSettings == null)
{
throw new ReadRequiredException($"{nameof(ChipSettings)} must be read from the device");
}
ExecuteCommand<WriteFlashDataResponse>(new WriteChipSettingsCommand(ChipSettings, password));
});
}
// <inheritdoc/>
public void WriteGpSettings()
{
HandleOperationExecution(
nameof(Device),
() =>
{
if (GpSettings == null)
{
throw new ReadRequiredException($"{nameof(GpSettings)} must be read from the device");
}
ExecuteCommand<WriteFlashDataResponse>(new WriteGpSettingsCommand(GpSettings));
});
}
// <inheritdoc/>
public void WriteSramSettings(bool clearInterrupts)
{
HandleOperationExecution(
nameof(Device),
() =>
{
if (SramSettings == null)
{
throw new ReadRequiredException($"{nameof(SramSettings)} must be read from the device");
}
ExecuteCommand<WriteSramSettingsResponse>(new WriteSramSettingsCommand(SramSettings, clearInterrupts));
});
}
// <inheritdoc/>
public void WriteGpioPorts()
{
HandleOperationExecution(
nameof(Device),
() =>
{
if (!_gpioPortsRead)
{
throw new ReadRequiredException($"Gpio ports must be read from the device");
}
ExecuteCommand<WriteGpioPortsResponse>(new WriteGpioPortsCommand(GpioPort0, GpioPort1, GpioPort2, GpioPort3));
});
}
// <inheritdoc/>
public void Reset()
{
HandleOperationExecution(
nameof(Device),
() =>
{
ExecuteCommand(new ResetCommand());
});
}
// <inheritdoc/>
public void CancelI2cBusTransfer()
{
HandleOperationExecution(
nameof(Device),
() =>
{
Status = ExecuteCommand<StatusSetParametersResponse>(new CancelI2cBusTransferCommand()).DeviceStatus;
});
}
// <inheritdoc/>
public void WriteI2cBusSpeed(int speed)
{
HandleOperationExecution(
nameof(Device),
() =>
{
Status = ExecuteCommand<StatusSetParametersResponse>(new UpdateI2cBusSpeedCommand(speed)).DeviceStatus;
if (Status.SpeedStatus != I2cSpeedStatus.Set)
{
CancelI2cBusTransfer();
}
_speed = speed;
});
}
// <inheritdoc/>
public void Open()
{
HandleOperationExecution(nameof(Device), () => _hidDevice.Open());
}
// <inheritdoc/>
public void Close()
{
Dispose();
}
// <inheritdoc/>
public void I2cWriteData(I2cAddress address, IList<byte> data)
{
HandleOperationExecution(
nameof(Device),
() =>
{
I2cWriteData<I2cWriteDataResponse>(CommandCodes.WriteI2cData, address, data);
});
}
// <inheritdoc/>
public void I2cWriteDataRepeatStart(I2cAddress address, IList<byte> data)
{
HandleOperationExecution(
nameof(Device),
() =>
{
I2cWriteData<I2cWriteDataRepeatStartResponse>(CommandCodes.WriteI2cDataRepeatedStart, address, data);
});
}
// <inheritdoc/>
public void I2cWriteDataNoStop(I2cAddress address, IList<byte> data)
{
HandleOperationExecution(
nameof(Device),
() =>
{
I2cWriteData<I2cWriteDataNoStopResponse>(CommandCodes.WriteI2cDataNoStop, address, data);
});
}
// <inheritdoc/>
public IList<byte> I2cReadData(I2cAddress address, ushort length)
{
return HandleOperationExecution(
nameof(Device),
() =>
{
return I2cReadData<I2cReadDataResponse>(CommandCodes.ReadI2cData, address, length);
});
}
// <inheritdoc/>
public IList<byte> I2cReadDataRepeatedStart(I2cAddress address, ushort length)
{
return HandleOperationExecution(
nameof(Device),
() =>
{
return I2cReadData<I2cReadDataRepeatedStarteResponse>(CommandCodes.ReadI2cDataRepeatedStart, address, length);
});
}
// <inheritdoc/>
public IList<I2cAddress> I2cScanBus(bool useTenBitAddressing)
{
List<I2cAddress> result = new List<I2cAddress>();
uint upperAddress = useTenBitAddressing ? I2cAddress.TenBitRangeUpper : I2cAddress.SevenBitRangeUpper;
_logger.LogDebug($"Setting I2C Speed: [0x{_speed:X}] [{_speed}]");
WriteI2cBusSpeed(_speed);
for (uint i = I2cAddress.SevenBitRangeLower + 1; i < upperAddress; i++)
{
I2cAddress address = new I2cAddress(i, useTenBitAddressing ? I2cAddressSize.TenBit : I2cAddressSize.SevenBit);
try
{
_logger.LogDebug($"Probing Device Address [0x{address.Value:X}]");
var response = I2cReadData(address, 1);
if (response.Count > 0)
{
_logger.LogDebug($"Read [{response.Count}] byte from Device Address [0x{address.Value:X}]");
}
result.Add(address);
}
catch (I2cOperationException ex)
{
_logger.LogWarning(ex, $"Device Address [0x{address.Value:X2}] did not respond");
CancelI2cBusTransfer();
}
}
return result;
}
private IList<byte> I2cReadData<T>(CommandCodes commandCode, I2cAddress address, ushort length) where T : IResponse, new()
{
if (address == null)
{
throw new ArgumentNullException(nameof(address));
}
if (length > IDevice.MaxI2cLength)
{
throw new ArgumentOutOfRangeException(nameof(length), length, $"Must be less than 0x{IDevice.MaxI2cLength:X4}");
}
return HandleOperationExecution(
nameof(Device),
() =>
{
List<byte> result = new List<byte>();
var response = ExecuteCommand<T>(new I2cReadDataCommand(commandCode, address, length), false);
if (response.ExecutionResult != 0)
{
throw new I2cOperationException(response.ExecutionResult, $"{nameof(I2cReadData)} The read of i2c data failed with execution result code [0x{response.ExecutionResult:x}]");
}
while (result.Count < length || length == 0)
{
var getResponse = ExecuteCommand<GetI2cDataResponse>(new GetI2cDataCommand(), false);
if (getResponse.ExecutionResult != 0)
{
throw new I2cOperationException(getResponse.ExecutionResult, $"{nameof(I2cReadData)} The read of i2c data failed with execution result code [0x{getResponse.ExecutionResult:x}]");
}
if (getResponse.Data.Count > 0)
{
result.AddRange(getResponse.Data);
}
else
{
break;
}
}
return result;
});
}
private void I2cWriteData<T>(CommandCodes commandCode, I2cAddress address, IList<byte> data) where T : IResponse, new()
{
if(address == null)
{
throw new ArgumentNullException(nameof(address));
}
if (data == null)
{
throw new ArgumentNullException(nameof(data));
}
if (data.Count > IDevice.MaxI2cLength)
{
throw new ArgumentOutOfRangeException(nameof(data), data, $"Must be less than 0x{IDevice.MaxI2cLength:X4}");
}
HandleOperationExecution(
nameof(Device),
() =>
{
//int blockCount = (data.Count + MaxBlockSize - 1) / MaxBlockSize;
//for (int i = 0; i < blockCount; i++)
//{
// int blockSize = Math.Min(MaxBlockSize, Math.Abs(data.Count - (i * MaxBlockSize)));
// ExecuteCommand<T>(new I2cWriteDataCommand(commandCode, address, data.Skip(MaxBlockSize * i).Take(blockSize).ToList()));
//}
});
}
private string GetFactorySerialNumber()
{
return HandleOperationExecution(
nameof(Device),
() =>
{
if (String.IsNullOrWhiteSpace(_factorySerialNumber))
{
var response = ExecuteCommand<FactorySerialNumberResponse>(new ReadFactorySerialNumberCommand());
_factorySerialNumber = response.SerialNumber;
}
return _factorySerialNumber;
});
}
private void ExecuteCommand(ICommand command)
{
var memoryStream = new MemoryStream(new byte[64], true);
command.Serialize(memoryStream);
_hidDevice.Write(memoryStream.ToArray());
}
private T ExecuteCommand<T>(ICommand command, bool checkResult = true) where T : IResponse, new()
{
var outStream = new MemoryStream(new byte[64], true);
var inStream = new MemoryStream();
command.Serialize(outStream);
inStream.Write(_hidDevice.WriteRead(outStream.ToArray()));
var result = new T();
result.Deserialize(inStream);
if (checkResult && result.ExecutionResult != 0)
{
throw new CommandExecutionFailedException($"Unexpected command execution status Expected: [0x00] Actual [0x{result.ExecutionResult:x}]");
}
return result;
}
[DebuggerStepThrough]
private void HandleOperationExecution(string className, Action operation, [CallerMemberName] string memberName = "")
{
Stopwatch sw = new Stopwatch();
try
{
sw.Start();
operation();
sw.Stop();
_logger.LogDebug($"Executed [{className}].[{memberName}] in [{sw.Elapsed.TotalMilliseconds}] ms");
}
catch (Exception ex)
{
_logger.LogError($"An exception occurred executing [{className}].[{memberName}] Reason: [{ex.Message}]");
throw;
}
}
[DebuggerStepThrough]
private T HandleOperationExecution<T>(string className, Func<T> operation, [CallerMemberName] string memberName = "")
{
Stopwatch sw = new Stopwatch();
T result = default(T);
try
{
sw.Start();
result = operation();
sw.Stop();
_logger.LogDebug($"Executed [{className}].[{memberName}] in [{sw.Elapsed.TotalMilliseconds}] ms");
}
catch (Exception ex)
{
_logger.LogError($"An exception occurred executing [{className}].[{memberName}] Reason: [{ex.Message}]");
throw;
}
return result;
}
#region Dispose
private bool disposedValue;
protected virtual void Dispose(bool disposing)
{
if (!disposedValue)
{
if (disposing)
{
_hidDevice = null;
}
disposedValue = true;
}
}
public void Dispose()
{
// Do not change this code. Put cleanup code in 'Dispose(bool disposing)' method
Dispose(disposing: true);
System.GC.SuppressFinalize(this);
}
#endregion
}
}
| 32.965964 | 206 | 0.512979 | [
"MIT"
] | DerekGn/MCP2221IO | MCP2221IO/Device.cs | 20,342 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
//Joshua Saxton
namespace Boys_vs.Girls
{
/// <summary>
/// This is the main type for your game
/// </summary>
public class Game1 : Microsoft.Xna.Framework.Game
{
GraphicsDeviceManager graphics;
SpriteBatch spriteBatch;
SpriteFont font;
public static Random jen = new Random();
public static Player p1;
public static Player p2;
private List<Enemy> enemylist = new List<Enemy>();
public static List<Weapon> onscreenWeapons = new List<Weapon>(3);
private Texture2D player_texture;
public Texture2D bulletHeart;
public Texture2D missilePod;
public Texture2D lipstick;
public Texture2D currbullet;
public Texture2D sword;
public Texture2D lollipop;
private Texture2D Spring;
public enum ScreenState
{
startScreen,
playingScreen,
highScore,
endGame
}
ScreenState currstate;
public Game1()
{
graphics = new GraphicsDeviceManager(this);
graphics.PreferredBackBufferHeight = 600;
graphics.PreferredBackBufferWidth = 800;
Content.RootDirectory = "Content";
}
/// <summary>
/// Allows the game to perform any initialization it needs to before starting to run.
/// This is where it can query for any required services and load any non-graphic
/// related content. Calling base.Initialize will enumerate through any components
/// and initialize them as well.
/// </summary>
protected override void Initialize()
{
// TODO: Add your initialization logic here
currstate = ScreenState.startScreen;
base.Initialize();
}
/// <summary>
/// LoadContent will be called once per game and is the place to load
/// all of your content.
/// </summary>
protected override void LoadContent()
{
// Create a new SpriteBatch, which can be used to draw textures.
spriteBatch = new SpriteBatch(GraphicsDevice);
// TODO: use this.Content to load your game content here
player_texture = Content.Load<Texture2D>("Girl");
p1 = new Player("Sweetie", 0, player_texture, new Vector2(100.0f, 100.0f), this, 1);
p2 = new Player("Honey", 0, player_texture, new Vector2(500.0f, 500.0f), this, 2);
font = Content.Load<SpriteFont>("font");
for (int i = 0; i < 20; i++)
{
enemylist.Add(new Spider(Content.Load<Texture2D>("Spider"), this));
enemylist.Add(new Boy(Content.Load<Texture2D>("Boy"), this));
enemylist.Add(new Monkey(Content.Load<Texture2D>("monkey"), this));
}
//Bullet loading
bulletHeart = Content.Load<Texture2D>("BulletHeart");
missilePod = Content.Load<Texture2D>("Missilepod");
lipstick = Content.Load<Texture2D>("Lipstick");
//Weapon loading
sword = Content.Load<Texture2D>("Sword");
onscreenWeapons.Add(new Sword(sword, this, 10.0f));
lollipop = Content.Load<Texture2D>("Lollipop");
onscreenWeapons.Add(new Lollipop(lollipop, this, 30.0f));
Spring = Content.Load<Texture2D>("Spring room");
}
/// <summary>
/// UnloadContent will be called once per game and is the place to unload
/// all content.
/// </summary>
protected override void UnloadContent()
{
// TODO: Unload any non ContentManager content here
}
/// <summary>
/// Allows the game to run logic such as updating the Room,
/// checking for collisions, gathering input, and playing audio.
/// </summary>
/// <param name="gameTime">Provides a snapshot of timing values.</param>
protected override void Update(GameTime gameTime)
{
switch (currstate)
{
case ScreenState.playingScreen:
if (p1.Health <= 0 && p2.Health <= 0 || enemylist.Count == 0)
{
currstate = ScreenState.endGame;
}
p1.Update();
p2.Update();
foreach (Enemy e in enemylist)
{
e.Update(p1.Position);
e.Update(p2.Position);
e.Attack(p1);
e.Attack(p2);
}
Collisions(p1.Bulletlist, enemylist, p1);
Collisions(p2.Bulletlist, enemylist, p2);
break;
case ScreenState.startScreen:
if (Keyboard.GetState().IsKeyDown(Keys.Enter))
{
currstate = ScreenState.playingScreen;
}
break;
case ScreenState.highScore:
case ScreenState.endGame:
break;
}
base.Update(gameTime);
}
/// <summary>
/// This is called when the game should draw itself.
/// </summary>
/// <param name="gameTime">Provides a snapshot of timing values.</param>
protected override void Draw(GameTime gameTime)
{
GraphicsDevice.Clear(Color.CornflowerBlue);
// TODO: Add your drawing code here
spriteBatch.Begin();
switch (currstate)
{
case ScreenState.playingScreen:
spriteBatch.Draw(Spring, new Vector2(0.0f, 0.0f), Color.White);
if (p1.Health >= 0)
p1.Draw(spriteBatch);
if (p2.Health >= 0)
p2.Draw(spriteBatch);
foreach (Enemy e in enemylist)
{
e.Draw(spriteBatch);
}
foreach (Weapon w in onscreenWeapons)
{
w.Draw(spriteBatch);
}
spriteBatch.DrawString(font, "Player 1 Health : " + p1.Health, Vector2.Zero, Color.LavenderBlush);
spriteBatch.DrawString(font, "Player 2 Score: " + p1.Score, new Vector2(0, 15), Color.LavenderBlush);
spriteBatch.DrawString(font, "Player 2 Health : " + p2.Health, new Vector2(600, 0), Color.Pink);
spriteBatch.DrawString(font, "Player 2 Score : " + p2.Score, new Vector2(600, 15), Color.Pink);
break;
case ScreenState.startScreen:
spriteBatch.Draw(Content.Load<Texture2D>("StartScreen"), Vector2.Zero, Color.White);
spriteBatch.DrawString(font, "Enter = Begin Game", new Vector2(0, 600), Color.White);
spriteBatch.DrawString(font, "F1 to enter fullscreen", new Vector2(0, 550), Color.White);
break;
}
spriteBatch.End();
base.Draw(gameTime);
}
private void Collisions(List<Bullet> bulletlist, List<Enemy> enemylist, Player p)
{
for (int i = enemylist.Count - 1; i >= 0; i--)
{
Enemy e = enemylist[i];
for (int j = bulletlist.Count - 1; j >= 0; j--)
{
Bullet b = bulletlist[j];
if (b.X >= 800 || b.X <= 0 || b.Y >= 600 || b.Y <= 0)
{
bulletlist.RemoveAt(j);
continue;
}
if (b.Spriterect.Intersects(e.Spriterect))
{
e.Health -= .005f;
if (e.Health <= 0)
{
enemylist.RemoveAt(i);
bulletlist.RemoveAt(j);
p.Score += 10;
break;
}
}
}
}
}
}
}
| 34.745968 | 121 | 0.511663 | [
"MIT"
] | saxtonjoshua1/CS-Intro-Game-Projects | Boys vs. Girls 2.0/Game1.cs | 8,617 | C# |
using System;
using System.IO;
namespace Pablo.Sauce
{
public class SauceStream : Stream
{
Stream stream;
public SauceStream(SauceInfo sauce, Stream stream)
{
this.Sauce = sauce;
this.stream = stream;
}
public SauceStream(Stream stream)
{
this.stream = stream;
if (SauceInfo.HasSauce(stream))
{
Sauce = new SauceInfo(stream);
}
else Sauce = null;
}
public override bool CanRead
{
get { return true; }
}
public override bool CanSeek
{
get { return true; }
}
public override bool CanWrite
{
get { return false; }
}
public override void Flush() { stream.Flush(); }
public override long Length { get { return (Sauce != null) ? Sauce.FileSize : stream.Length; } }
public override long Position
{
get { return stream.Position; }
set { stream.Position = value; }
}
public override int ReadByte()
{
if (Sauce != null && stream.Position >= Sauce.FileSize) return -1;
return stream.ReadByte();
}
public override int Read(byte[] array, int offset, int count)
{
if (Sauce != null)
{
if (stream.Position > Sauce.FileSize) return 0;
if (stream.Position+count > Sauce.FileSize) count = (int)(Sauce.FileSize - stream.Position);
}
return stream.Read(array, offset, count);
}
public override long Seek(long offset, SeekOrigin origin)
{
return stream.Seek(offset, origin);
}
public override void SetLength(long value)
{
throw new Exception("Cannot set length on a sauce stream");
}
public override void Write(byte[] array, int offset, int count)
{
stream.Write(array, offset, count);
}
public SauceInfo Sauce
{
get; set;
}
}
}
| 19.159091 | 98 | 0.649466 | [
"MIT"
] | blocktronics/pablodraw | Source/Pablo/Sauce/SauceStream.cs | 1,686 | C# |
using System;
using System.IO;
namespace Simple.ServiceBus.Logging
{
public class SimpleLogger
{
private const string TEXT_PREFIX_FORMAT = "yyyy-MM-dd HH:mm:ss>>";
protected static Object _thatObj;
protected static SimpleLogControl LogControl;
static SimpleLogger()
{
_thatObj = new Object();
LogControl = new SimpleLogControl();
LogControl.Init();
}
internal static void Write(String text, String fileName)
{
lock (_thatObj)
{
try
{
FileInfo fileInfo = new FileInfo(fileName);
using (StreamWriter writer = fileInfo.AppendText())
{
writer.WriteLine(text);
writer.Close();
}
LogControl.TryResetFileName(fileInfo.Length);
}
catch (Exception ex)
{
Console.WriteLine("{0}file:{1}, content:{2}, write log exception:{3}",
DateTime.Now.ToString(TEXT_PREFIX_FORMAT), fileName, text, ex);
}
}
}
public static void Info(String text)
{
LogControl.TryResetFileName();
String nowPrefix = DateTime.Now.ToString(TEXT_PREFIX_FORMAT);
text = nowPrefix + text;
Write(text, LogControl.GetFileFullName());
}
protected class SimpleLogControl
{
public String BaseDirectory { get; protected set; }
public DateTime Now { get; protected set; }
public Int64 LogSize { get; set; }
public String FileName { get; protected set; }
public SimpleLogControl()
{
this.BaseDirectory = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Logs");
this.LogSize = 20971520;//20MB
this.Now = DateTime.Now;
this.FileName = GetFileName("yyyyMMdd");
}
public void Init()
{
DirectoryInfo dirInfo = new DirectoryInfo(this.BaseDirectory);
if (!dirInfo.Exists)
{
dirInfo.Create();
return;
}
TryResetFileName(dirInfo);
}
private String GetFileName(String timeFormat)
{
return DateTime.Now.ToString(timeFormat) + ".log";
}
public String GetFileFullName()
{
return Path.Combine(this.BaseDirectory, this.FileName);
}
public Boolean TryResetFileName()
{
if (Now.Date == DateTime.Now.Date)
{
return false;
}
this.Now = DateTime.Now;
this.FileName = GetFileName("yyyyMMdd");
return true;
}
public Boolean TryResetFileName(Int64 fileLength)
{
Boolean isCreateNewFile = TryResetFileName();
if (isCreateNewFile)
{
return true;
}
isCreateNewFile = fileLength >= LogSize;
if (isCreateNewFile)
{
this.FileName = GetFileName("yyyyMMdd_HHmmss");
}
return isCreateNewFile;
}
protected Boolean TryResetFileName(DirectoryInfo dirInfo)
{
if (dirInfo == null || !dirInfo.Exists)
{
return false;
}
String searchPattern = DateTime.Now.ToString("yyyyMMdd") + "*.log";
FileInfo[] logFiles = dirInfo.GetFiles(searchPattern, SearchOption.TopDirectoryOnly);
if (logFiles != null && logFiles.Length > 1)
{
this.FileName = logFiles[logFiles.Length - 1].Name;
return true;
}
return false;
}
}
}
}
| 28.653061 | 101 | 0.473647 | [
"Apache-2.0"
] | yuanrui/Examples | Simple.ServiceBus.Common/Logging/SimpleLogger.cs | 4,214 | C# |
using Microsoft.ML.OnnxRuntime.Tensors;
namespace PaintDotNet.Effects.ML.StyleTransfer
{
/// <summary>
/// Style extraction model.
/// </summary>
public interface IStyleModel : IEffectModel
{
/// <summary>
/// Run inference on style extraction model and return style vector.
/// </summary>
/// <param name="styleImage">Normalised RGB image tensor in NHWC-format</param>
/// <returns>Style vector extracted from image in NHWC-format (100 elements)</returns>
Tensor<float> Run(Tensor<float> styleImage);
}
}
| 33.166667 | 95 | 0.631491 | [
"MIT"
] | patlevin/pdn-styletransfer | StyleTransfer/StyleTransferEffect/IStyleModel.cs | 599 | C# |
using System;
using System.Numerics;
class DecimalToBinaryNumber
{
static void Main()
{
int n = int.Parse(Console.ReadLine());
if (n == 0)
{
Console.WriteLine(0);
return;
}
BigInteger multiplier = 1;
BigInteger nBinary = 0;
int binaryDigit = 0;
while (n > 0)
{
binaryDigit = n % 2;
nBinary += binaryDigit * multiplier;
multiplier *= 10;
n /= 2;
}
if (binaryDigit == 0)
{
nBinary += multiplier;
}
string binary = nBinary.ToString();
Console.WriteLine(binary);
}
}
| 21.28125 | 48 | 0.469897 | [
"MIT"
] | Javorov1103/SoftUni-Course | Programming Basics/07.Loops/Homework/14.Decimal to Binary Number/Decimal to Binary Number.cs | 683 | C# |
using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("AWSSDK.KinesisFirehose")]
[assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (3.5) - Amazon Kinesis Firehose. Amazon Kinesis Firehose is a fully managed service for ingesting data streams directly into AWS data services such as Amazon S3 and Amazon Redshift.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyProduct("Amazon Web Services SDK for .NET")]
[assembly: AssemblyCompany("Amazon.com, Inc")]
[assembly: AssemblyCopyright("Copyright 2009-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("3.3")]
[assembly: AssemblyFileVersion("3.3.100.20")] | 47.9375 | 253 | 0.754889 | [
"Apache-2.0"
] | k0lpak/aws-sdk-net | sdk/code-analysis/ServiceAnalysis/KinesisFirehose/Properties/AssemblyInfo.cs | 1,534 | C# |
namespace CopperSharp.Entity.Impl;
/// <summary>
/// Represents a salmon entity
/// </summary>
public class Salmon : LivingEntity
{
internal Salmon() : base(EntityType.Salmon)
{
}
/// <summary>
/// Whether this salmon was released from bucket
/// </summary>
/// <param name="from">Marker</param>
/// <returns>This salmon</returns>
public Salmon FromBucket(bool from)
{
Bools["FromBucket"] = from;
return this;
}
} | 21.954545 | 56 | 0.598344 | [
"MIT"
] | Maxuss/CopperSharp | CopperSharp/Entity/Impl/Salmon.cs | 483 | C# |
using Microsoft.EntityFrameworkCore.Migrations;
namespace PizzaLab.Data.Migrations
{
public partial class OrderProductModified : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropForeignKey(
name: "FK_OrderProduct_Products_ProductId1",
table: "OrderProduct");
migrationBuilder.DropIndex(
name: "IX_OrderProduct_ProductId1",
table: "OrderProduct");
migrationBuilder.DropColumn(
name: "ProductId1",
table: "OrderProduct");
migrationBuilder.AlterColumn<string>(
name: "ProductId",
table: "OrderProduct",
nullable: true,
oldClrType: typeof(int));
migrationBuilder.CreateIndex(
name: "IX_OrderProduct_ProductId",
table: "OrderProduct",
column: "ProductId");
migrationBuilder.AddForeignKey(
name: "FK_OrderProduct_Products_ProductId",
table: "OrderProduct",
column: "ProductId",
principalTable: "Products",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropForeignKey(
name: "FK_OrderProduct_Products_ProductId",
table: "OrderProduct");
migrationBuilder.DropIndex(
name: "IX_OrderProduct_ProductId",
table: "OrderProduct");
migrationBuilder.AlterColumn<int>(
name: "ProductId",
table: "OrderProduct",
nullable: false,
oldClrType: typeof(string),
oldNullable: true);
migrationBuilder.AddColumn<string>(
name: "ProductId1",
table: "OrderProduct",
nullable: true);
migrationBuilder.CreateIndex(
name: "IX_OrderProduct_ProductId1",
table: "OrderProduct",
column: "ProductId1");
migrationBuilder.AddForeignKey(
name: "FK_OrderProduct_Products_ProductId1",
table: "OrderProduct",
column: "ProductId1",
principalTable: "Products",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
}
}
}
| 33.217949 | 71 | 0.541876 | [
"MIT"
] | EmORz/Simple_Example_Projects | Pizza-Lab-master/PizzaLabWebAPI/Data/PizzaLab.Data/Migrations/20181231112314_OrderProductModified.cs | 2,593 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MDPlayer;
using MDPlayer.Driver;
namespace mdpc
{
public class mdpc
{
private string[] args;
private bool waveout = false;
private string srcFn;
private string desFn;
public const int FCC_VGM = 0x206D6756; // "Vgm "
private Setting setting;
//private WaveWriter ww;
private EnmFileFormat format;
private byte[] vgmBuf;
//private double vgmSpeed;
//private MDPlayer.baseDriver driver;
private bool emuOnly=false;
public mdpc(string[] args)
{
this.args = args;
//ファイル、オプションの指定無し
if (args == null || args.Length < 1)
{
//disp usage
Console.WriteLine(msg.get("I00000"));
Environment.Exit(0);
}
//オプションの解析
int cnt = 0;
try
{
List<string> lstOpt = new List<string>();
while (args[cnt].Length > 1 && args[cnt][0] == '-')
{
lstOpt.Add(args[cnt++].Substring(1));
}
foreach (string opt in lstOpt)
{
//vgm switch
switch (opt[0])
{
case 'w':
waveout = true;
break;
case 'e':
emuOnly = true;
break;
}
}
}
catch
{
Console.WriteLine(msg.get("E0000"));
Environment.Exit(0);
}
//ファイルの指定無し
if (args == null || args.Length < cnt)
{
//disp usage
Console.WriteLine(msg.get("I00000"));
Environment.Exit(0);
}
//vgmファイル名の取得
srcFn = args[cnt++];
if (Path.GetExtension(srcFn) == "")
{
srcFn += ".vgm";
}
//wavファイル名の取得
if (args.Length > cnt)
{
desFn = args[cnt];
}
else
{
desFn = Path.Combine(Path.GetDirectoryName(srcFn), Path.GetFileNameWithoutExtension(srcFn) + ".wav");
}
int ret = Start();
log.Close();
Environment.Exit(ret);
}
private int Start()
{
int ret = 0;
try
{
log.debug = false;
log.Open();
log.Write("Start");
log.Write("(Stop ... Hit Spacebar)");
if (!File.Exists(srcFn))
{
log.Write(string.Format("File not found.({0})", srcFn));
return -1;
}
setting = new Setting();
setting.other.WavSwitch = waveout;
procMain();
while (!Audio.GetVGMStopped())
{
System.Threading.Thread.Sleep(1);
if (Console.KeyAvailable)
{
string outChar = Console.ReadKey().Key.ToString();
if (outChar == "Spacebar")
{
break;
}
}
}
}
catch (Exception e)
{
ret = -1;
log.ForcedWrite(e);
}
finally
{
Audio.Stop();
Audio.closeWaveWriter();
}
log.Write("End");
log.Close();
return ret;
}
public byte[] getAllBytes(string filename, out EnmFileFormat format)
{
format = EnmFileFormat.unknown;
//先ずは丸ごと読み込む
byte[] buf = System.IO.File.ReadAllBytes(filename);
string ext = Path.GetExtension(filename).ToLower();
//.NRDファイルの場合は拡張子判定
if (ext == ".nrd")
{
format = EnmFileFormat.NRT;
return buf;
}
if (ext == ".mdr")
{
format = EnmFileFormat.MDR;
return buf;
}
if (ext == ".mdx")
{
format = EnmFileFormat.MDX;
return buf;
}
if (ext == ".mnd")
{
format = EnmFileFormat.MND;
return buf;
}
if (ext == ".mub")
{
format = EnmFileFormat.MUB;
return buf;
}
if (ext == ".muc")
{
format = EnmFileFormat.MUC;
return buf;
}
if (ext == ".xgm")
{
format = EnmFileFormat.XGM;
return buf;
}
if (ext == ".s98")
{
format = EnmFileFormat.S98;
return buf;
}
if (ext == ".nsf")
{
format = EnmFileFormat.NSF;
return buf;
}
if (ext == ".hes")
{
format = EnmFileFormat.HES;
return buf;
}
if (ext == ".sid")
{
format = EnmFileFormat.SID;
return buf;
}
if (ext == ".mid")
{
format = EnmFileFormat.MID;
return buf;
}
if (ext == ".rcp")
{
format = EnmFileFormat.RCP;
return buf;
}
//.VGMの場合はヘッダの確認とGzipで解凍後のファイルのヘッダの確認
uint vgm = (UInt32)buf[0] + (UInt32)buf[1] * 0x100 + (UInt32)buf[2] * 0x10000 + (UInt32)buf[3] * 0x1000000;
if (vgm == FCC_VGM)
{
format = EnmFileFormat.VGM;
return buf;
}
buf = Common.unzipFile(filename);
format = EnmFileFormat.VGM;
return buf;
}
private void procMain()
{
Common.settingFilePath = Common.GetApplicationDataFolder(true);
vgmBuf = getAllBytes(srcFn, out format);
//Audio.isCommandLine = true;
Audio.emuOnly = emuOnly;
Audio.Init(setting);
Audio.SetVGMBuffer(format, vgmBuf, srcFn, "", 0, 0, null);
Audio.Play(setting);
Audio.GO();
}
}
}
| 25.671642 | 119 | 0.386337 | [
"MIT"
] | HoppingTappy/MDPlayer | MDPlayer/mdpc/mdpc.cs | 7,078 | C# |
using System.Diagnostics;
namespace Obscur.Core.Cryptography.Support.Math.EllipticCurve.Custom.SEC
{
internal class SecP224K1Field
{
// 2^224 - 2^32 - 2^12 - 2^11 - 2^9 - 2^7 - 2^4 - 2 - 1
internal static readonly uint[] P = new uint[]{ 0xFFFFE56D, 0xFFFFFFFE, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF,
0xFFFFFFFF };
internal static readonly uint[] PExt = new uint[]{ 0x02C23069, 0x00003526, 0x00000001, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0xFFFFCADA, 0xFFFFFFFD, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF };
private static readonly uint[] PExtInv = new uint[]{ 0xFD3DCF97, 0xFFFFCAD9, 0xFFFFFFFE, 0xFFFFFFFF, 0xFFFFFFFF,
0xFFFFFFFF, 0xFFFFFFFF, 0x00003525, 0x00000002 };
private const uint P6 = 0xFFFFFFFF;
private const uint PExt13 = 0xFFFFFFFF;
private const uint PInv33 = 0x1A93;
public static void Add (uint[] x, uint[] y, uint[] z) {
uint c = Nat224.Add(x, y, z);
if (c != 0 || (z[6] == P6 && Nat224.Gte(z, P))) {
Nat.Add33To(7, PInv33, z);
}
}
public static void AddExt (uint[] xx, uint[] yy, uint[] zz) {
uint c = Nat.Add(14, xx, yy, zz);
if (c != 0 || (zz[13] == PExt13 && Nat.Gte(14, zz, PExt))) {
if (Nat.AddTo(PExtInv.Length, PExtInv, zz) != 0) {
Nat.IncAt(14, zz, PExtInv.Length);
}
}
}
public static void AddOne (uint[] x, uint[] z) {
uint c = Nat.Inc(7, x, z);
if (c != 0 || (z[6] == P6 && Nat224.Gte(z, P))) {
Nat.Add33To(7, PInv33, z);
}
}
public static uint[] FromBigInteger (BigInteger x) {
uint[] z = Nat224.FromBigInteger(x);
if (z[6] == P6 && Nat224.Gte(z, P)) {
Nat224.SubFrom(P, z);
}
return z;
}
public static void Half (uint[] x, uint[] z) {
if ((x[0] & 1) == 0) {
Nat.ShiftDownBit(7, x, 0, z);
} else {
uint c = Nat224.Add(x, P, z);
Nat.ShiftDownBit(7, z, c);
}
}
public static void Multiply (uint[] x, uint[] y, uint[] z) {
uint[] tt = Nat224.CreateExt();
Nat224.Mul(x, y, tt);
Reduce(tt, z);
}
public static void MultiplyAddToExt (uint[] x, uint[] y, uint[] zz) {
uint c = Nat224.MulAddTo(x, y, zz);
if (c != 0 || (zz[13] == PExt13 && Nat.Gte(14, zz, PExt))) {
if (Nat.AddTo(PExtInv.Length, PExtInv, zz) != 0) {
Nat.IncAt(14, zz, PExtInv.Length);
}
}
}
public static void Negate (uint[] x, uint[] z) {
if (Nat224.IsZero(x)) {
Nat224.Zero(z);
} else {
Nat224.Sub(P, x, z);
}
}
public static void Reduce (uint[] xx, uint[] z) {
ulong cc = Nat224.Mul33Add(PInv33, xx, 7, xx, 0, z, 0);
uint c = Nat224.Mul33DWordAdd(PInv33, cc, z, 0);
Debug.Assert(c == 0 || c == 1);
if (c != 0 || (z[6] == P6 && Nat224.Gte(z, P))) {
Nat.Add33To(7, PInv33, z);
}
}
public static void Reduce32 (uint x, uint[] z) {
if ((x != 0 && Nat224.Mul33WordAdd(PInv33, x, z, 0) != 0)
|| (z[6] == P6 && Nat224.Gte(z, P))) {
Nat.Add33To(7, PInv33, z);
}
}
public static void Square (uint[] x, uint[] z) {
uint[] tt = Nat224.CreateExt();
Nat224.Square(x, tt);
Reduce(tt, z);
}
public static void SquareN (uint[] x, int n, uint[] z) {
Debug.Assert(n > 0);
uint[] tt = Nat224.CreateExt();
Nat224.Square(x, tt);
Reduce(tt, z);
while (--n > 0) {
Nat224.Square(z, tt);
Reduce(tt, z);
}
}
public static void Subtract (uint[] x, uint[] y, uint[] z) {
int c = Nat224.Sub(x, y, z);
if (c != 0) {
Nat.Sub33From(7, PInv33, z);
}
}
public static void SubtractExt (uint[] xx, uint[] yy, uint[] zz) {
int c = Nat.Sub(14, xx, yy, zz);
if (c != 0) {
if (Nat.SubFrom(PExtInv.Length, PExtInv, zz) != 0) {
Nat.DecAt(14, zz, PExtInv.Length);
}
}
}
public static void Twice (uint[] x, uint[] z) {
uint c = Nat.ShiftUpBit(7, x, 0, z);
if (c != 0 || (z[6] == P6 && Nat224.Gte(z, P))) {
Nat.Add33To(7, PInv33, z);
}
}
}
}
| 34.415493 | 127 | 0.452834 | [
"Apache-2.0"
] | xorxornop/ObscurCore | Obscur.Core/Cryptography/Support/Math/EllipticCurve/Custom/SEC/SecP224K1Field.cs | 4,889 | C# |
// <auto-generated>
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// </auto-generated>
namespace Microsoft.Azure.Management.Internal.Network.Version2017_10_01
{
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// PublicIPAddressesOperations operations.
/// </summary>
public partial interface IPublicIPAddressesOperations
{
/// <summary>
/// Deletes the specified public IP address.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='publicIpAddressName'>
/// The name of the subnet.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string publicIpAddressName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets the specified public IP address in a specified resource group.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='publicIpAddressName'>
/// The name of the subnet.
/// </param>
/// <param name='expand'>
/// Expands referenced resources.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<PublicIPAddress>> GetWithHttpMessagesAsync(string resourceGroupName, string publicIpAddressName, string expand = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Creates or updates a static or dynamic public IP address.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='publicIpAddressName'>
/// The name of the public IP address.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the create or update public IP address
/// operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<PublicIPAddress>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string publicIpAddressName, PublicIPAddress parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Updates public IP address tags.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='publicIpAddressName'>
/// The name of the public IP address.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to update public IP address tags.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<PublicIPAddress>> UpdateTagsWithHttpMessagesAsync(string resourceGroupName, string publicIpAddressName, TagsObject parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets all the public IP addresses in a subscription.
/// </summary>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<PublicIPAddress>>> ListAllWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets all public IP addresses in a resource group.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<PublicIPAddress>>> ListWithHttpMessagesAsync(string resourceGroupName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets information about all public IP addresses on a virtual machine
/// scale set level.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualMachineScaleSetName'>
/// The name of the virtual machine scale set.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<PublicIPAddress>>> ListVirtualMachineScaleSetPublicIPAddressesWithHttpMessagesAsync(string resourceGroupName, string virtualMachineScaleSetName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets information about all public IP addresses in a virtual machine
/// IP configuration in a virtual machine scale set.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualMachineScaleSetName'>
/// The name of the virtual machine scale set.
/// </param>
/// <param name='virtualmachineIndex'>
/// The virtual machine index.
/// </param>
/// <param name='networkInterfaceName'>
/// The network interface name.
/// </param>
/// <param name='ipConfigurationName'>
/// The IP configuration name.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<PublicIPAddress>>> ListVirtualMachineScaleSetVMPublicIPAddressesWithHttpMessagesAsync(string resourceGroupName, string virtualMachineScaleSetName, string virtualmachineIndex, string networkInterfaceName, string ipConfigurationName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Get the specified public IP address in a virtual machine scale set.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualMachineScaleSetName'>
/// The name of the virtual machine scale set.
/// </param>
/// <param name='virtualmachineIndex'>
/// The virtual machine index.
/// </param>
/// <param name='networkInterfaceName'>
/// The name of the network interface.
/// </param>
/// <param name='ipConfigurationName'>
/// The name of the IP configuration.
/// </param>
/// <param name='publicIpAddressName'>
/// The name of the public IP Address.
/// </param>
/// <param name='expand'>
/// Expands referenced resources.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<PublicIPAddress>> GetVirtualMachineScaleSetPublicIPAddressWithHttpMessagesAsync(string resourceGroupName, string virtualMachineScaleSetName, string virtualmachineIndex, string networkInterfaceName, string ipConfigurationName, string publicIpAddressName, string expand = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Deletes the specified public IP address.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='publicIpAddressName'>
/// The name of the subnet.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse> BeginDeleteWithHttpMessagesAsync(string resourceGroupName, string publicIpAddressName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Creates or updates a static or dynamic public IP address.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='publicIpAddressName'>
/// The name of the public IP address.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the create or update public IP address
/// operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<PublicIPAddress>> BeginCreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string publicIpAddressName, PublicIPAddress parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Updates public IP address tags.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='publicIpAddressName'>
/// The name of the public IP address.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to update public IP address tags.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<PublicIPAddress>> BeginUpdateTagsWithHttpMessagesAsync(string resourceGroupName, string publicIpAddressName, TagsObject parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets all the public IP addresses in a subscription.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<PublicIPAddress>>> ListAllNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets all public IP addresses in a resource group.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<PublicIPAddress>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets information about all public IP addresses on a virtual machine
/// scale set level.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<PublicIPAddress>>> ListVirtualMachineScaleSetPublicIPAddressesNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets information about all public IP addresses in a virtual machine
/// IP configuration in a virtual machine scale set.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<PublicIPAddress>>> ListVirtualMachineScaleSetVMPublicIPAddressesNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
}
}
| 51.035874 | 445 | 0.617301 | [
"MIT"
] | Azure/azure-powershell-common | src/Network/Version2017_10_01/IPublicIPAddressesOperations.cs | 22,762 | C# |
namespace Root.Coding.Code.Models.E01D.Base.Cli.Metadata.Semantic.Elements
{
public interface SemanticStruct_I:SemanticReferenceOrValueType_I
{
}
}
| 23 | 75 | 0.776398 | [
"Apache-2.0"
] | E01D/Base | src/E01D.Base.Cli.Metadata.Semantic.Models/Coding/Code/Models/E01D/Base/Cli/Metadata/Semantic/Elements/SemanticStruct_I.cs | 163 | C# |
using System;
namespace Sogeti.Capstone.Api.Areas.HelpPage
{
/// <summary>
/// This represents a preformatted text sample on the help page. There's a display template named TextSample associated with this class.
/// </summary>
public class TextSample
{
public TextSample(string text)
{
if (text == null)
{
throw new ArgumentNullException("text");
}
Text = text;
}
public string Text { get; private set; }
public override bool Equals(object obj)
{
TextSample other = obj as TextSample;
return other != null && Text == other.Text;
}
public override int GetHashCode()
{
return Text.GetHashCode();
}
public override string ToString()
{
return Text;
}
}
} | 24.189189 | 140 | 0.535196 | [
"MIT"
] | DavidMGardner/sogeti.capstone | Sogeti.Capstone.Web/Sogeti.Capstone.Api/Areas/HelpPage/SampleGeneration/TextSample.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.
// TODO: Remove old namespace after migrating OSGTools
// https://microsoft.visualstudio.com/_git/OSGTools?path=%2Fsrc%2FMicrosoft%2FInternal%2FWindows%2FTools%2FModularBuild%2FNative2Pbxproj%2FExe%2FModels%2FTypescriptParser.cs&version=GBmaster
// to new namespace, and change ParsingOptions back to sealed.
namespace TypeScript.Net.BuildXLScript
{
/// <summary>
/// DScript-specific parsing options for the TypeScript parser
/// </summary>
public sealed class ParsingOptions : TypeScript.Net.DScript.ParsingOptions
{
/// <nodoc/>
public ParsingOptions(
bool namespacesAreAutomaticallyExported,
bool generateWithQualifierFunctionForEveryNamespace,
bool preserveTrivia,
bool allowBackslashesInPathInterpolation,
bool useSpecPublicFacadeAndAstWhenAvailable,
bool escapeIdentifiers,
bool failOnMissingSemicolons = false,
bool collectImportFile = false,
bool convertPathLikeLiteralsAtParseTime = true)
: base(
namespacesAreAutomaticallyExported,
generateWithQualifierFunctionForEveryNamespace,
preserveTrivia,
allowBackslashesInPathInterpolation,
useSpecPublicFacadeAndAstWhenAvailable,
escapeIdentifiers,
failOnMissingSemicolons,
collectImportFile,
convertPathLikeLiteralsAtParseTime)
{
}
}
}
namespace TypeScript.Net.DScript
{
/// <summary>
/// DScript-specific parsing options for the TypeScript parser
/// </summary>
public /*TODO: sealed */ class ParsingOptions
{
/// <nodoc/>
public ParsingOptions(
bool namespacesAreAutomaticallyExported,
bool generateWithQualifierFunctionForEveryNamespace,
bool preserveTrivia,
bool allowBackslashesInPathInterpolation,
bool useSpecPublicFacadeAndAstWhenAvailable,
bool escapeIdentifiers,
bool failOnMissingSemicolons = false,
bool collectImportFile = false,
bool convertPathLikeLiteralsAtParseTime = true)
{
NamespacesAreAutomaticallyExported = namespacesAreAutomaticallyExported;
GenerateWithQualifierFunctionForEveryNamespace = generateWithQualifierFunctionForEveryNamespace;
PreserveTrivia = preserveTrivia;
AllowBackslashesInPathInterpolation = allowBackslashesInPathInterpolation;
UseSpecPublicFacadeAndAstWhenAvailable = useSpecPublicFacadeAndAstWhenAvailable;
EscapeIdentifiers = escapeIdentifiers;
FailOnMissingSemicolons = failOnMissingSemicolons;
CollectImportFile = collectImportFile;
ConvertPathLikeLiteralsAtParseTime = convertPathLikeLiteralsAtParseTime;
}
/// <summary>
/// If true, then such literals like p``, d``, f`` etc would be converted to internal BuildXL representation at parse time.
/// </summary>
public bool ConvertPathLikeLiteralsAtParseTime { get; }
/// <summary>
/// Temporary flag that controls whether double underscore identifiers are escaped (e.g. __test).
/// </summary>
/// <remarks>
/// Escaping is the TypeScript behavior, but due to a bug we need to incrementally fix this, and therefore we need this flag.
/// </remarks>
public bool EscapeIdentifiers { get; }
/// <summary>
/// Whether public surface and serialized AST of specs should be used when available
/// </summary>
public bool UseSpecPublicFacadeAndAstWhenAvailable { get; }
/// <summary>
/// Whether namespaces are automatically exported when any of its members are exported
/// </summary>
public bool NamespacesAreAutomaticallyExported { get; }
/// <summary>
/// Whether function 'withQualifier' is generated for every namespace. This is a V2 feature.
/// </summary>
public bool GenerateWithQualifierFunctionForEveryNamespace { get; }
/// <summary>
/// Back-compat flag to keep the legacy escaping for path interpolation
/// </summary>
/// <remarks>
/// This is mainly Office-specific. TODO: remove when Office is moved to V2
/// </remarks>
public bool AllowBackslashesInPathInterpolation { get; }
/// <summary>
/// Whether the scanner skips trivia (spaces, tabs, etc.)
/// </summary>
public bool PreserveTrivia { get; }
/// <summary>
/// Whether to collect specifiers inside of 'importFile' calls (in addition to collecting specifiers inside 'importFrom' calls).
/// </summary>
/// <remarks>
/// Only used for parsing config files, because they are allowed to use 'importFile' without
/// explicitly specifying all the files that are necessary for processing the config.
/// </remarks>
public bool CollectImportFile { get; }
/// <summary>
/// Whether to fail if the node does not ends with a semicolon.
/// </summary>
/// <remarks>
/// Originally the validation happened in the lint-rule but was moved to the parsing phase for performance reasons.
/// </remarks>
public bool FailOnMissingSemicolons { get; }
/// <nodoc />
public ParsingOptions WithGenerateWithQualifierFunctionForEveryNamespace(bool generateWithQualifierFunctionForEveryNamespace)
{
return new ParsingOptions(
namespacesAreAutomaticallyExported: NamespacesAreAutomaticallyExported,
generateWithQualifierFunctionForEveryNamespace: generateWithQualifierFunctionForEveryNamespace,
preserveTrivia: PreserveTrivia,
allowBackslashesInPathInterpolation: AllowBackslashesInPathInterpolation,
useSpecPublicFacadeAndAstWhenAvailable: UseSpecPublicFacadeAndAstWhenAvailable,
escapeIdentifiers: EscapeIdentifiers,
failOnMissingSemicolons: FailOnMissingSemicolons,
collectImportFile: CollectImportFile,
convertPathLikeLiteralsAtParseTime: ConvertPathLikeLiteralsAtParseTime);
}
/// <nodoc />
public ParsingOptions WithFailOnMissingSemicolons(bool failOnMissingSemicolons)
{
return new ParsingOptions(
namespacesAreAutomaticallyExported: NamespacesAreAutomaticallyExported,
generateWithQualifierFunctionForEveryNamespace: GenerateWithQualifierFunctionForEveryNamespace,
preserveTrivia: PreserveTrivia,
allowBackslashesInPathInterpolation: AllowBackslashesInPathInterpolation,
useSpecPublicFacadeAndAstWhenAvailable: UseSpecPublicFacadeAndAstWhenAvailable,
escapeIdentifiers: EscapeIdentifiers,
failOnMissingSemicolons: failOnMissingSemicolons,
collectImportFile: CollectImportFile,
convertPathLikeLiteralsAtParseTime: ConvertPathLikeLiteralsAtParseTime);
}
/// <nodoc />
public ParsingOptions WithEscapeIdentifiers(bool escapeIdentifiers)
{
return new ParsingOptions(
namespacesAreAutomaticallyExported: NamespacesAreAutomaticallyExported,
generateWithQualifierFunctionForEveryNamespace: GenerateWithQualifierFunctionForEveryNamespace,
preserveTrivia: PreserveTrivia,
allowBackslashesInPathInterpolation: AllowBackslashesInPathInterpolation,
useSpecPublicFacadeAndAstWhenAvailable: UseSpecPublicFacadeAndAstWhenAvailable,
escapeIdentifiers: escapeIdentifiers,
failOnMissingSemicolons: FailOnMissingSemicolons,
collectImportFile: CollectImportFile,
convertPathLikeLiteralsAtParseTime: ConvertPathLikeLiteralsAtParseTime);
}
/// <nodoc />
public ParsingOptions WithAllowBackslashesInPathInterpolation(bool allowBackslashesInPathInterpolation)
{
return new ParsingOptions(
namespacesAreAutomaticallyExported: NamespacesAreAutomaticallyExported,
generateWithQualifierFunctionForEveryNamespace: GenerateWithQualifierFunctionForEveryNamespace,
preserveTrivia: PreserveTrivia,
allowBackslashesInPathInterpolation: allowBackslashesInPathInterpolation,
useSpecPublicFacadeAndAstWhenAvailable: UseSpecPublicFacadeAndAstWhenAvailable,
escapeIdentifiers: EscapeIdentifiers,
failOnMissingSemicolons: FailOnMissingSemicolons,
collectImportFile: CollectImportFile,
convertPathLikeLiteralsAtParseTime: ConvertPathLikeLiteralsAtParseTime);
}
/// <nodoc />
public ParsingOptions WithCollectImportFile(bool collectImportFile)
{
return new ParsingOptions(
namespacesAreAutomaticallyExported: NamespacesAreAutomaticallyExported,
generateWithQualifierFunctionForEveryNamespace: GenerateWithQualifierFunctionForEveryNamespace,
preserveTrivia: PreserveTrivia,
allowBackslashesInPathInterpolation: AllowBackslashesInPathInterpolation,
useSpecPublicFacadeAndAstWhenAvailable: UseSpecPublicFacadeAndAstWhenAvailable,
escapeIdentifiers: EscapeIdentifiers,
failOnMissingSemicolons: FailOnMissingSemicolons,
collectImportFile: collectImportFile,
convertPathLikeLiteralsAtParseTime: ConvertPathLikeLiteralsAtParseTime);
}
/// <nodoc />
public ParsingOptions WithTrivia(bool preserveTrivia)
{
return new ParsingOptions(
namespacesAreAutomaticallyExported: NamespacesAreAutomaticallyExported,
generateWithQualifierFunctionForEveryNamespace: GenerateWithQualifierFunctionForEveryNamespace,
preserveTrivia: preserveTrivia,
allowBackslashesInPathInterpolation: AllowBackslashesInPathInterpolation,
useSpecPublicFacadeAndAstWhenAvailable: UseSpecPublicFacadeAndAstWhenAvailable,
escapeIdentifiers: EscapeIdentifiers,
failOnMissingSemicolons: FailOnMissingSemicolons,
collectImportFile: CollectImportFile,
convertPathLikeLiteralsAtParseTime: ConvertPathLikeLiteralsAtParseTime);
}
/// <summary>
/// Returns parsing options required for parsing prelude.
/// </summary>
/// <remarks>
/// Observe that the prelude module is always assumed to be a V1 module, qualifier wise.
/// </remarks>
public static ParsingOptions GetPreludeParsingOptions(bool escapeIdentifiers)
{
return new ParsingOptions(
namespacesAreAutomaticallyExported: false,
generateWithQualifierFunctionForEveryNamespace: false,
preserveTrivia: false,
allowBackslashesInPathInterpolation: true,
useSpecPublicFacadeAndAstWhenAvailable: false,
escapeIdentifiers: escapeIdentifiers,
failOnMissingSemicolons: true,
collectImportFile: false,
convertPathLikeLiteralsAtParseTime: false);
}
/// <summary>
/// Returns default parsing options.
/// </summary>
public static ParsingOptions DefaultParsingOptions { get; } =
new ParsingOptions(
namespacesAreAutomaticallyExported: true,
generateWithQualifierFunctionForEveryNamespace: false,
preserveTrivia: false,
allowBackslashesInPathInterpolation: true,
useSpecPublicFacadeAndAstWhenAvailable: false,
escapeIdentifiers: true,
failOnMissingSemicolons: false,
collectImportFile: false,
convertPathLikeLiteralsAtParseTime: false);
/// <summary>
/// Returns parsing options that matches the original TypeScript behavior.
/// </summary>
public static ParsingOptions TypeScriptParsingOptions { get; } =
new ParsingOptions(
namespacesAreAutomaticallyExported: false,
generateWithQualifierFunctionForEveryNamespace: false,
preserveTrivia: false,
allowBackslashesInPathInterpolation: false,
useSpecPublicFacadeAndAstWhenAvailable: false,
escapeIdentifiers: true,
failOnMissingSemicolons: false,
collectImportFile: false,
convertPathLikeLiteralsAtParseTime: false);
/// <summary>
/// Returns default parsing options + escape identifiers configuration.
/// </summary>
public static ParsingOptions GetDefaultParsingOptionsWithEscapeIdentifiers(bool escapeIdentifiers)
{
return DefaultParsingOptions.WithEscapeIdentifiers(escapeIdentifiers);
}
/// <summary>
/// Returns default parsing options + backslash configuration.
/// </summary>
public static ParsingOptions GetDefaultParsingOptionsWithBackslashSettings(bool allowBackslashesInPathInterpolation)
{
return DefaultParsingOptions.WithAllowBackslashesInPathInterpolation(allowBackslashesInPathInterpolation);
}
}
}
| 49.501754 | 191 | 0.660618 | [
"MIT"
] | MatisseHack/BuildXL | Public/Src/FrontEnd/TypeScript.Net/TypeScript.Net/DScript/ParsingOptions.cs | 14,108 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Thrower : MonoBehaviour
{
public static Thrower instance;
public GameObject throwPrefab;
public Transform throwPoint;
public float rate;
public Vector3 throwForce;
public Vector3 thisThrowForce;
public List<Thrown> thrownList = new List<Thrown>();
private void Awake()
{
instance = this;
StartCoroutine(DoThrowing());
}
private IEnumerator DoThrowing()
{
while (true)
{
yield return new WaitForSeconds(rate);
GameObject thrownGameObject = GameObject.Instantiate(throwPrefab);
GameObject.Destroy(thrownGameObject, 15f);
Thrown thrown = thrownGameObject.GetComponent<Thrown>();
thrown.rigidbody.position = throwPoint.position;
thrown.rigidbody.rotation = throwPoint.rotation;
yield return null;
thrown.rigidbody.AddRelativeForce(throwForce);
thrownList.Add(thrown);
}
}
}
| 22.156863 | 79 | 0.618584 | [
"BSD-3-Clause"
] | ValveSoftware/Moondust | Assets/Scripts/Throwing/Thrower.cs | 1,132 | C# |
using Microsoft.EntityFrameworkCore;
using Ordering.Application.Contracts.Persistence;
using Ordering.Domain.Entities;
using Ordering.Infrastructure.Persistence;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Ordering.Infrastructure.Repositories
{
public class OrderRepository : RepositoryBase<Order>, IOrderRepository
{
public OrderRepository(OrderContext orderContext) : base(orderContext)
{
}
public async Task<Order> GetOrderBy(Guid orderId)
{
return await _orderContext
.Orders
.Include(order => order.OrderItems)
.FirstOrDefaultAsync(order => order.Id == orderId);
}
public async Task<IEnumerable<Order>> GetOrdersBy(Guid userId)
{
var orderList = await _orderContext
.Orders
.Include(order => order.OrderItems)
.AsNoTracking()
.Where(order => order.UserId == userId)
.ToListAsync();
return orderList;
}
}
}
| 28.820513 | 78 | 0.625445 | [
"MIT"
] | Ninchuga/AspNetMicroservicesShop | Src/Services/Ordering/Ordering.Infrastructure/Repositories/OrderRepository.cs | 1,126 | C# |
/*
*代码由框架生成,任何更改都可能导致被代码生成器覆盖
*如果要增加方法请在当前目录下Partial文件夹Hiiops_Shop_User_ExtractController编写
*/
using Microsoft.AspNetCore.Mvc;
using VOL.Core.Controllers.Basic;
using VOL.Entity.AttributeManager;
using Hiiops.Shop.IServices;
namespace Hiiops.Shop.Controllers
{
[Route("api/Hiiops_Shop_User_Extract")]
[PermissionTable(Name = "Hiiops_Shop_User_Extract")]
public partial class Hiiops_Shop_User_ExtractController : ApiBaseController<IHiiops_Shop_User_ExtractService>
{
public Hiiops_Shop_User_ExtractController(IHiiops_Shop_User_ExtractService service)
: base(service)
{
}
}
}
| 28.636364 | 113 | 0.77619 | [
"MIT"
] | Hiiops/Hiiops.Outside | Vue.Net/VOL.WebApi/Controllers/Shop/Hiiops_Shop_User_ExtractController.cs | 716 | 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.DataFactory.Outputs
{
/// <summary>
/// Execution policy for an activity.
/// </summary>
[OutputType]
public sealed class ActivityPolicyResponse
{
/// <summary>
/// Maximum ordinary retry attempts. Default is 0. Type: integer (or Expression with resultType integer), minimum: 0.
/// </summary>
public readonly object? Retry;
/// <summary>
/// Interval between each retry attempt (in seconds). The default is 30 sec.
/// </summary>
public readonly int? RetryIntervalInSeconds;
/// <summary>
/// When set to true, Input from activity is considered as secure and will not be logged to monitoring.
/// </summary>
public readonly bool? SecureInput;
/// <summary>
/// When set to true, Output from activity is considered as secure and will not be logged to monitoring.
/// </summary>
public readonly bool? SecureOutput;
/// <summary>
/// Specifies the timeout for the activity to run. The default timeout is 7 days. Type: string (or Expression with resultType string), pattern: ((\d+)\.)?(\d\d):(60|([0-5][0-9])):(60|([0-5][0-9])).
/// </summary>
public readonly object? Timeout;
[OutputConstructor]
private ActivityPolicyResponse(
object? retry,
int? retryIntervalInSeconds,
bool? secureInput,
bool? secureOutput,
object? timeout)
{
Retry = retry;
RetryIntervalInSeconds = retryIntervalInSeconds;
SecureInput = secureInput;
SecureOutput = secureOutput;
Timeout = timeout;
}
}
}
| 34.116667 | 205 | 0.612604 | [
"Apache-2.0"
] | polivbr/pulumi-azure-native | sdk/dotnet/DataFactory/Outputs/ActivityPolicyResponse.cs | 2,047 | 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 lex-models-2017-04-19.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using System.Net;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.LexModelBuildingService.Model
{
/// <summary>
/// Provides configuration information for a slot type.
/// </summary>
public partial class SlotTypeConfiguration
{
private SlotTypeRegexConfiguration _regexConfiguration;
/// <summary>
/// Gets and sets the property RegexConfiguration.
/// <para>
/// A regular expression used to validate the value of a slot.
/// </para>
/// </summary>
public SlotTypeRegexConfiguration RegexConfiguration
{
get { return this._regexConfiguration; }
set { this._regexConfiguration = value; }
}
// Check to see if RegexConfiguration property is set
internal bool IsSetRegexConfiguration()
{
return this._regexConfiguration != null;
}
}
} | 31.561404 | 109 | 0.657588 | [
"Apache-2.0"
] | philasmar/aws-sdk-net | sdk/src/Services/LexModelBuildingService/Generated/Model/SlotTypeConfiguration.cs | 1,799 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
class Program
{
static void Main()
{
double width = double.Parse(Console.ReadLine());
double height = double.Parse(Console.ReadLine());
double area = CalculateArea(width, height);
Console.WriteLine(area);
}
static double CalculateArea(double width, double height)
{
double area = width * height / 2;
return area;
}
}
| 20.4 | 60 | 0.647059 | [
"MIT"
] | radoslavvv/Programming-Fundamentals-Extended-May-2017 | Labs/04.MethodsAndDebugging/05.CalculateTriangleArea/05.CalculateTriangleArea.cs | 512 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Data;
using Microsoft.EntityFrameworkCore.Storage;
namespace Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal
{
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
public class SqlServerByteTypeMapping : ByteTypeMapping
{
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
public SqlServerByteTypeMapping(
string storeType,
DbType? dbType = System.Data.DbType.Byte)
: base(storeType, dbType)
{
}
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
protected SqlServerByteTypeMapping(RelationalTypeMappingParameters parameters)
: base(parameters)
{
}
/// <summary>
/// Creates a copy of this mapping.
/// </summary>
/// <param name="parameters"> The parameters for this mapping. </param>
/// <returns> The newly created mapping. </returns>
protected override RelationalTypeMapping Clone(RelationalTypeMappingParameters parameters)
=> new SqlServerByteTypeMapping(parameters);
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
protected override string GenerateNonNullSqlLiteral(object value)
=> $"CAST({base.GenerateNonNullSqlLiteral(value)} AS {StoreType})";
}
}
| 53.847458 | 113 | 0.67548 | [
"MIT"
] | CameronAavik/efcore | src/EFCore.SqlServer/Storage/Internal/SqlServerByteTypeMapping.cs | 3,177 | C# |
using System;
using Google.Protobuf;
using Kronos.Server.Storage;
using Xunit;
namespace Kronos.Server.Tests.Storage
{
public class ExpiringKeyTests
{
[Fact]
public void Ctor_AssignsValues_WithExpiry()
{
// Arrange
var key = new Key();
var expiry = DateTimeOffset.MaxValue;
// Act
var element = new ExpiringKey(key, expiry);
// Assert
Assert.Equal(key, element.Key);
Assert.Equal(expiry, element.ExpiryDate);
}
[Fact]
public void IsExpiring_ReturnsTrueWhenElementIsExpiring()
{
// Arrange
var element = new Element(ByteString.Empty, DateTimeOffset.UtcNow);
// Act
bool expiring = element.IsExpiring;
// Assert
Assert.True(expiring);
}
[Fact]
public void IsExpired_ReturnsTrueWhenKeyExpired_WithoutPassingDate()
{
// Arrange
var expiryDate = DateTimeOffset.MinValue;
var element = new ExpiringKey(new Key("lorem ipsum"), expiryDate);
// Act
bool expired = element.IsExpired();
// Assert
Assert.True(expired);
}
[Fact]
public void IsExpired_ReturnsTrueWhenKeyExpired_WithPassingDate()
{
// Arrange
var expiryDate = DateTimeOffset.MinValue;
var element = new ExpiringKey(new Key("lorem ipsum"), expiryDate);
// Act
bool expired = element.IsExpired(DateTimeOffset.UtcNow);
// Assert
Assert.True(expired);
}
[Fact]
public void CompareTo_Returns_1_When_GivenIsBigger()
{
// Arrange
var expiryDate = DateTimeOffset.Now;
var element = new ExpiringKey(new Key("lorem ipsum"), expiryDate);
// Act
int result = element.CompareTo(new ExpiringKey(new Key("lorem ipsum"), expiryDate.AddDays(1)));
// Assert
Assert.Equal(1, result);
}
[Fact]
public void CompareTo_Returns_0_When_GivenIsEqual()
{
// Arrange
var expiryDate = DateTimeOffset.Now;
var element = new ExpiringKey(new Key("lorem ipsum"), expiryDate);
// Act
int result = element.CompareTo(new ExpiringKey(new Key("lorem ipsum"), expiryDate));
// Assert
Assert.Equal(0, result);
}
[Fact]
public void CompareTo_Returns_Minus1_When_GivenIsEqual()
{
// Arrange
var expiryDate = DateTimeOffset.Now;
var element = new ExpiringKey(new Key("lorem ipsum"), expiryDate);
// Act
int result = element.CompareTo(new ExpiringKey(new Key("lorem ipsum"), expiryDate.AddDays(-1)));
// Assert
Assert.Equal(-1, result);
}
[Fact]
public void GetHashCode_ReturnsKeyHashcode()
{
// Arrange
var key = new Key("lorem ipsum");
var element = new ExpiringKey(key, default);
// Act
int hash = element.GetHashCode();
// Assert
Assert.Equal(key.GetHashCode(), hash);
}
[Fact]
public void Equals_ReturnsFalse_IfTypeIsDifferent()
{
// Arrange
var element = new ExpiringKey(new Key(""), default);
// Act
bool equal = element.Equals(new object());
// Assert
Assert.False(equal);
}
[Fact]
public void Equals_ReturnsTrue_IfElementIsTheSame()
{
// Arrange
var element = new ExpiringKey(new Key(""), default);
// Act
bool equal = element.Equals(element);
// Assert
Assert.True(equal);
}
[Fact]
public void Equals_ReturnsTrue_IfElementIsTheSame_WhenPassedIsObject()
{
// Arrange
var element = new ExpiringKey(new Key(""), default);
// Act
bool equal = element.Equals((object)element);
// Assert
Assert.True(equal);
}
[Fact]
public void ToString_ContainsInformationAboutNameAndExpiry()
{
// Arrange
const string key = "lorem";
var time = DateTimeOffset.Now;
var element = new ExpiringKey(new Key(key), time);
// Act
string value = element.ToString();
// Assert
Assert.Contains(key, value);
Assert.Contains(time.ToString("g"), value);
}
}
}
| 26.820225 | 108 | 0.528907 | [
"MIT"
] | lukasz-pyrzyk/Kronos | Tests/Kronos.Server.Tests/Storage/ExpiringKeyTests.cs | 4,776 | C# |
using NUnit.Framework;
using PEG.SyntaxTree;
namespace PEG.Tests
{
[TestFixture]
public class CaptureTests
{
[Test]
public void CaptureInitializedProperly()
{
var grammar = TestGrammar.Create();
var parser = new PegParser<TestData>(grammar, grammar.Root());
var input = "AAABBBBB";
var result = parser.Parse(input);
Assert.AreEqual(input, result.Items);
}
public class TestData
{
public string Items { get; set; }
}
public class TestGrammar : Grammar<TestGrammar>
{
public virtual Expression Root()
{
return Items();
}
/*
public virtual Expression A()
{
return 'A'._().Repeat(4, 6);
}
public virtual Expression B()
{
return 'A'._() | 'B';
}
*/
public virtual Expression Items()
{
return -('A'._().Repeat(4, 6).Capture("A") | ('A'._() | 'B').Capture("B"));
}
}
}
} | 23.387755 | 91 | 0.461606 | [
"MIT"
] | andrew-boyarshin/npeg | PEG.Tests/CaptureTests.cs | 1,148 | C# |
// MonoGame - Copyright (C) The MonoGame Team
// This file is subject to the terms and conditions defined in
// file 'LICENSE.txt', which is part of this source code package.
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Diagnostics;
#if ANGLE
using OpenTK.Graphics;
#else
using MonoGame.OpenGL;
#endif
namespace Microsoft.Xna.Framework.Graphics
{
public partial class GraphicsDevice
{
#if DESKTOPGL || ANGLE
internal IGraphicsContext Context { get; private set; }
#endif
#if !GLES
private DrawBuffersEnum[] _drawBuffers;
#endif
enum ResourceType
{
Texture,
Buffer,
Shader,
Program,
Query,
Framebuffer
}
struct ResourceHandle
{
public ResourceType type;
public int handle;
public static ResourceHandle Texture(int handle)
{
return new ResourceHandle() { type = ResourceType.Texture, handle = handle };
}
public static ResourceHandle Buffer(int handle)
{
return new ResourceHandle() { type = ResourceType.Buffer, handle = handle };
}
public static ResourceHandle Shader(int handle)
{
return new ResourceHandle() { type = ResourceType.Shader, handle = handle };
}
public static ResourceHandle Program(int handle)
{
return new ResourceHandle() { type = ResourceType.Program, handle = handle };
}
public static ResourceHandle Query(int handle)
{
return new ResourceHandle() { type = ResourceType.Query, handle = handle };
}
public static ResourceHandle Framebuffer(int handle)
{
return new ResourceHandle() { type = ResourceType.Framebuffer, handle = handle };
}
public void Free()
{
switch (type)
{
case ResourceType.Texture:
GL.DeleteTextures(1, ref handle);
break;
case ResourceType.Buffer:
GL.DeleteBuffers(1, ref handle);
break;
case ResourceType.Shader:
if (GL.IsShader(handle))
GL.DeleteShader(handle);
break;
case ResourceType.Program:
if (GL.IsProgram(handle))
{
GL.DeleteProgram(handle);
}
break;
case ResourceType.Query:
#if !GLES
GL.DeleteQueries(1, ref handle);
#endif
break;
case ResourceType.Framebuffer:
GL.DeleteFramebuffers(1, ref handle);
break;
}
GraphicsExtensions.CheckGLError();
}
}
List<ResourceHandle> _disposeThisFrame = new List<ResourceHandle>();
List<ResourceHandle> _disposeNextFrame = new List<ResourceHandle>();
object _disposeActionsLock = new object();
static List<IntPtr> _disposeContexts = new List<IntPtr>();
static object _disposeContextsLock = new object();
private ShaderProgramCache _programCache;
private ShaderProgram _shaderProgram = null;
static readonly float[] _posFixup = new float[4];
private static BufferBindingInfo[] _bufferBindingInfos;
private static bool[] _newEnabledVertexAttributes;
internal static readonly List<int> _enabledVertexAttributes = new List<int>();
internal static bool _attribsDirty;
internal FramebufferHelper framebufferHelper;
internal int glMajorVersion = 0;
internal int glMinorVersion = 0;
internal int glFramebuffer = 0;
internal int MaxVertexAttributes;
internal int _maxTextureSize = 0;
// Keeps track of last applied state to avoid redundant OpenGL calls
internal bool _lastBlendEnable = false;
internal BlendState _lastBlendState = new BlendState();
internal DepthStencilState _lastDepthStencilState = new DepthStencilState();
internal RasterizerState _lastRasterizerState = new RasterizerState();
private Vector4 _lastClearColor = Vector4.Zero;
private float _lastClearDepth = 1.0f;
private int _lastClearStencil = 0;
// Get a hashed value based on the currently bound shaders
// throws an exception if no shaders are bound
private int ShaderProgramHash
{
get
{
if (_vertexShader == null && _pixelShader == null)
throw new InvalidOperationException("There is no shader bound!");
if (_vertexShader == null)
return _pixelShader.HashKey;
if (_pixelShader == null)
return _vertexShader.HashKey;
return _vertexShader.HashKey ^ _pixelShader.HashKey;
}
}
internal void SetVertexAttributeArray(bool[] attrs)
{
for (var x = 0; x < attrs.Length; x++)
{
if (attrs[x] && !_enabledVertexAttributes.Contains(x))
{
_enabledVertexAttributes.Add(x);
GL.EnableVertexAttribArray(x);
GraphicsExtensions.CheckGLError();
}
else if (!attrs[x] && _enabledVertexAttributes.Contains(x))
{
_enabledVertexAttributes.Remove(x);
GL.DisableVertexAttribArray(x);
GraphicsExtensions.CheckGLError();
}
}
}
private void ApplyAttribs(Shader shader, int baseVertex)
{
var programHash = ShaderProgramHash;
var bindingsChanged = false;
for (var slot = 0; slot < _vertexBuffers.Count; slot++)
{
var vertexBufferBinding = _vertexBuffers.Get(slot);
var vertexDeclaration = vertexBufferBinding.VertexBuffer.VertexDeclaration;
var attrInfo = vertexDeclaration.GetAttributeInfo(shader, programHash);
var vertexStride = vertexDeclaration.VertexStride;
var offset = (IntPtr)(vertexDeclaration.VertexStride * (baseVertex + vertexBufferBinding.VertexOffset));
if (!_attribsDirty &&
_bufferBindingInfos[slot].VertexOffset == offset &&
ReferenceEquals(_bufferBindingInfos[slot].AttributeInfo, attrInfo) &&
_bufferBindingInfos[slot].InstanceFrequency == vertexBufferBinding.InstanceFrequency &&
_bufferBindingInfos[slot].Vbo == vertexBufferBinding.VertexBuffer.vbo)
continue;
bindingsChanged = true;
GL.BindBuffer(BufferTarget.ArrayBuffer, vertexBufferBinding.VertexBuffer.vbo);
GraphicsExtensions.CheckGLError();
// If instancing is not supported, but InstanceFrequency of the buffer is not zero, throw an exception
if (!GraphicsCapabilities.SupportsInstancing && vertexBufferBinding.InstanceFrequency > 0)
throw new PlatformNotSupportedException("Instanced geometry drawing requires at least OpenGL 3.2 or GLES 3.2. Try upgrading your graphics drivers.");
foreach (var element in attrInfo.Elements)
{
GL.VertexAttribPointer(element.AttributeLocation,
element.NumberOfElements,
element.VertexAttribPointerType,
element.Normalized,
vertexStride,
(IntPtr)(offset.ToInt64() + element.Offset));
// only set the divisor if instancing is supported
if (GraphicsCapabilities.SupportsInstancing)
GL.VertexAttribDivisor(element.AttributeLocation, vertexBufferBinding.InstanceFrequency);
GraphicsExtensions.CheckGLError();
}
_bufferBindingInfos[slot].VertexOffset = offset;
_bufferBindingInfos[slot].AttributeInfo = attrInfo;
_bufferBindingInfos[slot].InstanceFrequency = vertexBufferBinding.InstanceFrequency;
_bufferBindingInfos[slot].Vbo = vertexBufferBinding.VertexBuffer.vbo;
}
_attribsDirty = false;
if (bindingsChanged)
{
Array.Clear(_newEnabledVertexAttributes, 0, _newEnabledVertexAttributes.Length);
for (var slot = 0; slot < _vertexBuffers.Count; slot++)
{
foreach (var element in _bufferBindingInfos[slot].AttributeInfo.Elements)
_newEnabledVertexAttributes[element.AttributeLocation] = true;
}
}
SetVertexAttributeArray(_newEnabledVertexAttributes);
}
private void PlatformSetup()
{
_programCache = new ShaderProgramCache(this);
#if DESKTOPGL || ANGLE
var windowInfo = new WindowInfo(SdlGameWindow.Instance.Handle);
if (Context == null || Context.IsDisposed)
{
Context = GL.CreateContext(windowInfo);
}
Context.MakeCurrent(windowInfo);
Context.SwapInterval = PresentationParameters.PresentationInterval.GetSwapInterval();
Context.MakeCurrent(windowInfo);
#endif
MaxTextureSlots = 16;
GL.GetInteger(GetPName.MaxTextureImageUnits, out MaxTextureSlots);
GraphicsExtensions.CheckGLError();
GL.GetInteger(GetPName.MaxTextureSize, out _maxTextureSize);
GraphicsExtensions.CheckGLError();
GL.GetInteger(GetPName.MaxVertexAttribs, out MaxVertexAttributes);
GraphicsExtensions.CheckGLError();
_maxVertexBufferSlots = MaxVertexAttributes;
_newEnabledVertexAttributes = new bool[MaxVertexAttributes];
SpriteBatch.NeedsHalfPixelOffset = true;
// try getting the context version
// GL_MAJOR_VERSION and GL_MINOR_VERSION are GL 3.0+ only, so we need to rely on the GL_VERSION string
// for non GLES this string always starts with the version number in the "major.minor" format, but can be followed by
// multiple vendor specific characters
// For GLES this string is formatted as: OpenGL<space>ES<space><version number><space><vendor-specific information>
#if GLES
try
{
string version = GL.GetString(StringName.Version);
if (string.IsNullOrEmpty(version))
throw new NoSuitableGraphicsDeviceException("Unable to retrieve OpenGL version");
string[] versionSplit = version.Split(' ');
if (versionSplit.Length > 2 && versionSplit[0].Equals("OpenGL") && versionSplit[1].Equals("ES"))
{
glMajorVersion = Convert.ToInt32(versionSplit[2].Substring(0, 1));
glMinorVersion = Convert.ToInt32(versionSplit[2].Substring(2, 1));
}
else
{
glMajorVersion = 1;
glMinorVersion = 1;
}
}
catch (FormatException)
{
//if it fails we default to 1.1 context
glMajorVersion = 1;
glMinorVersion = 1;
}
#else
try
{
string version = GL.GetString(StringName.Version);
if (string.IsNullOrEmpty(version))
throw new NoSuitableGraphicsDeviceException("Unable to retrieve OpenGL version");
glMajorVersion = Convert.ToInt32(version.Substring(0, 1));
glMinorVersion = Convert.ToInt32(version.Substring(2, 1));
}
catch (FormatException)
{
// if it fails, we assume to be on a 1.1 context
glMajorVersion = 1;
glMinorVersion = 1;
}
#endif
#if !GLES
// Initialize draw buffer attachment array
int maxDrawBuffers;
GL.GetInteger(GetPName.MaxDrawBuffers, out maxDrawBuffers);
GraphicsExtensions.CheckGLError ();
_drawBuffers = new DrawBuffersEnum[maxDrawBuffers];
for (int i = 0; i < maxDrawBuffers; i++)
_drawBuffers[i] = (DrawBuffersEnum)(FramebufferAttachment.ColorAttachment0Ext + i);
#endif
}
private void PlatformInitialize()
{
_viewport = new Viewport(0, 0, PresentationParameters.BackBufferWidth, PresentationParameters.BackBufferHeight);
// Ensure the vertex attributes are reset
_enabledVertexAttributes.Clear();
// Free all the cached shader programs.
_programCache.Clear();
_shaderProgram = null;
framebufferHelper = FramebufferHelper.Create(this);
// Force resetting states
this.PlatformApplyBlend(true);
this.DepthStencilState.PlatformApplyState(this, true);
this.RasterizerState.PlatformApplyState(this, true);
_bufferBindingInfos = new BufferBindingInfo[_maxVertexBufferSlots];
for (int i = 0; i < _bufferBindingInfos.Length; i++)
_bufferBindingInfos[i] = new BufferBindingInfo(null, IntPtr.Zero, 0, -1);
}
private DepthStencilState clearDepthStencilState = new DepthStencilState { StencilEnable = true };
public void PlatformClear(ClearOptions options, Vector4 color, float depth, int stencil)
{
// TODO: We need to figure out how to detect if we have a
// depth stencil buffer or not, and clear options relating
// to them if not attached.
// Unlike with XNA and DirectX... GL.Clear() obeys several
// different render states:
//
// - The color write flags.
// - The scissor rectangle.
// - The depth/stencil state.
//
// So overwrite these states with what is needed to perform
// the clear correctly and restore it afterwards.
//
var prevScissorRect = ScissorRectangle;
var prevDepthStencilState = DepthStencilState;
var prevBlendState = BlendState;
ScissorRectangle = _viewport.Bounds;
// DepthStencilState.Default has the Stencil Test disabled;
// make sure stencil test is enabled before we clear since
// some drivers won't clear with stencil test disabled
DepthStencilState = this.clearDepthStencilState;
BlendState = BlendState.Opaque;
ApplyState(false);
ClearBufferMask bufferMask = 0;
if ((options & ClearOptions.Target) == ClearOptions.Target)
{
if (color != _lastClearColor)
{
GL.ClearColor(color.X, color.Y, color.Z, color.W);
GraphicsExtensions.CheckGLError();
_lastClearColor = color;
}
bufferMask = bufferMask | ClearBufferMask.ColorBufferBit;
}
if ((options & ClearOptions.Stencil) == ClearOptions.Stencil)
{
if (stencil != _lastClearStencil)
{
GL.ClearStencil(stencil);
GraphicsExtensions.CheckGLError();
_lastClearStencil = stencil;
}
bufferMask = bufferMask | ClearBufferMask.StencilBufferBit;
}
if ((options & ClearOptions.DepthBuffer) == ClearOptions.DepthBuffer)
{
if (depth != _lastClearDepth)
{
GL.ClearDepth(depth);
GraphicsExtensions.CheckGLError();
_lastClearDepth = depth;
}
bufferMask = bufferMask | ClearBufferMask.DepthBufferBit;
}
#if MONOMAC
if (GL.CheckFramebufferStatus(FramebufferTarget.FramebufferExt) == FramebufferErrorCode.FramebufferComplete)
{
#endif
GL.Clear(bufferMask);
GraphicsExtensions.CheckGLError();
#if MONOMAC
}
#endif
// Restore the previous render state.
ScissorRectangle = prevScissorRect;
DepthStencilState = prevDepthStencilState;
BlendState = prevBlendState;
}
private void PlatformDispose()
{
// Free all the cached shader programs.
_programCache.Dispose();
#if DESKTOPGL || ANGLE
Context.Dispose();
Context = null;
#endif
}
internal void DisposeTexture(int handle)
{
if (!_isDisposed)
{
lock (_disposeActionsLock)
{
_disposeNextFrame.Add(ResourceHandle.Texture(handle));
}
}
}
internal void DisposeBuffer(int handle)
{
if (!_isDisposed)
{
lock (_disposeActionsLock)
{
_disposeNextFrame.Add(ResourceHandle.Buffer(handle));
}
}
}
internal void DisposeShader(int handle)
{
if (!_isDisposed)
{
lock (_disposeActionsLock)
{
_disposeNextFrame.Add(ResourceHandle.Shader(handle));
}
}
}
internal void DisposeProgram(int handle)
{
if (!_isDisposed)
{
lock (_disposeActionsLock)
{
_disposeNextFrame.Add(ResourceHandle.Program(handle));
}
}
}
internal void DisposeQuery(int handle)
{
if (!_isDisposed)
{
lock (_disposeActionsLock)
{
_disposeNextFrame.Add(ResourceHandle.Query(handle));
}
}
}
internal void DisposeFramebuffer(int handle)
{
if (!_isDisposed)
{
lock (_disposeActionsLock)
{
_disposeNextFrame.Add(ResourceHandle.Framebuffer(handle));
}
}
}
#if DESKTOPGL || ANGLE
static internal void DisposeContext(IntPtr resource)
{
lock (_disposeContextsLock)
{
_disposeContexts.Add(resource);
}
}
static internal void DisposeContexts()
{
lock (_disposeContextsLock)
{
int count = _disposeContexts.Count;
for (int i = 0; i < count; ++i)
Sdl.GL.DeleteContext(_disposeContexts[i]);
_disposeContexts.Clear();
}
}
#endif
public void PlatformPresent()
{
#if DESKTOPGL || ANGLE
Context.SwapBuffers();
#endif
GraphicsExtensions.CheckGLError();
// Dispose of any GL resources that were disposed in another thread
int count = _disposeThisFrame.Count;
for (int i = 0; i < count; ++i)
_disposeThisFrame[i].Free();
_disposeThisFrame.Clear();
lock (_disposeActionsLock)
{
// Swap lists so resources added during this draw will be released after the next draw
var temp = _disposeThisFrame;
_disposeThisFrame = _disposeNextFrame;
_disposeNextFrame = temp;
}
}
private void PlatformSetViewport(ref Viewport value)
{
if (IsRenderTargetBound)
GL.Viewport(value.X, value.Y, value.Width, value.Height);
else
GL.Viewport(value.X, PresentationParameters.BackBufferHeight - value.Y - value.Height, value.Width, value.Height);
GraphicsExtensions.LogGLError("GraphicsDevice.Viewport_set() GL.Viewport");
GL.DepthRange(value.MinDepth, value.MaxDepth);
GraphicsExtensions.LogGLError("GraphicsDevice.Viewport_set() GL.DepthRange");
// In OpenGL we have to re-apply the special "posFixup"
// vertex shader uniform if the viewport changes.
_vertexShaderDirty = true;
}
private void PlatformApplyDefaultRenderTarget()
{
this.framebufferHelper.BindFramebuffer(this.glFramebuffer);
// Reset the raster state because we flip vertices
// when rendering offscreen and hence the cull direction.
_rasterizerStateDirty = true;
// Textures will need to be rebound to render correctly in the new render target.
Textures.Dirty();
}
private class RenderTargetBindingArrayComparer : IEqualityComparer<RenderTargetBinding[]>
{
public bool Equals(RenderTargetBinding[] first, RenderTargetBinding[] second)
{
if (object.ReferenceEquals(first, second))
return true;
if (first == null || second == null)
return false;
if (first.Length != second.Length)
return false;
for (var i = 0; i < first.Length; ++i)
{
if ((first[i].RenderTarget != second[i].RenderTarget) || (first[i].ArraySlice != second[i].ArraySlice))
{
return false;
}
}
return true;
}
public int GetHashCode(RenderTargetBinding[] array)
{
if (array != null)
{
unchecked
{
int hash = 17;
foreach (var item in array)
{
if (item.RenderTarget != null)
hash = hash * 23 + item.RenderTarget.GetHashCode();
hash = hash * 23 + item.ArraySlice.GetHashCode();
}
return hash;
}
}
return 0;
}
}
// FBO cache, we create 1 FBO per RenderTargetBinding combination
private Dictionary<RenderTargetBinding[], int> glFramebuffers = new Dictionary<RenderTargetBinding[], int>(new RenderTargetBindingArrayComparer());
// FBO cache used to resolve MSAA rendertargets, we create 1 FBO per RenderTargetBinding combination
private Dictionary<RenderTargetBinding[], int> glResolveFramebuffers = new Dictionary<RenderTargetBinding[], int>(new RenderTargetBindingArrayComparer());
internal void PlatformCreateRenderTarget(IRenderTarget renderTarget, int width, int height, bool mipMap, SurfaceFormat preferredFormat, DepthFormat preferredDepthFormat, int preferredMultiSampleCount, RenderTargetUsage usage)
{
var color = 0;
var depth = 0;
var stencil = 0;
if (preferredMultiSampleCount > 0 && this.framebufferHelper.SupportsBlitFramebuffer)
{
this.framebufferHelper.GenRenderbuffer(out color);
this.framebufferHelper.BindRenderbuffer(color);
this.framebufferHelper.RenderbufferStorageMultisample(preferredMultiSampleCount, (int)RenderbufferStorage.Rgba8, width, height);
}
if (preferredDepthFormat != DepthFormat.None)
{
var depthInternalFormat = RenderbufferStorage.DepthComponent16;
var stencilInternalFormat = (RenderbufferStorage)0;
switch (preferredDepthFormat)
{
case DepthFormat.Depth16:
depthInternalFormat = RenderbufferStorage.DepthComponent16;
break;
#if GLES
case DepthFormat.Depth24:
if (GraphicsCapabilities.SupportsDepth24)
depthInternalFormat = RenderbufferStorage.DepthComponent24;
else if (GraphicsCapabilities.SupportsDepthNonLinear)
depthInternalFormat = (RenderbufferStorage)0x8E2C;
else
depthInternalFormat = RenderbufferStorage.DepthComponent16;
break;
case DepthFormat.Depth24Stencil8:
if (GraphicsCapabilities.SupportsPackedDepthStencil)
depthInternalFormat = RenderbufferStorage.Depth24Stencil8;
else
{
if (GraphicsCapabilities.SupportsDepth24)
depthInternalFormat = RenderbufferStorage.DepthComponent24;
else if (GraphicsCapabilities.SupportsDepthNonLinear)
depthInternalFormat = (RenderbufferStorage)0x8E2C;
else
depthInternalFormat = RenderbufferStorage.DepthComponent16;
stencilInternalFormat = RenderbufferStorage.StencilIndex8;
break;
}
break;
#else
case DepthFormat.Depth24:
depthInternalFormat = RenderbufferStorage.DepthComponent24;
break;
case DepthFormat.Depth24Stencil8:
depthInternalFormat = RenderbufferStorage.Depth24Stencil8;
break;
#endif
}
if (depthInternalFormat != 0)
{
this.framebufferHelper.GenRenderbuffer(out depth);
this.framebufferHelper.BindRenderbuffer(depth);
this.framebufferHelper.RenderbufferStorageMultisample(preferredMultiSampleCount, (int)depthInternalFormat, width, height);
if (preferredDepthFormat == DepthFormat.Depth24Stencil8)
{
stencil = depth;
if (stencilInternalFormat != 0)
{
this.framebufferHelper.GenRenderbuffer(out stencil);
this.framebufferHelper.BindRenderbuffer(stencil);
this.framebufferHelper.RenderbufferStorageMultisample(preferredMultiSampleCount, (int)stencilInternalFormat, width, height);
}
}
}
}
if (color != 0)
renderTarget.GLColorBuffer = color;
else
renderTarget.GLColorBuffer = renderTarget.GLTexture;
renderTarget.GLDepthBuffer = depth;
renderTarget.GLStencilBuffer = stencil;
}
internal void PlatformDeleteRenderTarget(IRenderTarget renderTarget)
{
var color = 0;
var depth = 0;
var stencil = 0;
var colorIsRenderbuffer = false;
color = renderTarget.GLColorBuffer;
depth = renderTarget.GLDepthBuffer;
stencil = renderTarget.GLStencilBuffer;
colorIsRenderbuffer = color != renderTarget.GLTexture;
if (color != 0)
{
if (colorIsRenderbuffer)
this.framebufferHelper.DeleteRenderbuffer(color);
if (stencil != 0 && stencil != depth)
this.framebufferHelper.DeleteRenderbuffer(stencil);
if (depth != 0)
this.framebufferHelper.DeleteRenderbuffer(depth);
var bindingsToDelete = new List<RenderTargetBinding[]>();
foreach (var bindings in this.glFramebuffers.Keys)
{
foreach (var binding in bindings)
{
if (binding.RenderTarget == renderTarget)
{
bindingsToDelete.Add(bindings);
break;
}
}
}
foreach (var bindings in bindingsToDelete)
{
var fbo = 0;
if (this.glFramebuffers.TryGetValue(bindings, out fbo))
{
this.framebufferHelper.DeleteFramebuffer(fbo);
this.glFramebuffers.Remove(bindings);
}
if (this.glResolveFramebuffers.TryGetValue(bindings, out fbo))
{
this.framebufferHelper.DeleteFramebuffer(fbo);
this.glResolveFramebuffers.Remove(bindings);
}
}
}
}
private void PlatformResolveRenderTargets()
{
if (this._currentRenderTargetCount == 0)
return;
var renderTargetBinding = this._currentRenderTargetBindings[0];
var renderTarget = renderTargetBinding.RenderTarget as IRenderTarget;
if (renderTarget.MultiSampleCount > 0 && this.framebufferHelper.SupportsBlitFramebuffer)
{
var glResolveFramebuffer = 0;
if (!this.glResolveFramebuffers.TryGetValue(this._currentRenderTargetBindings, out glResolveFramebuffer))
{
this.framebufferHelper.GenFramebuffer(out glResolveFramebuffer);
this.framebufferHelper.BindFramebuffer(glResolveFramebuffer);
for (var i = 0; i < this._currentRenderTargetCount; ++i)
{
var rt = this._currentRenderTargetBindings[i].RenderTarget as IRenderTarget;
this.framebufferHelper.FramebufferTexture2D((int)(FramebufferAttachment.ColorAttachment0 + i), (int) rt.GetFramebufferTarget(renderTargetBinding), rt.GLTexture);
}
this.glResolveFramebuffers.Add((RenderTargetBinding[])this._currentRenderTargetBindings.Clone(), glResolveFramebuffer);
}
else
{
this.framebufferHelper.BindFramebuffer(glResolveFramebuffer);
}
// The only fragment operations which affect the resolve are the pixel ownership test, the scissor test, and dithering.
if (this._lastRasterizerState.ScissorTestEnable)
{
GL.Disable(EnableCap.ScissorTest);
GraphicsExtensions.CheckGLError();
}
var glFramebuffer = this.glFramebuffers[this._currentRenderTargetBindings];
this.framebufferHelper.BindReadFramebuffer(glFramebuffer);
for (var i = 0; i < this._currentRenderTargetCount; ++i)
{
renderTargetBinding = this._currentRenderTargetBindings[i];
renderTarget = renderTargetBinding.RenderTarget as IRenderTarget;
this.framebufferHelper.BlitFramebuffer(i, renderTarget.Width, renderTarget.Height);
}
if (renderTarget.RenderTargetUsage == RenderTargetUsage.DiscardContents && this.framebufferHelper.SupportsInvalidateFramebuffer)
this.framebufferHelper.InvalidateReadFramebuffer();
if (this._lastRasterizerState.ScissorTestEnable)
{
GL.Enable(EnableCap.ScissorTest);
GraphicsExtensions.CheckGLError();
}
}
for (var i = 0; i < this._currentRenderTargetCount; ++i)
{
renderTargetBinding = this._currentRenderTargetBindings[i];
renderTarget = renderTargetBinding.RenderTarget as IRenderTarget;
if (renderTarget.LevelCount > 1)
{
GL.BindTexture((TextureTarget)renderTarget.GLTarget, renderTarget.GLTexture);
GraphicsExtensions.CheckGLError();
this.framebufferHelper.GenerateMipmap((int)renderTarget.GLTarget);
}
}
}
private IRenderTarget PlatformApplyRenderTargets()
{
var glFramebuffer = 0;
if (!this.glFramebuffers.TryGetValue(this._currentRenderTargetBindings, out glFramebuffer))
{
this.framebufferHelper.GenFramebuffer(out glFramebuffer);
this.framebufferHelper.BindFramebuffer(glFramebuffer);
var renderTargetBinding = this._currentRenderTargetBindings[0];
var renderTarget = renderTargetBinding.RenderTarget as IRenderTarget;
this.framebufferHelper.FramebufferRenderbuffer((int)FramebufferAttachment.DepthAttachment, renderTarget.GLDepthBuffer, 0);
this.framebufferHelper.FramebufferRenderbuffer((int)FramebufferAttachment.StencilAttachment, renderTarget.GLStencilBuffer, 0);
for (var i = 0; i < this._currentRenderTargetCount; ++i)
{
renderTargetBinding = this._currentRenderTargetBindings[i];
renderTarget = renderTargetBinding.RenderTarget as IRenderTarget;
var attachement = (int)(FramebufferAttachment.ColorAttachment0 + i);
if (renderTarget.GLColorBuffer != renderTarget.GLTexture)
this.framebufferHelper.FramebufferRenderbuffer(attachement, renderTarget.GLColorBuffer, 0);
else
this.framebufferHelper.FramebufferTexture2D(attachement, (int)renderTarget.GetFramebufferTarget(renderTargetBinding), renderTarget.GLTexture, 0, renderTarget.MultiSampleCount);
}
#if DEBUG
this.framebufferHelper.CheckFramebufferStatus();
#endif
this.glFramebuffers.Add((RenderTargetBinding[])_currentRenderTargetBindings.Clone(), glFramebuffer);
}
else
{
this.framebufferHelper.BindFramebuffer(glFramebuffer);
}
#if !GLES
GL.DrawBuffers(this._currentRenderTargetCount, this._drawBuffers);
#endif
// Reset the raster state because we flip vertices
// when rendering offscreen and hence the cull direction.
_rasterizerStateDirty = true;
// Textures will need to be rebound to render correctly in the new render target.
Textures.Dirty();
return _currentRenderTargetBindings[0].RenderTarget as IRenderTarget;
}
private static GLPrimitiveType PrimitiveTypeGL(PrimitiveType primitiveType)
{
switch (primitiveType)
{
case PrimitiveType.LineList:
return GLPrimitiveType.Lines;
case PrimitiveType.LineStrip:
return GLPrimitiveType.LineStrip;
case PrimitiveType.TriangleList:
return GLPrimitiveType.Triangles;
case PrimitiveType.TriangleStrip:
return GLPrimitiveType.TriangleStrip;
}
throw new ArgumentException();
}
/// <summary>
/// Activates the Current Vertex/Pixel shader pair into a program.
/// </summary>
private unsafe void ActivateShaderProgram()
{
// Lookup the shader program.
var shaderProgram = _programCache.GetProgram(VertexShader, PixelShader);
if (shaderProgram.Program == -1)
return;
// Set the new program if it has changed.
if (_shaderProgram != shaderProgram)
{
GL.UseProgram(shaderProgram.Program);
GraphicsExtensions.CheckGLError();
_shaderProgram = shaderProgram;
}
var posFixupLoc = shaderProgram.GetUniformLocation("posFixup");
if (posFixupLoc == -1)
return;
// Apply vertex shader fix:
// The following two lines are appended to the end of vertex shaders
// to account for rendering differences between OpenGL and DirectX:
//
// gl_Position.y = gl_Position.y * posFixup.y;
// gl_Position.xy += posFixup.zw * gl_Position.ww;
//
// (the following paraphrased from wine, wined3d/state.c and wined3d/glsl_shader.c)
//
// - We need to flip along the y-axis in case of offscreen rendering.
// - D3D coordinates refer to pixel centers while GL coordinates refer
// to pixel corners.
// - D3D has a top-left filling convention. We need to maintain this
// even after the y-flip mentioned above.
// In order to handle the last two points, we translate by
// (63.0 / 128.0) / VPw and (63.0 / 128.0) / VPh. This is equivalent to
// translating slightly less than half a pixel. We want the difference to
// be large enough that it doesn't get lost due to rounding inside the
// driver, but small enough to prevent it from interfering with any
// anti-aliasing.
//
// OpenGL coordinates specify the center of the pixel while d3d coords specify
// the corner. The offsets are stored in z and w in posFixup. posFixup.y contains
// 1.0 or -1.0 to turn the rendering upside down for offscreen rendering. PosFixup.x
// contains 1.0 to allow a mad.
_posFixup[0] = 1.0f;
_posFixup[1] = 1.0f;
_posFixup[2] = (63.0f/64.0f)/Viewport.Width;
_posFixup[3] = -(63.0f/64.0f)/Viewport.Height;
//If we have a render target bound (rendering offscreen)
if (IsRenderTargetBound)
{
//flip vertically
_posFixup[1] *= -1.0f;
_posFixup[3] *= -1.0f;
}
fixed (float* floatPtr = _posFixup)
{
GL.Uniform4(posFixupLoc, 1, floatPtr);
}
GraphicsExtensions.CheckGLError();
}
internal void PlatformBeginApplyState()
{
Threading.EnsureUIThread();
}
private void PlatformApplyBlend(bool force = false)
{
_actualBlendState.PlatformApplyState(this, force);
ApplyBlendFactor(force);
}
private void ApplyBlendFactor(bool force)
{
if (force || BlendFactor != _lastBlendState.BlendFactor)
{
GL.BlendColor(
this.BlendFactor.R/255.0f,
this.BlendFactor.G/255.0f,
this.BlendFactor.B/255.0f,
this.BlendFactor.A/255.0f);
GraphicsExtensions.CheckGLError();
_lastBlendState.BlendFactor = this.BlendFactor;
}
}
internal void PlatformApplyState(bool applyShaders)
{
if ( _scissorRectangleDirty )
{
var scissorRect = _scissorRectangle;
if (!IsRenderTargetBound)
scissorRect.Y = PresentationParameters.BackBufferHeight - (scissorRect.Y + scissorRect.Height);
GL.Scissor(scissorRect.X, scissorRect.Y, scissorRect.Width, scissorRect.Height);
GraphicsExtensions.CheckGLError();
_scissorRectangleDirty = false;
}
// If we're not applying shaders then early out now.
if (!applyShaders)
return;
if (_indexBufferDirty)
{
if (_indexBuffer != null)
{
GL.BindBuffer(BufferTarget.ElementArrayBuffer, _indexBuffer.ibo);
GraphicsExtensions.CheckGLError();
}
_indexBufferDirty = false;
}
if (_vertexShader == null)
throw new InvalidOperationException("A vertex shader must be set!");
if (_pixelShader == null)
throw new InvalidOperationException("A pixel shader must be set!");
if (_vertexShaderDirty || _pixelShaderDirty)
{
ActivateShaderProgram();
if (_vertexShaderDirty)
{
unchecked
{
_graphicsMetrics._vertexShaderCount++;
}
}
if (_pixelShaderDirty)
{
unchecked
{
_graphicsMetrics._pixelShaderCount++;
}
}
_vertexShaderDirty = _pixelShaderDirty = false;
}
_vertexConstantBuffers.SetConstantBuffers(this, _shaderProgram);
_pixelConstantBuffers.SetConstantBuffers(this, _shaderProgram);
Textures.SetTextures(this);
SamplerStates.PlatformSetSamplers(this);
}
private void PlatformDrawIndexedPrimitives(PrimitiveType primitiveType, int baseVertex, int startIndex, int primitiveCount)
{
ApplyState(true);
var shortIndices = _indexBuffer.IndexElementSize == IndexElementSize.SixteenBits;
var indexElementType = shortIndices ? DrawElementsType.UnsignedShort : DrawElementsType.UnsignedInt;
var indexElementSize = shortIndices ? 2 : 4;
var indexOffsetInBytes = (IntPtr)(startIndex * indexElementSize);
var indexElementCount = GetElementCountArray(primitiveType, primitiveCount);
var target = PrimitiveTypeGL(primitiveType);
ApplyAttribs(_vertexShader, baseVertex);
GL.DrawElements(target,
indexElementCount,
indexElementType,
indexOffsetInBytes);
GraphicsExtensions.CheckGLError();
}
private void PlatformDrawUserPrimitives<T>(PrimitiveType primitiveType, T[] vertexData, int vertexOffset, VertexDeclaration vertexDeclaration, int vertexCount) where T : struct
{
ApplyState(true);
// Unbind current VBOs.
GL.BindBuffer(BufferTarget.ArrayBuffer, 0);
GraphicsExtensions.CheckGLError();
GL.BindBuffer(BufferTarget.ElementArrayBuffer, 0);
GraphicsExtensions.CheckGLError();
_indexBufferDirty = true;
// Pin the buffers.
var vbHandle = GCHandle.Alloc(vertexData, GCHandleType.Pinned);
// Setup the vertex declaration to point at the VB data.
vertexDeclaration.GraphicsDevice = this;
vertexDeclaration.Apply(_vertexShader, vbHandle.AddrOfPinnedObject(), ShaderProgramHash);
//Draw
GL.DrawArrays(PrimitiveTypeGL(primitiveType),
vertexOffset,
vertexCount);
GraphicsExtensions.CheckGLError();
// Release the handles.
vbHandle.Free();
}
private void PlatformDrawPrimitives(PrimitiveType primitiveType, int vertexStart, int vertexCount)
{
ApplyState(true);
ApplyAttribs(_vertexShader, 0);
if (vertexStart < 0)
vertexStart = 0;
GL.DrawArrays(PrimitiveTypeGL(primitiveType),
vertexStart,
vertexCount);
GraphicsExtensions.CheckGLError();
}
private void PlatformDrawUserIndexedPrimitives<T>(PrimitiveType primitiveType, T[] vertexData, int vertexOffset, int numVertices, short[] indexData, int indexOffset, int primitiveCount, VertexDeclaration vertexDeclaration) where T : struct
{
ApplyState(true);
// Unbind current VBOs.
GL.BindBuffer(BufferTarget.ArrayBuffer, 0);
GraphicsExtensions.CheckGLError();
GL.BindBuffer(BufferTarget.ElementArrayBuffer, 0);
GraphicsExtensions.CheckGLError();
_indexBufferDirty = true;
// Pin the buffers.
var vbHandle = GCHandle.Alloc(vertexData, GCHandleType.Pinned);
var ibHandle = GCHandle.Alloc(indexData, GCHandleType.Pinned);
var vertexAddr = (IntPtr)(vbHandle.AddrOfPinnedObject().ToInt64() + vertexDeclaration.VertexStride * vertexOffset);
// Setup the vertex declaration to point at the VB data.
vertexDeclaration.GraphicsDevice = this;
vertexDeclaration.Apply(_vertexShader, vertexAddr, ShaderProgramHash);
//Draw
GL.DrawElements( PrimitiveTypeGL(primitiveType),
GetElementCountArray(primitiveType, primitiveCount),
DrawElementsType.UnsignedShort,
(IntPtr)(ibHandle.AddrOfPinnedObject().ToInt64() + (indexOffset * sizeof(short))));
GraphicsExtensions.CheckGLError();
// Release the handles.
ibHandle.Free();
vbHandle.Free();
}
private void PlatformDrawUserIndexedPrimitives<T>(PrimitiveType primitiveType, T[] vertexData, int vertexOffset, int numVertices, int[] indexData, int indexOffset, int primitiveCount, VertexDeclaration vertexDeclaration) where T : struct
{
ApplyState(true);
// Unbind current VBOs.
GL.BindBuffer(BufferTarget.ArrayBuffer, 0);
GraphicsExtensions.CheckGLError();
GL.BindBuffer(BufferTarget.ElementArrayBuffer, 0);
GraphicsExtensions.CheckGLError();
_indexBufferDirty = true;
// Pin the buffers.
var vbHandle = GCHandle.Alloc(vertexData, GCHandleType.Pinned);
var ibHandle = GCHandle.Alloc(indexData, GCHandleType.Pinned);
var vertexAddr = (IntPtr)(vbHandle.AddrOfPinnedObject().ToInt64() + vertexDeclaration.VertexStride * vertexOffset);
// Setup the vertex declaration to point at the VB data.
vertexDeclaration.GraphicsDevice = this;
vertexDeclaration.Apply(_vertexShader, vertexAddr, ShaderProgramHash);
//Draw
GL.DrawElements( PrimitiveTypeGL(primitiveType),
GetElementCountArray(primitiveType, primitiveCount),
DrawElementsType.UnsignedInt,
(IntPtr)(ibHandle.AddrOfPinnedObject().ToInt64() + (indexOffset * sizeof(int))));
GraphicsExtensions.CheckGLError();
// Release the handles.
ibHandle.Free();
vbHandle.Free();
}
private void PlatformDrawInstancedPrimitives(PrimitiveType primitiveType, int baseVertex, int startIndex, int primitiveCount, int instanceCount)
{
if (!GraphicsCapabilities.SupportsInstancing)
throw new PlatformNotSupportedException("Instanced geometry drawing requires at least OpenGL 3.2 or GLES 3.2. Try upgrading your graphics card drivers.");
ApplyState(true);
var shortIndices = _indexBuffer.IndexElementSize == IndexElementSize.SixteenBits;
var indexElementType = shortIndices ? DrawElementsType.UnsignedShort : DrawElementsType.UnsignedInt;
var indexElementSize = shortIndices ? 2 : 4;
var indexOffsetInBytes = (IntPtr)(startIndex * indexElementSize);
var indexElementCount = GetElementCountArray(primitiveType, primitiveCount);
var target = PrimitiveTypeGL(primitiveType);
ApplyAttribs(_vertexShader, baseVertex);
GL.DrawElementsInstanced(target,
indexElementCount,
indexElementType,
indexOffsetInBytes,
instanceCount);
GraphicsExtensions.CheckGLError();
}
private void PlatformGetBackBufferData<T>(Rectangle? rectangle, T[] data, int startIndex, int count) where T : struct
{
var rect = rectangle ?? new Rectangle(0, 0, PresentationParameters.BackBufferWidth, PresentationParameters.BackBufferHeight);
var tSize = Marshal.SizeOf(typeof(T));
var flippedY = PresentationParameters.BackBufferHeight - rect.Y - rect.Height;
GL.ReadPixels(rect.X, flippedY, rect.Width, rect.Height, PixelFormat.Rgba, PixelType.UnsignedByte, data);
// buffer is returned upside down, so we swap the rows around when copying over
var rowSize = rect.Width*PresentationParameters.BackBufferFormat.GetSize() / tSize;
var row = new T[rowSize];
for (var dy = 0; dy < rect.Height/2; dy++)
{
var topRow = startIndex + dy*rowSize;
var bottomRow = startIndex + (rect.Height - dy - 1)*rowSize;
// copy the bottom row to buffer
Array.Copy(data, bottomRow, row, 0, rowSize);
// copy top row to bottom row
Array.Copy(data, topRow, data, bottomRow, rowSize);
// copy buffer to top row
Array.Copy(row, 0, data, topRow, rowSize);
count -= rowSize;
}
}
private static Rectangle PlatformGetTitleSafeArea(int x, int y, int width, int height)
{
return new Rectangle(x, y, width, height);
}
internal void PlatformSetMultiSamplingToMaximum(PresentationParameters presentationParameters, out int quality)
{
presentationParameters.MultiSampleCount = 4;
quality = 0;
}
internal void OnPresentationChanged()
{
#if DESKTOPGL || ANGLE
Context.MakeCurrent(new WindowInfo(SdlGameWindow.Instance.Handle));
Context.SwapInterval = PresentationParameters.PresentationInterval.GetSwapInterval();
#endif
ApplyRenderTargets(null);
}
// Holds information for caching
private class BufferBindingInfo
{
public VertexDeclaration.VertexDeclarationAttributeInfo AttributeInfo;
public IntPtr VertexOffset;
public int InstanceFrequency;
public int Vbo;
public BufferBindingInfo(VertexDeclaration.VertexDeclarationAttributeInfo attributeInfo, IntPtr vertexOffset, int instanceFrequency, int vbo)
{
AttributeInfo = attributeInfo;
VertexOffset = vertexOffset;
InstanceFrequency = instanceFrequency;
Vbo = vbo;
}
}
#if DESKTOPGL
private void GetModeSwitchedSize(out int width, out int height)
{
var mode = new Sdl.Display.Mode
{
Width = PresentationParameters.BackBufferWidth,
Height = PresentationParameters.BackBufferHeight,
Format = 0,
RefreshRate = 0,
DriverData = IntPtr.Zero
};
Sdl.Display.Mode closest;
Sdl.Display.GetClosestDisplayMode(0, mode, out closest);
width = closest.Width;
height = closest.Height;
}
private void GetDisplayResolution(out int width, out int height)
{
Sdl.Display.Mode mode;
Sdl.Display.GetCurrentDisplayMode(0, out mode);
width = mode.Width;
height = mode.Height;
}
#endif
}
}
| 40.856809 | 247 | 0.567399 | [
"MPL-2.0",
"MPL-2.0-no-copyleft-exception"
] | HarryFreeMyLand/FML-Rebase | Other/libs/FSOMonoGame/MonoGame.Framework/Graphics/GraphicsDevice.OpenGL.cs | 52,501 | 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 mediastore-2017-09-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.MediaStore.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using ThirdParty.Json.LitJson;
namespace Amazon.MediaStore.Model.Internal.MarshallTransformations
{
/// <summary>
/// Response Unmarshaller for ContainerInUseException Object
/// </summary>
public class ContainerInUseExceptionUnmarshaller : IErrorResponseUnmarshaller<ContainerInUseException, JsonUnmarshallerContext>
{
/// <summary>
/// Unmarshaller the response from the service to the response class.
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
public ContainerInUseException Unmarshall(JsonUnmarshallerContext context)
{
return this.Unmarshall(context, new ErrorResponse());
}
/// <summary>
/// Unmarshaller the response from the service to the response class.
/// </summary>
/// <param name="context"></param>
/// <param name="errorResponse"></param>
/// <returns></returns>
public ContainerInUseException Unmarshall(JsonUnmarshallerContext context, ErrorResponse errorResponse)
{
context.Read();
ContainerInUseException unmarshalledObject = new ContainerInUseException(errorResponse.Message, errorResponse.InnerException,
errorResponse.Type, errorResponse.Code, errorResponse.RequestId, errorResponse.StatusCode);
int targetDepth = context.CurrentDepth;
while (context.ReadAtDepth(targetDepth))
{
}
return unmarshalledObject;
}
private static ContainerInUseExceptionUnmarshaller _instance = new ContainerInUseExceptionUnmarshaller();
/// <summary>
/// Gets the singleton.
/// </summary>
public static ContainerInUseExceptionUnmarshaller Instance
{
get
{
return _instance;
}
}
}
} | 35.752941 | 138 | 0.65153 | [
"Apache-2.0"
] | philasmar/aws-sdk-net | sdk/src/Services/MediaStore/Generated/Model/Internal/MarshallTransformations/ContainerInUseExceptionUnmarshaller.cs | 3,039 | C# |
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Collections.Generic;
using System.Linq;
namespace Spoj.Solver.UnitTests.Solutions._7___Immortal
{
[TestClass]
public sealed class ASSIGNTests : SolutionTestsBase
{
public override string SolutionSource => Solver.Solutions.ASSIGN;
public override IReadOnlyList<string> TestInputs => new[]
{
@"3
3
1 1 1
1 1 1
1 1 1
11
1 0 0 1 0 0 0 0 0 1 1
1 1 1 1 1 0 1 0 1 0 0
1 0 0 1 0 0 1 1 0 1 0
1 0 1 1 1 0 1 1 0 1 1
0 1 1 1 0 1 0 0 1 1 1
1 1 1 0 0 1 0 0 0 0 0
0 0 0 0 1 0 1 0 0 0 1
1 0 1 1 0 0 0 0 0 0 1
0 0 1 0 1 1 0 0 0 1 1
1 1 1 0 0 0 1 0 1 0 1
1 0 0 0 1 1 1 1 0 0 0
11
0 1 1 1 0 1 0 0 0 1 0
0 0 1 1 1 1 1 1 1 1 1
1 1 0 1 0 0 0 0 0 1 0
0 1 0 1 0 1 0 1 0 1 1
1 0 0 1 0 0 0 0 1 0 1
0 0 1 0 1 1 0 0 0 0 1
1 0 1 0 1 1 1 0 1 1 0
1 0 1 1 0 1 1 0 0 1 0
0 0 1 1 0 1 1 1 1 1 1
0 1 0 0 0 0 0 0 0 1 1
0 1 1 0 0 0 0 0 1 0 1"
};
public override IReadOnlyList<string> TestOutputs => new[]
{
@"6
7588
7426
"
// For performance reasons FastIO new lines are \n instead of \r\n.
}.Select(o => o.Replace(Environment.NewLine, "\n")).ToArray();
[TestMethod]
public void ASSIGN() => TestSolution();
}
}
| 21.59322 | 75 | 0.587127 | [
"MIT"
] | davghouse/Daves.SpojSpace | Spoj.Solver.UnitTests/Solutions/7 - Immortal/ASSIGNTests.cs | 1,276 | C# |
using UnityEngine;
namespace MazeObjects
{
class Start : FeatureObject
{
GameObject start;
Maze maze;
public GameObject StartPrefab { get; private set; }
public Start(int xCoord, int yCoord, Maze maze) : base(xCoord, yCoord)
{
this.maze = maze;
StartPrefab = (GameObject)Resources.Load("Prefabs/Maze/Start");
Build();
}
// Kill object from game
public override void KillObject()
{
Object.Destroy(start);
}
// Builds object in unity
public override void Build()
{
start = Object.Instantiate(StartPrefab, new Vector3(X + 0.5f, 0.1f, Y + 0.5f), Quaternion.identity);
}
// Update is called once per frame
public override void Update()
{
return;
}
}
}
| 22.615385 | 112 | 0.539683 | [
"MIT"
] | KevinLi3/GyroscopeMaze | SE101 Unity Physics/Assets/Scripts/MazeObjects/Start.cs | 882 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// <auto-generated/>
#nullable disable
using System;
using System.Collections.Generic;
using System.Text.Json;
using Azure.Core;
namespace Azure.Analytics.Synapse.Artifacts.Models
{
public partial class BigDataPoolResourceInfo : IUtf8JsonSerializable
{
void IUtf8JsonSerializable.Write(Utf8JsonWriter writer)
{
writer.WriteStartObject();
if (Optional.IsCollectionDefined(Tags))
{
writer.WritePropertyName("tags");
writer.WriteStartObject();
foreach (var item in Tags)
{
writer.WritePropertyName(item.Key);
writer.WriteStringValue(item.Value);
}
writer.WriteEndObject();
}
writer.WritePropertyName("location");
writer.WriteStringValue(Location);
writer.WritePropertyName("properties");
writer.WriteStartObject();
if (Optional.IsDefined(ProvisioningState))
{
writer.WritePropertyName("provisioningState");
writer.WriteStringValue(ProvisioningState);
}
if (Optional.IsDefined(AutoScale))
{
writer.WritePropertyName("autoScale");
writer.WriteObjectValue(AutoScale);
}
if (Optional.IsDefined(CreationDate))
{
writer.WritePropertyName("creationDate");
writer.WriteStringValue(CreationDate.Value, "O");
}
if (Optional.IsDefined(AutoPause))
{
writer.WritePropertyName("autoPause");
writer.WriteObjectValue(AutoPause);
}
if (Optional.IsDefined(IsComputeIsolationEnabled))
{
writer.WritePropertyName("isComputeIsolationEnabled");
writer.WriteBooleanValue(IsComputeIsolationEnabled.Value);
}
if (Optional.IsDefined(HaveLibraryRequirementsChanged))
{
writer.WritePropertyName("haveLibraryRequirementsChanged");
writer.WriteBooleanValue(HaveLibraryRequirementsChanged.Value);
}
if (Optional.IsDefined(SessionLevelPackagesEnabled))
{
writer.WritePropertyName("sessionLevelPackagesEnabled");
writer.WriteBooleanValue(SessionLevelPackagesEnabled.Value);
}
if (Optional.IsDefined(SparkEventsFolder))
{
writer.WritePropertyName("sparkEventsFolder");
writer.WriteStringValue(SparkEventsFolder);
}
if (Optional.IsDefined(NodeCount))
{
writer.WritePropertyName("nodeCount");
writer.WriteNumberValue(NodeCount.Value);
}
if (Optional.IsDefined(LibraryRequirements))
{
writer.WritePropertyName("libraryRequirements");
writer.WriteObjectValue(LibraryRequirements);
}
if (Optional.IsDefined(SparkConfigProperties))
{
writer.WritePropertyName("sparkConfigProperties");
writer.WriteObjectValue(SparkConfigProperties);
}
if (Optional.IsDefined(SparkVersion))
{
writer.WritePropertyName("sparkVersion");
writer.WriteStringValue(SparkVersion);
}
if (Optional.IsDefined(DefaultSparkLogFolder))
{
writer.WritePropertyName("defaultSparkLogFolder");
writer.WriteStringValue(DefaultSparkLogFolder);
}
if (Optional.IsDefined(NodeSize))
{
writer.WritePropertyName("nodeSize");
writer.WriteStringValue(NodeSize.Value.ToString());
}
if (Optional.IsDefined(NodeSizeFamily))
{
writer.WritePropertyName("nodeSizeFamily");
writer.WriteStringValue(NodeSizeFamily.Value.ToString());
}
writer.WriteEndObject();
writer.WriteEndObject();
}
internal static BigDataPoolResourceInfo DeserializeBigDataPoolResourceInfo(JsonElement element)
{
Optional<IDictionary<string, string>> tags = default;
string location = default;
Optional<string> id = default;
Optional<string> name = default;
Optional<string> type = default;
Optional<string> provisioningState = default;
Optional<AutoScaleProperties> autoScale = default;
Optional<DateTimeOffset> creationDate = default;
Optional<AutoPauseProperties> autoPause = default;
Optional<bool> isComputeIsolationEnabled = default;
Optional<bool> haveLibraryRequirementsChanged = default;
Optional<bool> sessionLevelPackagesEnabled = default;
Optional<string> sparkEventsFolder = default;
Optional<int> nodeCount = default;
Optional<LibraryRequirements> libraryRequirements = default;
Optional<LibraryRequirements> sparkConfigProperties = default;
Optional<string> sparkVersion = default;
Optional<string> defaultSparkLogFolder = default;
Optional<NodeSize> nodeSize = default;
Optional<NodeSizeFamily> nodeSizeFamily = default;
foreach (var property in element.EnumerateObject())
{
if (property.NameEquals("tags"))
{
if (property.Value.ValueKind == JsonValueKind.Null)
{
property.ThrowNonNullablePropertyIsNull();
continue;
}
Dictionary<string, string> dictionary = new Dictionary<string, string>();
foreach (var property0 in property.Value.EnumerateObject())
{
dictionary.Add(property0.Name, property0.Value.GetString());
}
tags = dictionary;
continue;
}
if (property.NameEquals("location"))
{
location = property.Value.GetString();
continue;
}
if (property.NameEquals("id"))
{
id = property.Value.GetString();
continue;
}
if (property.NameEquals("name"))
{
name = property.Value.GetString();
continue;
}
if (property.NameEquals("type"))
{
type = property.Value.GetString();
continue;
}
if (property.NameEquals("properties"))
{
if (property.Value.ValueKind == JsonValueKind.Null)
{
property.ThrowNonNullablePropertyIsNull();
continue;
}
foreach (var property0 in property.Value.EnumerateObject())
{
if (property0.NameEquals("provisioningState"))
{
provisioningState = property0.Value.GetString();
continue;
}
if (property0.NameEquals("autoScale"))
{
if (property0.Value.ValueKind == JsonValueKind.Null)
{
property0.ThrowNonNullablePropertyIsNull();
continue;
}
autoScale = AutoScaleProperties.DeserializeAutoScaleProperties(property0.Value);
continue;
}
if (property0.NameEquals("creationDate"))
{
if (property0.Value.ValueKind == JsonValueKind.Null)
{
property0.ThrowNonNullablePropertyIsNull();
continue;
}
creationDate = property0.Value.GetDateTimeOffset("O");
continue;
}
if (property0.NameEquals("autoPause"))
{
if (property0.Value.ValueKind == JsonValueKind.Null)
{
property0.ThrowNonNullablePropertyIsNull();
continue;
}
autoPause = AutoPauseProperties.DeserializeAutoPauseProperties(property0.Value);
continue;
}
if (property0.NameEquals("isComputeIsolationEnabled"))
{
if (property0.Value.ValueKind == JsonValueKind.Null)
{
property0.ThrowNonNullablePropertyIsNull();
continue;
}
isComputeIsolationEnabled = property0.Value.GetBoolean();
continue;
}
if (property0.NameEquals("haveLibraryRequirementsChanged"))
{
if (property0.Value.ValueKind == JsonValueKind.Null)
{
property0.ThrowNonNullablePropertyIsNull();
continue;
}
haveLibraryRequirementsChanged = property0.Value.GetBoolean();
continue;
}
if (property0.NameEquals("sessionLevelPackagesEnabled"))
{
if (property0.Value.ValueKind == JsonValueKind.Null)
{
property0.ThrowNonNullablePropertyIsNull();
continue;
}
sessionLevelPackagesEnabled = property0.Value.GetBoolean();
continue;
}
if (property0.NameEquals("sparkEventsFolder"))
{
sparkEventsFolder = property0.Value.GetString();
continue;
}
if (property0.NameEquals("nodeCount"))
{
if (property0.Value.ValueKind == JsonValueKind.Null)
{
property0.ThrowNonNullablePropertyIsNull();
continue;
}
nodeCount = property0.Value.GetInt32();
continue;
}
if (property0.NameEquals("libraryRequirements"))
{
if (property0.Value.ValueKind == JsonValueKind.Null)
{
property0.ThrowNonNullablePropertyIsNull();
continue;
}
libraryRequirements = LibraryRequirements.DeserializeLibraryRequirements(property0.Value);
continue;
}
if (property0.NameEquals("sparkConfigProperties"))
{
if (property0.Value.ValueKind == JsonValueKind.Null)
{
property0.ThrowNonNullablePropertyIsNull();
continue;
}
sparkConfigProperties = LibraryRequirements.DeserializeLibraryRequirements(property0.Value);
continue;
}
if (property0.NameEquals("sparkVersion"))
{
sparkVersion = property0.Value.GetString();
continue;
}
if (property0.NameEquals("defaultSparkLogFolder"))
{
defaultSparkLogFolder = property0.Value.GetString();
continue;
}
if (property0.NameEquals("nodeSize"))
{
if (property0.Value.ValueKind == JsonValueKind.Null)
{
property0.ThrowNonNullablePropertyIsNull();
continue;
}
nodeSize = new NodeSize(property0.Value.GetString());
continue;
}
if (property0.NameEquals("nodeSizeFamily"))
{
if (property0.Value.ValueKind == JsonValueKind.Null)
{
property0.ThrowNonNullablePropertyIsNull();
continue;
}
nodeSizeFamily = new NodeSizeFamily(property0.Value.GetString());
continue;
}
}
continue;
}
}
return new BigDataPoolResourceInfo(id.Value, name.Value, type.Value, Optional.ToDictionary(tags), location, provisioningState.Value, autoScale.Value, Optional.ToNullable(creationDate), autoPause.Value, Optional.ToNullable(isComputeIsolationEnabled), Optional.ToNullable(haveLibraryRequirementsChanged), Optional.ToNullable(sessionLevelPackagesEnabled), sparkEventsFolder.Value, Optional.ToNullable(nodeCount), libraryRequirements.Value, sparkConfigProperties.Value, sparkVersion.Value, defaultSparkLogFolder.Value, Optional.ToNullable(nodeSize), Optional.ToNullable(nodeSizeFamily));
}
}
}
| 46 | 595 | 0.476291 | [
"MIT"
] | ChenglongLiu/azure-sdk-for-net | sdk/synapse/Azure.Analytics.Synapse.Artifacts/src/Generated/Models/BigDataPoolResourceInfo.Serialization.cs | 14,720 | C# |
/*
* Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the elasticmapreduce-2009-03-31.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.ElasticMapReduce.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using ThirdParty.Json.LitJson;
namespace Amazon.ElasticMapReduce.Model.Internal.MarshallTransformations
{
/// <summary>
/// Response Unmarshaller for InstanceGroup Object
/// </summary>
public class InstanceGroupUnmarshaller : IUnmarshaller<InstanceGroup, XmlUnmarshallerContext>, IUnmarshaller<InstanceGroup, JsonUnmarshallerContext>
{
InstanceGroup IUnmarshaller<InstanceGroup, XmlUnmarshallerContext>.Unmarshall(XmlUnmarshallerContext context)
{
throw new NotImplementedException();
}
public InstanceGroup Unmarshall(JsonUnmarshallerContext context)
{
context.Read();
if (context.CurrentTokenType == JsonToken.Null)
return null;
InstanceGroup unmarshalledObject = new InstanceGroup();
int targetDepth = context.CurrentDepth;
while (context.ReadAtDepth(targetDepth))
{
if (context.TestExpression("BidPrice", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
unmarshalledObject.BidPrice = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("Id", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
unmarshalledObject.Id = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("InstanceGroupType", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
unmarshalledObject.InstanceGroupType = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("InstanceType", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
unmarshalledObject.InstanceType = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("Market", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
unmarshalledObject.Market = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("Name", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
unmarshalledObject.Name = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("RequestedInstanceCount", targetDepth))
{
var unmarshaller = IntUnmarshaller.Instance;
unmarshalledObject.RequestedInstanceCount = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("RunningInstanceCount", targetDepth))
{
var unmarshaller = IntUnmarshaller.Instance;
unmarshalledObject.RunningInstanceCount = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("Status", targetDepth))
{
var unmarshaller = InstanceGroupStatusUnmarshaller.Instance;
unmarshalledObject.Status = unmarshaller.Unmarshall(context);
continue;
}
}
return unmarshalledObject;
}
private static InstanceGroupUnmarshaller _instance = new InstanceGroupUnmarshaller();
public static InstanceGroupUnmarshaller Instance
{
get
{
return _instance;
}
}
}
} | 39.11811 | 152 | 0.598229 | [
"Apache-2.0"
] | ermshiperete/aws-sdk-net | AWSSDK_DotNet35/Amazon.ElasticMapReduce/Model/Internal/MarshallTransformations/InstanceGroupUnmarshaller.cs | 4,968 | C# |
using AutoMapper;
using Bogus;
using FluentAssertions;
using Kongres.Api.Application.Commands.Users;
using Kongres.Api.Application.Helpers;
using Kongres.Api.Application.Mappers.Profiles;
using Kongres.Api.Application.Services;
using Kongres.Api.Application.Services.Interfaces;
using Kongres.Api.Domain.DTOs;
using Kongres.Api.Domain.Entities;
using Kongres.Api.Domain.Enums;
using Kongres.Api.Infrastructure;
using Kongres.Api.Infrastructure.Repositories.Interfaces;
using Kongres.Api.Tests.Unit.Fakes;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Identity;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.DependencyInjection;
using Moq;
using System;
using System.Security.Authentication;
using System.Text;
using System.Threading.Tasks;
using Xunit;
namespace Kongres.Api.Tests.Unit.Services
{
public class UserServiceTests : IDisposable
{
private readonly Mock<IJwtHandler> _jwtHandlerMock = new Mock<IJwtHandler>();
private readonly Mock<IScientificWorkRepository> _scientificWorkRepositoryMock = new Mock<IScientificWorkRepository>();
private readonly Mock<IFileManager> _fileManagerMock = new Mock<IFileManager>();
private readonly Mock<IEmailSender> _emailSendeMock = new Mock<IEmailSender>();
private readonly Mock<FakeUserManager> _userManagerMock = new Mock<FakeUserManager>();
private readonly Mock<FakeSignInManager> _signInManagerMock = new Mock<FakeSignInManager>();
private readonly IUserService _userService;
private readonly Faker _faker = new Faker();
private readonly IMapper _mapper;
public UserServiceTests()
{
// https://stackoverflow.com/a/38319045/8423793
var services = new ServiceCollection();
services.AddMemoryCache();
var serviceProvider = services.BuildServiceProvider();
var memoryCache = serviceProvider.GetService<IMemoryCache>();
var configuration = new MapperConfiguration(cfg
=> cfg.AddProfile<UserProfile>());
_mapper = new Mapper(configuration);
_userService = new UserService(_userManagerMock.Object,
_signInManagerMock.Object,
_jwtHandlerMock.Object,
memoryCache,
_scientificWorkRepositoryMock.Object,
_fileManagerMock.Object,
_emailSendeMock.Object,
_mapper);
}
public void Dispose()
{
_jwtHandlerMock.Reset();
_scientificWorkRepositoryMock.Reset();
_fileManagerMock.Reset();
_emailSendeMock.Reset();
_userManagerMock.Reset();
_signInManagerMock.Reset();
}
[Fact]
public async Task GetUserInfoForHeaderAsyncReturnDtoWithScientificWorkId()
{
var userId = 1u;
var user = new User()
{
Id = userId,
Name = _faker.Person.FirstName,
Surname = _faker.Person.LastName,
UserName = UserHelper.GetUserName(UserTypeEnum.Participant, _faker.Person.Email)
};
var scientificWork = new ScientificWork() { Id = 1 };
var expectedDto = _mapper.Map<HeaderUserInfoDto>(user);
expectedDto.ScientificWorkId = scientificWork.Id;
HeaderUserInfoDto returnedDto = null;
_userManagerMock.Setup(x => x.FindByIdAsync(userId.ToString())).ReturnsAsync(user);
_scientificWorkRepositoryMock.Setup(x => x.GetByAuthorIdAsync(userId)).ReturnsAsync(scientificWork);
var err = await Record.ExceptionAsync(async () => returnedDto = await _userService.GetUserInfoForHeaderAsync(userId.ToString()));
err.Should().BeNull();
returnedDto.Should().NotBeNull();
returnedDto.Should().BeEquivalentTo(expectedDto);
_userManagerMock.Verify(x => x.FindByIdAsync(userId.ToString()), Times.Once);
_scientificWorkRepositoryMock.Verify(x => x.GetByAuthorIdAsync(userId), Times.Once);
}
[Fact]
public async Task GetUserInfoForHeaderAsyncReturnDtoWithoutScientificWorkId()
{
var userId = 1u;
var user = new User()
{
Id = userId,
Name = _faker.Person.FirstName,
Surname = _faker.Person.LastName,
UserName = UserHelper.GetUserName(UserTypeEnum.Participant, _faker.Person.Email)
};
var expectedDto = _mapper.Map<HeaderUserInfoDto>(user);
HeaderUserInfoDto returnedDto = null;
_userManagerMock.Setup(x => x.FindByIdAsync(userId.ToString())).ReturnsAsync(user);
_scientificWorkRepositoryMock.Setup(x => x.GetByAuthorIdAsync(userId)).ReturnsAsync((ScientificWork)null);
var err = await Record.ExceptionAsync(async () => returnedDto = await _userService.GetUserInfoForHeaderAsync(userId.ToString()));
err.Should().BeNull();
returnedDto.Should().NotBeNull();
returnedDto.Should().BeEquivalentTo(expectedDto);
_userManagerMock.Verify(x => x.FindByIdAsync(userId.ToString()), Times.Once);
_scientificWorkRepositoryMock.Verify(x => x.GetByAuthorIdAsync(userId), Times.Once);
}
[Fact]
public async Task GetUserInfoForHeaderAsyncReturnDtoWithPhoto()
{
var userId = 1u;
var randomBase64 = Convert.ToBase64String(Encoding.UTF8.GetBytes(_faker.Random.String(7)));
var photoExtension = "png";
var user = new User()
{
Id = userId,
Name = _faker.Person.FirstName,
Surname = _faker.Person.LastName,
UserName = UserHelper.GetUserName(UserTypeEnum.Participant, _faker.Person.Email),
Photo = _faker.System.FileName(photoExtension)
};
var expectedDto = _mapper.Map<HeaderUserInfoDto>(user);
expectedDto.PhotoBase64 = $"data:image/{photoExtension};base64,{randomBase64}";
HeaderUserInfoDto returnedDto = null;
_userManagerMock.Setup(x => x.FindByIdAsync(userId.ToString())).ReturnsAsync(user);
_scientificWorkRepositoryMock.Setup(x => x.GetByAuthorIdAsync(userId)).ReturnsAsync((ScientificWork)null);
_fileManagerMock.Setup(x => x.GetBase64FileAsync(user.Photo)).ReturnsAsync(randomBase64);
var err = await Record.ExceptionAsync(async () => returnedDto = await _userService.GetUserInfoForHeaderAsync(userId.ToString()));
err.Should().BeNull();
returnedDto.Should().NotBeNull();
returnedDto.Should().BeEquivalentTo(expectedDto);
_userManagerMock.Verify(x => x.FindByIdAsync(userId.ToString()), Times.Once);
_scientificWorkRepositoryMock.Verify(x => x.GetByAuthorIdAsync(userId), Times.Once);
_fileManagerMock.Verify(x => x.GetBase64FileAsync(user.Photo), Times.Once);
}
[Theory]
[InlineData(UserTypeEnum.Participant)]
[InlineData(UserTypeEnum.Reviewer)]
public async Task RegisterAsyncRegisterSuccesfullySendEmailConfirmation(UserTypeEnum userType)
{
var command = new CreateUserCommand()
{
FirstName = _faker.Person.FirstName,
LastName = _faker.Person.LastName,
AcademicTitle = _faker.Name.JobTitle(),
Email = _faker.Person.Email,
Specialization = _faker.Commerce.Categories(1)[0],
University = _faker.Company.CompanyName(),
Password = _faker.Internet.Password()
};
var user = new User
{
Id = 0,
Name = command.FirstName,
UserName = UserHelper.GetUserName(userType, command.Email),
Surname = command.LastName,
Degree = command.AcademicTitle,
Email = command.Email,
Specialization = command.Specialization,
University = command.University
};
var token = _faker.Random.String(10);
_userManagerMock.Setup(x => x.CreateAsync(It.IsAny<User>(), command.Password)).ReturnsAsync(IdentityResult.Success);
_userManagerMock.Setup(x => x.AddToRoleAsync(It.IsAny<User>(), userType.ToString()));
_userManagerMock.Setup(x => x.GenerateEmailConfirmationTokenAsync(It.IsAny<User>())).ReturnsAsync(token);
_emailSendeMock.Setup(x => x.SendConfirmationEmailAsync(user.Id, user.Email, token));
var err = await Record.ExceptionAsync(async () => await _userService.RegisterAsync(userType, command));
err.Should().BeNull();
_userManagerMock.Verify(x => x.CreateAsync(It.Is<User>(x => x.Id == user.Id && x.UserName == user.UserName), command.Password), Times.Once);
_userManagerMock.Verify(x => x.AddToRoleAsync(It.Is<User>(x => x.Id == user.Id && x.UserName == user.UserName), userType.ToString()), Times.Once);
_userManagerMock.Verify(x => x.GenerateEmailConfirmationTokenAsync(It.Is<User>(x => x.Id == user.Id && x.UserName == user.UserName)), Times.Once);
_emailSendeMock.Verify(x => x.SendConfirmationEmailAsync(user.Id, user.Email, token), Times.Once);
}
[Fact]
public async Task RegisterAsyncRegisterParticipantSaveAvatar()
{
var userType = UserTypeEnum.Participant;
var avatar = new FormFile(null, _faker.Random.Long(), _faker.Random.Long(), _faker.Internet.UserName(), _faker.System.FileName("pdf"));
var fileName = _faker.System.FileName("png");
var command = new CreateUserCommand()
{
Email = _faker.Person.Email,
Password = _faker.Internet.Password(),
Avatar = avatar
};
var user = new User
{
Id = 0,
UserName = UserHelper.GetUserName(userType, command.Email),
Email = command.Email,
};
var token = _faker.Random.String(10);
_userManagerMock.Setup(x => x.CreateAsync(It.IsAny<User>(), command.Password)).ReturnsAsync(IdentityResult.Success);
_userManagerMock.Setup(x => x.AddToRoleAsync(It.IsAny<User>(), userType.ToString()));
_userManagerMock.Setup(x => x.GenerateEmailConfirmationTokenAsync(It.IsAny<User>())).ReturnsAsync(token);
_fileManagerMock.Setup(x => x.SaveFileAsync(avatar)).ReturnsAsync(fileName);
_emailSendeMock.Setup(x => x.SendConfirmationEmailAsync(user.Id, user.Email, token));
var err = await Record.ExceptionAsync(async () => await _userService.RegisterAsync(userType, command));
err.Should().BeNull();
_fileManagerMock.Verify(x => x.SaveFileAsync(avatar), Times.Once);
}
[Fact]
public async Task RegisterAsyncRegisterReviewerDoNotSaveAvatar()
{
var userType = UserTypeEnum.Reviewer;
var command = new CreateUserCommand()
{
Email = _faker.Person.Email,
Password = _faker.Internet.Password(),
};
var user = new User
{
Id = 0,
UserName = UserHelper.GetUserName(userType, command.Email),
Email = command.Email,
};
var token = _faker.Random.String(10);
_userManagerMock.Setup(x => x.CreateAsync(It.IsAny<User>(), command.Password)).ReturnsAsync(IdentityResult.Success);
_userManagerMock.Setup(x => x.AddToRoleAsync(It.IsAny<User>(), userType.ToString()));
_userManagerMock.Setup(x => x.GenerateEmailConfirmationTokenAsync(It.IsAny<User>())).ReturnsAsync(token);
_emailSendeMock.Setup(x => x.SendConfirmationEmailAsync(user.Id, user.Email, token));
var err = await Record.ExceptionAsync(async () => await _userService.RegisterAsync(userType, command));
err.Should().BeNull();
_fileManagerMock.Verify(x => x.SaveFileAsync(It.IsAny<IFormFile>()), Times.Never);
}
[Theory]
[InlineData(UserTypeEnum.Participant)]
[InlineData(UserTypeEnum.Reviewer)]
public void LoginAsyncWhenCredentialsAreIncorrectThrowExcpetion(UserTypeEnum userType)
{
var command = new LoginUserCommand()
{
Email = _faker.Person.Email
};
var userName = UserHelper.GetUserName(userType, command.Email);
_userManagerMock.Setup(x => x.FindByNameAsync(userName)).ReturnsAsync((User)null);
Func<Task> err = async () => await _userService.LoginAsync(userType, command);
err.Should().Throw<Exception>();
}
[Theory]
[InlineData(UserTypeEnum.Participant)]
[InlineData(UserTypeEnum.Reviewer)]
public async Task LoginAsyncSignInSuccessedCreateJwtToken(UserTypeEnum userType)
{
var command = new LoginUserCommand()
{
Email = _faker.Person.Email,
Password = _faker.Internet.Password(),
TokenId = _faker.Random.Guid()
};
var userName = UserHelper.GetUserName(userType, command.Email);
var user = new User()
{
Id = 1
};
var jwtToken = "";
_userManagerMock.Setup(x => x.FindByNameAsync(userName)).ReturnsAsync(user);
_signInManagerMock.Setup(x => x.PasswordSignInAsync(user, command.Password, false, false)).ReturnsAsync(SignInResult.Success);
_jwtHandlerMock.Setup(x => x.CreateToken(user.Id, userType.ToString())).Returns(jwtToken);
var err = await Record.ExceptionAsync(async () => await _userService.LoginAsync(userType, command));
err.Should().BeNull();
_signInManagerMock.Verify(x => x.PasswordSignInAsync(user, command.Password, false, false), Times.Once);
_jwtHandlerMock.Verify(x => x.CreateToken(user.Id, userType.ToString()), Times.Once);
}
[Fact]
public async Task GetUserNameWhenUserIsNotParticipantThrowAuthenticationException()
{
var userId = 1u;
var user = new User() { Id = userId };
_userManagerMock.Setup(x => x.FindByIdAsync(userId.ToString())).ReturnsAsync(user);
_userManagerMock.Setup(x => x.IsInRoleAsync(user, nameof(UserTypeEnum.Participant))).ReturnsAsync(false);
var err = await Record.ExceptionAsync(async () => await _userService.GetUserName(userId.ToString()));
err.Should().BeOfType<AuthenticationException>();
_userManagerMock.Verify(x => x.FindByIdAsync(userId.ToString()), Times.Once);
_userManagerMock.Verify(x => x.IsInRoleAsync(user, nameof(UserTypeEnum.Participant)), Times.Once);
}
[Fact]
public async Task GetUserNameWhenUserHaveScientificWorkThrowInvalidOperationException()
{
var userId = 1u;
var user = new User() { Id = userId };
_userManagerMock.Setup(x => x.FindByIdAsync(userId.ToString())).ReturnsAsync(user);
_userManagerMock.Setup(x => x.IsInRoleAsync(user, nameof(UserTypeEnum.Participant))).ReturnsAsync(true);
_scientificWorkRepositoryMock.Setup(x => x.GetByAuthorIdAsync(userId)).ReturnsAsync(new ScientificWork());
var err = await Record.ExceptionAsync(async () => await _userService.GetUserName(userId.ToString()));
err.Should().BeOfType<InvalidOperationException>();
_userManagerMock.Verify(x => x.FindByIdAsync(userId.ToString()), Times.Once);
_userManagerMock.Verify(x => x.IsInRoleAsync(user, nameof(UserTypeEnum.Participant)), Times.Once);
_scientificWorkRepositoryMock.Verify(x => x.GetByAuthorIdAsync(userId), Times.Once);
}
[Fact]
public async Task GetUserNameSuccessReturnUserNameAndSurname()
{
var userId = 1u;
var user = new User()
{
Id = userId,
Name = _faker.Person.FirstName,
Surname = _faker.Person.LastName
};
var expectedStr = UserHelper.GetFullName(user);
var returnedStr = "";
_userManagerMock.Setup(x => x.FindByIdAsync(userId.ToString())).ReturnsAsync(user);
_userManagerMock.Setup(x => x.IsInRoleAsync(user, nameof(UserTypeEnum.Participant))).ReturnsAsync(true);
_scientificWorkRepositoryMock.Setup(x => x.GetByAuthorIdAsync(userId)).ReturnsAsync((ScientificWork)null);
var err = await Record.ExceptionAsync(async () => returnedStr = await _userService.GetUserName(userId.ToString()));
err.Should().BeNull();
returnedStr.Should().NotBeNullOrWhiteSpace();
_userManagerMock.Verify(x => x.FindByIdAsync(userId.ToString()), Times.Once);
_userManagerMock.Verify(x => x.IsInRoleAsync(user, nameof(UserTypeEnum.Participant)), Times.Once);
_scientificWorkRepositoryMock.Verify(x => x.GetByAuthorIdAsync(userId), Times.Once);
}
[Fact]
public async Task GetInformationFroMyProfileAsyncSuccessReturnDtoWithoutScientificWork()
{
var userId = 1u;
var user = new User()
{
Id = userId,
Name = _faker.Person.FirstName,
Surname = _faker.Person.LastName,
Email = _faker.Person.Email,
Degree = _faker.Name.JobTitle(),
University = _faker.Company.CompanyName(),
Specialization = _faker.Commerce.Categories(1)[0],
UserName = UserHelper.GetUserName(UserTypeEnum.Participant, _faker.Person.Email)
};
var expectedDto = _mapper.Map<MyProfileUserDto>(user);
MyProfileUserDto returnedDto = null;
_userManagerMock.Setup(x => x.FindByIdAsync(userId.ToString())).ReturnsAsync(user);
_scientificWorkRepositoryMock.Setup(x => x.GetByAuthorIdAsync(userId)).ReturnsAsync((ScientificWork)null);
var err = await Record.ExceptionAsync(async () => returnedDto = await _userService.GetInformationForMyProfileAsync(userId.ToString()));
err.Should().BeNull();
returnedDto.Should().NotBeNull();
returnedDto.Should().BeEquivalentTo(expectedDto);
_userManagerMock.Verify(x => x.FindByIdAsync(userId.ToString()), Times.Once);
_scientificWorkRepositoryMock.Verify(x => x.GetByAuthorIdAsync(userId), Times.Once);
}
[Fact]
public async Task GetInformationFroMyProfileAsyncSuccessReturnDtoWithScientificWork()
{
var userId = 1u;
var user = new User()
{
Id = userId,
Name = _faker.Person.FirstName,
Surname = _faker.Person.LastName,
Email = _faker.Person.Email,
Degree = _faker.Name.JobTitle(),
University = _faker.Company.CompanyName(),
Specialization = _faker.Commerce.Categories(1)[0],
UserName = UserHelper.GetUserName(UserTypeEnum.Participant, _faker.Person.Email)
};
var scientificWork = new ScientificWork() { Id = 1u };
var expectedDto = _mapper.Map<MyProfileUserDto>(user);
expectedDto.WorkId = scientificWork.Id;
MyProfileUserDto returnedDto = null;
_userManagerMock.Setup(x => x.FindByIdAsync(userId.ToString())).ReturnsAsync(user);
_scientificWorkRepositoryMock.Setup(x => x.GetByAuthorIdAsync(userId)).ReturnsAsync(scientificWork);
var err = await Record.ExceptionAsync(async () => returnedDto = await _userService.GetInformationForMyProfileAsync(userId.ToString()));
err.Should().BeNull();
returnedDto.Should().NotBeNull();
returnedDto.Should().BeEquivalentTo(expectedDto);
_userManagerMock.Verify(x => x.FindByIdAsync(userId.ToString()), Times.Once);
_scientificWorkRepositoryMock.Verify(x => x.GetByAuthorIdAsync(userId), Times.Once);
}
}
}
| 42.35102 | 158 | 0.62235 | [
"MIT"
] | WyimaginowaneKoniki/Kongres | Kongres.Api/Tests/Kongres.Api.Tests.Unit/Services/UserServiceTests.cs | 20,754 | C# |
using System;
using System.Linq;
using FizzWare.NBuilder;
using UrlBitlyClone.Core.Context;
namespace UrlBitlyClone.Tests.Infrastructure
{
public class ObjectMother
{
/// <summary>
/// Initializes a new instance of the <see cref="ObjectMother"/> class.
/// </summary>
public ObjectMother(UrlBitlyCloneContext context)
{
this.Context = context;
}
public UrlBitlyCloneContext Context { get; }
/// <summary>
/// Gets the first entity against the repository.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
public T GetFirstEntity<T>() where T : class
{
return Context.Set<T>().FirstOrDefault();
}
public ObjectMother WithUrls(int size, Func<IListBuilder<UrlShortForm>, IOperable<UrlShortForm>> actions = null) => With(size, null, actions);
internal ObjectMother With<T>(int size, Func<IListBuilder<T>, IOperable<T>> setupAction = null, Func<IListBuilder<T>, IOperable<T>> overrideAction = null) where T : class
{
var objects = Builder<T>.CreateListOfSize(size).All();
if (setupAction != null)
{
objects = setupAction(objects);
}
if (overrideAction != null)
{
objects = overrideAction(objects);
}
foreach (var d in objects.Build())
{
Context.Add<T>(d);
}
Context.SaveChanges();
return this;
}
}
}
| 28.280702 | 178 | 0.555831 | [
"MIT"
] | DanScottNI/UrlShortener | UrlBitlyClone.Tests/Infrastructure/ObjectMother.cs | 1,614 | C# |
using Microsoft.EntityFrameworkCore.Migrations;
namespace CarRentalSystem.Infrastructure.Persistence.Migrations
{
public partial class AddIndexes : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateIndex(
name: "IX_Manufacturers_Name",
table: "Manufacturers",
column: "Name",
unique: true);
migrationBuilder.CreateIndex(
name: "IX_Categories_Name",
table: "Categories",
column: "Name",
unique: true);
migrationBuilder.CreateIndex(
name: "IX_CarAds_IsAvailable",
table: "CarAds",
column: "IsAvailable");
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropIndex(
name: "IX_Manufacturers_Name",
table: "Manufacturers");
migrationBuilder.DropIndex(
name: "IX_Categories_Name",
table: "Categories");
migrationBuilder.DropIndex(
name: "IX_CarAds_IsAvailable",
table: "CarAds");
}
}
}
| 29.674419 | 71 | 0.545455 | [
"MIT"
] | SvetoslavIT/CarRentalSystemDDD | Server/CarRentalSystem.Infrastructure/Persistence/Migrations/20210522135607_AddIndexes.cs | 1,278 | C# |
namespace AnimaniaConsole.Data.Migrations
{
using System;
using System.Data.Entity.Migrations;
public partial class seedtest : DbMigration
{
public override void Up()
{
}
public override void Down()
{
}
}
}
| 17 | 47 | 0.550173 | [
"MIT"
] | theMoaningEchidnas/Database-Project | AnimaniaConsole/AnimaniaConsole.Data/Migrations/201803161405498_seed test.cs | 289 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class Ball : MonoBehaviour
{
public float velocity_x;
public float velocity_y = -0.1f;
bool direction;
public Rigidbody2D rb;
int time = 0;
int cache_time = 0;
public Sprite Triangle;
public Sprite Square;
public Sprite Hexagon;
public Vector2 posicion;
//To indicate if the ball has to start going to the right or to the left
float GiveDirection()
{
float direccion = Random.Range(0.0f, 5.0f);
if (direccion > 2.5)
{
velocity_x = 0.1f;
return velocity_x;
}
else
{
velocity_x = -0.1f;
return velocity_x;
}
}
// Start is called before the first frame update
void Start()
{
GiveDirection();
}
// Update is called once per frame
void Update()
{
transform.Translate(velocity_x, velocity_y, 0);
//transform.Rotate(0, 0, 2);
if(time>600)
{
if (velocity_x > 0)
{
velocity_x += 0.1f;
}
if (velocity_x < 0)
{
velocity_x -= 0.1f;
}
cache_time = cache_time + time;
time = 0;
}
if (cache_time < 599)
{
this.GetComponent<SpriteRenderer>().sprite = Triangle;
}
if (cache_time > 600 && cache_time < 1200)
{
this.GetComponent<SpriteRenderer>().sprite = Square;
}
if (cache_time > 1200 )
{
this.GetComponent<SpriteRenderer>().sprite = Hexagon;
}
time += 1;
posicion = transform.position;
Debug.Log(velocity_x);
Debug.Log(cache_time);
}
void OnCollisionEnter2D(Collision2D col)
{
if (col.gameObject.tag == "Border")
{
velocity_y = -velocity_y;
}
if (col.gameObject.tag == "Barra")
{
velocity_x = -velocity_x;
}
if (col.gameObject.tag == "lose")
{
SceneManager.LoadScene("Lose");
}
if (col.gameObject.tag == "win")
{
SceneManager.LoadScene("Level02");
}
if (col.gameObject.tag == "GANAR")
{
SceneManager.LoadScene("Win");
}
if (col.gameObject.tag == "Level3")
{
SceneManager.LoadScene("Level03");
}
}
}
| 20.265625 | 76 | 0.500386 | [
"MIT"
] | neripinata/Epic-Pong | EpicPongV/Assets/Scripts/Ball.cs | 2,596 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using UserStoryBoard.Interface;
using UserStoryBoard.Models;
using UserStoryBoard.Services;
namespace UserStoryBoard.Pages
{
public class UserStoryDetailModel : PageModel
{
[BindProperty]
public UserStory UserStory { get; set; }
public bool IsBacklog;
public int ColumnsToDraw;
public List<UserStory> UserStories { get; private set; }
// private BoardService boardService;
IBoards boards;
//public Board CurrentBoard { get; set; }
private int boardId;
public UserStoryDetailModel(IBoards repo)
{
boards = repo;
}
public void OnGet(int id, int boardId, bool backlog)
{
IsBacklog = backlog;
ColumnsToDraw = backlog ? Backlog.Columns : Board.Columns; // If backlog is true, use backlog columns, else use board columns. This is just shorthand for if/else.
this.boardId = boardId;
UserStories = boards.GetUserStories(boardId);
UserStory = boards.GetUserStory(id, boardId, backlog);
}
public Board GetCurrentBoard()
{
return boards.GetBoard(boardId);
}
public List<UserStory> GetUserStories()
{
if (IsBacklog == false)
return boards.GetUserStories(boardId);
else
return boards.GetUserStoriesInBacklog(boardId);
}
}
}
| 28.298246 | 174 | 0.630502 | [
"Unlicense"
] | Pingel91/KanbanBoard | UserStoryBoard/UserStoryBoard/Pages/UserStories/UserStoryDetail.cshtml.cs | 1,613 | C# |
namespace Miningcore.Time;
public class StandardClock : IMasterClock
{
public DateTime Now => DateTime.UtcNow;
}
| 16.857143 | 43 | 0.762712 | [
"MIT"
] | BitWizJason/miningcore | src/Miningcore/Time/StandardClock.cs | 118 | C# |
namespace HermesSpa.Services
{
public partial class RailKaolinApiClient
{
public class CarPlace
{
public int Number { get; set; }
public string Gender { get; set; }
public Price Price { get; set; }
public bool IsFree { get; set; }
}
}
}
| 23 | 46 | 0.531056 | [
"MIT"
] | svasorcery/rzd-ru-api | Clients/HermesSpa/Services/RailKaolinApiClient.CarPlace.cs | 324 | C# |
using System;
using SLua;
using System.Collections.Generic;
[UnityEngine.Scripting.Preserve]
public class Lua_UnityEngine_Rendering_CommandBuffer : LuaObject {
[SLua.MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
[UnityEngine.Scripting.Preserve]
static public int constructor(IntPtr l) {
try {
#if DEBUG
var method = System.Reflection.MethodBase.GetCurrentMethod();
string methodName = GetMethodName(method);
#if UNITY_5_5_OR_NEWER
UnityEngine.Profiling.Profiler.BeginSample(methodName);
#else
Profiler.BeginSample(methodName);
#endif
#endif
UnityEngine.Rendering.CommandBuffer o;
o=new UnityEngine.Rendering.CommandBuffer();
pushValue(l,true);
pushValue(l,o);
return 2;
}
catch(Exception e) {
return error(l,e);
}
#if DEBUG
finally {
#if UNITY_5_5_OR_NEWER
UnityEngine.Profiling.Profiler.EndSample();
#else
Profiler.EndSample();
#endif
}
#endif
}
[SLua.MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
[UnityEngine.Scripting.Preserve]
static public int Dispose(IntPtr l) {
try {
#if DEBUG
var method = System.Reflection.MethodBase.GetCurrentMethod();
string methodName = GetMethodName(method);
#if UNITY_5_5_OR_NEWER
UnityEngine.Profiling.Profiler.BeginSample(methodName);
#else
Profiler.BeginSample(methodName);
#endif
#endif
UnityEngine.Rendering.CommandBuffer self=(UnityEngine.Rendering.CommandBuffer)checkSelf(l);
self.Dispose();
pushValue(l,true);
return 1;
}
catch(Exception e) {
return error(l,e);
}
#if DEBUG
finally {
#if UNITY_5_5_OR_NEWER
UnityEngine.Profiling.Profiler.EndSample();
#else
Profiler.EndSample();
#endif
}
#endif
}
[SLua.MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
[UnityEngine.Scripting.Preserve]
static public int Release(IntPtr l) {
try {
#if DEBUG
var method = System.Reflection.MethodBase.GetCurrentMethod();
string methodName = GetMethodName(method);
#if UNITY_5_5_OR_NEWER
UnityEngine.Profiling.Profiler.BeginSample(methodName);
#else
Profiler.BeginSample(methodName);
#endif
#endif
UnityEngine.Rendering.CommandBuffer self=(UnityEngine.Rendering.CommandBuffer)checkSelf(l);
self.Release();
pushValue(l,true);
return 1;
}
catch(Exception e) {
return error(l,e);
}
#if DEBUG
finally {
#if UNITY_5_5_OR_NEWER
UnityEngine.Profiling.Profiler.EndSample();
#else
Profiler.EndSample();
#endif
}
#endif
}
[SLua.MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
[UnityEngine.Scripting.Preserve]
static public int CreateGPUFence(IntPtr l) {
try {
#if DEBUG
var method = System.Reflection.MethodBase.GetCurrentMethod();
string methodName = GetMethodName(method);
#if UNITY_5_5_OR_NEWER
UnityEngine.Profiling.Profiler.BeginSample(methodName);
#else
Profiler.BeginSample(methodName);
#endif
#endif
int argc = LuaDLL.lua_gettop(l);
if(argc==1){
UnityEngine.Rendering.CommandBuffer self=(UnityEngine.Rendering.CommandBuffer)checkSelf(l);
var ret=self.CreateGPUFence();
pushValue(l,true);
pushValue(l,ret);
return 2;
}
else if(argc==2){
UnityEngine.Rendering.CommandBuffer self=(UnityEngine.Rendering.CommandBuffer)checkSelf(l);
UnityEngine.Rendering.SynchronisationStage a1;
a1 = (UnityEngine.Rendering.SynchronisationStage)LuaDLL.luaL_checkinteger(l, 2);
var ret=self.CreateGPUFence(a1);
pushValue(l,true);
pushValue(l,ret);
return 2;
}
pushValue(l,false);
LuaDLL.lua_pushstring(l,"No matched override function CreateGPUFence to call");
return 2;
}
catch(Exception e) {
return error(l,e);
}
#if DEBUG
finally {
#if UNITY_5_5_OR_NEWER
UnityEngine.Profiling.Profiler.EndSample();
#else
Profiler.EndSample();
#endif
}
#endif
}
[SLua.MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
[UnityEngine.Scripting.Preserve]
static public int WaitOnGPUFence(IntPtr l) {
try {
#if DEBUG
var method = System.Reflection.MethodBase.GetCurrentMethod();
string methodName = GetMethodName(method);
#if UNITY_5_5_OR_NEWER
UnityEngine.Profiling.Profiler.BeginSample(methodName);
#else
Profiler.BeginSample(methodName);
#endif
#endif
int argc = LuaDLL.lua_gettop(l);
if(argc==2){
UnityEngine.Rendering.CommandBuffer self=(UnityEngine.Rendering.CommandBuffer)checkSelf(l);
UnityEngine.Rendering.GPUFence a1;
checkValueType(l,2,out a1);
self.WaitOnGPUFence(a1);
pushValue(l,true);
return 1;
}
else if(argc==3){
UnityEngine.Rendering.CommandBuffer self=(UnityEngine.Rendering.CommandBuffer)checkSelf(l);
UnityEngine.Rendering.GPUFence a1;
checkValueType(l,2,out a1);
UnityEngine.Rendering.SynchronisationStage a2;
a2 = (UnityEngine.Rendering.SynchronisationStage)LuaDLL.luaL_checkinteger(l, 3);
self.WaitOnGPUFence(a1,a2);
pushValue(l,true);
return 1;
}
pushValue(l,false);
LuaDLL.lua_pushstring(l,"No matched override function WaitOnGPUFence to call");
return 2;
}
catch(Exception e) {
return error(l,e);
}
#if DEBUG
finally {
#if UNITY_5_5_OR_NEWER
UnityEngine.Profiling.Profiler.EndSample();
#else
Profiler.EndSample();
#endif
}
#endif
}
[SLua.MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
[UnityEngine.Scripting.Preserve]
static public int SetComputeFloatParam(IntPtr l) {
try {
#if DEBUG
var method = System.Reflection.MethodBase.GetCurrentMethod();
string methodName = GetMethodName(method);
#if UNITY_5_5_OR_NEWER
UnityEngine.Profiling.Profiler.BeginSample(methodName);
#else
Profiler.BeginSample(methodName);
#endif
#endif
int argc = LuaDLL.lua_gettop(l);
if(matchType(l,argc,2,typeof(UnityEngine.ComputeShader),typeof(int),typeof(float))){
UnityEngine.Rendering.CommandBuffer self=(UnityEngine.Rendering.CommandBuffer)checkSelf(l);
UnityEngine.ComputeShader a1;
checkType(l,2,out a1);
System.Int32 a2;
checkType(l,3,out a2);
System.Single a3;
checkType(l,4,out a3);
self.SetComputeFloatParam(a1,a2,a3);
pushValue(l,true);
return 1;
}
else if(matchType(l,argc,2,typeof(UnityEngine.ComputeShader),typeof(string),typeof(float))){
UnityEngine.Rendering.CommandBuffer self=(UnityEngine.Rendering.CommandBuffer)checkSelf(l);
UnityEngine.ComputeShader a1;
checkType(l,2,out a1);
System.String a2;
checkType(l,3,out a2);
System.Single a3;
checkType(l,4,out a3);
self.SetComputeFloatParam(a1,a2,a3);
pushValue(l,true);
return 1;
}
pushValue(l,false);
LuaDLL.lua_pushstring(l,"No matched override function SetComputeFloatParam to call");
return 2;
}
catch(Exception e) {
return error(l,e);
}
#if DEBUG
finally {
#if UNITY_5_5_OR_NEWER
UnityEngine.Profiling.Profiler.EndSample();
#else
Profiler.EndSample();
#endif
}
#endif
}
[SLua.MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
[UnityEngine.Scripting.Preserve]
static public int SetComputeIntParam(IntPtr l) {
try {
#if DEBUG
var method = System.Reflection.MethodBase.GetCurrentMethod();
string methodName = GetMethodName(method);
#if UNITY_5_5_OR_NEWER
UnityEngine.Profiling.Profiler.BeginSample(methodName);
#else
Profiler.BeginSample(methodName);
#endif
#endif
int argc = LuaDLL.lua_gettop(l);
if(matchType(l,argc,2,typeof(UnityEngine.ComputeShader),typeof(int),typeof(int))){
UnityEngine.Rendering.CommandBuffer self=(UnityEngine.Rendering.CommandBuffer)checkSelf(l);
UnityEngine.ComputeShader a1;
checkType(l,2,out a1);
System.Int32 a2;
checkType(l,3,out a2);
System.Int32 a3;
checkType(l,4,out a3);
self.SetComputeIntParam(a1,a2,a3);
pushValue(l,true);
return 1;
}
else if(matchType(l,argc,2,typeof(UnityEngine.ComputeShader),typeof(string),typeof(int))){
UnityEngine.Rendering.CommandBuffer self=(UnityEngine.Rendering.CommandBuffer)checkSelf(l);
UnityEngine.ComputeShader a1;
checkType(l,2,out a1);
System.String a2;
checkType(l,3,out a2);
System.Int32 a3;
checkType(l,4,out a3);
self.SetComputeIntParam(a1,a2,a3);
pushValue(l,true);
return 1;
}
pushValue(l,false);
LuaDLL.lua_pushstring(l,"No matched override function SetComputeIntParam to call");
return 2;
}
catch(Exception e) {
return error(l,e);
}
#if DEBUG
finally {
#if UNITY_5_5_OR_NEWER
UnityEngine.Profiling.Profiler.EndSample();
#else
Profiler.EndSample();
#endif
}
#endif
}
[SLua.MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
[UnityEngine.Scripting.Preserve]
static public int SetComputeVectorParam(IntPtr l) {
try {
#if DEBUG
var method = System.Reflection.MethodBase.GetCurrentMethod();
string methodName = GetMethodName(method);
#if UNITY_5_5_OR_NEWER
UnityEngine.Profiling.Profiler.BeginSample(methodName);
#else
Profiler.BeginSample(methodName);
#endif
#endif
int argc = LuaDLL.lua_gettop(l);
if(matchType(l,argc,2,typeof(UnityEngine.ComputeShader),typeof(int),typeof(UnityEngine.Vector4))){
UnityEngine.Rendering.CommandBuffer self=(UnityEngine.Rendering.CommandBuffer)checkSelf(l);
UnityEngine.ComputeShader a1;
checkType(l,2,out a1);
System.Int32 a2;
checkType(l,3,out a2);
UnityEngine.Vector4 a3;
checkType(l,4,out a3);
self.SetComputeVectorParam(a1,a2,a3);
pushValue(l,true);
return 1;
}
else if(matchType(l,argc,2,typeof(UnityEngine.ComputeShader),typeof(string),typeof(UnityEngine.Vector4))){
UnityEngine.Rendering.CommandBuffer self=(UnityEngine.Rendering.CommandBuffer)checkSelf(l);
UnityEngine.ComputeShader a1;
checkType(l,2,out a1);
System.String a2;
checkType(l,3,out a2);
UnityEngine.Vector4 a3;
checkType(l,4,out a3);
self.SetComputeVectorParam(a1,a2,a3);
pushValue(l,true);
return 1;
}
pushValue(l,false);
LuaDLL.lua_pushstring(l,"No matched override function SetComputeVectorParam to call");
return 2;
}
catch(Exception e) {
return error(l,e);
}
#if DEBUG
finally {
#if UNITY_5_5_OR_NEWER
UnityEngine.Profiling.Profiler.EndSample();
#else
Profiler.EndSample();
#endif
}
#endif
}
[SLua.MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
[UnityEngine.Scripting.Preserve]
static public int SetComputeVectorArrayParam(IntPtr l) {
try {
#if DEBUG
var method = System.Reflection.MethodBase.GetCurrentMethod();
string methodName = GetMethodName(method);
#if UNITY_5_5_OR_NEWER
UnityEngine.Profiling.Profiler.BeginSample(methodName);
#else
Profiler.BeginSample(methodName);
#endif
#endif
int argc = LuaDLL.lua_gettop(l);
if(matchType(l,argc,2,typeof(UnityEngine.ComputeShader),typeof(int),typeof(UnityEngine.Vector4[]))){
UnityEngine.Rendering.CommandBuffer self=(UnityEngine.Rendering.CommandBuffer)checkSelf(l);
UnityEngine.ComputeShader a1;
checkType(l,2,out a1);
System.Int32 a2;
checkType(l,3,out a2);
UnityEngine.Vector4[] a3;
checkArray(l,4,out a3);
self.SetComputeVectorArrayParam(a1,a2,a3);
pushValue(l,true);
return 1;
}
else if(matchType(l,argc,2,typeof(UnityEngine.ComputeShader),typeof(string),typeof(UnityEngine.Vector4[]))){
UnityEngine.Rendering.CommandBuffer self=(UnityEngine.Rendering.CommandBuffer)checkSelf(l);
UnityEngine.ComputeShader a1;
checkType(l,2,out a1);
System.String a2;
checkType(l,3,out a2);
UnityEngine.Vector4[] a3;
checkArray(l,4,out a3);
self.SetComputeVectorArrayParam(a1,a2,a3);
pushValue(l,true);
return 1;
}
pushValue(l,false);
LuaDLL.lua_pushstring(l,"No matched override function SetComputeVectorArrayParam to call");
return 2;
}
catch(Exception e) {
return error(l,e);
}
#if DEBUG
finally {
#if UNITY_5_5_OR_NEWER
UnityEngine.Profiling.Profiler.EndSample();
#else
Profiler.EndSample();
#endif
}
#endif
}
[SLua.MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
[UnityEngine.Scripting.Preserve]
static public int SetComputeMatrixParam(IntPtr l) {
try {
#if DEBUG
var method = System.Reflection.MethodBase.GetCurrentMethod();
string methodName = GetMethodName(method);
#if UNITY_5_5_OR_NEWER
UnityEngine.Profiling.Profiler.BeginSample(methodName);
#else
Profiler.BeginSample(methodName);
#endif
#endif
int argc = LuaDLL.lua_gettop(l);
if(matchType(l,argc,2,typeof(UnityEngine.ComputeShader),typeof(int),typeof(UnityEngine.Matrix4x4))){
UnityEngine.Rendering.CommandBuffer self=(UnityEngine.Rendering.CommandBuffer)checkSelf(l);
UnityEngine.ComputeShader a1;
checkType(l,2,out a1);
System.Int32 a2;
checkType(l,3,out a2);
UnityEngine.Matrix4x4 a3;
checkValueType(l,4,out a3);
self.SetComputeMatrixParam(a1,a2,a3);
pushValue(l,true);
return 1;
}
else if(matchType(l,argc,2,typeof(UnityEngine.ComputeShader),typeof(string),typeof(UnityEngine.Matrix4x4))){
UnityEngine.Rendering.CommandBuffer self=(UnityEngine.Rendering.CommandBuffer)checkSelf(l);
UnityEngine.ComputeShader a1;
checkType(l,2,out a1);
System.String a2;
checkType(l,3,out a2);
UnityEngine.Matrix4x4 a3;
checkValueType(l,4,out a3);
self.SetComputeMatrixParam(a1,a2,a3);
pushValue(l,true);
return 1;
}
pushValue(l,false);
LuaDLL.lua_pushstring(l,"No matched override function SetComputeMatrixParam to call");
return 2;
}
catch(Exception e) {
return error(l,e);
}
#if DEBUG
finally {
#if UNITY_5_5_OR_NEWER
UnityEngine.Profiling.Profiler.EndSample();
#else
Profiler.EndSample();
#endif
}
#endif
}
[SLua.MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
[UnityEngine.Scripting.Preserve]
static public int SetComputeMatrixArrayParam(IntPtr l) {
try {
#if DEBUG
var method = System.Reflection.MethodBase.GetCurrentMethod();
string methodName = GetMethodName(method);
#if UNITY_5_5_OR_NEWER
UnityEngine.Profiling.Profiler.BeginSample(methodName);
#else
Profiler.BeginSample(methodName);
#endif
#endif
int argc = LuaDLL.lua_gettop(l);
if(matchType(l,argc,2,typeof(UnityEngine.ComputeShader),typeof(int),typeof(UnityEngine.Matrix4x4[]))){
UnityEngine.Rendering.CommandBuffer self=(UnityEngine.Rendering.CommandBuffer)checkSelf(l);
UnityEngine.ComputeShader a1;
checkType(l,2,out a1);
System.Int32 a2;
checkType(l,3,out a2);
UnityEngine.Matrix4x4[] a3;
checkArray(l,4,out a3);
self.SetComputeMatrixArrayParam(a1,a2,a3);
pushValue(l,true);
return 1;
}
else if(matchType(l,argc,2,typeof(UnityEngine.ComputeShader),typeof(string),typeof(UnityEngine.Matrix4x4[]))){
UnityEngine.Rendering.CommandBuffer self=(UnityEngine.Rendering.CommandBuffer)checkSelf(l);
UnityEngine.ComputeShader a1;
checkType(l,2,out a1);
System.String a2;
checkType(l,3,out a2);
UnityEngine.Matrix4x4[] a3;
checkArray(l,4,out a3);
self.SetComputeMatrixArrayParam(a1,a2,a3);
pushValue(l,true);
return 1;
}
pushValue(l,false);
LuaDLL.lua_pushstring(l,"No matched override function SetComputeMatrixArrayParam to call");
return 2;
}
catch(Exception e) {
return error(l,e);
}
#if DEBUG
finally {
#if UNITY_5_5_OR_NEWER
UnityEngine.Profiling.Profiler.EndSample();
#else
Profiler.EndSample();
#endif
}
#endif
}
[SLua.MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
[UnityEngine.Scripting.Preserve]
static public int SetComputeFloatParams(IntPtr l) {
try {
#if DEBUG
var method = System.Reflection.MethodBase.GetCurrentMethod();
string methodName = GetMethodName(method);
#if UNITY_5_5_OR_NEWER
UnityEngine.Profiling.Profiler.BeginSample(methodName);
#else
Profiler.BeginSample(methodName);
#endif
#endif
int argc = LuaDLL.lua_gettop(l);
if(matchType(l,argc,2,typeof(UnityEngine.ComputeShader),typeof(int),typeof(System.Single[]))){
UnityEngine.Rendering.CommandBuffer self=(UnityEngine.Rendering.CommandBuffer)checkSelf(l);
UnityEngine.ComputeShader a1;
checkType(l,2,out a1);
System.Int32 a2;
checkType(l,3,out a2);
System.Single[] a3;
checkParams(l,4,out a3);
self.SetComputeFloatParams(a1,a2,a3);
pushValue(l,true);
return 1;
}
else if(matchType(l,argc,2,typeof(UnityEngine.ComputeShader),typeof(string),typeof(System.Single[]))){
UnityEngine.Rendering.CommandBuffer self=(UnityEngine.Rendering.CommandBuffer)checkSelf(l);
UnityEngine.ComputeShader a1;
checkType(l,2,out a1);
System.String a2;
checkType(l,3,out a2);
System.Single[] a3;
checkParams(l,4,out a3);
self.SetComputeFloatParams(a1,a2,a3);
pushValue(l,true);
return 1;
}
pushValue(l,false);
LuaDLL.lua_pushstring(l,"No matched override function SetComputeFloatParams to call");
return 2;
}
catch(Exception e) {
return error(l,e);
}
#if DEBUG
finally {
#if UNITY_5_5_OR_NEWER
UnityEngine.Profiling.Profiler.EndSample();
#else
Profiler.EndSample();
#endif
}
#endif
}
[SLua.MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
[UnityEngine.Scripting.Preserve]
static public int SetComputeIntParams(IntPtr l) {
try {
#if DEBUG
var method = System.Reflection.MethodBase.GetCurrentMethod();
string methodName = GetMethodName(method);
#if UNITY_5_5_OR_NEWER
UnityEngine.Profiling.Profiler.BeginSample(methodName);
#else
Profiler.BeginSample(methodName);
#endif
#endif
int argc = LuaDLL.lua_gettop(l);
if(matchType(l,argc,2,typeof(UnityEngine.ComputeShader),typeof(int),typeof(System.Int32[]))){
UnityEngine.Rendering.CommandBuffer self=(UnityEngine.Rendering.CommandBuffer)checkSelf(l);
UnityEngine.ComputeShader a1;
checkType(l,2,out a1);
System.Int32 a2;
checkType(l,3,out a2);
System.Int32[] a3;
checkParams(l,4,out a3);
self.SetComputeIntParams(a1,a2,a3);
pushValue(l,true);
return 1;
}
else if(matchType(l,argc,2,typeof(UnityEngine.ComputeShader),typeof(string),typeof(System.Int32[]))){
UnityEngine.Rendering.CommandBuffer self=(UnityEngine.Rendering.CommandBuffer)checkSelf(l);
UnityEngine.ComputeShader a1;
checkType(l,2,out a1);
System.String a2;
checkType(l,3,out a2);
System.Int32[] a3;
checkParams(l,4,out a3);
self.SetComputeIntParams(a1,a2,a3);
pushValue(l,true);
return 1;
}
pushValue(l,false);
LuaDLL.lua_pushstring(l,"No matched override function SetComputeIntParams to call");
return 2;
}
catch(Exception e) {
return error(l,e);
}
#if DEBUG
finally {
#if UNITY_5_5_OR_NEWER
UnityEngine.Profiling.Profiler.EndSample();
#else
Profiler.EndSample();
#endif
}
#endif
}
[SLua.MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
[UnityEngine.Scripting.Preserve]
static public int SetComputeTextureParam(IntPtr l) {
try {
#if DEBUG
var method = System.Reflection.MethodBase.GetCurrentMethod();
string methodName = GetMethodName(method);
#if UNITY_5_5_OR_NEWER
UnityEngine.Profiling.Profiler.BeginSample(methodName);
#else
Profiler.BeginSample(methodName);
#endif
#endif
int argc = LuaDLL.lua_gettop(l);
if(matchType(l,argc,2,typeof(UnityEngine.ComputeShader),typeof(int),typeof(int),typeof(UnityEngine.Rendering.RenderTargetIdentifier))){
UnityEngine.Rendering.CommandBuffer self=(UnityEngine.Rendering.CommandBuffer)checkSelf(l);
UnityEngine.ComputeShader a1;
checkType(l,2,out a1);
System.Int32 a2;
checkType(l,3,out a2);
System.Int32 a3;
checkType(l,4,out a3);
UnityEngine.Rendering.RenderTargetIdentifier a4;
checkValueType(l,5,out a4);
self.SetComputeTextureParam(a1,a2,a3,a4);
pushValue(l,true);
return 1;
}
else if(matchType(l,argc,2,typeof(UnityEngine.ComputeShader),typeof(int),typeof(string),typeof(UnityEngine.Rendering.RenderTargetIdentifier))){
UnityEngine.Rendering.CommandBuffer self=(UnityEngine.Rendering.CommandBuffer)checkSelf(l);
UnityEngine.ComputeShader a1;
checkType(l,2,out a1);
System.Int32 a2;
checkType(l,3,out a2);
System.String a3;
checkType(l,4,out a3);
UnityEngine.Rendering.RenderTargetIdentifier a4;
checkValueType(l,5,out a4);
self.SetComputeTextureParam(a1,a2,a3,a4);
pushValue(l,true);
return 1;
}
pushValue(l,false);
LuaDLL.lua_pushstring(l,"No matched override function SetComputeTextureParam to call");
return 2;
}
catch(Exception e) {
return error(l,e);
}
#if DEBUG
finally {
#if UNITY_5_5_OR_NEWER
UnityEngine.Profiling.Profiler.EndSample();
#else
Profiler.EndSample();
#endif
}
#endif
}
[SLua.MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
[UnityEngine.Scripting.Preserve]
static public int SetComputeBufferParam(IntPtr l) {
try {
#if DEBUG
var method = System.Reflection.MethodBase.GetCurrentMethod();
string methodName = GetMethodName(method);
#if UNITY_5_5_OR_NEWER
UnityEngine.Profiling.Profiler.BeginSample(methodName);
#else
Profiler.BeginSample(methodName);
#endif
#endif
int argc = LuaDLL.lua_gettop(l);
if(matchType(l,argc,2,typeof(UnityEngine.ComputeShader),typeof(int),typeof(int),typeof(UnityEngine.ComputeBuffer))){
UnityEngine.Rendering.CommandBuffer self=(UnityEngine.Rendering.CommandBuffer)checkSelf(l);
UnityEngine.ComputeShader a1;
checkType(l,2,out a1);
System.Int32 a2;
checkType(l,3,out a2);
System.Int32 a3;
checkType(l,4,out a3);
UnityEngine.ComputeBuffer a4;
checkType(l,5,out a4);
self.SetComputeBufferParam(a1,a2,a3,a4);
pushValue(l,true);
return 1;
}
else if(matchType(l,argc,2,typeof(UnityEngine.ComputeShader),typeof(int),typeof(string),typeof(UnityEngine.ComputeBuffer))){
UnityEngine.Rendering.CommandBuffer self=(UnityEngine.Rendering.CommandBuffer)checkSelf(l);
UnityEngine.ComputeShader a1;
checkType(l,2,out a1);
System.Int32 a2;
checkType(l,3,out a2);
System.String a3;
checkType(l,4,out a3);
UnityEngine.ComputeBuffer a4;
checkType(l,5,out a4);
self.SetComputeBufferParam(a1,a2,a3,a4);
pushValue(l,true);
return 1;
}
pushValue(l,false);
LuaDLL.lua_pushstring(l,"No matched override function SetComputeBufferParam to call");
return 2;
}
catch(Exception e) {
return error(l,e);
}
#if DEBUG
finally {
#if UNITY_5_5_OR_NEWER
UnityEngine.Profiling.Profiler.EndSample();
#else
Profiler.EndSample();
#endif
}
#endif
}
[SLua.MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
[UnityEngine.Scripting.Preserve]
static public int DispatchCompute(IntPtr l) {
try {
#if DEBUG
var method = System.Reflection.MethodBase.GetCurrentMethod();
string methodName = GetMethodName(method);
#if UNITY_5_5_OR_NEWER
UnityEngine.Profiling.Profiler.BeginSample(methodName);
#else
Profiler.BeginSample(methodName);
#endif
#endif
int argc = LuaDLL.lua_gettop(l);
if(argc==5){
UnityEngine.Rendering.CommandBuffer self=(UnityEngine.Rendering.CommandBuffer)checkSelf(l);
UnityEngine.ComputeShader a1;
checkType(l,2,out a1);
System.Int32 a2;
checkType(l,3,out a2);
UnityEngine.ComputeBuffer a3;
checkType(l,4,out a3);
System.UInt32 a4;
checkType(l,5,out a4);
self.DispatchCompute(a1,a2,a3,a4);
pushValue(l,true);
return 1;
}
else if(argc==6){
UnityEngine.Rendering.CommandBuffer self=(UnityEngine.Rendering.CommandBuffer)checkSelf(l);
UnityEngine.ComputeShader a1;
checkType(l,2,out a1);
System.Int32 a2;
checkType(l,3,out a2);
System.Int32 a3;
checkType(l,4,out a3);
System.Int32 a4;
checkType(l,5,out a4);
System.Int32 a5;
checkType(l,6,out a5);
self.DispatchCompute(a1,a2,a3,a4,a5);
pushValue(l,true);
return 1;
}
pushValue(l,false);
LuaDLL.lua_pushstring(l,"No matched override function DispatchCompute to call");
return 2;
}
catch(Exception e) {
return error(l,e);
}
#if DEBUG
finally {
#if UNITY_5_5_OR_NEWER
UnityEngine.Profiling.Profiler.EndSample();
#else
Profiler.EndSample();
#endif
}
#endif
}
[SLua.MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
[UnityEngine.Scripting.Preserve]
static public int GenerateMips(IntPtr l) {
try {
#if DEBUG
var method = System.Reflection.MethodBase.GetCurrentMethod();
string methodName = GetMethodName(method);
#if UNITY_5_5_OR_NEWER
UnityEngine.Profiling.Profiler.BeginSample(methodName);
#else
Profiler.BeginSample(methodName);
#endif
#endif
UnityEngine.Rendering.CommandBuffer self=(UnityEngine.Rendering.CommandBuffer)checkSelf(l);
UnityEngine.RenderTexture a1;
checkType(l,2,out a1);
self.GenerateMips(a1);
pushValue(l,true);
return 1;
}
catch(Exception e) {
return error(l,e);
}
#if DEBUG
finally {
#if UNITY_5_5_OR_NEWER
UnityEngine.Profiling.Profiler.EndSample();
#else
Profiler.EndSample();
#endif
}
#endif
}
[SLua.MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
[UnityEngine.Scripting.Preserve]
static public int CopyCounterValue(IntPtr l) {
try {
#if DEBUG
var method = System.Reflection.MethodBase.GetCurrentMethod();
string methodName = GetMethodName(method);
#if UNITY_5_5_OR_NEWER
UnityEngine.Profiling.Profiler.BeginSample(methodName);
#else
Profiler.BeginSample(methodName);
#endif
#endif
UnityEngine.Rendering.CommandBuffer self=(UnityEngine.Rendering.CommandBuffer)checkSelf(l);
UnityEngine.ComputeBuffer a1;
checkType(l,2,out a1);
UnityEngine.ComputeBuffer a2;
checkType(l,3,out a2);
System.UInt32 a3;
checkType(l,4,out a3);
self.CopyCounterValue(a1,a2,a3);
pushValue(l,true);
return 1;
}
catch(Exception e) {
return error(l,e);
}
#if DEBUG
finally {
#if UNITY_5_5_OR_NEWER
UnityEngine.Profiling.Profiler.EndSample();
#else
Profiler.EndSample();
#endif
}
#endif
}
[SLua.MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
[UnityEngine.Scripting.Preserve]
static public int Clear(IntPtr l) {
try {
#if DEBUG
var method = System.Reflection.MethodBase.GetCurrentMethod();
string methodName = GetMethodName(method);
#if UNITY_5_5_OR_NEWER
UnityEngine.Profiling.Profiler.BeginSample(methodName);
#else
Profiler.BeginSample(methodName);
#endif
#endif
UnityEngine.Rendering.CommandBuffer self=(UnityEngine.Rendering.CommandBuffer)checkSelf(l);
self.Clear();
pushValue(l,true);
return 1;
}
catch(Exception e) {
return error(l,e);
}
#if DEBUG
finally {
#if UNITY_5_5_OR_NEWER
UnityEngine.Profiling.Profiler.EndSample();
#else
Profiler.EndSample();
#endif
}
#endif
}
[SLua.MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
[UnityEngine.Scripting.Preserve]
static public int DrawMesh(IntPtr l) {
try {
#if DEBUG
var method = System.Reflection.MethodBase.GetCurrentMethod();
string methodName = GetMethodName(method);
#if UNITY_5_5_OR_NEWER
UnityEngine.Profiling.Profiler.BeginSample(methodName);
#else
Profiler.BeginSample(methodName);
#endif
#endif
int argc = LuaDLL.lua_gettop(l);
if(argc==4){
UnityEngine.Rendering.CommandBuffer self=(UnityEngine.Rendering.CommandBuffer)checkSelf(l);
UnityEngine.Mesh a1;
checkType(l,2,out a1);
UnityEngine.Matrix4x4 a2;
checkValueType(l,3,out a2);
UnityEngine.Material a3;
checkType(l,4,out a3);
self.DrawMesh(a1,a2,a3);
pushValue(l,true);
return 1;
}
else if(argc==5){
UnityEngine.Rendering.CommandBuffer self=(UnityEngine.Rendering.CommandBuffer)checkSelf(l);
UnityEngine.Mesh a1;
checkType(l,2,out a1);
UnityEngine.Matrix4x4 a2;
checkValueType(l,3,out a2);
UnityEngine.Material a3;
checkType(l,4,out a3);
System.Int32 a4;
checkType(l,5,out a4);
self.DrawMesh(a1,a2,a3,a4);
pushValue(l,true);
return 1;
}
else if(argc==6){
UnityEngine.Rendering.CommandBuffer self=(UnityEngine.Rendering.CommandBuffer)checkSelf(l);
UnityEngine.Mesh a1;
checkType(l,2,out a1);
UnityEngine.Matrix4x4 a2;
checkValueType(l,3,out a2);
UnityEngine.Material a3;
checkType(l,4,out a3);
System.Int32 a4;
checkType(l,5,out a4);
System.Int32 a5;
checkType(l,6,out a5);
self.DrawMesh(a1,a2,a3,a4,a5);
pushValue(l,true);
return 1;
}
else if(argc==7){
UnityEngine.Rendering.CommandBuffer self=(UnityEngine.Rendering.CommandBuffer)checkSelf(l);
UnityEngine.Mesh a1;
checkType(l,2,out a1);
UnityEngine.Matrix4x4 a2;
checkValueType(l,3,out a2);
UnityEngine.Material a3;
checkType(l,4,out a3);
System.Int32 a4;
checkType(l,5,out a4);
System.Int32 a5;
checkType(l,6,out a5);
UnityEngine.MaterialPropertyBlock a6;
checkType(l,7,out a6);
self.DrawMesh(a1,a2,a3,a4,a5,a6);
pushValue(l,true);
return 1;
}
pushValue(l,false);
LuaDLL.lua_pushstring(l,"No matched override function DrawMesh to call");
return 2;
}
catch(Exception e) {
return error(l,e);
}
#if DEBUG
finally {
#if UNITY_5_5_OR_NEWER
UnityEngine.Profiling.Profiler.EndSample();
#else
Profiler.EndSample();
#endif
}
#endif
}
[SLua.MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
[UnityEngine.Scripting.Preserve]
static public int DrawRenderer(IntPtr l) {
try {
#if DEBUG
var method = System.Reflection.MethodBase.GetCurrentMethod();
string methodName = GetMethodName(method);
#if UNITY_5_5_OR_NEWER
UnityEngine.Profiling.Profiler.BeginSample(methodName);
#else
Profiler.BeginSample(methodName);
#endif
#endif
int argc = LuaDLL.lua_gettop(l);
if(argc==3){
UnityEngine.Rendering.CommandBuffer self=(UnityEngine.Rendering.CommandBuffer)checkSelf(l);
UnityEngine.Renderer a1;
checkType(l,2,out a1);
UnityEngine.Material a2;
checkType(l,3,out a2);
self.DrawRenderer(a1,a2);
pushValue(l,true);
return 1;
}
else if(argc==4){
UnityEngine.Rendering.CommandBuffer self=(UnityEngine.Rendering.CommandBuffer)checkSelf(l);
UnityEngine.Renderer a1;
checkType(l,2,out a1);
UnityEngine.Material a2;
checkType(l,3,out a2);
System.Int32 a3;
checkType(l,4,out a3);
self.DrawRenderer(a1,a2,a3);
pushValue(l,true);
return 1;
}
else if(argc==5){
UnityEngine.Rendering.CommandBuffer self=(UnityEngine.Rendering.CommandBuffer)checkSelf(l);
UnityEngine.Renderer a1;
checkType(l,2,out a1);
UnityEngine.Material a2;
checkType(l,3,out a2);
System.Int32 a3;
checkType(l,4,out a3);
System.Int32 a4;
checkType(l,5,out a4);
self.DrawRenderer(a1,a2,a3,a4);
pushValue(l,true);
return 1;
}
pushValue(l,false);
LuaDLL.lua_pushstring(l,"No matched override function DrawRenderer to call");
return 2;
}
catch(Exception e) {
return error(l,e);
}
#if DEBUG
finally {
#if UNITY_5_5_OR_NEWER
UnityEngine.Profiling.Profiler.EndSample();
#else
Profiler.EndSample();
#endif
}
#endif
}
[SLua.MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
[UnityEngine.Scripting.Preserve]
static public int DrawProcedural(IntPtr l) {
try {
#if DEBUG
var method = System.Reflection.MethodBase.GetCurrentMethod();
string methodName = GetMethodName(method);
#if UNITY_5_5_OR_NEWER
UnityEngine.Profiling.Profiler.BeginSample(methodName);
#else
Profiler.BeginSample(methodName);
#endif
#endif
int argc = LuaDLL.lua_gettop(l);
if(argc==6){
UnityEngine.Rendering.CommandBuffer self=(UnityEngine.Rendering.CommandBuffer)checkSelf(l);
UnityEngine.Matrix4x4 a1;
checkValueType(l,2,out a1);
UnityEngine.Material a2;
checkType(l,3,out a2);
System.Int32 a3;
checkType(l,4,out a3);
UnityEngine.MeshTopology a4;
a4 = (UnityEngine.MeshTopology)LuaDLL.luaL_checkinteger(l, 5);
System.Int32 a5;
checkType(l,6,out a5);
self.DrawProcedural(a1,a2,a3,a4,a5);
pushValue(l,true);
return 1;
}
else if(argc==7){
UnityEngine.Rendering.CommandBuffer self=(UnityEngine.Rendering.CommandBuffer)checkSelf(l);
UnityEngine.Matrix4x4 a1;
checkValueType(l,2,out a1);
UnityEngine.Material a2;
checkType(l,3,out a2);
System.Int32 a3;
checkType(l,4,out a3);
UnityEngine.MeshTopology a4;
a4 = (UnityEngine.MeshTopology)LuaDLL.luaL_checkinteger(l, 5);
System.Int32 a5;
checkType(l,6,out a5);
System.Int32 a6;
checkType(l,7,out a6);
self.DrawProcedural(a1,a2,a3,a4,a5,a6);
pushValue(l,true);
return 1;
}
else if(argc==8){
UnityEngine.Rendering.CommandBuffer self=(UnityEngine.Rendering.CommandBuffer)checkSelf(l);
UnityEngine.Matrix4x4 a1;
checkValueType(l,2,out a1);
UnityEngine.Material a2;
checkType(l,3,out a2);
System.Int32 a3;
checkType(l,4,out a3);
UnityEngine.MeshTopology a4;
a4 = (UnityEngine.MeshTopology)LuaDLL.luaL_checkinteger(l, 5);
System.Int32 a5;
checkType(l,6,out a5);
System.Int32 a6;
checkType(l,7,out a6);
UnityEngine.MaterialPropertyBlock a7;
checkType(l,8,out a7);
self.DrawProcedural(a1,a2,a3,a4,a5,a6,a7);
pushValue(l,true);
return 1;
}
pushValue(l,false);
LuaDLL.lua_pushstring(l,"No matched override function DrawProcedural to call");
return 2;
}
catch(Exception e) {
return error(l,e);
}
#if DEBUG
finally {
#if UNITY_5_5_OR_NEWER
UnityEngine.Profiling.Profiler.EndSample();
#else
Profiler.EndSample();
#endif
}
#endif
}
[SLua.MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
[UnityEngine.Scripting.Preserve]
static public int DrawProceduralIndirect(IntPtr l) {
try {
#if DEBUG
var method = System.Reflection.MethodBase.GetCurrentMethod();
string methodName = GetMethodName(method);
#if UNITY_5_5_OR_NEWER
UnityEngine.Profiling.Profiler.BeginSample(methodName);
#else
Profiler.BeginSample(methodName);
#endif
#endif
int argc = LuaDLL.lua_gettop(l);
if(argc==6){
UnityEngine.Rendering.CommandBuffer self=(UnityEngine.Rendering.CommandBuffer)checkSelf(l);
UnityEngine.Matrix4x4 a1;
checkValueType(l,2,out a1);
UnityEngine.Material a2;
checkType(l,3,out a2);
System.Int32 a3;
checkType(l,4,out a3);
UnityEngine.MeshTopology a4;
a4 = (UnityEngine.MeshTopology)LuaDLL.luaL_checkinteger(l, 5);
UnityEngine.ComputeBuffer a5;
checkType(l,6,out a5);
self.DrawProceduralIndirect(a1,a2,a3,a4,a5);
pushValue(l,true);
return 1;
}
else if(argc==7){
UnityEngine.Rendering.CommandBuffer self=(UnityEngine.Rendering.CommandBuffer)checkSelf(l);
UnityEngine.Matrix4x4 a1;
checkValueType(l,2,out a1);
UnityEngine.Material a2;
checkType(l,3,out a2);
System.Int32 a3;
checkType(l,4,out a3);
UnityEngine.MeshTopology a4;
a4 = (UnityEngine.MeshTopology)LuaDLL.luaL_checkinteger(l, 5);
UnityEngine.ComputeBuffer a5;
checkType(l,6,out a5);
System.Int32 a6;
checkType(l,7,out a6);
self.DrawProceduralIndirect(a1,a2,a3,a4,a5,a6);
pushValue(l,true);
return 1;
}
else if(argc==8){
UnityEngine.Rendering.CommandBuffer self=(UnityEngine.Rendering.CommandBuffer)checkSelf(l);
UnityEngine.Matrix4x4 a1;
checkValueType(l,2,out a1);
UnityEngine.Material a2;
checkType(l,3,out a2);
System.Int32 a3;
checkType(l,4,out a3);
UnityEngine.MeshTopology a4;
a4 = (UnityEngine.MeshTopology)LuaDLL.luaL_checkinteger(l, 5);
UnityEngine.ComputeBuffer a5;
checkType(l,6,out a5);
System.Int32 a6;
checkType(l,7,out a6);
UnityEngine.MaterialPropertyBlock a7;
checkType(l,8,out a7);
self.DrawProceduralIndirect(a1,a2,a3,a4,a5,a6,a7);
pushValue(l,true);
return 1;
}
pushValue(l,false);
LuaDLL.lua_pushstring(l,"No matched override function DrawProceduralIndirect to call");
return 2;
}
catch(Exception e) {
return error(l,e);
}
#if DEBUG
finally {
#if UNITY_5_5_OR_NEWER
UnityEngine.Profiling.Profiler.EndSample();
#else
Profiler.EndSample();
#endif
}
#endif
}
[SLua.MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
[UnityEngine.Scripting.Preserve]
static public int DrawMeshInstanced(IntPtr l) {
try {
#if DEBUG
var method = System.Reflection.MethodBase.GetCurrentMethod();
string methodName = GetMethodName(method);
#if UNITY_5_5_OR_NEWER
UnityEngine.Profiling.Profiler.BeginSample(methodName);
#else
Profiler.BeginSample(methodName);
#endif
#endif
int argc = LuaDLL.lua_gettop(l);
if(argc==6){
UnityEngine.Rendering.CommandBuffer self=(UnityEngine.Rendering.CommandBuffer)checkSelf(l);
UnityEngine.Mesh a1;
checkType(l,2,out a1);
System.Int32 a2;
checkType(l,3,out a2);
UnityEngine.Material a3;
checkType(l,4,out a3);
System.Int32 a4;
checkType(l,5,out a4);
UnityEngine.Matrix4x4[] a5;
checkArray(l,6,out a5);
self.DrawMeshInstanced(a1,a2,a3,a4,a5);
pushValue(l,true);
return 1;
}
else if(argc==7){
UnityEngine.Rendering.CommandBuffer self=(UnityEngine.Rendering.CommandBuffer)checkSelf(l);
UnityEngine.Mesh a1;
checkType(l,2,out a1);
System.Int32 a2;
checkType(l,3,out a2);
UnityEngine.Material a3;
checkType(l,4,out a3);
System.Int32 a4;
checkType(l,5,out a4);
UnityEngine.Matrix4x4[] a5;
checkArray(l,6,out a5);
System.Int32 a6;
checkType(l,7,out a6);
self.DrawMeshInstanced(a1,a2,a3,a4,a5,a6);
pushValue(l,true);
return 1;
}
else if(argc==8){
UnityEngine.Rendering.CommandBuffer self=(UnityEngine.Rendering.CommandBuffer)checkSelf(l);
UnityEngine.Mesh a1;
checkType(l,2,out a1);
System.Int32 a2;
checkType(l,3,out a2);
UnityEngine.Material a3;
checkType(l,4,out a3);
System.Int32 a4;
checkType(l,5,out a4);
UnityEngine.Matrix4x4[] a5;
checkArray(l,6,out a5);
System.Int32 a6;
checkType(l,7,out a6);
UnityEngine.MaterialPropertyBlock a7;
checkType(l,8,out a7);
self.DrawMeshInstanced(a1,a2,a3,a4,a5,a6,a7);
pushValue(l,true);
return 1;
}
pushValue(l,false);
LuaDLL.lua_pushstring(l,"No matched override function DrawMeshInstanced to call");
return 2;
}
catch(Exception e) {
return error(l,e);
}
#if DEBUG
finally {
#if UNITY_5_5_OR_NEWER
UnityEngine.Profiling.Profiler.EndSample();
#else
Profiler.EndSample();
#endif
}
#endif
}
[SLua.MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
[UnityEngine.Scripting.Preserve]
static public int DrawMeshInstancedIndirect(IntPtr l) {
try {
#if DEBUG
var method = System.Reflection.MethodBase.GetCurrentMethod();
string methodName = GetMethodName(method);
#if UNITY_5_5_OR_NEWER
UnityEngine.Profiling.Profiler.BeginSample(methodName);
#else
Profiler.BeginSample(methodName);
#endif
#endif
int argc = LuaDLL.lua_gettop(l);
if(argc==6){
UnityEngine.Rendering.CommandBuffer self=(UnityEngine.Rendering.CommandBuffer)checkSelf(l);
UnityEngine.Mesh a1;
checkType(l,2,out a1);
System.Int32 a2;
checkType(l,3,out a2);
UnityEngine.Material a3;
checkType(l,4,out a3);
System.Int32 a4;
checkType(l,5,out a4);
UnityEngine.ComputeBuffer a5;
checkType(l,6,out a5);
self.DrawMeshInstancedIndirect(a1,a2,a3,a4,a5);
pushValue(l,true);
return 1;
}
else if(argc==7){
UnityEngine.Rendering.CommandBuffer self=(UnityEngine.Rendering.CommandBuffer)checkSelf(l);
UnityEngine.Mesh a1;
checkType(l,2,out a1);
System.Int32 a2;
checkType(l,3,out a2);
UnityEngine.Material a3;
checkType(l,4,out a3);
System.Int32 a4;
checkType(l,5,out a4);
UnityEngine.ComputeBuffer a5;
checkType(l,6,out a5);
System.Int32 a6;
checkType(l,7,out a6);
self.DrawMeshInstancedIndirect(a1,a2,a3,a4,a5,a6);
pushValue(l,true);
return 1;
}
else if(argc==8){
UnityEngine.Rendering.CommandBuffer self=(UnityEngine.Rendering.CommandBuffer)checkSelf(l);
UnityEngine.Mesh a1;
checkType(l,2,out a1);
System.Int32 a2;
checkType(l,3,out a2);
UnityEngine.Material a3;
checkType(l,4,out a3);
System.Int32 a4;
checkType(l,5,out a4);
UnityEngine.ComputeBuffer a5;
checkType(l,6,out a5);
System.Int32 a6;
checkType(l,7,out a6);
UnityEngine.MaterialPropertyBlock a7;
checkType(l,8,out a7);
self.DrawMeshInstancedIndirect(a1,a2,a3,a4,a5,a6,a7);
pushValue(l,true);
return 1;
}
pushValue(l,false);
LuaDLL.lua_pushstring(l,"No matched override function DrawMeshInstancedIndirect to call");
return 2;
}
catch(Exception e) {
return error(l,e);
}
#if DEBUG
finally {
#if UNITY_5_5_OR_NEWER
UnityEngine.Profiling.Profiler.EndSample();
#else
Profiler.EndSample();
#endif
}
#endif
}
[SLua.MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
[UnityEngine.Scripting.Preserve]
static public int SetRenderTarget(IntPtr l) {
try {
#if DEBUG
var method = System.Reflection.MethodBase.GetCurrentMethod();
string methodName = GetMethodName(method);
#if UNITY_5_5_OR_NEWER
UnityEngine.Profiling.Profiler.BeginSample(methodName);
#else
Profiler.BeginSample(methodName);
#endif
#endif
int argc = LuaDLL.lua_gettop(l);
if(argc==2){
UnityEngine.Rendering.CommandBuffer self=(UnityEngine.Rendering.CommandBuffer)checkSelf(l);
UnityEngine.Rendering.RenderTargetIdentifier a1;
checkValueType(l,2,out a1);
self.SetRenderTarget(a1);
pushValue(l,true);
return 1;
}
else if(matchType(l,argc,2,typeof(UnityEngine.Rendering.RenderTargetIdentifier),typeof(UnityEngine.Rendering.RenderTargetIdentifier))){
UnityEngine.Rendering.CommandBuffer self=(UnityEngine.Rendering.CommandBuffer)checkSelf(l);
UnityEngine.Rendering.RenderTargetIdentifier a1;
checkValueType(l,2,out a1);
UnityEngine.Rendering.RenderTargetIdentifier a2;
checkValueType(l,3,out a2);
self.SetRenderTarget(a1,a2);
pushValue(l,true);
return 1;
}
else if(matchType(l,argc,2,typeof(UnityEngine.Rendering.RenderTargetIdentifier[]),typeof(UnityEngine.Rendering.RenderTargetIdentifier))){
UnityEngine.Rendering.CommandBuffer self=(UnityEngine.Rendering.CommandBuffer)checkSelf(l);
UnityEngine.Rendering.RenderTargetIdentifier[] a1;
checkArray(l,2,out a1);
UnityEngine.Rendering.RenderTargetIdentifier a2;
checkValueType(l,3,out a2);
self.SetRenderTarget(a1,a2);
pushValue(l,true);
return 1;
}
else if(matchType(l,argc,2,typeof(UnityEngine.Rendering.RenderTargetIdentifier),typeof(int))){
UnityEngine.Rendering.CommandBuffer self=(UnityEngine.Rendering.CommandBuffer)checkSelf(l);
UnityEngine.Rendering.RenderTargetIdentifier a1;
checkValueType(l,2,out a1);
System.Int32 a2;
checkType(l,3,out a2);
self.SetRenderTarget(a1,a2);
pushValue(l,true);
return 1;
}
else if(matchType(l,argc,2,typeof(UnityEngine.Rendering.RenderTargetIdentifier),typeof(UnityEngine.Rendering.RenderTargetIdentifier),typeof(int))){
UnityEngine.Rendering.CommandBuffer self=(UnityEngine.Rendering.CommandBuffer)checkSelf(l);
UnityEngine.Rendering.RenderTargetIdentifier a1;
checkValueType(l,2,out a1);
UnityEngine.Rendering.RenderTargetIdentifier a2;
checkValueType(l,3,out a2);
System.Int32 a3;
checkType(l,4,out a3);
self.SetRenderTarget(a1,a2,a3);
pushValue(l,true);
return 1;
}
else if(matchType(l,argc,2,typeof(UnityEngine.Rendering.RenderTargetIdentifier),typeof(int),typeof(UnityEngine.CubemapFace))){
UnityEngine.Rendering.CommandBuffer self=(UnityEngine.Rendering.CommandBuffer)checkSelf(l);
UnityEngine.Rendering.RenderTargetIdentifier a1;
checkValueType(l,2,out a1);
System.Int32 a2;
checkType(l,3,out a2);
UnityEngine.CubemapFace a3;
a3 = (UnityEngine.CubemapFace)LuaDLL.luaL_checkinteger(l, 4);
self.SetRenderTarget(a1,a2,a3);
pushValue(l,true);
return 1;
}
else if(matchType(l,argc,2,typeof(UnityEngine.Rendering.RenderTargetIdentifier),typeof(int),typeof(UnityEngine.CubemapFace),typeof(int))){
UnityEngine.Rendering.CommandBuffer self=(UnityEngine.Rendering.CommandBuffer)checkSelf(l);
UnityEngine.Rendering.RenderTargetIdentifier a1;
checkValueType(l,2,out a1);
System.Int32 a2;
checkType(l,3,out a2);
UnityEngine.CubemapFace a3;
a3 = (UnityEngine.CubemapFace)LuaDLL.luaL_checkinteger(l, 4);
System.Int32 a4;
checkType(l,5,out a4);
self.SetRenderTarget(a1,a2,a3,a4);
pushValue(l,true);
return 1;
}
else if(matchType(l,argc,2,typeof(UnityEngine.Rendering.RenderTargetIdentifier),typeof(UnityEngine.Rendering.RenderTargetIdentifier),typeof(int),typeof(UnityEngine.CubemapFace))){
UnityEngine.Rendering.CommandBuffer self=(UnityEngine.Rendering.CommandBuffer)checkSelf(l);
UnityEngine.Rendering.RenderTargetIdentifier a1;
checkValueType(l,2,out a1);
UnityEngine.Rendering.RenderTargetIdentifier a2;
checkValueType(l,3,out a2);
System.Int32 a3;
checkType(l,4,out a3);
UnityEngine.CubemapFace a4;
a4 = (UnityEngine.CubemapFace)LuaDLL.luaL_checkinteger(l, 5);
self.SetRenderTarget(a1,a2,a3,a4);
pushValue(l,true);
return 1;
}
else if(argc==6){
UnityEngine.Rendering.CommandBuffer self=(UnityEngine.Rendering.CommandBuffer)checkSelf(l);
UnityEngine.Rendering.RenderTargetIdentifier a1;
checkValueType(l,2,out a1);
UnityEngine.Rendering.RenderTargetIdentifier a2;
checkValueType(l,3,out a2);
System.Int32 a3;
checkType(l,4,out a3);
UnityEngine.CubemapFace a4;
a4 = (UnityEngine.CubemapFace)LuaDLL.luaL_checkinteger(l, 5);
System.Int32 a5;
checkType(l,6,out a5);
self.SetRenderTarget(a1,a2,a3,a4,a5);
pushValue(l,true);
return 1;
}
pushValue(l,false);
LuaDLL.lua_pushstring(l,"No matched override function SetRenderTarget to call");
return 2;
}
catch(Exception e) {
return error(l,e);
}
#if DEBUG
finally {
#if UNITY_5_5_OR_NEWER
UnityEngine.Profiling.Profiler.EndSample();
#else
Profiler.EndSample();
#endif
}
#endif
}
[SLua.MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
[UnityEngine.Scripting.Preserve]
static public int SetRandomWriteTarget(IntPtr l) {
try {
#if DEBUG
var method = System.Reflection.MethodBase.GetCurrentMethod();
string methodName = GetMethodName(method);
#if UNITY_5_5_OR_NEWER
UnityEngine.Profiling.Profiler.BeginSample(methodName);
#else
Profiler.BeginSample(methodName);
#endif
#endif
int argc = LuaDLL.lua_gettop(l);
if(matchType(l,argc,2,typeof(int),typeof(UnityEngine.ComputeBuffer))){
UnityEngine.Rendering.CommandBuffer self=(UnityEngine.Rendering.CommandBuffer)checkSelf(l);
System.Int32 a1;
checkType(l,2,out a1);
UnityEngine.ComputeBuffer a2;
checkType(l,3,out a2);
self.SetRandomWriteTarget(a1,a2);
pushValue(l,true);
return 1;
}
else if(matchType(l,argc,2,typeof(int),typeof(UnityEngine.Rendering.RenderTargetIdentifier))){
UnityEngine.Rendering.CommandBuffer self=(UnityEngine.Rendering.CommandBuffer)checkSelf(l);
System.Int32 a1;
checkType(l,2,out a1);
UnityEngine.Rendering.RenderTargetIdentifier a2;
checkValueType(l,3,out a2);
self.SetRandomWriteTarget(a1,a2);
pushValue(l,true);
return 1;
}
else if(argc==4){
UnityEngine.Rendering.CommandBuffer self=(UnityEngine.Rendering.CommandBuffer)checkSelf(l);
System.Int32 a1;
checkType(l,2,out a1);
UnityEngine.ComputeBuffer a2;
checkType(l,3,out a2);
System.Boolean a3;
checkType(l,4,out a3);
self.SetRandomWriteTarget(a1,a2,a3);
pushValue(l,true);
return 1;
}
pushValue(l,false);
LuaDLL.lua_pushstring(l,"No matched override function SetRandomWriteTarget to call");
return 2;
}
catch(Exception e) {
return error(l,e);
}
#if DEBUG
finally {
#if UNITY_5_5_OR_NEWER
UnityEngine.Profiling.Profiler.EndSample();
#else
Profiler.EndSample();
#endif
}
#endif
}
[SLua.MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
[UnityEngine.Scripting.Preserve]
static public int ClearRandomWriteTargets(IntPtr l) {
try {
#if DEBUG
var method = System.Reflection.MethodBase.GetCurrentMethod();
string methodName = GetMethodName(method);
#if UNITY_5_5_OR_NEWER
UnityEngine.Profiling.Profiler.BeginSample(methodName);
#else
Profiler.BeginSample(methodName);
#endif
#endif
UnityEngine.Rendering.CommandBuffer self=(UnityEngine.Rendering.CommandBuffer)checkSelf(l);
self.ClearRandomWriteTargets();
pushValue(l,true);
return 1;
}
catch(Exception e) {
return error(l,e);
}
#if DEBUG
finally {
#if UNITY_5_5_OR_NEWER
UnityEngine.Profiling.Profiler.EndSample();
#else
Profiler.EndSample();
#endif
}
#endif
}
[SLua.MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
[UnityEngine.Scripting.Preserve]
static public int CopyTexture(IntPtr l) {
try {
#if DEBUG
var method = System.Reflection.MethodBase.GetCurrentMethod();
string methodName = GetMethodName(method);
#if UNITY_5_5_OR_NEWER
UnityEngine.Profiling.Profiler.BeginSample(methodName);
#else
Profiler.BeginSample(methodName);
#endif
#endif
int argc = LuaDLL.lua_gettop(l);
if(argc==3){
UnityEngine.Rendering.CommandBuffer self=(UnityEngine.Rendering.CommandBuffer)checkSelf(l);
UnityEngine.Rendering.RenderTargetIdentifier a1;
checkValueType(l,2,out a1);
UnityEngine.Rendering.RenderTargetIdentifier a2;
checkValueType(l,3,out a2);
self.CopyTexture(a1,a2);
pushValue(l,true);
return 1;
}
else if(argc==5){
UnityEngine.Rendering.CommandBuffer self=(UnityEngine.Rendering.CommandBuffer)checkSelf(l);
UnityEngine.Rendering.RenderTargetIdentifier a1;
checkValueType(l,2,out a1);
System.Int32 a2;
checkType(l,3,out a2);
UnityEngine.Rendering.RenderTargetIdentifier a3;
checkValueType(l,4,out a3);
System.Int32 a4;
checkType(l,5,out a4);
self.CopyTexture(a1,a2,a3,a4);
pushValue(l,true);
return 1;
}
else if(argc==7){
UnityEngine.Rendering.CommandBuffer self=(UnityEngine.Rendering.CommandBuffer)checkSelf(l);
UnityEngine.Rendering.RenderTargetIdentifier a1;
checkValueType(l,2,out a1);
System.Int32 a2;
checkType(l,3,out a2);
System.Int32 a3;
checkType(l,4,out a3);
UnityEngine.Rendering.RenderTargetIdentifier a4;
checkValueType(l,5,out a4);
System.Int32 a5;
checkType(l,6,out a5);
System.Int32 a6;
checkType(l,7,out a6);
self.CopyTexture(a1,a2,a3,a4,a5,a6);
pushValue(l,true);
return 1;
}
else if(argc==13){
UnityEngine.Rendering.CommandBuffer self=(UnityEngine.Rendering.CommandBuffer)checkSelf(l);
UnityEngine.Rendering.RenderTargetIdentifier a1;
checkValueType(l,2,out a1);
System.Int32 a2;
checkType(l,3,out a2);
System.Int32 a3;
checkType(l,4,out a3);
System.Int32 a4;
checkType(l,5,out a4);
System.Int32 a5;
checkType(l,6,out a5);
System.Int32 a6;
checkType(l,7,out a6);
System.Int32 a7;
checkType(l,8,out a7);
UnityEngine.Rendering.RenderTargetIdentifier a8;
checkValueType(l,9,out a8);
System.Int32 a9;
checkType(l,10,out a9);
System.Int32 a10;
checkType(l,11,out a10);
System.Int32 a11;
checkType(l,12,out a11);
System.Int32 a12;
checkType(l,13,out a12);
self.CopyTexture(a1,a2,a3,a4,a5,a6,a7,a8,a9,a10,a11,a12);
pushValue(l,true);
return 1;
}
pushValue(l,false);
LuaDLL.lua_pushstring(l,"No matched override function CopyTexture to call");
return 2;
}
catch(Exception e) {
return error(l,e);
}
#if DEBUG
finally {
#if UNITY_5_5_OR_NEWER
UnityEngine.Profiling.Profiler.EndSample();
#else
Profiler.EndSample();
#endif
}
#endif
}
[SLua.MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
[UnityEngine.Scripting.Preserve]
static public int SetViewport(IntPtr l) {
try {
#if DEBUG
var method = System.Reflection.MethodBase.GetCurrentMethod();
string methodName = GetMethodName(method);
#if UNITY_5_5_OR_NEWER
UnityEngine.Profiling.Profiler.BeginSample(methodName);
#else
Profiler.BeginSample(methodName);
#endif
#endif
UnityEngine.Rendering.CommandBuffer self=(UnityEngine.Rendering.CommandBuffer)checkSelf(l);
UnityEngine.Rect a1;
checkValueType(l,2,out a1);
self.SetViewport(a1);
pushValue(l,true);
return 1;
}
catch(Exception e) {
return error(l,e);
}
#if DEBUG
finally {
#if UNITY_5_5_OR_NEWER
UnityEngine.Profiling.Profiler.EndSample();
#else
Profiler.EndSample();
#endif
}
#endif
}
[SLua.MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
[UnityEngine.Scripting.Preserve]
static public int Blit(IntPtr l) {
try {
#if DEBUG
var method = System.Reflection.MethodBase.GetCurrentMethod();
string methodName = GetMethodName(method);
#if UNITY_5_5_OR_NEWER
UnityEngine.Profiling.Profiler.BeginSample(methodName);
#else
Profiler.BeginSample(methodName);
#endif
#endif
int argc = LuaDLL.lua_gettop(l);
if(matchType(l,argc,2,typeof(UnityEngine.Rendering.RenderTargetIdentifier),typeof(UnityEngine.Rendering.RenderTargetIdentifier))){
UnityEngine.Rendering.CommandBuffer self=(UnityEngine.Rendering.CommandBuffer)checkSelf(l);
UnityEngine.Rendering.RenderTargetIdentifier a1;
checkValueType(l,2,out a1);
UnityEngine.Rendering.RenderTargetIdentifier a2;
checkValueType(l,3,out a2);
self.Blit(a1,a2);
pushValue(l,true);
return 1;
}
else if(matchType(l,argc,2,typeof(UnityEngine.Texture),typeof(UnityEngine.Rendering.RenderTargetIdentifier))){
UnityEngine.Rendering.CommandBuffer self=(UnityEngine.Rendering.CommandBuffer)checkSelf(l);
UnityEngine.Texture a1;
checkType(l,2,out a1);
UnityEngine.Rendering.RenderTargetIdentifier a2;
checkValueType(l,3,out a2);
self.Blit(a1,a2);
pushValue(l,true);
return 1;
}
else if(matchType(l,argc,2,typeof(UnityEngine.Rendering.RenderTargetIdentifier),typeof(UnityEngine.Rendering.RenderTargetIdentifier),typeof(UnityEngine.Material))){
UnityEngine.Rendering.CommandBuffer self=(UnityEngine.Rendering.CommandBuffer)checkSelf(l);
UnityEngine.Rendering.RenderTargetIdentifier a1;
checkValueType(l,2,out a1);
UnityEngine.Rendering.RenderTargetIdentifier a2;
checkValueType(l,3,out a2);
UnityEngine.Material a3;
checkType(l,4,out a3);
self.Blit(a1,a2,a3);
pushValue(l,true);
return 1;
}
else if(matchType(l,argc,2,typeof(UnityEngine.Texture),typeof(UnityEngine.Rendering.RenderTargetIdentifier),typeof(UnityEngine.Material))){
UnityEngine.Rendering.CommandBuffer self=(UnityEngine.Rendering.CommandBuffer)checkSelf(l);
UnityEngine.Texture a1;
checkType(l,2,out a1);
UnityEngine.Rendering.RenderTargetIdentifier a2;
checkValueType(l,3,out a2);
UnityEngine.Material a3;
checkType(l,4,out a3);
self.Blit(a1,a2,a3);
pushValue(l,true);
return 1;
}
else if(matchType(l,argc,2,typeof(UnityEngine.Rendering.RenderTargetIdentifier),typeof(UnityEngine.Rendering.RenderTargetIdentifier),typeof(UnityEngine.Material),typeof(int))){
UnityEngine.Rendering.CommandBuffer self=(UnityEngine.Rendering.CommandBuffer)checkSelf(l);
UnityEngine.Rendering.RenderTargetIdentifier a1;
checkValueType(l,2,out a1);
UnityEngine.Rendering.RenderTargetIdentifier a2;
checkValueType(l,3,out a2);
UnityEngine.Material a3;
checkType(l,4,out a3);
System.Int32 a4;
checkType(l,5,out a4);
self.Blit(a1,a2,a3,a4);
pushValue(l,true);
return 1;
}
else if(matchType(l,argc,2,typeof(UnityEngine.Rendering.RenderTargetIdentifier),typeof(UnityEngine.Rendering.RenderTargetIdentifier),typeof(UnityEngine.Vector2),typeof(UnityEngine.Vector2))){
UnityEngine.Rendering.CommandBuffer self=(UnityEngine.Rendering.CommandBuffer)checkSelf(l);
UnityEngine.Rendering.RenderTargetIdentifier a1;
checkValueType(l,2,out a1);
UnityEngine.Rendering.RenderTargetIdentifier a2;
checkValueType(l,3,out a2);
UnityEngine.Vector2 a3;
checkType(l,4,out a3);
UnityEngine.Vector2 a4;
checkType(l,5,out a4);
self.Blit(a1,a2,a3,a4);
pushValue(l,true);
return 1;
}
else if(matchType(l,argc,2,typeof(UnityEngine.Texture),typeof(UnityEngine.Rendering.RenderTargetIdentifier),typeof(UnityEngine.Vector2),typeof(UnityEngine.Vector2))){
UnityEngine.Rendering.CommandBuffer self=(UnityEngine.Rendering.CommandBuffer)checkSelf(l);
UnityEngine.Texture a1;
checkType(l,2,out a1);
UnityEngine.Rendering.RenderTargetIdentifier a2;
checkValueType(l,3,out a2);
UnityEngine.Vector2 a3;
checkType(l,4,out a3);
UnityEngine.Vector2 a4;
checkType(l,5,out a4);
self.Blit(a1,a2,a3,a4);
pushValue(l,true);
return 1;
}
else if(matchType(l,argc,2,typeof(UnityEngine.Texture),typeof(UnityEngine.Rendering.RenderTargetIdentifier),typeof(UnityEngine.Material),typeof(int))){
UnityEngine.Rendering.CommandBuffer self=(UnityEngine.Rendering.CommandBuffer)checkSelf(l);
UnityEngine.Texture a1;
checkType(l,2,out a1);
UnityEngine.Rendering.RenderTargetIdentifier a2;
checkValueType(l,3,out a2);
UnityEngine.Material a3;
checkType(l,4,out a3);
System.Int32 a4;
checkType(l,5,out a4);
self.Blit(a1,a2,a3,a4);
pushValue(l,true);
return 1;
}
pushValue(l,false);
LuaDLL.lua_pushstring(l,"No matched override function Blit to call");
return 2;
}
catch(Exception e) {
return error(l,e);
}
#if DEBUG
finally {
#if UNITY_5_5_OR_NEWER
UnityEngine.Profiling.Profiler.EndSample();
#else
Profiler.EndSample();
#endif
}
#endif
}
[SLua.MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
[UnityEngine.Scripting.Preserve]
static public int GetTemporaryRT(IntPtr l) {
try {
#if DEBUG
var method = System.Reflection.MethodBase.GetCurrentMethod();
string methodName = GetMethodName(method);
#if UNITY_5_5_OR_NEWER
UnityEngine.Profiling.Profiler.BeginSample(methodName);
#else
Profiler.BeginSample(methodName);
#endif
#endif
int argc = LuaDLL.lua_gettop(l);
if(argc==3){
UnityEngine.Rendering.CommandBuffer self=(UnityEngine.Rendering.CommandBuffer)checkSelf(l);
System.Int32 a1;
checkType(l,2,out a1);
UnityEngine.RenderTextureDescriptor a2;
checkValueType(l,3,out a2);
self.GetTemporaryRT(a1,a2);
pushValue(l,true);
return 1;
}
else if(matchType(l,argc,2,typeof(int),typeof(int),typeof(int))){
UnityEngine.Rendering.CommandBuffer self=(UnityEngine.Rendering.CommandBuffer)checkSelf(l);
System.Int32 a1;
checkType(l,2,out a1);
System.Int32 a2;
checkType(l,3,out a2);
System.Int32 a3;
checkType(l,4,out a3);
self.GetTemporaryRT(a1,a2,a3);
pushValue(l,true);
return 1;
}
else if(matchType(l,argc,2,typeof(int),typeof(UnityEngine.RenderTextureDescriptor),typeof(UnityEngine.FilterMode))){
UnityEngine.Rendering.CommandBuffer self=(UnityEngine.Rendering.CommandBuffer)checkSelf(l);
System.Int32 a1;
checkType(l,2,out a1);
UnityEngine.RenderTextureDescriptor a2;
checkValueType(l,3,out a2);
UnityEngine.FilterMode a3;
a3 = (UnityEngine.FilterMode)LuaDLL.luaL_checkinteger(l, 4);
self.GetTemporaryRT(a1,a2,a3);
pushValue(l,true);
return 1;
}
else if(argc==5){
UnityEngine.Rendering.CommandBuffer self=(UnityEngine.Rendering.CommandBuffer)checkSelf(l);
System.Int32 a1;
checkType(l,2,out a1);
System.Int32 a2;
checkType(l,3,out a2);
System.Int32 a3;
checkType(l,4,out a3);
System.Int32 a4;
checkType(l,5,out a4);
self.GetTemporaryRT(a1,a2,a3,a4);
pushValue(l,true);
return 1;
}
else if(argc==6){
UnityEngine.Rendering.CommandBuffer self=(UnityEngine.Rendering.CommandBuffer)checkSelf(l);
System.Int32 a1;
checkType(l,2,out a1);
System.Int32 a2;
checkType(l,3,out a2);
System.Int32 a3;
checkType(l,4,out a3);
System.Int32 a4;
checkType(l,5,out a4);
UnityEngine.FilterMode a5;
a5 = (UnityEngine.FilterMode)LuaDLL.luaL_checkinteger(l, 6);
self.GetTemporaryRT(a1,a2,a3,a4,a5);
pushValue(l,true);
return 1;
}
else if(argc==7){
UnityEngine.Rendering.CommandBuffer self=(UnityEngine.Rendering.CommandBuffer)checkSelf(l);
System.Int32 a1;
checkType(l,2,out a1);
System.Int32 a2;
checkType(l,3,out a2);
System.Int32 a3;
checkType(l,4,out a3);
System.Int32 a4;
checkType(l,5,out a4);
UnityEngine.FilterMode a5;
a5 = (UnityEngine.FilterMode)LuaDLL.luaL_checkinteger(l, 6);
UnityEngine.RenderTextureFormat a6;
a6 = (UnityEngine.RenderTextureFormat)LuaDLL.luaL_checkinteger(l, 7);
self.GetTemporaryRT(a1,a2,a3,a4,a5,a6);
pushValue(l,true);
return 1;
}
else if(argc==8){
UnityEngine.Rendering.CommandBuffer self=(UnityEngine.Rendering.CommandBuffer)checkSelf(l);
System.Int32 a1;
checkType(l,2,out a1);
System.Int32 a2;
checkType(l,3,out a2);
System.Int32 a3;
checkType(l,4,out a3);
System.Int32 a4;
checkType(l,5,out a4);
UnityEngine.FilterMode a5;
a5 = (UnityEngine.FilterMode)LuaDLL.luaL_checkinteger(l, 6);
UnityEngine.RenderTextureFormat a6;
a6 = (UnityEngine.RenderTextureFormat)LuaDLL.luaL_checkinteger(l, 7);
UnityEngine.RenderTextureReadWrite a7;
a7 = (UnityEngine.RenderTextureReadWrite)LuaDLL.luaL_checkinteger(l, 8);
self.GetTemporaryRT(a1,a2,a3,a4,a5,a6,a7);
pushValue(l,true);
return 1;
}
else if(argc==9){
UnityEngine.Rendering.CommandBuffer self=(UnityEngine.Rendering.CommandBuffer)checkSelf(l);
System.Int32 a1;
checkType(l,2,out a1);
System.Int32 a2;
checkType(l,3,out a2);
System.Int32 a3;
checkType(l,4,out a3);
System.Int32 a4;
checkType(l,5,out a4);
UnityEngine.FilterMode a5;
a5 = (UnityEngine.FilterMode)LuaDLL.luaL_checkinteger(l, 6);
UnityEngine.RenderTextureFormat a6;
a6 = (UnityEngine.RenderTextureFormat)LuaDLL.luaL_checkinteger(l, 7);
UnityEngine.RenderTextureReadWrite a7;
a7 = (UnityEngine.RenderTextureReadWrite)LuaDLL.luaL_checkinteger(l, 8);
System.Int32 a8;
checkType(l,9,out a8);
self.GetTemporaryRT(a1,a2,a3,a4,a5,a6,a7,a8);
pushValue(l,true);
return 1;
}
else if(argc==10){
UnityEngine.Rendering.CommandBuffer self=(UnityEngine.Rendering.CommandBuffer)checkSelf(l);
System.Int32 a1;
checkType(l,2,out a1);
System.Int32 a2;
checkType(l,3,out a2);
System.Int32 a3;
checkType(l,4,out a3);
System.Int32 a4;
checkType(l,5,out a4);
UnityEngine.FilterMode a5;
a5 = (UnityEngine.FilterMode)LuaDLL.luaL_checkinteger(l, 6);
UnityEngine.RenderTextureFormat a6;
a6 = (UnityEngine.RenderTextureFormat)LuaDLL.luaL_checkinteger(l, 7);
UnityEngine.RenderTextureReadWrite a7;
a7 = (UnityEngine.RenderTextureReadWrite)LuaDLL.luaL_checkinteger(l, 8);
System.Int32 a8;
checkType(l,9,out a8);
System.Boolean a9;
checkType(l,10,out a9);
self.GetTemporaryRT(a1,a2,a3,a4,a5,a6,a7,a8,a9);
pushValue(l,true);
return 1;
}
else if(argc==11){
UnityEngine.Rendering.CommandBuffer self=(UnityEngine.Rendering.CommandBuffer)checkSelf(l);
System.Int32 a1;
checkType(l,2,out a1);
System.Int32 a2;
checkType(l,3,out a2);
System.Int32 a3;
checkType(l,4,out a3);
System.Int32 a4;
checkType(l,5,out a4);
UnityEngine.FilterMode a5;
a5 = (UnityEngine.FilterMode)LuaDLL.luaL_checkinteger(l, 6);
UnityEngine.RenderTextureFormat a6;
a6 = (UnityEngine.RenderTextureFormat)LuaDLL.luaL_checkinteger(l, 7);
UnityEngine.RenderTextureReadWrite a7;
a7 = (UnityEngine.RenderTextureReadWrite)LuaDLL.luaL_checkinteger(l, 8);
System.Int32 a8;
checkType(l,9,out a8);
System.Boolean a9;
checkType(l,10,out a9);
UnityEngine.RenderTextureMemoryless a10;
a10 = (UnityEngine.RenderTextureMemoryless)LuaDLL.luaL_checkinteger(l, 11);
self.GetTemporaryRT(a1,a2,a3,a4,a5,a6,a7,a8,a9,a10);
pushValue(l,true);
return 1;
}
else if(argc==12){
UnityEngine.Rendering.CommandBuffer self=(UnityEngine.Rendering.CommandBuffer)checkSelf(l);
System.Int32 a1;
checkType(l,2,out a1);
System.Int32 a2;
checkType(l,3,out a2);
System.Int32 a3;
checkType(l,4,out a3);
System.Int32 a4;
checkType(l,5,out a4);
UnityEngine.FilterMode a5;
a5 = (UnityEngine.FilterMode)LuaDLL.luaL_checkinteger(l, 6);
UnityEngine.RenderTextureFormat a6;
a6 = (UnityEngine.RenderTextureFormat)LuaDLL.luaL_checkinteger(l, 7);
UnityEngine.RenderTextureReadWrite a7;
a7 = (UnityEngine.RenderTextureReadWrite)LuaDLL.luaL_checkinteger(l, 8);
System.Int32 a8;
checkType(l,9,out a8);
System.Boolean a9;
checkType(l,10,out a9);
UnityEngine.RenderTextureMemoryless a10;
a10 = (UnityEngine.RenderTextureMemoryless)LuaDLL.luaL_checkinteger(l, 11);
System.Boolean a11;
checkType(l,12,out a11);
self.GetTemporaryRT(a1,a2,a3,a4,a5,a6,a7,a8,a9,a10,a11);
pushValue(l,true);
return 1;
}
pushValue(l,false);
LuaDLL.lua_pushstring(l,"No matched override function GetTemporaryRT to call");
return 2;
}
catch(Exception e) {
return error(l,e);
}
#if DEBUG
finally {
#if UNITY_5_5_OR_NEWER
UnityEngine.Profiling.Profiler.EndSample();
#else
Profiler.EndSample();
#endif
}
#endif
}
[SLua.MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
[UnityEngine.Scripting.Preserve]
static public int GetTemporaryRTArray(IntPtr l) {
try {
#if DEBUG
var method = System.Reflection.MethodBase.GetCurrentMethod();
string methodName = GetMethodName(method);
#if UNITY_5_5_OR_NEWER
UnityEngine.Profiling.Profiler.BeginSample(methodName);
#else
Profiler.BeginSample(methodName);
#endif
#endif
int argc = LuaDLL.lua_gettop(l);
if(argc==5){
UnityEngine.Rendering.CommandBuffer self=(UnityEngine.Rendering.CommandBuffer)checkSelf(l);
System.Int32 a1;
checkType(l,2,out a1);
System.Int32 a2;
checkType(l,3,out a2);
System.Int32 a3;
checkType(l,4,out a3);
System.Int32 a4;
checkType(l,5,out a4);
self.GetTemporaryRTArray(a1,a2,a3,a4);
pushValue(l,true);
return 1;
}
else if(argc==6){
UnityEngine.Rendering.CommandBuffer self=(UnityEngine.Rendering.CommandBuffer)checkSelf(l);
System.Int32 a1;
checkType(l,2,out a1);
System.Int32 a2;
checkType(l,3,out a2);
System.Int32 a3;
checkType(l,4,out a3);
System.Int32 a4;
checkType(l,5,out a4);
System.Int32 a5;
checkType(l,6,out a5);
self.GetTemporaryRTArray(a1,a2,a3,a4,a5);
pushValue(l,true);
return 1;
}
else if(argc==7){
UnityEngine.Rendering.CommandBuffer self=(UnityEngine.Rendering.CommandBuffer)checkSelf(l);
System.Int32 a1;
checkType(l,2,out a1);
System.Int32 a2;
checkType(l,3,out a2);
System.Int32 a3;
checkType(l,4,out a3);
System.Int32 a4;
checkType(l,5,out a4);
System.Int32 a5;
checkType(l,6,out a5);
UnityEngine.FilterMode a6;
a6 = (UnityEngine.FilterMode)LuaDLL.luaL_checkinteger(l, 7);
self.GetTemporaryRTArray(a1,a2,a3,a4,a5,a6);
pushValue(l,true);
return 1;
}
else if(argc==8){
UnityEngine.Rendering.CommandBuffer self=(UnityEngine.Rendering.CommandBuffer)checkSelf(l);
System.Int32 a1;
checkType(l,2,out a1);
System.Int32 a2;
checkType(l,3,out a2);
System.Int32 a3;
checkType(l,4,out a3);
System.Int32 a4;
checkType(l,5,out a4);
System.Int32 a5;
checkType(l,6,out a5);
UnityEngine.FilterMode a6;
a6 = (UnityEngine.FilterMode)LuaDLL.luaL_checkinteger(l, 7);
UnityEngine.RenderTextureFormat a7;
a7 = (UnityEngine.RenderTextureFormat)LuaDLL.luaL_checkinteger(l, 8);
self.GetTemporaryRTArray(a1,a2,a3,a4,a5,a6,a7);
pushValue(l,true);
return 1;
}
else if(argc==9){
UnityEngine.Rendering.CommandBuffer self=(UnityEngine.Rendering.CommandBuffer)checkSelf(l);
System.Int32 a1;
checkType(l,2,out a1);
System.Int32 a2;
checkType(l,3,out a2);
System.Int32 a3;
checkType(l,4,out a3);
System.Int32 a4;
checkType(l,5,out a4);
System.Int32 a5;
checkType(l,6,out a5);
UnityEngine.FilterMode a6;
a6 = (UnityEngine.FilterMode)LuaDLL.luaL_checkinteger(l, 7);
UnityEngine.RenderTextureFormat a7;
a7 = (UnityEngine.RenderTextureFormat)LuaDLL.luaL_checkinteger(l, 8);
UnityEngine.RenderTextureReadWrite a8;
a8 = (UnityEngine.RenderTextureReadWrite)LuaDLL.luaL_checkinteger(l, 9);
self.GetTemporaryRTArray(a1,a2,a3,a4,a5,a6,a7,a8);
pushValue(l,true);
return 1;
}
else if(argc==10){
UnityEngine.Rendering.CommandBuffer self=(UnityEngine.Rendering.CommandBuffer)checkSelf(l);
System.Int32 a1;
checkType(l,2,out a1);
System.Int32 a2;
checkType(l,3,out a2);
System.Int32 a3;
checkType(l,4,out a3);
System.Int32 a4;
checkType(l,5,out a4);
System.Int32 a5;
checkType(l,6,out a5);
UnityEngine.FilterMode a6;
a6 = (UnityEngine.FilterMode)LuaDLL.luaL_checkinteger(l, 7);
UnityEngine.RenderTextureFormat a7;
a7 = (UnityEngine.RenderTextureFormat)LuaDLL.luaL_checkinteger(l, 8);
UnityEngine.RenderTextureReadWrite a8;
a8 = (UnityEngine.RenderTextureReadWrite)LuaDLL.luaL_checkinteger(l, 9);
System.Int32 a9;
checkType(l,10,out a9);
self.GetTemporaryRTArray(a1,a2,a3,a4,a5,a6,a7,a8,a9);
pushValue(l,true);
return 1;
}
else if(argc==11){
UnityEngine.Rendering.CommandBuffer self=(UnityEngine.Rendering.CommandBuffer)checkSelf(l);
System.Int32 a1;
checkType(l,2,out a1);
System.Int32 a2;
checkType(l,3,out a2);
System.Int32 a3;
checkType(l,4,out a3);
System.Int32 a4;
checkType(l,5,out a4);
System.Int32 a5;
checkType(l,6,out a5);
UnityEngine.FilterMode a6;
a6 = (UnityEngine.FilterMode)LuaDLL.luaL_checkinteger(l, 7);
UnityEngine.RenderTextureFormat a7;
a7 = (UnityEngine.RenderTextureFormat)LuaDLL.luaL_checkinteger(l, 8);
UnityEngine.RenderTextureReadWrite a8;
a8 = (UnityEngine.RenderTextureReadWrite)LuaDLL.luaL_checkinteger(l, 9);
System.Int32 a9;
checkType(l,10,out a9);
System.Boolean a10;
checkType(l,11,out a10);
self.GetTemporaryRTArray(a1,a2,a3,a4,a5,a6,a7,a8,a9,a10);
pushValue(l,true);
return 1;
}
else if(argc==12){
UnityEngine.Rendering.CommandBuffer self=(UnityEngine.Rendering.CommandBuffer)checkSelf(l);
System.Int32 a1;
checkType(l,2,out a1);
System.Int32 a2;
checkType(l,3,out a2);
System.Int32 a3;
checkType(l,4,out a3);
System.Int32 a4;
checkType(l,5,out a4);
System.Int32 a5;
checkType(l,6,out a5);
UnityEngine.FilterMode a6;
a6 = (UnityEngine.FilterMode)LuaDLL.luaL_checkinteger(l, 7);
UnityEngine.RenderTextureFormat a7;
a7 = (UnityEngine.RenderTextureFormat)LuaDLL.luaL_checkinteger(l, 8);
UnityEngine.RenderTextureReadWrite a8;
a8 = (UnityEngine.RenderTextureReadWrite)LuaDLL.luaL_checkinteger(l, 9);
System.Int32 a9;
checkType(l,10,out a9);
System.Boolean a10;
checkType(l,11,out a10);
System.Boolean a11;
checkType(l,12,out a11);
self.GetTemporaryRTArray(a1,a2,a3,a4,a5,a6,a7,a8,a9,a10,a11);
pushValue(l,true);
return 1;
}
pushValue(l,false);
LuaDLL.lua_pushstring(l,"No matched override function GetTemporaryRTArray to call");
return 2;
}
catch(Exception e) {
return error(l,e);
}
#if DEBUG
finally {
#if UNITY_5_5_OR_NEWER
UnityEngine.Profiling.Profiler.EndSample();
#else
Profiler.EndSample();
#endif
}
#endif
}
[SLua.MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
[UnityEngine.Scripting.Preserve]
static public int ReleaseTemporaryRT(IntPtr l) {
try {
#if DEBUG
var method = System.Reflection.MethodBase.GetCurrentMethod();
string methodName = GetMethodName(method);
#if UNITY_5_5_OR_NEWER
UnityEngine.Profiling.Profiler.BeginSample(methodName);
#else
Profiler.BeginSample(methodName);
#endif
#endif
UnityEngine.Rendering.CommandBuffer self=(UnityEngine.Rendering.CommandBuffer)checkSelf(l);
System.Int32 a1;
checkType(l,2,out a1);
self.ReleaseTemporaryRT(a1);
pushValue(l,true);
return 1;
}
catch(Exception e) {
return error(l,e);
}
#if DEBUG
finally {
#if UNITY_5_5_OR_NEWER
UnityEngine.Profiling.Profiler.EndSample();
#else
Profiler.EndSample();
#endif
}
#endif
}
[SLua.MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
[UnityEngine.Scripting.Preserve]
static public int ClearRenderTarget(IntPtr l) {
try {
#if DEBUG
var method = System.Reflection.MethodBase.GetCurrentMethod();
string methodName = GetMethodName(method);
#if UNITY_5_5_OR_NEWER
UnityEngine.Profiling.Profiler.BeginSample(methodName);
#else
Profiler.BeginSample(methodName);
#endif
#endif
int argc = LuaDLL.lua_gettop(l);
if(argc==4){
UnityEngine.Rendering.CommandBuffer self=(UnityEngine.Rendering.CommandBuffer)checkSelf(l);
System.Boolean a1;
checkType(l,2,out a1);
System.Boolean a2;
checkType(l,3,out a2);
UnityEngine.Color a3;
checkType(l,4,out a3);
self.ClearRenderTarget(a1,a2,a3);
pushValue(l,true);
return 1;
}
else if(argc==5){
UnityEngine.Rendering.CommandBuffer self=(UnityEngine.Rendering.CommandBuffer)checkSelf(l);
System.Boolean a1;
checkType(l,2,out a1);
System.Boolean a2;
checkType(l,3,out a2);
UnityEngine.Color a3;
checkType(l,4,out a3);
System.Single a4;
checkType(l,5,out a4);
self.ClearRenderTarget(a1,a2,a3,a4);
pushValue(l,true);
return 1;
}
pushValue(l,false);
LuaDLL.lua_pushstring(l,"No matched override function ClearRenderTarget to call");
return 2;
}
catch(Exception e) {
return error(l,e);
}
#if DEBUG
finally {
#if UNITY_5_5_OR_NEWER
UnityEngine.Profiling.Profiler.EndSample();
#else
Profiler.EndSample();
#endif
}
#endif
}
[SLua.MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
[UnityEngine.Scripting.Preserve]
static public int SetGlobalFloat(IntPtr l) {
try {
#if DEBUG
var method = System.Reflection.MethodBase.GetCurrentMethod();
string methodName = GetMethodName(method);
#if UNITY_5_5_OR_NEWER
UnityEngine.Profiling.Profiler.BeginSample(methodName);
#else
Profiler.BeginSample(methodName);
#endif
#endif
int argc = LuaDLL.lua_gettop(l);
if(matchType(l,argc,2,typeof(int),typeof(float))){
UnityEngine.Rendering.CommandBuffer self=(UnityEngine.Rendering.CommandBuffer)checkSelf(l);
System.Int32 a1;
checkType(l,2,out a1);
System.Single a2;
checkType(l,3,out a2);
self.SetGlobalFloat(a1,a2);
pushValue(l,true);
return 1;
}
else if(matchType(l,argc,2,typeof(string),typeof(float))){
UnityEngine.Rendering.CommandBuffer self=(UnityEngine.Rendering.CommandBuffer)checkSelf(l);
System.String a1;
checkType(l,2,out a1);
System.Single a2;
checkType(l,3,out a2);
self.SetGlobalFloat(a1,a2);
pushValue(l,true);
return 1;
}
pushValue(l,false);
LuaDLL.lua_pushstring(l,"No matched override function SetGlobalFloat to call");
return 2;
}
catch(Exception e) {
return error(l,e);
}
#if DEBUG
finally {
#if UNITY_5_5_OR_NEWER
UnityEngine.Profiling.Profiler.EndSample();
#else
Profiler.EndSample();
#endif
}
#endif
}
[SLua.MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
[UnityEngine.Scripting.Preserve]
static public int SetGlobalVector(IntPtr l) {
try {
#if DEBUG
var method = System.Reflection.MethodBase.GetCurrentMethod();
string methodName = GetMethodName(method);
#if UNITY_5_5_OR_NEWER
UnityEngine.Profiling.Profiler.BeginSample(methodName);
#else
Profiler.BeginSample(methodName);
#endif
#endif
int argc = LuaDLL.lua_gettop(l);
if(matchType(l,argc,2,typeof(int),typeof(UnityEngine.Vector4))){
UnityEngine.Rendering.CommandBuffer self=(UnityEngine.Rendering.CommandBuffer)checkSelf(l);
System.Int32 a1;
checkType(l,2,out a1);
UnityEngine.Vector4 a2;
checkType(l,3,out a2);
self.SetGlobalVector(a1,a2);
pushValue(l,true);
return 1;
}
else if(matchType(l,argc,2,typeof(string),typeof(UnityEngine.Vector4))){
UnityEngine.Rendering.CommandBuffer self=(UnityEngine.Rendering.CommandBuffer)checkSelf(l);
System.String a1;
checkType(l,2,out a1);
UnityEngine.Vector4 a2;
checkType(l,3,out a2);
self.SetGlobalVector(a1,a2);
pushValue(l,true);
return 1;
}
pushValue(l,false);
LuaDLL.lua_pushstring(l,"No matched override function SetGlobalVector to call");
return 2;
}
catch(Exception e) {
return error(l,e);
}
#if DEBUG
finally {
#if UNITY_5_5_OR_NEWER
UnityEngine.Profiling.Profiler.EndSample();
#else
Profiler.EndSample();
#endif
}
#endif
}
[SLua.MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
[UnityEngine.Scripting.Preserve]
static public int SetGlobalColor(IntPtr l) {
try {
#if DEBUG
var method = System.Reflection.MethodBase.GetCurrentMethod();
string methodName = GetMethodName(method);
#if UNITY_5_5_OR_NEWER
UnityEngine.Profiling.Profiler.BeginSample(methodName);
#else
Profiler.BeginSample(methodName);
#endif
#endif
int argc = LuaDLL.lua_gettop(l);
if(matchType(l,argc,2,typeof(int),typeof(UnityEngine.Color))){
UnityEngine.Rendering.CommandBuffer self=(UnityEngine.Rendering.CommandBuffer)checkSelf(l);
System.Int32 a1;
checkType(l,2,out a1);
UnityEngine.Color a2;
checkType(l,3,out a2);
self.SetGlobalColor(a1,a2);
pushValue(l,true);
return 1;
}
else if(matchType(l,argc,2,typeof(string),typeof(UnityEngine.Color))){
UnityEngine.Rendering.CommandBuffer self=(UnityEngine.Rendering.CommandBuffer)checkSelf(l);
System.String a1;
checkType(l,2,out a1);
UnityEngine.Color a2;
checkType(l,3,out a2);
self.SetGlobalColor(a1,a2);
pushValue(l,true);
return 1;
}
pushValue(l,false);
LuaDLL.lua_pushstring(l,"No matched override function SetGlobalColor to call");
return 2;
}
catch(Exception e) {
return error(l,e);
}
#if DEBUG
finally {
#if UNITY_5_5_OR_NEWER
UnityEngine.Profiling.Profiler.EndSample();
#else
Profiler.EndSample();
#endif
}
#endif
}
[SLua.MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
[UnityEngine.Scripting.Preserve]
static public int SetGlobalMatrix(IntPtr l) {
try {
#if DEBUG
var method = System.Reflection.MethodBase.GetCurrentMethod();
string methodName = GetMethodName(method);
#if UNITY_5_5_OR_NEWER
UnityEngine.Profiling.Profiler.BeginSample(methodName);
#else
Profiler.BeginSample(methodName);
#endif
#endif
int argc = LuaDLL.lua_gettop(l);
if(matchType(l,argc,2,typeof(int),typeof(UnityEngine.Matrix4x4))){
UnityEngine.Rendering.CommandBuffer self=(UnityEngine.Rendering.CommandBuffer)checkSelf(l);
System.Int32 a1;
checkType(l,2,out a1);
UnityEngine.Matrix4x4 a2;
checkValueType(l,3,out a2);
self.SetGlobalMatrix(a1,a2);
pushValue(l,true);
return 1;
}
else if(matchType(l,argc,2,typeof(string),typeof(UnityEngine.Matrix4x4))){
UnityEngine.Rendering.CommandBuffer self=(UnityEngine.Rendering.CommandBuffer)checkSelf(l);
System.String a1;
checkType(l,2,out a1);
UnityEngine.Matrix4x4 a2;
checkValueType(l,3,out a2);
self.SetGlobalMatrix(a1,a2);
pushValue(l,true);
return 1;
}
pushValue(l,false);
LuaDLL.lua_pushstring(l,"No matched override function SetGlobalMatrix to call");
return 2;
}
catch(Exception e) {
return error(l,e);
}
#if DEBUG
finally {
#if UNITY_5_5_OR_NEWER
UnityEngine.Profiling.Profiler.EndSample();
#else
Profiler.EndSample();
#endif
}
#endif
}
[SLua.MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
[UnityEngine.Scripting.Preserve]
static public int EnableShaderKeyword(IntPtr l) {
try {
#if DEBUG
var method = System.Reflection.MethodBase.GetCurrentMethod();
string methodName = GetMethodName(method);
#if UNITY_5_5_OR_NEWER
UnityEngine.Profiling.Profiler.BeginSample(methodName);
#else
Profiler.BeginSample(methodName);
#endif
#endif
UnityEngine.Rendering.CommandBuffer self=(UnityEngine.Rendering.CommandBuffer)checkSelf(l);
System.String a1;
checkType(l,2,out a1);
self.EnableShaderKeyword(a1);
pushValue(l,true);
return 1;
}
catch(Exception e) {
return error(l,e);
}
#if DEBUG
finally {
#if UNITY_5_5_OR_NEWER
UnityEngine.Profiling.Profiler.EndSample();
#else
Profiler.EndSample();
#endif
}
#endif
}
[SLua.MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
[UnityEngine.Scripting.Preserve]
static public int DisableShaderKeyword(IntPtr l) {
try {
#if DEBUG
var method = System.Reflection.MethodBase.GetCurrentMethod();
string methodName = GetMethodName(method);
#if UNITY_5_5_OR_NEWER
UnityEngine.Profiling.Profiler.BeginSample(methodName);
#else
Profiler.BeginSample(methodName);
#endif
#endif
UnityEngine.Rendering.CommandBuffer self=(UnityEngine.Rendering.CommandBuffer)checkSelf(l);
System.String a1;
checkType(l,2,out a1);
self.DisableShaderKeyword(a1);
pushValue(l,true);
return 1;
}
catch(Exception e) {
return error(l,e);
}
#if DEBUG
finally {
#if UNITY_5_5_OR_NEWER
UnityEngine.Profiling.Profiler.EndSample();
#else
Profiler.EndSample();
#endif
}
#endif
}
[SLua.MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
[UnityEngine.Scripting.Preserve]
static public int SetViewMatrix(IntPtr l) {
try {
#if DEBUG
var method = System.Reflection.MethodBase.GetCurrentMethod();
string methodName = GetMethodName(method);
#if UNITY_5_5_OR_NEWER
UnityEngine.Profiling.Profiler.BeginSample(methodName);
#else
Profiler.BeginSample(methodName);
#endif
#endif
UnityEngine.Rendering.CommandBuffer self=(UnityEngine.Rendering.CommandBuffer)checkSelf(l);
UnityEngine.Matrix4x4 a1;
checkValueType(l,2,out a1);
self.SetViewMatrix(a1);
pushValue(l,true);
return 1;
}
catch(Exception e) {
return error(l,e);
}
#if DEBUG
finally {
#if UNITY_5_5_OR_NEWER
UnityEngine.Profiling.Profiler.EndSample();
#else
Profiler.EndSample();
#endif
}
#endif
}
[SLua.MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
[UnityEngine.Scripting.Preserve]
static public int SetProjectionMatrix(IntPtr l) {
try {
#if DEBUG
var method = System.Reflection.MethodBase.GetCurrentMethod();
string methodName = GetMethodName(method);
#if UNITY_5_5_OR_NEWER
UnityEngine.Profiling.Profiler.BeginSample(methodName);
#else
Profiler.BeginSample(methodName);
#endif
#endif
UnityEngine.Rendering.CommandBuffer self=(UnityEngine.Rendering.CommandBuffer)checkSelf(l);
UnityEngine.Matrix4x4 a1;
checkValueType(l,2,out a1);
self.SetProjectionMatrix(a1);
pushValue(l,true);
return 1;
}
catch(Exception e) {
return error(l,e);
}
#if DEBUG
finally {
#if UNITY_5_5_OR_NEWER
UnityEngine.Profiling.Profiler.EndSample();
#else
Profiler.EndSample();
#endif
}
#endif
}
[SLua.MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
[UnityEngine.Scripting.Preserve]
static public int SetViewProjectionMatrices(IntPtr l) {
try {
#if DEBUG
var method = System.Reflection.MethodBase.GetCurrentMethod();
string methodName = GetMethodName(method);
#if UNITY_5_5_OR_NEWER
UnityEngine.Profiling.Profiler.BeginSample(methodName);
#else
Profiler.BeginSample(methodName);
#endif
#endif
UnityEngine.Rendering.CommandBuffer self=(UnityEngine.Rendering.CommandBuffer)checkSelf(l);
UnityEngine.Matrix4x4 a1;
checkValueType(l,2,out a1);
UnityEngine.Matrix4x4 a2;
checkValueType(l,3,out a2);
self.SetViewProjectionMatrices(a1,a2);
pushValue(l,true);
return 1;
}
catch(Exception e) {
return error(l,e);
}
#if DEBUG
finally {
#if UNITY_5_5_OR_NEWER
UnityEngine.Profiling.Profiler.EndSample();
#else
Profiler.EndSample();
#endif
}
#endif
}
[SLua.MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
[UnityEngine.Scripting.Preserve]
static public int SetGlobalDepthBias(IntPtr l) {
try {
#if DEBUG
var method = System.Reflection.MethodBase.GetCurrentMethod();
string methodName = GetMethodName(method);
#if UNITY_5_5_OR_NEWER
UnityEngine.Profiling.Profiler.BeginSample(methodName);
#else
Profiler.BeginSample(methodName);
#endif
#endif
UnityEngine.Rendering.CommandBuffer self=(UnityEngine.Rendering.CommandBuffer)checkSelf(l);
System.Single a1;
checkType(l,2,out a1);
System.Single a2;
checkType(l,3,out a2);
self.SetGlobalDepthBias(a1,a2);
pushValue(l,true);
return 1;
}
catch(Exception e) {
return error(l,e);
}
#if DEBUG
finally {
#if UNITY_5_5_OR_NEWER
UnityEngine.Profiling.Profiler.EndSample();
#else
Profiler.EndSample();
#endif
}
#endif
}
[SLua.MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
[UnityEngine.Scripting.Preserve]
static public int SetGlobalFloatArray(IntPtr l) {
try {
#if DEBUG
var method = System.Reflection.MethodBase.GetCurrentMethod();
string methodName = GetMethodName(method);
#if UNITY_5_5_OR_NEWER
UnityEngine.Profiling.Profiler.BeginSample(methodName);
#else
Profiler.BeginSample(methodName);
#endif
#endif
int argc = LuaDLL.lua_gettop(l);
if(matchType(l,argc,2,typeof(string),typeof(System.Single[]))){
UnityEngine.Rendering.CommandBuffer self=(UnityEngine.Rendering.CommandBuffer)checkSelf(l);
System.String a1;
checkType(l,2,out a1);
System.Single[] a2;
checkArray(l,3,out a2);
self.SetGlobalFloatArray(a1,a2);
pushValue(l,true);
return 1;
}
else if(matchType(l,argc,2,typeof(int),typeof(System.Single[]))){
UnityEngine.Rendering.CommandBuffer self=(UnityEngine.Rendering.CommandBuffer)checkSelf(l);
System.Int32 a1;
checkType(l,2,out a1);
System.Single[] a2;
checkArray(l,3,out a2);
self.SetGlobalFloatArray(a1,a2);
pushValue(l,true);
return 1;
}
else if(matchType(l,argc,2,typeof(string),typeof(List<System.Single>))){
UnityEngine.Rendering.CommandBuffer self=(UnityEngine.Rendering.CommandBuffer)checkSelf(l);
System.String a1;
checkType(l,2,out a1);
System.Collections.Generic.List<System.Single> a2;
checkType(l,3,out a2);
self.SetGlobalFloatArray(a1,a2);
pushValue(l,true);
return 1;
}
else if(matchType(l,argc,2,typeof(int),typeof(List<System.Single>))){
UnityEngine.Rendering.CommandBuffer self=(UnityEngine.Rendering.CommandBuffer)checkSelf(l);
System.Int32 a1;
checkType(l,2,out a1);
System.Collections.Generic.List<System.Single> a2;
checkType(l,3,out a2);
self.SetGlobalFloatArray(a1,a2);
pushValue(l,true);
return 1;
}
pushValue(l,false);
LuaDLL.lua_pushstring(l,"No matched override function SetGlobalFloatArray to call");
return 2;
}
catch(Exception e) {
return error(l,e);
}
#if DEBUG
finally {
#if UNITY_5_5_OR_NEWER
UnityEngine.Profiling.Profiler.EndSample();
#else
Profiler.EndSample();
#endif
}
#endif
}
[SLua.MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
[UnityEngine.Scripting.Preserve]
static public int SetGlobalVectorArray(IntPtr l) {
try {
#if DEBUG
var method = System.Reflection.MethodBase.GetCurrentMethod();
string methodName = GetMethodName(method);
#if UNITY_5_5_OR_NEWER
UnityEngine.Profiling.Profiler.BeginSample(methodName);
#else
Profiler.BeginSample(methodName);
#endif
#endif
int argc = LuaDLL.lua_gettop(l);
if(matchType(l,argc,2,typeof(string),typeof(UnityEngine.Vector4[]))){
UnityEngine.Rendering.CommandBuffer self=(UnityEngine.Rendering.CommandBuffer)checkSelf(l);
System.String a1;
checkType(l,2,out a1);
UnityEngine.Vector4[] a2;
checkArray(l,3,out a2);
self.SetGlobalVectorArray(a1,a2);
pushValue(l,true);
return 1;
}
else if(matchType(l,argc,2,typeof(int),typeof(UnityEngine.Vector4[]))){
UnityEngine.Rendering.CommandBuffer self=(UnityEngine.Rendering.CommandBuffer)checkSelf(l);
System.Int32 a1;
checkType(l,2,out a1);
UnityEngine.Vector4[] a2;
checkArray(l,3,out a2);
self.SetGlobalVectorArray(a1,a2);
pushValue(l,true);
return 1;
}
else if(matchType(l,argc,2,typeof(string),typeof(List<UnityEngine.Vector4>))){
UnityEngine.Rendering.CommandBuffer self=(UnityEngine.Rendering.CommandBuffer)checkSelf(l);
System.String a1;
checkType(l,2,out a1);
System.Collections.Generic.List<UnityEngine.Vector4> a2;
checkType(l,3,out a2);
self.SetGlobalVectorArray(a1,a2);
pushValue(l,true);
return 1;
}
else if(matchType(l,argc,2,typeof(int),typeof(List<UnityEngine.Vector4>))){
UnityEngine.Rendering.CommandBuffer self=(UnityEngine.Rendering.CommandBuffer)checkSelf(l);
System.Int32 a1;
checkType(l,2,out a1);
System.Collections.Generic.List<UnityEngine.Vector4> a2;
checkType(l,3,out a2);
self.SetGlobalVectorArray(a1,a2);
pushValue(l,true);
return 1;
}
pushValue(l,false);
LuaDLL.lua_pushstring(l,"No matched override function SetGlobalVectorArray to call");
return 2;
}
catch(Exception e) {
return error(l,e);
}
#if DEBUG
finally {
#if UNITY_5_5_OR_NEWER
UnityEngine.Profiling.Profiler.EndSample();
#else
Profiler.EndSample();
#endif
}
#endif
}
[SLua.MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
[UnityEngine.Scripting.Preserve]
static public int SetGlobalMatrixArray(IntPtr l) {
try {
#if DEBUG
var method = System.Reflection.MethodBase.GetCurrentMethod();
string methodName = GetMethodName(method);
#if UNITY_5_5_OR_NEWER
UnityEngine.Profiling.Profiler.BeginSample(methodName);
#else
Profiler.BeginSample(methodName);
#endif
#endif
int argc = LuaDLL.lua_gettop(l);
if(matchType(l,argc,2,typeof(string),typeof(UnityEngine.Matrix4x4[]))){
UnityEngine.Rendering.CommandBuffer self=(UnityEngine.Rendering.CommandBuffer)checkSelf(l);
System.String a1;
checkType(l,2,out a1);
UnityEngine.Matrix4x4[] a2;
checkArray(l,3,out a2);
self.SetGlobalMatrixArray(a1,a2);
pushValue(l,true);
return 1;
}
else if(matchType(l,argc,2,typeof(int),typeof(UnityEngine.Matrix4x4[]))){
UnityEngine.Rendering.CommandBuffer self=(UnityEngine.Rendering.CommandBuffer)checkSelf(l);
System.Int32 a1;
checkType(l,2,out a1);
UnityEngine.Matrix4x4[] a2;
checkArray(l,3,out a2);
self.SetGlobalMatrixArray(a1,a2);
pushValue(l,true);
return 1;
}
else if(matchType(l,argc,2,typeof(string),typeof(List<UnityEngine.Matrix4x4>))){
UnityEngine.Rendering.CommandBuffer self=(UnityEngine.Rendering.CommandBuffer)checkSelf(l);
System.String a1;
checkType(l,2,out a1);
System.Collections.Generic.List<UnityEngine.Matrix4x4> a2;
checkType(l,3,out a2);
self.SetGlobalMatrixArray(a1,a2);
pushValue(l,true);
return 1;
}
else if(matchType(l,argc,2,typeof(int),typeof(List<UnityEngine.Matrix4x4>))){
UnityEngine.Rendering.CommandBuffer self=(UnityEngine.Rendering.CommandBuffer)checkSelf(l);
System.Int32 a1;
checkType(l,2,out a1);
System.Collections.Generic.List<UnityEngine.Matrix4x4> a2;
checkType(l,3,out a2);
self.SetGlobalMatrixArray(a1,a2);
pushValue(l,true);
return 1;
}
pushValue(l,false);
LuaDLL.lua_pushstring(l,"No matched override function SetGlobalMatrixArray to call");
return 2;
}
catch(Exception e) {
return error(l,e);
}
#if DEBUG
finally {
#if UNITY_5_5_OR_NEWER
UnityEngine.Profiling.Profiler.EndSample();
#else
Profiler.EndSample();
#endif
}
#endif
}
[SLua.MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
[UnityEngine.Scripting.Preserve]
static public int SetGlobalTexture(IntPtr l) {
try {
#if DEBUG
var method = System.Reflection.MethodBase.GetCurrentMethod();
string methodName = GetMethodName(method);
#if UNITY_5_5_OR_NEWER
UnityEngine.Profiling.Profiler.BeginSample(methodName);
#else
Profiler.BeginSample(methodName);
#endif
#endif
int argc = LuaDLL.lua_gettop(l);
if(matchType(l,argc,2,typeof(int),typeof(UnityEngine.Rendering.RenderTargetIdentifier))){
UnityEngine.Rendering.CommandBuffer self=(UnityEngine.Rendering.CommandBuffer)checkSelf(l);
System.Int32 a1;
checkType(l,2,out a1);
UnityEngine.Rendering.RenderTargetIdentifier a2;
checkValueType(l,3,out a2);
self.SetGlobalTexture(a1,a2);
pushValue(l,true);
return 1;
}
else if(matchType(l,argc,2,typeof(string),typeof(UnityEngine.Rendering.RenderTargetIdentifier))){
UnityEngine.Rendering.CommandBuffer self=(UnityEngine.Rendering.CommandBuffer)checkSelf(l);
System.String a1;
checkType(l,2,out a1);
UnityEngine.Rendering.RenderTargetIdentifier a2;
checkValueType(l,3,out a2);
self.SetGlobalTexture(a1,a2);
pushValue(l,true);
return 1;
}
pushValue(l,false);
LuaDLL.lua_pushstring(l,"No matched override function SetGlobalTexture to call");
return 2;
}
catch(Exception e) {
return error(l,e);
}
#if DEBUG
finally {
#if UNITY_5_5_OR_NEWER
UnityEngine.Profiling.Profiler.EndSample();
#else
Profiler.EndSample();
#endif
}
#endif
}
[SLua.MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
[UnityEngine.Scripting.Preserve]
static public int SetGlobalBuffer(IntPtr l) {
try {
#if DEBUG
var method = System.Reflection.MethodBase.GetCurrentMethod();
string methodName = GetMethodName(method);
#if UNITY_5_5_OR_NEWER
UnityEngine.Profiling.Profiler.BeginSample(methodName);
#else
Profiler.BeginSample(methodName);
#endif
#endif
int argc = LuaDLL.lua_gettop(l);
if(matchType(l,argc,2,typeof(int),typeof(UnityEngine.ComputeBuffer))){
UnityEngine.Rendering.CommandBuffer self=(UnityEngine.Rendering.CommandBuffer)checkSelf(l);
System.Int32 a1;
checkType(l,2,out a1);
UnityEngine.ComputeBuffer a2;
checkType(l,3,out a2);
self.SetGlobalBuffer(a1,a2);
pushValue(l,true);
return 1;
}
else if(matchType(l,argc,2,typeof(string),typeof(UnityEngine.ComputeBuffer))){
UnityEngine.Rendering.CommandBuffer self=(UnityEngine.Rendering.CommandBuffer)checkSelf(l);
System.String a1;
checkType(l,2,out a1);
UnityEngine.ComputeBuffer a2;
checkType(l,3,out a2);
self.SetGlobalBuffer(a1,a2);
pushValue(l,true);
return 1;
}
pushValue(l,false);
LuaDLL.lua_pushstring(l,"No matched override function SetGlobalBuffer to call");
return 2;
}
catch(Exception e) {
return error(l,e);
}
#if DEBUG
finally {
#if UNITY_5_5_OR_NEWER
UnityEngine.Profiling.Profiler.EndSample();
#else
Profiler.EndSample();
#endif
}
#endif
}
[SLua.MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
[UnityEngine.Scripting.Preserve]
static public int SetShadowSamplingMode(IntPtr l) {
try {
#if DEBUG
var method = System.Reflection.MethodBase.GetCurrentMethod();
string methodName = GetMethodName(method);
#if UNITY_5_5_OR_NEWER
UnityEngine.Profiling.Profiler.BeginSample(methodName);
#else
Profiler.BeginSample(methodName);
#endif
#endif
UnityEngine.Rendering.CommandBuffer self=(UnityEngine.Rendering.CommandBuffer)checkSelf(l);
UnityEngine.Rendering.RenderTargetIdentifier a1;
checkValueType(l,2,out a1);
UnityEngine.Rendering.ShadowSamplingMode a2;
a2 = (UnityEngine.Rendering.ShadowSamplingMode)LuaDLL.luaL_checkinteger(l, 3);
self.SetShadowSamplingMode(a1,a2);
pushValue(l,true);
return 1;
}
catch(Exception e) {
return error(l,e);
}
#if DEBUG
finally {
#if UNITY_5_5_OR_NEWER
UnityEngine.Profiling.Profiler.EndSample();
#else
Profiler.EndSample();
#endif
}
#endif
}
[SLua.MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
[UnityEngine.Scripting.Preserve]
static public int IssuePluginEvent(IntPtr l) {
try {
#if DEBUG
var method = System.Reflection.MethodBase.GetCurrentMethod();
string methodName = GetMethodName(method);
#if UNITY_5_5_OR_NEWER
UnityEngine.Profiling.Profiler.BeginSample(methodName);
#else
Profiler.BeginSample(methodName);
#endif
#endif
UnityEngine.Rendering.CommandBuffer self=(UnityEngine.Rendering.CommandBuffer)checkSelf(l);
System.IntPtr a1;
checkType(l,2,out a1);
System.Int32 a2;
checkType(l,3,out a2);
self.IssuePluginEvent(a1,a2);
pushValue(l,true);
return 1;
}
catch(Exception e) {
return error(l,e);
}
#if DEBUG
finally {
#if UNITY_5_5_OR_NEWER
UnityEngine.Profiling.Profiler.EndSample();
#else
Profiler.EndSample();
#endif
}
#endif
}
[SLua.MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
[UnityEngine.Scripting.Preserve]
static public int BeginSample(IntPtr l) {
try {
#if DEBUG
var method = System.Reflection.MethodBase.GetCurrentMethod();
string methodName = GetMethodName(method);
#if UNITY_5_5_OR_NEWER
UnityEngine.Profiling.Profiler.BeginSample(methodName);
#else
Profiler.BeginSample(methodName);
#endif
#endif
UnityEngine.Rendering.CommandBuffer self=(UnityEngine.Rendering.CommandBuffer)checkSelf(l);
System.String a1;
checkType(l,2,out a1);
self.BeginSample(a1);
pushValue(l,true);
return 1;
}
catch(Exception e) {
return error(l,e);
}
#if DEBUG
finally {
#if UNITY_5_5_OR_NEWER
UnityEngine.Profiling.Profiler.EndSample();
#else
Profiler.EndSample();
#endif
}
#endif
}
[SLua.MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
[UnityEngine.Scripting.Preserve]
static public int EndSample(IntPtr l) {
try {
#if DEBUG
var method = System.Reflection.MethodBase.GetCurrentMethod();
string methodName = GetMethodName(method);
#if UNITY_5_5_OR_NEWER
UnityEngine.Profiling.Profiler.BeginSample(methodName);
#else
Profiler.BeginSample(methodName);
#endif
#endif
UnityEngine.Rendering.CommandBuffer self=(UnityEngine.Rendering.CommandBuffer)checkSelf(l);
System.String a1;
checkType(l,2,out a1);
self.EndSample(a1);
pushValue(l,true);
return 1;
}
catch(Exception e) {
return error(l,e);
}
#if DEBUG
finally {
#if UNITY_5_5_OR_NEWER
UnityEngine.Profiling.Profiler.EndSample();
#else
Profiler.EndSample();
#endif
}
#endif
}
[SLua.MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
[UnityEngine.Scripting.Preserve]
static public int IssuePluginEventAndData(IntPtr l) {
try {
#if DEBUG
var method = System.Reflection.MethodBase.GetCurrentMethod();
string methodName = GetMethodName(method);
#if UNITY_5_5_OR_NEWER
UnityEngine.Profiling.Profiler.BeginSample(methodName);
#else
Profiler.BeginSample(methodName);
#endif
#endif
UnityEngine.Rendering.CommandBuffer self=(UnityEngine.Rendering.CommandBuffer)checkSelf(l);
System.IntPtr a1;
checkType(l,2,out a1);
System.Int32 a2;
checkType(l,3,out a2);
System.IntPtr a3;
checkType(l,4,out a3);
self.IssuePluginEventAndData(a1,a2,a3);
pushValue(l,true);
return 1;
}
catch(Exception e) {
return error(l,e);
}
#if DEBUG
finally {
#if UNITY_5_5_OR_NEWER
UnityEngine.Profiling.Profiler.EndSample();
#else
Profiler.EndSample();
#endif
}
#endif
}
[SLua.MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
[UnityEngine.Scripting.Preserve]
static public int IssuePluginCustomBlit(IntPtr l) {
try {
#if DEBUG
var method = System.Reflection.MethodBase.GetCurrentMethod();
string methodName = GetMethodName(method);
#if UNITY_5_5_OR_NEWER
UnityEngine.Profiling.Profiler.BeginSample(methodName);
#else
Profiler.BeginSample(methodName);
#endif
#endif
UnityEngine.Rendering.CommandBuffer self=(UnityEngine.Rendering.CommandBuffer)checkSelf(l);
System.IntPtr a1;
checkType(l,2,out a1);
System.UInt32 a2;
checkType(l,3,out a2);
UnityEngine.Rendering.RenderTargetIdentifier a3;
checkValueType(l,4,out a3);
UnityEngine.Rendering.RenderTargetIdentifier a4;
checkValueType(l,5,out a4);
System.UInt32 a5;
checkType(l,6,out a5);
System.UInt32 a6;
checkType(l,7,out a6);
self.IssuePluginCustomBlit(a1,a2,a3,a4,a5,a6);
pushValue(l,true);
return 1;
}
catch(Exception e) {
return error(l,e);
}
#if DEBUG
finally {
#if UNITY_5_5_OR_NEWER
UnityEngine.Profiling.Profiler.EndSample();
#else
Profiler.EndSample();
#endif
}
#endif
}
[SLua.MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
[UnityEngine.Scripting.Preserve]
static public int IssuePluginCustomTextureUpdate(IntPtr l) {
try {
#if DEBUG
var method = System.Reflection.MethodBase.GetCurrentMethod();
string methodName = GetMethodName(method);
#if UNITY_5_5_OR_NEWER
UnityEngine.Profiling.Profiler.BeginSample(methodName);
#else
Profiler.BeginSample(methodName);
#endif
#endif
UnityEngine.Rendering.CommandBuffer self=(UnityEngine.Rendering.CommandBuffer)checkSelf(l);
System.IntPtr a1;
checkType(l,2,out a1);
UnityEngine.Texture a2;
checkType(l,3,out a2);
System.UInt32 a3;
checkType(l,4,out a3);
self.IssuePluginCustomTextureUpdate(a1,a2,a3);
pushValue(l,true);
return 1;
}
catch(Exception e) {
return error(l,e);
}
#if DEBUG
finally {
#if UNITY_5_5_OR_NEWER
UnityEngine.Profiling.Profiler.EndSample();
#else
Profiler.EndSample();
#endif
}
#endif
}
[SLua.MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
[UnityEngine.Scripting.Preserve]
static public int get_name(IntPtr l) {
try {
#if DEBUG
var method = System.Reflection.MethodBase.GetCurrentMethod();
string methodName = GetMethodName(method);
#if UNITY_5_5_OR_NEWER
UnityEngine.Profiling.Profiler.BeginSample(methodName);
#else
Profiler.BeginSample(methodName);
#endif
#endif
UnityEngine.Rendering.CommandBuffer self=(UnityEngine.Rendering.CommandBuffer)checkSelf(l);
pushValue(l,true);
pushValue(l,self.name);
return 2;
}
catch(Exception e) {
return error(l,e);
}
#if DEBUG
finally {
#if UNITY_5_5_OR_NEWER
UnityEngine.Profiling.Profiler.EndSample();
#else
Profiler.EndSample();
#endif
}
#endif
}
[SLua.MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
[UnityEngine.Scripting.Preserve]
static public int set_name(IntPtr l) {
try {
#if DEBUG
var method = System.Reflection.MethodBase.GetCurrentMethod();
string methodName = GetMethodName(method);
#if UNITY_5_5_OR_NEWER
UnityEngine.Profiling.Profiler.BeginSample(methodName);
#else
Profiler.BeginSample(methodName);
#endif
#endif
UnityEngine.Rendering.CommandBuffer self=(UnityEngine.Rendering.CommandBuffer)checkSelf(l);
string v;
checkType(l,2,out v);
self.name=v;
pushValue(l,true);
return 1;
}
catch(Exception e) {
return error(l,e);
}
#if DEBUG
finally {
#if UNITY_5_5_OR_NEWER
UnityEngine.Profiling.Profiler.EndSample();
#else
Profiler.EndSample();
#endif
}
#endif
}
[SLua.MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
[UnityEngine.Scripting.Preserve]
static public int get_sizeInBytes(IntPtr l) {
try {
#if DEBUG
var method = System.Reflection.MethodBase.GetCurrentMethod();
string methodName = GetMethodName(method);
#if UNITY_5_5_OR_NEWER
UnityEngine.Profiling.Profiler.BeginSample(methodName);
#else
Profiler.BeginSample(methodName);
#endif
#endif
UnityEngine.Rendering.CommandBuffer self=(UnityEngine.Rendering.CommandBuffer)checkSelf(l);
pushValue(l,true);
pushValue(l,self.sizeInBytes);
return 2;
}
catch(Exception e) {
return error(l,e);
}
#if DEBUG
finally {
#if UNITY_5_5_OR_NEWER
UnityEngine.Profiling.Profiler.EndSample();
#else
Profiler.EndSample();
#endif
}
#endif
}
[UnityEngine.Scripting.Preserve]
static public void reg(IntPtr l) {
getTypeTable(l,"UnityEngine.Rendering.CommandBuffer");
addMember(l,Dispose);
addMember(l,Release);
addMember(l,CreateGPUFence);
addMember(l,WaitOnGPUFence);
addMember(l,SetComputeFloatParam);
addMember(l,SetComputeIntParam);
addMember(l,SetComputeVectorParam);
addMember(l,SetComputeVectorArrayParam);
addMember(l,SetComputeMatrixParam);
addMember(l,SetComputeMatrixArrayParam);
addMember(l,SetComputeFloatParams);
addMember(l,SetComputeIntParams);
addMember(l,SetComputeTextureParam);
addMember(l,SetComputeBufferParam);
addMember(l,DispatchCompute);
addMember(l,GenerateMips);
addMember(l,CopyCounterValue);
addMember(l,Clear);
addMember(l,DrawMesh);
addMember(l,DrawRenderer);
addMember(l,DrawProcedural);
addMember(l,DrawProceduralIndirect);
addMember(l,DrawMeshInstanced);
addMember(l,DrawMeshInstancedIndirect);
addMember(l,SetRenderTarget);
addMember(l,SetRandomWriteTarget);
addMember(l,ClearRandomWriteTargets);
addMember(l,CopyTexture);
addMember(l,SetViewport);
addMember(l,Blit);
addMember(l,GetTemporaryRT);
addMember(l,GetTemporaryRTArray);
addMember(l,ReleaseTemporaryRT);
addMember(l,ClearRenderTarget);
addMember(l,SetGlobalFloat);
addMember(l,SetGlobalVector);
addMember(l,SetGlobalColor);
addMember(l,SetGlobalMatrix);
addMember(l,EnableShaderKeyword);
addMember(l,DisableShaderKeyword);
addMember(l,SetViewMatrix);
addMember(l,SetProjectionMatrix);
addMember(l,SetViewProjectionMatrices);
addMember(l,SetGlobalDepthBias);
addMember(l,SetGlobalFloatArray);
addMember(l,SetGlobalVectorArray);
addMember(l,SetGlobalMatrixArray);
addMember(l,SetGlobalTexture);
addMember(l,SetGlobalBuffer);
addMember(l,SetShadowSamplingMode);
addMember(l,IssuePluginEvent);
addMember(l,BeginSample);
addMember(l,EndSample);
addMember(l,IssuePluginEventAndData);
addMember(l,IssuePluginCustomBlit);
addMember(l,IssuePluginCustomTextureUpdate);
addMember(l,"name",get_name,set_name,true);
addMember(l,"sizeInBytes",get_sizeInBytes,null,true);
createTypeMetatable(l,constructor, typeof(UnityEngine.Rendering.CommandBuffer));
}
}
| 30.00841 | 194 | 0.714088 | [
"BSD-3-Clause"
] | HugoFang/LuaProfiler | SLua/Assets/Slua/LuaObject/Unity/Lua_UnityEngine_Rendering_CommandBuffer.cs | 107,042 | C# |
using AAS.API.Models;
using AAS.API.Models.Interfaces;
using Azure;
using Azure.Storage.Blobs;
using Azure.Storage.Blobs.Models;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
namespace AAS.API.AASXFile
{
public class AzureBlobAASXFileService : AASAASXFile
{
private BlobServiceClient blobServiceClient; // See https://docs.microsoft.com/en-us/azure/storage/blobs/storage-quickstart-blobs-dotnet#upload-a-blob-to-a-container
private readonly ILogger _logger;
private readonly HttpClient httpClient;
private string aasxfilesContainername = "aasxfiles";
private BlobContainerClient containerClient;
private bool autoCreateContainer = true;
private const string PACKAGE_METADATA_KEY = "package";
private const string PACKAGE_FILENAME_KEY = "filename";
private const string PACKAGE_BLOBNAME = "Package.aasx";
private bool createExtraAASIdentifierBlob;
public bool CreateExtraAASIdentifierBlob
{
get { return createExtraAASIdentifierBlob; }
set { createExtraAASIdentifierBlob = value; }
}
private const string AASIDENTIFIERSBLOBNAME = "aasIdentifiers";
public bool AutoCreateContainer { get => autoCreateContainer; set => autoCreateContainer = value; }
public AzureBlobAASXFileService(BlobServiceClient serviceClient, IConfiguration config, ILogger<AzureBlobAASXFileService> logger, IHttpClientFactory httpClientFactory)
{
blobServiceClient = serviceClient;
_logger = logger;
createExtraAASIdentifierBlob = false;
if (config != null && config["AASX_FILESERVICE_CONTAINERNAME"] != null)
{
aasxfilesContainername = config["AASX_FILESERVICE_CONTAINERNAME"];
}
containerClient = serviceClient.GetBlobContainerClient(aasxfilesContainername);
httpClient = httpClientFactory.CreateClient();
}
public async Task<PackageDescription> StoreAASXPackage(List<string> aasIds, byte[] file, string fileName)
{
if (containerClient == null)
throw new AASXFileServiceException("Invalid setup. No Blob container client configured");
if (fileName == null || fileName.Length == 0)
throw new AASXFileServiceException("Parameter 'fileName' must not be empty");
bool isDownload = false;
if (file == null || file.Length == 0)
{
Uri uriResult;
isDownload = Uri.TryCreate(fileName, UriKind.Absolute, out uriResult)
&& (uriResult.Scheme == Uri.UriSchemeHttp || uriResult.Scheme == Uri.UriSchemeHttps);
if(!isDownload)
throw new AASXFileServiceException("Parameter 'file' must not be empty");
}
string aFilename = fileName;
if (isDownload)
{
file = await httpClient.GetByteArrayAsync(fileName);
aFilename = fileName.Substring(fileName.LastIndexOf('/')+1);
}
PackageDescription result = CreatePackageDescriptionFor(aasIds, aFilename);
try
{
BlobContainerClient blobContainer = await GetContainerClient();
string containerpath = WebUtility.UrlEncode(result.PackageId);
// First write the Package file
BlobClient blobClient = blobContainer.GetBlobClient($"{containerpath}/{PACKAGE_BLOBNAME}");
await UploadPackage(blobClient, aFilename, file, aasIds);
// Second write the aasIdentifiers file
if (CreateExtraAASIdentifierBlob)
{
blobClient = blobContainer.GetBlobClient($"{containerpath}/{AASIDENTIFIERSBLOBNAME}");
await UploadAASIdentifers(blobClient, aasIds, false);
}
}
catch(RequestFailedException exc)
{
_logger.LogError($"*** Error in accessing Blob:{exc.Status}/{exc.Message}");
throw new AASXFileServiceException($"*** Error in accessing Blob:{exc.Status}/{exc.Message}");
}
return result;
}
public async Task DeleteAASXByPackageId(string packageId)
{
if (containerClient == null)
throw new AASXFileServiceException("Invalid setup. No Blob container client configured");
if (packageId == null || packageId.Length == 0)
throw new AASXFileServiceException("Parameter 'fileName' must not be empty");
_logger.LogDebug($"Deleting AASX package with id '{packageId}'");
try
{
BlobContainerClient blobContainer = await GetContainerClient();
string containerpath = WebUtility.UrlEncode(packageId);
bool hasDeleted = false;
await foreach (BlobItem item in blobContainer.GetBlobsAsync(BlobTraits.None, BlobStates.None, $"{containerpath}/"))
{
Response response = await blobContainer.DeleteBlobAsync(item.Name);
_logger.LogDebug($"Deleted blob '{item.Name}' from AASX package '{packageId}'");
hasDeleted |= response.Status == (int)HttpStatusCode.Accepted;
}
if (!hasDeleted)
throw new AASXFileServiceException($"No blobs for package with id '{packageId}' found");
}
catch (RequestFailedException exc)
{
_logger.LogError($"*** Error deleting aasx package '{packageId}':{exc.Status}/{exc.Message}");
throw new AASXFileServiceException($"*** Error deleting aasx package '{packageId}':{exc.Status}/{exc.Message}");
}
}
public async Task<PackageFile> GetAASXByPackageId(string packageId)
{
if (containerClient == null)
throw new AASXFileServiceException("Invalid setup. No Blob container client configured");
if (packageId == null || packageId.Length == 0)
throw new AASXFileServiceException("Parameter 'fileName' must not be empty");
_logger.LogDebug($"Retrieving AASX package with id '{packageId}'");
PackageFile result = null;
try
{
BlobContainerClient blobContainer = await GetContainerClient();
string containerpath = WebUtility.UrlEncode(packageId);
BlobClient blobClient = blobContainer.GetBlobClient($"{containerpath}/{PACKAGE_BLOBNAME}");
if (await blobClient.ExistsAsync())
{
BlobDownloadResult downloadResult = await blobClient.DownloadContentAsync();
string filename = (await blobClient.GetPropertiesAsync()).Value.Metadata[PACKAGE_FILENAME_KEY];
result = new PackageFile() { Filename = filename, Contents = downloadResult.Content.ToArray() };
}
}
catch (RequestFailedException exc)
{
_logger.LogError($"*** Error retrieving aasx package '{packageId}':{exc.Status}/{exc.Message}");
throw new AASXFileServiceException($"*** Error retrieving aasx package '{packageId}':{exc.Status}/{exc.Message}");
}
return result;
}
public async Task<List<PackageDescription>> GetAllAASXPackageIds(string aasId)
{
List<PackageDescription> result = new List<PackageDescription>();
BlobContainerClient blobContainer = await GetContainerClient();
await foreach (BlobItem item in blobContainer.GetBlobsAsync(BlobTraits.Metadata, BlobStates.None))
{
if (item.Metadata.ContainsKey(PACKAGE_METADATA_KEY) && item.Name.Contains('/'))
{
List<string> aasIds = item.Metadata.Where(key => key.Key.StartsWith("aasId_")).Select(key => key.Value).ToList();
if (aasIds != null )
{
if (aasId == null || aasIds.Contains(aasId))
{
string packId = WebUtility.UrlDecode(item.Name.Split('/')[0]);
result.Add(new PackageDescription() { PackageId = packId, AasIds = aasIds });
}
}
}
}
return result;
}
public async Task<PackageDescription> UpdateAASXPackage(string packageId, List<string> aasIds, byte[] file, string fileName)
{
if (containerClient == null)
throw new AASXFileServiceException("Invalid setup. No Blob container client configured");
if (packageId == null || packageId.Length == 0)
throw new AASXFileServiceException("Parameter 'packageId' must not be empty");
PackageDescription result = null;
try
{
BlobContainerClient blobContainer = await GetContainerClient();
string containerpath = WebUtility.UrlEncode(packageId);
BlobClient blobClient = blobContainer.GetBlobClient($"{containerpath}/{PACKAGE_BLOBNAME}");
if (await blobClient.ExistsAsync())
{
IDictionary<string, string> blobMetadata = (await blobClient.GetPropertiesAsync()).Value.Metadata;
if (file != null)
{
//BlobHttpHeaders headers = (await blobClient.GetPropertiesAsync()).Value.
await blobClient.UploadAsync(new BinaryData(file), true);
await blobClient.SetMetadataAsync(blobMetadata);
}
bool needsMetadataUpdate = false;
if (fileName != null)
{
blobMetadata[PACKAGE_FILENAME_KEY] = fileName;
needsMetadataUpdate = true;
}
result = new PackageDescription() { PackageId = packageId};
List<string> aasIdKeys = blobMetadata.Where(key => key.Key.StartsWith("aasId_")).Select(key => key.Key).ToList();
result.AasIds = aasIdKeys.Select(key => blobMetadata[key]).ToList();
if (aasIds != null && aasIds.Count > 0)
{
foreach(string key in aasIdKeys)
{
blobMetadata.Remove(key);
}
for (int i = 0; i < aasIds.Count; i++)
blobMetadata.Add($"aasId_{i + 1}", aasIds[i]);
needsMetadataUpdate = true;
if (CreateExtraAASIdentifierBlob)
{
blobClient = blobContainer.GetBlobClient($"{containerpath}/AASIDENTIFIERSBLOBNAME");
await UploadAASIdentifers(blobClient, aasIds, true);
}
result.AasIds = aasIds;
}
if (needsMetadataUpdate)
await blobClient.SetMetadataAsync(blobMetadata);
}
}
catch (RequestFailedException exc)
{
_logger.LogError($"*** Error updating aasx package '{packageId}':{exc.Status}/{exc.Message}");
throw new AASXFileServiceException($"*** Error updating aasx package '{packageId}':{exc.Status}/{exc.Message}");
}
return result;
}
private async Task<BlobItem> FindPackageBlob(BlobContainerClient blobContainer, string packageId)
{
BlobItem result = null;
string containerpath = WebUtility.UrlEncode(packageId);
await foreach (BlobItem item in blobContainer.GetBlobsAsync(BlobTraits.Metadata, BlobStates.None, $"{containerpath}/"))
{
if (item.Metadata.ContainsKey(PACKAGE_METADATA_KEY) && item.Metadata[PACKAGE_METADATA_KEY] == "true")
{
result = item;
break;
}
}
return result;
}
private async Task UploadPackage(BlobClient blobClient, string fileName, byte[] file, List<string> aasIds, bool overwrite = false)
{
await blobClient.UploadAsync(new BinaryData(file), overwrite);
IDictionary<string, string> metadata = new Dictionary<string, string>() {
{ PACKAGE_METADATA_KEY, "true" }, { PACKAGE_FILENAME_KEY, fileName } };
if (aasIds != null)
{
for (int i = 0; i < aasIds.Count; i++)
metadata.Add($"aasId_{i + 1}", aasIds[i]);
}
await blobClient.SetMetadataAsync(metadata);
}
private async Task<Response<BlobContentInfo>> UploadAASIdentifers(BlobClient blobClient, List<string> aasIds, bool overwrite)
{
string aasIdsQuotedSep = String.Join(",", aasIds.Select(s => $"\"{s}\"").ToArray());
Response<BlobContentInfo> result = await blobClient.UploadAsync(new BinaryData(Encoding.UTF8.GetBytes(aasIdsQuotedSep)), overwrite);
if (!overwrite)
{
BlobProperties properties = await blobClient.GetPropertiesAsync();
BlobHttpHeaders headers = new BlobHttpHeaders
{
// Set the MIME ContentType every time the properties
// are updated or the field will be cleared
ContentType = "text/plain",
ContentLanguage = "en-us",
// Populate remaining headers with
// the pre-existing properties
CacheControl = properties.CacheControl,
ContentDisposition = properties.ContentDisposition,
ContentEncoding = Encoding.UTF8.EncodingName,
ContentHash = properties.ContentHash
};
// Set the blob's properties.
await blobClient.SetHttpHeadersAsync(headers);
}
return result;
}
private PackageDescription CreatePackageDescriptionFor(List<string> aasIds, string fileName)
{
PackageDescription result = new PackageDescription() { AasIds = aasIds, PackageId = BuildPackageIdFrom(aasIds, fileName) };
return result;
}
private string BuildPackageIdFrom(List<string> aasIds, string fileName)
{
// Make sure we are using a valid blob name. See https://docs.microsoft.com/en-us/rest/api/storageservices/naming-and-referencing-containers--blobs--and-metadata
string result = fileName.Trim(); // Remove whitespaces at the end and at the beginning
if (result.Contains('.'))
result = Path.GetFileNameWithoutExtension(fileName);
result = result.Replace("/", "");
if (result.EndsWith('.'))
result = result.Substring(0, result.Length - 1);
return result;
}
private async Task<BlobContainerClient> GetContainerClient()
{
if (AutoCreateContainer)
{
await containerClient.CreateIfNotExistsAsync();
}
return containerClient;
}
}
}
| 40.878866 | 175 | 0.577013 | [
"MIT"
] | JMayrbaeurl/opendigitaltwins-aas-azureservices | src/aas-aasxfile-service/AzureBlobImpl/AzureBlobAASXFileService.cs | 15,863 | C# |
using NHibernate.Cfg.MappingSchema;
using NHibernateHbmToFluent.Converter;
using NHibernateHbmToFluent.Converter.Methods;
using NUnit.Framework;
namespace ConverterTests.Methods
{
public class ColumnTests
{
[TestFixture]
public class When_asked_for_a_FluentNHibernate_name
{
[Test]
public void Should_return_the_correct_value_for__Column()
{
Column.FluentNHibernateNames.Column.ShouldBeEqualTo("Column");
}
}
[TestFixture]
public class When_asked_to_Add_a_column_name
{
private CodeFileBuilder _builder;
private Column _column;
[SetUp]
public void BeforeEachTest()
{
_builder = new CodeFileBuilder();
_column = new Column(_builder);
}
[Test]
public void Should_return_empty_given_MappedPropertyInfo_Type_is_Component()
{
MappedPropertyInfo mappedPropertyInfo = new MappedPropertyInfo(new HbmComponent(), null);
_column.Add(mappedPropertyInfo);
string result = _builder.ToString();
result.ShouldBeEqualTo("");
}
[Test]
public void Should_return_empty_given_MappedPropertyInfo_Type_is_Property()
{
MappedPropertyInfo mappedPropertyInfo = new MappedPropertyInfo(new HbmProperty(), null);
_column.Add(mappedPropertyInfo);
string result = _builder.ToString();
result.ShouldBeEqualTo("");
}
[Test]
public void Should_return_empty_given_MappedPropertyInfo_Type_is_Set()
{
MappedPropertyInfo mappedPropertyInfo = new MappedPropertyInfo(new HbmSet(), null);
_column.Add(mappedPropertyInfo);
string result = _builder.ToString();
result.ShouldBeEqualTo("");
}
[Test]
public void Should_return_empty_given_MappedPropertyInfo_Type_is_Bag()
{
MappedPropertyInfo mappedPropertyInfo = new MappedPropertyInfo(new HbmBag(), null);
_column.Add(mappedPropertyInfo);
string result = _builder.ToString();
result.ShouldBeEqualTo("");
}
[Test]
public void Should_return_empty_given_MappedPropertyInfo_Type_is_Id_and_columnName_is_null()
{
MappedPropertyInfo mappedPropertyInfo = new MappedPropertyInfo(new HbmId(), null);
_column.Add(mappedPropertyInfo);
string result = _builder.ToString();
result.ShouldBeEqualTo("");
}
[Test]
public void Should_generate_correct_code_given_MappedPropertyInfo_Type_is_Id_and_columnName_is_not_null()
{
const string columnName = "FirstName";
MappedPropertyInfo mappedPropertyInfo = new MappedPropertyInfo(new HbmId
{
column = new[]
{
new HbmColumn
{
name = columnName
}
}
}, null);
_column.Add(mappedPropertyInfo);
string result = _builder.ToString();
result.ShouldBeEqualTo(string.Format(".{0}(\"{1}\")\r\n", Column.FluentNHibernateNames.Column, columnName));
}
}
}
} | 28.428571 | 112 | 0.730438 | [
"MIT"
] | burlhock/hbm-to-fnh | src/ConverterTests/Methods/ColumnTests.cs | 2,786 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace TestSetup
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
MessageBox.Show("0");
}
}
}
| 18.692308 | 62 | 0.641975 | [
"MIT"
] | wannaphongcom/TestGit | TestSetup/TestSetup/Form1.cs | 488 | C# |
using System;
using System.Runtime.InteropServices;
namespace MsRdpEx
{
public class RdpCoreApi
{
public IMsRdpExCoreApi iface;
public RdpCoreApi()
{
iface = Bindings.GetCoreApi();
}
public void Load()
{
iface.Load();
}
public void Unload()
{
iface.Unload();
}
public string MsRdpExDllPath
{
get { return Marshal.PtrToStringAnsi(iface.GetMsRdpExDllPath()); }
}
public bool LogEnabled
{
set { iface.SetLogEnabled(value); }
}
public MsRdpEx_LogLevel LogLevel
{
set { iface.SetLogLevel(value); }
}
public string LogFilePath
{
set { iface.SetLogFilePath(value); }
}
public bool PcapEnabled
{
set { iface.SetPcapEnabled(value); }
}
public string PcapFilePath
{
set { iface.SetPcapFilePath(value); }
}
public bool AxHookEnabled
{
set { iface.SetAxHookEnabled(value); }
}
}
}
| 19.016393 | 78 | 0.497414 | [
"MIT"
] | Devolutions/MsRdpEx | dotnet/Devolutions.MsRdpEx/RdpCoreApi.cs | 1,160 | C# |
namespace BankSystem.Client.Commands.BankAccountCommands
{
using System.Linq;
using BankSystem.Client.IO;
using BankSystem.Data;
public static class ListAccountsCommand
{
public static void ListAccounts(BankSystemDbContext db, OutputWriter writer)
{
var result = db
.Users
.Where(u => u.IsLogged)
.Select(u => new
{
u.Username,
SavingAccounts = u
.SavingAccounts
.Select(s => new
{
s.AccountNumber,
s.Balance
}),
CheckingAccounts = u
.CheckingAccounts
.Select(c => new
{
c.AccountNumber,
c.Balance
})
})
.FirstOrDefault();
writer.WriteLine($"Accounts for user {result.Username}:");
writer.WriteLine("Saving Accounts:");
foreach (var account in result.SavingAccounts)
{
writer.WriteLine($"--{account.AccountNumber} {account.Balance}");
}
writer.WriteLine("Checking Accounts:");
foreach (var account in result.CheckingAccounts)
{
writer.WriteLine($"--{account.AccountNumber} {account.Balance}");
}
}
}
} | 31.4 | 84 | 0.435669 | [
"MIT"
] | mdamyanova/C-Sharp-Web-Development | 09.C# Web/09.01.C# Web Development Basics/02.Introduction to .NET Core and EF Core - Exercise - Complex Databases/04.BankSystem/BankSystem.Client/Commands/BankAccountCommands/ListAccountsCommand.cs | 1,572 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class package : MonoBehaviour {
panel package_panel;
//int selected_index = -1;
Image display;
Animator anim;
Text text_description;
Text text_name;
public Sprite nodisplay;
int selected = -1;
public static package main;
public Transform wp;
private void Awake() {
if (main == null)
main = this;
else if (main != this)
Destroy(gameObject);
}
// Use this for initialization
void Start () {
anim = GetComponent<Animator>();
package_panel = transform.Find("weapons_panel").GetComponent<panel>();
display = transform.Find("Image").GetComponent<Image>();
text_description = transform.Find("Text_description").GetComponent<Text>();
text_description.text = "";
text_name = transform.Find("Text_weaponsname").GetComponent<Text>();
text_name.text = "";
package_panel.initial_panel();
}
// Update is called once per frame
void Update () {
if (Input.GetKeyDown(KeyCode.I)) {
if (anim.GetBool("open")) {
close();
} else {
anim.SetBool("open",true);
anim.SetBool("isout", false);
}
}
}
public void additem(item i)
{
package_panel.addItem(i);
}
public void selected_item(int i)
{
if(!package_panel.blocks[i].isNull)
{
selected = i;
display.sprite = package_panel.blocks[i].sprite;
int n = package_panel.findweapons(package_panel.blocks[i].NAME);
text_name.text = package_panel.blocks[i].NAME;
text_description.text = package_panel.weapons[n].description;
}
}
public void close()
{
anim.SetBool("isout", true);
anim.SetBool("open",false);
}
public void delete()
{
if(selected!=-1)
{
package_panel.deleteItem(selected);
display.sprite =nodisplay;
text_name.text = "";
text_description.text = "";
}
}
}
| 26.488095 | 83 | 0.565393 | [
"MIT"
] | smjy/unity_game | Assets/LSN/Scripts_lsn/package.cs | 2,227 | C# |
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using SimpleStore.DataModel.Model;
using Microsoft.EntityFrameworkCore;
namespace SimpleStore.WebApp
{
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.AddControllersWithViews();
services.AddDbContext<AppDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("default")));
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
}
}
}
| 33.442623 | 144 | 0.611275 | [
"MIT"
] | 2011-nov02-net/david-code | 3-MVC/SimpleStore/SimpleStore.WebApp/Startup.cs | 2,040 | C# |
using System;
using Charlotte.Commons;
namespace Charlotte
{
// Token: 0x02000006 RID: 6
internal static class Program
{
// Token: 0x0600000A RID: 10 RVA: 0x00002297 File Offset: 0x00000497
[STAThread]
private static void Main()
{
ProcMain.GUIMain(() => new MainWin());
}
}
}
| 17.352941 | 70 | 0.688136 | [
"MIT"
] | soleil-taruto/Hatena | a20201226/Decompile/BeforeConfuse/Elsa20200001/Program.cs | 297 | C# |
using Verse;
#pragma warning disable IDE1006 // Naming Styles
namespace LoonyLadle.TFs
{
public class HediffCompProperties_Transformative : HediffCompProperties
{
public HediffCompProperties_Transformative() => compClass = typeof(HediffComp_Transformative);
// List of possible transformations.
public TransformationDef transformation;
// Mean time between TFs.
public float mtbDays;
// Number of transformations to do.
public int number = 1;
// Hash update interval (advanced users only).
public int interval = 60;
}
}
| 25.952381 | 96 | 0.765138 | [
"Unlicense"
] | LoonyLadle/TransformativeFramework | Source/TransformativeFramework/WaysToTransform/HediffCompProperties_Transformative.cs | 547 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
namespace Microsoft.Azure.PowerShell.Cmdlets.Synapse.Support
{
/// <summary>The provisioned state of the resource.</summary>
[System.ComponentModel.TypeConverter(typeof(Microsoft.Azure.PowerShell.Cmdlets.Synapse.Support.ResourceProvisioningStateTypeConverter))]
public partial struct ResourceProvisioningState :
System.Management.Automation.IArgumentCompleter
{
/// <summary>
/// Implementations of this function are called by PowerShell to complete arguments.
/// </summary>
/// <param name="commandName">The name of the command that needs argument completion.</param>
/// <param name="parameterName">The name of the parameter that needs argument completion.</param>
/// <param name="wordToComplete">The (possibly empty) word being completed.</param>
/// <param name="commandAst">The command ast in case it is needed for completion.</param>
/// <param name="fakeBoundParameters">This parameter is similar to $PSBoundParameters, except that sometimes PowerShell cannot
/// or will not attempt to evaluate an argument, in which case you may need to use commandAst.</param>
/// <returns>
/// A collection of completion results, most like with ResultType set to ParameterValue.
/// </returns>
public global::System.Collections.Generic.IEnumerable<global::System.Management.Automation.CompletionResult> CompleteArgument(global::System.String commandName, global::System.String parameterName, global::System.String wordToComplete, global::System.Management.Automation.Language.CommandAst commandAst, global::System.Collections.IDictionary fakeBoundParameters)
{
if (global::System.String.IsNullOrEmpty(wordToComplete) || "Running".StartsWith(wordToComplete, global::System.StringComparison.InvariantCultureIgnoreCase))
{
yield return new global::System.Management.Automation.CompletionResult("'Running'", "Running", global::System.Management.Automation.CompletionResultType.ParameterValue, "Running");
}
if (global::System.String.IsNullOrEmpty(wordToComplete) || "Creating".StartsWith(wordToComplete, global::System.StringComparison.InvariantCultureIgnoreCase))
{
yield return new global::System.Management.Automation.CompletionResult("'Creating'", "Creating", global::System.Management.Automation.CompletionResultType.ParameterValue, "Creating");
}
if (global::System.String.IsNullOrEmpty(wordToComplete) || "Deleting".StartsWith(wordToComplete, global::System.StringComparison.InvariantCultureIgnoreCase))
{
yield return new global::System.Management.Automation.CompletionResult("'Deleting'", "Deleting", global::System.Management.Automation.CompletionResultType.ParameterValue, "Deleting");
}
if (global::System.String.IsNullOrEmpty(wordToComplete) || "Succeeded".StartsWith(wordToComplete, global::System.StringComparison.InvariantCultureIgnoreCase))
{
yield return new global::System.Management.Automation.CompletionResult("'Succeeded'", "Succeeded", global::System.Management.Automation.CompletionResultType.ParameterValue, "Succeeded");
}
if (global::System.String.IsNullOrEmpty(wordToComplete) || "Failed".StartsWith(wordToComplete, global::System.StringComparison.InvariantCultureIgnoreCase))
{
yield return new global::System.Management.Automation.CompletionResult("'Failed'", "Failed", global::System.Management.Automation.CompletionResultType.ParameterValue, "Failed");
}
if (global::System.String.IsNullOrEmpty(wordToComplete) || "Moving".StartsWith(wordToComplete, global::System.StringComparison.InvariantCultureIgnoreCase))
{
yield return new global::System.Management.Automation.CompletionResult("'Moving'", "Moving", global::System.Management.Automation.CompletionResultType.ParameterValue, "Moving");
}
if (global::System.String.IsNullOrEmpty(wordToComplete) || "Canceled".StartsWith(wordToComplete, global::System.StringComparison.InvariantCultureIgnoreCase))
{
yield return new global::System.Management.Automation.CompletionResult("'Canceled'", "Canceled", global::System.Management.Automation.CompletionResultType.ParameterValue, "Canceled");
}
}
}
} | 82.084746 | 373 | 0.715259 | [
"MIT"
] | Agazoth/azure-powershell | src/Synapse/Synapse.Autorest/generated/api/Support/ResourceProvisioningState.Completer.cs | 4,785 | C# |
namespace Shuhari.Framework.DomainModel
{
/// <summary>
/// Save authentication result
/// </summary>
public class AuthenticationResultDto : ResultDto
{
/// <summary>
/// User information, or null if auth failed.
/// </summary>
public UserInfo User { get; set; }
}
}
| 23.142857 | 53 | 0.580247 | [
"Apache-2.0"
] | shuhari/Shuhari.Framework | Shuhari.Framework.Common/DomainModel/AuthenticationResultDTO.cs | 326 | C# |
namespace NuGet.ProjectModel
{
public enum ProjectStyle : ushort
{
/// <summary>
/// Unknown
/// </summary>
Unknown = 0,
/// <summary>
/// UAP style, project.lock.json is generated next to project.json
/// </summary>
ProjectJson = 1,
/// <summary>
/// MSBuild style, project.assets.json is generated in the RestoreOutputPath folder
/// </summary>
PackageReference = 2,
/// <summary>
/// Tool
/// </summary>
DotnetCliTool = 3,
/// <summary>
/// Non-MSBuild project with no project dependencies.
/// </summary>
Standalone = 4,
/// <summary>
/// Packages.config project
/// </summary>
PackagesConfig = 5
}
} | 23.257143 | 91 | 0.501229 | [
"Apache-2.0"
] | Thomas06000/NuGet.Client | src/NuGet.Core/NuGet.ProjectModel/RestoreOutputType.cs | 816 | C# |
using System;
using System.IO;
using NLog;
namespace t4my
{
class Program
{
private static NLog.Logger log = NLog.LogManager.GetCurrentClassLogger();
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
Console.WriteLine("CWD = " + Environment.CurrentDirectory);
// Debug_WriteEnvVare();
// Debug_WriteConfigSample();
RunProcess(args);
log.Debug("Bye World");
Console.WriteLine("Bye World!");
NLog.LogManager.Shutdown(); // Flush and close down internal threads and timers
}
/// <summary>
///
/// </summary>
/// <param name="args"></param>
/// <returns></returns>
private static bool RunProcess(string[] args)
{
log.Info("Processing Commandline arguments");
if (args.Length < 1)
{
// Throw Error
log.Error("Insufficient arguments, cannot proceeed");
return false;
}
string lsAction = args[0].ToLower();
string lsOutFile;
t4my.Config loConfig;
// [Output file]
lsOutFile = (args.Length > 1) ? args[1] : string.Empty;
// [Configuration file]
loConfig = (args.Length > 2 && !string.IsNullOrWhiteSpace(args[2]))
? t4my.Config.FromFile (args[2])
: t4my.Config.FromFile()
;
if (loConfig == null)
{
log.Error("Cannot proceed without a valid configuration.");
return false;
}
// [Trigger template file]
if (args.Length > 3)
{
loConfig.TriggerTemplateFile = args[3];
}
// [Audit template file]
if (args.Length > 4)
{
loConfig.AuditTableTemplateFile = args[4];
}
if (!string.IsNullOrEmpty(lsOutFile))
{
loConfig.OutputFile = lsOutFile;
}
(bool lbIsValid, string lsErrors) = loConfig.Validate();
if (!lbIsValid)
{
log.Error("Cannot proceed, unrecoverable errors. See details below.");
log.Error(lsErrors);
return false;
}
// Begin processing
switch (lsAction)
{
case "l":
log.Info("Option selected: L = 'List all Tables'");
string lsTables = t4my.Tables.List(loConfig);
Console.WriteLine(lsTables);
return true;
case "g":
log.Info("Option selected: G = 'Generate Script'");
string lsScript = t4my.Triggers.TriggersScript(loConfig);
break;
default:
// Throw error condition
log.Error(
new ArgumentException($"Unknown value '{lsAction}', aborting further processing.", "Action")
, $"Unknown value '{lsAction}', aborting further processing."
);
return false;
}
return true;
}
#region Debugging functions - Can be safely deleted
static string NL = Environment.NewLine;
static void Debug_WriteEnvVare()
{
System.Collections.Hashtable loEVs = Environment.GetEnvironmentVariables() as System.Collections.Hashtable;
string lsVar, lsLongOutput = Environment.NewLine;
int liCount = 0;
lsLongOutput += "Emitting Environment Variables - BEGIN" + NL;
// Console.WriteLine("Emitting Environment Variables - BEGIN");
foreach (string vKey in loEVs.Keys)
{
liCount++;
lsVar = string.Format("{0,2}. {1,-30} = {2}", liCount, vKey, loEVs[vKey].ToString());
lsLongOutput += lsVar + NL;
// Console.WriteLine(lsVar);
}
lsLongOutput += "Emitting Environment Variables - END" + NL;
// Console.WriteLine("Emitting Environment Variables - END");
log.Info(lsLongOutput);
}
static void Debug_WriteConfigSample()
{
t4my.Config loConfig = Debug_GetConfigSample();
// Console.WriteLine(loConfig.ToJSON());
log.Info(NL + loConfig.ToJSON() + NL);
}
static t4my.Config Debug_GetConfigSample()
{
System.Collections.Generic.List<string> loList = new System.Collections.Generic.List<string>();
loList.Add("Table_A");
loList.Add("Table_B");
loList.Add("Table_C");
loList.Add("Table_D");
t4my.Config loConfig = new Config()
{
ConnectionString = "server=127.0.0.1;port=3306;user=db_schema_user;password=plain_text_password;database=schema-name",
Schema = "schema-name",
TableList = loList,
};
return loConfig;
}
#endregion Debugging functions
}
}
| 26.99359 | 123 | 0.632154 | [
"MIT"
] | sajidak/MySQL-Triggers | t4my/Program.cs | 4,213 | C# |
using Improbable.Gdk.Core;
using Unity.Entities;
using UnityEngine;
namespace Improbable.Gdk.TransformSynchronization
{
[DisableAutoCreation]
[UpdateAfter(typeof(DefaultUpdateLatestTransformSystem))]
[UpdateAfter(typeof(RateLimitedTransformSendSystem))]
[UpdateInGroup(typeof(SpatialOSUpdateGroup))]
public class RateLimitedPositionSendSystem : ComponentSystem
{
private EntityQuery positionGroup;
protected override void OnCreate()
{
base.OnCreate();
positionGroup = GetEntityQuery(
ComponentType.ReadWrite<LastPositionSentData>(),
ComponentType.ReadWrite<Position.Component>(),
ComponentType.ReadOnly<TransformInternal.Component>(),
ComponentType.ReadOnly<RateLimitedSendConfig>(),
ComponentType.ReadOnly<Position.HasAuthority>()
);
}
protected override void OnUpdate()
{
Entities.With(positionGroup).ForEach((RateLimitedSendConfig config, ref Position.Component position,
ref TransformInternal.Component transformInternal, ref LastPositionSentData lastPositionSent) =>
{
lastPositionSent.TimeSinceLastUpdate += Time.DeltaTime;
if (lastPositionSent.TimeSinceLastUpdate < 1.0f / config.MaxPositionUpdateRateHz)
{
return;
}
var coords = transformInternal.Location.ToCoordinates();
if (coords == position.Coords)
{
return;
}
position.Coords = coords;
lastPositionSent.TimeSinceLastUpdate = 0.0f;
lastPositionSent.Position = position;
});
}
}
}
| 33.685185 | 112 | 0.611325 | [
"MIT"
] | 456-Ritwik/gdk-for-unity | workers/unity/Packages/io.improbable.gdk.transformsynchronization/Systems/RateLimitedPositionSendSystem.cs | 1,819 | 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.
#nullable disable
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.Packaging;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.AddPackage
{
internal class InstallPackageDirectlyCodeAction : CodeAction
{
private readonly CodeActionOperation _installPackageOperation;
public override string Title { get; }
public InstallPackageDirectlyCodeAction(
IPackageInstallerService installerService,
Document document,
string source,
string packageName,
string versionOpt,
bool includePrerelease,
bool isLocal
)
{
Title =
versionOpt == null
? FeaturesResources.Find_and_install_latest_version
: isLocal
? string.Format(FeaturesResources.Use_local_version_0, versionOpt)
: string.Format(FeaturesResources.Install_version_0, versionOpt);
_installPackageOperation = new InstallPackageDirectlyCodeActionOperation(
installerService,
document,
source,
packageName,
versionOpt,
includePrerelease,
isLocal
);
}
protected override Task<IEnumerable<CodeActionOperation>> ComputeOperationsAsync(
CancellationToken cancellationToken
) => Task.FromResult(SpecializedCollections.SingletonEnumerable(_installPackageOperation));
}
}
| 33.781818 | 99 | 0.649085 | [
"MIT"
] | belav/roslyn | src/Features/Core/Portable/AddPackage/InstallPackageDirectlyCodeAction.cs | 1,860 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerHealth : Health
{
int tierRange; //How many value are in one tier
int CurrentTier => Mathf.CeilToInt((float)currentHealth / tierRange); //Get which tier the player is in
int currentTier;
protected override void Start()
{
base.Start();
SetID(PoolID.Player);
tierRange = MaxHealth / 5; //5 is the number of health bars
currentTier = CurrentTier; //Set the current tier
}
public override void Heal(int amount)
{
base.Heal(amount);
UpdateHealthBar();
}
public override void TakeDamage(int damage)
{
base.TakeDamage(damage);
UpdateHealthBar();
//Turn off characters and stop coroutines
if(currentHealth <= 0)
{
EventManager.playerDied.Invoke();
EventManager.toggleCharacters(0);
}
}
void UpdateHealthBar()
{
//When player change tier update current tier and UI health bar
if(currentTier != CurrentTier)
{
currentTier = CurrentTier;
UIManager.Instance.UpdateHealthBar(currentTier);
}
}
} | 25.479167 | 107 | 0.619787 | [
"MIT"
] | SpeedyE1780/Light-Is-Your-Friend | Assets/Scripts/Player/PlayerHealth.cs | 1,225 | C# |
using System.Collections.Generic;
using System.Linq;
using Windows.Services.Maps;
namespace Microsoft.Maui.Essentials
{
public static partial class LocationExtensions
{
internal static IEnumerable<Placemark> ToPlacemarks(this IEnumerable<MapLocation> mapLocations)
{
return mapLocations.Select(address => new Placemark
{
Location = address.ToLocation(),
FeatureName = address.DisplayName,
PostalCode = address.Address.PostCode,
CountryCode = address.Address.CountryCode,
CountryName = address.Address.Country,
Thoroughfare = address.Address.Street,
SubThoroughfare = address.Address.StreetNumber,
Locality = address.Address.Town,
AdminArea = address.Address.Region,
SubAdminArea = address.Address.District,
SubLocality = address.Address.Neighborhood
});
}
internal static IEnumerable<Placemark> ToPlacemarks(this MapLocationFinderResult result) =>
result?.ToPlacemarks();
}
}
| 36.967742 | 103 | 0.6274 | [
"MIT"
] | Eilon/maui | src/Essentials/src/Types/PlacemarkExtensions.uwp.cs | 1,146 | C# |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Description;
using lab_47_NET_API.Areas.HelpPage.ModelDescriptions;
using lab_47_NET_API.Areas.HelpPage.Models;
namespace lab_47_NET_API.Areas.HelpPage
{
public static class HelpPageConfigurationExtensions
{
private const string ApiModelPrefix = "MS_HelpPageApiModel_";
/// <summary>
/// Sets the documentation provider for help page.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="documentationProvider">The documentation provider.</param>
public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider)
{
config.Services.Replace(typeof(IDocumentationProvider), documentationProvider);
}
/// <summary>
/// Sets the objects that will be used by the formatters to produce sample requests/responses.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleObjects">The sample objects.</param>
public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects)
{
config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects;
}
/// <summary>
/// Sets the sample request directly for the specified media type and action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type and action with parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type of the action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample response directly for the specified media type of the action with specific parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified type and media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="type">The parameter type or return type of an action.</param>
public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Gets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <returns>The help page sample generator.</returns>
public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config)
{
return (HelpPageSampleGenerator)config.Properties.GetOrAdd(
typeof(HelpPageSampleGenerator),
k => new HelpPageSampleGenerator());
}
/// <summary>
/// Sets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleGenerator">The help page sample generator.</param>
public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator)
{
config.Properties.AddOrUpdate(
typeof(HelpPageSampleGenerator),
k => sampleGenerator,
(k, o) => sampleGenerator);
}
/// <summary>
/// Gets the model description generator.
/// </summary>
/// <param name="config">The configuration.</param>
/// <returns>The <see cref="ModelDescriptionGenerator"/></returns>
public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config)
{
return (ModelDescriptionGenerator)config.Properties.GetOrAdd(
typeof(ModelDescriptionGenerator),
k => InitializeModelDescriptionGenerator(config));
}
/// <summary>
/// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param>
/// <returns>
/// An <see cref="HelpPageApiModel"/>
/// </returns>
public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId)
{
object model;
string modelId = ApiModelPrefix + apiDescriptionId;
if (!config.Properties.TryGetValue(modelId, out model))
{
Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions;
ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase));
if (apiDescription != null)
{
model = GenerateApiModel(apiDescription, config);
config.Properties.TryAdd(modelId, model);
}
}
return (HelpPageApiModel)model;
}
private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config)
{
HelpPageApiModel apiModel = new HelpPageApiModel()
{
ApiDescription = apiDescription,
};
ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator();
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
GenerateUriParameters(apiModel, modelGenerator);
GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator);
GenerateResourceDescription(apiModel, modelGenerator);
GenerateSamples(apiModel, sampleGenerator);
return apiModel;
}
private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromUri)
{
HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor;
Type parameterType = null;
ModelDescription typeDescription = null;
ComplexTypeModelDescription complexTypeDescription = null;
if (parameterDescriptor != null)
{
parameterType = parameterDescriptor.ParameterType;
typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
complexTypeDescription = typeDescription as ComplexTypeModelDescription;
}
// Example:
// [TypeConverter(typeof(PointConverter))]
// public class Point
// {
// public Point(int x, int y)
// {
// X = x;
// Y = y;
// }
// public int X { get; set; }
// public int Y { get; set; }
// }
// Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection.
//
// public class Point
// {
// public int X { get; set; }
// public int Y { get; set; }
// }
// Regular complex class Point will have properties X and Y added to UriParameters collection.
if (complexTypeDescription != null
&& !IsBindableWithTypeConverter(parameterType))
{
foreach (ParameterDescription uriParameter in complexTypeDescription.Properties)
{
apiModel.UriParameters.Add(uriParameter);
}
}
else if (parameterDescriptor != null)
{
ParameterDescription uriParameter =
AddParameterDescription(apiModel, apiParameter, typeDescription);
if (!parameterDescriptor.IsOptional)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" });
}
object defaultValue = parameterDescriptor.DefaultValue;
if (defaultValue != null)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) });
}
}
else
{
Debug.Assert(parameterDescriptor == null);
// If parameterDescriptor is null, this is an undeclared route parameter which only occurs
// when source is FromUri. Ignored in request model and among resource parameters but listed
// as a simple string here.
ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string));
AddParameterDescription(apiModel, apiParameter, modelDescription);
}
}
}
}
private static bool IsBindableWithTypeConverter(Type parameterType)
{
if (parameterType == null)
{
return false;
}
return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string));
}
private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel,
ApiParameterDescription apiParameter, ModelDescription typeDescription)
{
ParameterDescription parameterDescription = new ParameterDescription
{
Name = apiParameter.Name,
Documentation = apiParameter.Documentation,
TypeDescription = typeDescription,
};
apiModel.UriParameters.Add(parameterDescription);
return parameterDescription;
}
private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromBody)
{
Type parameterType = apiParameter.ParameterDescriptor.ParameterType;
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
apiModel.RequestDocumentation = apiParameter.Documentation;
}
else if (apiParameter.ParameterDescriptor != null &&
apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))
{
Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
if (parameterType != null)
{
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
}
}
private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ResponseDescription response = apiModel.ApiDescription.ResponseDescription;
Type responseType = response.ResponseType ?? response.DeclaredType;
if (responseType != null && responseType != typeof(void))
{
apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType);
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")]
private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator)
{
try
{
foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription))
{
apiModel.SampleRequests.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription))
{
apiModel.SampleResponses.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
}
catch (Exception e)
{
apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture,
"An exception has occurred while generating the sample. Exception message: {0}",
HelpPageSampleGenerator.UnwrapException(e).Message));
}
}
private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType)
{
parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault(
p => p.Source == ApiParameterSource.FromBody ||
(p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)));
if (parameterDescription == null)
{
resourceType = null;
return false;
}
resourceType = parameterDescription.ParameterDescriptor.ParameterType;
if (resourceType == typeof(HttpRequestMessage))
{
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
}
if (resourceType == null)
{
parameterDescription = null;
return false;
}
return true;
}
private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config)
{
ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config);
Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions;
foreach (ApiDescription api in apis)
{
ApiParameterDescription parameterDescription;
Type parameterType;
if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType))
{
modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
return modelGenerator;
}
private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample)
{
InvalidSample invalidSample = sample as InvalidSample;
if (invalidSample != null)
{
apiModel.ErrorMessages.Add(invalidSample.ErrorMessage);
}
}
}
}
| 51.470085 | 196 | 0.62309 | [
"MIT"
] | aesmailsparta/2019-09-c-sharp-labs | labs/lab_47_NET_API/Areas/HelpPage/HelpPageConfigurationExtensions.cs | 24,088 | C# |
//Lambda动态表达式
public static class LambdaDynamicExpressions
{
public static Expression<Func<T, bool>> True<T>() { return f => true; }
public static Expression<Func<T, bool>> False<T>() { return f => false; }
public static Expression<Func<T, bool>> Or<T>(this Expression<Func<T, bool>> expr1, Expression<Func<T, bool>> expr2)
{
var invokedExpr = Expression.Invoke(expr2, expr1.Parameters);
return Expression.Lambda<Func<T, bool>>(Expression.Or(expr1.Body, invokedExpr), expr1.Parameters);
}
public static Expression<Func<T, bool>> And<T>(this Expression<Func<T, bool>> expr1, Expression<Func<T, bool>> expr2)
{
var invokedExpr = Expression.Invoke(expr2, expr1.Parameters);
return Expression.Lambda<Func<T, bool>>(Expression.And(expr1.Body, invokedExpr), expr1.Parameters);
}
} | 44.263158 | 121 | 0.687277 | [
"MIT"
] | colindcli/COLINBLOG | Net.Utility/LambdaDynamicExpressions.cs | 851 | C# |
using System.Collections.Generic;
using JetBrains.Annotations;
namespace System.Linq.Dynamic.Core.CustomTypeProviders
{
/// <summary>
/// Interface for providing functionality to find custom types for or resolve any type.
/// </summary>
public interface IDynamicLinkCustomTypeProvider
{
/// <summary>
/// Returns a list of custom types that System.Linq.Dynamic.Core will understand.
/// </summary>
/// <returns>A <see cref="HashSet<Type>" /> list of custom types.</returns>
HashSet<Type> GetCustomTypes();
/// <summary>
/// Resolve any type which is registered in the current application domain.
/// </summary>
/// <param name="typeName">The typename to resolve.</param>
/// <returns>A resolved <see cref="Type"/> or null when not found.</returns>
Type ResolveType([NotNull] string typeName);
}
}
| 36.72 | 91 | 0.645969 | [
"Apache-2.0"
] | akrisiun/System.Linq.Dynamic.Core | src/System.Linq.Dynamic.Core/CustomTypeProviders/IDynamicLinkCustomTypeProvider.cs | 920 | C# |
// This file was modified by Kin Ecosystem (2019)
using System;
using System.Globalization;
using System.Linq;
using System.Text;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Kin.Base;
namespace kin_base_test
{
[TestClass]
public class OperationTest
{
[TestMethod]
public void TestCreateAccountOperation()
{
// GC5SIC4E3V56VOHJ3OZAX5SJDTWY52JYI2AFK6PUGSXFVRJQYQXXZBZF
var source = KeyPair.FromSecretSeed("SC4CGETADVYTCR5HEAVZRB3DZQY5Y4J7RFNJTRA6ESMHIPEZUSTE2QDK");
// GDW6AUTBXTOC7FIKUO5BOO3OGLK4SF7ZPOBLMQHMZDI45J2Z6VXRB5NR
var destination = KeyPair.FromSecretSeed("SDHZGHURAYXKU2KMVHPOXI6JG2Q4BSQUQCEOY72O3QQTCLR2T455PMII");
const string startingAmount = "100000";
var operation = new CreateAccountOperation.Builder(destination, startingAmount)
.SetSourceAccount(source)
.Build();
var xdr = operation.ToXdr();
var parsedOperation = (CreateAccountOperation) Operation.FromXdr(xdr);
Assert.AreEqual(10000000000L, xdr.Body.CreateAccountOp.StartingBalance.InnerValue);
Assert.AreEqual(source.AccountId, parsedOperation.SourceAccount.AccountId);
Assert.AreEqual(destination.AccountId, parsedOperation.Destination.AccountId);
Assert.AreEqual(startingAmount, parsedOperation.StartingBalance);
Assert.AreEqual(OperationThreshold.Medium, parsedOperation.Threshold);
Assert.AreEqual(
"AAAAAQAAAAC7JAuE3XvquOnbsgv2SRztjuk4RoBVefQ0rlrFMMQvfAAAAAAAAAAA7eBSYbzcL5UKo7oXO24y1ckX+XuCtkDsyNHOp1n1bxAAAAACVAvkAA==",
operation.ToXdrBase64());
}
[TestMethod]
public void TestPaymentOperation()
{
// GC5SIC4E3V56VOHJ3OZAX5SJDTWY52JYI2AFK6PUGSXFVRJQYQXXZBZF
var source = KeyPair.FromSecretSeed("SC4CGETADVYTCR5HEAVZRB3DZQY5Y4J7RFNJTRA6ESMHIPEZUSTE2QDK");
// GDW6AUTBXTOC7FIKUO5BOO3OGLK4SF7ZPOBLMQHMZDI45J2Z6VXRB5NR
var destination = KeyPair.FromSecretSeed("SDHZGHURAYXKU2KMVHPOXI6JG2Q4BSQUQCEOY72O3QQTCLR2T455PMII");
Asset asset = new AssetTypeNative();
var amount = "100000";
var operation = new PaymentOperation.Builder(destination, asset, amount)
.SetSourceAccount(source)
.Build();
var xdr = operation.ToXdr();
var parsedOperation = (PaymentOperation) Operation.FromXdr(xdr);
Assert.AreEqual(10000000000L, xdr.Body.PaymentOp.Amount.InnerValue);
Assert.AreEqual(source.AccountId, parsedOperation.SourceAccount.AccountId);
Assert.AreEqual(destination.AccountId, parsedOperation.Destination.AccountId);
Assert.IsTrue(parsedOperation.Asset is AssetTypeNative);
Assert.AreEqual(amount, parsedOperation.Amount);
Assert.AreEqual(OperationThreshold.Medium, parsedOperation.Threshold);
Assert.AreEqual(
"AAAAAQAAAAC7JAuE3XvquOnbsgv2SRztjuk4RoBVefQ0rlrFMMQvfAAAAAEAAAAA7eBSYbzcL5UKo7oXO24y1ckX+XuCtkDsyNHOp1n1bxAAAAAAAAAAAlQL5AA=",
operation.ToXdrBase64());
}
[TestMethod]
public void TestPathPaymentOperation()
{
// GC5SIC4E3V56VOHJ3OZAX5SJDTWY52JYI2AFK6PUGSXFVRJQYQXXZBZF
var source = KeyPair.FromSecretSeed("SC4CGETADVYTCR5HEAVZRB3DZQY5Y4J7RFNJTRA6ESMHIPEZUSTE2QDK");
// GDW6AUTBXTOC7FIKUO5BOO3OGLK4SF7ZPOBLMQHMZDI45J2Z6VXRB5NR
var destination = KeyPair.FromSecretSeed("SDHZGHURAYXKU2KMVHPOXI6JG2Q4BSQUQCEOY72O3QQTCLR2T455PMII");
// GCGZLB3X2B3UFOFSHHQ6ZGEPEX7XYPEH6SBFMIV74EUDOFZJA3VNL6X4
var issuer = KeyPair.FromSecretSeed("SBOBVZUN6WKVMI6KIL2GHBBEETEV6XKQGILITNH6LO6ZA22DBMSDCPAG");
// GAVAQKT2M7B4V3NN7RNNXPU5CWNDKC27MYHKLF5UNYXH4FNLFVDXKRSV
var pathIssuer1 = KeyPair.FromSecretSeed("SALDLG5XU5AEJWUOHAJPSC4HJ2IK3Z6BXXP4GWRHFT7P7ILSCFFQ7TC5");
// GBCP5W2VS7AEWV2HFRN7YYC623LTSV7VSTGIHFXDEJU7S5BAGVCSETRR
var pathIssuer2 = KeyPair.FromSecretSeed("SA64U7C5C7BS5IHWEPA7YWFN3Z6FE5L6KAMYUIT4AQ7KVTVLD23C6HEZ");
Asset sendAsset = new AssetTypeNative();
var sendMax = "0.01";
Asset destAsset = new AssetTypeCreditAlphaNum4("USD", issuer.AccountId);
var destAmount = "0.01";
Asset[] path = {new AssetTypeCreditAlphaNum4("USD", pathIssuer1.AccountId), new AssetTypeCreditAlphaNum12("TESTTEST", pathIssuer2.AccountId)};
var operation = new PathPaymentOperation.Builder(
sendAsset, sendMax, destination, destAsset, destAmount)
.SetPath(path)
.SetSourceAccount(source)
.Build();
var xdr = operation.ToXdr();
var parsedOperation = (PathPaymentOperation) Operation.FromXdr(xdr);
Assert.AreEqual(1000L, xdr.Body.PathPaymentOp.SendMax.InnerValue);
Assert.AreEqual(1000L, xdr.Body.PathPaymentOp.DestAmount.InnerValue);
Assert.IsTrue(parsedOperation.SendAsset is AssetTypeNative);
Assert.AreEqual(source.AccountId, parsedOperation.SourceAccount.AccountId);
Assert.AreEqual(destination.AccountId, parsedOperation.Destination.AccountId);
Assert.AreEqual(sendMax, parsedOperation.SendMax);
Assert.IsTrue(parsedOperation.DestAsset is AssetTypeCreditAlphaNum4);
Assert.AreEqual(destAmount, parsedOperation.DestAmount);
Assert.AreEqual(path.Length, parsedOperation.Path.Length);
Assert.AreEqual(OperationThreshold.Medium, parsedOperation.Threshold);
Assert.AreEqual(
"AAAAAQAAAAC7JAuE3XvquOnbsgv2SRztjuk4RoBVefQ0rlrFMMQvfAAAAAIAAAAAAAAAAAAAA+gAAAAA7eBSYbzcL5UKo7oXO24y1ckX+XuCtkDsyNHOp1n1bxAAAAABVVNEAAAAAACNlYd30HdCuLI54eyYjyX/fDyH9IJWIr/hKDcXKQbq1QAAAAAAAAPoAAAAAgAAAAFVU0QAAAAAACoIKnpnw8rtrfxa276dFZo1C19mDqWXtG4ufhWrLUd1AAAAAlRFU1RURVNUAAAAAAAAAABE/ttVl8BLV0csW/xgXtbXOVf1lMyDluMiafl0IDVFIg==",
operation.ToXdrBase64());
}
[TestMethod]
public void TestPathPaymentEmptyPathOperation()
{
// GC5SIC4E3V56VOHJ3OZAX5SJDTWY52JYI2AFK6PUGSXFVRJQYQXXZBZF
var source = KeyPair.FromSecretSeed("SC4CGETADVYTCR5HEAVZRB3DZQY5Y4J7RFNJTRA6ESMHIPEZUSTE2QDK");
// GDW6AUTBXTOC7FIKUO5BOO3OGLK4SF7ZPOBLMQHMZDI45J2Z6VXRB5NR
var destination = KeyPair.FromSecretSeed("SDHZGHURAYXKU2KMVHPOXI6JG2Q4BSQUQCEOY72O3QQTCLR2T455PMII");
// GCGZLB3X2B3UFOFSHHQ6ZGEPEX7XYPEH6SBFMIV74EUDOFZJA3VNL6X4
var issuer = KeyPair.FromSecretSeed("SBOBVZUN6WKVMI6KIL2GHBBEETEV6XKQGILITNH6LO6ZA22DBMSDCPAG");
// GAVAQKT2M7B4V3NN7RNNXPU5CWNDKC27MYHKLF5UNYXH4FNLFVDXKRSV
var unused1 = KeyPair.FromSecretSeed("SALDLG5XU5AEJWUOHAJPSC4HJ2IK3Z6BXXP4GWRHFT7P7ILSCFFQ7TC5");
// GBCP5W2VS7AEWV2HFRN7YYC623LTSV7VSTGIHFXDEJU7S5BAGVCSETRR
var unused = KeyPair.FromSecretSeed("SA64U7C5C7BS5IHWEPA7YWFN3Z6FE5L6KAMYUIT4AQ7KVTVLD23C6HEZ");
Asset sendAsset = new AssetTypeNative();
var sendMax = "0.01";
Asset destAsset = new AssetTypeCreditAlphaNum4("USD", issuer.AccountId);
var destAmount = "0.01";
var operation = new PathPaymentOperation.Builder(
sendAsset, sendMax, destination, destAsset, destAmount)
.SetSourceAccount(source)
.Build();
var xdr = operation.ToXdr();
var parsedOperation = (PathPaymentOperation) Operation.FromXdr(xdr);
Assert.AreEqual(1000L, xdr.Body.PathPaymentOp.SendMax.InnerValue);
Assert.AreEqual(1000L, xdr.Body.PathPaymentOp.DestAmount.InnerValue);
Assert.IsTrue(parsedOperation.SendAsset is AssetTypeNative);
Assert.AreEqual(source.AccountId, parsedOperation.SourceAccount.AccountId);
Assert.AreEqual(destination.AccountId, parsedOperation.Destination.AccountId);
Assert.AreEqual(sendMax, parsedOperation.SendMax);
Assert.IsTrue(parsedOperation.DestAsset is AssetTypeCreditAlphaNum4);
Assert.AreEqual(destAmount, parsedOperation.DestAmount);
Assert.AreEqual(0, parsedOperation.Path.Length);
Assert.AreEqual(OperationThreshold.Medium, parsedOperation.Threshold);
Assert.AreEqual(
"AAAAAQAAAAC7JAuE3XvquOnbsgv2SRztjuk4RoBVefQ0rlrFMMQvfAAAAAIAAAAAAAAAAAAAA+gAAAAA7eBSYbzcL5UKo7oXO24y1ckX+XuCtkDsyNHOp1n1bxAAAAABVVNEAAAAAACNlYd30HdCuLI54eyYjyX/fDyH9IJWIr/hKDcXKQbq1QAAAAAAAAPoAAAAAA==",
operation.ToXdrBase64());
}
[TestMethod]
public void TestChangeTrustOperation()
{
// GC5SIC4E3V56VOHJ3OZAX5SJDTWY52JYI2AFK6PUGSXFVRJQYQXXZBZF
var source = KeyPair.FromSecretSeed("SC4CGETADVYTCR5HEAVZRB3DZQY5Y4J7RFNJTRA6ESMHIPEZUSTE2QDK");
Asset asset = new AssetTypeNative();
var limit = "92233720368547.75807";
var operation = new ChangeTrustOperation.Builder(asset, limit)
.SetSourceAccount(source)
.Build();
var xdr = operation.ToXdr();
var parsedOperation = (ChangeTrustOperation) Operation.FromXdr(xdr);
Assert.AreEqual(9223372036854775807L, xdr.Body.ChangeTrustOp.Limit.InnerValue);
Assert.AreEqual(source.AccountId, parsedOperation.SourceAccount.AccountId);
Assert.IsTrue(parsedOperation.Asset is AssetTypeNative);
Assert.AreEqual(limit, parsedOperation.Limit);
Assert.AreEqual(OperationThreshold.Medium, parsedOperation.Threshold);
Assert.AreEqual(
"AAAAAQAAAAC7JAuE3XvquOnbsgv2SRztjuk4RoBVefQ0rlrFMMQvfAAAAAYAAAAAf/////////8=",
operation.ToXdrBase64());
}
[TestMethod]
public void TestAllowTrustOperation()
{
// GC5SIC4E3V56VOHJ3OZAX5SJDTWY52JYI2AFK6PUGSXFVRJQYQXXZBZF
var source = KeyPair.FromSecretSeed("SC4CGETADVYTCR5HEAVZRB3DZQY5Y4J7RFNJTRA6ESMHIPEZUSTE2QDK");
// GDW6AUTBXTOC7FIKUO5BOO3OGLK4SF7ZPOBLMQHMZDI45J2Z6VXRB5NR
var trustor = KeyPair.FromSecretSeed("SDHZGHURAYXKU2KMVHPOXI6JG2Q4BSQUQCEOY72O3QQTCLR2T455PMII");
const string assetCode = "USDA";
const bool authorize = true;
var operation = new AllowTrustOperation.Builder(trustor, assetCode, true)
.SetSourceAccount(source)
.Build();
var xdr = operation.ToXdr();
var parsedOperation = (AllowTrustOperation) Operation.FromXdr(xdr);
Assert.AreEqual(source.AccountId, parsedOperation.SourceAccount.AccountId);
Assert.AreEqual(trustor.AccountId, parsedOperation.Trustor.AccountId);
Assert.AreEqual(assetCode, parsedOperation.AssetCode);
Assert.AreEqual(authorize, parsedOperation.Authorize);
Assert.AreEqual(OperationThreshold.Low, parsedOperation.Threshold);
Assert.AreEqual(
"AAAAAQAAAAC7JAuE3XvquOnbsgv2SRztjuk4RoBVefQ0rlrFMMQvfAAAAAcAAAAA7eBSYbzcL5UKo7oXO24y1ckX+XuCtkDsyNHOp1n1bxAAAAABVVNEQQAAAAE=",
operation.ToXdrBase64());
}
[TestMethod]
public void TestSetOptionsOperation()
{
// GC5SIC4E3V56VOHJ3OZAX5SJDTWY52JYI2AFK6PUGSXFVRJQYQXXZBZF
var source = KeyPair.FromSecretSeed("SC4CGETADVYTCR5HEAVZRB3DZQY5Y4J7RFNJTRA6ESMHIPEZUSTE2QDK");
// GDW6AUTBXTOC7FIKUO5BOO3OGLK4SF7ZPOBLMQHMZDI45J2Z6VXRB5NR
var inflationDestination = KeyPair.FromSecretSeed("SDHZGHURAYXKU2KMVHPOXI6JG2Q4BSQUQCEOY72O3QQTCLR2T455PMII");
// GBCP5W2VS7AEWV2HFRN7YYC623LTSV7VSTGIHFXDEJU7S5BAGVCSETRR
var signer = Signer.Ed25519PublicKey(KeyPair.FromSecretSeed("SA64U7C5C7BS5IHWEPA7YWFN3Z6FE5L6KAMYUIT4AQ7KVTVLD23C6HEZ"));
var clearFlags = 1;
var setFlags = 1;
var masterKeyWeight = 1;
var lowThreshold = 2;
var mediumThreshold = 3;
var highThreshold = 4;
var homeDomain = "stellar.org";
var signerWeight = 1;
var operation = new SetOptionsOperation.Builder()
.SetInflationDestination(inflationDestination)
.SetClearFlags(clearFlags)
.SetSetFlags(setFlags)
.SetMasterKeyWeight(masterKeyWeight)
.SetLowThreshold(lowThreshold)
.SetMediumThreshold(mediumThreshold)
.SetHighThreshold(highThreshold)
.SetHomeDomain(homeDomain)
.SetSigner(signer, signerWeight)
.SetSourceAccount(source)
.Build();
var xdr = operation.ToXdr();
var parsedOperation = (SetOptionsOperation) Operation.FromXdr(xdr);
Assert.AreEqual(inflationDestination.AccountId, parsedOperation.InflationDestination.AccountId);
Assert.AreEqual(clearFlags, parsedOperation.ClearFlags);
Assert.AreEqual(setFlags, parsedOperation.SetFlags);
Assert.AreEqual(masterKeyWeight, parsedOperation.MasterKeyWeight);
Assert.AreEqual(lowThreshold, parsedOperation.LowThreshold);
Assert.AreEqual(mediumThreshold, parsedOperation.MediumThreshold);
Assert.AreEqual(highThreshold, parsedOperation.HighThreshold);
Assert.AreEqual(homeDomain, parsedOperation.HomeDomain);
Assert.AreEqual(signer.Discriminant.InnerValue, parsedOperation.Signer.Discriminant.InnerValue);
Assert.AreEqual(signer.Ed25519.InnerValue, parsedOperation.Signer.Ed25519.InnerValue);
Assert.AreEqual(signerWeight, parsedOperation.SignerWeight);
Assert.AreEqual(source.AccountId, parsedOperation.SourceAccount.AccountId);
Assert.AreEqual(OperationThreshold.High, parsedOperation.Threshold);
Assert.AreEqual(
"AAAAAQAAAAC7JAuE3XvquOnbsgv2SRztjuk4RoBVefQ0rlrFMMQvfAAAAAUAAAABAAAAAO3gUmG83C+VCqO6FztuMtXJF/l7grZA7MjRzqdZ9W8QAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAIAAAABAAAAAwAAAAEAAAAEAAAAAQAAAAtzdGVsbGFyLm9yZwAAAAABAAAAAET+21WXwEtXRyxb/GBe1tc5V/WUzIOW4yJp+XQgNUUiAAAAAQ==",
operation.ToXdrBase64());
}
[TestMethod]
public void TestSetOptionsOperationSingleField()
{
// GC5SIC4E3V56VOHJ3OZAX5SJDTWY52JYI2AFK6PUGSXFVRJQYQXXZBZF
var source = KeyPair.FromSecretSeed("SC4CGETADVYTCR5HEAVZRB3DZQY5Y4J7RFNJTRA6ESMHIPEZUSTE2QDK");
var homeDomain = "stellar.org";
var operation = new SetOptionsOperation.Builder()
.SetHomeDomain(homeDomain)
.SetSourceAccount(source)
.Build();
var xdr = operation.ToXdr();
var parsedOperation = (SetOptionsOperation) Operation.FromXdr(xdr);
Assert.AreEqual(null, parsedOperation.InflationDestination);
Assert.AreEqual(null, parsedOperation.ClearFlags);
Assert.AreEqual(null, parsedOperation.SetFlags);
Assert.AreEqual(null, parsedOperation.MasterKeyWeight);
Assert.AreEqual(null, parsedOperation.LowThreshold);
Assert.AreEqual(null, parsedOperation.MediumThreshold);
Assert.AreEqual(null, parsedOperation.HighThreshold);
Assert.AreEqual(homeDomain, parsedOperation.HomeDomain);
Assert.AreEqual(null, parsedOperation.Signer);
Assert.AreEqual(null, parsedOperation.SignerWeight);
Assert.AreEqual(source.AccountId, parsedOperation.SourceAccount.AccountId);
Assert.AreEqual(
"AAAAAQAAAAC7JAuE3XvquOnbsgv2SRztjuk4RoBVefQ0rlrFMMQvfAAAAAUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQAAAAtzdGVsbGFyLm9yZwAAAAAA",
operation.ToXdrBase64());
}
[TestMethod]
public void TestSetOptionsOperationSignerSha256()
{
// GC5SIC4E3V56VOHJ3OZAX5SJDTWY52JYI2AFK6PUGSXFVRJQYQXXZBZF
var source = KeyPair.FromSecretSeed("SC4CGETADVYTCR5HEAVZRB3DZQY5Y4J7RFNJTRA6ESMHIPEZUSTE2QDK");
var preimage = Encoding.UTF8.GetBytes("stellar.org");
var hash = Util.Hash(preimage);
var operation = new SetOptionsOperation.Builder()
.SetSigner(Signer.Sha256Hash(hash), 10)
.SetSourceAccount(source)
.Build();
var xdr = operation.ToXdr();
var parsedOperation = (SetOptionsOperation) Operation.FromXdr(xdr);
Assert.AreEqual(null, parsedOperation.InflationDestination);
Assert.AreEqual(null, parsedOperation.ClearFlags);
Assert.AreEqual(null, parsedOperation.SetFlags);
Assert.AreEqual(null, parsedOperation.MasterKeyWeight);
Assert.AreEqual(null, parsedOperation.LowThreshold);
Assert.AreEqual(null, parsedOperation.MediumThreshold);
Assert.AreEqual(null, parsedOperation.HighThreshold);
Assert.AreEqual(null, parsedOperation.HomeDomain);
Assert.IsTrue(hash.SequenceEqual(parsedOperation.Signer.HashX.InnerValue));
Assert.AreEqual(10, parsedOperation.SignerWeight);
Assert.AreEqual(source.AccountId, parsedOperation.SourceAccount.AccountId);
Assert.AreEqual(
"AAAAAQAAAAC7JAuE3XvquOnbsgv2SRztjuk4RoBVefQ0rlrFMMQvfAAAAAUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAACbpRqMkaQAfCYSk/n3xIl4fCoHfKqxF34ht2iuvSYEJQAAAAK",
operation.ToXdrBase64());
}
[TestMethod]
public void TestSetOptionsOperationPreAuthTxSigner()
{
Network OriginalTestNetwork = new Network("Test SDF Network ; September 2015");
Network.Use(OriginalTestNetwork);
// GBPMKIRA2OQW2XZZQUCQILI5TMVZ6JNRKM423BSAISDM7ZFWQ6KWEBC4
var source = KeyPair.FromSecretSeed("SCH27VUZZ6UAKB67BDNF6FA42YMBMQCBKXWGMFD5TZ6S5ZZCZFLRXKHS");
var destination = KeyPair.FromAccountId("GDW6AUTBXTOC7FIKUO5BOO3OGLK4SF7ZPOBLMQHMZDI45J2Z6VXRB5NR");
var sequenceNumber = 2908908335136768L;
var account = new Account(source.AccountId, sequenceNumber);
var transaction = new Transaction.Builder(account)
.AddOperation(new CreateAccountOperation.Builder(destination, "200000").Build())
.Build();
// GC5SIC4E3V56VOHJ3OZAX5SJDTWY52JYI2AFK6PUGSXFVRJQYQXXZBZF
var opSource = KeyPair.FromSecretSeed("SC4CGETADVYTCR5HEAVZRB3DZQY5Y4J7RFNJTRA6ESMHIPEZUSTE2QDK");
var operation = new SetOptionsOperation.Builder()
.SetSigner(Signer.PreAuthTx(transaction), 10)
.SetSourceAccount(opSource)
.Build();
var xdr = operation.ToXdr();
var parsedOperation = (SetOptionsOperation) Operation.FromXdr(xdr);
Assert.AreEqual(null, parsedOperation.InflationDestination);
Assert.AreEqual(null, parsedOperation.ClearFlags);
Assert.AreEqual(null, parsedOperation.SetFlags);
Assert.AreEqual(null, parsedOperation.MasterKeyWeight);
Assert.AreEqual(null, parsedOperation.LowThreshold);
Assert.AreEqual(null, parsedOperation.MediumThreshold);
Assert.AreEqual(null, parsedOperation.HighThreshold);
Assert.AreEqual(null, parsedOperation.HomeDomain);
Assert.IsTrue(transaction.Hash().SequenceEqual(parsedOperation.Signer.PreAuthTx.InnerValue));
Assert.AreEqual(10, parsedOperation.SignerWeight);
Assert.AreEqual(opSource.AccountId, parsedOperation.SourceAccount.AccountId);
Assert.AreEqual(
"AAAAAQAAAAC7JAuE3XvquOnbsgv2SRztjuk4RoBVefQ0rlrFMMQvfAAAAAUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAB1vRBIRC3w7ZH5rQa17hIBKUwZTvBP4kNmSP7jVyw1fQAAAAK",
operation.ToXdrBase64());
}
[TestMethod]
public void TestManageOfferOperation()
{
// GC5SIC4E3V56VOHJ3OZAX5SJDTWY52JYI2AFK6PUGSXFVRJQYQXXZBZF
var source = KeyPair.FromSecretSeed("SC4CGETADVYTCR5HEAVZRB3DZQY5Y4J7RFNJTRA6ESMHIPEZUSTE2QDK");
// GBCP5W2VS7AEWV2HFRN7YYC623LTSV7VSTGIHFXDEJU7S5BAGVCSETRR
var issuer = KeyPair.FromSecretSeed("SA64U7C5C7BS5IHWEPA7YWFN3Z6FE5L6KAMYUIT4AQ7KVTVLD23C6HEZ");
Asset selling = new AssetTypeNative();
var buying = Asset.CreateNonNativeAsset("USD", issuer.AccountId);
var amount = "0.001";
var price = "0.85334384"; // n=5333399 d=6250000
var priceObj = Price.FromString(price);
long offerId = 1;
var operation = new ManageOfferOperation.Builder(selling, buying, amount, price)
.SetOfferId(offerId)
.SetSourceAccount(source)
.Build();
Assert.AreEqual(
"AAAAAQAAAAC7JAuE3XvquOnbsgv2SRztjuk4RoBVefQ0rlrFMMQvfAAAAAMAAAAAAAAAAVVTRAAAAAAARP7bVZfAS1dHLFv8YF7W1zlX9ZTMg5bjImn5dCA1RSIAAAAAAAAAZABRYZcAX14QAAAAAAAAAAE=",
operation.ToXdrBase64());
}
[TestMethod]
public void TestManageSellOfferOperation()
{
// GC5SIC4E3V56VOHJ3OZAX5SJDTWY52JYI2AFK6PUGSXFVRJQYQXXZBZF
var source = KeyPair.FromSecretSeed("SC4CGETADVYTCR5HEAVZRB3DZQY5Y4J7RFNJTRA6ESMHIPEZUSTE2QDK");
// GBCP5W2VS7AEWV2HFRN7YYC623LTSV7VSTGIHFXDEJU7S5BAGVCSETRR
var issuer = KeyPair.FromSecretSeed("SA64U7C5C7BS5IHWEPA7YWFN3Z6FE5L6KAMYUIT4AQ7KVTVLD23C6HEZ");
Asset selling = new AssetTypeNative();
var buying = Asset.CreateNonNativeAsset("USD", issuer.AccountId);
var amount = "0.001";
var price = "0.85334384"; // n=5333399 d=6250000
var priceObj = Price.FromString(price);
long offerId = 1;
var operation = new ManageSellOfferOperation.Builder(selling, buying, amount, price)
.SetOfferId(offerId)
.SetSourceAccount(source)
.Build();
var xdr = operation.ToXdr();
var parsedOperation = (ManageSellOfferOperation) Operation.FromXdr(xdr);
Assert.AreEqual(100L, xdr.Body.ManageSellOfferOp.Amount.InnerValue);
Assert.IsTrue(parsedOperation.Selling is AssetTypeNative);
Assert.IsTrue(parsedOperation.Buying is AssetTypeCreditAlphaNum4);
Assert.IsTrue(parsedOperation.Buying.Equals(buying));
Assert.AreEqual(amount, parsedOperation.Amount);
Assert.AreEqual(price, parsedOperation.Price);
Assert.AreEqual(priceObj.Numerator, 5333399);
Assert.AreEqual(priceObj.Denominator, 6250000);
Assert.AreEqual(offerId, parsedOperation.OfferId);
Assert.AreEqual(OperationThreshold.Medium, parsedOperation.Threshold);
Assert.AreEqual(
"AAAAAQAAAAC7JAuE3XvquOnbsgv2SRztjuk4RoBVefQ0rlrFMMQvfAAAAAMAAAAAAAAAAVVTRAAAAAAARP7bVZfAS1dHLFv8YF7W1zlX9ZTMg5bjImn5dCA1RSIAAAAAAAAAZABRYZcAX14QAAAAAAAAAAE=",
operation.ToXdrBase64());
}
[TestMethod]
public void TestManageBuyOfferOperation()
{
// GC5SIC4E3V56VOHJ3OZAX5SJDTWY52JYI2AFK6PUGSXFVRJQYQXXZBZF
var source = KeyPair.FromSecretSeed("SC4CGETADVYTCR5HEAVZRB3DZQY5Y4J7RFNJTRA6ESMHIPEZUSTE2QDK");
// GBCP5W2VS7AEWV2HFRN7YYC623LTSV7VSTGIHFXDEJU7S5BAGVCSETRR
var issuer = KeyPair.FromSecretSeed("SA64U7C5C7BS5IHWEPA7YWFN3Z6FE5L6KAMYUIT4AQ7KVTVLD23C6HEZ");
Asset selling = new AssetTypeNative();
var buying = Asset.CreateNonNativeAsset("USD", issuer.AccountId);
var amount = "0.001";
var price = "0.85334384"; // n=5333399 d=6250000
var priceObj = Price.FromString(price);
long offerId = 1;
var operation = new ManageBuyOfferOperation.Builder(selling, buying, amount, price)
.SetOfferId(offerId)
.SetSourceAccount(source)
.Build();
var xdr = operation.ToXdr();
var parsedOperation = (ManageBuyOfferOperation) Operation.FromXdr(xdr);
Assert.AreEqual(100L, xdr.Body.ManageBuyOfferOp.BuyAmount.InnerValue);
Assert.IsTrue(parsedOperation.Selling is AssetTypeNative);
Assert.IsTrue(parsedOperation.Buying is AssetTypeCreditAlphaNum4);
Assert.IsTrue(parsedOperation.Buying.Equals(buying));
Assert.AreEqual(amount, parsedOperation.BuyAmount);
Assert.AreEqual(price, parsedOperation.Price);
Assert.AreEqual(priceObj.Numerator, 5333399);
Assert.AreEqual(priceObj.Denominator, 6250000);
Assert.AreEqual(offerId, parsedOperation.OfferId);
Assert.AreEqual(OperationThreshold.Medium, parsedOperation.Threshold);
Assert.AreEqual(
"AAAAAQAAAAC7JAuE3XvquOnbsgv2SRztjuk4RoBVefQ0rlrFMMQvfAAAAAwAAAAAAAAAAVVTRAAAAAAARP7bVZfAS1dHLFv8YF7W1zlX9ZTMg5bjImn5dCA1RSIAAAAAAAAAZABRYZcAX14QAAAAAAAAAAE=",
operation.ToXdrBase64());
}
[TestMethod]
public void TestCreatePassiveOfferOperation()
{
// GC5SIC4E3V56VOHJ3OZAX5SJDTWY52JYI2AFK6PUGSXFVRJQYQXXZBZF
var source = KeyPair.FromSecretSeed("SC4CGETADVYTCR5HEAVZRB3DZQY5Y4J7RFNJTRA6ESMHIPEZUSTE2QDK");
// GBCP5W2VS7AEWV2HFRN7YYC623LTSV7VSTGIHFXDEJU7S5BAGVCSETRR
var issuer = KeyPair.FromSecretSeed("SA64U7C5C7BS5IHWEPA7YWFN3Z6FE5L6KAMYUIT4AQ7KVTVLD23C6HEZ");
Asset selling = new AssetTypeNative();
var buying = Asset.CreateNonNativeAsset("USD", issuer.AccountId);
var amount = "0.001";
var price = "2.93850088"; // n=36731261 d=12500000
var priceObj = Price.FromString(price);
var operation = new CreatePassiveOfferOperation.Builder(selling, buying, amount, price)
.SetSourceAccount(source)
.Build();
Assert.AreEqual(
"AAAAAQAAAAC7JAuE3XvquOnbsgv2SRztjuk4RoBVefQ0rlrFMMQvfAAAAAQAAAAAAAAAAVVTRAAAAAAARP7bVZfAS1dHLFv8YF7W1zlX9ZTMg5bjImn5dCA1RSIAAAAAAAAAZAIweX0Avrwg",
operation.ToXdrBase64());
}
[TestMethod]
public void TestCreatePassiveSellOfferOperation()
{
// GC5SIC4E3V56VOHJ3OZAX5SJDTWY52JYI2AFK6PUGSXFVRJQYQXXZBZF
var source = KeyPair.FromSecretSeed("SC4CGETADVYTCR5HEAVZRB3DZQY5Y4J7RFNJTRA6ESMHIPEZUSTE2QDK");
// GBCP5W2VS7AEWV2HFRN7YYC623LTSV7VSTGIHFXDEJU7S5BAGVCSETRR
var issuer = KeyPair.FromSecretSeed("SA64U7C5C7BS5IHWEPA7YWFN3Z6FE5L6KAMYUIT4AQ7KVTVLD23C6HEZ");
Asset selling = new AssetTypeNative();
var buying = Asset.CreateNonNativeAsset("USD", issuer.AccountId);
var amount = "0.001";
var price = "2.93850088"; // n=36731261 d=12500000
var priceObj = Price.FromString(price);
var operation = new CreatePassiveSellOfferOperation.Builder(selling, buying, amount, price)
.SetSourceAccount(source)
.Build();
var xdr = operation.ToXdr();
var parsedOperation = (CreatePassiveSellOfferOperation) Operation.FromXdr(xdr);
Assert.AreEqual(100L, xdr.Body.CreatePassiveSellOfferOp.Amount.InnerValue);
Assert.IsTrue(parsedOperation.Selling is AssetTypeNative);
Assert.IsTrue(parsedOperation.Buying is AssetTypeCreditAlphaNum4);
Assert.IsTrue(parsedOperation.Buying.Equals(buying));
Assert.AreEqual(amount, parsedOperation.Amount);
Assert.AreEqual(price, parsedOperation.Price);
Assert.AreEqual(priceObj.Numerator, 36731261);
Assert.AreEqual(priceObj.Denominator, 12500000);
Assert.AreEqual(OperationThreshold.Medium, parsedOperation.Threshold);
Assert.AreEqual(
"AAAAAQAAAAC7JAuE3XvquOnbsgv2SRztjuk4RoBVefQ0rlrFMMQvfAAAAAQAAAAAAAAAAVVTRAAAAAAARP7bVZfAS1dHLFv8YF7W1zlX9ZTMg5bjImn5dCA1RSIAAAAAAAAAZAIweX0Avrwg",
operation.ToXdrBase64());
}
[TestMethod]
public void TestAccountMergeOperation()
{
// GC5SIC4E3V56VOHJ3OZAX5SJDTWY52JYI2AFK6PUGSXFVRJQYQXXZBZF
var source = KeyPair.FromSecretSeed("SC4CGETADVYTCR5HEAVZRB3DZQY5Y4J7RFNJTRA6ESMHIPEZUSTE2QDK");
// GDW6AUTBXTOC7FIKUO5BOO3OGLK4SF7ZPOBLMQHMZDI45J2Z6VXRB5NR
var destination = KeyPair.FromSecretSeed("SDHZGHURAYXKU2KMVHPOXI6JG2Q4BSQUQCEOY72O3QQTCLR2T455PMII");
var operation = new AccountMergeOperation.Builder(destination)
.SetSourceAccount(source)
.Build();
var xdr = operation.ToXdr();
var parsedOperation = (AccountMergeOperation) Operation.FromXdr(xdr);
Assert.AreEqual(destination.AccountId, parsedOperation.Destination.AccountId);
Assert.AreEqual(OperationThreshold.High, parsedOperation.Threshold);
Assert.AreEqual(
"AAAAAQAAAAC7JAuE3XvquOnbsgv2SRztjuk4RoBVefQ0rlrFMMQvfAAAAAgAAAAA7eBSYbzcL5UKo7oXO24y1ckX+XuCtkDsyNHOp1n1bxA=",
operation.ToXdrBase64());
}
[TestMethod]
public void TestManageDataOperation()
{
// GC5SIC4E3V56VOHJ3OZAX5SJDTWY52JYI2AFK6PUGSXFVRJQYQXXZBZF
var source = KeyPair.FromSecretSeed("SC4CGETADVYTCR5HEAVZRB3DZQY5Y4J7RFNJTRA6ESMHIPEZUSTE2QDK");
var operation = new ManageDataOperation.Builder("test", new byte[] {0, 1, 2, 3, 4})
.SetSourceAccount(source)
.Build();
var xdr = operation.ToXdr();
var parsedOperation = (ManageDataOperation) Operation.FromXdr(xdr);
Assert.AreEqual("test", parsedOperation.Name);
Assert.IsTrue(new byte[] {0, 1, 2, 3, 4}.SequenceEqual(parsedOperation.Value));
Assert.AreEqual(OperationThreshold.Medium, parsedOperation.Threshold);
Assert.AreEqual(
"AAAAAQAAAAC7JAuE3XvquOnbsgv2SRztjuk4RoBVefQ0rlrFMMQvfAAAAAoAAAAEdGVzdAAAAAEAAAAFAAECAwQAAAA=",
operation.ToXdrBase64());
}
[TestMethod]
public void TestManageDataOperationEmptyValue()
{
// GC5SIC4E3V56VOHJ3OZAX5SJDTWY52JYI2AFK6PUGSXFVRJQYQXXZBZF
var source = KeyPair.FromSecretSeed("SC4CGETADVYTCR5HEAVZRB3DZQY5Y4J7RFNJTRA6ESMHIPEZUSTE2QDK");
var operation = new ManageDataOperation.Builder("test", null)
.SetSourceAccount(source)
.Build();
var xdr = operation.ToXdr();
var parsedOperation = (ManageDataOperation) Operation.FromXdr(xdr);
Assert.AreEqual("test", parsedOperation.Name);
Assert.AreEqual(null, parsedOperation.Value);
Assert.AreEqual("AAAAAQAAAAC7JAuE3XvquOnbsgv2SRztjuk4RoBVefQ0rlrFMMQvfAAAAAoAAAAEdGVzdAAAAAA=",
operation.ToXdrBase64());
}
[TestMethod]
public void TestToXdrAmount()
{
Assert.AreEqual(0L, Operation.ToXdrAmount("0"));
Assert.AreEqual(1L, Operation.ToXdrAmount("0.00001"));
Assert.AreEqual(10000000L, Operation.ToXdrAmount("100"));
Assert.AreEqual(11234567L, Operation.ToXdrAmount("112.34567"));
Assert.AreEqual(729912843007381L, Operation.ToXdrAmount("7299128430.07381"));
Assert.AreEqual(729912843007381L, Operation.ToXdrAmount("7299128430.073810"));
Assert.AreEqual(1014016711446800155L, Operation.ToXdrAmount("10140167114468.00155"));
Assert.AreEqual(9223372036854775807L, Operation.ToXdrAmount("92233720368547.75807"));
try
{
Operation.ToXdrAmount("0.000001");
Assert.Fail();
}
catch (ArithmeticException)
{
}
catch (Exception)
{
Assert.Fail();
}
try
{
Operation.ToXdrAmount("7299128430.073811");
Assert.Fail();
}
catch (ArithmeticException)
{
}
catch (Exception)
{
Assert.Fail();
}
}
[TestMethod]
public void TestBumpSequence()
{
// GC5SIC4E3V56VOHJ3OZAX5SJDTWY52JYI2AFK6PUGSXFVRJQYQXXZBZF
var source = KeyPair.FromSecretSeed("SC4CGETADVYTCR5HEAVZRB3DZQY5Y4J7RFNJTRA6ESMHIPEZUSTE2QDK");
var operation = new BumpSequenceOperation.Builder(156L)
.SetSourceAccount(source)
.Build();
var xdr = operation.ToXdr();
var parsedOperation = (BumpSequenceOperation) Operation.FromXdr(xdr);
Assert.AreEqual(156L, parsedOperation.BumpTo);
Assert.AreEqual(OperationThreshold.Low, parsedOperation.Threshold);
Assert.AreEqual("AAAAAQAAAAC7JAuE3XvquOnbsgv2SRztjuk4RoBVefQ0rlrFMMQvfAAAAAsAAAAAAAAAnA==", operation.ToXdrBase64());
}
[TestMethod]
public void TestInflationOperation()
{
// GC5SIC4E3V56VOHJ3OZAX5SJDTWY52JYI2AFK6PUGSXFVRJQYQXXZBZF
var source = KeyPair.FromSecretSeed("SC4CGETADVYTCR5HEAVZRB3DZQY5Y4J7RFNJTRA6ESMHIPEZUSTE2QDK");
var operation = new InflationOperation.Builder()
.SetSourceAccount(source)
.Build();
var xdr = operation.ToXdr();
var parsedOperation = (InflationOperation) Operation.FromXdr(xdr);
Assert.AreEqual(operation.SourceAccount.AccountId, parsedOperation.SourceAccount.AccountId);
Assert.AreEqual("AAAAAQAAAAC7JAuE3XvquOnbsgv2SRztjuk4RoBVefQ0rlrFMMQvfAAAAAk=", operation.ToXdrBase64());
}
[TestMethod]
public void TestFromXdrAmount()
{
Assert.AreEqual("0", Operation.FromXdrAmount(0L));
Assert.AreEqual("0.00001", Operation.FromXdrAmount(1L));
Assert.AreEqual("100", Operation.FromXdrAmount(10000000L));
Assert.AreEqual("112.34567", Operation.FromXdrAmount(11234567L));
Assert.AreEqual("7299128430.07381", Operation.FromXdrAmount(729912843007381L));
Assert.AreEqual("10140167114468.00155", Operation.FromXdrAmount(1014016711446800155L));
Assert.AreEqual("92233720368547.75807", Operation.FromXdrAmount(9223372036854775807L));
}
}
}
| 49.515625 | 347 | 0.680484 | [
"Apache-2.0"
] | kinecosystem/dotnet-stellar-sdk | kin-base-test/OperationTest.cs | 34,859 | 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/credentialprovider.h in the Windows SDK for Windows 10.0.22000.0
// Original source is Copyright © Microsoft. All rights reserved.
namespace TerraFX.Interop.Windows;
/// <include file='CREDENTIAL_PROVIDER_FIELD_INTERACTIVE_STATE.xml' path='doc/member[@name="CREDENTIAL_PROVIDER_FIELD_INTERACTIVE_STATE"]/*' />
public enum CREDENTIAL_PROVIDER_FIELD_INTERACTIVE_STATE
{
/// <include file='CREDENTIAL_PROVIDER_FIELD_INTERACTIVE_STATE.xml' path='doc/member[@name="CREDENTIAL_PROVIDER_FIELD_INTERACTIVE_STATE.CPFIS_NONE"]/*' />
CPFIS_NONE = 0,
/// <include file='CREDENTIAL_PROVIDER_FIELD_INTERACTIVE_STATE.xml' path='doc/member[@name="CREDENTIAL_PROVIDER_FIELD_INTERACTIVE_STATE.CPFIS_READONLY"]/*' />
CPFIS_READONLY = (CPFIS_NONE + 1),
/// <include file='CREDENTIAL_PROVIDER_FIELD_INTERACTIVE_STATE.xml' path='doc/member[@name="CREDENTIAL_PROVIDER_FIELD_INTERACTIVE_STATE.CPFIS_DISABLED"]/*' />
CPFIS_DISABLED = (CPFIS_READONLY + 1),
/// <include file='CREDENTIAL_PROVIDER_FIELD_INTERACTIVE_STATE.xml' path='doc/member[@name="CREDENTIAL_PROVIDER_FIELD_INTERACTIVE_STATE.CPFIS_FOCUSED"]/*' />
CPFIS_FOCUSED = (CPFIS_DISABLED + 1),
}
| 57.869565 | 162 | 0.783621 | [
"MIT"
] | reflectronic/terrafx.interop.windows | sources/Interop/Windows/Windows/um/credentialprovider/CREDENTIAL_PROVIDER_FIELD_INTERACTIVE_STATE.cs | 1,333 | C# |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* 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.Collections.Generic;
using Aliyun.Acs.Core;
using Aliyun.Acs.Core.Http;
using Aliyun.Acs.Core.Transform;
using Aliyun.Acs.Core.Utils;
using Aliyun.Acs.Alidns.Transform;
using Aliyun.Acs.Alidns.Transform.V20150109;
namespace Aliyun.Acs.Alidns.Model.V20150109
{
public class DeleteGtmAddressPoolRequest : RpcAcsRequest<DeleteGtmAddressPoolResponse>
{
public DeleteGtmAddressPoolRequest()
: base("Alidns", "2015-01-09", "DeleteGtmAddressPool", "alidns", "openAPI")
{
}
private string addrPoolId;
private string userClientIp;
private string lang;
public string AddrPoolId
{
get
{
return addrPoolId;
}
set
{
addrPoolId = value;
DictionaryUtil.Add(QueryParameters, "AddrPoolId", value);
}
}
public string UserClientIp
{
get
{
return userClientIp;
}
set
{
userClientIp = value;
DictionaryUtil.Add(QueryParameters, "UserClientIp", value);
}
}
public string Lang
{
get
{
return lang;
}
set
{
lang = value;
DictionaryUtil.Add(QueryParameters, "Lang", value);
}
}
public override DeleteGtmAddressPoolResponse GetResponse(UnmarshallerContext unmarshallerContext)
{
return DeleteGtmAddressPoolResponseUnmarshaller.Unmarshall(unmarshallerContext);
}
}
}
| 25.204545 | 105 | 0.688458 | [
"Apache-2.0"
] | fossabot/aliyun-openapi-net-sdk | aliyun-net-sdk-alidns/Alidns/Model/V20150109/DeleteGtmAddressPoolRequest.cs | 2,218 | C# |
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Hosting;
using SFA.DAS.NServiceBus.AzureFunction.Hosting;
using SFA.DAS.NServiceBus.AzureFunctionExample;
[assembly: WebJobsStartup(typeof(Startup))]
namespace SFA.DAS.NServiceBus.AzureFunctionExample
{
public class Startup :IWebJobsStartup
{
public void Configure(IWebJobsBuilder builder)
{
//Environment variables need creating for
// NServiceBusConnectionString
// NServiceBusLicense
builder.AddExecutionContextBinding();
builder.AddExtension<NServiceBusExtensionConfigProvider>();
}
}
}
| 31.428571 | 71 | 0.70303 | [
"MIT"
] | SkillsFundingAgency/das-shared-packages | SFA.DAS.NServiceBus/SFA.DAS.NServiceBus.AzureFunctionExample/Startup.cs | 662 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NEXCORE.Common.Data;
namespace NEXCORE.Interfaces
{
public interface IMenuRepository
{
void LoadMenu();
IList<Menu> GetMenus();
IList<Menu> GetMyMenuList(string userId);
void AddMenu(Menu menu);
void UpdateMenu(Menu menu);
void DeleteMenu(Menu menu);
void AddMyMenu(Menu menu);
void ModifyMyMenu(Menu menu);
void UpdateMyMenu(Menu menu);
void DeleteMyMenu(Menu menu);
}
}
| 18.258065 | 49 | 0.64841 | [
"MIT"
] | hsi79/SK.WMS | 10.NEXCORE Framework/NEXCORE.Interfaces/Menu Manager/IMenuRepository.cs | 568 | C# |
// DragonFruit Link Copyright (C) DragonFruit Network <inbox@dragonfruit.network>
// Licensed under MIT. Please refer to the LICENCE file for more info
using System;
using Newtonsoft.Json;
namespace DragonFruit.Link.Store.Objects
{
public class SteamFeaturedAppListing
{
[JsonProperty("id")]
public uint Id { get; set; }
//todo is this the same as the ListingType enum?
[JsonProperty("type")]
public uint Type { get; set; }
[JsonProperty("name")]
public string Name { get; set; }
#region Price & Discounts
[JsonProperty("discounted")]
public bool IsDiscounted { get; set; }
[JsonProperty("discount_percent")]
public uint? DiscountPercent { get; set; }
[JsonProperty("original_price")]
public uint? OriginalPrice { get; set; }
[JsonProperty("final_price")]
public uint CurrentPrice { get; set; }
[JsonProperty("currency")]
public string Currency { get; set; }
#endregion
#region Images
[JsonProperty("large_capsule_image")]
public string LargeImage { get; set; }
[JsonProperty("small_capsule_image")]
public string SmallImage { get; set; }
[JsonProperty("header_image")]
public string HeaderImage { get; set; }
#endregion
#region Platforms
[JsonProperty("windows_available")]
public bool IsOnWindows { get; set; }
[JsonProperty("linux_available")]
public bool IsOnLinux { get; set; }
[JsonProperty("mac_available")]
public bool IsOnMac { get; set; }
#endregion
[JsonProperty("streamingvideo_available")]
public bool VideoStreamAvailable { get; set; }
[JsonProperty("discount_expiration")]
public long DiscountExpirationEpoch { get; set; }
[JsonIgnore]
public DateTimeOffset DiscountExpiration => DateTimeOffset.FromUnixTimeSeconds(DiscountExpirationEpoch);
}
}
| 26.644737 | 112 | 0.627654 | [
"MIT"
] | dragonfruitnetwork/Link | DragonFruit.Link/Store/Objects/SteamFeaturedAppListing.cs | 2,027 | C# |
using Discord;
using Discord.Commands;
using Discord.Commands.Permissions.Levels;
using Discord.Modules;
using Discord.Net;
using DiscordBot.Services;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
namespace DiscordBot.Modules.Github
{
internal class GithubModule : IModule
{
private ModuleManager _manager;
private DiscordClient _client;
private bool _isRunning;
private HttpService _http;
private SettingsManager<Settings> _settings;
void IModule.Install(ModuleManager manager)
{
_manager = manager;
_client = manager.Client;
_http = _client.GetService<HttpService>();
_settings = _client.GetService<SettingsService>()
.AddModule<GithubModule, Settings>(manager);
manager.CreateCommands("repos", group =>
{
group.MinPermissions((int)PermissionLevel.BotOwner);
group.CreateCommand("list")
.Do(async e =>
{
StringBuilder builder = new StringBuilder();
var settings = _settings.Load(e.Server);
foreach (var repo in settings.Repos.OrderBy(x => x.Key))
builder.AppendLine($"{repo.Key} [{string.Join(",", repo.Value.Branches)}] => {_client.GetChannel(repo.Value.ChannelId)?.Name ?? "Unknown"}");
await _client.Reply(e, "Linked Repos", builder.ToString());
});
group.CreateCommand("add")
.Parameter("githubrepo")
.Parameter("channel", ParameterType.Optional)
.Do(async e =>
{
var settings = _settings.Load(e.Server);
Channel channel;
if (e.Args[1] != "")
channel = await _client.FindChannel(e, e.Args[1], ChannelType.Text);
else
channel = e.Channel;
if (channel == null) return;
string url = FilterUrl(e.Args[0]);
if (settings.AddRepo(url, channel.Id))
{
await _settings.Save(e.Server.Id, settings);
await _client.Reply(e, $"Linked repo {url} to {channel.Name}.");
}
else
await _client.Reply(e, $"Error: Repo {url} is already being watched.");
});
group.CreateCommand("remove")
.Parameter("githubrepo")
.Do(async e =>
{
var settings = _settings.Load(e.Server);
string url = FilterUrl(e.Args[0]);
if (settings.RemoveRepo(url))
{
await _settings.Save(e.Server.Id, settings);
await _client.Reply(e, $"Unlinked repo {url}.");
}
else
await _client.Reply(e, $"Error: Repo {url} is not currently being watched.");
});
group.CreateCommand("addbranch")
.Parameter("githubrepo")
.Parameter("branch")
.Do(async e =>
{
var settings = _settings.Load(e.Server);
string url = FilterUrl(e.Args[0]);
var repo = settings.Repos[url];
if (repo != null)
{
if (repo.AddBranch(e.Args[1]))
{
await _settings.Save(e.Server.Id, settings);
await _client.Reply(e, $"Added branch {url}/{e.Args[1]}.");
}
else
await _client.Reply(e, $"Error: Branch {url}/{e.Args[1]} is already being watched.");
}
else
await _client.Reply(e, $"Error: Repo {url} is not currently being watched.");
});
group.CreateCommand("removebranch")
.Parameter("githubrepo")
.Parameter("branch")
.Do(async e =>
{
var settings = _settings.Load(e.Server);
string url = FilterUrl(e.Args[0]);
var repo = settings.Repos[url];
if (repo != null)
{
if (repo.RemoveBranch(e.Args[1]))
{
await _settings.Save(e.Server.Id, settings);
await _client.Reply(e, $"Removed branch {url}/{e.Args[1]}.");
}
else
await _client.Reply(e, $"Error: Branch {url}/{e.Args[1]} is not being watched.");
}
else
await _client.Reply(e, $"Error: Repo {url} is not currently being watched.");
});
});
_client.Ready += (s, e) =>
{
if (!_isRunning)
{
Task.Run(Run);
_isRunning = true;
}
};
}
public async Task Run()
{
try
{
var cancelToken = _client.CancelToken;
StringBuilder builder = new StringBuilder();
while (!_client.CancelToken.IsCancellationRequested)
{
foreach (var settings in _settings.AllServers)
{
foreach (var repo in settings.Value.Repos)
{
try
{
var channel = _client.GetChannel(repo.Value.ChannelId);
if (channel != null && channel.Server.CurrentUser.GetPermissions(channel).SendMessages)
{
bool dateChanged = false;
var since = repo.Value.LastUpdate.UtcDateTime.ToString("yyyy-MM-ddTHH:mm:ssZ");
DateTimeOffset newDate = repo.Value.LastUpdate;
string repoAuthor = repo.Key.Split('/')[0];
HttpContent content;
string response;
JToken json;
foreach (var branch in repo.Value.Branches)
{
try
{
content = await _http.Send(
HttpMethod.Get,
$"https://api.github.com/repos/{repo.Key}/commits?sha={branch}&since={since}",
authToken: GlobalSettings.Github.Token);
}
catch (HttpException ex) when (ex.StatusCode == HttpStatusCode.Forbidden || ex.StatusCode == HttpStatusCode.NotFound)
{
_client.Log.Warning("Github", $"Unable to access {repo.Key}'s {branch} branch.");
continue;
}
response = await content.ReadAsStringAsync();
json = JsonConvert.DeserializeObject(response) as JToken;
if (json.Children().Any())
{
builder.Clear();
builder.Append($"{Format.Bold(repo.Key)}");
if (branch != "master")
builder.Append($" ({Format.Bold(branch)})");
foreach (var commit in json.Children().Reverse())
{
var sha = commit.Value<string>("sha")?.Substring(0, 7);
var msg = commit["commit"].Value<string>("message");
var date = new DateTimeOffset(commit["commit"]["committer"].Value<DateTime>("date").AddSeconds(1.0), TimeSpan.Zero);
var author = commit["commit"]["committer"].Value<string>("name");
//var url = commit.Value<string>("html_url");
_client.Log.Info("Github", $"{repo.Key} {branch} #{sha}");
string prefix = $"\n{Format.Code(sha)} ";
builder.Append($"{prefix}{Format.Escape(msg.Split('\n')[0])} [{author}]");
//builder.Append($"{prefix}{url}");
if (date > newDate)
{
newDate = date;
dateChanged = true;
}
}
try
{
await channel.SendMessage(builder.ToString());
}
catch (HttpException ex) when (ex.StatusCode == HttpStatusCode.Forbidden || ex.StatusCode == HttpStatusCode.NotFound) { }
}
await Task.Delay(1000, cancelToken);
}
try
{
content = await _http.Send(
HttpMethod.Get,
$"https://api.github.com/repos/{repo.Key}/issues?state=all&sort=updated&since={since}",
authToken: GlobalSettings.Github.Token);
}
catch
{
_client.Log.Warning("Github", $"Unable to access {repo.Key}'s issues.");
continue;
}
response = await content.ReadAsStringAsync();
json = JsonConvert.DeserializeObject(response) as JToken;
foreach (var issue in json.Children().Reverse())
{
var author = issue["user"].Value<string>("login");
var id = issue.Value<string>("number");
var url = issue.Value<string>("html_url");
var createdAt = issue.Value<DateTime>("created_at");
var updatedAt = issue.Value<DateTime>("updated_at");
var closedAt = issue.Value<DateTime?>("closed_at");
var title = issue.Value<string>("title");
string text;
bool skip = false;
string type = (issue.Value<JToken>("pull_request") != null) ? "Pull Request" : "Issue";
if (author.Equals(repoAuthor, StringComparison.OrdinalIgnoreCase))
skip = true;
if (updatedAt == closedAt)
text = $"Closed {type} #{id}";
else if (createdAt == updatedAt)
text = $"New {type} #{id}";
else
{
skip = true;
text = $"Updated {type} #{id}";
}
_client.Log.Info("Github", $"{repo.Key} {text}");
if (!string.IsNullOrEmpty(title))
text += '\n' + title;
if (!skip)
{
try
{
await channel.SendMessage($"{Format.Bold(repo.Key)} {text}\n{Format.Escape(url)}");
}
catch (HttpException ex) when (ex.StatusCode == HttpStatusCode.Forbidden || ex.StatusCode == HttpStatusCode.NotFound) { }
}
var date = new DateTimeOffset(updatedAt.AddSeconds(1.0), TimeSpan.Zero);
if (date > newDate)
{
newDate = date;
dateChanged = true;
}
}
if (dateChanged)
{
repo.Value.LastUpdate = newDate;
await _settings.Save(settings);
}
}
}
catch (Exception ex) when (!(ex is TaskCanceledException))
{
_client.Log.Error("Github", ex);
await Task.Delay(5000);
continue;
}
await Task.Delay(1000, cancelToken); //Wait 1 second between individual requests
}
}
await Task.Delay(60000, cancelToken); //Wait 1 minute between full updates
}
}
catch (TaskCanceledException) { }
}
private static string FilterUrl(string url)
{
if (url.StartsWith("http://github.com/"))
url = url.Substring("http://github.com/".Length);
else if (url.StartsWith("https://github.com/"))
url = url.Substring("https://github.com/".Length);
if (url.EndsWith("/"))
url = url.Substring(0, url.Length - 1);
return url.Trim();
}
}
}
| 44.860317 | 165 | 0.408181 | [
"MIT"
] | Asian-Demon-Blast/DemoBot | src/DiscordBot/Modules/Github/GithubModule.cs | 14,133 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.