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.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("DuplicateFilesManager.Core")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("DuplicateFilesManager.Core")]
[assembly: AssemblyCopyright("Copyright © 2020")]
[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("91f53377-4736-4e27-a461-ccbc79990a7d")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 38.378378 | 84 | 0.751408 | [
"CC0-1.0"
] | shreeharshas/DuplicateFilesRemover | DuplicateFilesManager.Core/Properties/AssemblyInfo.cs | 1,423 | C# |
using System.Collections.Generic;
namespace Yorozu.UI
{
public static class YorozuButtonManager
{
private static List<YorozuButton> _activeButtons = new List<YorozuButton>(20);
public static IEnumerable<YorozuButton> Buttons => _activeButtons;
private static float _clickLockTime = 0.5f;
/// <summary>
/// 最後にクリックした時間
/// </summary>
private static float _lastClickTime = 0f;
/// <summary>
/// 最後にクリックしてから一定時間経過しているか
/// </summary>
internal static bool Clickable => UnityEngine.Time.realtimeSinceStartup - _lastClickTime > _clickLockTime;
internal static void Register(YorozuButton button)
{
if (_activeButtons.Contains(button))
return;
_activeButtons.Add(button);
}
internal static void Unregister(YorozuButton button)
{
if (!_activeButtons.Contains(button))
return;
_activeButtons.Remove(button);
}
internal static void ClickRegister()
{
_lastClickTime = UnityEngine.Time.realtimeSinceStartup;
}
/// <summary>
/// 連続クリック時間を更新
/// </summary>
public static void SetClickLockTime(float time)
{
_clickLockTime = time;
}
}
}
| 21 | 108 | 0.716083 | [
"MIT"
] | yayorozu/UnityUIButton | Script/YorozuButtonManager.cs | 1,201 | C# |
using System;
using HotChocolate.Language;
using HotChocolate.Properties;
#nullable enable
namespace HotChocolate.Types
{
public abstract class FloatTypeBase<TRuntimeType>
: ScalarType<TRuntimeType>
where TRuntimeType : IComparable
{
protected FloatTypeBase(
NameString name,
TRuntimeType min,
TRuntimeType max,
BindingBehavior bind = BindingBehavior.Explicit)
: base(name, bind)
{
MinValue = min;
MaxValue = max;
}
public TRuntimeType MinValue { get; }
public TRuntimeType MaxValue { get; }
public override bool IsInstanceOfType(IValueNode valueSyntax)
{
if (valueSyntax is null)
{
throw new ArgumentNullException(nameof(valueSyntax));
}
if (valueSyntax is NullValueNode)
{
return true;
}
if (valueSyntax is FloatValueNode floatLiteral && IsInstanceOfType(floatLiteral))
{
return true;
}
// Input coercion rules specify that float values can be coerced
// from IntValueNode and FloatValueNode:
// http://facebook.github.io/graphql/June2018/#sec-Float
if (valueSyntax is IntValueNode intLiteral && IsInstanceOfType(intLiteral))
{
return true;
}
return false;
}
protected virtual bool IsInstanceOfType(IFloatValueLiteral valueSyntax)
{
return IsInstanceOfType(ParseLiteral(valueSyntax));
}
protected virtual bool IsInstanceOfType(TRuntimeType value)
{
if (value.CompareTo(MinValue) == -1 || value.CompareTo(MaxValue) == 1)
{
return false;
}
return true;
}
public override object? ParseLiteral(IValueNode valueSyntax, bool withDefaults = true)
{
if (valueSyntax is null)
{
throw new ArgumentNullException(nameof(valueSyntax));
}
if (valueSyntax is NullValueNode)
{
return null;
}
if (valueSyntax is FloatValueNode floatLiteral)
{
return ParseLiteral(floatLiteral);
}
// Input coercion rules specify that float values can be coerced
// from IntValueNode and FloatValueNode:
// http://facebook.github.io/graphql/June2018/#sec-Float
if (valueSyntax is IntValueNode intLiteral)
{
return ParseLiteral(intLiteral);
}
throw new SerializationException(
TypeResourceHelper.Scalar_Cannot_ParseLiteral(Name, valueSyntax.GetType()),
this);
}
protected abstract TRuntimeType ParseLiteral(IFloatValueLiteral valueSyntax);
public override IValueNode ParseValue(object? runtimeValue)
{
if (runtimeValue is null)
{
return NullValueNode.Default;
}
if (runtimeValue is TRuntimeType casted && IsInstanceOfType(casted))
{
return ParseValue(casted);
}
throw new SerializationException(
TypeResourceHelper.Scalar_Cannot_ParseValue(Name, runtimeValue.GetType()),
this);
}
protected abstract FloatValueNode ParseValue(TRuntimeType runtimeValue);
public sealed override IValueNode ParseResult(object? resultValue)
{
if (resultValue is null)
{
return NullValueNode.Default;
}
if (resultValue is TRuntimeType casted && IsInstanceOfType(casted))
{
return ParseValue(casted);
}
if (TryConvertSerialized(resultValue, ValueKind.Integer, out TRuntimeType c)
&& IsInstanceOfType(c))
{
return ParseValue(c);
}
throw new SerializationException(
TypeResourceHelper.Scalar_Cannot_ParseResult(Name, resultValue.GetType()),
this);
}
public override bool TrySerialize(object? runtimeValue, out object? resultValue)
{
if (runtimeValue is null)
{
resultValue = null;
return true;
}
if (runtimeValue is TRuntimeType casted && IsInstanceOfType(casted))
{
resultValue = runtimeValue;
return true;
}
resultValue = null;
return false;
}
public override bool TryDeserialize(object? resultValue, out object? runtimeValue)
{
if (resultValue is null)
{
runtimeValue = null;
return true;
}
if (resultValue is TRuntimeType casted && IsInstanceOfType(casted))
{
runtimeValue = resultValue;
return true;
}
if ((TryConvertSerialized(resultValue, ValueKind.Float, out TRuntimeType c)
|| TryConvertSerialized(resultValue, ValueKind.Integer, out c))
&& IsInstanceOfType(c))
{
runtimeValue = c;
return true;
}
runtimeValue = null;
return false;
}
}
}
| 29.230366 | 94 | 0.54057 | [
"MIT"
] | Asshiah/hotchocolate | src/HotChocolate/Core/src/Types/Types/Scalars/FloatTypeBase.cs | 5,583 | C# |
using System;
using System.Collections.Generic;
using System.Reflection;
namespace ILRuntime.Runtime.Generated
{
class CLRBindings
{
//will auto register in unity
#if UNITY_5_3_OR_NEWER
[UnityEngine.RuntimeInitializeOnLoadMethod(UnityEngine.RuntimeInitializeLoadType.BeforeSceneLoad)]
#endif
static private void RegisterBindingAction()
{
ILRuntime.Runtime.CLRBinding.CLRBindingUtils.RegisterBindingAction(Initialize);
}
internal static ILRuntime.Runtime.Enviorment.ValueTypeBinder<ILRuntimeTest.TestFramework.TestVector3> s_ILRuntimeTest_TestFramework_TestVector3_Binding_Binder = null;
internal static ILRuntime.Runtime.Enviorment.ValueTypeBinder<ILRuntimeTest.TestFramework.TestVectorStruct> s_ILRuntimeTest_TestFramework_TestVectorStruct_Binding_Binder = null;
internal static ILRuntime.Runtime.Enviorment.ValueTypeBinder<ILRuntimeTest.TestFramework.TestVectorStruct2> s_ILRuntimeTest_TestFramework_TestVectorStruct2_Binding_Binder = null;
internal static ILRuntime.Runtime.Enviorment.ValueTypeBinder<System.Collections.Generic.KeyValuePair<System.UInt32, ILRuntime.Runtime.Intepreter.ILTypeInstance>> s_System_Collections_Generic_KeyValuePair_2_UInt32_ILTypeInstance_Binding_Binder = null;
/// <summary>
/// Initialize the CLR binding, please invoke this AFTER CLR Redirection registration
/// </summary>
public static void Initialize(ILRuntime.Runtime.Enviorment.AppDomain app)
{
System_Object_Binding.Register(app);
System_String_Binding.Register(app);
System_Collections_Generic_EqualityComparer_1_Int32_Binding.Register(app);
System_Collections_Generic_EqualityComparer_1_Single_Binding.Register(app);
System_Collections_Generic_EqualityComparer_1_String_Binding.Register(app);
System_Collections_Generic_EqualityComparer_1_ILTypeInstance_Binding.Register(app);
System_Activator_Binding.Register(app);
System_Int32_Binding.Register(app);
System_Exception_Binding.Register(app);
System_Console_Binding.Register(app);
System_Single_Binding.Register(app);
System_Type_Binding.Register(app);
System_Math_Binding.Register(app);
System_Runtime_CompilerServices_AsyncTaskMethodBuilder_Binding.Register(app);
System_Runtime_CompilerServices_AsyncTaskMethodBuilder_1_Int32_Binding.Register(app);
System_Runtime_CompilerServices_AsyncVoidMethodBuilder_Binding.Register(app);
System_Threading_Tasks_Task_Binding.Register(app);
System_Runtime_CompilerServices_TaskAwaiter_Binding.Register(app);
System_Threading_Tasks_Task_1_Int32_Binding.Register(app);
System_Runtime_CompilerServices_TaskAwaiter_1_Int32_Binding.Register(app);
System_Collections_IDictionary_Binding.Register(app);
System_Byte_Binding.Register(app);
ILRuntimeTest_TestFramework_TestClass3_Binding.Register(app);
System_Int32_Array_Binding.Register(app);
ILRuntimeTest_TestBase_StaticGenericMethods_Binding.Register(app);
System_Int32_Array_Binding_Array_Binding.Register(app);
System_Collections_Generic_List_1_Int32_Binding.Register(app);
System_Linq_Enumerable_Binding.Register(app);
System_Collections_Generic_List_1_Dictionary_2_String_Object_Binding.Register(app);
System_Collections_Generic_Dictionary_2_String_Object_Binding.Register(app);
ILRuntimeTest_TestFramework_ClassInheritanceTest_Binding.Register(app);
System_Object_Array_Binding.Register(app);
System_Action_1_Int32_Binding.Register(app);
System_Collections_Generic_Dictionary_2_Int32_List_1_Int32_Binding.Register(app);
ILRuntimeTest_TestBase_ExtensionClass_Binding.Register(app);
ILRuntimeTest_TestBase_GenericExtensions_Binding.Register(app);
ILRuntimeTest_TestBase_ExtensionClass_1_Int32_Binding.Register(app);
ILRuntimeTest_TestBase_SubExtensionClass_Binding.Register(app);
ILRuntimeTest_TestBase_SubExtensionClass_1_Int32_Binding.Register(app);
System_ArgumentException_Binding.Register(app);
System_Action_1_ILTypeInstance_Binding.Register(app);
System_Array_Binding.Register(app);
System_Collections_Generic_Dictionary_2_Int32_ILTypeInstance_Binding.Register(app);
LitJson_JsonMapper_Binding.Register(app);
System_Collections_Generic_KeyValuePair_2_Int32_List_1_Int32_Binding.Register(app);
System_Collections_Generic_List_1_ILTypeInstance_Binding.Register(app);
System_Collections_Generic_Dictionary_2_String_ILTypeInstance_Binding.Register(app);
System_Collections_Generic_Dictionary_2_String_Int32_Binding.Register(app);
System_Collections_Generic_List_1_ILRuntimeTest_TestFramework_TestClass3Adaptor_Binding_Adaptor_Binding.Register(app);
System_Collections_Generic_List_1_String_Binding.Register(app);
System_Collections_Generic_Dictionary_2_Int32_List_1_String_Binding.Register(app);
System_Collections_Generic_List_1_String_Binding_Enumerator_Binding.Register(app);
System_IDisposable_Binding.Register(app);
System_Reflection_MethodBase_Binding.Register(app);
System_Reflection_MemberInfo_Binding.Register(app);
System_Reflection_FieldInfo_Binding.Register(app);
ILRuntimeTest_TestFramework_TestCLRAttribute_Binding.Register(app);
System_Reflection_PropertyInfo_Binding.Register(app);
ILRuntimeTest_TestMainForm_Binding.Register(app);
ILRuntime_Runtime_Enviorment_AppDomain_Binding.Register(app);
System_Collections_Generic_KeyValuePair_2_String_IType_Binding.Register(app);
ILRuntime_CLR_TypeSystem_IType_Binding.Register(app);
System_Boolean_Binding.Register(app);
System_Collections_Generic_List_1_ILRuntimeTest_TestFramework_ClassInheritanceTestAdaptor_Binding_Adaptor_Binding.Register(app);
ILRuntimeTest_TestFramework_ClassInheritanceTest2_1_ILRuntimeTest_TestFramework_ClassInheritanceTest2Adaptor_Binding_Adaptor_Binding.Register(app);
ILRuntimeTest_TestFramework_TestClass2_Binding.Register(app);
ILRuntimeTest_TestFramework_TestClass4_Binding.Register(app);
System_Collections_Generic_Dictionary_2_Int32_ILRuntimeTest_TestFramework_ClassInheritanceTestAdaptor_Binding_Adaptor_Binding.Register(app);
ILRuntimeTest_TestFramework_DelegateTest_Binding.Register(app);
ILRuntimeTest_TestFramework_IntDelegate_Binding.Register(app);
ILRuntimeTest_TestFramework_IntDelegate2_Binding.Register(app);
System_Func_2_Int32_Int32_Binding.Register(app);
System_Action_3_Int32_String_String_Binding.Register(app);
ILRuntimeTest_TestFramework_BaseClassTest_Binding.Register(app);
System_Action_1_String_Binding.Register(app);
System_Collections_Generic_List_1_Action_1_Int32_Binding.Register(app);
System_Collections_Generic_List_1_Func_2_Int32_Int32_Binding.Register(app);
System_Action_2_String_Object_Binding.Register(app);
System_Action_1_Boolean_Binding.Register(app);
System_Collections_Generic_List_1_TestVector3_Binding.Register(app);
ILRuntimeTest_TestFramework_TestVector3_Binding.Register(app);
System_Action_Binding.Register(app);
ILRuntimeTest_TestFramework_TestVector3NoBinding_Binding.Register(app);
System_Convert_Binding.Register(app);
System_Collections_Generic_Dictionary_2_Int32_Int32_Binding.Register(app);
System_Collections_Generic_Dictionary_2_Int32_Boolean_Binding.Register(app);
ILRuntimeTest_TestFramework_TestStruct_Binding.Register(app);
System_Char_Binding.Register(app);
System_IO_File_Binding.Register(app);
System_IO_FileStream_Binding.Register(app);
System_IO_Stream_Binding.Register(app);
System_Collections_Generic_Dictionary_2_Int64_Int32_Binding.Register(app);
System_Enum_Binding.Register(app);
System_Collections_IEnumerator_Binding.Register(app);
System_Collections_Generic_Dictionary_2_String_Int64_Binding.Register(app);
System_Double_Binding.Register(app);
System_Int32_Array3_Binding.Register(app);
System_Int32_Array2_Binding.Register(app);
System_UInt16_Binding.Register(app);
System_Int64_Binding.Register(app);
ILRuntimeTest_TestFramework_TestCLREnumClass_Binding.Register(app);
System_Nullable_1_Int32_Binding.Register(app);
System_Collections_Generic_Dictionary_2_String_Int32_Binding_Enumerator_Binding.Register(app);
System_Collections_Generic_KeyValuePair_2_String_Int32_Binding.Register(app);
System_Diagnostics_Stopwatch_Binding.Register(app);
ILRuntimeTest_TestFramework_TestVectorClass_Binding.Register(app);
System_Func_4_Int32_Single_Int16_Double_Binding.Register(app);
System_Collections_Generic_Dictionary_2_Int64_Int64_Array_Binding.Register(app);
System_Collections_Generic_Dictionary_2_String_ILTypeInstance_Array_Binding.Register(app);
System_Collections_Generic_IEnumerator_1_KeyValuePair_2_Int32_Int32_Binding.Register(app);
System_Collections_Generic_KeyValuePair_2_Int32_Int32_Binding.Register(app);
System_Collections_Generic_List_1_List_1_Int32_Binding.Register(app);
System_Collections_Generic_List_1_List_1_List_1_Int32_Binding.Register(app);
System_Collections_Generic_Dictionary_2_ILTypeInstance_Int32_Binding.Register(app);
System_Collections_Generic_List_1_Int32_Array_Binding.Register(app);
System_Collections_Generic_List_1_Object_Binding.Register(app);
System_Linq_IGrouping_2_Byte_Byte_Binding.Register(app);
System_Collections_Generic_Dictionary_2_Int32_ILTypeInstance_Binding_ValueCollection_Binding.Register(app);
System_Collections_Generic_Dictionary_2_Int32_ILTypeInstance_Binding_ValueCollection_Binding_Enumerator_Binding.Register(app);
System_NotSupportedException_Binding.Register(app);
System_Collections_Generic_List_1_ILTypeInstance_Binding_Enumerator_Binding.Register(app);
System_Collections_Generic_Dictionary_2_Type_Int32_Binding.Register(app);
System_NotImplementedException_Binding.Register(app);
ILRuntimeTest_TestFramework_TestVectorStruct_Binding.Register(app);
ILRuntimeTest_TestFramework_TestVectorStruct2_Binding.Register(app);
System_DateTime_Binding.Register(app);
System_Collections_Generic_Dictionary_2_UInt32_ILTypeInstance_Binding.Register(app);
System_Collections_Generic_Dictionary_2_UInt32_ILTypeInstance_Binding_Enumerator_Binding.Register(app);
System_Collections_Generic_KeyValuePair_2_UInt32_ILTypeInstance_Binding.Register(app);
System_AccessViolationException_Binding.Register(app);
System_Func_1_TestVector3_Binding.Register(app);
ILRuntimeTest_TestFramework_JInt_Binding.Register(app);
System_Collections_Generic_Dictionary_2_Object_Object_Binding.Register(app);
System_IComparable_1_Int32_Binding.Register(app);
System_Collections_Generic_Dictionary_2_String_Single_Array_Binding.Register(app);
System_Collections_Generic_Dictionary_2_String_Single_Binding.Register(app);
System_Collections_Generic_Dictionary_2_Int32_Int32_Binding_Enumerator_Binding.Register(app);
ILRuntime.CLR.TypeSystem.CLRType __clrType = null;
__clrType = (ILRuntime.CLR.TypeSystem.CLRType)app.GetType (typeof(ILRuntimeTest.TestFramework.TestVector3));
s_ILRuntimeTest_TestFramework_TestVector3_Binding_Binder = __clrType.ValueTypeBinder as ILRuntime.Runtime.Enviorment.ValueTypeBinder<ILRuntimeTest.TestFramework.TestVector3>;
__clrType = (ILRuntime.CLR.TypeSystem.CLRType)app.GetType (typeof(ILRuntimeTest.TestFramework.TestVectorStruct));
s_ILRuntimeTest_TestFramework_TestVectorStruct_Binding_Binder = __clrType.ValueTypeBinder as ILRuntime.Runtime.Enviorment.ValueTypeBinder<ILRuntimeTest.TestFramework.TestVectorStruct>;
__clrType = (ILRuntime.CLR.TypeSystem.CLRType)app.GetType (typeof(ILRuntimeTest.TestFramework.TestVectorStruct2));
s_ILRuntimeTest_TestFramework_TestVectorStruct2_Binding_Binder = __clrType.ValueTypeBinder as ILRuntime.Runtime.Enviorment.ValueTypeBinder<ILRuntimeTest.TestFramework.TestVectorStruct2>;
__clrType = (ILRuntime.CLR.TypeSystem.CLRType)app.GetType (typeof(System.Collections.Generic.KeyValuePair<System.UInt32, ILRuntime.Runtime.Intepreter.ILTypeInstance>));
s_System_Collections_Generic_KeyValuePair_2_UInt32_ILTypeInstance_Binding_Binder = __clrType.ValueTypeBinder as ILRuntime.Runtime.Enviorment.ValueTypeBinder<System.Collections.Generic.KeyValuePair<System.UInt32, ILRuntime.Runtime.Intepreter.ILTypeInstance>>;
}
/// <summary>
/// Release the CLR binding, please invoke this BEFORE ILRuntime Appdomain destroy
/// </summary>
public static void Shutdown(ILRuntime.Runtime.Enviorment.AppDomain app)
{
s_ILRuntimeTest_TestFramework_TestVector3_Binding_Binder = null;
s_ILRuntimeTest_TestFramework_TestVectorStruct_Binding_Binder = null;
s_ILRuntimeTest_TestFramework_TestVectorStruct2_Binding_Binder = null;
s_System_Collections_Generic_KeyValuePair_2_UInt32_ILTypeInstance_Binding_Binder = null;
}
}
}
| 74.068421 | 270 | 0.781354 | [
"MIT"
] | ErQing/ILRuntime | ILRuntimeTest/AutoGenerate/CLRBindings.cs | 14,073 | C# |
using BlogApp.Dotnet.API.IntegrationTests.Helpers;
using BlogApp.Dotnet.ApplicationCore.DTOs;
using Microsoft.AspNetCore.Mvc.Testing;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Xunit;
namespace BlogApp.Dotnet.API.IntegrationTests
{
public class CommentsTests : IClassFixture<CustomWebApplicationFactoryComments<Startup>>
{
private readonly CustomWebApplicationFactoryComments<Startup> _factory;
private readonly HttpClient _client;
public CommentsTests(CustomWebApplicationFactoryComments<Startup> factory)
{
_factory = factory;
_client = factory.CreateClient(new WebApplicationFactoryClientOptions
{
AllowAutoRedirect = false
});
}
[Fact]
public async Task Get_GetComments_ReturnsPaginatedDTO()
{
string request = "/api/comments?postID=1";
var response = await _client.GetAsync(request);
response.EnsureSuccessStatusCode();
Assert.Equal("application/json", response.Content.Headers.ContentType.MediaType);
var content = await response.Content.ReadAsAsync<PaginatedDTO<CommentsDTO>>();
Assert.Equal(5, content.Items.Count());
Assert.True(content.HasNextPage);
Assert.False(content.HasPreviousPage);
Assert.Equal(7, content.Items.ToList()[4].ID);
Assert.Equal(1, content.Items.ToList()[0].ID);
}
[Fact]
public async Task Get_GetComments_ReturnsPaginatedDTO_SecondPage()
{
string request = "/api/comments?postID=1&page=2";
var response = await _client.GetAsync(request);
response.EnsureSuccessStatusCode();
Assert.Equal("application/json", response.Content.Headers.ContentType.MediaType);
var content = await response.Content.ReadAsAsync<PaginatedDTO<CommentsDTO>>();
Assert.Equal(5, content.Items.Count());
Assert.False(content.HasNextPage);
Assert.True(content.HasPreviousPage);
Assert.Equal(8, content.Items.ToList()[0].ID);
Assert.Equal(12, content.Items.ToList()[4].ID);
}
[Fact]
public async Task Get_GetComments_ReturnsPaginatedDTO_WithSearch()
{
string request = "/api/comments?postID=1&search=special";
var response = await _client.GetAsync(request);
response.EnsureSuccessStatusCode();
Assert.Equal("application/json", response.Content.Headers.ContentType.MediaType);
var content = await response.Content.ReadAsAsync<PaginatedDTO<CommentsDTO>>();
Assert.Single(content.Items);
Assert.False(content.HasNextPage);
Assert.False(content.HasPreviousPage);
Assert.Equal(8, content.Items.ToList()[0].ID);
}
[Fact]
public async Task Get_GetReplies_ReturnsEmpty()
{
string request = "/api/comments/1?postid=1";
var response = await _client.GetAsync(request);
response.EnsureSuccessStatusCode();
Assert.Equal("application/json", response.Content.Headers.ContentType.MediaType);
var content = await response.Content.ReadAsAsync<PaginatedDTO<CommentsDTO>>();
Assert.Empty(content.Items);
}
[Fact]
public async Task Get_GetReplies_ReturnsPaginated()
{
string request = "/api/comments/3?postid=1";
var response = await _client.GetAsync(request);
response.EnsureSuccessStatusCode();
Assert.Equal("application/json", response.Content.Headers.ContentType.MediaType);
var content = await response.Content.ReadAsAsync<PaginatedDTO<CommentsDTO>>();
Assert.Equal(2, content.Items.Count());
Assert.False(content.HasNextPage);
Assert.False(content.HasPreviousPage);
Assert.Equal(4, content.Items.ToList()[0].ID);
}
[Fact]
public async Task Put_PutComment_ReturnsSuccess()
{
string request = "/api/comments?postID=1";
var response = await _client.GetAsync(request);
var content = await response.Content.ReadAsAsync<PaginatedDTO<CommentsDTO>>();
var comm = content.Items.ToList()[0];
comm.Content = "Update";
var sendEdited = await _client.PutAsJsonAsync("/api/comments/1", comm);
sendEdited.EnsureSuccessStatusCode();
Assert.Equal("application/json", response.Content.Headers.ContentType.MediaType);
Assert.Equal(HttpStatusCode.NoContent, sendEdited.StatusCode);
response = await _client.GetAsync(request);
content = await response.Content.ReadAsAsync<PaginatedDTO<CommentsDTO>>();
comm = content.Items.ToList()[0];
Assert.Equal("Update", comm.Content);
}
[Fact]
public async Task Put_PutComment_ReturnsBadRequestWhenIDisWrong()
{
string request = "/api/comments?postID=1";
var response = await _client.GetAsync(request);
var content = await response.Content.ReadAsAsync<PaginatedDTO<CommentsDTO>>();
var comm = content.Items.ToList()[0];
comm.Content = "Update";
var sendEdited = await _client.PutAsJsonAsync("/api/comments/100", comm);
Assert.Equal("application/problem+json", sendEdited.Content.Headers.ContentType.MediaType);
Assert.Equal(HttpStatusCode.BadRequest, sendEdited.StatusCode);
}
[Fact]
public async Task Put_PutComment_ReturnsBadRequestWhenModelIsInvalid()
{
string request = "/api/comments?postID=1";
var response = await _client.GetAsync(request);
var content = await response.Content.ReadAsAsync<PaginatedDTO<CommentsDTO>>();
var comm = content.Items.ToList()[0];
comm.Content = null;
var sendEdited = await _client.PutAsJsonAsync("/api/comments/1", comm);
Assert.Equal("application/problem+json", sendEdited.Content.Headers.ContentType.MediaType);
Assert.Equal(HttpStatusCode.BadRequest, sendEdited.StatusCode);
}
[Fact]
public async Task Post_PostComment_ReturnsSuccess()
{
string request = "/api/comments";
var comm = new CommentsDTO()
{
PostID = 1,
Content = "This is an added comment"
};
var response = await _client.PostAsJsonAsync(request, comm);
response.EnsureSuccessStatusCode();
Assert.Equal(HttpStatusCode.NoContent, response.StatusCode);
var updatedResponse = await _client.GetAsync("/api/comments?postid=1&page=3");
var content = await updatedResponse.Content.ReadAsAsync<PaginatedDTO<CommentsDTO>>();
var addedComment = content.Items.ToList().Last();
Assert.Equal(comm.Content, addedComment.Content);
}
[Fact]
public async Task Post_PostCommentReply_ReturnsSuccess()
{
string request = "/api/comments";
var comm = new CommentsDTO()
{
PostID = 1,
Content = "This is a reply comment",
ParentID = 1
};
var response = await _client.PostAsJsonAsync(request, comm);
response.EnsureSuccessStatusCode();
Assert.Equal(HttpStatusCode.NoContent, response.StatusCode);
var updatedResponse = await _client.GetAsync("/api/comments/1?postid=1");
var content = await updatedResponse.Content.ReadAsAsync<PaginatedDTO<CommentsDTO>>();
var addedComment = content.Items.ToList().Last();
Assert.Equal(comm.Content, addedComment.Content);
}
[Fact]
public async Task Post_PostComment_ReturnsBadRequest()
{
string request = "/api/comments";
var comm = new CommentsDTO()
{
PostID = 1,
Content = null
};
var response = await _client.PostAsJsonAsync(request, comm);
Assert.Equal("application/problem+json", response.Content.Headers.ContentType.MediaType);
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
}
[Fact]
public async Task Delete_DeleteComment_ReturnsSuccess()
{
string request = "/api/comments/13";
var response = await _client.DeleteAsync(request);
response.EnsureSuccessStatusCode();
Assert.Equal(HttpStatusCode.NoContent, response.StatusCode);
var updatedResponse = await _client.GetAsync("/api/comments?postid=1&page=2");
var content = await updatedResponse.Content.ReadAsAsync<PaginatedDTO<CommentsDTO>>();
var comm = content.Items.ToList().Last();
Assert.Equal(12, comm.ID);
Assert.False(content.HasNextPage);
}
}
}
| 39.344681 | 103 | 0.624378 | [
"Unlicense"
] | 44m0n/blog-app | BlogApp/BlogApp.Dotnet.API.IntegrationTests/CommentsTests.cs | 9,248 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
namespace Project_UI
{
public class Program
{
public static void Main(string[] args)
{
BuildWebHost(args).Run();
}
public static IWebHost BuildWebHost(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.Build();
}
}
| 23.038462 | 61 | 0.662771 | [
"MIT"
] | AlexanderAnishchik/ASP-Core-API-Template | Core/Project.UI/Program.cs | 599 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
using Microsoft.Azure.Management.Resources;
using Microsoft.Azure.Management.Sql;
using Microsoft.Azure.Management.Sql.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using Xunit;
namespace Sql.Tests
{
public class UsageScenarioTests
{
[Fact]
public void TestGetUsageData()
{
string testPrefix = "sqlcrudtest-";
string suiteName = this.GetType().FullName;
SqlManagementTestUtilities.RunTestInNewV12Server(suiteName, "TestGetUsageData", testPrefix, (resClient, sqlClient, resourceGroup, server) =>
{
// Get server metrics
IEnumerable<ServerMetric> serverMetrics = sqlClient.Servers.ListUsages(resourceGroup.Name, server.Name);
Assert.True(serverMetrics.Count(s => s.ResourceName == server.Name) > 1);
// Create a database and get metrics
string dbName = SqlManagementTestUtilities.GenerateName();
var dbInput = new Database()
{
Location = server.Location
};
sqlClient.Databases.CreateOrUpdate(resourceGroup.Name, server.Name, dbName, dbInput);
IEnumerable<DatabaseMetric> databaseMetrics = sqlClient.Databases.ListUsages(resourceGroup.Name, server.Name, dbName);
Assert.True(databaseMetrics.Where(db => db.ResourceName == dbName).Count() == 1);
});
}
}
}
| 41.05 | 152 | 0.646772 | [
"MIT"
] | DiogenesPolanco/azure-sdk-for-net | src/ResourceManagement/SqlManagement/Sql.Tests/UsageScenarioTests.cs | 1,644 | C# |
// Copyright (c) Microsoft Corporation
// The Microsoft Corporation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Runtime.CompilerServices;
using System.Text;
using System.Text.Json;
using System.Text.Json.Serialization;
namespace Microsoft.PowerToys.Settings.UI.Lib
{
public class ImageSize : INotifyPropertyChanged
{
public ImageSize(int id)
{
Id = id;
Name = string.Empty;
Fit = (int)ResizeFit.Fit;
Width = 0;
Height = 0;
Unit = (int)ResizeUnit.Pixel;
}
public ImageSize()
{
Id = 0;
Name = string.Empty;
Fit = (int)ResizeFit.Fit;
Width = 0;
Height = 0;
Unit = (int)ResizeUnit.Pixel;
}
public ImageSize(int id, string name, ResizeFit fit, double width, double height, ResizeUnit unit)
{
Id = id;
Name = name;
Fit = (int)fit;
Width = width;
Height = height;
Unit = (int)unit;
}
private int _id;
private string _name;
private int _fit;
private double _height;
private double _width;
private int _unit;
public int Id
{
get
{
return _id;
}
set
{
if (_id != value)
{
_id = value;
OnPropertyChanged();
}
}
}
[JsonPropertyName("name")]
public string Name
{
get
{
return _name;
}
set
{
if (_name != value)
{
_name = value;
OnPropertyChanged();
}
}
}
[JsonPropertyName("fit")]
public int Fit
{
get
{
return _fit;
}
set
{
if (_fit != value)
{
_fit = value;
OnPropertyChanged();
}
}
}
[JsonPropertyName("width")]
public double Width
{
get
{
return _width;
}
set
{
if (_width != value)
{
_width = value;
OnPropertyChanged();
}
}
}
[JsonPropertyName("height")]
public double Height
{
get
{
return _height;
}
set
{
if (_height != value)
{
_height = value;
OnPropertyChanged();
}
}
}
[JsonPropertyName("unit")]
public int Unit
{
get
{
return _unit;
}
set
{
if (_unit != value)
{
_unit = value;
OnPropertyChanged();
}
}
}
public event PropertyChangedEventHandler PropertyChanged;
public void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
var handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
public void Update(ImageSize modifiedSize)
{
Id = modifiedSize.Id;
Name = modifiedSize.Name;
Fit = modifiedSize.Fit;
Width = modifiedSize.Width;
Height = modifiedSize.Height;
Unit = modifiedSize.Unit;
}
public string ToJsonString()
{
return JsonSerializer.Serialize(this);
}
}
}
| 22.542553 | 106 | 0.411751 | [
"MIT"
] | 01DKAC/PowerToys | src/core/Microsoft.PowerToys.Settings.UI.Lib/ImageSize.cs | 4,240 | C# |
using System.Collections;
using System.Collections.ObjectModel;
using TLCGen.Helpers;
using TLCGen.Plugins;
namespace TLCGen.ViewModels
{
[TLCGenTabItem(index: 1, type: TabItemTypeEnum.OVTab)]
public class OVOverzichtTabViewModel : TLCGenTabItemViewModel
{
#region Fields
private ObservableCollection<OVHDFaseDataOverviewViewModel> _Fasen;
private OVHDFaseDataOverviewViewModel _SelectedFaseCyclus;
private IList _SelectedFaseCycli = new ArrayList();
#endregion // Fields
#region Properties
public ObservableCollection<OVHDFaseDataOverviewViewModel> Fasen
{
get
{
if (_Fasen == null)
{
_Fasen = new ObservableCollection<OVHDFaseDataOverviewViewModel>();
}
return _Fasen;
}
}
public OVHDFaseDataOverviewViewModel SelectedFaseCyclus
{
get => _SelectedFaseCyclus;
set
{
_SelectedFaseCyclus = value;
RaisePropertyChanged();
}
}
public IList SelectedFaseCycli
{
get => _SelectedFaseCycli;
set
{
_SelectedFaseCycli = value;
_settingMultiple = false;
RaisePropertyChanged();
}
}
#endregion // Properties
#region TabItem Overrides
public override string DisplayName => "Overzicht";
public override bool CanBeEnabled()
{
return _Controller?.OVData?.OVIngreepType != Models.Enumerations.OVIngreepTypeEnum.Geen;
}
public override void OnSelected()
{
var temp = SelectedFaseCyclus;
foreach (var fcvm in Fasen)
{
fcvm.PropertyChanged -= OVHDFaseData_PropertyChanged;
if(fcvm.OVIngreep != null) fcvm.OVIngreep.PropertyChanged -= OVIngreep_PropertyChanged;
if(fcvm.HDIngreep != null) fcvm.HDIngreep.PropertyChanged -= HDIngreep_PropertyChanged;
}
Fasen.Clear();
SelectedFaseCyclus = null;
foreach (var fcm in _Controller.Fasen)
{
var fcvm = new OVHDFaseDataOverviewViewModel(fcm, this, _Controller);
Fasen.Add(fcvm);
fcvm.PropertyChanged += OVHDFaseData_PropertyChanged;
if (temp == null || fcvm.FaseCyclusNaam != temp.FaseCyclusNaam) continue;
SelectedFaseCyclus = fcvm;
temp = null;
}
if(SelectedFaseCyclus == null && Fasen.Count > 0)
{
SelectedFaseCyclus = Fasen[0];
}
}
#endregion // TabItem Overrides
#region Commands
#endregion // Commands
#region Command functionality
#endregion // Command functionality
#region Private methods
#endregion // Private methods
#region Public methods
#endregion // Public methods
#region TLCGen events
#endregion TLCGen events
#region Event Handling
private bool _settingMultiple;
private void OVHDFaseData_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
{
if (_settingMultiple || string.IsNullOrEmpty(e.PropertyName))
return;
if (SelectedFaseCycli != null && SelectedFaseCycli.Count > 1)
{
_settingMultiple = true;
MultiPropertySetter.SetPropertyForAllItems<OVHDFaseDataOverviewViewModel>(sender, e.PropertyName, SelectedFaseCycli);
}
_settingMultiple = false;
}
public void OVIngreep_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
{
if (_settingMultiple || string.IsNullOrEmpty(e.PropertyName))
return;
if (SelectedFaseCycli != null && SelectedFaseCycli.Count > 1)
{
_settingMultiple = true;
var l = new ArrayList();
foreach (OVHDFaseDataOverviewViewModel fc in SelectedFaseCycli)
{
if(fc.FaseCyclusNaam != null)
{
l.Add(fc.OVIngreep);
}
}
MultiPropertySetter.SetPropertyForAllItems<OVIngreepViewModel>(sender, e.PropertyName, l);
}
_settingMultiple = false;
}
public void HDIngreep_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
{
if (_settingMultiple || string.IsNullOrEmpty(e.PropertyName))
return;
if (SelectedFaseCycli != null && SelectedFaseCycli.Count > 1)
{
_settingMultiple = true;
var l = new ArrayList();
foreach (OVHDFaseDataOverviewViewModel fc in SelectedFaseCycli)
{
if(fc.FaseCyclusNaam != null)
{
l.Add(fc.HDIngreep);
}
}
MultiPropertySetter.SetPropertyForAllItems<HDIngreepViewModel>(sender, e.PropertyName, l);
}
_settingMultiple = false;
}
#endregion // Event Handling
#region Constructor
public OVOverzichtTabViewModel()
{
}
#endregion // Constructor
}
} | 26.472826 | 121 | 0.6434 | [
"MIT"
] | LexTrafico/TLCGen | TLCGen/Views/Tabs/OVTab/Tabs/OVOverzichtTabViewModel.cs | 4,873 | C# |
using System;
using System.Collections.Generic;
using System.Text;
namespace Core.Entities
{
public class UserLike
{
public AppUser SourceUser { get; set; }
public int SourceUserId { get; set; }
public AppUser LikedUser { get; set; }
public int LikedUserId { get; set; }
}
}
| 20.125 | 47 | 0.636646 | [
"MIT"
] | ritchie200/datingwebsite | Core/Entities/UserLike.cs | 324 | C# |
using UnityEngine;
using System.Collections;
public abstract class LeverAction : MonoBehaviour
{
#region Fields
protected LeverPull leverScript;
private bool performedAction;
#endregion
#region Mandatory To Implement
abstract protected void Action();
#endregion
#region Optional To Implement
virtual protected void OnUpdate()
{
}
#endregion
#region Internal
void Awake()
{
leverScript = GetComponentInChildren<LeverPull>();
if (leverScript == null)
{
Debug.Log("LeverPull component missing.");
}
performedAction = false;
}
void Update()
{
if (leverScript.IsMoving())
{
if (performedAction == false)
{
performedAction = true;
Action();
}
}
else
{
performedAction = false;
}
OnUpdate();
}
#endregion
}
| 13.491525 | 52 | 0.672111 | [
"MIT"
] | AmalJossy/ARTreasureHunt | Assets/Assets/Lever/Materials/Materials/LeverAction.cs | 798 | C# |
namespace Magellan.Framework
{
/// <summary>
/// The action invoker that is used by the <see cref="Controller"/> to process the request.
/// </summary>
public interface IActionInvoker
{
/// <summary>
/// Executes the action on the specified controller.
/// </summary>
/// <param name="controllerContext">The controller context.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="modelBinders">The model binders.</param>
void ExecuteAction(ControllerContext controllerContext, string actionName, ModelBinderDictionary modelBinders);
}
} | 40.4375 | 119 | 0.652241 | [
"MIT"
] | rog1039/magellan-framework | src/Magellan/Framework/IActionInvoker.cs | 649 | C# |
namespace Sqlbi.Bravo.Infrastructure
{
using Sqlbi.Bravo.Infrastructure.Extensions;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.CompilerServices;
using System.Text.Json.Serialization;
using System.Threading.Tasks;
/// <summary>
/// Represents unexpected errors that occur during application execution.
/// </summary>
/// <remarks>
/// This class does not inherit from <see cref="BravoException"/>. <see cref="BravoUnexpectedException"/> will be tracked in telemetry as an unhandled exception and should not be handled at the application level.
/// </remarks>
[Serializable]
public class BravoUnexpectedException : Exception
{
public BravoUnexpectedException(string message)
: base(message)
{
}
/// <summary>
/// Throws an <see cref="BravoUnexpectedArgumentNullException"/> if <paramref name="argument"/> is null. See https://github.com/dotnet/runtime/issues/48573
/// </summary>
/// <param name="argument">The reference type argument to validate as non-null.</param>
/// <param name="paramName">The name of the parameter with which <paramref name="argument"/> corresponds.</param>
public static void ThrowIfNull([NotNull] object? argument, [CallerArgumentExpression("argument")] string? paramName = null)
{
if (argument is null)
{
ThrowUnexpectedArgumentNullException(paramName);
}
}
/// <summary>
/// Throws an <see cref="BravoUnexpectedInvalidOperationException"/> if <paramref name="condition"/> is false.
/// </summary>
/// <param name="condition">The Boolean condition to be evaluated.</param>
/// <param name="paramName">The name of the parameter with which <paramref name="condition"/> corresponds.</param>
public static void Assert([DoesNotReturnIf(false)] bool condition, [CallerArgumentExpression("condition")] string? paramName = null)
{
if (condition == false)
{
ThrowUnexpectedInvalidOperationException(paramName);
}
}
[DoesNotReturn]
private static void ThrowUnexpectedArgumentNullException(string? paramName) => throw new BravoUnexpectedArgumentNullException(paramName);
[DoesNotReturn]
private static void ThrowUnexpectedInvalidOperationException(string? condition) => throw new BravoUnexpectedInvalidOperationException($"Condition failed '{ condition }'");
}
public class BravoUnexpectedArgumentNullException : ArgumentNullException
{
public BravoUnexpectedArgumentNullException(string? paramName)
: base(paramName)
{
}
}
public class BravoUnexpectedInvalidOperationException : InvalidOperationException
{
public BravoUnexpectedInvalidOperationException(string? message)
: base(message)
{
}
}
/// <summary>
/// Represents the base class for error that occurs during application execution.
/// </summary>
[Serializable]
public class BravoException : Exception
{
public BravoProblem Problem { get; private set; }
public string? ProblemDetail => Message.NullIfWhiteSpace();
public string ProblemInstance => $"{ (int)Problem }";
public BravoException(BravoProblem problem)
: base(string.Empty)
{
Problem = problem;
}
public BravoException(BravoProblem problem, string message)
: base(message)
{
Problem = problem;
}
public BravoException(BravoProblem problem, string message, Exception innerException)
: base(message, innerException)
{
Problem = problem;
}
}
public enum BravoProblem
{
[JsonPropertyName("None")]
None = 0,
/// <summary>
/// A <see cref="OperationCanceledException"/> or <see cref="TaskCanceledException"/> was thrown, an HTTP request was aborted or the user cancelled a long-running operation.
/// This BravoProblem is a placehoder since the response message is never sent back to the user/UI due to the aborted request.
/// </summary>
[JsonPropertyName("OperationCancelled")]
OperationCancelled = 1,
/// <summary>
/// A connection problem arises between the server and current application
/// </summary>
[JsonPropertyName("AnalysisServicesConnectionFailed")]
AnalysisServicesConnectionFailed = 10,
/// <summary>
/// TOM database does not exists in the collection or the user does not have admin rights for it.
/// </summary>
[JsonPropertyName("TOMDatabaseDatabaseNotFound")]
TOMDatabaseDatabaseNotFound = 101,
/// <summary>
/// TOM database update failed while saving local changes made on the model tree to the version of the model residing in the database server.
/// </summary>
[JsonPropertyName("TOMDatabaseUpdateFailed")]
TOMDatabaseUpdateFailed = 102,
/// <summary>
/// TOM measure update request conflict with current state of the target resource
/// </summary>
[JsonPropertyName("TOMDatabaseUpdateConflictMeasure")]
TOMDatabaseUpdateConflictMeasure = 103,
/// <summary>
/// TOM measure update request failed because the measure contains DaxFormatter errors
/// </summary>
[JsonPropertyName("TOMDatabaseUpdateErrorMeasure")]
TOMDatabaseUpdateErrorMeasure = 104,
/// <summary>
/// The connection to the requested resource is not supported
/// </summary>
[JsonPropertyName("ConnectionUnsupported")]
ConnectionUnsupported = 200,
/// <summary>
/// An error occurred while saving user settings
/// </summary>
[JsonPropertyName("UserSettingsSaveError")]
UserSettingsSaveError = 300,
///// <summary>
///// PBIDesktop process is no longer running or the identifier might be expired.
///// </summary>
//[JsonPropertyName("PBIDesktopProcessNotFound")]
//PBIDesktopProcessNotFound = 200,
///// <summary>
///// PBIDesktop SSAS instance process not found.
///// </summary>
//[JsonPropertyName("PBIDesktopSSASProcessNotFound")]
//PBIDesktopSSASProcessNotFound = 300,
///// <summary>
///// PBIDesktop SSAS instance connection not found.
///// </summary>
//[JsonPropertyName("PBIDesktopSSASConnectionNotFound")]
//PBIDesktopSSASConnectionNotFound = 301,
///// <summary>
///// PBIDesktop SSAS instance contains an unexpected number of databases.
///// </summary>
//[JsonPropertyName("PBIDesktopSSASDatabaseUnexpectedCount")]
//PBIDesktopSSASDatabaseUnexpectedCount = 302,
///// <summary>
///// PBIDesktop SSAS instance does not contain any databases.
///// </summary>
//[JsonPropertyName("PBIDesktopSSASDatabaseCollectionEmpty")]
//PBIDesktopSSASDatabaseCollectionEmpty = 303,
/// <summary>
/// An error occurs during token acquisition.
/// </summary>
/// <remarks>
/// Exceptions in MSAL.NET are intended for app developers to troubleshoot and not for displaying to end-users
/// </remarks>
[JsonPropertyName("SignInMsalExceptionOccurred")]
SignInMsalExceptionOccurred = 400,
/// <summary>
/// Sign-in request was canceled because the configured timeout period elapsed prior to completion of the operation
/// </summary>
[JsonPropertyName("SignInMsalTimeoutExpired")]
SignInMsalTimeoutExpired = 401,
/// <summary>
/// VPAX file format is not valid or file contains corrupted data
/// </summary>
[JsonPropertyName("VpaxFileContainsCorruptedData")]
VpaxFileContainsCorruptedData = 500,
/// <summary>
/// You are not connected to the Internet
/// </summary>
[JsonPropertyName("NetworkError")]
NetworkError = 600,
/// <summary>
/// An exception occurred while exporting data to file
/// </summary>
[JsonPropertyName("ExportDataFileError")]
ExportDataFileError = 700,
/// <summary>
/// An exception occurred while executing the DAX template engine
/// </summary>
[JsonPropertyName("ManageDateTemplateError")]
ManageDateTemplateError = 800,
}
}
| 38.241228 | 216 | 0.635738 | [
"MIT"
] | isdataninja/Bravo | src/Infrastructure/AppExceptions.cs | 8,721 | C# |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Runtime.InteropServices;
using EnvDTE;
using VSLangProj;
namespace Microsoft.VisualStudioTools.Project.Automation
{
/// <summary>
/// Represents an automation friendly version of a language-specific project.
/// </summary>
[ComVisible(true), CLSCompliant(false)]
public class OAVSProject : VSProject
{
#region fields
private ProjectNode project;
private OAVSProjectEvents events;
#endregion
#region ctors
internal OAVSProject(ProjectNode project)
{
this.project = project;
}
#endregion
#region VSProject Members
public virtual ProjectItem AddWebReference(string bstrUrl)
{
throw new NotImplementedException();
}
public virtual BuildManager BuildManager => throw new NotImplementedException();
public virtual void CopyProject(string bstrDestFolder, string bstrDestUNCPath, prjCopyProjectOption copyProjectOption, string bstrUsername, string bstrPassword)
{
throw new NotImplementedException();
}
public virtual ProjectItem CreateWebReferencesFolder()
{
throw new NotImplementedException();
}
public virtual DTE DTE => (EnvDTE.DTE)this.project.Site.GetService(typeof(EnvDTE.DTE));
public virtual VSProjectEvents Events
{
get
{
if (this.events == null)
{
this.events = new OAVSProjectEvents(this);
}
return this.events;
}
}
public virtual void Exec(prjExecCommand command, int bSuppressUI, object varIn, out object pVarOut)
{
throw new NotImplementedException(); ;
}
public virtual void GenerateKeyPairFiles(string strPublicPrivateFile, string strPublicOnlyFile)
{
throw new NotImplementedException(); ;
}
public virtual string GetUniqueFilename(object pDispatch, string bstrRoot, string bstrDesiredExt)
{
throw new NotImplementedException(); ;
}
public virtual Imports Imports => throw new NotImplementedException();
public virtual EnvDTE.Project Project => this.project.GetAutomationObject() as EnvDTE.Project;
public virtual References References
{
get
{
var references = this.project.GetReferenceContainer() as ReferenceContainerNode;
if (null == references)
{
return new OAReferences(null, this.project);
}
return references.Object as References;
}
}
public virtual void Refresh()
{
}
public virtual string TemplatePath => throw new NotImplementedException();
public virtual ProjectItem WebReferencesFolder => throw new NotImplementedException();
public virtual bool WorkOffline
{
get
{
throw new NotImplementedException();
}
set
{
throw new NotImplementedException();
}
}
#endregion
}
/// <summary>
/// Provides access to language-specific project events
/// </summary>
[ComVisible(true), CLSCompliant(false)]
public class OAVSProjectEvents : VSProjectEvents
{
#region fields
private OAVSProject vsProject;
#endregion
#region ctors
public OAVSProjectEvents(OAVSProject vsProject)
{
this.vsProject = vsProject;
}
#endregion
#region VSProjectEvents Members
public virtual BuildManagerEvents BuildManagerEvents => this.vsProject.BuildManager as BuildManagerEvents;
public virtual ImportsEvents ImportsEvents => throw new NotImplementedException();
public virtual ReferencesEvents ReferencesEvents => this.vsProject.References as ReferencesEvents;
#endregion
}
}
| 30.448276 | 169 | 0.594564 | [
"Apache-2.0"
] | Abd-Elrazek/nodejstools | Nodejs/Product/Nodejs/SharedProject/Automation/VSProject/OAVSProject.cs | 4,271 | C# |
// *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.Aws.WafV2.Outputs
{
[OutputType]
public sealed class WebAclRuleStatementRateBasedStatementScopeDownStatementOrStatementStatementNotStatementStatementGeoMatchStatementForwardedIpConfig
{
/// <summary>
/// - The match status to assign to the web request if the request doesn't have a valid IP address in the specified position. Valid values include: `MATCH` or `NO_MATCH`.
/// </summary>
public readonly string FallbackBehavior;
/// <summary>
/// - The name of the HTTP header to use for the IP address.
/// </summary>
public readonly string HeaderName;
[OutputConstructor]
private WebAclRuleStatementRateBasedStatementScopeDownStatementOrStatementStatementNotStatementStatementGeoMatchStatementForwardedIpConfig(
string fallbackBehavior,
string headerName)
{
FallbackBehavior = fallbackBehavior;
HeaderName = headerName;
}
}
}
| 36.694444 | 178 | 0.706283 | [
"ECL-2.0",
"Apache-2.0"
] | Otanikotani/pulumi-aws | sdk/dotnet/WafV2/Outputs/WebAclRuleStatementRateBasedStatementScopeDownStatementOrStatementStatementNotStatementStatementGeoMatchStatementForwardedIpConfig.cs | 1,321 | C# |
//
// TextureBuffer.cs
//
// Copyright (C) 2018 OpenTK
//
// This software may be modified and distributed under the terms
// of the MIT license. See the LICENSE file for details.
//
using System;
using ObjectTK.Buffers;
using OpenTK.Graphics.OpenGL;
namespace ObjectTK.Textures
{
/// <summary>
/// Represents a buffer texture.<br/>
/// The image in this texture (only one image. No mipmapping) is 1-dimensional.
/// The storage for this data comes from a Buffer Object.
/// </summary>
public sealed class TextureBuffer
: Texture
{
public override TextureTarget TextureTarget { get { return TextureTarget.TextureBuffer; } }
public override bool SupportsMipmaps { get { return false; } }
/// <summary>
/// Creates a buffer texture and uses the given internal format to access a bound buffer, if not specified otherwise.
/// </summary>
/// <param name="internalFormat"></param>
public TextureBuffer(SizedInternalFormat internalFormat)
: base(internalFormat, 1)
{
}
/// <summary>
/// Binds the given buffer to this texture.<br/>
/// Applies the internal format specified in the constructor.
/// </summary>
/// <param name="buffer">The buffer to bind.</param>
public void BindBufferToTexture<T>(Buffer<T> buffer)
where T : struct
{
BindBufferToTexture(buffer, InternalFormat);
}
/// <summary>
/// Binds the given buffer to this texture using the given internal format.
/// </summary>
/// <param name="buffer">The buffer to bind.</param>
/// <param name="internalFormat">The internal format used when accessing the buffer.</param>
/// <typeparam name="T">The type of elements in the buffer object.</typeparam>
public void BindBufferToTexture<T>(Buffer<T> buffer, SizedInternalFormat internalFormat)
where T : struct
{
if (!buffer.Initialized) throw new ArgumentException("Can not bind uninitialized buffer to buffer texture.", "buffer");
GL.BindTexture(TextureTarget.TextureBuffer, Handle);
GL.TexBuffer(TextureBufferTarget.TextureBuffer, internalFormat, buffer.Handle);
}
}
} | 37.852459 | 131 | 0.638805 | [
"MIT"
] | JcBernack/ObjectTK | ObjectTK/Textures/TextureBuffer.cs | 2,311 | C# |
using Rogue.Serializables;
using UnityEngine;
namespace Rogue.Items
{
public class WeaponItem : MonoBehaviour
{
#region VARIABLES
[Header("Weapon Properties")]
public Weapon WeaponData;
#endregion
#region UNITY METHODS
private void OnTriggerEnter2D(Collider2D other)
{
}
#endregion
#region METHODS
#endregion
}
} | 15.555556 | 55 | 0.597619 | [
"MIT"
] | Macawls/vega_project_2A | Assets/_Project/Scripts/Runtime/Items/WeaponItem.cs | 420 | C# |
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Windows;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Arsync.SharedResources")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Arsync.SharedResources")]
[assembly: AssemblyCopyright("Copyright © 2019")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
//In order to begin building localizable applications, set
//<UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file
//inside a <PropertyGroup>. For example, if you are using US english
//in your source files, set the <UICulture> to en-US. Then uncomment
//the NeutralResourceLanguage attribute below. Update the "en-US" in
//the line below to match the UICulture setting in the project file.
//[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)]
[assembly:ThemeInfo(
ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located
//(used if a resource is not found in the page,
// or application resource dictionaries)
ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located
//(used if a resource is not found in the page,
// app, or any theme specific resource dictionaries)
)]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 42.125 | 96 | 0.721068 | [
"MIT"
] | Arsync/wpfchrometabs-mvvm | Arsync.SharedResources/Properties/AssemblyInfo.cs | 2,362 | C# |
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
namespace BluetoothDevicePairing
{
class PairingServer
{
private const int SERVICE_PORT = 11000;
private const int BUF_SIZE = 4 * 1024;
private readonly Socket ServerSocket = new(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
public delegate void MessageHandler(PairingServer pairingServer, Socket socket, EndPoint epFrom, string newMessage);
public event MessageHandler NewMessageReceived;
public PairingServer()
{
}
public void Start()
{
IPEndPoint localEndPoint = new(IPAddress.Parse("127.0.0.1"), SERVICE_PORT);
try
{
ServerSocket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.ReuseAddress, true);
ServerSocket.Bind(localEndPoint);
Receive();
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
Console.WriteLine("\n Press any key to continue");
Console.ReadKey();
}
public void SendTo(EndPoint epTo, uint value)
{
try {
State BufferState = new();
byte[] data = BitConverter.GetBytes(value);
ServerSocket.BeginSendTo(data, 0, data.Length, SocketFlags.None, epTo, (ar) =>
{
State so = (State)ar.AsyncState;
int bytes = ServerSocket.EndSendTo(ar);
Console.WriteLine("SEND: {0}, {1}", bytes, value);
}, BufferState);
} catch (Exception ex)
{
Console.WriteLine($"{ex.Message}");
Console.WriteLine($"{ex.StackTrace}");
}
}
public void SendTo(EndPoint epTo, string text)
{
State BufferState = new();
byte[] data = Encoding.ASCII.GetBytes(text);
ServerSocket.BeginSendTo(data, 0, data.Length, SocketFlags.None, epTo, (ar) =>
{
State so = (State)ar.AsyncState;
int bytes = ServerSocket.EndSendTo(ar);
Console.WriteLine("SEND: {0}, {1}", bytes, text);
}, BufferState);
}
private void Receive()
{
State BufferState = new();
AsyncCallback InteralSockCallback = null;
EndPoint epFrom = new IPEndPoint(IPAddress.Any, 0);
ServerSocket.BeginReceiveFrom(BufferState.buffer, 0, BUF_SIZE, SocketFlags.None, ref epFrom, InteralSockCallback = (ar) =>
{
State so = (State)ar.AsyncState;
int bytes = ServerSocket.EndReceiveFrom(ar, ref epFrom);
ServerSocket.BeginReceiveFrom(so.buffer, 0, BUF_SIZE, SocketFlags.None, ref epFrom, InteralSockCallback, so);
string receivedMessage = Encoding.ASCII.GetString(so.buffer, 0, bytes);
Console.WriteLine("RECV: {0}: {1}, {2}", epFrom.ToString(), bytes, receivedMessage);
NewMessageReceived?.Invoke(this, ServerSocket, epFrom, receivedMessage);
}, BufferState);
}
// BufferState
public class State
{
public byte[] buffer = new byte[BUF_SIZE];
}
}
}
| 35.21875 | 134 | 0.557232 | [
"MIT"
] | BeneyKim/BluetoothDevicePairing | Src/PairingServer.cs | 3,383 | C# |
using Microsoft.Xna.Framework;
namespace P3D.Legacy.MapEditor.Data
{
public class EntityNPCInfo : EntityInfo
{
public string Name { get; set; }
public string TextureID { get; set; }
public string Movement { get; set; }
public Rectangle[] MoveRectangles { get; set; }
public bool AnimateIdle { get; set; }
public int FaceRotation { get; set; }
public override string ToString() => $"{base.ToString()} {Name}";
}
} | 30.1875 | 73 | 0.619048 | [
"MIT"
] | P3D-Legacy/P3D-Legacy-MapEditor | P3D-Legacy-MapEditor/Data/EntityNPCInfo.cs | 485 | C# |
using GAAPICommon.Architecture;
using GACore.Architecture;
using GACore.Extensions;
using System;
using System.Globalization;
using System.Windows.Data;
using System.Windows.Media;
namespace GACore.Controls.View
{
public class RadToDegStringConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
double rad = (float)value;
return rad.RadToDeg();
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
=> throw new NotImplementedException("RadToDegStringConverter ConvertBack()");
}
public class IsVirtualColorConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
bool isVirtual = (bool)value;
return isVirtual ? Brushes.Cyan : Brushes.Black;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
=> throw new NotImplementedException("IsVirtualColorConverter ConvertBack()");
}
public class DynamicLimiterStatusToOverlayTextConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
DynamicLimiterStatus status = (DynamicLimiterStatus)value;
BrushCollection brushCollection = BrushDictionaries.DynamicLimiterStatusBrushCollectionDictionary.GetBrushCollection(status);
BrushCollectionProperty property = (BrushCollectionProperty)parameter;
return brushCollection.GetProperty(property);
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
=> throw new NotImplementedException();
}
public sealed class NavigationStatusToOverlayTextConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
NavigationStatus status = (NavigationStatus)value;
BrushCollection brushCollection = BrushDictionaries.NavigationStatusBackgroundBrushCollectionDictionary.GetBrushCollection(status);
BrushCollectionProperty property = (BrushCollectionProperty)parameter;
return brushCollection.GetProperty(property);
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
=> throw new NotImplementedException();
}
public class PositionControlStatusToOverlayTextConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
PositionControlStatus status = (PositionControlStatus)value;
BrushCollection brushCollection = BrushDictionaries.PositionControlStatusBackgroundBrushCollectionDictionary.GetBrushCollection(status);
BrushCollectionProperty property = (BrushCollectionProperty)parameter;
return brushCollection.GetProperty(property);
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
=> throw new NotImplementedException();
}
}
| 37.35 | 139 | 0.807898 | [
"MIT"
] | GuidanceAutomation/GACore | src/GACore.Controls/View/Converters.cs | 2,990 | C# |
using Netch.Models;
namespace Netch.Servers
{
public class Socks5Server : Server
{
/// <summary>
/// 密码
/// </summary>
public string? Password { get; set; }
/// <summary>
/// 账号
/// </summary>
public string? Username { get; set; }
public override string Type { get; } = "Socks5";
public override string MaskedData()
{
return $"Auth: {Auth()}";
}
public Socks5Server()
{
}
public Socks5Server(string hostname, ushort port)
{
Hostname = hostname;
Port = port;
}
public Socks5Server(string hostname, ushort port, string username, string password) : this(hostname, port)
{
Username = username;
Password = password;
}
public bool Auth()
{
return !string.IsNullOrWhiteSpace(Username) && !string.IsNullOrWhiteSpace(Password);
}
}
} | 22.6 | 114 | 0.504425 | [
"MIT"
] | C0S1N3/Netch | Netch/Servers/Socks5/Socks5Server.cs | 1,027 | C# |
using InTheHand.Net;
using InTheHand.Net.Bluetooth;
using InTheHand.Net.Sockets;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO.Ports;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace FC_Options
{
public partial class DeviceOpt : Form
{
public ComboBox MyCmbDevice
{
get { return CmbDevice; }
}
public DeviceOpt()
{
InitializeComponent();
//CmbDevice.SelectedItem = FormFCOptions.ReadSetting("device", "ArduinoFC");
FormFCOptions.btc = new BluetoothClient();
BluetoothDeviceInfo[] devices = FormFCOptions.btc.DiscoverDevices(8, true, true, false, false);
CmbDevice.DataSource = devices;
CmbDevice.DisplayMember = "DeviceName";
CmbDevice.ValueMember = "DeviceAddress";
if (devices[Int32.Parse(FormFCOptions.ReadSetting("device_index", "0"))].DeviceAddress.ToString() == FormFCOptions.ReadSetting("device_name", ""))
{
CmbDevice.SelectedIndex = Int32.Parse(FormFCOptions.ReadSetting("device_index", "0"));
}
}
private void BtnOK_Click(object sender, EventArgs e)
{
if (CmbDevice.SelectedValue != null)
{
//1. Disconnect and then reconnect >> close thread while disconnected
//3. If already connected, than leave it as is/show dialog >> do not close thread
//4. Device was disconnected by itself (use try catch in thread to detect) >> close thread and wait for the reconnect
//2. Connect >> start thread
try
{
FormFCOptions.btc.Connect(new BluetoothEndPoint((BluetoothAddress)CmbDevice.SelectedValue, BluetoothService.SerialPort));
this.DialogResult = DialogResult.OK;
this.Close();
}
catch (SocketException err)
{
Console.WriteLine(err);
}
}
else
{
Warning_InvalidValue warning = new Warning_InvalidValue();
warning.ShowDialog();
}
}
private void BtnCancel_Click(object sender, EventArgs e)
{
//FormFCOptions.btc.Close();
this.Close();
}
}
}
| 30.357143 | 158 | 0.583137 | [
"Apache-2.0"
] | tylim2946/Foot-Controller-Mk-I | FC-Options/DeviceOpt.cs | 2,552 | C# |
namespace Zu.ChromeDevTools.Page
{
using Newtonsoft.Json;
/// <summary>
/// Forces compilation cache to be generated for every subresource script.
/// </summary>
public sealed class SetProduceCompilationCacheCommand : ICommand
{
private const string ChromeRemoteInterface_CommandName = "Page.setProduceCompilationCache";
[JsonIgnore]
public string CommandName
{
get { return ChromeRemoteInterface_CommandName; }
}
/// <summary>
/// Gets or sets the enabled
/// </summary>
[JsonProperty("enabled")]
public bool Enabled
{
get;
set;
}
}
public sealed class SetProduceCompilationCacheCommandResponse : ICommandResponse<SetProduceCompilationCacheCommand>
{
}
} | 26.21875 | 119 | 0.618594 | [
"Apache-2.0"
] | DoctorDump/AsyncChromeDriver | ChromeDevToolsClient/Page/SetProduceCompilationCacheCommand.cs | 839 | C# |
// ***********************************************************************
// Copyright (c) Charlie Poole and TestCentric contributors.
// Licensed under the MIT License. See LICENSE in root directory.
// ***********************************************************************
using System.IO;
using System.Reflection;
namespace TCLite.Internal
{
public class AssemblyHelperTests
{
[TestCase]
public void GetPathForAssembly()
{
string path = AssemblyHelper.GetAssemblyPath(this.GetType().Assembly);
Assert.That(Path.GetFileName(path), Is.EqualTo("tclite.tests.dll"));
Assert.That(File.Exists(path));
}
[TestCase]
public void GetPathForType()
{
string path = AssemblyHelper.GetAssemblyPath(this.GetType());
Assert.That(Path.GetFileName(path), Is.EqualTo("tclite.tests.dll").IgnoreCase);
Assert.That(File.Exists(path));
}
// The following tests are only useful to the extent that the test cases
// match what will actually be provided to the method in production.
// As currently used, NUnit's codebase can only use the file: schema,
// since we don't load assemblies from anything but files. The uri's
// provided can be absolute file paths or UNC paths.
#if NYI // Windows path
// Local paths - Windows Drive
[TestCase(@"file:///C:/path/to/assembly.dll", @"C:\path\to\assembly.dll")]
[TestCase(@"file:///C:/my path/to my/assembly.dll", @"C:/my path/to my/assembly.dll")]
[TestCase(@"file:///C:/dev/C#/assembly.dll", @"C:\dev\C#\assembly.dll")]
[TestCase(@"file:///C:/dev/funnychars?:=/assembly.dll", @"C:\dev\funnychars?:=\assembly.dll")]
// Windows drive specified as if it were a server - odd case, sometimes seen
[TestCase(@"file://C:/path/to/assembly.dll", @"C:\path\to\assembly.dll")]
[TestCase(@"file://C:/my path/to my/assembly.dll", @"C:\my path\to my\assembly.dll")]
[TestCase(@"file://C:/dev/C#/assembly.dll", @"C:\dev\C#\assembly.dll")]
[TestCase(@"file://C:/dev/funnychars?:=/assembly.dll", @"C:\dev\funnychars?:=\assembly.dll")]
#endif
// Local paths - Linux or Windows absolute without a drive
[TestCase(@"file:///path/to/assembly.dll", @"/path/to/assembly.dll")]
[TestCase(@"file:///my path/to my/assembly.dll", @"/my path/to my/assembly.dll")]
[TestCase(@"file:///dev/C#/assembly.dll", @"/dev/C#/assembly.dll")]
[TestCase(@"file:///dev/funnychars?:=/assembly.dll", @"/dev/funnychars?:=/assembly.dll")]
// UNC format with server and path
[TestCase(@"file://server/path/to/assembly.dll", @"//server/path/to/assembly.dll")]
[TestCase(@"file://server/my path/to my/assembly.dll", @"//server/my path/to my/assembly.dll")]
[TestCase(@"file://server/dev/C#/assembly.dll", @"//server/dev/C#/assembly.dll")]
[TestCase(@"file://server/dev/funnychars?:=/assembly.dll", @"//server/dev/funnychars?:=/assembly.dll")]
//[TestCase(@"http://server/path/to/assembly.dll", "//server/path/to/assembly.dll")]
public void GetAssemblyPathFromCodeBase(string uri, string expectedPath)
{
string localPath = AssemblyHelper.GetAssemblyPathFromCodeBase(uri);
Assert.That(localPath, Is.EqualTo(expectedPath));
}
}
}
| 52.492308 | 111 | 0.599062 | [
"MIT"
] | TestCentric/tc-lite | src/tclite.tests/Internal/AssemblyHelperTests.cs | 3,414 | C# |
/*
Copyright (C) 2019 Alex Watt (alexwatt@hotmail.com)
This file is part of Highlander Project https://github.com/alexanderwatt/Hghlander.Net
Highlander is free software: you can redistribute it and/or modify it
under the terms of the Highlander license. You should have received a
copy of the license along with this program; if not, license is
available at <https://github.com/alexanderwatt/Hghlander.Net/blob/develop/LICENSE>.
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the license for more details.
*/
namespace FpML.V5r10.Reporting
{
public partial class QuotedCurrencyPair
{
/// <summary>
///
/// </summary>
/// <param name="currency1"></param>
/// <param name="currency2"></param>
/// <param name="quoteBasis"></param>
/// <returns></returns>
public static QuotedCurrencyPair Create(string currency1, string currency2, QuoteBasisEnum quoteBasis)
{
var quotedCurrencyPair = new QuotedCurrencyPair
{
currency1 = Parse(currency1),
currency2 = Parse(currency2),
quoteBasis = quoteBasis
};
return quotedCurrencyPair;
}
private static Currency Parse(string currencyCode)
{
var currency = new Currency { Value = currencyCode };
return currency;
}
}
}
| 33.630435 | 110 | 0.645766 | [
"BSD-3-Clause"
] | mmrath/Highlander.Net | Metadata/FpML.V5r10/FpML.V5r10.Reporting/QuotedCurrencyPair.cs | 1,549 | C# |
using System;
using System.Collections.Generic;
using System.Reflection;
namespace Neemo
{
public static class EnumerableExtensions
{
public static void ForEach<T>(this IEnumerable<T> items, Action<T> action)
{
foreach (var i in items)
{
action(i);
}
}
}
}
| 19.277778 | 82 | 0.56196 | [
"MIT"
] | wijayakoon/Unixmo | Neemo.Web/Neemo/Extensions/EnumerableExtensions.cs | 349 | C# |
using System.Collections.Generic;
using Microsoft.AspNetCore.Mvc;
using DreamClient.Models;
using Microsoft.AspNetCore.Authorization;
namespace DreamClient.Controllers
{
public class DreamsController : Controller
{
public IActionResult Index()
{
var allDreams = Dream.GetDreams();
return View(allDreams);
}
public IActionResult Create()
{
return View();
}
[HttpPost]
public IActionResult Create(Dream dream)
{
Dream.Post(dream);
return RedirectToAction("Index");
}
public IActionResult Filter(string search)
{
List<Dream> searchObject = new List<Dream> {};
var allDreams = Dream.GetDreams();
for (int i = 0; i < allDreams.Count; i++)
{
if (search != null && allDreams[i].Title.ToLower().Contains(search.ToLower()))
{
searchObject.Add(allDreams[i]);
}
}
return View(searchObject);
}
}
} | 26.575 | 90 | 0.557855 | [
"MIT"
] | fetonecontrol/DreamClient | Controllers/DreamsController.cs | 1,063 | C# |
using System.IO;
namespace Xameleon.Function {
public static class HttpWebResponseStream {
///<summary>
///</summary>
///<param name="stream"></param>
///<returns></returns>
public static string GetResponseString ( Stream stream ) {
using (StreamReader reader = new StreamReader(stream)) {
return reader.ReadToEnd();
}
}
}
}
| 24.555556 | 69 | 0.533937 | [
"BSD-3-Clause"
] | 3rdandUrban-dev/Nuxleus | linux-distro/package/nuxleus/Source/Xameleon/Function/HttpWebResponseStream.cs | 444 | C# |
using System.Linq;
using HotChocolate.Execution;
using NodaTime.Text;
using Xunit;
namespace HotChocolate.Types.NodaTime.Tests
{
public class OffsetDateTimeTypeExtendedIntegrationTests
{
private readonly IRequestExecutor testExecutor;
public OffsetDateTimeTypeExtendedIntegrationTests()
{
testExecutor = SchemaBuilder.New()
.AddQueryType<OffsetDateTimeTypeIntegrationTests.Schema.Query>()
.AddMutationType<OffsetDateTimeTypeIntegrationTests.Schema.Mutation>()
.AddNodaTime(typeof(OffsetDateTimeType))
.AddType(new OffsetDateTimeType(OffsetDateTimePattern.ExtendedIso))
.Create()
.MakeExecutable();
}
[Fact]
public void QueryReturns()
{
IExecutionResult? result = testExecutor.Execute("query { test: hours }");
var queryResult = result as IReadOnlyQueryResult;
Assert.Equal("2020-12-31T18:30:13.000001234+02", queryResult!.Data!["test"]);
}
[Fact]
public void QueryReturnsWithMinutes()
{
IExecutionResult? result = testExecutor.Execute("query { test: hoursAndMinutes }");
var queryResult = result as IReadOnlyQueryResult;
Assert.Equal("2020-12-31T18:30:13.000001234+02:30", queryResult!.Data!["test"]);
}
[Fact]
public void ParsesVariable()
{
IExecutionResult? result = testExecutor
.Execute(QueryRequestBuilder.New()
.SetQuery("mutation($arg: OffsetDateTime!) { test(arg: $arg) }")
.SetVariableValue("arg", "2020-12-31T18:30:13+02")
.Create());
var queryResult = result as IReadOnlyQueryResult;
Assert.Equal("2020-12-31T18:40:13+02", queryResult!.Data!["test"]);
}
[Fact]
public void ParsesVariableWithMinutes()
{
IExecutionResult? result = testExecutor
.Execute(QueryRequestBuilder.New()
.SetQuery("mutation($arg: OffsetDateTime!) { test(arg: $arg) }")
.SetVariableValue("arg", "2020-12-31T18:30:13+02:35")
.Create());
var queryResult = result as IReadOnlyQueryResult;
Assert.Equal("2020-12-31T18:40:13+02:35", queryResult!.Data!["test"]);
}
[Fact]
public void DoesntParseAnIncorrectVariable()
{
IExecutionResult? result = testExecutor
.Execute(QueryRequestBuilder.New()
.SetQuery("mutation($arg: OffsetDateTime!) { test(arg: $arg) }")
.SetVariableValue("arg", "2020-12-31T18:30:13")
.Create());
var queryResult = result as IReadOnlyQueryResult;
Assert.Null(queryResult!.Data);
Assert.Equal(1, queryResult!.Errors!.Count);
}
[Fact]
public void ParsesLiteral()
{
IExecutionResult? result = testExecutor
.Execute(QueryRequestBuilder.New()
.SetQuery("mutation { test(arg: \"2020-12-31T18:30:13+02\") }")
.Create());
var queryResult = result as IReadOnlyQueryResult;
Assert.Equal("2020-12-31T18:40:13+02", queryResult!.Data!["test"]);
}
[Fact]
public void ParsesLiteralWithMinutes()
{
IExecutionResult? result = testExecutor
.Execute(QueryRequestBuilder.New()
.SetQuery("mutation { test(arg: \"2020-12-31T18:30:13+02:35\") }")
.Create());
var queryResult = result as IReadOnlyQueryResult;
Assert.Equal("2020-12-31T18:40:13+02:35", queryResult!.Data!["test"]);
}
[Fact]
public void DoesntParseIncorrectLiteral()
{
IExecutionResult? result = testExecutor
.Execute(QueryRequestBuilder.New()
.SetQuery("mutation { test(arg: \"2020-12-31T18:30:13\") }")
.Create());
var queryResult = result as IReadOnlyQueryResult;
Assert.Null(queryResult!.Data);
Assert.Equal(1, queryResult!.Errors!.Count);
Assert.Null(queryResult.Errors[0].Code);
Assert.Equal(
"Unable to deserialize string to OffsetDateTime",
queryResult.Errors[0].Message);
}
}
}
| 39.217391 | 95 | 0.566297 | [
"MIT"
] | dan-ferguson-unanet/hotchocolate | src/HotChocolate/Core/test/Types.NodaTime.Tests/OffsetDateTimeTypeExtendedIntegrationTests.cs | 4,510 | C# |
namespace BullOak.Test.Benchmark.Behavioural
{
using System;
public interface IInterface
{
int Count { get; set; }
string Name { get; set; }
}
internal class TestClass : IInterface
{
public bool canEdit = false;
private int _count;
public int Count
{
get { return _count; }
set
{
if (canEdit) _count = value;
else
throw new Exception("You can only edit this item during reconstitution");
}
}
public string Name { get; set; }
}
}
| 20.866667 | 93 | 0.5 | [
"MIT"
] | BullOak/BullOak | src/BullOak.Test.Benchmark/Behavioural/TestClass.cs | 628 | C# |
using System;
namespace Peddler {
/// <summary>
/// A base exception for when an <see cref="IComparableGenerator{T}" />
/// or <see cref="IDistinctGenerator{T}" /> is unable to generate values
/// because their internal constraints are incompatible with the value provided.
/// </summary>
/// <remarks>
/// For example, this would be raised if an <see cref="IComparableGenerator{Int32}" />
/// was asked to generate a value that is less than <see cref="Int32.MinValue" />.
/// The generator could not fulfill that request as no <see cref="Int32" /> can be
/// less than the type's minimum value, so this exception would be thrown.
/// </remarks>
public class UnableToGenerateValueException : ArgumentException {
/// <summary>
/// Instantiates an <see cref="UnableToGenerateValueException" /> for use when
/// a generator cannot create a value that fulfills the caller's request.
/// </summary>
public UnableToGenerateValueException() :
base() {}
/// <summary>
/// Instantiates an <see cref="UnableToGenerateValueException" /> for use when
/// a generator cannot create a value that fulfills the caller's request.
/// </summary>
/// <param name="message">
/// An explanation as to why the generator could not create a value.
/// </param>
public UnableToGenerateValueException(String message) :
base(message) {}
/// <summary>
/// Instantiates an <see cref="UnableToGenerateValueException" /> for use when
/// a generator cannot create a value that fulfills the caller's request.
/// </summary>
/// <param name="message">
/// An explanation as to why the generator could not create a value.
/// </param>
/// <param name="paramName">
/// The name of the parameter the caller provided which referenced a value
/// that was incompatible with the generator.
/// </param>
public UnableToGenerateValueException(String message, String paramName) :
base(message, paramName) {}
/// <summary>
/// Instantiates an <see cref="UnableToGenerateValueException" /> for use when
/// a generator cannot create a value that fulfills the caller's request.
/// </summary>
/// <param name="message">
/// An explanation as to why the generator could not create a value.
/// </param>
/// <param name="innerException">
/// A lower-level exception that caused this exception to occur.
/// </param>
public UnableToGenerateValueException(String message, Exception innerException) :
base(message, innerException) {}
/// <summary>
/// Instantiates an <see cref="UnableToGenerateValueException" /> for use when
/// a generator cannot create a value that fulfills the caller's request.
/// </summary>
/// <param name="message">
/// An explanation as to why the generator could not create a value.
/// </param>
/// <param name="paramName">
/// The name of the parameter the caller provided which referenced a value
/// that was incompatible with the generator.
/// </param>
/// <param name="innerException">
/// A lower-level exception that caused this exception to occur.
/// </param>
public UnableToGenerateValueException(
String message,
String paramName,
Exception innerException) :
base(message, paramName, innerException) {}
}
}
| 43.788235 | 92 | 0.607738 | [
"MIT"
] | invio/Peddler | src/Peddler/UnableToGenerateValueException.cs | 3,722 | C# |
///-------------------------------------------------------------------------------------------------
// file: Elements\BasicElements\Segment.razor.cs
//
// summary: Implements the segment.razor class
///-------------------------------------------------------------------------------------------------
using Microsoft.AspNetCore.Authorization;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Fomantic
{
///-------------------------------------------------------------------------------------------------
/// <summary> A segment. </summary>
///
/// ### <inheritdoc/>
///-------------------------------------------------------------------------------------------------
public partial class Segment
{
/// <summary> Create new Segment. </summary>
public Segment()
{
Color = SegmentDefaults.ColorDefault;
ContentHorizontalAlignment = SegmentDefaults.ContentAlignmentDefault;
ContentSpace = SegmentDefaults.ContentSpaceDefault;
EnterTransition = SegmentDefaults.EnterTransitionDefault;
EnterTransitionDuration = SegmentDefaults.EnterTransitionDurationDefault;
Attaching = SegmentDefaults.AttachingDefault;
IsCircular = SegmentDefaults.IsCircularDefault;
IsCompact = SegmentDefaults.IsCompactDefault;
IsDisabled = SegmentDefaults.IsDisabledDefault;
IsInverted = SegmentDefaults.IsInvertedDefault;
IsLoading = SegmentDefaults.IsLoadingDefault;
IsPlaceholder = SegmentDefaults.IsPlaceholderDefault;
}
}
}
| 37.6 | 104 | 0.520686 | [
"MIT"
] | DotFomanticNet/fomantic-blazor | src/Fomantic.Blazor.UI/Components/BasicComponents/SegmantComponent/Segment.razor.cs | 1,694 | C# |
using System;
namespace Fault {
public interface Locateable {
Location getLocation();
Locateable getParent();
}
} | 15 | 30 | 0.733333 | [
"Apache-2.0"
] | YourWishes/FaultEnginev3 | Fault/FaultEngine/Location/Locateable.cs | 120 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace Portal.Testing {
public partial class TestRequest {
/// <summary>
/// mainform control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.HtmlControls.HtmlForm mainform;
}
}
| 30.56 | 84 | 0.465969 | [
"MIT"
] | mind0n/hive | Product/Website/Portal/Portal/Testing/TestRequest.aspx.designer.cs | 766 | C# |
using System;
using System.Web.UI.WebControls;
using CMS.FormEngine.Web.UI;
using CMS.Helpers;
/// <summary>
/// FormEngine control to select a period of time
/// </summary>
public partial class CMSModules_SharePoint_FormControls_TimeIntervalSelector : FormEngineUserControl
{
private const string MINUTES = "minutes";
private const string HOURS = "hours";
private bool mDropDownPopulated = false;
/// <summary>
/// Gets or sets the value of the control - Integer number of minutes
/// </summary>
public override object Value
{
get
{
return GetValue();
}
set
{
SetValue(value);
}
}
/// <summary>
/// Validates the input.
/// Sets ValidationError if input is not valid.
/// </summary>
/// <returns>True if input is valid.</returns>
public override bool IsValid()
{
// Verify the number
int quantity = ValidationHelper.GetInteger(txtQuantity.Text, -1);
if (quantity < 0)
{
ValidationError = GetString("basicform.errornotinteger");
return false;
}
// Verify that scale wasn't forged
string scale = drpScale.SelectedValue;
switch (scale)
{
case MINUTES:
case HOURS:
return true;
default:
return false;
}
}
/// <summary>
/// Ensures the nested controls are set up properly
/// </summary>
/// <param name="sender">Ignored</param>
/// <param name="e">Ignored</param>
protected void Page_Init(object sender, EventArgs e)
{
EnsureDropDownItems();
}
/// <summary>
/// Fills the drop-down menu with options. Only once.
/// </summary>
private void EnsureDropDownItems()
{
if (!mDropDownPopulated)
{
drpScale.Items.AddRange(new ListItem[] {
new ListItem(ResHelper.GetString("TimeIntervalSelector.Scale.Minutes"),MINUTES),
new ListItem(ResHelper.GetString("TimeIntervalSelector.Scale.Hours"),HOURS),
});
mDropDownPopulated = true;
}
}
/// <summary>
/// Gets the number of minutes
/// </summary>
/// <returns>Number of minutes</returns>
private object GetValue()
{
int quantity = ValidationHelper.GetInteger(txtQuantity.Text, -1);
if (quantity > 0)
{
var scale = drpScale.SelectedValue;
switch (scale)
{
case MINUTES:
return quantity;
case HOURS:
return TimeSpan.FromHours(quantity).TotalMinutes;
default:
return null;
}
}
return null;
}
/// <summary>
/// Sets nested controls' values to reflect the provided value
/// </summary>
/// <param name="value">Number of minutes</param>
private void SetValue(object value)
{
EnsureDropDownItems();
int minutes = ValidationHelper.GetInteger(value, -1);
if (minutes < 0)
{
return;
}
TimeSpan timeSpan = TimeSpan.FromMinutes(minutes);
if (timeSpan.Minutes == 0)
{
drpScale.SelectedValue = HOURS;
txtQuantity.Text = timeSpan.TotalHours.ToString();
}
else
{
drpScale.SelectedValue = MINUTES;
txtQuantity.Text = timeSpan.TotalMinutes.ToString();
}
}
} | 25.8125 | 101 | 0.531073 | [
"MIT"
] | CMeeg/kentico-contrib | src/CMS/CMSModules/Sharepoint/FormControls/TimeIntervalSelector.ascx.cs | 3,719 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace MarkupExtensionConverter.Properties
{
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0")]
internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase
{
private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
public static Settings Default
{
get
{
return defaultInstance;
}
}
}
}
| 34.806452 | 151 | 0.586654 | [
"MIT"
] | RenePeuser/MarkupExtensionConverter | MarkupExtensionConverter/MarkupExtensionConverter/Properties/Settings.Designer.cs | 1,081 | C# |
/*
Copyright 2014 Rustici Software
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using Newtonsoft.Json.Linq;
using System;
using TinCan.Json;
namespace TinCan
{
public class Verb : JsonModel
{
public Uri id { get; set; }
public LanguageMap display { get; set; }
public Verb() { }
public Verb(StringOfJSON json) : this(json.toJObject()) { }
public Verb(JObject jobj)
{
if (jobj["id"] != null)
{
id = new Uri(jobj.Value<string>("id"));
}
if (jobj["display"] != null)
{
display = (LanguageMap)jobj.Value<JObject>("display");
}
}
public Verb(Uri uri)
{
id = uri;
}
public Verb(string str)
{
id = new Uri(str);
}
public override JObject ToJObject(TCAPIVersion version)
{
var result = new JObject();
if (id != null)
{
result.Add("id", id.ToString());
}
if (display != null && !display.isEmpty())
{
result.Add("display", display.ToJObject(version));
}
return result;
}
public static explicit operator Verb(JObject jobj)
{
return new Verb(jobj);
}
}
}
| 25.4 | 76 | 0.542782 | [
"Apache-2.0"
] | cawerkenthin/xAPI.Net | Verb.cs | 1,907 | 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 Aliyun.Acs.Core;
using System.Collections.Generic;
namespace Aliyun.Acs.Cdn.Model.V20141111
{
public class DescribeDomainConfigsResponse : AcsResponse
{
public DomainConfigs_ DomainConfigs { get; set; }
public class DomainConfigs_{
public List<CacheExpiredConfig> CacheExpiredConfigs { get; set; }
public List<HttpHeaderConfig> HttpHeaderConfigs { get; set; }
public CcConfig_ CcConfig { get; set; }
public ErrorPageConfig_ ErrorPageConfig { get; set; }
public OptimizeConfig_ OptimizeConfig { get; set; }
public PageCompressConfig_ PageCompressConfig { get; set; }
public IgnoreQueryStringConfig_ IgnoreQueryStringConfig { get; set; }
public RangeConfig_ RangeConfig { get; set; }
public RefererConfig_ RefererConfig { get; set; }
public ReqAuthConfig_ ReqAuthConfig { get; set; }
public SrcHostConfig_ SrcHostConfig { get; set; }
public VideoSeekConfig_ VideoSeekConfig { get; set; }
public WafConfig_ WafConfig { get; set; }
public NotifyUrlConfig_ NotifyUrlConfig { get; set; }
public RedirectTypeConfig_ RedirectTypeConfig { get; set; }
public ForwardSchemeConfig_ ForwardSchemeConfig { get; set; }
public class CacheExpiredConfig{
public string ConfigId { get; set; }
public string CacheType { get; set; }
public string CacheContent { get; set; }
public string TTL { get; set; }
public string Weight { get; set; }
public string Status { get; set; }
}
public class HttpHeaderConfig{
public string ConfigId { get; set; }
public string HeaderKey { get; set; }
public string HeaderValue { get; set; }
public string Status { get; set; }
}
public class CcConfig_{
public string Enable { get; set; }
public string AllowIps { get; set; }
public string BlockIps { get; set; }
}
public class ErrorPageConfig_{
public string ErrorCode { get; set; }
public string PageType { get; set; }
public string CustomPageUrl { get; set; }
}
public class OptimizeConfig_{
public string Enable { get; set; }
}
public class PageCompressConfig_{
public string Enable { get; set; }
}
public class IgnoreQueryStringConfig_{
public string HashKeyArgs { get; set; }
public string Enable { get; set; }
}
public class RangeConfig_{
public string Enable { get; set; }
}
public class RefererConfig_{
public string ReferType { get; set; }
public string ReferList { get; set; }
public string AllowEmpty { get; set; }
}
public class ReqAuthConfig_{
public string AuthType { get; set; }
public string Key1 { get; set; }
public string Key2 { get; set; }
}
public class SrcHostConfig_{
public string DomainName { get; set; }
}
public class VideoSeekConfig_{
public string Enable { get; set; }
}
public class WafConfig_{
public string Enable { get; set; }
}
public class NotifyUrlConfig_{
public string Enable { get; set; }
public string NotifyUrl { get; set; }
}
public class RedirectTypeConfig_{
public string RedirectType { get; set; }
}
public class ForwardSchemeConfig_{
public string Enable { get; set; }
public string SchemeOrigin { get; set; }
public string SchemeOriginPort { get; set; }
}
}
}
} | 26.463855 | 78 | 0.651946 | [
"Apache-2.0"
] | VAllens/aliyun-openapi-sdk-net-core | src/aliyun-net-sdk-cdn/Model/V20141111/DescribeDomainConfigsResponse.cs | 4,393 | C# |
using System;
using System.Text;
namespace Animals
{
public class Cat : Animal
{
public Cat(string name, string favouriteFood)
: base(name, favouriteFood)
{
}
public override string ExplainSelf()
{
return base.ExplainSelf() + Environment.NewLine + "MEEOW";
}
}
}
| 17.333333 | 70 | 0.538462 | [
"MIT"
] | DeyanDanailov/SoftUni-OOP | Polymorphism/Animals/Cat.cs | 366 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
// Generation date: 1/20/2021 5:35:39 PM
namespace Microsoft.Dynamics.DataEntities
{
/// <summary>
/// There are no comments for SystemNotificationSingle in the schema.
/// </summary>
public partial class SystemNotificationSingle : global::Microsoft.OData.Client.DataServiceQuerySingle<SystemNotification>
{
/// <summary>
/// Initialize a new SystemNotificationSingle object.
/// </summary>
public SystemNotificationSingle(global::Microsoft.OData.Client.DataServiceContext context, string path)
: base(context, path) {}
/// <summary>
/// Initialize a new SystemNotificationSingle object.
/// </summary>
public SystemNotificationSingle(global::Microsoft.OData.Client.DataServiceContext context, string path, bool isComposable)
: base(context, path, isComposable) {}
/// <summary>
/// Initialize a new SystemNotificationSingle object.
/// </summary>
public SystemNotificationSingle(global::Microsoft.OData.Client.DataServiceQuerySingle<SystemNotification> query)
: base(query) {}
}
/// <summary>
/// There are no comments for SystemNotification in the schema.
/// </summary>
/// <KeyProperties>
/// RuleId
/// </KeyProperties>
[global::Microsoft.OData.Client.Key("RuleId")]
[global::Microsoft.OData.Client.EntitySet("SystemNotification")]
public partial class SystemNotification : global::Microsoft.OData.Client.BaseEntityType, global::System.ComponentModel.INotifyPropertyChanged
{
/// <summary>
/// Create a new SystemNotification object.
/// </summary>
/// <param name="ruleId">Initial value of RuleId.</param>
/// <param name="sequenceId">Initial value of SequenceId.</param>
/// <param name="reminderInterval">Initial value of ReminderInterval.</param>
/// <param name="expirationDateTime">Initial value of ExpirationDateTime.</param>
/// <param name="systemNotificationId">Initial value of SystemNotificationId.</param>
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")]
public static SystemNotification CreateSystemNotification(string ruleId, long sequenceId, long reminderInterval, global::System.DateTimeOffset expirationDateTime, long systemNotificationId)
{
SystemNotification systemNotification = new SystemNotification();
systemNotification.RuleId = ruleId;
systemNotification.SequenceId = sequenceId;
systemNotification.ReminderInterval = reminderInterval;
systemNotification.ExpirationDateTime = expirationDateTime;
systemNotification.SystemNotificationId = systemNotificationId;
return systemNotification;
}
/// <summary>
/// There are no comments for Property RuleId in the schema.
/// </summary>
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")]
public virtual string RuleId
{
get
{
return this._RuleId;
}
set
{
this.OnRuleIdChanging(value);
this._RuleId = value;
this.OnRuleIdChanged();
this.OnPropertyChanged("RuleId");
}
}
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")]
private string _RuleId;
partial void OnRuleIdChanging(string value);
partial void OnRuleIdChanged();
/// <summary>
/// There are no comments for Property Title in the schema.
/// </summary>
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")]
public virtual string Title
{
get
{
return this._Title;
}
set
{
this.OnTitleChanging(value);
this._Title = value;
this.OnTitleChanged();
this.OnPropertyChanged("Title");
}
}
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")]
private string _Title;
partial void OnTitleChanging(string value);
partial void OnTitleChanged();
/// <summary>
/// There are no comments for Property State in the schema.
/// </summary>
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")]
public virtual global::System.Nullable<global::Microsoft.Dynamics.DataEntities.SystemNotificationState> State
{
get
{
return this._State;
}
set
{
this.OnStateChanging(value);
this._State = value;
this.OnStateChanged();
this.OnPropertyChanged("State");
}
}
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")]
private global::System.Nullable<global::Microsoft.Dynamics.DataEntities.SystemNotificationState> _State;
partial void OnStateChanging(global::System.Nullable<global::Microsoft.Dynamics.DataEntities.SystemNotificationState> value);
partial void OnStateChanged();
/// <summary>
/// There are no comments for Property Message in the schema.
/// </summary>
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")]
public virtual string Message
{
get
{
return this._Message;
}
set
{
this.OnMessageChanging(value);
this._Message = value;
this.OnMessageChanged();
this.OnPropertyChanged("Message");
}
}
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")]
private string _Message;
partial void OnMessageChanging(string value);
partial void OnMessageChanged();
/// <summary>
/// There are no comments for Property Severity in the schema.
/// </summary>
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")]
public virtual global::System.Nullable<global::Microsoft.Dynamics.DataEntities.SystemNotificationSeverity> Severity
{
get
{
return this._Severity;
}
set
{
this.OnSeverityChanging(value);
this._Severity = value;
this.OnSeverityChanged();
this.OnPropertyChanged("Severity");
}
}
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")]
private global::System.Nullable<global::Microsoft.Dynamics.DataEntities.SystemNotificationSeverity> _Severity;
partial void OnSeverityChanging(global::System.Nullable<global::Microsoft.Dynamics.DataEntities.SystemNotificationSeverity> value);
partial void OnSeverityChanged();
/// <summary>
/// There are no comments for Property SequenceId in the schema.
/// </summary>
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")]
public virtual long SequenceId
{
get
{
return this._SequenceId;
}
set
{
this.OnSequenceIdChanging(value);
this._SequenceId = value;
this.OnSequenceIdChanged();
this.OnPropertyChanged("SequenceId");
}
}
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")]
private long _SequenceId;
partial void OnSequenceIdChanging(long value);
partial void OnSequenceIdChanged();
/// <summary>
/// There are no comments for Property ReminderInterval in the schema.
/// </summary>
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")]
public virtual long ReminderInterval
{
get
{
return this._ReminderInterval;
}
set
{
this.OnReminderIntervalChanging(value);
this._ReminderInterval = value;
this.OnReminderIntervalChanged();
this.OnPropertyChanged("ReminderInterval");
}
}
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")]
private long _ReminderInterval;
partial void OnReminderIntervalChanging(long value);
partial void OnReminderIntervalChanged();
/// <summary>
/// There are no comments for Property Type in the schema.
/// </summary>
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")]
public virtual global::System.Nullable<global::Microsoft.Dynamics.DataEntities.SystemNotificationType> Type
{
get
{
return this._Type;
}
set
{
this.OnTypeChanging(value);
this._Type = value;
this.OnTypeChanged();
this.OnPropertyChanged("Type");
}
}
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")]
private global::System.Nullable<global::Microsoft.Dynamics.DataEntities.SystemNotificationType> _Type;
partial void OnTypeChanging(global::System.Nullable<global::Microsoft.Dynamics.DataEntities.SystemNotificationType> value);
partial void OnTypeChanged();
/// <summary>
/// There are no comments for Property ExpirationDateTime in the schema.
/// </summary>
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")]
public virtual global::System.DateTimeOffset ExpirationDateTime
{
get
{
return this._ExpirationDateTime;
}
set
{
this.OnExpirationDateTimeChanging(value);
this._ExpirationDateTime = value;
this.OnExpirationDateTimeChanged();
this.OnPropertyChanged("ExpirationDateTime");
}
}
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")]
private global::System.DateTimeOffset _ExpirationDateTime;
partial void OnExpirationDateTimeChanging(global::System.DateTimeOffset value);
partial void OnExpirationDateTimeChanged();
/// <summary>
/// There are no comments for Property SystemNotificationId in the schema.
/// </summary>
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")]
public virtual long SystemNotificationId
{
get
{
return this._SystemNotificationId;
}
set
{
this.OnSystemNotificationIdChanging(value);
this._SystemNotificationId = value;
this.OnSystemNotificationIdChanged();
this.OnPropertyChanged("SystemNotificationId");
}
}
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")]
private long _SystemNotificationId;
partial void OnSystemNotificationIdChanging(long value);
partial void OnSystemNotificationIdChanged();
/// <summary>
/// This event is raised when the value of the property is changed
/// </summary>
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")]
public event global::System.ComponentModel.PropertyChangedEventHandler PropertyChanged;
/// <summary>
/// The value of the property is changed
/// </summary>
/// <param name="property">property name</param>
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")]
protected virtual void OnPropertyChanged(string property)
{
if ((this.PropertyChanged != null))
{
this.PropertyChanged(this, new global::System.ComponentModel.PropertyChangedEventArgs(property));
}
}
}
}
| 44.687296 | 197 | 0.609884 | [
"MIT"
] | NathanClouseAX/AAXDataEntityPerfTest | Projects/AAXDataEntityPerfTest/ODataUtility/Connected Services/D365/SystemNotification.cs | 13,721 | C# |
namespace DEVisIT.SiFatto.ApplicationCore.Interfaces.Services
{
public interface IQuestionService
{
}
}
| 16.714286 | 62 | 0.74359 | [
"MIT"
] | andreadottor/DEVisIT.SiFatto | src/DEVisIT.SiFatto.ApplicationCore/Interfaces/Services/IQuestionService.cs | 119 | C# |
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using Shouldly;
using Xunit;
using Abp.Application.Services.Dto;
using SE347.L11_HelloWork.Users;
using SE347.L11_HelloWork.Users.Dto;
namespace SE347.L11_HelloWork.Tests.Users
{
public class UserAppService_Tests : L11_HelloWorkTestBase
{
private readonly IUserAppService _userAppService;
public UserAppService_Tests()
{
_userAppService = Resolve<IUserAppService>();
}
[Fact]
public async Task GetUsers_Test()
{
// Act
var output = await _userAppService.GetAllAsync(new PagedUserResultRequestDto{MaxResultCount=20, SkipCount=0} );
// Assert
output.Items.Count.ShouldBeGreaterThan(0);
}
[Fact]
public async Task CreateUser_Test()
{
// Act
await _userAppService.CreateAsync(
new CreateUserDto
{
EmailAddress = "john@volosoft.com",
IsActive = true,
Name = "John",
Surname = "Nash",
Password = "123qwe",
UserName = "john.nash"
});
await UsingDbContextAsync(async context =>
{
var johnNashUser = await context.Users.FirstOrDefaultAsync(u => u.UserName == "john.nash");
johnNashUser.ShouldNotBeNull();
});
}
}
}
| 28.45283 | 123 | 0.558355 | [
"MIT"
] | NgocSon288/HelloWork | aspnet-core/test/SE347.L11_HelloWork.Tests/Users/UserAppService_Tests.cs | 1,510 | C# |
using System.Linq;
using BenchmarkDotNet.Environments;
using JetBrains.Annotations;
namespace BenchmarkDotNet.Reports
{
public static class BenchmarkReportExtensions
{
private const string DisplayedRuntimeInfoPrefix = "// " + BenchmarkEnvironmentInfo.RuntimeInfoPrefix;
private const string DisplayedGcInfoPrefix = "// " + BenchmarkEnvironmentInfo.GcInfoPrefix;
[CanBeNull]
public static string GetRuntimeInfo(this BenchmarkReport report) => report.GetInfoFromOutput(DisplayedRuntimeInfoPrefix);
[CanBeNull]
public static string GetGcInfo(this BenchmarkReport report) => report.GetInfoFromOutput(DisplayedGcInfoPrefix);
[CanBeNull]
private static string GetInfoFromOutput(this BenchmarkReport report, string prefix)
{
return (
from executeResults in report.ExecuteResults
from extraOutputLine in executeResults.ExtraOutput.Where(line => line.StartsWith(prefix))
select extraOutputLine.Substring(prefix.Length)).FirstOrDefault();
}
}
} | 40.407407 | 129 | 0.718607 | [
"MIT"
] | AlexGhiondea/BenchmarkDotNet | src/BenchmarkDotNet.Core/Reports/BenchmarkReportExtensions.cs | 1,093 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DS4WinWPF;
using Nefarius.ViGEm.Client;
using Nefarius.ViGEm.Client.Targets;
using Nefarius.ViGEm.Client.Targets.Xbox360;
namespace DS4Windows
{
public class Xbox360OutDevice : OutputDevice
{
private const int inputResolution = 127 - (-128);
private const float reciprocalInputResolution = 1 / (float)inputResolution;
private const int outputResolution = 32767 - (-32768);
public const string devType = "X360";
public Xbox360Controller cont;
private Xbox360Report report;
public Xbox360OutDevice(ViGEmClient client)
{
cont = new Xbox360Controller(client);
report = new Xbox360Report();
}
public override void ConvertandSendReport(DS4State state, int device)
{
Xbox360Buttons tempButtons = 0;
unchecked
{
if (state.Share) tempButtons |= Xbox360Buttons.Back;
if (state.L3) tempButtons |= Xbox360Buttons.LeftThumb;
if (state.R3) tempButtons |= Xbox360Buttons.RightThumb;
if (state.Options) tempButtons |= Xbox360Buttons.Start;
if (state.DpadUp) tempButtons |= Xbox360Buttons.Up;
if (state.DpadRight) tempButtons |= Xbox360Buttons.Right;
if (state.DpadDown) tempButtons |= Xbox360Buttons.Down;
if (state.DpadLeft) tempButtons |= Xbox360Buttons.Left;
if (state.L1) tempButtons |= Xbox360Buttons.LeftShoulder;
if (state.R1) tempButtons |= Xbox360Buttons.RightShoulder;
if (state.Triangle) tempButtons |= Xbox360Buttons.Y;
if (state.Circle) tempButtons |= Xbox360Buttons.B;
if (state.Cross) tempButtons |= Xbox360Buttons.A;
if (state.Square) tempButtons |= Xbox360Buttons.X;
if (state.PS) tempButtons |= Xbox360Buttons.Guide;
report.SetButtonsFull(tempButtons);
}
report.LeftTrigger = state.L2;
report.RightTrigger = state.R2;
SASteeringWheelEmulationAxisType steeringWheelMappedAxis = Global.GetSASteeringWheelEmulationAxis(device);
switch (steeringWheelMappedAxis)
{
case SASteeringWheelEmulationAxisType.None:
report.LeftThumbX = AxisScale(state.LX, false);
report.LeftThumbY = AxisScale(state.LY, true);
report.RightThumbX = AxisScale(state.RX, false);
report.RightThumbY = AxisScale(state.RY, true);
break;
case SASteeringWheelEmulationAxisType.LX:
report.LeftThumbX = (short)state.SASteeringWheelEmulationUnit;
report.LeftThumbY = AxisScale(state.LY, true);
report.RightThumbX = AxisScale(state.RX, false);
report.RightThumbY = AxisScale(state.RY, true);
break;
case SASteeringWheelEmulationAxisType.LY:
report.LeftThumbX = AxisScale(state.LX, false);
report.LeftThumbY = (short)state.SASteeringWheelEmulationUnit;
report.RightThumbX = AxisScale(state.RX, false);
report.RightThumbY = AxisScale(state.RY, true);
break;
case SASteeringWheelEmulationAxisType.RX:
report.LeftThumbX = AxisScale(state.LX, false);
report.LeftThumbY = AxisScale(state.LY, true);
report.RightThumbX = (short)state.SASteeringWheelEmulationUnit;
report.RightThumbY = AxisScale(state.RY, true);
break;
case SASteeringWheelEmulationAxisType.RY:
report.LeftThumbX = AxisScale(state.LX, false);
report.LeftThumbY = AxisScale(state.LY, true);
report.RightThumbX = AxisScale(state.RX, false);
report.RightThumbY = (short)state.SASteeringWheelEmulationUnit;
break;
case SASteeringWheelEmulationAxisType.L2R2:
report.LeftTrigger = report.RightTrigger = 0;
if (state.SASteeringWheelEmulationUnit >= 0) report.LeftTrigger = (Byte)state.SASteeringWheelEmulationUnit;
else report.RightTrigger = (Byte)state.SASteeringWheelEmulationUnit;
goto case SASteeringWheelEmulationAxisType.None;
case SASteeringWheelEmulationAxisType.VJoy1X:
case SASteeringWheelEmulationAxisType.VJoy2X:
DS4Windows.VJoyFeeder.vJoyFeeder.FeedAxisValue(state.SASteeringWheelEmulationUnit, ((((uint)steeringWheelMappedAxis) - ((uint)SASteeringWheelEmulationAxisType.VJoy1X)) / 3) + 1, DS4Windows.VJoyFeeder.HID_USAGES.HID_USAGE_X);
goto case SASteeringWheelEmulationAxisType.None;
case SASteeringWheelEmulationAxisType.VJoy1Y:
case SASteeringWheelEmulationAxisType.VJoy2Y:
DS4Windows.VJoyFeeder.vJoyFeeder.FeedAxisValue(state.SASteeringWheelEmulationUnit, ((((uint)steeringWheelMappedAxis) - ((uint)SASteeringWheelEmulationAxisType.VJoy1X)) / 3) + 1, DS4Windows.VJoyFeeder.HID_USAGES.HID_USAGE_Y);
goto case SASteeringWheelEmulationAxisType.None;
case SASteeringWheelEmulationAxisType.VJoy1Z:
case SASteeringWheelEmulationAxisType.VJoy2Z:
DS4Windows.VJoyFeeder.vJoyFeeder.FeedAxisValue(state.SASteeringWheelEmulationUnit, ((((uint)steeringWheelMappedAxis) - ((uint)SASteeringWheelEmulationAxisType.VJoy1X)) / 3) + 1, DS4Windows.VJoyFeeder.HID_USAGES.HID_USAGE_Z);
goto case SASteeringWheelEmulationAxisType.None;
default:
// Should never come here but just in case use the NONE case as default handler....
goto case SASteeringWheelEmulationAxisType.None;
}
ProcessLinker.ReceiveControllerReport(report, device);
cont.SendReport(report);
}
private short AxisScale(Int32 Value, Boolean Flip)
{
unchecked
{
Value -= 0x80;
//float temp = (Value - (-128)) / (float)inputResolution;
float temp = (Value - (-128)) * reciprocalInputResolution;
if (Flip) temp = (temp - 0.5f) * -1.0f + 0.5f;
return (short)(temp * outputResolution + (-32768));
}
}
public override void Connect() => cont.Connect();
public override void Disconnect() => cont.Disconnect();
public override string GetDeviceType() => devType;
}
}
| 47.737931 | 244 | 0.613984 | [
"MIT"
] | counter185/DS4Windows_Scriptable_Lightbar | DS4Windows/DS4Control/Xbox360OutDevice.cs | 6,924 | C# |
using Agencia.Infra.CrossCutting.DependencyRegistration;
using AutoMapper;
using Bankflix.API.Configurations;
using Bankflix.API.Mapper;
using Bankflix.API.Models;
using Clientes.Infra.CrossCutting.DependencyRegistration;
using Core.Domain.CommandHandlers;
using Core.Domain.Interfaces;
using Core.Domain.Notifications;
using Core.Domain.Repository;
using Core.Domain.Services;
using MediatR;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Movimentacoes.Infra.CrossCutting.DependencyRegistration;
namespace Bankflix.API
{
public class Startup
{
private readonly IConfiguration _configuration;
public Startup(IConfiguration configuration)
{
_configuration = configuration;
}
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
services.Configure<ApiBehaviorOptions>(options =>
{
options.SuppressModelStateInvalidFilter = true;
});
services.ConfigurarAutenticacao();
services.ConfigurarServicosFila();
services.AddAutoMapper();
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
services.AddScoped<IMediatorHandler, MediatorHandler>();
services.AddScoped<IUsuario, AspNetUser>();
services.AddMediatR(typeof(Startup));
services.AddScoped<INotificationHandler<DomainNotification>, DomainNotificationHandler>();
services.AddScoped<IMongoSequenceRepository, MongoSequenceRepository>();
services.AddHostedService<QueueHostedService>();
AutoMapperConfiguration.RegisterMappings();
BootstrapperAgencia.RegistrarServicos(services);
BootstrapperClientes.RegistrarServicos(services);
BootstrapperMovimentacoes.RegistrarServicos(services);
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
app.UseDeveloperExceptionPage();
app.UseHttpsRedirection();
app.UseRouting();
app.UseCors(c => c
.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader());
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints => endpoints.MapControllers());
}
}
}
| 34.584416 | 102 | 0.686819 | [
"MIT"
] | alexandrebeato/bankflix | server/src/Bankflix.API/Startup.cs | 2,663 | C# |
using System;
using Microsoft.EntityFrameworkCore.Migrations;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
namespace ThriveDevCenter.Server.Migrations
{
public partial class AddExternalServerModel : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "external_servers",
columns: table => new
{
id = table.Column<long>(type: "bigint", nullable: false)
.Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn),
ssh_key_file_name = table.Column<string>(type: "text", nullable: false),
xmin = table.Column<uint>(type: "xid", rowVersion: true, nullable: false),
created_at = table.Column<DateTime>(type: "timestamp without time zone", nullable: false),
updated_at = table.Column<DateTime>(type: "timestamp without time zone", nullable: false),
status = table.Column<int>(type: "integer", nullable: false),
status_last_checked = table.Column<DateTime>(type: "timestamp without time zone", nullable: false),
reservation_type = table.Column<int>(type: "integer", nullable: false),
reserved_for = table.Column<long>(type: "bigint", nullable: true),
public_address = table.Column<string>(type: "text", nullable: false),
running_since = table.Column<DateTime>(type: "timestamp without time zone", nullable: true),
provisioned_fully = table.Column<bool>(type: "boolean", nullable: false),
used_disk_space = table.Column<int>(type: "integer", nullable: false, defaultValue: -1),
clean_up_queued = table.Column<bool>(type: "boolean", nullable: false),
wants_maintenance = table.Column<bool>(type: "boolean", nullable: false),
last_maintenance = table.Column<DateTime>(type: "timestamp without time zone", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("pk_external_servers", x => x.id);
});
migrationBuilder.CreateIndex(
name: "ix_external_servers_public_address",
table: "external_servers",
column: "public_address",
unique: true);
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "external_servers");
}
}
}
| 52.538462 | 125 | 0.591874 | [
"MIT"
] | Revolutionary-Games/ThriveDevCenter | Server/Migrations/20210815094057_AddExternalServerModel.cs | 2,734 | C# |
using System;
using System.IO;
using System.Linq;
namespace _02LineNumbers
{
class Program
{
static void Main(string[] args)
{
string textPath = "text.txt";
string outputPath = "output.txt";
var textLines = File.ReadAllLines(textPath);
int lineCounter = 1;
foreach (var line in textLines)
{
int lettersCount = line.Count(char.IsLetter);
int punctuationCount = line.Count(char.IsPunctuation);
File.AppendAllText(outputPath, $"Line {lineCounter}: {line} ({lettersCount})({punctuationCount}){Environment.NewLine}");
lineCounter++;
}
}
}
}
| 24.233333 | 136 | 0.555708 | [
"MIT"
] | kalintsenkov/SoftUni-Software-Engineering | CSharp-Advanced/Homeworks-And-Labs/04StreamsAndFilesExercise/02LineNumbers/Program.cs | 729 | C# |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using Microsoft.AspNetCore.Mvc;
namespace ControllersFromServicesClassLibrary
{
public class Inventory : ResourcesController
{
[HttpGet]
public IActionResult Get()
{
return new ContentResult { Content = "4" };
}
}
} | 27.5 | 111 | 0.675 | [
"Apache-2.0"
] | 06b/AspNetCore | src/Mvc/test/WebSites/ControllersFromServicesClassLibrary/Inventory.cs | 440 | C# |
// WARNING
//
// This file has been generated automatically by Xamarin Studio to store outlets and
// actions made in the UI designer. If it is removed, they will be lost.
// Manual changes to this file may not be handled correctly.
//
using Foundation;
using System.CodeDom.Compiler;
namespace FrenchPhraseBook
{
[Register ("WorkController")]
partial class WorkController
{
void ReleaseDesignerOutlets ()
{
}
}
}
| 20.380952 | 84 | 0.738318 | [
"Apache-2.0"
] | TheArchitect123/Tongue-Twister- | CategoryControllers/WorkController.designer.cs | 428 | C# |
// Copyright (c) MOSA Project. Licensed under the New BSD License.
namespace Mosa.Compiler.Framework.CIL
{
/// <summary>
/// Load Instruction
/// </summary>
/// <seealso cref="Mosa.Compiler.Framework.CIL.BaseCILInstruction" />
public class LoadInstruction : BaseCILInstruction
{
#region Construction
/// <summary>
/// Initializes a new instance of the <see cref="LoadInstruction"/> class.
/// </summary>
/// <param name="opCode">The op code.</param>
public LoadInstruction(OpCode opCode)
: base(opCode, 1, 1)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="LoadInstruction"/> class.
/// </summary>
/// <param name="code">The code.</param>
/// <param name="operandCount">The number of operands of the load.</param>
protected LoadInstruction(OpCode code, byte operandCount)
: base(code, operandCount, 1)
{
}
#endregion Construction
}
}
| 25.857143 | 76 | 0.674033 | [
"BSD-3-Clause"
] | AnErrupTion/MOSA-Project | Source/Mosa.Compiler.Framework/CIL/LoadInstruction.cs | 907 | C# |
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
// **NOTE** This file was generated by a tool and any changes will be overwritten.
// <auto-generated/>
// Template Source: Templates\CSharp\Requests\EntityRequestBuilder.cs.tt
namespace Microsoft.Graph
{
using System;
using System.Collections.Generic;
using System.IO;
/// <summary>
/// The type WindowsPhone81CertificateProfileBaseRequestBuilder.
/// </summary>
public partial class WindowsPhone81CertificateProfileBaseRequestBuilder : DeviceConfigurationRequestBuilder, IWindowsPhone81CertificateProfileBaseRequestBuilder
{
/// <summary>
/// Constructs a new WindowsPhone81CertificateProfileBaseRequestBuilder.
/// </summary>
/// <param name="requestUrl">The URL for the built request.</param>
/// <param name="client">The <see cref="IBaseClient"/> for handling requests.</param>
public WindowsPhone81CertificateProfileBaseRequestBuilder(
string requestUrl,
IBaseClient client)
: base(requestUrl, client)
{
}
/// <summary>
/// Builds the request.
/// </summary>
/// <returns>The built request.</returns>
public new IWindowsPhone81CertificateProfileBaseRequest Request()
{
return this.Request(null);
}
/// <summary>
/// Builds the request.
/// </summary>
/// <param name="options">The query and header options for the request.</param>
/// <returns>The built request.</returns>
public new IWindowsPhone81CertificateProfileBaseRequest Request(IEnumerable<Option> options)
{
return new WindowsPhone81CertificateProfileBaseRequest(this.RequestUrl, this.Client, options);
}
}
}
| 37.909091 | 164 | 0.610552 | [
"MIT"
] | OfficeGlobal/msgraph-beta-sdk-dotnet | src/Microsoft.Graph/Requests/Generated/WindowsPhone81CertificateProfileBaseRequestBuilder.cs | 2,085 | 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 medialive-2017-10-14.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.MediaLive.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using ThirdParty.Json.LitJson;
namespace Amazon.MediaLive.Model.Internal.MarshallTransformations
{
/// <summary>
/// MultiplexProgramServiceDescriptor Marshaller
/// </summary>
public class MultiplexProgramServiceDescriptorMarshaller : IRequestMarshaller<MultiplexProgramServiceDescriptor, 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(MultiplexProgramServiceDescriptor requestObject, JsonMarshallerContext context)
{
if(requestObject.IsSetProviderName())
{
context.Writer.WritePropertyName("providerName");
context.Writer.Write(requestObject.ProviderName);
}
if(requestObject.IsSetServiceName())
{
context.Writer.WritePropertyName("serviceName");
context.Writer.Write(requestObject.ServiceName);
}
}
/// <summary>
/// Singleton Marshaller.
/// </summary>
public readonly static MultiplexProgramServiceDescriptorMarshaller Instance = new MultiplexProgramServiceDescriptorMarshaller();
}
} | 35.794118 | 141 | 0.67009 | [
"Apache-2.0"
] | philasmar/aws-sdk-net | sdk/src/Services/MediaLive/Generated/Model/Internal/MarshallTransformations/MultiplexProgramServiceDescriptorMarshaller.cs | 2,434 | C# |
namespace MassTransit.JobService.Components
{
using System;
using System.Threading.Tasks;
using GreenPipes.Internals.Extensions;
public class ConsumerJobHandle<T> :
JobHandle
where T : class
{
readonly ConsumeJobContext<T> _context;
public ConsumerJobHandle(ConsumeJobContext<T> context, Task task)
{
_context = context;
JobTask = task;
}
public Guid JobId => _context.JobId;
public Task JobTask { get; }
public async Task Cancel()
{
if (_context.CancellationToken.IsCancellationRequested)
return;
_context.Cancel();
try
{
await JobTask.OrTimeout(TimeSpan.FromSeconds(30)).ConfigureAwait(false);
}
catch (OperationCanceledException)
{
}
}
}
}
| 22.875 | 88 | 0.556284 | [
"ECL-2.0",
"Apache-2.0"
] | AhmedKhalil777/MassTransit | src/MassTransit/JobService/Components/ConsumerJobHandle.cs | 917 | C# |
namespace DEVisIT.SiFatto.Infrastructure
{
using DEVisIT.SiFatto.ApplicationCore.Interfaces.Repositories;
using DEVisIT.SiFatto.ApplicationCore.Interfaces.Services;
using DEVisIT.SiFatto.Infrastructure.Repositories;
using DEVisIT.SiFatto.Infrastructure.Services;
using Microsoft.Extensions.DependencyInjection;
public static class DependencyInjection
{
public static IServiceCollection AddInfrastructure(
this IServiceCollection services)
{
services.AddScoped<IQuestionRepository, QuestionRepository>();
services.AddScoped<IMailService, MailService>();
return services;
}
}
}
| 33.272727 | 81 | 0.67623 | [
"MIT"
] | andreadottor/DEVisIT.SiFatto | src/DEVisIT.SiFatto.Infrastructure/DependencyInjection.cs | 734 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.ComponentModel;
using System.Drawing;
namespace Yggdrasil.Controls
{
class GridEditControl : Panel
{
public event EventHandler<TileClickEventArgs> TileClick;
protected override CreateParams CreateParams
{
get
{
CreateParams cp = base.CreateParams;
cp.ExStyle |= 0x02000000; // WS_EX_COMPOSITED
return cp;
}
}
[DefaultValue(typeof(Color), "Black")]
public override Color BackColor
{
get { return base.BackColor; }
set { base.BackColor = value; }
}
int columns;
[DefaultValue(8)]
public int Columns { get { return columns; } set { columns = value; UpdateDisplay(); } }
int rows;
[DefaultValue(8)]
public int Rows { get { return rows; } set { rows = value; UpdateDisplay(); } }
Size tileSize;
[DefaultValue(typeof(Size), "8, 8")]
public Size TileSize { get { return tileSize; } set { tileSize = value; UpdateDisplay(); } }
int tileGap;
[DefaultValue(2)]
public int TileGap { get { return tileGap; } set { tileGap = value; UpdateDisplay(); } }
int zoom;
[DefaultValue(1), NotifyParentProperty(true), RefreshProperties(RefreshProperties.Repaint)]
public int Zoom { get { return zoom; } set { zoom = value; UpdateDisplay(); } }
bool showGrid;
[DefaultValue(false)]
public bool ShowGrid { get { return showGrid; } set { showGrid = value; UpdateDisplay(); } }
Color gridColor;
[DefaultValue(typeof(Color), "128, 128, 128, 128")]
public Color GridColor { get { return gridColor; } set { gridColor = value; UpdateDisplay(); } }
protected override Size DefaultSize
{
get { return new Size(zoom * tileSize.Width, zoom * tileSize.Height); }
}
public override Size MinimumSize
{
get { return DefaultSize; }
}
[DefaultValue(true), Browsable(false), EditorBrowsable(EditorBrowsableState.Never)]
public new bool AutoSize
{
get { return true; }
}
[DefaultValue(typeof(System.Windows.Forms.AutoSizeMode), "GrowAndShrink"), Browsable(false), EditorBrowsable(EditorBrowsableState.Never)]
public new AutoSizeMode AutoSizeMode
{
get { return System.Windows.Forms.AutoSizeMode.GrowAndShrink; }
}
Size zoomedTileSize;
[Browsable(false), EditorBrowsable(EditorBrowsableState.Never)]
public Size ZoomedTileSize { get { return zoomedTileSize; } }
int zoomedTileGap;
[Browsable(false), EditorBrowsable(EditorBrowsableState.Never)]
public int ZoomedTileGap { get { return zoomedTileGap; } }
bool debug;
[Browsable(false), EditorBrowsable(EditorBrowsableState.Never)]
public bool Debug { get { return debug; } set { debug = value; UpdateDisplay(); } }
Point hoverTileCoords, selectedTileCoords;
Rectangle hoverTileRect, selectedTileRect;
public GridEditControl()
{
SetStyle(ControlStyles.OptimizedDoubleBuffer | ControlStyles.AllPaintingInWmPaint | ControlStyles.ResizeRedraw, true);
BackColor = Color.Black;
columns = 8;
rows = 8;
tileSize = new Size(8, 8);
tileGap = 2;
zoom = 1;
showGrid = false;
gridColor = Color.FromArgb(128, Color.Gray);
zoomedTileSize = Size.Empty;
zoomedTileGap = -1;
hoverTileCoords = selectedTileCoords = Point.Empty;
hoverTileRect = selectedTileRect = Rectangle.Empty;
debug = false;
}
private void UpdateDisplay()
{
zoomedTileSize = new Size(tileSize.Width * zoom, tileSize.Height * zoom);
zoomedTileGap = tileGap * zoom;
Invalidate();
OnResize(EventArgs.Empty);
}
protected override void OnResize(EventArgs eventargs)
{
Size newSize = new Size(Columns * (zoomedTileSize.Width + zoomedTileGap), Rows * (zoomedTileSize.Height + zoomedTileGap));
if (Size != newSize)
{
Size = newSize;
base.OnResize(eventargs);
}
}
protected override void OnMouseMove(MouseEventArgs e)
{
base.OnMouseMove(e);
hoverTileCoords = new Point((e.X / (zoomedTileSize.Width + zoomedTileGap)), (e.Y / (zoomedTileSize.Height + zoomedTileGap)));
hoverTileRect = new Rectangle(
hoverTileCoords.X * (zoomedTileSize.Width + zoomedTileGap), hoverTileCoords.Y * (zoomedTileSize.Height + zoomedTileGap),
zoomedTileSize.Width - 1, zoomedTileSize.Height - 1);
Invalidate();
}
protected override void OnMouseDown(MouseEventArgs e)
{
selectedTileCoords = new Point((e.X / (zoomedTileSize.Width + zoomedTileGap)), (e.Y / (zoomedTileSize.Height + zoomedTileGap)));
selectedTileRect = new Rectangle(
selectedTileCoords.X * (zoomedTileSize.Width + zoomedTileGap), selectedTileCoords.Y * (zoomedTileSize.Height + zoomedTileGap),
zoomedTileSize.Width - 1, zoomedTileSize.Height - 1);
Select();
TileClick?.Invoke(this, new TileClickEventArgs(e.Button, selectedTileCoords));
}
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
e.Graphics.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.None;
e.Graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.NearestNeighbor;
e.Graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.None;
if (showGrid)
{
using (SolidBrush brush = new SolidBrush(gridColor))
{
for (int x = 0; x < columns; x++)
{
for (int y = 0; y < rows; y++)
{
/* Right */
e.Graphics.FillRectangle(brush, new Rectangle(
x * (zoomedTileSize.Width + zoomedTileGap) + zoomedTileSize.Width, y * (zoomedTileSize.Height + zoomedTileGap),
zoomedTileGap, zoomedTileSize.Height));
/* Bottom */
e.Graphics.FillRectangle(brush, new Rectangle(
x * (zoomedTileSize.Width + zoomedTileGap), y * (zoomedTileSize.Height + zoomedTileGap) + zoomedTileSize.Height,
zoomedTileSize.Width, zoomedTileGap));
/* Corner */
e.Graphics.FillRectangle(brush, new Rectangle(
x * (zoomedTileSize.Width + zoomedTileGap) + zoomedTileSize.Width, y * (zoomedTileSize.Height + zoomedTileGap) + zoomedTileSize.Height,
zoomedTileGap, zoomedTileGap));
}
}
}
}
using (Pen pen = new Pen(Color.FromArgb(160, Color.Orange), 3.0f))
{
e.Graphics.DrawRectangle(pen, hoverTileRect);
if (debug) e.Graphics.DrawLine(pen, Point.Empty, hoverTileRect.Location);
}
using (Pen pen = new Pen(Color.FromArgb(160, Color.Red), 3.0f))
{
e.Graphics.DrawRectangle(pen, selectedTileRect);
if (debug) e.Graphics.DrawLine(pen, new Point(ClientRectangle.Right, ClientRectangle.Bottom), new Point(selectedTileRect.Right, selectedTileRect.Bottom));
}
if (debug) e.Graphics.DrawString(string.Format("Hover:{0}, Selected:{1}", hoverTileCoords, selectedTileCoords), SystemFonts.MessageBoxFont, Brushes.Yellow, Point.Empty);
}
protected override void OnPaintBackground(PaintEventArgs e)
{
e.Graphics.Clear(BackColor);
}
}
class TileClickEventArgs : EventArgs
{
public MouseButtons Button { get; private set; }
public Point Coordinates { get; private set; }
public TileClickEventArgs(MouseButtons button, Point coords)
{
Button = button;
Coordinates = coords;
}
}
}
| 31.008734 | 172 | 0.704126 | [
"MIT"
] | xdanieldzd/Yggdrasil | Yggdrasil/Controls/GridEditControl.cs | 7,103 | C# |
using System.Collections.Generic;
using Shouldly.Tests.TestHelpers;
namespace Shouldly.Tests.ShouldBe.EnumerableType
{
public class IgnoreOrderIEnumerableMethodYieldReturn : ShouldlyShouldTestScenario
{
protected override void ShouldPass()
{
GetEnumerable().ShouldBe(new[] {1}, true);
}
protected override void ShouldThrowAWobbly()
{
GetEnumerable().ShouldBe(new[] { 1, 2 }, true, "Some additional context");
}
protected override string ChuckedAWobblyErrorMessage
{
get
{
return @"GetEnumerable() should be [1, 2] (ignoring order) but GetEnumerable() is missing [2]
Additional Info:
Some additional context";
}
}
private static IEnumerable<int> GetEnumerable()
{
yield return 1;
}
}
}
| 26.058824 | 109 | 0.603837 | [
"BSD-3-Clause"
] | augustoproiete-forks/shouldly--shouldly | src/Shouldly.Tests/ShouldBe/EnumerableType/IgnoreOrderIEnumerableMethodYieldReturn.cs | 888 | C# |
using Pat.Subscriber.IoC;
using StructureMap;
namespace Pat.Subscriber.StructureMap4DependencyResolution
{
public class StructureMapDependencyResolver : StructureMapDependencyScope, IMessageDependencyResolver
{
public StructureMapDependencyResolver(IContainer container)
: base(container)
{
}
public IMessageDependencyScope BeginScope()
{
IContainer child = Container.GetNestedContainer();
return new StructureMapDependencyResolver(child);
}
}
}
| 27.25 | 105 | 0.697248 | [
"Apache-2.0"
] | Bigtalljosh/Pat.Subscriber | Pat.Subscriber.StructureMap4DependencyResolution/StructureMapDependencyResolver.cs | 547 | C# |
// Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gagvr = Google.Ads.GoogleAds.V2.Resources;
using gax = Google.Api.Gax;
using gaxgrpc = Google.Api.Gax.Grpc;
using pb = Google.Protobuf;
using pbwkt = Google.Protobuf.WellKnownTypes;
using grpccore = Grpc.Core;
using sys = System;
using sc = System.Collections;
using scg = System.Collections.Generic;
using sco = System.Collections.ObjectModel;
using st = System.Threading;
using stt = System.Threading.Tasks;
namespace Google.Ads.GoogleAds.V2.Services
{
/// <summary>
/// Settings for a <see cref="DynamicSearchAdsSearchTermViewServiceClient"/>.
/// </summary>
public sealed partial class DynamicSearchAdsSearchTermViewServiceSettings : gaxgrpc::ServiceSettingsBase
{
/// <summary>
/// Get a new instance of the default <see cref="DynamicSearchAdsSearchTermViewServiceSettings"/>.
/// </summary>
/// <returns>
/// A new instance of the default <see cref="DynamicSearchAdsSearchTermViewServiceSettings"/>.
/// </returns>
public static DynamicSearchAdsSearchTermViewServiceSettings GetDefault() => new DynamicSearchAdsSearchTermViewServiceSettings();
/// <summary>
/// Constructs a new <see cref="DynamicSearchAdsSearchTermViewServiceSettings"/> object with default settings.
/// </summary>
public DynamicSearchAdsSearchTermViewServiceSettings() { }
private DynamicSearchAdsSearchTermViewServiceSettings(DynamicSearchAdsSearchTermViewServiceSettings existing) : base(existing)
{
gax::GaxPreconditions.CheckNotNull(existing, nameof(existing));
GetDynamicSearchAdsSearchTermViewSettings = existing.GetDynamicSearchAdsSearchTermViewSettings;
OnCopy(existing);
}
partial void OnCopy(DynamicSearchAdsSearchTermViewServiceSettings existing);
/// <summary>
/// The filter specifying which RPC <see cref="grpccore::StatusCode"/>s are eligible for retry
/// for "Idempotent" <see cref="DynamicSearchAdsSearchTermViewServiceClient"/> RPC methods.
/// </summary>
/// <remarks>
/// The eligible RPC <see cref="grpccore::StatusCode"/>s for retry for "Idempotent" RPC methods are:
/// <list type="bullet">
/// <item><description><see cref="grpccore::StatusCode.DeadlineExceeded"/></description></item>
/// <item><description><see cref="grpccore::StatusCode.Unavailable"/></description></item>
/// </list>
/// </remarks>
public static sys::Predicate<grpccore::RpcException> IdempotentRetryFilter { get; } =
gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.DeadlineExceeded, grpccore::StatusCode.Unavailable);
/// <summary>
/// The filter specifying which RPC <see cref="grpccore::StatusCode"/>s are eligible for retry
/// for "NonIdempotent" <see cref="DynamicSearchAdsSearchTermViewServiceClient"/> RPC methods.
/// </summary>
/// <remarks>
/// There are no RPC <see cref="grpccore::StatusCode"/>s eligible for retry for "NonIdempotent" RPC methods.
/// </remarks>
public static sys::Predicate<grpccore::RpcException> NonIdempotentRetryFilter { get; } =
gaxgrpc::RetrySettings.FilterForStatusCodes();
/// <summary>
/// "Default" retry backoff for <see cref="DynamicSearchAdsSearchTermViewServiceClient"/> RPC methods.
/// </summary>
/// <returns>
/// The "Default" retry backoff for <see cref="DynamicSearchAdsSearchTermViewServiceClient"/> RPC methods.
/// </returns>
/// <remarks>
/// The "Default" retry backoff for <see cref="DynamicSearchAdsSearchTermViewServiceClient"/> RPC methods is defined as:
/// <list type="bullet">
/// <item><description>Initial delay: 5000 milliseconds</description></item>
/// <item><description>Maximum delay: 60000 milliseconds</description></item>
/// <item><description>Delay multiplier: 1.3</description></item>
/// </list>
/// </remarks>
public static gaxgrpc::BackoffSettings GetDefaultRetryBackoff() => new gaxgrpc::BackoffSettings(
delay: sys::TimeSpan.FromMilliseconds(5000),
maxDelay: sys::TimeSpan.FromMilliseconds(60000),
delayMultiplier: 1.3
);
/// <summary>
/// "Default" timeout backoff for <see cref="DynamicSearchAdsSearchTermViewServiceClient"/> RPC methods.
/// </summary>
/// <returns>
/// The "Default" timeout backoff for <see cref="DynamicSearchAdsSearchTermViewServiceClient"/> RPC methods.
/// </returns>
/// <remarks>
/// The "Default" timeout backoff for <see cref="DynamicSearchAdsSearchTermViewServiceClient"/> RPC methods is defined as:
/// <list type="bullet">
/// <item><description>Initial timeout: 3600000 milliseconds</description></item>
/// <item><description>Timeout multiplier: 1.0</description></item>
/// <item><description>Maximum timeout: 3600000 milliseconds</description></item>
/// </list>
/// </remarks>
public static gaxgrpc::BackoffSettings GetDefaultTimeoutBackoff() => new gaxgrpc::BackoffSettings(
delay: sys::TimeSpan.FromMilliseconds(3600000),
maxDelay: sys::TimeSpan.FromMilliseconds(3600000),
delayMultiplier: 1.0
);
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to
/// <c>DynamicSearchAdsSearchTermViewServiceClient.GetDynamicSearchAdsSearchTermView</c> and <c>DynamicSearchAdsSearchTermViewServiceClient.GetDynamicSearchAdsSearchTermViewAsync</c>.
/// </summary>
/// <remarks>
/// The default <c>DynamicSearchAdsSearchTermViewServiceClient.GetDynamicSearchAdsSearchTermView</c> and
/// <c>DynamicSearchAdsSearchTermViewServiceClient.GetDynamicSearchAdsSearchTermViewAsync</c> <see cref="gaxgrpc::RetrySettings"/> are:
/// <list type="bullet">
/// <item><description>Initial retry delay: 5000 milliseconds</description></item>
/// <item><description>Retry delay multiplier: 1.3</description></item>
/// <item><description>Retry maximum delay: 60000 milliseconds</description></item>
/// <item><description>Initial timeout: 3600000 milliseconds</description></item>
/// <item><description>Timeout multiplier: 1.0</description></item>
/// <item><description>Timeout maximum delay: 3600000 milliseconds</description></item>
/// </list>
/// Retry will be attempted on the following response status codes:
/// <list>
/// <item><description><see cref="grpccore::StatusCode.DeadlineExceeded"/></description></item>
/// <item><description><see cref="grpccore::StatusCode.Unavailable"/></description></item>
/// </list>
/// Default RPC expiration is 3600000 milliseconds.
/// </remarks>
public gaxgrpc::CallSettings GetDynamicSearchAdsSearchTermViewSettings { get; set; } = gaxgrpc::CallSettings.FromCallTiming(
gaxgrpc::CallTiming.FromRetry(new gaxgrpc::RetrySettings(
retryBackoff: GetDefaultRetryBackoff(),
timeoutBackoff: GetDefaultTimeoutBackoff(),
totalExpiration: gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(3600000)),
retryFilter: IdempotentRetryFilter
)));
/// <summary>
/// Creates a deep clone of this object, with all the same property values.
/// </summary>
/// <returns>A deep clone of this <see cref="DynamicSearchAdsSearchTermViewServiceSettings"/> object.</returns>
public DynamicSearchAdsSearchTermViewServiceSettings Clone() => new DynamicSearchAdsSearchTermViewServiceSettings(this);
}
/// <summary>
/// Builder class for <see cref="DynamicSearchAdsSearchTermViewServiceClient"/> to provide simple configuration of credentials, endpoint etc.
/// </summary>
public sealed partial class DynamicSearchAdsSearchTermViewServiceClientBuilder : gaxgrpc::ClientBuilderBase<DynamicSearchAdsSearchTermViewServiceClient>
{
/// <summary>
/// The settings to use for RPCs, or null for the default settings.
/// </summary>
public DynamicSearchAdsSearchTermViewServiceSettings Settings { get; set; }
/// <inheritdoc/>
public override DynamicSearchAdsSearchTermViewServiceClient Build()
{
Validate();
grpccore::CallInvoker callInvoker = CreateCallInvoker();
return DynamicSearchAdsSearchTermViewServiceClient.Create(callInvoker, Settings);
}
/// <inheritdoc />
public override async stt::Task<DynamicSearchAdsSearchTermViewServiceClient> BuildAsync(st::CancellationToken cancellationToken = default)
{
Validate();
grpccore::CallInvoker callInvoker = await CreateCallInvokerAsync(cancellationToken).ConfigureAwait(false);
return DynamicSearchAdsSearchTermViewServiceClient.Create(callInvoker, Settings);
}
/// <inheritdoc />
protected override gaxgrpc::ServiceEndpoint GetDefaultEndpoint() => DynamicSearchAdsSearchTermViewServiceClient.DefaultEndpoint;
/// <inheritdoc />
protected override scg::IReadOnlyList<string> GetDefaultScopes() => DynamicSearchAdsSearchTermViewServiceClient.DefaultScopes;
/// <inheritdoc />
protected override gaxgrpc::ChannelPool GetChannelPool() => DynamicSearchAdsSearchTermViewServiceClient.ChannelPool;
}
/// <summary>
/// DynamicSearchAdsSearchTermViewService client wrapper, for convenient use.
/// </summary>
public abstract partial class DynamicSearchAdsSearchTermViewServiceClient
{
/// <summary>
/// The default endpoint for the DynamicSearchAdsSearchTermViewService service, which is a host of "googleads.googleapis.com" and a port of 443.
/// </summary>
public static gaxgrpc::ServiceEndpoint DefaultEndpoint { get; } = new gaxgrpc::ServiceEndpoint("googleads.googleapis.com", 443);
/// <summary>
/// The default DynamicSearchAdsSearchTermViewService scopes.
/// </summary>
/// <remarks>
/// The default DynamicSearchAdsSearchTermViewService scopes are:
/// <list type="bullet">
/// </list>
/// </remarks>
public static scg::IReadOnlyList<string> DefaultScopes { get; } = new sco::ReadOnlyCollection<string>(new string[] {
});
private static readonly gaxgrpc::ChannelPool s_channelPool = new gaxgrpc::ChannelPool(DefaultScopes);
internal static gaxgrpc::ChannelPool ChannelPool => s_channelPool;
/// <summary>
/// Asynchronously creates a <see cref="DynamicSearchAdsSearchTermViewServiceClient"/>, applying defaults for all unspecified settings,
/// and creating a channel connecting to the given endpoint with application default credentials where
/// necessary. See the example for how to use custom credentials.
/// </summary>
/// <example>
/// This sample shows how to create a client using default credentials:
/// <code>
/// using Google.Ads.GoogleAds.V2.Services;
/// ...
/// // When running on Google Cloud Platform this will use the project Compute Credential.
/// // Or set the GOOGLE_APPLICATION_CREDENTIALS environment variable to the path of a JSON
/// // credential file to use that credential.
/// DynamicSearchAdsSearchTermViewServiceClient client = await DynamicSearchAdsSearchTermViewServiceClient.CreateAsync();
/// </code>
/// This sample shows how to create a client using credentials loaded from a JSON file:
/// <code>
/// using Google.Ads.GoogleAds.V2.Services;
/// using Google.Apis.Auth.OAuth2;
/// using Grpc.Auth;
/// using Grpc.Core;
/// ...
/// GoogleCredential cred = GoogleCredential.FromFile("/path/to/credentials.json");
/// Channel channel = new Channel(
/// DynamicSearchAdsSearchTermViewServiceClient.DefaultEndpoint.Host, DynamicSearchAdsSearchTermViewServiceClient.DefaultEndpoint.Port, cred.ToChannelCredentials());
/// DynamicSearchAdsSearchTermViewServiceClient client = DynamicSearchAdsSearchTermViewServiceClient.Create(channel);
/// ...
/// // Shutdown the channel when it is no longer required.
/// await channel.ShutdownAsync();
/// </code>
/// </example>
/// <param name="endpoint">Optional <see cref="gaxgrpc::ServiceEndpoint"/>.</param>
/// <param name="settings">Optional <see cref="DynamicSearchAdsSearchTermViewServiceSettings"/>.</param>
/// <returns>The task representing the created <see cref="DynamicSearchAdsSearchTermViewServiceClient"/>.</returns>
public static async stt::Task<DynamicSearchAdsSearchTermViewServiceClient> CreateAsync(gaxgrpc::ServiceEndpoint endpoint = null, DynamicSearchAdsSearchTermViewServiceSettings settings = null)
{
grpccore::Channel channel = await s_channelPool.GetChannelAsync(endpoint ?? DefaultEndpoint).ConfigureAwait(false);
return Create(channel, settings);
}
/// <summary>
/// Synchronously creates a <see cref="DynamicSearchAdsSearchTermViewServiceClient"/>, applying defaults for all unspecified settings,
/// and creating a channel connecting to the given endpoint with application default credentials where
/// necessary. See the example for how to use custom credentials.
/// </summary>
/// <example>
/// This sample shows how to create a client using default credentials:
/// <code>
/// using Google.Ads.GoogleAds.V2.Services;
/// ...
/// // When running on Google Cloud Platform this will use the project Compute Credential.
/// // Or set the GOOGLE_APPLICATION_CREDENTIALS environment variable to the path of a JSON
/// // credential file to use that credential.
/// DynamicSearchAdsSearchTermViewServiceClient client = DynamicSearchAdsSearchTermViewServiceClient.Create();
/// </code>
/// This sample shows how to create a client using credentials loaded from a JSON file:
/// <code>
/// using Google.Ads.GoogleAds.V2.Services;
/// using Google.Apis.Auth.OAuth2;
/// using Grpc.Auth;
/// using Grpc.Core;
/// ...
/// GoogleCredential cred = GoogleCredential.FromFile("/path/to/credentials.json");
/// Channel channel = new Channel(
/// DynamicSearchAdsSearchTermViewServiceClient.DefaultEndpoint.Host, DynamicSearchAdsSearchTermViewServiceClient.DefaultEndpoint.Port, cred.ToChannelCredentials());
/// DynamicSearchAdsSearchTermViewServiceClient client = DynamicSearchAdsSearchTermViewServiceClient.Create(channel);
/// ...
/// // Shutdown the channel when it is no longer required.
/// channel.ShutdownAsync().Wait();
/// </code>
/// </example>
/// <param name="endpoint">Optional <see cref="gaxgrpc::ServiceEndpoint"/>.</param>
/// <param name="settings">Optional <see cref="DynamicSearchAdsSearchTermViewServiceSettings"/>.</param>
/// <returns>The created <see cref="DynamicSearchAdsSearchTermViewServiceClient"/>.</returns>
public static DynamicSearchAdsSearchTermViewServiceClient Create(gaxgrpc::ServiceEndpoint endpoint = null, DynamicSearchAdsSearchTermViewServiceSettings settings = null)
{
grpccore::Channel channel = s_channelPool.GetChannel(endpoint ?? DefaultEndpoint);
return Create(channel, settings);
}
/// <summary>
/// Creates a <see cref="DynamicSearchAdsSearchTermViewServiceClient"/> which uses the specified channel for remote operations.
/// </summary>
/// <param name="channel">The <see cref="grpccore::Channel"/> for remote operations. Must not be null.</param>
/// <param name="settings">Optional <see cref="DynamicSearchAdsSearchTermViewServiceSettings"/>.</param>
/// <returns>The created <see cref="DynamicSearchAdsSearchTermViewServiceClient"/>.</returns>
public static DynamicSearchAdsSearchTermViewServiceClient Create(grpccore::Channel channel, DynamicSearchAdsSearchTermViewServiceSettings settings = null)
{
gax::GaxPreconditions.CheckNotNull(channel, nameof(channel));
return Create(new grpccore::DefaultCallInvoker(channel), settings);
}
/// <summary>
/// Creates a <see cref="DynamicSearchAdsSearchTermViewServiceClient"/> which uses the specified call invoker for remote operations.
/// </summary>
/// <param name="callInvoker">The <see cref="grpccore::CallInvoker"/> for remote operations. Must not be null.</param>
/// <param name="settings">Optional <see cref="DynamicSearchAdsSearchTermViewServiceSettings"/>.</param>
/// <returns>The created <see cref="DynamicSearchAdsSearchTermViewServiceClient"/>.</returns>
public static DynamicSearchAdsSearchTermViewServiceClient Create(grpccore::CallInvoker callInvoker, DynamicSearchAdsSearchTermViewServiceSettings settings = null)
{
gax::GaxPreconditions.CheckNotNull(callInvoker, nameof(callInvoker));
grpccore::Interceptors.Interceptor interceptor = settings?.Interceptor;
if (interceptor != null)
{
callInvoker = grpccore::Interceptors.CallInvokerExtensions.Intercept(callInvoker, interceptor);
}
DynamicSearchAdsSearchTermViewService.DynamicSearchAdsSearchTermViewServiceClient grpcClient = new DynamicSearchAdsSearchTermViewService.DynamicSearchAdsSearchTermViewServiceClient(callInvoker);
return new DynamicSearchAdsSearchTermViewServiceClientImpl(grpcClient, settings);
}
/// <summary>
/// Shuts down any channels automatically created by <see cref="Create(gaxgrpc::ServiceEndpoint, DynamicSearchAdsSearchTermViewServiceSettings)"/>
/// and <see cref="CreateAsync(gaxgrpc::ServiceEndpoint, DynamicSearchAdsSearchTermViewServiceSettings)"/>. Channels which weren't automatically
/// created are not affected.
/// </summary>
/// <remarks>After calling this method, further calls to <see cref="Create(gaxgrpc::ServiceEndpoint, DynamicSearchAdsSearchTermViewServiceSettings)"/>
/// and <see cref="CreateAsync(gaxgrpc::ServiceEndpoint, DynamicSearchAdsSearchTermViewServiceSettings)"/> will create new channels, which could
/// in turn be shut down by another call to this method.</remarks>
/// <returns>A task representing the asynchronous shutdown operation.</returns>
public static stt::Task ShutdownDefaultChannelsAsync() => s_channelPool.ShutdownChannelsAsync();
/// <summary>
/// The underlying gRPC DynamicSearchAdsSearchTermViewService client.
/// </summary>
public virtual DynamicSearchAdsSearchTermViewService.DynamicSearchAdsSearchTermViewServiceClient GrpcClient
{
get { throw new sys::NotImplementedException(); }
}
/// <summary>
/// Returns the requested dynamic search ads search term view in full detail.
/// </summary>
/// <param name="resourceName">
/// The resource name of the dynamic search ads search term view to fetch.
/// </param>
/// <param name="callSettings">
/// If not null, applies overrides to this RPC call.
/// </param>
/// <returns>
/// A Task containing the RPC response.
/// </returns>
public virtual stt::Task<gagvr::DynamicSearchAdsSearchTermView> GetDynamicSearchAdsSearchTermViewAsync(
string resourceName,
gaxgrpc::CallSettings callSettings = null) => GetDynamicSearchAdsSearchTermViewAsync(
new GetDynamicSearchAdsSearchTermViewRequest
{
ResourceName = gax::GaxPreconditions.CheckNotNullOrEmpty(resourceName, nameof(resourceName)),
},
callSettings);
/// <summary>
/// Returns the requested dynamic search ads search term view in full detail.
/// </summary>
/// <param name="resourceName">
/// The resource name of the dynamic search ads search term view to fetch.
/// </param>
/// <param name="cancellationToken">
/// A <see cref="st::CancellationToken"/> to use for this RPC.
/// </param>
/// <returns>
/// A Task containing the RPC response.
/// </returns>
public virtual stt::Task<gagvr::DynamicSearchAdsSearchTermView> GetDynamicSearchAdsSearchTermViewAsync(
string resourceName,
st::CancellationToken cancellationToken) => GetDynamicSearchAdsSearchTermViewAsync(
resourceName,
gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Returns the requested dynamic search ads search term view in full detail.
/// </summary>
/// <param name="resourceName">
/// The resource name of the dynamic search ads search term view to fetch.
/// </param>
/// <param name="callSettings">
/// If not null, applies overrides to this RPC call.
/// </param>
/// <returns>
/// The RPC response.
/// </returns>
public virtual gagvr::DynamicSearchAdsSearchTermView GetDynamicSearchAdsSearchTermView(
string resourceName,
gaxgrpc::CallSettings callSettings = null) => GetDynamicSearchAdsSearchTermView(
new GetDynamicSearchAdsSearchTermViewRequest
{
ResourceName = gax::GaxPreconditions.CheckNotNullOrEmpty(resourceName, nameof(resourceName)),
},
callSettings);
/// <summary>
/// Returns the requested dynamic search ads search term view in full detail.
/// </summary>
/// <param name="request">
/// The request object containing all of the parameters for the API call.
/// </param>
/// <param name="callSettings">
/// If not null, applies overrides to this RPC call.
/// </param>
/// <returns>
/// A Task containing the RPC response.
/// </returns>
public virtual stt::Task<gagvr::DynamicSearchAdsSearchTermView> GetDynamicSearchAdsSearchTermViewAsync(
GetDynamicSearchAdsSearchTermViewRequest request,
gaxgrpc::CallSettings callSettings = null)
{
throw new sys::NotImplementedException();
}
/// <summary>
/// Returns the requested dynamic search ads search term view in full detail.
/// </summary>
/// <param name="request">
/// The request object containing all of the parameters for the API call.
/// </param>
/// <param name="cancellationToken">
/// A <see cref="st::CancellationToken"/> to use for this RPC.
/// </param>
/// <returns>
/// A Task containing the RPC response.
/// </returns>
public virtual stt::Task<gagvr::DynamicSearchAdsSearchTermView> GetDynamicSearchAdsSearchTermViewAsync(
GetDynamicSearchAdsSearchTermViewRequest request,
st::CancellationToken cancellationToken) => GetDynamicSearchAdsSearchTermViewAsync(
request,
gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Returns the requested dynamic search ads search term view in full detail.
/// </summary>
/// <param name="request">
/// The request object containing all of the parameters for the API call.
/// </param>
/// <param name="callSettings">
/// If not null, applies overrides to this RPC call.
/// </param>
/// <returns>
/// The RPC response.
/// </returns>
public virtual gagvr::DynamicSearchAdsSearchTermView GetDynamicSearchAdsSearchTermView(
GetDynamicSearchAdsSearchTermViewRequest request,
gaxgrpc::CallSettings callSettings = null)
{
throw new sys::NotImplementedException();
}
}
/// <summary>
/// DynamicSearchAdsSearchTermViewService client wrapper implementation, for convenient use.
/// </summary>
public sealed partial class DynamicSearchAdsSearchTermViewServiceClientImpl : DynamicSearchAdsSearchTermViewServiceClient
{
private readonly gaxgrpc::ApiCall<GetDynamicSearchAdsSearchTermViewRequest, gagvr::DynamicSearchAdsSearchTermView> _callGetDynamicSearchAdsSearchTermView;
/// <summary>
/// Constructs a client wrapper for the DynamicSearchAdsSearchTermViewService service, with the specified gRPC client and settings.
/// </summary>
/// <param name="grpcClient">The underlying gRPC client.</param>
/// <param name="settings">The base <see cref="DynamicSearchAdsSearchTermViewServiceSettings"/> used within this client </param>
public DynamicSearchAdsSearchTermViewServiceClientImpl(DynamicSearchAdsSearchTermViewService.DynamicSearchAdsSearchTermViewServiceClient grpcClient, DynamicSearchAdsSearchTermViewServiceSettings settings)
{
GrpcClient = grpcClient;
DynamicSearchAdsSearchTermViewServiceSettings effectiveSettings = settings ?? DynamicSearchAdsSearchTermViewServiceSettings.GetDefault();
gaxgrpc::ClientHelper clientHelper = new gaxgrpc::ClientHelper(effectiveSettings);
_callGetDynamicSearchAdsSearchTermView = clientHelper.BuildApiCall<GetDynamicSearchAdsSearchTermViewRequest, gagvr::DynamicSearchAdsSearchTermView>(
GrpcClient.GetDynamicSearchAdsSearchTermViewAsync, GrpcClient.GetDynamicSearchAdsSearchTermView, effectiveSettings.GetDynamicSearchAdsSearchTermViewSettings)
.WithCallSettingsOverlay(request => gaxgrpc::CallSettings.FromHeader("x-goog-request-params", $"resource_name={request.ResourceName}"));
Modify_ApiCall(ref _callGetDynamicSearchAdsSearchTermView);
Modify_GetDynamicSearchAdsSearchTermViewApiCall(ref _callGetDynamicSearchAdsSearchTermView);
OnConstruction(grpcClient, effectiveSettings, clientHelper);
}
// Partial methods are named to (mostly) ensure there cannot be conflicts with RPC method names.
// Partial methods called for every ApiCall on construction.
// Allows modification of all the underlying ApiCall objects.
partial void Modify_ApiCall<TRequest, TResponse>(ref gaxgrpc::ApiCall<TRequest, TResponse> call)
where TRequest : class, pb::IMessage<TRequest>
where TResponse : class, pb::IMessage<TResponse>;
// Partial methods called for each ApiCall on construction.
// Allows per-RPC-method modification of the underlying ApiCall object.
partial void Modify_GetDynamicSearchAdsSearchTermViewApiCall(ref gaxgrpc::ApiCall<GetDynamicSearchAdsSearchTermViewRequest, gagvr::DynamicSearchAdsSearchTermView> call);
partial void OnConstruction(DynamicSearchAdsSearchTermViewService.DynamicSearchAdsSearchTermViewServiceClient grpcClient, DynamicSearchAdsSearchTermViewServiceSettings effectiveSettings, gaxgrpc::ClientHelper clientHelper);
/// <summary>
/// The underlying gRPC DynamicSearchAdsSearchTermViewService client.
/// </summary>
public override DynamicSearchAdsSearchTermViewService.DynamicSearchAdsSearchTermViewServiceClient GrpcClient { get; }
// Partial methods called on each request.
// Allows per-RPC-call modification to the request and CallSettings objects,
// before the underlying RPC is performed.
partial void Modify_GetDynamicSearchAdsSearchTermViewRequest(ref GetDynamicSearchAdsSearchTermViewRequest request, ref gaxgrpc::CallSettings settings);
/// <summary>
/// Returns the requested dynamic search ads search term view in full detail.
/// </summary>
/// <param name="request">
/// The request object containing all of the parameters for the API call.
/// </param>
/// <param name="callSettings">
/// If not null, applies overrides to this RPC call.
/// </param>
/// <returns>
/// A Task containing the RPC response.
/// </returns>
public override stt::Task<gagvr::DynamicSearchAdsSearchTermView> GetDynamicSearchAdsSearchTermViewAsync(
GetDynamicSearchAdsSearchTermViewRequest request,
gaxgrpc::CallSettings callSettings = null)
{
Modify_GetDynamicSearchAdsSearchTermViewRequest(ref request, ref callSettings);
return _callGetDynamicSearchAdsSearchTermView.Async(request, callSettings);
}
/// <summary>
/// Returns the requested dynamic search ads search term view in full detail.
/// </summary>
/// <param name="request">
/// The request object containing all of the parameters for the API call.
/// </param>
/// <param name="callSettings">
/// If not null, applies overrides to this RPC call.
/// </param>
/// <returns>
/// The RPC response.
/// </returns>
public override gagvr::DynamicSearchAdsSearchTermView GetDynamicSearchAdsSearchTermView(
GetDynamicSearchAdsSearchTermViewRequest request,
gaxgrpc::CallSettings callSettings = null)
{
Modify_GetDynamicSearchAdsSearchTermViewRequest(ref request, ref callSettings);
return _callGetDynamicSearchAdsSearchTermView.Sync(request, callSettings);
}
}
// Partial classes to enable page-streaming
}
| 54.759786 | 231 | 0.678473 | [
"Apache-2.0"
] | chrisdunelm/google-ads-dotnet | src/V2/Stubs/DynamicSearchAdsSearchTermViewServiceClient.cs | 30,775 | 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 codedeploy-2014-10-06.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.CodeDeploy.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using ThirdParty.Json.LitJson;
namespace Amazon.CodeDeploy.Model.Internal.MarshallTransformations
{
/// <summary>
/// Response Unmarshaller for ListApplications operation
/// </summary>
public class ListApplicationsResponseUnmarshaller : JsonResponseUnmarshaller
{
/// <summary>
/// Unmarshaller the response from the service to the response class.
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
public override AmazonWebServiceResponse Unmarshall(JsonUnmarshallerContext context)
{
ListApplicationsResponse response = new ListApplicationsResponse();
context.Read();
int targetDepth = context.CurrentDepth;
while (context.ReadAtDepth(targetDepth))
{
if (context.TestExpression("applications", targetDepth))
{
var unmarshaller = new ListUnmarshaller<string, StringUnmarshaller>(StringUnmarshaller.Instance);
response.Applications = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("nextToken", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
response.NextToken = unmarshaller.Unmarshall(context);
continue;
}
}
return response;
}
/// <summary>
/// Unmarshaller error response to exception.
/// </summary>
/// <param name="context"></param>
/// <param name="innerException"></param>
/// <param name="statusCode"></param>
/// <returns></returns>
public override AmazonServiceException UnmarshallException(JsonUnmarshallerContext context, Exception innerException, HttpStatusCode statusCode)
{
var errorResponse = JsonErrorResponseUnmarshaller.GetInstance().Unmarshall(context);
errorResponse.InnerException = innerException;
errorResponse.StatusCode = statusCode;
var responseBodyBytes = context.GetResponseBodyBytes();
using (var streamCopy = new MemoryStream(responseBodyBytes))
using (var contextCopy = new JsonUnmarshallerContext(streamCopy, false, null))
{
if (errorResponse.Code != null && errorResponse.Code.Equals("InvalidNextTokenException"))
{
return InvalidNextTokenExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse);
}
}
return new AmazonCodeDeployException(errorResponse.Message, errorResponse.InnerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, errorResponse.StatusCode);
}
private static ListApplicationsResponseUnmarshaller _instance = new ListApplicationsResponseUnmarshaller();
internal static ListApplicationsResponseUnmarshaller GetInstance()
{
return _instance;
}
/// <summary>
/// Gets the singleton.
/// </summary>
public static ListApplicationsResponseUnmarshaller Instance
{
get
{
return _instance;
}
}
}
} | 37.724138 | 193 | 0.644881 | [
"Apache-2.0"
] | ChristopherButtars/aws-sdk-net | sdk/src/Services/CodeDeploy/Generated/Model/Internal/MarshallTransformations/ListApplicationsResponseUnmarshaller.cs | 4,376 | C# |
using System;
using ProtoCore.AssociativeGraph;
namespace ProtoScript.Runners
{
public partial class LiveRunner
{
private abstract class Task
{
protected LiveRunner runner;
protected Task(LiveRunner runner)
{
this.runner = runner;
}
public abstract void Execute();
}
}
} | 21.277778 | 45 | 0.561358 | [
"Apache-2.0",
"MIT"
] | frankfralick/Dynamo | src/Engine/ProtoScript/Runners/LiveRunnerTasks.cs | 383 | 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/winnt.h in the Windows SDK for Windows 10.0.19041.0
// Original source is Copyright © Microsoft. All rights reserved.
using System.Runtime.InteropServices;
namespace TerraFX.Interop
{
[StructLayout(LayoutKind.Sequential, Pack = 4)]
public partial struct IMAGE_LOAD_CONFIG_DIRECTORY64
{
[NativeTypeName("DWORD")]
public uint Size;
[NativeTypeName("DWORD")]
public uint TimeDateStamp;
[NativeTypeName("WORD")]
public ushort MajorVersion;
[NativeTypeName("WORD")]
public ushort MinorVersion;
[NativeTypeName("DWORD")]
public uint GlobalFlagsClear;
[NativeTypeName("DWORD")]
public uint GlobalFlagsSet;
[NativeTypeName("DWORD")]
public uint CriticalSectionDefaultTimeout;
[NativeTypeName("ULONGLONG")]
public ulong DeCommitFreeBlockThreshold;
[NativeTypeName("ULONGLONG")]
public ulong DeCommitTotalFreeThreshold;
[NativeTypeName("ULONGLONG")]
public ulong LockPrefixTable;
[NativeTypeName("ULONGLONG")]
public ulong MaximumAllocationSize;
[NativeTypeName("ULONGLONG")]
public ulong VirtualMemoryThreshold;
[NativeTypeName("ULONGLONG")]
public ulong ProcessAffinityMask;
[NativeTypeName("DWORD")]
public uint ProcessHeapFlags;
[NativeTypeName("WORD")]
public ushort CSDVersion;
[NativeTypeName("WORD")]
public ushort DependentLoadFlags;
[NativeTypeName("ULONGLONG")]
public ulong EditList;
[NativeTypeName("ULONGLONG")]
public ulong SecurityCookie;
[NativeTypeName("ULONGLONG")]
public ulong SEHandlerTable;
[NativeTypeName("ULONGLONG")]
public ulong SEHandlerCount;
[NativeTypeName("ULONGLONG")]
public ulong GuardCFCheckFunctionPointer;
[NativeTypeName("ULONGLONG")]
public ulong GuardCFDispatchFunctionPointer;
[NativeTypeName("ULONGLONG")]
public ulong GuardCFFunctionTable;
[NativeTypeName("ULONGLONG")]
public ulong GuardCFFunctionCount;
[NativeTypeName("DWORD")]
public uint GuardFlags;
public IMAGE_LOAD_CONFIG_CODE_INTEGRITY CodeIntegrity;
[NativeTypeName("ULONGLONG")]
public ulong GuardAddressTakenIatEntryTable;
[NativeTypeName("ULONGLONG")]
public ulong GuardAddressTakenIatEntryCount;
[NativeTypeName("ULONGLONG")]
public ulong GuardLongJumpTargetTable;
[NativeTypeName("ULONGLONG")]
public ulong GuardLongJumpTargetCount;
[NativeTypeName("ULONGLONG")]
public ulong DynamicValueRelocTable;
[NativeTypeName("ULONGLONG")]
public ulong CHPEMetadataPointer;
[NativeTypeName("ULONGLONG")]
public ulong GuardRFFailureRoutine;
[NativeTypeName("ULONGLONG")]
public ulong GuardRFFailureRoutineFunctionPointer;
[NativeTypeName("DWORD")]
public uint DynamicValueRelocTableOffset;
[NativeTypeName("WORD")]
public ushort DynamicValueRelocTableSection;
[NativeTypeName("WORD")]
public ushort Reserved2;
[NativeTypeName("ULONGLONG")]
public ulong GuardRFVerifyStackPointerFunctionPointer;
[NativeTypeName("DWORD")]
public uint HotPatchTableOffset;
[NativeTypeName("DWORD")]
public uint Reserved3;
[NativeTypeName("ULONGLONG")]
public ulong EnclaveConfigurationPointer;
[NativeTypeName("ULONGLONG")]
public ulong VolatileMetadataPointer;
[NativeTypeName("ULONGLONG")]
public ulong GuardEHContinuationTable;
[NativeTypeName("ULONGLONG")]
public ulong GuardEHContinuationCount;
}
}
| 27.558621 | 145 | 0.667167 | [
"MIT"
] | Ethereal77/terrafx.interop.windows | sources/Interop/Windows/um/winnt/IMAGE_LOAD_CONFIG_DIRECTORY64.cs | 3,998 | C# |
using Newtonsoft.Json;
using Switcheo.Net.Converters;
namespace Switcheo.Net.Objects
{
/// <summary>
/// Result of asking balances of a contract
/// </summary>
[JsonConverter(typeof(BalancesListConverter))]
public class SwitcheoBalancesList
{
/// <summary>
/// Confirming balances
/// </summary>
[JsonIgnore]
public SwitcheoAssetConfirming[] Confirming { get; set; }
/// <summary>
/// Confirmed balances
/// </summary>
[JsonIgnore]
public SwitcheoAssetBalance[] Confirmed { get; set; }
/// <summary>
/// Locked balances
/// </summary>
[JsonIgnore]
public SwitcheoAssetBalance[] Locked { get; set; }
}
}
| 24.354839 | 65 | 0.576159 | [
"MIT"
] | Switcheo/Switcheo.Net | Switcheo.Net/Objects/SwitcheoBalancesList.cs | 757 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace FileHandler2.Api.Helpers
{
public class DbHelper
{
}
}
| 14.666667 | 34 | 0.738636 | [
"MIT"
] | marcinru/filehandler | FileHandler2/FileHandler2.Api/Helpers/DbHelper.cs | 178 | C# |
using NetModular.Lib.Data.Abstractions;
namespace NetModular.Module.Admin.Infrastructure.Repositories.PostgreSQL
{
public class AccountConfigRepository : SqlServer.AccountConfigRepository
{
public AccountConfigRepository(IDbContext context) : base(context)
{
}
}
}
| 25.25 | 76 | 0.735974 | [
"MIT"
] | 380138129/NetModular | src/Admin/Library/Infrastructure/Repositories/PostgreSQL/AccountConfigRepository.cs | 305 | C# |
// ReSharper disable All
namespace OpenTl.Schema.Account
{
using System;
using System.Collections;
using OpenTl.Schema;
public interface IPasswordInputSettings : IObject
{
BitArray Flags {get; set;}
byte[] NewSalt {get; set;}
byte[] NewPasswordHash {get; set;}
byte[] HintAsBinary {get; set;}
string Hint {get; set;}
byte[] EmailAsBinary {get; set;}
string Email {get; set;}
byte[] NewSecureSalt {get; set;}
byte[] NewSecureSecret {get; set;}
long NewSecureSecretId {get; set;}
}
}
| 18.1875 | 53 | 0.609966 | [
"MIT"
] | zzz8415/OpenTl.Schema | src/OpenTl.Schema/_generated/Account/PasswordInputSettings/IPasswordInputSettings.cs | 584 | C# |
using System;
using System.IO;
using System.Threading;
namespace SazPatcher
{
class Program
{
static void Main()
{
Console.WriteLine("SazPatcher started.");
if (!Directory.Exists(Utils.patchPath))
{
Console.WriteLine("No Patch folder in current directory: {0}", Directory.GetCurrentDirectory());
Utils.ExitProgram(3000);
}
Patcher.Patch();
Console.WriteLine("SazPatcher finished.");
Console.WriteLine("Press any key to quit.");
Console.ReadKey();
}
static void ReloadProgram(int delay)
{
Console.WriteLine("Reloading");
Thread.Sleep(delay);
Console.Clear();
Main();
}
}
}
| 23.257143 | 112 | 0.528256 | [
"MIT"
] | Sazails/SazPatch | SazPatcher/Program.cs | 816 | C# |
namespace Template.UI.Controllers
{
#region << Using >>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using Incoding.MvcContrib;
using Template.UI.Models;
#endregion
public class DataController : IncControllerBase
{
#region Http action
[HttpGet]
public ActionResult FetchComplex()
{
return IncJson(new List<ComplexVm>
{
new ComplexVm { Country = GetCountries(), Group = "Public", IsRed = true },
new ComplexVm { Country = GetCountries(), Group = "Private", IsRed = false },
});
}
[HttpGet]
public ActionResult FetchCountries()
{
return IncJson(GetCountries());
}
[HttpGet]
public ActionResult FetchCountry()
{
return IncJson(GetCountries().FirstOrDefault());
}
[HttpGet]
public ActionResult FetchEmpty()
{
return IncJson(new List<CountryVm>());
}
[HttpGet]
public ActionResult FetchUnary()
{
return IncJson(new List<UnaryVm>
{
new UnaryVm { Is = true },
new UnaryVm { Is = false },
new UnaryVm { Is = true },
});
}
#endregion
List<CountryVm> GetCountries()
{
Func<string, string[], CountryVm> createCountry = (title, cities) =>
{
var country = new CountryVm { Title = title, Code = title.GetHashCode().ToString(), Cities = new List<CityVm>() };
foreach (var city in cities)
country.Cities.Add(new CityVm { Name = city });
return country;
};
return new List<CountryVm>
{
createCountry("Afghanistan", new[] { "Kabul", "Kandahar" }),
createCountry("Minsk", new[] { "Kabul", "Barysaw" }),
createCountry("Cambodia", new[] { "Battambang", "Kampong Cham" }),
createCountry("Denmark", new[] { "Copenhagena", "Aarhus" }),
createCountry("Egypt", new[] { "Cairo", "Alexandria" }),
createCountry("Greece", new[] { "Athens", "Thessaloniki" }),
};
}
}
} | 37.049383 | 184 | 0.398201 | [
"Apache-2.0"
] | IncodingSoftware/Template | Template.UI/Controllers/DataController.cs | 3,003 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.X86;
namespace JIT.HardwareIntrinsics.X86
{
public static partial class Program
{
private static void RoundToZeroScalarDouble()
{
var test = new SimpleBinaryOpTest__RoundToZeroScalarDouble();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
}
// Validates passing a static member works
test.RunClsVarScenario();
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
}
// Validates passing the field of a local works
test.RunLclFldScenario();
// Validates passing an instance member works
test.RunFldScenario();
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class SimpleBinaryOpTest__RoundToZeroScalarDouble
{
private const int VectorSize = 16;
private const int Op1ElementCount = VectorSize / sizeof(Double);
private const int Op2ElementCount = VectorSize / sizeof(Double);
private const int RetElementCount = VectorSize / sizeof(Double);
private static Double[] _data1 = new Double[Op1ElementCount];
private static Double[] _data2 = new Double[Op2ElementCount];
private static Vector128<Double> _clsVar1;
private static Vector128<Double> _clsVar2;
private Vector128<Double> _fld1;
private Vector128<Double> _fld2;
private SimpleBinaryOpTest__DataTable<Double, Double, Double> _dataTable;
static SimpleBinaryOpTest__RoundToZeroScalarDouble()
{
var random = new Random();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (double)(random.NextDouble()); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _clsVar1), ref Unsafe.As<Double, byte>(ref _data1[0]), VectorSize);
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (double)(random.NextDouble()); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _clsVar2), ref Unsafe.As<Double, byte>(ref _data2[0]), VectorSize);
}
public SimpleBinaryOpTest__RoundToZeroScalarDouble()
{
Succeeded = true;
var random = new Random();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (double)(random.NextDouble()); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _fld1), ref Unsafe.As<Double, byte>(ref _data1[0]), VectorSize);
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (double)(random.NextDouble()); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _fld2), ref Unsafe.As<Double, byte>(ref _data2[0]), VectorSize);
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (double)(random.NextDouble()); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (double)(random.NextDouble()); }
_dataTable = new SimpleBinaryOpTest__DataTable<Double, Double, Double>(_data1, _data2, new Double[RetElementCount], VectorSize);
}
public bool IsSupported => Sse41.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
var result = Sse41.RoundToZeroScalar(
Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Double>>(_dataTable.inArray2Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
var result = Sse41.RoundToZeroScalar(
Sse2.LoadVector128((Double*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((Double*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
var result = Sse41.RoundToZeroScalar(
Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
var result = typeof(Sse41).GetMethod(nameof(Sse41.RoundToZeroScalar), new Type[] { typeof(Vector128<Double>), typeof(Vector128<Double>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Double>>(_dataTable.inArray2Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
var result = typeof(Sse41).GetMethod(nameof(Sse41.RoundToZeroScalar), new Type[] { typeof(Vector128<Double>), typeof(Vector128<Double>) })
.Invoke(null, new object[] {
Sse2.LoadVector128((Double*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((Double*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
var result = typeof(Sse41).GetMethod(nameof(Sse41.RoundToZeroScalar), new Type[] { typeof(Vector128<Double>), typeof(Vector128<Double>) })
.Invoke(null, new object[] {
Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
var result = Sse41.RoundToZeroScalar(
_clsVar1,
_clsVar2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
var left = Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr);
var right = Unsafe.Read<Vector128<Double>>(_dataTable.inArray2Ptr);
var result = Sse41.RoundToZeroScalar(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
var left = Sse2.LoadVector128((Double*)(_dataTable.inArray1Ptr));
var right = Sse2.LoadVector128((Double*)(_dataTable.inArray2Ptr));
var result = Sse41.RoundToZeroScalar(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
var left = Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray1Ptr));
var right = Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray2Ptr));
var result = Sse41.RoundToZeroScalar(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclFldScenario()
{
var test = new SimpleBinaryOpTest__RoundToZeroScalarDouble();
var result = Sse41.RoundToZeroScalar(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunFldScenario()
{
var result = Sse41.RoundToZeroScalar(_fld1, _fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunUnsupportedScenario()
{
Succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
Succeeded = true;
}
}
private void ValidateResult(Vector128<Double> left, Vector128<Double> right, void* result, [CallerMemberName] string method = "")
{
Double[] inArray1 = new Double[Op1ElementCount];
Double[] inArray2 = new Double[Op2ElementCount];
Double[] outArray = new Double[RetElementCount];
Unsafe.Write(Unsafe.AsPointer(ref inArray1[0]), left);
Unsafe.Write(Unsafe.AsPointer(ref inArray2[0]), right);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* left, void* right, void* result, [CallerMemberName] string method = "")
{
Double[] inArray1 = new Double[Op1ElementCount];
Double[] inArray2 = new Double[Op2ElementCount];
Double[] outArray = new Double[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(Double[] left, Double[] right, Double[] result, [CallerMemberName] string method = "")
{
if (BitConverter.DoubleToInt64Bits(result[0]) != BitConverter.DoubleToInt64Bits((right[0] > 0) ? Math.Floor(right[0]) : Math.Ceiling(right[0])))
{
Succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if (BitConverter.DoubleToInt64Bits(result[i]) != BitConverter.DoubleToInt64Bits(left[i]))
{
Succeeded = false;
break;
}
}
}
if (!Succeeded)
{
Console.WriteLine($"{nameof(Sse41)}.{nameof(Sse41.RoundToZeroScalar)}<Double>(Vector128<Double>, Vector128<Double>): {method} failed:");
Console.WriteLine($" left: ({string.Join(", ", left)})");
Console.WriteLine($" right: ({string.Join(", ", right)})");
Console.WriteLine($" result: ({string.Join(", ", result)})");
Console.WriteLine();
}
}
}
}
| 42.870091 | 156 | 0.582664 | [
"MIT"
] | ruben-ayrapetyan/coreclr | tests/src/JIT/HardwareIntrinsics/X86/Sse41/RoundToZeroScalar.Double.cs | 14,190 | C# |
using System;
namespace Wolfgang
{
public abstract class ArcBase : IArc
{
private readonly INet _net;
private readonly IToken _token;
private readonly int _quantity;
public IPlace Place { get; }
public ITransition Transition { get; }
public IToken Token => _token;
public bool TryGetProduceRequest(out Place.ITokenRequest request)
=> Place.TryCreateTokenChangeRequest(in _token, Quantity, out request);
public bool TryGetConsumeRequest(out Place.ITokenRequest request)
=> Place.TryCreateTokenChangeRequest(in _token, -Quantity, out request);
public int Quantity => _quantity;
public INet Net => _net;
internal ArcBase(
in INet net,
in IToken token,
in IPlace place,
in ITransition transition,
int quantity,
string description
)
{
if (quantity < 0)
throw new ArgumentException($"Arcs must be constructed with a positive quantity.", nameof(quantity));
_net = net;
Place = place;
Transition = transition;
_token = token;
_quantity = quantity;
}
}
} | 28.434783 | 118 | 0.566514 | [
"MIT"
] | gerolds/Wolfgang | Wolfgang/ArcBase.cs | 1,308 | C# |
namespace AgileObjects.AgileMapper.UnitTests.Dictionaries
{
using System.Collections.Generic;
using System.Collections.ObjectModel;
using Common;
using TestClasses;
#if !NET35
using Xunit;
#else
using Fact = NUnit.Framework.TestAttribute;
[NUnit.Framework.TestFixture]
#endif
public class WhenViewingDictionaryMappingPlans
{
[Fact]
public void ShouldShowATargetObjectMappingPlan()
{
string plan = Mapper
.GetPlanFor<Dictionary<string, string>>()
.ToANew<CustomerViewModel>();
plan.ShouldContain("Dictionary<string, string> sourceDictionary_String_String");
plan.ShouldContain("idKey = sourceDictionary_String_String.Keys.FirstOrDefault(key => key.MatchesKey(\"Id\"");
plan.ShouldContain("id = sourceDictionary_String_String[idKey]");
plan.ShouldContain("customerViewModel.Id =");
#if NET35
plan.ShouldContain("id.ToGuid()");
#else
plan.ShouldContain("Guid.TryParse(id");
#endif
}
[Fact]
public void ShouldShowATargetComplexTypeCollectionMappingPlan()
{
string plan = Mapper
.GetPlanFor<Dictionary<string, object>>()
.ToANew<Collection<Address>>();
plan.ShouldContain("targetElementKey = \"[\" + i + \"]\"");
plan.ShouldContain("elementKeyExists = sourceDictionary_String_Object.ContainsKey(targetElementKey)");
plan.ShouldContain("var line1Key = \"[\" + i + \"].Line1\"");
plan.ShouldContain("line1 = sourceDictionary_String_Object[line1Key]");
plan.ShouldContain("address.Line1 = line1.ToString()");
}
[Fact]
public void ShouldShowASourceObjectMappingPlan()
{
string plan = Mapper
.GetPlanFor<MysteryCustomer>()
.ToANew<Dictionary<string, object>>();
plan.ShouldContain("dictionary_String_Object = new Dictionary<string, object>()");
plan.ShouldContain("dictionary_String_Object[\"Name\"] = sourceMysteryCustomer.Name");
plan.ShouldContain("dictionary_String_Object[\"Address.Line1\"] = sourceMysteryCustomer.Address.Line1;");
}
[Fact]
public void ShouldShowASourceComplexTypeEnumerableMappingPlan()
{
string plan = Mapper
.GetPlanFor<IEnumerable<CustomerViewModel>>()
.ToANew<Dictionary<string, string>>();
plan.ShouldContain("sourceMysteryCustomerViewModel = enumerator.Current as MysteryCustomerViewModel");
plan.ShouldContain("dictionary_String_String[\"[\" + i + \"].Report\"] = sourceMysteryCustomerViewModel.Report");
plan.ShouldContain("dictionary_String_String[\"[\" + i + \"].AddressLine1\"] = enumerator.Current.AddressLine1");
}
}
} | 39.767123 | 125 | 0.635894 | [
"MIT"
] | WeiiWang/AgileMapper | AgileMapper.UnitTests/Dictionaries/WhenViewingDictionaryMappingPlans.cs | 2,905 | C# |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.VisualStudio.ProjectSystem.VS.Automation;
using Moq;
using Xunit;
namespace Microsoft.VisualStudio.ProjectSystem.VS.TempPE
{
public class DesignTimeInputsBuildManagerBridgeTests : IDisposable
{
private readonly TestBuildManager _buildManager;
private readonly TestDesignTimeInputsBuildManagerBridge _bridge;
private string? _lastCompiledFile;
private string? _lastOutputPath;
private ImmutableHashSet<string>? _lastSharedInputs;
[Fact]
public async Task ChangedFile_FiresTempPEDirty()
{
await _bridge.ApplyAsync(new DesignTimeInputsDelta(
ImmutableHashSet.CreateRange(new string[] { "Resources1.Designer.cs" }),
ImmutableHashSet<string>.Empty,
new DesignTimeInputFileChange[] { new DesignTimeInputFileChange("Resources1.Designer.cs", false) },
"C:\\TempPE"));
// One file should have been added
Assert.Single(_buildManager.DirtyItems);
Assert.Equal("Resources1.Designer.cs", _buildManager.DirtyItems.First());
Assert.Empty(_buildManager.DeletedItems);
}
[Fact]
public async Task RemovedFile_FiresTempPEDeleted()
{
await _bridge.ApplyAsync(new DesignTimeInputsDelta(
ImmutableHashSet.CreateRange(new string[] { "Resources1.Designer.cs" }),
ImmutableHashSet<string>.Empty,
Array.Empty<DesignTimeInputFileChange>(),
""));
await _bridge.ApplyAsync(new DesignTimeInputsDelta(
ImmutableHashSet<string>.Empty,
ImmutableHashSet<string>.Empty,
Array.Empty<DesignTimeInputFileChange>(),
""));
// One file should have been added
Assert.Empty(_buildManager.DirtyItems);
Assert.Single(_buildManager.DeletedItems);
Assert.Equal("Resources1.Designer.cs", _buildManager.DeletedItems.First());
}
[Fact]
public async Task GetDesignTimeInputXmlAsync_HasCorrectArguments()
{
await _bridge.ApplyAsync(new DesignTimeInputsDelta(
ImmutableHashSet.CreateRange(new string[] { "Resources1.Designer.cs" }),
ImmutableHashSet<string>.Empty,
new DesignTimeInputFileChange[] { new DesignTimeInputFileChange("Resources1.Designer.cs", false) },
"C:\\TempPE"));
await _bridge.GetDesignTimeInputXmlAsync("Resources1.Designer.cs");
Assert.Equal("Resources1.Designer.cs", _lastCompiledFile);
Assert.Equal("C:\\TempPE", _lastOutputPath);
Assert.Equal(ImmutableHashSet<string>.Empty, _lastSharedInputs);
}
public DesignTimeInputsBuildManagerBridgeTests()
{
var threadingService = IProjectThreadingServiceFactory.Create();
var changeTracker = Mock.Of<IDesignTimeInputsChangeTracker>();
var compilerMock = new Mock<IDesignTimeInputsCompiler>();
compilerMock.Setup(c => c.GetDesignTimeInputXmlAsync(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<ImmutableHashSet<string>>()))
.Callback<string, string, ImmutableHashSet<string>>((file, outputPath, sharedInputs) =>
{
_lastCompiledFile = file;
_lastOutputPath = outputPath;
_lastSharedInputs = sharedInputs;
});
var project = UnconfiguredProjectFactory.Create(filePath: @"C:\MyProject\MyProject.csproj");
_buildManager = new TestBuildManager();
_bridge = new TestDesignTimeInputsBuildManagerBridge(project, threadingService, changeTracker, compilerMock.Object, _buildManager);
_bridge.SkipInitialization = true;
}
public void Dispose()
{
((IDisposable)_bridge).Dispose();
}
internal class TestDesignTimeInputsBuildManagerBridge : DesignTimeInputsBuildManagerBridge
{
public TestDesignTimeInputsBuildManagerBridge(UnconfiguredProject project, IProjectThreadingService threadingService, IDesignTimeInputsChangeTracker designTimeInputsChangeTracker, IDesignTimeInputsCompiler designTimeInputsCompiler, VSBuildManager buildManager)
: base(project, threadingService, designTimeInputsChangeTracker, designTimeInputsCompiler, buildManager)
{
}
public Task ApplyAsync(DesignTimeInputsDelta delta)
{
var input = IProjectVersionedValueFactory.Create(delta);
return base.ApplyAsync(input);
}
}
internal class TestBuildManager : VSBuildManager
{
public List<string> DeletedItems { get; } = new List<string>();
public List<string> DirtyItems { get; } = new List<string>();
internal TestBuildManager()
: base(IProjectThreadingServiceFactory.Create(),
IUnconfiguredProjectCommonServicesFactory.Create(UnconfiguredProjectFactory.Create()))
{
}
internal override void OnDesignTimeOutputDeleted(string outputMoniker)
{
DeletedItems.Add(outputMoniker);
}
internal override void OnDesignTimeOutputDirty(string outputMoniker)
{
DirtyItems.Add(outputMoniker);
}
}
}
}
| 42.248227 | 273 | 0.630351 | [
"Apache-2.0"
] | PooyaZv/project-system | tests/Microsoft.VisualStudio.ProjectSystem.Managed.VS.UnitTests/ProjectSystem/VS/TempPE/DesignTimeInputsBuildManagerBridgeTests.cs | 5,819 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayBox : MonoBehaviour
{
public Spawner spawner;
public AudioSource audioSource;
public AudioClip explosionClip;
public GameObject explosionEffect;
public GameObject text;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
}
void OnTriggerEnter(Collider other) {
if(other.tag == "Player"){
text.SetActive(false);
spawner.StartGame();
Instantiate(explosionEffect,transform.position,Quaternion.Euler(-90,0,0));
audioSource.PlayOneShot(explosionClip);
GetComponent<MeshRenderer>().enabled = false;
Destroy(gameObject,explosionClip.length);
}
}
}
| 20.022222 | 86 | 0.619312 | [
"MIT"
] | TayoTwo/Unstable | Assets/PlayBox.cs | 901 | C# |
using System.Linq;
using Umbraco.Core.Models.Membership;
namespace Umbraco.Core.Services
{
public static class ContentServiceExtensions
{
/// <summary>
/// Remove all permissions for this user for all nodes
/// </summary>
/// <param name="contentService"></param>
/// <param name="contentId"></param>
public static void RemoveContentPermissions(this IContentService contentService, int contentId)
{
contentService.ReplaceContentPermissions(new EntityPermissionSet(contentId, Enumerable.Empty<EntityPermissionSet.UserPermission>()));
}
/// <summary>
/// Returns true if there is any content in the recycle bin
/// </summary>
/// <param name="contentService"></param>
/// <returns></returns>
public static bool RecycleBinSmells(this IContentService contentService)
{
return contentService.CountChildren(Constants.System.RecycleBinContent) > 0;
}
/// <summary>
/// Returns true if there is any media in the recycle bin
/// </summary>
/// <param name="mediaService"></param>
/// <returns></returns>
public static bool RecycleBinSmells(this IMediaService mediaService)
{
return mediaService.CountChildren(Constants.System.RecycleBinMedia) > 0;
}
}
} | 37.473684 | 146 | 0.616573 | [
"MIT"
] | ClaytonWang/Umbraco-CMS | src/Umbraco.Core/Services/ContentServiceExtensions.cs | 1,424 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Configuration;
public partial class JPReg : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Session["User"] = null;
Session["Company"] = null;
Label1.Visible = false;
Label2.Visible = false;
}
protected void Bregister_Click(object sender, EventArgs e)
{
try
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
conn.Open();
string check = "select count(*) from Cprofile where cname='" + TBname.Text + "'";
SqlCommand com1 = new SqlCommand(check, conn);
int temp = Convert.ToInt32(com1.ExecuteScalar().ToString());
string checkphno = "select count(*) from Cprofile where phno='" + TBphno.Text + "'";
SqlCommand com3 = new SqlCommand(checkphno, conn);
int temp2 = Convert.ToInt32(com3.ExecuteScalar().ToString());
if (temp2 > 0)
{
Label2.Visible = true;
Label2.Text = "Phone number is already registered";
}
conn.Close();
if (temp > 0)
{
Label1.Visible=true;
Label1.Text = "User already exists";
}
else
{
conn.Open();
string insert = "insert into Cprofile (cname, password, hq, phno) values (@Name, @Password, @HQ, @Phno)";
SqlCommand com2 = new SqlCommand(insert, conn);
com2.Parameters.AddWithValue("@Name", TBname.Text);
com2.Parameters.AddWithValue("@Password", TBpassword.Text);
com2.Parameters.AddWithValue("@HQ", TBhq.Text);
com2.Parameters.AddWithValue("@Phno", TBphno.Text);
com2.ExecuteNonQuery();
conn.Close();
Response.Redirect("JPRegComplete.aspx");
}
}
catch (Exception ex)
{
Response.Write("ERROR" + ex.ToString());
}
}
} | 35.409091 | 129 | 0.543432 | [
"MIT"
] | itskrrish/online-job-portal | JPReg.aspx.cs | 2,339 | 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.MySql.Support
{
/// <summary>Enable Geo-redundant or not for server backup.</summary>
[System.ComponentModel.TypeConverter(typeof(Microsoft.Azure.PowerShell.Cmdlets.MySql.Support.GeoRedundantBackupTypeConverter))]
public partial struct GeoRedundantBackup :
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) || "Enabled".StartsWith(wordToComplete, global::System.StringComparison.InvariantCultureIgnoreCase))
{
yield return new global::System.Management.Automation.CompletionResult("'Enabled'", "Enabled", global::System.Management.Automation.CompletionResultType.ParameterValue, "Enabled");
}
if (global::System.String.IsNullOrEmpty(wordToComplete) || "Disabled".StartsWith(wordToComplete, global::System.StringComparison.InvariantCultureIgnoreCase))
{
yield return new global::System.Management.Automation.CompletionResult("'Disabled'", "Disabled", global::System.Management.Automation.CompletionResultType.ParameterValue, "Disabled");
}
}
}
} | 72.692308 | 373 | 0.719224 | [
"MIT"
] | Agazoth/azure-powershell | src/MySql/generated/api/Support/GeoRedundantBackup.Completer.cs | 2,797 | C# |
using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Shapes;
using Tektosyne.Geometry;
using Tektosyne.Windows;
using Tektosyne.Xml;
namespace Tektosyne.GuiTest {
/// <summary>
/// Provides a <see cref="Window"/> for testing the brute force variant of the <see
/// cref="MultiLineIntersection"/> algorithm.</summary>
/// <remarks>
/// <b>IntersectionTest</b> draws a random set of lines and marks any points of intersection
/// that were found.</remarks>
public partial class IntersectionTest: Window {
#region IntersectionTest()
public IntersectionTest() {
InitializeComponent();
DrawIntersections(null);
}
#endregion
#region Private Fields
// current lines & intersections
private LineD[] _lines;
MultiLinePoint[] _crossings;
#endregion
#region DrawIntersections
private void DrawIntersections(LineD[] lines) {
const double radius = 4.0;
// generate new random line set if desired
if (lines == null) {
Size scale = new Size(OutputBox.Width - 4 * radius, OutputBox.Height - 4 * radius);
int count = MersenneTwister.Default.Next(3, 20);
lines = new LineD[count];
for (int i = 0; i < lines.Length; i++)
lines[i] = GeoAlgorithms.RandomLine(
2 * radius, 2 * radius, scale.Width, scale.Height);
}
_lines = lines;
double epsilon = (double) ToleranceUpDown.Value;
_crossings = (epsilon > 0.0 ?
MultiLineIntersection.FindSimple(lines, epsilon) :
MultiLineIntersection.FindSimple(lines));
LinesLabel.Content = String.Format("{0}/{1}", lines.Length, _crossings.Length);
OutputBox.Children.Clear();
// draw line set
foreach (LineD line in lines) {
var shape = new Line() {
X1 = line.Start.X, Y1 = line.Start.Y,
X2 = line.End.X, Y2 = line.End.Y,
Stroke = Brushes.Black
};
OutputBox.Children.Add(shape);
}
// draw intersections as hollow circles
foreach (var crossing in _crossings) {
var circle = new Ellipse() {
Width = 2 * radius, Height = 2 * radius,
Stroke = Brushes.Red
};
Canvas.SetLeft(circle, crossing.Shared.X - radius);
Canvas.SetTop(circle, crossing.Shared.Y - radius);
OutputBox.Children.Add(circle);
}
}
#endregion
#region CopyCommandExecuted
private void CopyCommandExecuted(object sender, ExecutedRoutedEventArgs args) {
args.Handled = true;
try {
string text = XmlSerialization.Serialize<LineD[]>(_lines);
Clipboard.SetText(text);
}
catch (Exception e) {
MessageDialog.Show(this,
"An error occurred while attempting to copy\n" +
"the current line set to the clipboard.",
Strings.ClipboardCopyError, e, MessageBoxButton.OK,
WindowsUtility.GetSystemBitmap(MessageBoxImage.Error));
}
}
#endregion
#region NewCommandExecuted
private void NewCommandExecuted(object sender, ExecutedRoutedEventArgs args) {
args.Handled = true;
DrawIntersections(null);
}
#endregion
#region PasteCommandCanExecute
private void PasteCommandCanExecute(object sender, CanExecuteRoutedEventArgs args) {
args.Handled = true;
args.CanExecute = Clipboard.ContainsText();
}
#endregion
#region PasteCommandExecuted
private void PasteCommandExecuted(object sender, ExecutedRoutedEventArgs args) {
args.Handled = true;
try {
string text = Clipboard.GetText();
LineD[] lines = XmlSerialization.Deserialize<LineD[]>(text);
DrawIntersections(lines);
}
catch (Exception e) {
MessageDialog.Show(this,
"An error occurred while attempting to\n" +
"paste a new line set from the clipboard.",
Strings.ClipboardPasteError, e, MessageBoxButton.OK,
WindowsUtility.GetSystemBitmap(MessageBoxImage.Error));
}
}
#endregion
#region OnSplit
private void OnSplit(object sender, RoutedEventArgs args) {
args.Handled = true;
var lines = MultiLineIntersection.Split(_lines, _crossings);
DrawIntersections(lines);
}
#endregion
#region OnToleranceChanged
private void OnToleranceChanged(object sender, EventArgs args) {
RoutedEventArgs routedArgs = args as RoutedEventArgs;
if (routedArgs != null) routedArgs.Handled = true;
DrawIntersections(_lines);
}
#endregion
#region OnToleranceMaximum
private void OnToleranceMaximum(object sender, RoutedEventArgs args) {
args.Handled = true;
ToleranceUpDown.Value = ToleranceUpDown.Maximum;
}
#endregion
#region OnToleranceMinimum
private void OnToleranceMinimum(object sender, RoutedEventArgs args) {
args.Handled = true;
ToleranceUpDown.Value = ToleranceUpDown.Minimum;
}
#endregion
}
}
| 32.054945 | 99 | 0.567707 | [
"MIT"
] | prepare/Tektosyne.NET | Tektosyne.GuiTest/IntersectionTest.xaml.cs | 5,836 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Text;
using KS.Fiks.ASiC_E.Crypto;
using KS.Fiks.ASiC_E.Manifest;
using KS.Fiks.ASiC_E.Sign;
using NLog;
using Org.BouncyCastle.Crypto.IO;
using Org.BouncyCastle.Security;
namespace KS.Fiks.ASiC_E.Model
{
public class AsiceArchive : IDisposable
{
private static readonly Logger Log = LogManager.GetCurrentClassLogger();
private ICertificateHolder SignatureCertificate { get; }
private ZipArchive Archive { get; }
private readonly Queue<AsicePackageEntry> entries = new Queue<AsicePackageEntry>();
private readonly IManifestCreator manifestCreator;
private MessageDigestAlgorithm MessageDigestAlgorithm { get; }
public AsiceArchive(ZipArchive archive, IManifestCreator creator, MessageDigestAlgorithm messageDigestAlgorithm, ICertificateHolder signatureCertificate)
{
Archive = archive ?? throw new ArgumentNullException(nameof(archive));
this.manifestCreator = creator ?? throw new ArgumentNullException(nameof(creator));
MessageDigestAlgorithm = messageDigestAlgorithm ?? throw new ArgumentNullException(nameof(messageDigestAlgorithm));
SignatureCertificate = signatureCertificate;
}
public static AsiceArchive Create(Stream zipOutStream, IManifestCreator manifestCreator, ICertificateHolder signatureCertificateHolder)
{
Log.Debug("Creating ASiC-e Zip");
var zipArchive = new ZipArchive(zipOutStream, ZipArchiveMode.Create, false, Encoding.UTF8);
// Add mimetype entry
var zipArchiveEntry = zipArchive.CreateEntry(AsiceConstants.FileNameMimeType);
using (var stream = zipArchiveEntry.Open())
{
var contentAsBytes = Encoding.UTF8.GetBytes(AsiceConstants.ContentTypeASiCe);
stream.Write(contentAsBytes, 0, contentAsBytes.Length);
}
return new AsiceArchive(zipArchive, manifestCreator, MessageDigestAlgorithm.SHA256, signatureCertificateHolder);
}
/// <summary>
/// Add file to ASiC-E package
/// </summary>
/// <param name="contentStream">The stream that contains the data</param>
/// <param name="entry">A description of the file entry</param>
/// <returns>The archive with the entry added</returns>
/// <exception cref="ArgumentException">If any if the parameters is null or invalid.
/// Only files that are not in the /META-INF may be added</exception>
public AsiceArchive AddEntry(Stream contentStream, FileRef entry)
{
var packageEntry = entry ?? throw new ArgumentNullException(nameof(entry), "Entry must be provided");
if (packageEntry.FileName.StartsWith("META-INF/", StringComparison.CurrentCultureIgnoreCase))
{
throw new ArgumentException("Adding files to META-INF is not allowed.");
}
Log.Debug($"Adding entry '{entry.FileName}' of type '{entry.MimeType}' to the ASiC-e archive");
this.entries.Enqueue(CreateEntry(contentStream, new AsicePackageEntry(entry.FileName, entry.MimeType, MessageDigestAlgorithm)));
return this;
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool dispose)
{
AddManifest();
Archive.Dispose();
}
private AsicePackageEntry CreateEntry(Stream contentStream, AsicePackageEntry entry)
{
var fileName = entry.FileName ?? throw new ArgumentNullException(nameof(entry), "File name must be provided");
var dataStream = contentStream ?? throw new ArgumentNullException(nameof(contentStream));
var zipEntry = Archive.CreateEntry(fileName);
using (var zipStream = zipEntry.Open())
using (var digestStream = new DigestStream(zipStream, null, MessageDigestAlgorithm.Digest))
{
dataStream.CopyTo(digestStream);
dataStream.Flush();
entry.Digest = new DigestContainer(DigestUtilities.DoFinal(digestStream.WriteDigest()), MessageDigestAlgorithm);
}
return entry;
}
private void AddManifest()
{
Log.Debug("Creating manifest");
var manifest = CreateManifest();
if (manifest.ManifestSpec == ManifestSpec.Cades && manifest.SignatureFileRef != null)
{
var signatureFile = SignatureCreator.Create(SignatureCertificate).CreateCadesSignatureFile(manifest);
manifest.SignatureFileRef = signatureFile.SignatureFileRef;
using (var signatureStream = new MemoryStream(signatureFile.Data.ToArray()))
{
var entry = Archive.CreateEntry(signatureFile.SignatureFileRef.FileName);
using (var zipEntryStream = entry.Open())
{
signatureStream.CopyTo(zipEntryStream);
}
}
}
using (var manifestStream = new MemoryStream(manifest.Data.ToArray()))
{
CreateEntry(manifestStream, new AsicePackageEntry(manifest.FileName, MimeType.ForString(AsiceConstants.ContentTypeXml), MessageDigestAlgorithm));
}
Log.Debug("Manifest added to archive");
}
private ManifestContainer CreateManifest()
{
return this.manifestCreator.CreateManifest(this.entries);
}
}
} | 41.985401 | 161 | 0.64847 | [
"MIT"
] | ks-no/fiks-asice-dotnet | KS.Fiks.ASiC-E/Model/AsiceArchive.cs | 5,752 | 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.SecurityInsights.V20210301Preview.Outputs
{
/// <summary>
/// Data type for Microsoft Threat Intelligence Platforms data connector.
/// </summary>
[OutputType]
public sealed class MSTIDataConnectorDataTypesResponseBingSafetyPhishingURL
{
/// <summary>
/// lookback period
/// </summary>
public readonly string LookbackPeriod;
/// <summary>
/// Describe whether this data type connection is enabled or not.
/// </summary>
public readonly string State;
[OutputConstructor]
private MSTIDataConnectorDataTypesResponseBingSafetyPhishingURL(
string lookbackPeriod,
string state)
{
LookbackPeriod = lookbackPeriod;
State = state;
}
}
}
| 29.025641 | 81 | 0.659011 | [
"Apache-2.0"
] | polivbr/pulumi-azure-native | sdk/dotnet/SecurityInsights/V20210301Preview/Outputs/MSTIDataConnectorDataTypesResponseBingSafetyPhishingURL.cs | 1,132 | C# |
namespace MusicPlayerTests3.Models
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MusicPlayer.Models;
internal class DummySound : ISound
{
private string url;
private bool noticedNearTheEnd;
private float volume = 100;
public event EventHandler MediaEnded;
public event EventHandler MediaStarted;
public event EventHandler LoadCompleted;
public event EventHandler NearTheEnd;
public bool Playing { get; private set; }
public bool Loading => throw new NotImplementedException();
public string URL
{
get => url;
set
{
url = value;
Position = 0;
noticedNearTheEnd = false;
LoadCompleted?.Invoke(this, EventArgs.Empty);
}
}
public float Volume
{
get => volume;
set => volume = Math.Max(Math.Min(1, value), 0);
}
public double Position { get; set; }
public double Duration { get; set; }
public int SwitchingDuration { get; set; }
public bool IsSelected { get => throw new NotImplementedException(); set => throw new NotImplementedException(); }
public string Name => throw new NotImplementedException();
public int FrontCut { get; set; }
public int BackCut { get; set; }
public int ListenCount { get; set; }
public void Pause()
{
throw new NotImplementedException();
}
public void Play()
{
if (Duration > 0)
{
Playing = true;
}
}
public void Resume()
{
throw new NotImplementedException();
}
public void Stop()
{
Playing = false;
Position = 0;
}
public void Forward(double time)
{
if (!Playing)
{
return;
}
Position += time;
if (Position >= Duration)
{
Playing = false;
MediaEnded?.Invoke(this, EventArgs.Empty);
}
else if (SwitchingDuration > 0 && !noticedNearTheEnd && Position >= Duration - SwitchingDuration)
{
NearTheEnd?.Invoke(this, EventArgs.Empty);
noticedNearTheEnd = true;
}
}
public void Load()
{
}
}
}
| 24.321429 | 123 | 0.487885 | [
"MIT"
] | UmsrAkne/MusicPlayer | MusicPlayerTests3/Models/DummySound.cs | 2,726 | C# |
//
// Copyright (C) DataStax Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
using System.IO;
using Cassandra.Serialization;
namespace Cassandra.Requests
{
internal interface IRequest
{
/// <summary>
/// Writes the frame for this request on the provided stream
/// </summary>
int WriteFrame(short streamId, MemoryStream stream, Serializer serializer);
}
}
| 31.4 | 83 | 0.693206 | [
"Apache-2.0"
] | mintsoft/csharp-driver | src/Cassandra/Requests/IRequest.cs | 942 | C# |
// <auto-generated />
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using Repository;
namespace Repository.Migrations
{
[DbContext(typeof(DatabaseContext))]
[Migration("20210406093716_Add_environment_schedule")]
partial class Add_environment_schedule
{
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("Relational:MaxIdentifierLength", 128)
.HasAnnotation("ProductVersion", "5.0.4")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
modelBuilder.Entity("EnvironmentResource", b =>
{
b.Property<Guid>("EnvironmentsId")
.HasColumnType("uniqueidentifier");
b.Property<Guid>("ResourcesId")
.HasColumnType("uniqueidentifier");
b.HasKey("EnvironmentsId", "ResourcesId");
b.HasIndex("ResourcesId");
b.ToTable("EnvironmentResources");
});
modelBuilder.Entity("Repository.Models.Environment", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uniqueidentifier");
b.Property<string>("Description")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("ScheduledStartup")
.HasColumnType("nvarchar(max)");
b.Property<int>("ScheduledUptime")
.HasColumnType("int");
b.HasKey("Id");
b.ToTable("Environments");
});
modelBuilder.Entity("Repository.Models.Resource", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uniqueidentifier");
b.Property<string>("Description")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<int>("Kind")
.HasColumnType("int");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("nvarchar(450)");
b.Property<int?>("NodePoolCount")
.HasColumnType("int");
b.Property<string>("ResourceGroup")
.IsRequired()
.HasColumnType("nvarchar(450)");
b.HasKey("Id");
b.HasIndex("Name", "ResourceGroup")
.IsUnique();
b.ToTable("Resources");
});
modelBuilder.Entity("EnvironmentResource", b =>
{
b.HasOne("Repository.Models.Environment", null)
.WithMany()
.HasForeignKey("EnvironmentsId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("Repository.Models.Resource", null)
.WithMany()
.HasForeignKey("ResourcesId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
#pragma warning restore 612, 618
}
}
}
| 34.710526 | 117 | 0.489765 | [
"MIT"
] | chrishaland/az-resource-scheduler | Repository/Migrations/20210406093716_Add_environment_schedule.Designer.cs | 3,959 | C# |
using System;
using System.Collections;
using System.Linq;
using System.Drawing;
using Console = Colorful.Console;
namespace DeviceDice
{
//TODO: Define 'business logic' in a separate classs file (number of dice to play with, etc).
//TODO: Version 2: Make it so we can play with multiple dice sides (e.g. diceboard with 3 d2 and 6 d12); we can take away and add dice of a specific type and roll them.
// can extend to multiple dice types by converting from array to dictionary
//TODO: Unit tests: check all validation points for out-of-bounds and type matching input
// create a few classes to do this.
//TODO: added exception + exit everywhere when initializing the dice rolls just to experment - should remove them (?) and put while loops in.
//Worth keeping for int.parse? - would reject string values and silly -+32bit values
// change to create a new branch
class DeviceDice
{
static void Main(string[] args)
{
Boolean playerWantsToPlay = true;
while (playerWantsToPlay == true)
{
//
//
//
// instantiate first set of dice
Console.WriteAscii("DeviceDice", Color.Red);
Console.WriteLine("\r\nHow many sides do you need on your dice? Acceptable values are 4, 6, 8, 10, 12, or 20.");
int[] acceptableDiceSideValuesArray = { 4, 6, 8, 10, 12, 20 };
int diceSides = 0;
try
{
diceSides = int.Parse(Console.ReadLine());
}
catch (Exception e)
{
Console.WriteLine("Invalid input." + e);
Environment.Exit(1);
}
while (!acceptableDiceSideValuesArray.Contains(diceSides))
{
Console.WriteLine("Must chose between dice with 4, 6, 8, 10, 12, or 20 sides.");
try
{
diceSides = int.Parse(Console.ReadLine());
}
catch (Exception e)
{
Console.WriteLine("Invalid input." + e);
Environment.Exit(1);
}
}
Console.WriteLine("How many dice do you want to roll? Acceptable values are 1-10.");
int numberOfPlayerDice = 0;
try
{
numberOfPlayerDice = int.Parse(Console.ReadLine());
}
catch (Exception e)
{
Console.WriteLine("Invalid input." + e);
Environment.Exit(1);
}
while (!(numberOfPlayerDice < 11 || numberOfPlayerDice <= 0))
{
Console.WriteLine("Must chose between one and ten dice.");
try
{
numberOfPlayerDice = int.Parse(Console.ReadLine());
}
catch (Exception e)
{
Console.WriteLine("Invalid input." + e);
Environment.Exit(1);
}
}
int initialDiceValue = 0;
Dice[] diceBoard = new Dice[numberOfPlayerDice];
for (int i = 0; i < numberOfPlayerDice; i++)
{
diceBoard[i] = new Dice(diceSides);
initialDiceValue += diceBoard[i].value;
}
Console.WriteLine("Set a roll modifier? (y/n)");
String useRollModifier = Console.ReadLine();
while (!(useRollModifier == "y" || useRollModifier == "n"))
{
Console.WriteLine("Please enter a proper value.");
useRollModifier = Console.ReadLine();
}
int rollModifier = 0;
if (useRollModifier == "y")
{
Console.WriteLine("Enter a modifier value greater than 0.");
try
{
rollModifier = int.Parse(Console.ReadLine());
}
catch (Exception e)
{
Console.WriteLine("Invalid input." + e);
Environment.Exit(1);
}
while (rollModifier <= 0)
{
Console.Write("Please enter a value greater than 0");
try
{
rollModifier = int.Parse(Console.ReadLine());
}
catch (Exception e)
{
Console.WriteLine("Invalid input." + e);
Environment.Exit(1);
}
}
}
if (useRollModifier == "n") { Console.WriteLine("No modifier used."); }
// Print initial dice values
Console.WriteLine("\r\nYou now have " + numberOfPlayerDice + " beautiful dice, all lined up in a row. You stare at them in awe:");
for (int i = 0; i < diceBoard.Length; i++)
{
Console.WriteLine("\r\nThe " + Ordinal.AddOrdinal((i + 1)) + " die has a value of " + diceBoard[i].value + ".");
}
Console.WriteLine("\r\nThe sum of all dice values are " + initialDiceValue + ".");
if (useRollModifier == "y")
{
Console.WriteLine("\r\nWith a roll modfier of " + rollModifier + ", your dice roll has a value of " + (initialDiceValue + rollModifier) + ".");
}
// while loop for rolling with modified number of dice
// logic for rolling again
Boolean playerWantsToPlayWithCurrentDiceNumber = true;
while (playerWantsToPlayWithCurrentDiceNumber) {
// roll loop logic. For simplicity's sake - modifier can be added here and not during the initial roll.
Boolean rollAgain = true;
while (rollAgain)
{
Console.WriteLine("\r\nYou roll your beautiful dice.");
int allDiceValueForRoll = 0;
foreach (Dice specficDice in diceBoard)
{
specficDice.Roll();
allDiceValueForRoll += specficDice.value;
}
Console.WriteLine("\r\nYou stare at your marvelous dice again. Through the magic of physics, they've changed.");
for (int i = 0; i < diceBoard.Length; i++)
{
Console.WriteLine("\r\nThe " + Ordinal.AddOrdinal((i + 1)) + " die has a value of " + diceBoard[i].value + ".");
}
//print only if dice number > 1?
Console.WriteLine("\r\nThe sum of all dice is now " + allDiceValueForRoll + ".");
if (useRollModifier == "y")
{
Console.WriteLine("\r\nWith a roll modfier of " + rollModifier + ", your dice roll has a value of " + (allDiceValueForRoll + rollModifier) + ".");
}
Console.WriteLine("\r\nRoll again? (y/n)");
String rollAgainConfirmation = Console.ReadLine();
while(!((rollAgainConfirmation == "y") || (rollAgainConfirmation == "n"))) {
Console.WriteLine("Invalid Input, please specify whether or not your want to roll again. (y/n)");
rollAgainConfirmation = Console.ReadLine();
}
if (rollAgainConfirmation == "n") { break; }
}
// add/subtract input validation
Console.WriteLine("\r\nSpecify whether to add or subtract dice, change the roll modifier, or exit. (add/subtract/modifier/exit)");
String[] addOrSubtractChoices = { "add", "subtract", "modifier", "exit" };
String addOrSubtractConfirmation = "";
addOrSubtractConfirmation = Console.ReadLine();
while (!addOrSubtractChoices.Contains(addOrSubtractConfirmation))
{
Console.WriteLine("Invalid Input. Please specify whether to add or subtract dice, or exit. (add/subtract/modifier/exit)");
addOrSubtractConfirmation = Console.ReadLine();
}
int valueToModifyDiceBoard = 0;
if (addOrSubtractConfirmation == "add" || addOrSubtractConfirmation == "subtract")
{
Console.WriteLine("\r\nBy how much? You currently have " + diceBoard.Length + " dice.");
try
{
// need validation for specifying invalid numbers.
valueToModifyDiceBoard = int.Parse(Console.ReadLine());
}
catch (Exception e)
{
Console.WriteLine("Invalid input." + e);
Environment.Exit(1);
}
if (valueToModifyDiceBoard < 0)
{
Console.WriteLine("A negative number, eh? Don't mind if I convert your input to an absolute number.");
valueToModifyDiceBoard = Math.Abs(valueToModifyDiceBoard);
}
// welcome to Off-By-One City: logic for actually modifying the diceBoard array
int originalDiceBoardLength = diceBoard.Length;
int newDiceValue = 0;
if (addOrSubtractConfirmation == "add")
{
while ((diceBoard.Length + valueToModifyDiceBoard) > 10)
{
Console.WriteLine("You can only have between 1 and 10 dice. Please chose a proper value.");
try
{
valueToModifyDiceBoard = int.Parse(Console.ReadLine());
}
catch (Exception e)
{
Console.WriteLine("Invalid input." + e);
Environment.Exit(1);
}
}
Array.Resize(ref diceBoard, (diceBoard.Length + valueToModifyDiceBoard));
for (int i = originalDiceBoardLength; i < diceBoard.Length; i++)
{
diceBoard[i] = new Dice(diceSides);
}
foreach (Dice specificDice in diceBoard)
{
newDiceValue += specificDice.value;
}
Console.WriteLine("\r\nYou added " + valueToModifyDiceBoard + " and now have " + diceBoard.Length + " dice, with a total sum of " + newDiceValue + ".");
}
if (addOrSubtractConfirmation == "subtract")
{
while ((diceBoard.Length - valueToModifyDiceBoard) < 1)
{
Console.WriteLine("You can only have between 1 and 10 dice. Please chose a proper value.");
try
{
valueToModifyDiceBoard = int.Parse(Console.ReadLine());
}
catch (Exception e)
{
Console.WriteLine("Invalid input." + e);
Environment.Exit(1);
}
}
Array.Resize(ref diceBoard, (diceBoard.Length - valueToModifyDiceBoard));
foreach (Dice specificDice in diceBoard)
{
newDiceValue += specificDice.value;
}
Console.WriteLine("\r\nYou subtracted " + valueToModifyDiceBoard + " and now have " + diceBoard.Length + " dice, with a total sum of " + newDiceValue + ".");
}
}
if (addOrSubtractConfirmation == "modifier")
{
Console.WriteLine("\r\nAdd a modifier, change your modifier, stop using a roll modifier, or exit (add/change/stop/exit)");
String modifierChoice = Console.ReadLine();
String[] modifyRollModifier = { "add", "change", "stop", "exit" };
while (!modifyRollModifier.Contains(modifierChoice))
{
Console.WriteLine("Please chose a valid input (change/stopmodifier/exit)");
modifierChoice = Console.ReadLine();
}
if (modifierChoice == "add")
{
Console.WriteLine("\r\nYou're now playing with a roll modifier.");
useRollModifier = "y";
modifierChoice = "change";
}
if (modifierChoice == "change")
{
Console.WriteLine("\r\nInput a value for the dice modifier greater than 0.");
try
{
rollModifier = int.Parse(Console.ReadLine());
}
catch (Exception e)
{
Console.WriteLine("Invalid input." + e);
Environment.Exit(1);
}
while (rollModifier <= 0)
{
Console.Write("Please enter a value greater than 0.");
try
{
rollModifier = int.Parse(Console.ReadLine());
}
catch (Exception e)
{
Console.WriteLine("Invalid input." + e);
Environment.Exit(1);
}
}
}
if (modifierChoice == "stop") { Console.WriteLine("\r\nYou stop using a dice modifier."); useRollModifier = "n"; rollModifier = 0; }
}
if (addOrSubtractConfirmation == "exit") { break; }
}
Console.WriteLine("\r\nPlay again soon!");
playerWantsToPlay = false;
}
}
}
}
public class Dice
{
public int value;
public int sides;
public Guid id;
public Dice(int _sides)
{
sides = Math.Abs(_sides);
id = Guid.NewGuid();
Random rnd = new Random();
value = rnd.Next(1, _sides);
}
public void Roll()
{
Random rnd = new Random();
value = rnd.Next(1, sides);
}
}
//shamelessly stolen from StackOverflow 🙏
//implements non-internationalized ordinals for english culture numbers
//source: user samjudson on Aug 21 '08 -- https://stackoverflow.com/questions/20156/is-there-an-easy-way-to-create-ordinals-in-c
class Ordinal
{
public static string AddOrdinal(int num)
{
if (num <= 0) return num.ToString();
switch (num % 100)
{
case 11:
case 12:
case 13:
return num + "th";
}
switch (num % 10)
{
case 1:
return num + "st";
case 2:
return num + "nd";
case 3:
return num + "rd";
default:
return num + "th";
}
}
}
//class DiceGame
//{
// public Guid SessionId {get;}
// public String[] CurrentDiceBoard;
//} | 33.84585 | 185 | 0.433259 | [
"MIT"
] | qhcode/DeviceDice | DeviceDice/Program.cs | 17,131 | C# |
//------------------------------------------------------------------------------
// <auto-generated />
// This file was automatically generated by the UpdateVendors tool.
//------------------------------------------------------------------------------
// Copyright 2013-2015 Serilog Contributors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using SignalFx.Tracing.Vendors.Serilog.Core;
using SignalFx.Tracing.Vendors.Serilog.Core.Filters;
using SignalFx.Tracing.Vendors.Serilog.Events;
namespace SignalFx.Tracing.Vendors.Serilog.Configuration
{
/// <summary>
/// Controls filter configuration.
/// </summary>
internal class LoggerFilterConfiguration
{
readonly LoggerConfiguration _loggerConfiguration;
readonly Action<ILogEventFilter> _addFilter;
internal LoggerFilterConfiguration(
LoggerConfiguration loggerConfiguration,
Action<ILogEventFilter> addFilter)
{
if (loggerConfiguration == null) throw new ArgumentNullException(nameof(loggerConfiguration));
if (addFilter == null) throw new ArgumentNullException(nameof(addFilter));
_loggerConfiguration = loggerConfiguration;
_addFilter = addFilter;
}
/// <summary>
/// Filter out log events from the stream based on the provided filter.
/// </summary>
/// <param name="filters">The filters to apply.</param>
/// <returns>Configuration object allowing method chaining.</returns>
public LoggerConfiguration With(params ILogEventFilter[] filters)
{
if (filters == null) throw new ArgumentNullException(nameof(filters));
foreach (var logEventFilter in filters)
{
if (logEventFilter == null)
throw new ArgumentException("Null filter is not allowed.");
_addFilter(logEventFilter);
}
return _loggerConfiguration;
}
/// <summary>
/// Filter out log events from the stream based on the provided filter.
/// </summary>
/// <typeparam name="TFilter">The filters to apply.</typeparam>
/// <returns>Configuration object allowing method chaining.</returns>
public LoggerConfiguration With<TFilter>()
where TFilter : ILogEventFilter, new()
{
return With(new TFilter());
}
/// <summary>
/// Filter out log events that match a predicate.
/// </summary>
/// <param name="exclusionPredicate">Function that returns true when an event
/// should be excluded (silenced).</param>
/// <returns>Configuration object allowing method chaining.</returns>
public LoggerConfiguration ByExcluding(Func<LogEvent, bool> exclusionPredicate)
{
return With(new DelegateFilter(logEvent => !exclusionPredicate(logEvent)));
}
/// <summary>
/// Filter log events to include only those that match a predicate.
/// </summary>
/// <param name="inclusionPredicate">Function that returns true when an event
/// should be included (emitted).</param>
/// <returns>Configuration object allowing method chaining.</returns>
public LoggerConfiguration ByIncludingOnly(Func<LogEvent, bool> inclusionPredicate)
{
return With(new DelegateFilter(inclusionPredicate));
}
}
}
| 40.969072 | 106 | 0.629844 | [
"Apache-2.0"
] | AJJLVizio/signalfx-dotnet-tracing | src/Datadog.Trace/Vendors/Serilog/Configuration/LoggerFilterConfiguration.cs | 3,974 | C# |
namespace LFHotfixHelper
{
partial class MainForm
{
/// <summary>
///Gerekli tasarımcı değişkeni.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
///Kullanılan tüm kaynakları temizleyin.
/// </summary>
///<param name="disposing">yönetilen kaynaklar dispose edilmeliyse doğru; aksi halde yanlış.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer üretilen kod
/// <summary>
/// Tasarımcı desteği için gerekli metot - bu metodun
///içeriğini kod düzenleyici ile değiştirmeyin.
/// </summary>
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(MainForm));
this.rbConsole = new System.Windows.Forms.RichTextBox();
this.plBottom = new System.Windows.Forms.Panel();
this.lblName = new System.Windows.Forms.Label();
this.pbProgress = new System.Windows.Forms.ProgressBar();
this.plBottom.SuspendLayout();
this.SuspendLayout();
//
// rbConsole
//
this.rbConsole.BackColor = System.Drawing.Color.White;
this.rbConsole.BorderStyle = System.Windows.Forms.BorderStyle.None;
this.rbConsole.Dock = System.Windows.Forms.DockStyle.Top;
this.rbConsole.ForeColor = System.Drawing.Color.White;
this.rbConsole.HideSelection = false;
this.rbConsole.Location = new System.Drawing.Point(0, 0);
this.rbConsole.Name = "rbConsole";
this.rbConsole.ReadOnly = true;
this.rbConsole.Size = new System.Drawing.Size(800, 389);
this.rbConsole.TabIndex = 3;
this.rbConsole.Text = "";
//
// plBottom
//
this.plBottom.BackColor = System.Drawing.SystemColors.Control;
this.plBottom.Controls.Add(this.lblName);
this.plBottom.Controls.Add(this.pbProgress);
this.plBottom.Dock = System.Windows.Forms.DockStyle.Fill;
this.plBottom.Location = new System.Drawing.Point(0, 389);
this.plBottom.Name = "plBottom";
this.plBottom.Size = new System.Drawing.Size(800, 61);
this.plBottom.TabIndex = 4;
this.plBottom.Visible = false;
//
// lblName
//
this.lblName.AutoSize = true;
this.lblName.ForeColor = System.Drawing.Color.Black;
this.lblName.Location = new System.Drawing.Point(9, 10);
this.lblName.Name = "lblName";
this.lblName.Size = new System.Drawing.Size(32, 13);
this.lblName.TabIndex = 1;
this.lblName.Text = "File : ";
//
// pbProgress
//
this.pbProgress.Location = new System.Drawing.Point(12, 26);
this.pbProgress.Name = "pbProgress";
this.pbProgress.Size = new System.Drawing.Size(776, 23);
this.pbProgress.TabIndex = 0;
//
// MainForm
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink;
this.ClientSize = new System.Drawing.Size(800, 450);
this.Controls.Add(this.plBottom);
this.Controls.Add(this.rbConsole);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.SizableToolWindow;
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Name = "MainForm";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "Hotfix Helper";
this.FormClosed += new System.Windows.Forms.FormClosedEventHandler(this.MainForm_FormClosed);
this.Load += new System.EventHandler(this.MainForm_Load);
this.plBottom.ResumeLayout(false);
this.plBottom.PerformLayout();
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.RichTextBox rbConsole;
private System.Windows.Forms.Panel plBottom;
private System.Windows.Forms.Label lblName;
private System.Windows.Forms.ProgressBar pbProgress;
}
}
| 42.878261 | 141 | 0.57899 | [
"MIT"
] | Lufzys/HotfixHelper | HotfixHelper/LFHotfixHelper/MainForm.Designer.cs | 4,954 | C# |
using System.IO;
using System.Runtime.Serialization;
using WolvenKit.CR2W.Reflection;
using FastMember;
using static WolvenKit.CR2W.Types.Enums;
namespace WolvenKit.CR2W.Types
{
[DataContract(Namespace = "")]
[REDMeta]
public class W3PointOfInterestMappinEntity : CR4MapPinEntity
{
public W3PointOfInterestMappinEntity(CR2WFile cr2w, CVariable parent, string name) : base(cr2w, parent, name){ }
public static new CVariable Create(CR2WFile cr2w, CVariable parent, string name) => new W3PointOfInterestMappinEntity(cr2w, parent, name);
public override void Read(BinaryReader file, uint size) => base.Read(file, size);
public override void Write(BinaryWriter file) => base.Write(file);
}
} | 31.608696 | 141 | 0.753783 | [
"MIT"
] | DerinHalil/CP77Tools | CP77.CR2W/Types/W3/RTTIConvert/W3PointOfInterestMappinEntity.cs | 705 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// Este código foi gerado por uma ferramenta.
// Versão de Tempo de Execução: 4.0.30319.42000
//
// As alterações ao arquivo poderão causar comportamento incorreto e serão perdidas se
// o código for recriado
// </auto-generated>
//------------------------------------------------------------------------------
namespace MeuFormularioCarro.Properties
{
/// <summary>
/// Uma classe de recurso fortemente tipados, para pesquisar cadeias de caracteres localizadas etc.
/// </summary>
// Esta classe foi gerada automaticamente pela StronglyTypedResourceBuilder
// classe através de uma ferramenta como ResGen ou Visual Studio.
// Para adicionar ou remover um associado, edite o arquivo .ResX e execute ResGen novamente
// com a opção /str ou reconstrua seu projeto VS.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class Resources
{
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Resources()
{
}
/// <summary>
/// Retorna a instância cacheada de ResourceManager utilizada por esta classe.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager
{
get
{
if ((resourceMan == null))
{
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("MeuFormularioCarro.Properties.Resources", typeof(Resources).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// Substitui a propriedade CurrentUICulture do thread atual para todas
/// as pesquisas de recursos que usam esta classe de recursos fortemente tipados.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture
{
get
{
return resourceCulture;
}
set
{
resourceCulture = value;
}
}
}
}
| 40.625 | 184 | 0.620171 | [
"MIT"
] | aline0liveira/GitC | 2 a 9 de agosto/MeuFormularioCarro/Properties/Resources.Designer.cs | 2,940 | C# |
using System;
using System.Linq;
using ManagementStocks.Core.Entities;
using ManagementStocks.Core.Interfaces;
using ManagementStocks.MVC.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using StockManagement.Utils.QueryUtils;
namespace ManagementStocks.MVC.Controllers
{
public class ProductsController : Controller
{
private readonly ICommandRepository<Product> _productsCommandRepository;
private readonly IQueryRepository<Product> _productsQueryRepository;
private readonly IStocksQueryRepository _stocksQueryRepository;
public ProductsController(
ICommandRepository<Product> productsCommandRepository,
IQueryRepository<Product> productsQueryRepository,
IStocksQueryRepository stocksQueryRepository)
{
_productsCommandRepository = productsCommandRepository;
_productsQueryRepository = productsQueryRepository;
_stocksQueryRepository = stocksQueryRepository;
}
// GET: Products
public IActionResult Index(string sortOrder, string searchString, int? page, int? pageSize)
{
ViewData["NameSortParm"] = string.IsNullOrEmpty(sortOrder) || sortOrder == "name_desc" ? "name" : "name_desc";
ViewData["QttySortParm"] = sortOrder == "qtty" ? "qtty_desc" : "qtty";
ViewData["CurrentFilter"] = searchString;
var queryParameters = new QueryParameters
{
PageNumber = page ?? 1,
PageSize = pageSize ?? 10
};
var sortItem = new QuerySortItem();
switch (sortOrder)
{
case "name_desc":
sortItem.FieldName = "Name";
sortItem.Descending = true;
break;
case "qtty":
sortItem.FieldName = "Qtty";
sortItem.Descending = false;
break;
case "qtty_desc":
sortItem.FieldName = "Qtty";
sortItem.Descending = true;
break;
default:
sortItem.FieldName = "Name";
sortItem.Descending = false;
break;
}
queryParameters.SortItems.Add(sortItem);
if (!string.IsNullOrEmpty(searchString))
{
queryParameters.Filters.Add(new QueryFilterItem
{
FieldName = "Name",
FilterValue = searchString,
FilterOperator = "LIKE",
ParameterName = "Name"
});
}
var products = _productsQueryRepository.Get(queryParameters)
.Select(x => new ProductViewModel
{
Id = x.Id,
Name = x.Name,
Description = x.Description,
Qtty = _stocksQueryRepository.GetProductQtty(x.Id)
}).ToList();
return View(products);
}
// GET: Products/Details/5
public IActionResult Details(Guid? id)
{
if (id == null)
{
return NotFound();
}
var product = _productsQueryRepository.Get(id.Value);
if (product == null)
{
return NotFound();
}
return View(product);
}
// GET: Products/Create
public IActionResult Create()
{
return View();
}
// POST: Products/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult Create([Bind("Id,Name,Description")] Product product)
{
if (ModelState.IsValid)
{
product.Id = Guid.NewGuid();
_productsCommandRepository.Create(product);
return RedirectToAction(nameof(Index));
}
return View(product);
}
// GET: Products/Edit/5
public IActionResult Edit(Guid? id)
{
if (id == null)
{
return NotFound();
}
var product = _productsQueryRepository.Get(id.Value);
if (product == null)
{
return NotFound();
}
return View(product);
}
// POST: Products/Edit/5
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult Edit(Guid id, [Bind("Id,Name,Description")] Product product)
{
if (id != product.Id)
{
return NotFound();
}
if (ModelState.IsValid)
{
try
{
_productsCommandRepository.Update(product);
}
catch (DbUpdateConcurrencyException)
{
if (_productsQueryRepository.Get(product.Id) == null)
{
return NotFound();
}
else
{
throw;
}
}
return RedirectToAction(nameof(Index));
}
return View(product);
}
// GET: Products/Delete/5
public IActionResult Delete(Guid? id)
{
if (id == null)
{
return NotFound();
}
var product = _productsQueryRepository.Get(id.Value);
if (product == null)
{
return NotFound();
}
if (Math.Abs(_stocksQueryRepository.GetProductQtty(id.Value)) > double.Epsilon)
{
return RedirectToAction(nameof(Details), new { id });
}
return View(product);
}
// POST: Products/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public IActionResult DeleteConfirmed(Guid id)
{
if (Math.Abs(_stocksQueryRepository.GetProductQtty(id)) > double.Epsilon)
{
return RedirectToAction(nameof(Index));
}
_productsCommandRepository.Delete(id);
return RedirectToAction(nameof(Index));
}
}
}
| 32.303318 | 122 | 0.512471 | [
"MIT"
] | oanaspoiala/Stock-Management | StockMVC/Controllers/ProductsController.cs | 6,818 | C# |
/*
KeePass Password Safe - The Open-Source Password Manager
Copyright (C) 2003-2016 Dominik Reichl <dominik.reichl@t-online.de>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;
using KeePass.App;
using KeePass.App.Configuration;
using KeePass.Native;
using KeePass.Resources;
using KeePass.UI;
using KeePassLib;
using KeePassLib.Security;
using NativeLib = KeePassLib.Native.NativeLib;
namespace KeePass.Forms
{
public partial class CharPickerForm : Form
{
private ProtectedString m_psWord = null;
private ProtectedString m_psSelected = ProtectedString.Empty;
private SecureEdit m_secWord = new SecureEdit();
private List<Button> m_lButtons = new List<Button>();
private List<Label> m_lLabels = new List<Label>();
private bool m_bFormLoaded = false;
private int m_nFormHeight = 0;
private string m_strInitialFormRect = string.Empty;
private bool m_bSetForeground = false;
private uint m_uCharCount = 0;
private bool? m_bInitHide = null;
private int m_nBannerWidth = -1;
private Font m_fontChars = null;
public ProtectedString SelectedCharacters
{
get { return m_psSelected; }
}
internal static string ShowAndRestore(ProtectedString psWord,
bool bCenterScreen, bool bSetForeground, uint uCharCount, bool? bInitHide)
{
IntPtr h = IntPtr.Zero;
try { h = NativeMethods.GetForegroundWindowHandle(); }
catch(Exception) { Debug.Assert(false); }
CharPickerForm dlg = new CharPickerForm();
dlg.InitEx(psWord, bCenterScreen, bSetForeground, uCharCount, bInitHide);
DialogResult dr = dlg.ShowDialog();
ProtectedString ps = dlg.SelectedCharacters;
string strRet = null;
if((dr == DialogResult.OK) && (ps != null)) strRet = ps.ReadString();
UIUtil.DestroyForm(dlg);
try
{
if(h != IntPtr.Zero)
NativeMethods.EnsureForegroundWindow(h);
}
catch(Exception) { Debug.Assert(false); }
return strRet;
}
public CharPickerForm()
{
InitializeComponent();
Program.Translation.ApplyTo(this);
}
/// <summary>
/// Initialize the dialog.
/// </summary>
/// <param name="psWord">Password to pick characters from.</param>
/// <param name="bCenterScreen">Specifies whether to center the form
/// on the screen or not.</param>
/// <param name="bSetForeground">If <c>true</c>, the window will be
/// brought to the foreground when showing it.</param>
/// <param name="uCharCount">Number of characters to pick. Specify
/// 0 to allow picking a variable amount of characters.</param>
public void InitEx(ProtectedString psWord, bool bCenterScreen,
bool bSetForeground, uint uCharCount, bool? bInitHide)
{
m_psWord = psWord;
if(bCenterScreen) this.StartPosition = FormStartPosition.CenterScreen;
m_bSetForeground = bSetForeground;
m_uCharCount = uCharCount;
m_bInitHide = bInitHide;
}
private void OnFormLoad(object sender, EventArgs e)
{
Debug.Assert(m_psWord != null);
if(m_psWord == null) throw new InvalidOperationException();
m_bFormLoaded = false;
GlobalWindowManager.AddWindow(this);
m_nFormHeight = this.Height; // Before restoring the position/size
string strRect = Program.Config.UI.CharPickerRect;
if(strRect.Length > 0) UIUtil.SetWindowScreenRect(this, strRect);
m_strInitialFormRect = UIUtil.GetWindowScreenRect(this);
m_fontChars = FontUtil.CreateFont("Tahoma", 8.25f, FontStyle.Bold);
this.Icon = Properties.Resources.KeePass;
this.Text = KPRes.PickCharacters + " - " + PwDefs.ShortProductName;
m_secWord.Attach(m_tbSelected, OnSelectedTextChangedEx, true);
PwInputControlGroup.ConfigureHideButton(m_cbHideChars, null);
AceColumn colPw = Program.Config.MainWindow.FindColumn(AceColumnType.Password);
bool bHide = ((colPw != null) ? colPw.HideWithAsterisks : true);
if(m_bInitHide.HasValue) bHide = m_bInitHide.Value;
bHide |= !AppPolicy.Current.UnhidePasswords;
m_cbHideChars.Checked = bHide;
RecreateResizableWindowControls();
if(m_uCharCount > 0)
{
m_btnOK.Enabled = false;
// m_btnOK.Visible = false;
}
if(m_bSetForeground)
{
this.BringToFront();
this.Activate();
}
UIUtil.SetFocus(m_tbSelected, this);
m_bFormLoaded = true;
}
private void OnFormClosed(object sender, FormClosedEventArgs e)
{
CleanUpEx();
GlobalWindowManager.RemoveWindow(this);
}
private void OnBtnOK(object sender, EventArgs e)
{
byte[] pbUtf8 = m_secWord.ToUtf8();
m_psSelected = new ProtectedString(true, pbUtf8);
Array.Clear(pbUtf8, 0, pbUtf8.Length);
}
private void OnBtnCancel(object sender, EventArgs e)
{
}
private void CleanUpEx()
{
string strRect = UIUtil.GetWindowScreenRect(this);
if(strRect != m_strInitialFormRect)
Program.Config.UI.CharPickerRect = strRect;
m_secWord.Detach();
RemoveAllCharButtons();
m_fontChars.Dispose();
}
private void RemoveAllCharButtons()
{
if((m_lButtons != null) && (m_pnlSelect != null))
{
foreach(Button btn in m_lButtons)
{
btn.Click -= this.OnSelectCharacter;
m_pnlSelect.Controls.Remove(btn);
btn.Dispose();
}
m_lButtons.Clear();
}
if((m_lLabels != null) && (m_pnlSelect != null))
{
foreach(Label lbl in m_lLabels)
{
m_pnlSelect.Controls.Remove(lbl);
lbl.Dispose();
}
m_lLabels.Clear();
}
}
private void RecreateResizableWindowControls()
{
string strTitle = KPRes.PickCharacters;
if(m_uCharCount > 0) strTitle += " (" + m_uCharCount.ToString() + ")";
BannerFactory.UpdateBanner(this, m_bannerImage,
Properties.Resources.B48x48_KGPG_Key2, strTitle,
KPRes.PickCharactersDesc, ref m_nBannerWidth);
RemoveAllCharButtons();
string strWord = ((m_psWord != null) ? m_psWord.ReadString() : string.Empty);
if(strWord.Length >= 1)
{
int x = 0;
int nPnlWidth = m_pnlSelect.Width, nPnlHeight = m_pnlSelect.Height;
for(int i = 0; i < strWord.Length; ++i)
{
int w = ((nPnlWidth * (i + 1)) / strWord.Length) - x;
Button btn = new Button();
btn.Location = new Point(x, 0);
btn.Size = new Size(w, nPnlHeight / 2 - 1);
btn.Font = m_fontChars;
btn.Tag = strWord[i];
btn.Click += this.OnSelectCharacter;
m_lButtons.Add(btn);
m_pnlSelect.Controls.Add(btn);
Label lbl = new Label();
lbl.Text = (i + 1).ToString();
lbl.TextAlign = ContentAlignment.MiddleCenter;
lbl.Location = new Point(x, nPnlHeight / 2);
lbl.Size = new Size(w + 1, nPnlHeight / 2 - 3);
m_lLabels.Add(lbl);
m_pnlSelect.Controls.Add(lbl);
x += w;
}
}
OnHideCharsCheckedChanged(null, EventArgs.Empty);
}
private void OnHideCharsCheckedChanged(object sender, EventArgs e)
{
bool bHide = m_cbHideChars.Checked;
if(!bHide && !AppPolicy.Try(AppPolicyId.UnhidePasswords))
{
m_cbHideChars.Checked = true;
return;
}
m_secWord.EnableProtection(bHide);
string strHiddenChar = new string(SecureEdit.PasswordChar, 1);
bool bHideBtns = bHide;
bHideBtns |= !Program.Config.UI.Hiding.UnhideButtonAlsoUnhidesSource;
foreach(Button btn in m_lButtons)
{
if(bHideBtns) btn.Text = strHiddenChar;
else btn.Text = new string((char)btn.Tag, 1);
}
}
private void OnSelectCharacter(object sender, EventArgs e)
{
Button btn = (sender as Button);
if(btn == null) { Debug.Assert(false); return; }
try
{
char ch = (char)btn.Tag;
if(ch == char.MinValue) { Debug.Assert(false); return; }
string strMask = m_tbSelected.Text;
int iSelStart = m_tbSelected.SelectionStart;
int iSelLen = m_tbSelected.SelectionLength;
if(iSelLen >= 1) strMask = strMask.Remove(iSelStart, iSelLen);
strMask = strMask.Insert(iSelStart, new string(ch, 1));
m_tbSelected.Text = strMask;
m_tbSelected.Select(iSelStart + 1, 0);
}
catch(Exception) { Debug.Assert(false); }
}
private void OnFormResize(object sender, EventArgs e)
{
ProcessResize();
}
private void OnFormSizeChanged(object sender, EventArgs e)
{
ProcessResize();
}
private void ProcessResize()
{
if((this.Height != m_nFormHeight) && (m_nFormHeight != 0))
this.Height = m_nFormHeight;
if(m_bFormLoaded) RecreateResizableWindowControls();
}
private void OnSelectedTextChangedEx(object sender, EventArgs e)
{
if((m_uCharCount > 0) && (m_secWord.TextLength == m_uCharCount))
{
// m_btnOK.Visible = true;
m_btnOK.Enabled = true;
m_btnOK.PerformClick();
}
}
}
}
| 27.163265 | 82 | 0.698937 | [
"BSD-3-Clause"
] | FDlucifer/KeeThief | KeePass-2.34-Source-Patched/KeePass/Forms/CharPickerForm.cs | 9,317 | C# |
// Copyright 2020 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// [START dlp_inspect_datastore]
using Google.Api.Gax.ResourceNames;
using Google.Cloud.BigQuery.V2;
using Google.Cloud.Dlp.V2;
using Google.Protobuf.WellKnownTypes;
using System;
using System.Collections.Generic;
using System.Threading;
using static Google.Cloud.Dlp.V2.InspectConfig.Types;
public class InspectCloudDataStore
{
public static object Inspect(
string projectId,
Likelihood minLikelihood,
int maxFindings,
bool includeQuote,
string kindName,
string namespaceId,
IEnumerable<InfoType> infoTypes,
IEnumerable<CustomInfoType> customInfoTypes,
string datasetId,
string tableId)
{
var inspectJob = new InspectJobConfig
{
StorageConfig = new StorageConfig
{
DatastoreOptions = new DatastoreOptions
{
Kind = new KindExpression { Name = kindName },
PartitionId = new PartitionId
{
NamespaceId = namespaceId,
ProjectId = projectId,
}
},
TimespanConfig = new StorageConfig.Types.TimespanConfig
{
StartTime = Timestamp.FromDateTime(System.DateTime.UtcNow.AddYears(-1)),
EndTime = Timestamp.FromDateTime(System.DateTime.UtcNow)
}
},
InspectConfig = new InspectConfig
{
InfoTypes = { infoTypes },
CustomInfoTypes = { customInfoTypes },
Limits = new FindingLimits
{
MaxFindingsPerRequest = maxFindings
},
ExcludeInfoTypes = false,
IncludeQuote = includeQuote,
MinLikelihood = minLikelihood
},
Actions =
{
new Google.Cloud.Dlp.V2.Action
{
// Save results in BigQuery Table
SaveFindings = new Google.Cloud.Dlp.V2.Action.Types.SaveFindings
{
OutputConfig = new OutputStorageConfig
{
Table = new Google.Cloud.Dlp.V2.BigQueryTable
{
ProjectId = projectId,
DatasetId = datasetId,
TableId = tableId
}
}
},
}
}
};
// Issue Create Dlp Job Request
var client = DlpServiceClient.Create();
var request = new CreateDlpJobRequest
{
InspectJob = inspectJob,
ParentAsProjectName = new ProjectName(projectId),
};
// We need created job name
var dlpJob = client.CreateDlpJob(request);
var jobName = dlpJob.Name;
// Make sure the job finishes before inspecting the results.
// Alternatively, we can inspect results opportunistically, but
// for testing purposes, we want consistent outcome
var finishedJob = EnsureJobFinishes(projectId, jobName);
var bigQueryClient = BigQueryClient.Create(projectId);
var table = bigQueryClient.GetTable(datasetId, tableId);
// Return only first page of 10 rows
Console.WriteLine("DLP v2 Results:");
var firstPage = table.ListRows(new ListRowsOptions { StartIndex = 0, PageSize = 10 });
foreach (var item in firstPage)
{
Console.WriteLine($"\t {item[""]}");
}
return finishedJob;
}
private static DlpJob EnsureJobFinishes(string projectId, string jobName)
{
var client = DlpServiceClient.Create();
var request = new GetDlpJobRequest
{
DlpJobName = new DlpJobName(projectId, jobName),
};
// Simple logic that gives the job 5*30 sec at most to complete - for testing purposes only
var numOfAttempts = 5;
do
{
var dlpJob = client.GetDlpJob(request);
numOfAttempts--;
if (dlpJob.State != DlpJob.Types.JobState.Running)
{
return dlpJob;
}
Thread.Sleep(TimeSpan.FromSeconds(30));
} while (numOfAttempts > 0);
throw new InvalidOperationException("Job did not complete in time");
}
}
// [END dlp_inspect_datastore]
| 34.72 | 99 | 0.552803 | [
"ECL-2.0",
"Apache-2.0"
] | andysim3d/dotnet-docs-samples | dlp/api/Snippets/InspectCloudDataStore.cs | 5,208 | C# |
using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
namespace LinqToDB.Expressions
{
using LinqToDB.Extensions;
using Linq;
using Linq.Builder;
using Mapping;
using System.Diagnostics.CodeAnalysis;
static class InternalExtensions
{
#region IsConstant
public static bool IsConstantable(this Type type)
{
if (type.IsEnum)
return true;
switch (type.GetTypeCodeEx())
{
case TypeCode.Int16 :
case TypeCode.Int32 :
case TypeCode.Int64 :
case TypeCode.UInt16 :
case TypeCode.UInt32 :
case TypeCode.UInt64 :
case TypeCode.SByte :
case TypeCode.Byte :
case TypeCode.Decimal :
case TypeCode.Double :
case TypeCode.Single :
case TypeCode.Boolean :
case TypeCode.String :
case TypeCode.Char : return true;
}
if (type.IsNullable())
return type.GetGenericArguments()[0].IsConstantable();
return false;
}
#endregion
#region Caches
static readonly ConcurrentDictionary<MethodInfo,SqlQueryDependentAttribute[]?> _queryDependentMethods =
new ConcurrentDictionary<MethodInfo,SqlQueryDependentAttribute[]?>();
public static void ClearCaches()
{
_queryDependentMethods.Clear();
}
#endregion
#region EqualsTo
internal static bool EqualsTo(this Expression expr1, Expression expr2,
Dictionary<Expression,QueryableAccessor> queryableAccessorDic,
Dictionary<Expression,Expression>? queryDependedObjects,
bool compareConstantValues = false)
{
return EqualsTo(expr1, expr2, new EqualsToInfo(queryableAccessorDic, queryDependedObjects, compareConstantValues));
}
class EqualsToInfo
{
public EqualsToInfo(
Dictionary<Expression, QueryableAccessor> queryableAccessorDic,
Dictionary<Expression, Expression>? queryDependedObjects,
bool compareConstantValues)
{
QueryableAccessorDic = queryableAccessorDic;
QueryDependedObjects = queryDependedObjects;
CompareConstantValues = compareConstantValues;
}
public HashSet<Expression> Visited { get; } = new HashSet<Expression>();
public Dictionary<Expression, QueryableAccessor> QueryableAccessorDic { get; }
public Dictionary<Expression, Expression>? QueryDependedObjects { get; }
public bool CompareConstantValues { get; }
}
static bool EqualsTo(this Expression? expr1, Expression? expr2, EqualsToInfo info)
{
if (expr1 == expr2)
return true;
if (expr1 == null || expr2 == null || expr1.NodeType != expr2.NodeType || expr1.Type != expr2.Type)
return false;
switch (expr1.NodeType)
{
case ExpressionType.Add:
case ExpressionType.AddChecked:
case ExpressionType.And:
case ExpressionType.AndAlso:
case ExpressionType.ArrayIndex:
case ExpressionType.Assign:
case ExpressionType.Coalesce:
case ExpressionType.Divide:
case ExpressionType.Equal:
case ExpressionType.ExclusiveOr:
case ExpressionType.GreaterThan:
case ExpressionType.GreaterThanOrEqual:
case ExpressionType.LeftShift:
case ExpressionType.LessThan:
case ExpressionType.LessThanOrEqual:
case ExpressionType.Modulo:
case ExpressionType.Multiply:
case ExpressionType.MultiplyChecked:
case ExpressionType.NotEqual:
case ExpressionType.Or:
case ExpressionType.OrElse:
case ExpressionType.Power:
case ExpressionType.RightShift:
case ExpressionType.Subtract:
case ExpressionType.SubtractChecked:
{
// var e1 = (BinaryExpression)expr1;
// var e2 = (BinaryExpression)expr2;
return
((BinaryExpression)expr1).Method == ((BinaryExpression)expr2).Method &&
((BinaryExpression)expr1).Conversion.EqualsTo(((BinaryExpression)expr2).Conversion, info) &&
((BinaryExpression)expr1).Left. EqualsTo(((BinaryExpression)expr2).Left, info) &&
((BinaryExpression)expr1).Right. EqualsTo(((BinaryExpression)expr2).Right, info);
}
case ExpressionType.ArrayLength:
case ExpressionType.Convert:
case ExpressionType.ConvertChecked:
case ExpressionType.Negate:
case ExpressionType.NegateChecked:
case ExpressionType.Not:
case ExpressionType.Quote:
case ExpressionType.TypeAs:
case ExpressionType.UnaryPlus:
{
// var e1 = (UnaryExpression)expr1;
// var e2 = (UnaryExpression)expr2;
return
((UnaryExpression)expr1).Method == ((UnaryExpression)expr2).Method &&
((UnaryExpression)expr1).Operand.EqualsTo(((UnaryExpression)expr2).Operand, info);
}
case ExpressionType.Conditional:
{
// var e1 = (ConditionalExpression)expr1;
// var e2 = (ConditionalExpression)expr2;
return
((ConditionalExpression)expr1).Test. EqualsTo(((ConditionalExpression)expr2).Test, info) &&
((ConditionalExpression)expr1).IfTrue. EqualsTo(((ConditionalExpression)expr2).IfTrue, info) &&
((ConditionalExpression)expr1).IfFalse.EqualsTo(((ConditionalExpression)expr2).IfFalse, info);
}
case ExpressionType.Call : return EqualsToX((MethodCallExpression)expr1, (MethodCallExpression)expr2, info);
case ExpressionType.Constant : return EqualsToX((ConstantExpression) expr1, (ConstantExpression) expr2, info);
case ExpressionType.Invoke : return EqualsToX((InvocationExpression)expr1, (InvocationExpression)expr2, info);
case ExpressionType.Lambda : return EqualsToX((LambdaExpression) expr1, (LambdaExpression) expr2, info);
case ExpressionType.ListInit : return EqualsToX((ListInitExpression) expr1, (ListInitExpression) expr2, info);
case ExpressionType.MemberAccess : return EqualsToX((MemberExpression) expr1, (MemberExpression) expr2, info);
case ExpressionType.MemberInit : return EqualsToX((MemberInitExpression)expr1, (MemberInitExpression)expr2, info);
case ExpressionType.New : return EqualsToX((NewExpression) expr1, (NewExpression) expr2, info);
case ExpressionType.NewArrayBounds:
case ExpressionType.NewArrayInit : return EqualsToX((NewArrayExpression) expr1, (NewArrayExpression) expr2, info);
case ExpressionType.Default : return true;
case ExpressionType.Parameter : return ((ParameterExpression) expr1).Name == ((ParameterExpression) expr2).Name;
case ExpressionType.TypeIs:
{
// var e1 = (TypeBinaryExpression)expr1;
// var e2 = (TypeBinaryExpression)expr2;
return
((TypeBinaryExpression)expr1).TypeOperand == ((TypeBinaryExpression)expr2).TypeOperand &&
((TypeBinaryExpression)expr1).Expression.EqualsTo(((TypeBinaryExpression)expr2).Expression, info);
}
case ExpressionType.Block:
return EqualsToX((BlockExpression)expr1, (BlockExpression)expr2, info);
}
throw new InvalidOperationException();
}
static bool EqualsToX(BlockExpression expr1, BlockExpression expr2, EqualsToInfo info)
{
for (var i = 0; i < expr1.Expressions.Count; i++)
if (!expr1.Expressions[i].EqualsTo(expr2.Expressions[i], info))
return false;
for (var i = 0; i < expr1.Variables.Count; i++)
if (!expr1.Variables[i].EqualsTo(expr2.Variables[i], info))
return false;
return true;
}
static bool EqualsToX(NewArrayExpression expr1, NewArrayExpression expr2, EqualsToInfo info)
{
if (expr1.Expressions.Count != expr2.Expressions.Count)
return false;
for (var i = 0; i < expr1.Expressions.Count; i++)
if (!expr1.Expressions[i].EqualsTo(expr2.Expressions[i], info))
return false;
return true;
}
static bool EqualsToX(NewExpression expr1, NewExpression expr2, EqualsToInfo info)
{
if (expr1.Arguments.Count != expr2.Arguments.Count)
return false;
if (expr1.Members == null && expr2.Members != null)
return false;
if (expr1.Members != null && expr2.Members == null)
return false;
if (expr1.Constructor != expr2.Constructor)
return false;
if (expr1.Members != null)
{
if (expr1.Members.Count != expr2.Members!.Count)
return false;
for (var i = 0; i < expr1.Members.Count; i++)
if (expr1.Members[i] != expr2.Members[i])
return false;
}
for (var i = 0; i < expr1.Arguments.Count; i++)
if (!expr1.Arguments[i].EqualsTo(expr2.Arguments[i], info))
return false;
return true;
}
static bool EqualsToX(MemberInitExpression expr1, MemberInitExpression expr2, EqualsToInfo info)
{
if (expr1.Bindings.Count != expr2.Bindings.Count || !expr1.NewExpression.EqualsTo(expr2.NewExpression, info))
return false;
bool CompareBindings(MemberBinding? b1, MemberBinding? b2)
{
if (b1 == b2)
return true;
if (b1 == null || b2 == null || b1.BindingType != b2.BindingType || b1.Member != b2.Member)
return false;
switch (b1.BindingType)
{
case MemberBindingType.Assignment:
return ((MemberAssignment)b1).Expression.EqualsTo(((MemberAssignment)b2).Expression, info);
case MemberBindingType.ListBinding:
var ml1 = (MemberListBinding)b1;
var ml2 = (MemberListBinding)b2;
if (ml1.Initializers.Count != ml2.Initializers.Count)
return false;
for (var i = 0; i < ml1.Initializers.Count; i++)
{
var ei1 = ml1.Initializers[i];
var ei2 = ml2.Initializers[i];
if (ei1.AddMethod != ei2.AddMethod || ei1.Arguments.Count != ei2.Arguments.Count)
return false;
for (var j = 0; j < ei1.Arguments.Count; j++)
if (!ei1.Arguments[j].EqualsTo(ei2.Arguments[j], info))
return false;
}
break;
case MemberBindingType.MemberBinding:
var mm1 = (MemberMemberBinding)b1;
var mm2 = (MemberMemberBinding)b2;
if (mm1.Bindings.Count != mm2.Bindings.Count)
return false;
for (var i = 0; i < mm1.Bindings.Count; i++)
if (!CompareBindings(mm1.Bindings[i], mm2.Bindings[i]))
return false;
break;
}
return true;
}
for (var i = 0; i < expr1.Bindings.Count; i++)
{
var b1 = expr1.Bindings[i];
var b2 = expr2.Bindings[i];
if (!CompareBindings(b1, b2))
return false;
}
return true;
}
static bool EqualsToX(MemberExpression expr1, MemberExpression expr2, EqualsToInfo info)
{
if (expr1.Member == expr2.Member)
{
if (expr1.Expression == expr2.Expression || expr1.Expression.Type == expr2.Expression.Type)
{
if (info.QueryableAccessorDic.Count > 0)
{
if (info.QueryableAccessorDic.TryGetValue(expr1, out var qa))
return
expr1.Expression.EqualsTo(expr2.Expression, info) &&
qa.Queryable.Expression.EqualsTo(qa.Accessor(expr2).Expression, info);
}
}
return expr1.Expression.EqualsTo(expr2.Expression, info);
}
return false;
}
static bool EqualsToX(ListInitExpression expr1, ListInitExpression expr2, EqualsToInfo info)
{
if (expr1.Initializers.Count != expr2.Initializers.Count || !expr1.NewExpression.EqualsTo(expr2.NewExpression, info))
return false;
for (var i = 0; i < expr1.Initializers.Count; i++)
{
var i1 = expr1.Initializers[i];
var i2 = expr2.Initializers[i];
if (i1.Arguments.Count != i2.Arguments.Count || i1.AddMethod != i2.AddMethod)
return false;
for (var j = 0; j < i1.Arguments.Count; j++)
if (!i1.Arguments[j].EqualsTo(i2.Arguments[j], info))
return false;
}
return true;
}
static bool EqualsToX(LambdaExpression expr1, LambdaExpression expr2, EqualsToInfo info)
{
if (expr1.Parameters.Count != expr2.Parameters.Count || !expr1.Body.EqualsTo(expr2.Body, info))
return false;
for (var i = 0; i < expr1.Parameters.Count; i++)
if (!expr1.Parameters[i].EqualsTo(expr2.Parameters[i], info))
return false;
return true;
}
static bool EqualsToX(InvocationExpression expr1, InvocationExpression expr2, EqualsToInfo info)
{
if (expr1.Arguments.Count != expr2.Arguments.Count || !expr1.Expression.EqualsTo(expr2.Expression, info))
return false;
for (var i = 0; i < expr1.Arguments.Count; i++)
if (!expr1.Arguments[i].EqualsTo(expr2.Arguments[i], info))
return false;
return true;
}
static bool EqualsToX(ConstantExpression expr1, ConstantExpression expr2, EqualsToInfo info)
{
if (expr1.Value == null && expr2.Value == null)
return true;
if (IsConstantable(expr1.Type))
return Equals(expr1.Value, expr2.Value);
if (expr1.Value == null || expr2.Value == null)
return false;
if (expr1.Value is IQueryable queryable)
{
var eq1 = queryable.Expression;
var eq2 = ((IQueryable)expr2.Value).Expression;
if (!info.Visited.Contains(eq1))
{
info.Visited.Add(eq1);
return eq1.EqualsTo(eq2, info);
}
}
else if (expr1.Value is IEnumerable list1 && expr2.Value is IEnumerable list2)
{
var enum1 = list1.GetEnumerator();
var enum2 = list2.GetEnumerator();
using (enum1 as IDisposable)
using (enum2 as IDisposable)
{
while (enum1.MoveNext())
{
if (!enum2.MoveNext() || !object.Equals(enum1.Current, enum2.Current))
return false;
}
if (enum2.MoveNext())
return false;
}
return true;
}
return !info.CompareConstantValues || expr1.Value == expr2.Value;
}
static bool EqualsToX(MethodCallExpression expr1, MethodCallExpression expr2, EqualsToInfo info)
{
if (expr1.Arguments.Count != expr2.Arguments.Count || expr1.Method != expr2.Method)
return false;
if (!expr1.Object.EqualsTo(expr2.Object, info))
return false;
var parameters = expr1.Method.GetParameters();
var dependentParameters = _queryDependentMethods.GetOrAdd(
expr1.Method, mi =>
{
var arr = parameters
.Select(p => p.GetCustomAttributes(typeof(SqlQueryDependentAttribute), false).OfType<SqlQueryDependentAttribute>().FirstOrDefault())
.ToArray();
return arr.Any(a => a != null) ? arr : null;
});
bool DefaultCompareArguments(Expression arg1, Expression arg2)
{
if (typeof(Sql.IQueryableContainer).IsSameOrParentOf(arg1.Type))
{
if (arg1.NodeType == ExpressionType.Constant && arg2.NodeType == ExpressionType.Constant)
{
var query1 = ((Sql.IQueryableContainer)arg1.EvaluateExpression()!).Query;
var query2 = ((Sql.IQueryableContainer)arg2.EvaluateExpression()!).Query;
return EqualsTo(query1.Expression, query2.Expression, info);
}
}
if (!arg1.EqualsTo(arg2, info))
return false;
return true;
}
if (dependentParameters == null)
{
for (var i = 0; i < expr1.Arguments.Count; i++)
{
if (!DefaultCompareArguments(expr1.Arguments[i], expr2.Arguments[i]))
return false;
}
}
else
{
for (var i = 0; i < expr1.Arguments.Count; i++)
{
var dependentAttribute = dependentParameters[i];
if (dependentAttribute != null)
{
var prevArg = expr1.Arguments[i];
if (info.QueryDependedObjects != null && info.QueryDependedObjects.TryGetValue(expr1.Arguments[i], out var nevValue))
prevArg = nevValue;
if (!dependentAttribute.ExpressionsEqual(prevArg, expr2.Arguments[i], (e1, e2) => e1.EqualsTo(e2, info)))
return false;
}
else
{
if (!DefaultCompareArguments(expr1.Arguments[i], expr2.Arguments[i]))
return false;
}
}
}
if (info.QueryableAccessorDic.Count > 0)
if (info.QueryableAccessorDic.TryGetValue(expr1, out var qa))
return qa.Queryable.Expression.EqualsTo(qa.Accessor(expr2).Expression, info);
return true;
}
#endregion
#region Path
class PathInfo
{
public PathInfo(
HashSet<Expression> visited,
Action<Expression,Expression> func)
{
Visited = visited;
Func = func;
}
public HashSet<Expression> Visited;
public Action<Expression,Expression> Func;
}
static Expression ConvertTo(Expression expr, Type type)
{
return Expression.Convert(expr, type);
}
static void Path<T>(IEnumerable<T> source, Expression path, MethodInfo property, Action<T,Expression> func)
where T : class
{
#if DEBUG
_callCounter4++;
#endif
var prop = Expression.Property(path, property);
var i = 0;
foreach (var item in source)
func(item, Expression.Call(prop, ReflectionHelper.IndexExpressor<T>.Item, new Expression[] { Expression.Constant(i++) }));
}
static void Path<T>(PathInfo info, IEnumerable<T> source, Expression path, MethodInfo property)
where T : Expression
{
#if DEBUG
_callCounter3++;
#endif
var prop = Expression.Property(path, property);
var i = 0;
foreach (var item in source)
Path(info, item, Expression.Call(prop, ReflectionHelper.IndexExpressor<T>.Item, Expression.Constant(i++)));
}
static void Path(PathInfo info, Expression expr, Expression path, MethodInfo property)
{
#if DEBUG
_callCounter2++;
#endif
Path(info, expr, Expression.Property(path, property));
}
public static void Path(this Expression expr, Expression path, Action<Expression, Expression> func)
{
#if DEBUG
_callCounter1 = 0;
_callCounter2 = 0;
_callCounter3 = 0;
_callCounter4 = 0;
#endif
Path(new PathInfo(new HashSet<Expression>(), func), expr, path);
}
#if DEBUG
static int _callCounter1;
static int _callCounter2;
static int _callCounter3;
static int _callCounter4;
#endif
static void Path(PathInfo info, Expression? expr, Expression path)
{
#if DEBUG
_callCounter1++;
#endif
if (expr == null)
return;
switch (expr.NodeType)
{
case ExpressionType.Add:
case ExpressionType.AddChecked:
case ExpressionType.And:
case ExpressionType.AndAlso:
case ExpressionType.ArrayIndex:
case ExpressionType.Assign:
case ExpressionType.Coalesce:
case ExpressionType.Divide:
case ExpressionType.Equal:
case ExpressionType.ExclusiveOr:
case ExpressionType.GreaterThan:
case ExpressionType.GreaterThanOrEqual:
case ExpressionType.LeftShift:
case ExpressionType.LessThan:
case ExpressionType.LessThanOrEqual:
case ExpressionType.Modulo:
case ExpressionType.Multiply:
case ExpressionType.MultiplyChecked:
case ExpressionType.NotEqual:
case ExpressionType.Or:
case ExpressionType.OrElse:
case ExpressionType.Power:
case ExpressionType.RightShift:
case ExpressionType.Subtract:
case ExpressionType.SubtractChecked:
{
path = ConvertTo(path, typeof(BinaryExpression));
Path(info, ((BinaryExpression)expr).Conversion, Expression.Property(path, ReflectionHelper.Binary.Conversion));
Path(info, ((BinaryExpression)expr).Left, Expression.Property(path, ReflectionHelper.Binary.Left));
Path(info, ((BinaryExpression)expr).Right, Expression.Property(path, ReflectionHelper.Binary.Right));
break;
}
case ExpressionType.ArrayLength:
case ExpressionType.Convert:
case ExpressionType.ConvertChecked:
case ExpressionType.Negate:
case ExpressionType.NegateChecked:
case ExpressionType.Not:
case ExpressionType.Quote:
case ExpressionType.TypeAs:
case ExpressionType.UnaryPlus:
Path(
info,
((UnaryExpression)expr).Operand,
path = ConvertTo(path, typeof(UnaryExpression)),
ReflectionHelper.Unary.Operand);
break;
case ExpressionType.Call:
{
path = ConvertTo(path, typeof(MethodCallExpression));
Path(info, ((MethodCallExpression)expr).Object, path, ReflectionHelper.MethodCall.Object);
Path(info, ((MethodCallExpression)expr).Arguments, path, ReflectionHelper.MethodCall.Arguments);
break;
}
case ExpressionType.Conditional:
{
path = ConvertTo(path, typeof(ConditionalExpression));
Path(info, ((ConditionalExpression)expr).Test, path, ReflectionHelper.Conditional.Test);
Path(info, ((ConditionalExpression)expr).IfTrue, path, ReflectionHelper.Conditional.IfTrue);
Path(info, ((ConditionalExpression)expr).IfFalse, path, ReflectionHelper.Conditional.IfFalse);
break;
}
case ExpressionType.Invoke:
{
path = ConvertTo(path, typeof(InvocationExpression));
Path(info, ((InvocationExpression)expr).Expression, path, ReflectionHelper.Invocation.Expression);
Path(info, ((InvocationExpression)expr).Arguments, path, ReflectionHelper.Invocation.Arguments);
break;
}
case ExpressionType.Lambda:
{
path = ConvertTo(path, typeof(LambdaExpression));
Path(info, ((LambdaExpression)expr).Body, path, ReflectionHelper.LambdaExpr.Body);
Path(info, ((LambdaExpression)expr).Parameters, path, ReflectionHelper.LambdaExpr.Parameters);
break;
}
case ExpressionType.ListInit:
{
path = ConvertTo(path, typeof(ListInitExpression));
Path(info, ((ListInitExpression)expr).NewExpression, path, ReflectionHelper.ListInit.NewExpression);
Path( ((ListInitExpression)expr).Initializers, path, ReflectionHelper.ListInit.Initializers,
(ex, p) => Path(info, ex.Arguments, p, ReflectionHelper.ElementInit.Arguments));
break;
}
case ExpressionType.MemberAccess:
Path(
info,
((MemberExpression)expr).Expression,
path = ConvertTo(path, typeof(MemberExpression)),
ReflectionHelper.Member.Expression);
break;
case ExpressionType.MemberInit:
{
void Modify(MemberBinding b, Expression pinf)
{
switch (b.BindingType)
{
case MemberBindingType.Assignment:
Path(
info,
((MemberAssignment)b).Expression,
ConvertTo(pinf, typeof(MemberAssignment)),
ReflectionHelper.MemberAssignmentBind.Expression);
break;
case MemberBindingType.ListBinding:
Path(
((MemberListBinding)b).Initializers,
ConvertTo(pinf, typeof(MemberListBinding)),
ReflectionHelper.MemberListBind.Initializers,
(p, psi) => Path(info, p.Arguments, psi, ReflectionHelper.ElementInit.Arguments));
break;
case MemberBindingType.MemberBinding:
Path(
((MemberMemberBinding)b).Bindings,
ConvertTo(pinf, typeof(MemberMemberBinding)),
ReflectionHelper.MemberMemberBind.Bindings,
Modify);
break;
}
}
path = ConvertTo(path, typeof(MemberInitExpression));
Path(info, ((MemberInitExpression)expr).NewExpression, path, ReflectionHelper.MemberInit.NewExpression);
Path( ((MemberInitExpression)expr).Bindings, path, ReflectionHelper.MemberInit.Bindings, Modify);
break;
}
case ExpressionType.New:
Path(
info,
((NewExpression)expr).Arguments,
path = ConvertTo(path, typeof(NewExpression)),
ReflectionHelper.New.Arguments);
break;
case ExpressionType.NewArrayBounds:
Path(
info,
((NewArrayExpression)expr).Expressions,
path = ConvertTo(path, typeof(NewArrayExpression)),
ReflectionHelper.NewArray.Expressions);
break;
case ExpressionType.NewArrayInit:
Path(
info,
((NewArrayExpression)expr).Expressions,
path = ConvertTo(path, typeof(NewArrayExpression)),
ReflectionHelper.NewArray.Expressions);
break;
case ExpressionType.TypeIs:
Path(
info,
((TypeBinaryExpression)expr).Expression,
path = ConvertTo(path, typeof(TypeBinaryExpression)),
ReflectionHelper.TypeBinary.Expression);
break;
case ExpressionType.Block:
{
path = ConvertTo(path, typeof(BlockExpression));
Path(info,((BlockExpression)expr).Expressions, path, ReflectionHelper.Block.Expressions);
Path(info,((BlockExpression)expr).Variables, path, ReflectionHelper.Block.Variables); // ?
break;
}
case ExpressionType.Constant:
{
path = ConvertTo(path, typeof(ConstantExpression));
if (((ConstantExpression)expr).Value is IQueryable iq && !info.Visited.Contains(iq.Expression))
{
info.Visited.Add(iq.Expression);
Expression p = Expression.Property(path, ReflectionHelper.Constant.Value);
p = ConvertTo(p, typeof(IQueryable));
Path(info, iq.Expression, p, ReflectionHelper.QueryableInt.Expression);
}
break;
}
case ExpressionType.Parameter: path = ConvertTo(path, typeof(ParameterExpression)); break;
case ExpressionType.Extension:
{
if (expr.CanReduce)
{
expr = expr.Reduce();
Path(info, expr, path);
}
break;
}
}
info.Func(expr, path);
}
#endregion
#region Helpers
[return: NotNullIfNotNull("ex")]
public static Expression? Unwrap(this Expression? ex)
{
if (ex == null)
return null;
switch (ex.NodeType)
{
case ExpressionType.Quote :
case ExpressionType.ConvertChecked :
case ExpressionType.Convert :
return ((UnaryExpression)ex).Operand.Unwrap();
}
return ex;
}
[return: NotNullIfNotNull("ex")]
public static Expression? UnwrapConvert(this Expression? ex)
{
if (ex == null)
return null;
switch (ex.NodeType)
{
case ExpressionType.ConvertChecked :
case ExpressionType.Convert :
return ((UnaryExpression)ex).Operand.Unwrap();
}
return ex;
}
[return: NotNullIfNotNull("ex")]
public static Expression? UnwrapWithAs(this Expression? ex)
{
if (ex == null)
return null;
switch (ex.NodeType)
{
case ExpressionType.TypeAs:
return ((UnaryExpression)ex).Operand.Unwrap();
}
return ex.Unwrap();
}
public static Expression SkipPathThrough(this Expression expr)
{
while (expr is MethodCallExpression mce && mce.IsQueryable("AsQueryable"))
expr = mce.Arguments[0];
return expr;
}
public static Expression SkipMethodChain(this Expression expr, MappingSchema mappingSchema)
{
return Sql.ExtensionAttribute.ExcludeExtensionChain(mappingSchema, expr);
}
public static Dictionary<Expression,Expression> GetExpressionAccessors(this Expression expression, Expression path)
{
var accessors = new Dictionary<Expression,Expression>();
expression.Path(path, (e,p) =>
{
switch (e.NodeType)
{
case ExpressionType.Call :
case ExpressionType.MemberAccess :
case ExpressionType.New :
if (!accessors.ContainsKey(e))
accessors.Add(e, p);
break;
case ExpressionType.Constant :
if (!accessors.ContainsKey(e))
accessors.Add(e, Expression.Property(p, ReflectionHelper.Constant.Value));
break;
case ExpressionType.ConvertChecked :
case ExpressionType.Convert :
if (!accessors.ContainsKey(e))
{
var ue = (UnaryExpression)e;
switch (ue.Operand.NodeType)
{
case ExpressionType.Call :
case ExpressionType.MemberAccess :
case ExpressionType.New :
case ExpressionType.Constant :
accessors.Add(e, p);
break;
}
}
break;
}
});
return accessors;
}
[return: NotNullIfNotNull("expr")]
public static Expression? GetRootObject(this Expression? expr, MappingSchema mapping)
{
if (expr == null)
return null;
expr = expr.SkipMethodChain(mapping);
switch (expr.NodeType)
{
case ExpressionType.Call :
{
var e = (MethodCallExpression)expr;
if (e.Object != null)
return GetRootObject(e.Object, mapping);
if (e.Arguments?.Count > 0 &&
(e.IsQueryable() || e.IsAggregate(mapping) || e.IsAssociation(mapping) || e.Method.IsSqlPropertyMethodEx()))
return GetRootObject(e.Arguments[0], mapping);
break;
}
case ExpressionType.MemberAccess :
{
var e = (MemberExpression)expr;
if (e.Expression != null)
return GetRootObject(e.Expression.UnwrapWithAs(), mapping);
break;
}
}
return expr;
}
public static List<Expression> GetMembers(this Expression? expr)
{
if (expr == null)
return new List<Expression>();
List<Expression> list;
switch (expr.NodeType)
{
case ExpressionType.Call :
{
var e = (MethodCallExpression)expr;
if (e.Object != null)
list = GetMembers(e.Object);
else if (e.Arguments?.Count > 0 && e.IsQueryable())
list = GetMembers(e.Arguments[0]);
else
list = new List<Expression>();
break;
}
case ExpressionType.MemberAccess :
{
var e = (MemberExpression)expr;
list = e.Expression != null ? GetMembers(e.Expression.Unwrap()) : new List<Expression>();
break;
}
default :
list = new List<Expression>();
break;
}
list.Add(expr);
return list;
}
public static bool IsQueryable(this MethodCallExpression method, bool enumerable = true)
{
var type = method.Method.DeclaringType;
return type == typeof(Queryable) || (enumerable && type == typeof(Enumerable)) || type == typeof(LinqExtensions) || type == typeof(DataExtensions);
}
public static bool IsAsyncExtension(this MethodCallExpression method, bool enumerable = true)
{
var type = method.Method.DeclaringType;
return type == typeof(AsyncExtensions);
}
public static bool IsAggregate(this MethodCallExpression methodCall, MappingSchema mapping)
{
if (methodCall.IsQueryable(AggregationBuilder.MethodNames))
return true;
if (methodCall.Arguments.Count > 0)
{
var function = AggregationBuilder.GetAggregateDefinition(methodCall, mapping);
return function != null;
}
return false;
}
public static bool IsExtensionMethod(this MethodCallExpression methodCall, MappingSchema mapping)
{
var functions = mapping.GetAttributes<Sql.ExtensionAttribute>(methodCall.Method.ReflectedType,
methodCall.Method,
f => f.Configuration);
return functions.Any();
}
public static bool IsQueryable(this MethodCallExpression method, string name)
{
return method.Method.Name == name && method.IsQueryable();
}
public static bool IsQueryable(this MethodCallExpression method, params string[] names)
{
if (method.IsQueryable())
foreach (var name in names)
if (method.Method.Name == name)
return true;
return false;
}
public static bool IsAsyncExtension(this MethodCallExpression method, params string[] names)
{
if (method.IsAsyncExtension())
foreach (var name in names)
if (method.Method.Name == name + "Async")
return true;
return false;
}
public static bool IsSameGenericMethod(this MethodCallExpression method, MethodInfo genericMethodInfo)
{
if (!method.Method.IsGenericMethod)
return false;
return method.Method.GetGenericMethodDefinition() == genericMethodInfo;
}
public static bool IsSameGenericMethod(this MethodCallExpression method, params MethodInfo[] genericMethodInfo)
{
if (!method.Method.IsGenericMethod)
return false;
var genericDefinition = method.Method.GetGenericMethodDefinition();
return Array.IndexOf(genericMethodInfo, genericDefinition) >= 0;
}
public static bool IsAssociation(this MethodCallExpression method, MappingSchema mappingSchema)
{
return mappingSchema.GetAttribute<AssociationAttribute>(method.Method.DeclaringType, method.Method) != null;
}
public static bool IsCte(this MethodCallExpression method, MappingSchema mappingSchema)
{
return method.IsQueryable("AsCte", "GetCte");
}
static Expression FindLevel(Expression expression, MappingSchema mapping, int level, ref int current)
{
switch (expression.NodeType)
{
case ExpressionType.Call :
{
var call = (MethodCallExpression)expression;
var expr = call.Object;
if (expr == null && (call.IsQueryable() || call.IsAggregate(mapping) || call.IsExtensionMethod(mapping) || call.IsAssociation(mapping) || call.Method.IsSqlPropertyMethodEx()) && call.Arguments.Count > 0)
expr = call.Arguments[0];
if (expr != null)
{
var ex = FindLevel(expr, mapping, level, ref current);
if (level == current)
return ex;
current++;
}
break;
}
case ExpressionType.MemberAccess:
{
var e = ((MemberExpression)expression);
if (e.Expression != null)
{
var expr = FindLevel(e.Expression.UnwrapWithAs(), mapping, level, ref current);
if (level == current)
return expr;
current++;
}
break;
}
}
return expression;
}
/// <summary>
/// Returns part of expression based on its level.
/// </summary>
/// <param name="expression">Base expression that needs decomposition.</param>
/// <param name="mapping">Maping schema.</param>
/// <param name="level">Level that should be to be extracted.</param>
/// <returns>Exstracted expression.</returns>
/// <example>
/// This sample shows what method returns for expression [c.ParentId].
/// <code>
/// expression.GetLevelExpression(mapping, 0) == [c]
/// expression.GetLevelExpression(mapping, 1) == [c.ParentId]
/// </code>
/// </example>
public static Expression GetLevelExpression(this Expression expression, MappingSchema mapping, int level)
{
var current = 0;
var expr = FindLevel(expression, mapping, level, ref current);
if (expr == null || current != level)
throw new InvalidOperationException();
return expr;
}
public static int GetLevel(this Expression expression)
{
switch (expression.NodeType)
{
case ExpressionType.MemberAccess:
{
var e = ((MemberExpression)expression);
if (e.Expression != null)
return GetLevel(e.Expression.Unwrap()) + 1;
break;
}
}
return 0;
}
public static object? EvaluateExpression(this Expression? expr)
{
if (expr == null)
return null;
switch (expr.NodeType)
{
case ExpressionType.Constant:
return ((ConstantExpression)expr).Value;
case ExpressionType.MemberAccess:
{
var member = (MemberExpression) expr;
if (member.Member.IsFieldEx())
return ((FieldInfo)member.Member).GetValue(member.Expression.EvaluateExpression());
if (member.Member.IsPropertyEx())
return ((PropertyInfo)member.Member).GetValue(member.Expression.EvaluateExpression(), null);
break;
}
case ExpressionType.Call:
{
var mc = (MethodCallExpression)expr;
var arguments = mc.Arguments.Select(EvaluateExpression).ToArray();
var instance = mc.Object.EvaluateExpression();
return mc.Method.Invoke(instance, arguments);
}
}
var value = Expression.Lambda(expr).Compile().DynamicInvoke();
return value;
}
#endregion
}
}
| 29.854905 | 210 | 0.65066 | [
"MIT"
] | ozergurbanov1/linq2db | Source/LinqToDB/Expressions/InternalExtensions.cs | 35,004 | 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 waf-regional-2016-11-28.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.WAFRegional.Model
{
/// <summary>
/// Container for the parameters to the GetPermissionPolicy operation.
/// Returns the IAM policy attached to the RuleGroup.
/// </summary>
public partial class GetPermissionPolicyRequest : AmazonWAFRegionalRequest
{
private string _resourceArn;
/// <summary>
/// Gets and sets the property ResourceArn.
/// <para>
/// The Amazon Resource Name (ARN) of the RuleGroup for which you want to get the policy.
/// </para>
/// </summary>
[AWSProperty(Required=true, Min=1, Max=1224)]
public string ResourceArn
{
get { return this._resourceArn; }
set { this._resourceArn = value; }
}
// Check to see if ResourceArn property is set
internal bool IsSetResourceArn()
{
return this._resourceArn != null;
}
}
} | 31.293103 | 110 | 0.666116 | [
"Apache-2.0"
] | FoxBearBear/aws-sdk-net | sdk/src/Services/WAFRegional/Generated/Model/GetPermissionPolicyRequest.cs | 1,815 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Windows.Forms;
using System.Linq;
using System.Threading;
using System.Media;
using NAudio.Wave;
using System.Diagnostics;
using System.ComponentModel;
using System.Reflection;
namespace AudioHotkeySoundboard
{
public partial class MainForm : Form
{
WaveIn loopbackSourceStream = null;
BufferedWaveProvider loopbackWaveProvider = null;
WaveOut loopbackWaveOut = null;
Random rand = new Random();
// A lot of this code depends on soundHotkeys and dgvKeySounds both being sorted alphabetically
// They aren't synced with each other in any way, so if one isn't properly sorted and you try to play a sound it can play the wrong sound
internal List<XMLSettings.SoundHotkey> soundHotkeys = new List<XMLSettings.SoundHotkey>();
internal string xmlLoc = "";
public static MainForm Instance;
public MainForm()
{
Instance = this;
InitializeComponent();
loadSoundDevices();
XMLSettings.LoadSoundboardSettingsXML();
if (cbPlaybackDevices.Items.Contains(XMLSettings.soundboardSettings.LastPlaybackDevice)) cbPlaybackDevices.SelectedItem = XMLSettings.soundboardSettings.LastPlaybackDevice;
if (cbPlaybackDevices2.Items.Contains(XMLSettings.soundboardSettings.LastPlaybackDevice2)) cbPlaybackDevices2.SelectedItem = XMLSettings.soundboardSettings.LastPlaybackDevice2;
if (cbLoopbackDevices.Items.Contains(XMLSettings.soundboardSettings.LastLoopbackDevice)) cbLoopbackDevices.SelectedItem = XMLSettings.soundboardSettings.LastLoopbackDevice;
//add events after settings have been loaded
cbPlaybackDevices.SelectedIndexChanged += cbPlaybackDevices_SelectedIndexChanged;
cbPlaybackDevices2.SelectedIndexChanged += cbPlaybackDevices2_SelectedIndexChanged;
cbLoopbackDevices.SelectedIndexChanged += cbLoopbackDevices_SelectedIndexChanged;
mainTimer.Enabled = true;
initAudioPlaybackEngine();
string filePath = Path.GetDirectoryName(Application.ExecutablePath) + "\\AHS-autosave.xml";
if (File.Exists(filePath))
{
loadXMLFile(filePath);
}
}
private void initAudioPlaybackEngine()
{
int deviceNumberPrimary = cbPlaybackDevices.SelectedIndex - 1;
int deviceNumberSecondary = cbPlaybackDevices2.SelectedIndex - 1;
AudioPlaybackEngine.Primary.Dispose();
AudioPlaybackEngine.Secondary.Dispose();
stopLoopback();
// Primary Playback
if (cbPlaybackDevices.SelectedIndex > 0)
{
try
{
AudioPlaybackEngine.Primary.Init(deviceNumberPrimary);
}
catch (NAudio.MmException ex)
{
SystemSounds.Beep.Play();
string msg = ex.ToString();
if (msg.Contains("AlreadyAllocated calling waveOutOpen"))
{
msg = "Failed to open device for primary playback device. Already in exclusive use by another application? \n\n" + msg;
}
MessageBox.Show(msg);
}
}
// Secondary Playback
if (cbPlaybackDevices2.SelectedIndex > 0)
{
try
{
AudioPlaybackEngine.Secondary.Init(deviceNumberSecondary);
}
catch (NAudio.MmException ex)
{
SystemSounds.Beep.Play();
string msg = ex.ToString();
if (msg.Contains("AlreadyAllocated calling waveOutOpen"))
{
msg = "Failed to open device for secondary playback device. Already in exclusive use by another application? \n\n" + msg;
}
MessageBox.Show(msg);
}
}
if (cbLoopbackDevices.SelectedIndex > 0) // loopback should only start if we have a primary playback device to loopback into
startLoopback();
}
private void loadSoundDevices()
{
var playbackSources = new List<WaveOutCapabilities>();
var loopbackSources = new List<WaveInCapabilities>();
for (int i = 0; i < WaveOut.DeviceCount; i++)
{
playbackSources.Add(WaveOut.GetCapabilities(i));
}
for (int i = 0; i < WaveIn.DeviceCount; i++)
{
loopbackSources.Add(WaveIn.GetCapabilities(i));
}
cbPlaybackDevices.Items.Clear();
cbPlaybackDevices2.Items.Clear();
cbLoopbackDevices.Items.Clear();
cbPlaybackDevices.Items.Add("");
cbPlaybackDevices2.Items.Add("");
cbLoopbackDevices.Items.Add("");
foreach (var source in playbackSources)
{
cbPlaybackDevices.Items.Add(source.ProductName);
cbPlaybackDevices2.Items.Add(source.ProductName);
}
cbPlaybackDevices.SelectedIndex = 0;
cbPlaybackDevices2.SelectedIndex = 0;
foreach (var source in loopbackSources)
{
cbLoopbackDevices.Items.Add(source.ProductName);
}
cbLoopbackDevices.SelectedIndex = 0;
}
private void startLoopback()
{
stopLoopback();
int deviceNumber = cbLoopbackDevices.SelectedIndex - 1;
if (deviceNumber >= 0)
{
if (loopbackSourceStream == null)
loopbackSourceStream = new WaveIn();
loopbackSourceStream.DeviceNumber = deviceNumber;
loopbackSourceStream.WaveFormat = new WaveFormat(44100, WaveIn.GetCapabilities(deviceNumber).Channels);
loopbackSourceStream.BufferMilliseconds = 25;
loopbackSourceStream.NumberOfBuffers = 5;
loopbackSourceStream.DataAvailable += loopbackSourceStream_DataAvailable;
loopbackWaveProvider = new BufferedWaveProvider(loopbackSourceStream.WaveFormat);
loopbackWaveProvider.DiscardOnBufferOverflow = true;
if (loopbackWaveOut == null)
loopbackWaveOut = new WaveOut();
loopbackWaveOut.DeviceNumber = cbPlaybackDevices.SelectedIndex - 1; // Loopback only goes through the primary playback device
loopbackWaveOut.DesiredLatency = 125;
loopbackWaveOut.Init(loopbackWaveProvider);
loopbackSourceStream.StartRecording();
loopbackWaveOut.Play();
}
}
private void stopLoopback()
{
try
{
if (loopbackWaveOut != null)
{
loopbackWaveOut.Stop();
loopbackWaveOut.Dispose();
loopbackWaveOut = null;
}
if (loopbackWaveProvider != null)
{
loopbackWaveProvider.ClearBuffer();
loopbackWaveProvider = null;
}
if (loopbackSourceStream != null)
{
loopbackSourceStream.StopRecording();
loopbackSourceStream.Dispose();
loopbackSourceStream = null;
}
}
catch (Exception) { }
}
private void stopPlayback()
{
AudioPlaybackEngine.Primary.StopAllSounds();
AudioPlaybackEngine.Secondary.StopAllSounds();
}
private void playSelection()
{
if (dgvKeySounds.SelectedRows.Count > 0)
playKeySound(soundHotkeys[dgvKeySounds.SelectedRows[0].Index]);
}
private void playSound(string file)
{
if (!XMLSettings.soundboardSettings.PlaySoundsOverEachOther) stopPlayback();
try
{
//AudioPlaybackEngine.Primary.PlaySound(file);
//AudioPlaybackEngine.Secondary.PlaySound(file);
CachedSound cachedSound = null;
if (!AudioPlaybackEngine.cachedSounds.TryGetValue(file, out cachedSound))
{
cachedSound = new CachedSound(file);
AudioPlaybackEngine.cachedSounds.Add(file, cachedSound);
}
AudioPlaybackEngine.Primary.PlaySound(cachedSound);
AudioPlaybackEngine.Secondary.PlaySound(cachedSound);
}
catch (FormatException ex)
{
SystemSounds.Beep.Play();
MessageBox.Show(ex.ToString());
}
catch (System.Runtime.InteropServices.COMException ex)
{
SystemSounds.Beep.Play();
MessageBox.Show(ex.ToString());
}
catch (NAudio.MmException ex)
{
SystemSounds.Beep.Play();
string msg = ex.ToString();
MessageBox.Show((msg.Contains("UnspecifiedError calling waveOutOpen") ? "Something is wrong with either the sound you tried to play (" + file.Substring(file.LastIndexOf("\\") + 1) + ") (try converting it to another format) or your sound card driver\n\n" + msg : msg));
}
}
private void loadXMLFile(string path)
{
XMLSettings.Settings s = (XMLSettings.Settings)XMLSettings.ReadXML(typeof(XMLSettings.Settings), path);
if (s != null && s.SoundHotkeys != null && s.SoundHotkeys.Length > 0)
{
var items = new List<object[]>();
string errors = "";
for (int i = 0; i < s.SoundHotkeys.Length; i++)
{
int kLength = s.SoundHotkeys[i].Keys.Length;
bool keysNull = (kLength > 0 && !s.SoundHotkeys[i].Keys.Any(x => x != 0));
int sLength = s.SoundHotkeys[i].SoundLocations.Length;
bool soundsNotEmpty = s.SoundHotkeys[i].SoundLocations.All(x => !string.IsNullOrWhiteSpace(x));
Environment.CurrentDirectory = Path.GetDirectoryName(Application.ExecutablePath);
bool filesExist = s.SoundHotkeys[i].SoundLocations.All(x => File.Exists(x));
if (keysNull || sLength < 1 || !soundsNotEmpty || !filesExist) //error in XML file
{
string tempErr = "";
if (kLength == 0 && (sLength == 0 || !soundsNotEmpty)) tempErr = "entry is empty";
else if (!keysNull) tempErr = "one or more sounds do not exist"; // "one or more keys are null";
else if (sLength == 0) tempErr = "no sounds provided";
else if (!filesExist) tempErr = "one or more sounds do not exist";
errors += "Entry #" + (i + 1).ToString() + " has an error: " + tempErr + "\r\n";
}
object[] temp = new object[2];
temp[0] = s.SoundHotkeys[i].SoundClips;
temp[1] = Helper.keysToString(s.SoundHotkeys[i].Keys);
items.Add(temp); // add even if there was an error, so that the user can fix within the app
}
if (items.Count > 0)
{
if (errors != "")
{
MessageBox.Show((errors == "" ? "" : errors));
}
soundHotkeys.Clear();
soundHotkeys.AddRange(s.SoundHotkeys);
dgvKeySounds.Rows.Clear();
foreach (object[] row in items)
{
dgvKeySounds.Rows.Add(row);
}
xmlLoc = path;
}
else
{
SystemSounds.Beep.Play();
MessageBox.Show("No entries found, or all entries had errors in them (sound location behind empty or non-existant)");
}
}
else
{
SystemSounds.Beep.Play();
MessageBox.Show("No entries found, or there was an error reading the settings file");
}
AutoSave();
}
private void editSelectedSoundHotkey()
{
if (dgvKeySounds.SelectedRows.Count > 0)
{
var form = new AddEditHotkeyForm();
DataGridViewRow row = dgvKeySounds.SelectedRows[0];
form.editIndex = dgvKeySounds.SelectedRows[0].Index;
form.editStrings = new string[2];
form.editStrings[0] = Helper.soundLocsArrayToString(soundHotkeys[form.editIndex].SoundLocations);
form.editStrings[1] = (string)row.Cells[1].Value;
form.ShowDialog();
}
AutoSave();
}
private void loopbackSourceStream_DataAvailable(object sender, WaveInEventArgs e)
{
if (loopbackWaveProvider != null && loopbackWaveProvider.BufferedDuration.TotalMilliseconds <= 100)
loopbackWaveProvider.AddSamples(e.Buffer, 0, e.BytesRecorded);
}
private void settingsToolStripMenuItem_Click(object sender, EventArgs e)
{
var form = new SettingsForm();
form.ShowDialog();
}
private void checkForUpdateToolStripMenuItem_Click(object sender, EventArgs e)
{
Process.Start("https://github.com/x753/");
}
private void btnAdd_Click(object sender, EventArgs e)
{
var form = new AddEditHotkeyForm();
form.ShowDialog();
}
private void btnEdit_Click(object sender, EventArgs e)
{
editSelectedSoundHotkey();
}
private void btnRemove_Click(object sender, EventArgs e)
{
if (dgvKeySounds.SelectedRows.Count > 0)
{
soundHotkeys.RemoveAt(dgvKeySounds.SelectedRows[0].Index);
dgvKeySounds.Rows.Remove(dgvKeySounds.SelectedRows[0]);
}
AutoSave();
}
private void btnClear_Click(object sender, EventArgs e)
{
if (MessageBox.Show("Are you sure you want to clear all items?", "Clear", MessageBoxButtons.YesNo) == DialogResult.Yes)
{
soundHotkeys.Clear();
dgvKeySounds.Rows.Clear();
}
AutoSave();
}
private void btnPlaySound_Click(object sender, EventArgs e)
{
if (dgvKeySounds.SelectedRows.Count > 0)
playKeySound(soundHotkeys[dgvKeySounds.SelectedRows[0].Index]);
}
private void btnStopAllSounds_Click(object sender, EventArgs e)
{
stopPlayback();
}
private void btnLoad_Click(object sender, EventArgs e)
{
var diag = new OpenFileDialog();
diag.Filter = "XML file containing keys and sounds|*.xml";
var result = diag.ShowDialog();
if (result == DialogResult.OK)
{
string path = diag.FileName;
loadXMLFile(path);
}
}
//private void btnSave_Click(object sender, EventArgs e)
//{
// if (xmlLoc == "" || !File.Exists(xmlLoc))
// xmlLoc = Helper.userGetXMLLoc();
// if (xmlLoc != "")
// {
// XMLSettings.WriteXML(new XMLSettings.Settings() { SoundHotkeys = soundHotkeys.ToArray() }, xmlLoc);
// MessageBox.Show("Saved");
// }
//}
public void AutoSave()
{
XMLSettings.WriteXML(new XMLSettings.Settings() { SoundHotkeys = soundHotkeys.ToArray() }, Path.GetDirectoryName(Application.ExecutablePath) + "\\AHS-autosave.xml");
}
private void btnSaveAs_Click(object sender, EventArgs e)
{
string last = xmlLoc;
xmlLoc = Helper.userGetXMLLoc();
if (xmlLoc == "")
xmlLoc = last;
else if (last != xmlLoc)
{
XMLSettings.WriteXML(new XMLSettings.Settings() { SoundHotkeys = soundHotkeys.ToArray() }, xmlLoc);
}
}
private void btnReloadDevices_Click(object sender, EventArgs e)
{
stopPlayback();
stopLoopback();
loadSoundDevices();
}
private void dgvKeySounds_MouseDoubleClick(object sender, MouseEventArgs e)
{
editSelectedSoundHotkey();
}
Keys[] keysJustPressed = null;
bool showingMsgBox = false;
int lastIndex = -1;
private void mainTimer_Tick(object sender, EventArgs e)
{
int keysPressed = 0;
if (soundHotkeys.Count > 0) //check that required keys are pressed to play sound
{
for (int i = 0; i < soundHotkeys.Count; i++)
{
keysPressed = 0;
if (soundHotkeys[i].Keys.Length == 0) continue;
for (int j = 0; j < soundHotkeys[i].Keys.Length; j++)
{
if (Keyboard.IsKeyDown(soundHotkeys[i].Keys[j]))
keysPressed++;
}
if (keysPressed == soundHotkeys[i].Keys.Length)
{
if (keysJustPressed == soundHotkeys[i].Keys) continue;
if (soundHotkeys[i].Keys.Length > 0 && soundHotkeys[i].Keys.All(x => x != 0) && soundHotkeys[i].SoundLocations.Length > 0
&& soundHotkeys[i].SoundLocations.Length > 0 && soundHotkeys[i].SoundLocations.Any(x => File.Exists(x)))
{
playKeySound(soundHotkeys[i]);
return;
}
}
else if (keysJustPressed == soundHotkeys[i].Keys)
keysJustPressed = null;
}
keysPressed = 0;
}
if (XMLSettings.soundboardSettings.StopSoundKeys != null && XMLSettings.soundboardSettings.StopSoundKeys.Length > 0) //check that required keys are pressed to stop all sounds
{
for (int i = 0; i < XMLSettings.soundboardSettings.StopSoundKeys.Length; i++)
{
if (Keyboard.IsKeyDown(XMLSettings.soundboardSettings.StopSoundKeys[i])) keysPressed++;
}
if (keysPressed == XMLSettings.soundboardSettings.StopSoundKeys.Length)
{
if (keysJustPressed == null || !keysJustPressed.Intersect(XMLSettings.soundboardSettings.StopSoundKeys).Any())
{
stopPlayback();
keysJustPressed = XMLSettings.soundboardSettings.StopSoundKeys;
return;
}
}
else if (keysJustPressed == XMLSettings.soundboardSettings.StopSoundKeys)
keysJustPressed = null;
keysPressed = 0;
}
if (XMLSettings.soundboardSettings.PlaySelectionKeys != null && XMLSettings.soundboardSettings.PlaySelectionKeys.Length > 0) //check that required keys are pressed to play the currently selected sound
{
for (int i = 0; i < XMLSettings.soundboardSettings.PlaySelectionKeys.Length; i++)
{
if (Keyboard.IsKeyDown(XMLSettings.soundboardSettings.PlaySelectionKeys[i])) keysPressed++;
}
if (keysPressed == XMLSettings.soundboardSettings.PlaySelectionKeys.Length)
{
if (keysJustPressed == null || !keysJustPressed.Intersect(XMLSettings.soundboardSettings.PlaySelectionKeys).Any())
{
playSelection();
keysJustPressed = XMLSettings.soundboardSettings.PlaySelectionKeys;
return;
}
}
else if (keysJustPressed == XMLSettings.soundboardSettings.PlaySelectionKeys)
keysJustPressed = null;
keysPressed = 0;
}
if (XMLSettings.soundboardSettings.LoadXMLFiles != null && XMLSettings.soundboardSettings.LoadXMLFiles.Length > 0) //check that required keys are pressed to load XML file
{
for (int i = 0; i < XMLSettings.soundboardSettings.LoadXMLFiles.Length; i++)
{
if (XMLSettings.soundboardSettings.LoadXMLFiles[i].Keys.Length == 0) continue;
keysPressed = 0;
for (int j = 0; j < XMLSettings.soundboardSettings.LoadXMLFiles[i].Keys.Length; j++)
{
if (Keyboard.IsKeyDown(XMLSettings.soundboardSettings.LoadXMLFiles[i].Keys[j])) keysPressed++;
}
if (keysPressed == XMLSettings.soundboardSettings.LoadXMLFiles[i].Keys.Length)
{
if (keysJustPressed == null || !keysJustPressed.Intersect(XMLSettings.soundboardSettings.LoadXMLFiles[i].Keys).Any())
{
if (!string.IsNullOrWhiteSpace(XMLSettings.soundboardSettings.LoadXMLFiles[i].XMLLocation) && File.Exists(XMLSettings.soundboardSettings.LoadXMLFiles[i].XMLLocation))
{
keysJustPressed = XMLSettings.soundboardSettings.LoadXMLFiles[i].Keys;
loadXMLFile(XMLSettings.soundboardSettings.LoadXMLFiles[i].XMLLocation);
}
return;
}
}
else if (keysJustPressed == XMLSettings.soundboardSettings.LoadXMLFiles[i].Keys)
{
keysJustPressed = null;
}
}
keysPressed = 0;
}
}
private void playKeySound(XMLSettings.SoundHotkey currentKeysSounds)
{
Environment.CurrentDirectory = Path.GetDirectoryName(Application.ExecutablePath);
string path;
if (currentKeysSounds.SoundLocations.Length > 1)
{
//get random sound
int temp;
while (true)
{
temp = rand.Next(0, currentKeysSounds.SoundLocations.Length);
if (temp != lastIndex && File.Exists(currentKeysSounds.SoundLocations[temp])) break;
Thread.Sleep(1);
}
lastIndex = temp;
path = currentKeysSounds.SoundLocations[lastIndex];
}
else
path = currentKeysSounds.SoundLocations[0]; //get first sound
if (File.Exists(path))
{
playSound(path);
keysJustPressed = currentKeysSounds.Keys;
}
else if (!showingMsgBox) //dont run when already showing messagebox (don't want a bunch of these on your screen, do you?)
{
SystemSounds.Beep.Play();
showingMsgBox = true;
MessageBox.Show("File " + path + " does not exist");
showingMsgBox = false;
}
}
private void cbLoopbackDevices_SelectedIndexChanged(object sender, EventArgs e)
{
stopLoopback();
if (cbLoopbackDevices.SelectedIndex > 0)
startLoopback();
XMLSettings.soundboardSettings.LastLoopbackDevice = (string)cbLoopbackDevices.SelectedItem;
XMLSettings.SaveSoundboardSettingsXML();
}
private void cbPlaybackDevices_SelectedIndexChanged(object sender, EventArgs e)
{
stopPlayback();
initAudioPlaybackEngine();
XMLSettings.soundboardSettings.LastPlaybackDevice = (string)cbPlaybackDevices.SelectedItem;
XMLSettings.SaveSoundboardSettingsXML();
}
private void cbPlaybackDevices2_SelectedIndexChanged(object sender, EventArgs e)
{
stopPlayback();
initAudioPlaybackEngine();
XMLSettings.soundboardSettings.LastPlaybackDevice2 = (string)cbPlaybackDevices2.SelectedItem;
XMLSettings.SaveSoundboardSettingsXML();
}
private void frmMain_Resize(object sender, EventArgs e)
{
if (XMLSettings.soundboardSettings.MinimizeToTray)
{
if (this.WindowState == FormWindowState.Minimized)
{
notifyIcon1.Visible = true;
this.Hide();
}
}
}
private void notifyIcon1_MouseClick(object sender, MouseEventArgs e)
{
notifyIcon1.Visible = false;
//show form and give focus
this.WindowState = FormWindowState.Minimized;
this.Show();
this.WindowState = FormWindowState.Normal;
}
private void DgvKeySounds_DragEnter(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(DataFormats.FileDrop)) e.Effect = DragDropEffects.Copy;
}
private void DgvKeySounds_DragDrop(object sender, DragEventArgs e)
{
string[] files = (string[])e.Data.GetData(DataFormats.FileDrop);
bool unsupported = false;
foreach (string file in files)
{
if (!Helper.isSupportedFileType(file))
{
unsupported = true;
continue;
}
object[] newRow = new object[2];
newRow[0] = Helper.fileNamesFromLocations(file);
dgvKeySounds.Rows.Add(newRow);
soundHotkeys.Add(new XMLSettings.SoundHotkey(new Keys[] { }, new string[] { file }));
}
// Sorting Alphabetically
dgvKeySounds.Sort(dgvKeySounds.Columns[0], ListSortDirection.Ascending);
soundHotkeys.Sort(delegate (XMLSettings.SoundHotkey x, XMLSettings.SoundHotkey y)
{
if (x.SoundClips == null && y.SoundClips == null) return 0;
else if (x.SoundClips == null) return -1;
else if (y.SoundClips == null) return 1;
else return x.SoundClips.CompareTo(y.SoundClips);
});
if (unsupported) MessageBox.Show("One or more files were of an unsupported file type.");
AutoSave();
}
private void TrackBar1_Scroll(object sender, EventArgs e)
{
if (cbAudioOverdrive.Checked)
{
labelVolume.Text = (trackbarVolume.Value*3).ToString() + " dB";
}
else
{
labelVolume.Text = trackbarVolume.Value.ToString() + " dB";
}
XMLSettings.soundboardSettings.GainValue = trackbarVolume.Value;
XMLSettings.SaveSoundboardSettingsXML();
}
public void GoEvenFurtherBeyond(bool state)
{
cbAudioOverdrive.Checked = state;
}
public void SetGain(int gain)
{
trackbarVolume.Value = gain;
if (cbAudioOverdrive.Checked)
{
labelVolume.Text = (trackbarVolume.Value * 3).ToString() + " dB";
}
else
{
labelVolume.Text = trackbarVolume.Value.ToString() + " dB";
}
}
public float GetGain()
{
if (cbAudioOverdrive.Checked)
{
return trackbarVolume.Value * 3;
}
else
{
return trackbarVolume.Value;
}
}
private void CbAudioOverdrive_CheckedChanged(object sender, EventArgs e)
{
if (cbAudioOverdrive.Checked)
{
labelVolume.Text = (trackbarVolume.Value*3).ToString() + " dB";
}
else
{
labelVolume.Text = trackbarVolume.Value.ToString() + " dB";
}
XMLSettings.soundboardSettings.GoEvenFurtherBeyond = cbAudioOverdrive.Checked;
XMLSettings.SaveSoundboardSettingsXML();
}
public static System.Windows.Forms.Timer IdleTimer = new System.Windows.Forms.Timer();
public static string TypeTarget = "";
// Jump to the first sound starting with whatever key you pressed if the DGV is selected
private void DgvKeySounds_KeyPress(object sender, KeyPressEventArgs e)
{
TypeTarget += Char.ToLower(e.KeyChar);
IdleTimer.Stop();
IdleTimer.Interval = 600;
IdleTimer.Tick += TypeTargetTimeDone;
IdleTimer.Start();
Debug.WriteLine(TypeTarget);
for (int i = 0; i < dgvKeySounds.Rows.Count; i++)
{
if (dgvKeySounds.Rows[i].Cells[0].Value.ToString().ToLower().StartsWith(TypeTarget))
{
BindingSource bs = new BindingSource();
dgvKeySounds.BindingContext[bs].Position = i;
dgvKeySounds.CurrentCell = dgvKeySounds.Rows[i].Cells[0];
return;
}
}
}
static private void TypeTargetTimeDone(object sender, EventArgs e)
{
IdleTimer.Stop();
TypeTarget = "";
}
// Button for manually clearing cached sounds and running garbage collection
private void MemoryManagementToolStripMenuItem_Click(object sender, EventArgs e)
{
AudioPlaybackEngine.cachedSounds.Clear();
GC.Collect();
}
private void DownloadVBAudioCableToolStripMenuItem_Click(object sender, EventArgs e)
{
Process.Start("https://www.vb-audio.com/Cable/");
}
}
}
| 36.961538 | 284 | 0.540875 | [
"MIT"
] | deathart/AudioHotkey-Soundboard | MainForm.cs | 30,754 | C# |
using System;
// ReSharper disable once CheckNamespace
namespace Binance
{
/// <summary>
/// Account commissions.
/// </summary>
public sealed class AccountCommissions
{
#region Public Properties
/// <summary>
/// Get the maker commission in basis points (bips).
/// </summary>
public int Maker { get; }
/// <summary>
/// Get the taker commission in basis points (bips).
/// </summary>
public int Taker { get; }
/// <summary>
/// Get the buyer commission in basis points (bips).
/// </summary>
public int Buyer { get; }
/// <summary>
/// Get the seller commission in basis points (bips).
/// </summary>
public int Seller { get; }
#endregion Public Properties
#region Constructors
/// <summary>
/// Constructor.
/// </summary>
/// <param name="maker">The maker commission (bips).</param>
/// <param name="taker">The taker commission (bips).</param>
/// <param name="buyer">The buyer commission (bips).</param>
/// <param name="seller">The seller commission (bips).</param>
public AccountCommissions(int maker, int taker, int buyer, int seller)
{
ThrowIfCommissionIsInvalid(maker, nameof(maker));
ThrowIfCommissionIsInvalid(taker, nameof(taker));
ThrowIfCommissionIsInvalid(buyer, nameof(buyer));
ThrowIfCommissionIsInvalid(seller, nameof(seller));
Maker = maker;
Taker = taker;
Buyer = buyer;
Seller = seller;
}
#endregion Constructors
#region Private Methods
/// <summary>
/// Verify commission argument is valid.
/// </summary>
/// <param name="commission">The commission (bips).</param>
/// <param name="paramName">The parameter name.</param>
// ReSharper disable once ParameterOnlyUsedForPreconditionCheck.Local
private static void ThrowIfCommissionIsInvalid(decimal commission, string paramName)
{
if (commission < 0 || commission > 10000)
throw new ArgumentException($"{nameof(AccountCommissions)} commission must be in the range [0-10000] BPS.", paramName);
}
#endregion Private Methods
}
}
| 31.407895 | 135 | 0.577294 | [
"MIT"
] | MyJetWallet/Binance | src/Binance/Account/AccountCommissions.cs | 2,389 | C# |
using System;
using Windows.UI.Xaml.Data;
namespace DandD_Desktop_v2.Helpers
{
public class EnumToBooleanConverter : IValueConverter
{
public Type EnumType { get; set; }
public object Convert(object value, Type targetType, object parameter, string language)
{
if (parameter is string enumString)
{
if (!Enum.IsDefined(EnumType, value))
{
throw new ArgumentException("ExceptionEnumToBooleanConverterValueMustBeAnEnum".GetLocalized());
}
var enumValue = Enum.Parse(EnumType, enumString);
return enumValue.Equals(value);
}
throw new ArgumentException("ExceptionEnumToBooleanConverterParameterMustBeAnEnumName".GetLocalized());
}
public object ConvertBack(object value, Type targetType, object parameter, string language)
{
if (parameter is string enumString)
{
return Enum.Parse(EnumType, enumString);
}
throw new ArgumentException("ExceptionEnumToBooleanConverterParameterMustBeAnEnumName".GetLocalized());
}
}
}
| 30.769231 | 115 | 0.618333 | [
"MIT"
] | CoderMP/D-and-D-Desktop-Companion | DandD_Desktop_v2/Helpers/EnumToBooleanConverter.cs | 1,202 | 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("StatePuSub")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("StatePuSub")]
[assembly: AssemblyCopyright("Copyright © 2014")]
[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("a1e46116-5c15-404c-82b6-26c70e2b3689")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Revision and Build Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 37.583333 | 84 | 0.747967 | [
"MIT"
] | XSockets/XVA | XVA-01-05-StatePubSub/StatePuSub/StatePuSub/Properties/AssemblyInfo.cs | 1,356 | C# |
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Text;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using System.Text;
namespace DougMurphy.SourceGenerators.ArgumentNullException {
[Generator]
public class ThrowArgumentNullExceptionGenerator : ISourceGenerator {
public void Initialize(GeneratorInitializationContext context) {
#if DEBUG
if (!Debugger.IsAttached) {
Debugger.Launch();
}
#endif
}
public void Execute(GeneratorExecutionContext context) {
//find usages of our attribute
IEnumerable<SyntaxTree> syntaxTrees = context.Compilation.SyntaxTrees;
foreach (SyntaxTree syntaxTree in syntaxTrees) {
var methodDeclarations = syntaxTree.GetRoot().DescendantNodes().OfType<MethodDeclarationSyntax>().ToImmutableArray();
foreach (MethodDeclarationSyntax methodDeclaration in methodDeclarations) {
var parameterNamesToGenerateThrowFor = new List<string>();
SeparatedSyntaxList<ParameterSyntax> parameters = methodDeclaration.ParameterList.Parameters;
foreach (ParameterSyntax parameter in parameters.Where(p => p.AttributeLists.Count > 0)) {
ISymbol parameterSymbol = context.Compilation.GetSemanticModel(parameter.SyntaxTree).GetDeclaredSymbol(parameter);
if (parameterSymbol.GetAttributes().Any(a => a.AttributeClass.Name == "GenerateThrowException")) {
parameterNamesToGenerateThrowFor.Add(parameterSymbol.Name);
}
}
foreach (string parameterNameToGenerateThrowFor in parameterNamesToGenerateThrowFor) {
//generate code
var generatedCode = $@"
if ({parameterNameToGenerateThrowFor} is null) {{
throw new System.ArgumentNullException(nameof({parameterNameToGenerateThrowFor}));
}}";
context.AddSource("ArgumentNullExceptionGenerator.g.cs", SourceText.From(generatedCode, Encoding.UTF8));
}
}
}
}
}
}
| 38.254902 | 121 | 0.774987 | [
"MIT"
] | Doug-Murphy/SourceGenerator.ArgumentNullException | src/DougMurphy.SourceGenerators.ArgumentNullException/ThrowArgumentNullExceptionGenerator.cs | 1,953 | 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.Security.Outputs
{
[OutputType]
public sealed class AutomationRuleSetResponse
{
public readonly ImmutableArray<Outputs.AutomationTriggeringRuleResponse> Rules;
[OutputConstructor]
private AutomationRuleSetResponse(ImmutableArray<Outputs.AutomationTriggeringRuleResponse> rules)
{
Rules = rules;
}
}
}
| 27.96 | 105 | 0.725322 | [
"Apache-2.0"
] | pulumi-bot/pulumi-azure-native | sdk/dotnet/Security/Outputs/AutomationRuleSetResponse.cs | 699 | C# |
namespace DapperExtensions.Test.Data.Common
{
public class Car
{
public string Id { get; set; }
public string Name { get; set; }
}
}
| 18 | 44 | 0.58642 | [
"Apache-2.0"
] | balchen/Dapper-Extensions | DapperExtensions.Test/Data/Common/Car.cs | 164 | C# |
using System.Collections.Generic;
using FriendOrganizer.Domain;
namespace FriendOrganizer.UI.Data
{
public interface IFriendDataService
{
IEnumerable<Friend> GetAll();
}
} | 19.3 | 39 | 0.73057 | [
"MIT"
] | feliperomero3/FriendOrganizer | FriendOrganizer.UI/Data/IFriendDataService.cs | 195 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.