content
stringlengths
5
1.04M
avg_line_length
float64
1.75
12.9k
max_line_length
int64
2
244k
alphanum_fraction
float64
0
0.98
licenses
list
repository_name
stringlengths
7
92
path
stringlengths
3
249
size
int64
5
1.04M
lang
stringclasses
2 values
using System; using System.ComponentModel; using System.Drawing.Design; using System.Windows.Forms; using JetBrains.Annotations; namespace essentialMix.Windows.UITypeEditors { /// <inheritdoc /> public class CollectionEditor : System.ComponentModel.Design.CollectionEditor { /// <inheritdoc /> public CollectionEditor(Type type) : base(type) { } public override UITypeEditorEditStyle GetEditStyle(ITypeDescriptorContext context) { return UITypeEditorEditStyle.Modal; } public static EventHandler FormCreated; public static EventHandler Apply; public static EventHandler Cancel; protected CollectionForm Form { get; private set; } protected override CollectionForm CreateCollectionForm() { Form = base.CreateCollectionForm(); if (Form.AcceptButton is Button button) button.Click += (_, _) => OnOKClick(EventArgs.Empty); button = Form.CancelButton as Button; if (button != null) button.Click += (_, _) => OnCancelClick(EventArgs.Empty); OnFormCreated(EventArgs.Empty); return Form; } protected virtual void OnFormCreated(EventArgs args) { FormCreated?.Invoke(this, args); } protected virtual void OnOKClick(EventArgs args) { Apply?.Invoke(this, args); } protected virtual void OnCancelClick(EventArgs args) { Cancel?.Invoke(this, args); } } /// <inheritdoc /> public class CollectionEditor<TItem> : CollectionEditor { /// <inheritdoc /> public CollectionEditor(Type type) : base(type) { } [NotNull] protected override Type CreateCollectionItemType() { return typeof(TItem); } } public class CollectionEditor<TCollection, TItem> : CollectionEditor<TItem> { /// <inheritdoc /> public CollectionEditor() : base(typeof(TCollection)) { } } }
24.068493
124
0.7251
[ "MIT" ]
asm2025/asm
Framework/essentialMix.Windows/UITypeEditors/CollectionEditor.cs
1,757
C#
using System; using System.Runtime.InteropServices; namespace MediaDevices.Internal { [Guid("886D8EEB-8CF2-4446-8D02-CDBA1DBDCF99")] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] internal interface IPropertyStore { void GetCount( [Out] out uint cProps); void GetAt( [In] uint iProp, [Out] out PropertyKey pKey); void GetValue( [In] ref PropertyKey key, [Out] out PropVariant pv); void SetValue( [In] ref PropertyKey key, [In] ref PropVariant propvar); void Commit(); } }
22.535714
57
0.587956
[ "MIT" ]
Bassman2/MediaDevices
Src/MediaDevicesShare/Internal/IPropertyStore.cs
633
C#
//Copyright (c) 2007. Clarius Consulting, Manas Technology Solutions, InSTEDD //https://github.com/moq/moq4 //All rights reserved. //Redistribution and use in source and binary forms, //with or without modification, are permitted provided //that the following conditions are met: // * Redistributions of source code must retain the // above copyright notice, this list of conditions and // the following disclaimer. // * Redistributions in binary form must reproduce // the above copyright notice, this list of conditions // and the following disclaimer in the documentation // and/or other materials provided with the distribution. // * Neither the name of Clarius Consulting, Manas Technology Solutions or InSTEDD nor the // names of its contributors may be used to endorse // or promote products derived from this software // without specific prior written permission. //THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND //CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, //INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF //MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE //DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR //CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, //SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, //BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR //SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS //INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, //WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING //NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE //OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF //SUCH DAMAGE. //[This is the BSD license, see // http://www.opensource.org/licenses/bsd-license.php] using System; using System.ComponentModel; using Moq.Language.Flow; namespace Moq.Language { partial interface ICallback { /// <summary> /// Specifies a callback to invoke when the method is called that receives the original arguments. /// </summary> /// <typeparam name="T1">The type of the first argument of the invoked method.</typeparam> /// <typeparam name="T2">The type of the second argument of the invoked method.</typeparam> /// <param name="action">The callback method to invoke.</param> /// <returns>A reference to <see cref="ICallbackResult"/> interface.</returns> /// <example> /// Invokes the given callback with the concrete invocation arguments values. /// <para> /// Notice how the specific arguments are retrieved by simply declaring /// them as part of the lambda expression for the callback: /// </para> /// <code> /// mock.Setup(x => x.Execute( /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;())) /// .Callback((string arg1, string arg2) => Console.WriteLine(arg1 + arg2)); /// </code> /// </example> ICallbackResult Callback<T1, T2>(Action<T1, T2> action); /// <summary> /// Specifies a callback to invoke when the method is called that receives the original arguments. /// </summary> /// <typeparam name="T1">The type of the first argument of the invoked method.</typeparam> /// <typeparam name="T2">The type of the second argument of the invoked method.</typeparam> /// <typeparam name="T3">The type of the third argument of the invoked method.</typeparam> /// <param name="action">The callback method to invoke.</param> /// <returns>A reference to <see cref="ICallbackResult"/> interface.</returns> /// <example> /// Invokes the given callback with the concrete invocation arguments values. /// <para> /// Notice how the specific arguments are retrieved by simply declaring /// them as part of the lambda expression for the callback: /// </para> /// <code> /// mock.Setup(x => x.Execute( /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;())) /// .Callback((string arg1, string arg2, string arg3) => Console.WriteLine(arg1 + arg2 + arg3)); /// </code> /// </example> ICallbackResult Callback<T1, T2, T3>(Action<T1, T2, T3> action); /// <summary> /// Specifies a callback to invoke when the method is called that receives the original arguments. /// </summary> /// <typeparam name="T1">The type of the first argument of the invoked method.</typeparam> /// <typeparam name="T2">The type of the second argument of the invoked method.</typeparam> /// <typeparam name="T3">The type of the third argument of the invoked method.</typeparam> /// <typeparam name="T4">The type of the fourth argument of the invoked method.</typeparam> /// <param name="action">The callback method to invoke.</param> /// <returns>A reference to <see cref="ICallbackResult"/> interface.</returns> /// <example> /// Invokes the given callback with the concrete invocation arguments values. /// <para> /// Notice how the specific arguments are retrieved by simply declaring /// them as part of the lambda expression for the callback: /// </para> /// <code> /// mock.Setup(x => x.Execute( /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;())) /// .Callback((string arg1, string arg2, string arg3, string arg4) => Console.WriteLine(arg1 + arg2 + arg3 + arg4)); /// </code> /// </example> ICallbackResult Callback<T1, T2, T3, T4>(Action<T1, T2, T3, T4> action); /// <summary> /// Specifies a callback to invoke when the method is called that receives the original arguments. /// </summary> /// <typeparam name="T1">The type of the first argument of the invoked method.</typeparam> /// <typeparam name="T2">The type of the second argument of the invoked method.</typeparam> /// <typeparam name="T3">The type of the third argument of the invoked method.</typeparam> /// <typeparam name="T4">The type of the fourth argument of the invoked method.</typeparam> /// <typeparam name="T5">The type of the fifth argument of the invoked method.</typeparam> /// <param name="action">The callback method to invoke.</param> /// <returns>A reference to <see cref="ICallbackResult"/> interface.</returns> /// <example> /// Invokes the given callback with the concrete invocation arguments values. /// <para> /// Notice how the specific arguments are retrieved by simply declaring /// them as part of the lambda expression for the callback: /// </para> /// <code> /// mock.Setup(x => x.Execute( /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;())) /// .Callback((string arg1, string arg2, string arg3, string arg4, string arg5) => Console.WriteLine(arg1 + arg2 + arg3 + arg4 + arg5)); /// </code> /// </example> ICallbackResult Callback<T1, T2, T3, T4, T5>(Action<T1, T2, T3, T4, T5> action); /// <summary> /// Specifies a callback to invoke when the method is called that receives the original arguments. /// </summary> /// <typeparam name="T1">The type of the first argument of the invoked method.</typeparam> /// <typeparam name="T2">The type of the second argument of the invoked method.</typeparam> /// <typeparam name="T3">The type of the third argument of the invoked method.</typeparam> /// <typeparam name="T4">The type of the fourth argument of the invoked method.</typeparam> /// <typeparam name="T5">The type of the fifth argument of the invoked method.</typeparam> /// <typeparam name="T6">The type of the sixth argument of the invoked method.</typeparam> /// <param name="action">The callback method to invoke.</param> /// <returns>A reference to <see cref="ICallbackResult"/> interface.</returns> /// <example> /// Invokes the given callback with the concrete invocation arguments values. /// <para> /// Notice how the specific arguments are retrieved by simply declaring /// them as part of the lambda expression for the callback: /// </para> /// <code> /// mock.Setup(x => x.Execute( /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;())) /// .Callback((string arg1, string arg2, string arg3, string arg4, string arg5, string arg6) => Console.WriteLine(arg1 + arg2 + arg3 + arg4 + arg5 + arg6)); /// </code> /// </example> ICallbackResult Callback<T1, T2, T3, T4, T5, T6>(Action<T1, T2, T3, T4, T5, T6> action); /// <summary> /// Specifies a callback to invoke when the method is called that receives the original arguments. /// </summary> /// <typeparam name="T1">The type of the first argument of the invoked method.</typeparam> /// <typeparam name="T2">The type of the second argument of the invoked method.</typeparam> /// <typeparam name="T3">The type of the third argument of the invoked method.</typeparam> /// <typeparam name="T4">The type of the fourth argument of the invoked method.</typeparam> /// <typeparam name="T5">The type of the fifth argument of the invoked method.</typeparam> /// <typeparam name="T6">The type of the sixth argument of the invoked method.</typeparam> /// <typeparam name="T7">The type of the seventh argument of the invoked method.</typeparam> /// <param name="action">The callback method to invoke.</param> /// <returns>A reference to <see cref="ICallbackResult"/> interface.</returns> /// <example> /// Invokes the given callback with the concrete invocation arguments values. /// <para> /// Notice how the specific arguments are retrieved by simply declaring /// them as part of the lambda expression for the callback: /// </para> /// <code> /// mock.Setup(x => x.Execute( /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;())) /// .Callback((string arg1, string arg2, string arg3, string arg4, string arg5, string arg6, string arg7) => Console.WriteLine(arg1 + arg2 + arg3 + arg4 + arg5 + arg6 + arg7)); /// </code> /// </example> ICallbackResult Callback<T1, T2, T3, T4, T5, T6, T7>(Action<T1, T2, T3, T4, T5, T6, T7> action); /// <summary> /// Specifies a callback to invoke when the method is called that receives the original arguments. /// </summary> /// <typeparam name="T1">The type of the first argument of the invoked method.</typeparam> /// <typeparam name="T2">The type of the second argument of the invoked method.</typeparam> /// <typeparam name="T3">The type of the third argument of the invoked method.</typeparam> /// <typeparam name="T4">The type of the fourth argument of the invoked method.</typeparam> /// <typeparam name="T5">The type of the fifth argument of the invoked method.</typeparam> /// <typeparam name="T6">The type of the sixth argument of the invoked method.</typeparam> /// <typeparam name="T7">The type of the seventh argument of the invoked method.</typeparam> /// <typeparam name="T8">The type of the eighth argument of the invoked method.</typeparam> /// <param name="action">The callback method to invoke.</param> /// <returns>A reference to <see cref="ICallbackResult"/> interface.</returns> /// <example> /// Invokes the given callback with the concrete invocation arguments values. /// <para> /// Notice how the specific arguments are retrieved by simply declaring /// them as part of the lambda expression for the callback: /// </para> /// <code> /// mock.Setup(x => x.Execute( /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;())) /// .Callback((string arg1, string arg2, string arg3, string arg4, string arg5, string arg6, string arg7, string arg8) => Console.WriteLine(arg1 + arg2 + arg3 + arg4 + arg5 + arg6 + arg7 + arg8)); /// </code> /// </example> ICallbackResult Callback<T1, T2, T3, T4, T5, T6, T7, T8>(Action<T1, T2, T3, T4, T5, T6, T7, T8> action); /// <summary> /// Specifies a callback to invoke when the method is called that receives the original arguments. /// </summary> /// <typeparam name="T1">The type of the first argument of the invoked method.</typeparam> /// <typeparam name="T2">The type of the second argument of the invoked method.</typeparam> /// <typeparam name="T3">The type of the third argument of the invoked method.</typeparam> /// <typeparam name="T4">The type of the fourth argument of the invoked method.</typeparam> /// <typeparam name="T5">The type of the fifth argument of the invoked method.</typeparam> /// <typeparam name="T6">The type of the sixth argument of the invoked method.</typeparam> /// <typeparam name="T7">The type of the seventh argument of the invoked method.</typeparam> /// <typeparam name="T8">The type of the eighth argument of the invoked method.</typeparam> /// <typeparam name="T9">The type of the ninth argument of the invoked method.</typeparam> /// <param name="action">The callback method to invoke.</param> /// <returns>A reference to <see cref="ICallbackResult"/> interface.</returns> /// <example> /// Invokes the given callback with the concrete invocation arguments values. /// <para> /// Notice how the specific arguments are retrieved by simply declaring /// them as part of the lambda expression for the callback: /// </para> /// <code> /// mock.Setup(x => x.Execute( /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;())) /// .Callback((string arg1, string arg2, string arg3, string arg4, string arg5, string arg6, string arg7, string arg8, string arg9) => Console.WriteLine(arg1 + arg2 + arg3 + arg4 + arg5 + arg6 + arg7 + arg8 + arg9)); /// </code> /// </example> ICallbackResult Callback<T1, T2, T3, T4, T5, T6, T7, T8, T9>(Action<T1, T2, T3, T4, T5, T6, T7, T8, T9> action); /// <summary> /// Specifies a callback to invoke when the method is called that receives the original arguments. /// </summary> /// <typeparam name="T1">The type of the first argument of the invoked method.</typeparam> /// <typeparam name="T2">The type of the second argument of the invoked method.</typeparam> /// <typeparam name="T3">The type of the third argument of the invoked method.</typeparam> /// <typeparam name="T4">The type of the fourth argument of the invoked method.</typeparam> /// <typeparam name="T5">The type of the fifth argument of the invoked method.</typeparam> /// <typeparam name="T6">The type of the sixth argument of the invoked method.</typeparam> /// <typeparam name="T7">The type of the seventh argument of the invoked method.</typeparam> /// <typeparam name="T8">The type of the eighth argument of the invoked method.</typeparam> /// <typeparam name="T9">The type of the ninth argument of the invoked method.</typeparam> /// <typeparam name="T10">The type of the tenth argument of the invoked method.</typeparam> /// <param name="action">The callback method to invoke.</param> /// <returns>A reference to <see cref="ICallbackResult"/> interface.</returns> /// <example> /// Invokes the given callback with the concrete invocation arguments values. /// <para> /// Notice how the specific arguments are retrieved by simply declaring /// them as part of the lambda expression for the callback: /// </para> /// <code> /// mock.Setup(x => x.Execute( /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;())) /// .Callback((string arg1, string arg2, string arg3, string arg4, string arg5, string arg6, string arg7, string arg8, string arg9, string arg10) => Console.WriteLine(arg1 + arg2 + arg3 + arg4 + arg5 + arg6 + arg7 + arg8 + arg9 + arg10)); /// </code> /// </example> ICallbackResult Callback<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10>(Action<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10> action); /// <summary> /// Specifies a callback to invoke when the method is called that receives the original arguments. /// </summary> /// <typeparam name="T1">The type of the first argument of the invoked method.</typeparam> /// <typeparam name="T2">The type of the second argument of the invoked method.</typeparam> /// <typeparam name="T3">The type of the third argument of the invoked method.</typeparam> /// <typeparam name="T4">The type of the fourth argument of the invoked method.</typeparam> /// <typeparam name="T5">The type of the fifth argument of the invoked method.</typeparam> /// <typeparam name="T6">The type of the sixth argument of the invoked method.</typeparam> /// <typeparam name="T7">The type of the seventh argument of the invoked method.</typeparam> /// <typeparam name="T8">The type of the eighth argument of the invoked method.</typeparam> /// <typeparam name="T9">The type of the ninth argument of the invoked method.</typeparam> /// <typeparam name="T10">The type of the tenth argument of the invoked method.</typeparam> /// <typeparam name="T11">The type of the eleventh argument of the invoked method.</typeparam> /// <param name="action">The callback method to invoke.</param> /// <returns>A reference to <see cref="ICallbackResult"/> interface.</returns> /// <example> /// Invokes the given callback with the concrete invocation arguments values. /// <para> /// Notice how the specific arguments are retrieved by simply declaring /// them as part of the lambda expression for the callback: /// </para> /// <code> /// mock.Setup(x => x.Execute( /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;())) /// .Callback((string arg1, string arg2, string arg3, string arg4, string arg5, string arg6, string arg7, string arg8, string arg9, string arg10, string arg11) => Console.WriteLine(arg1 + arg2 + arg3 + arg4 + arg5 + arg6 + arg7 + arg8 + arg9 + arg10 + arg11)); /// </code> /// </example> ICallbackResult Callback<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11>(Action<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11> action); /// <summary> /// Specifies a callback to invoke when the method is called that receives the original arguments. /// </summary> /// <typeparam name="T1">The type of the first argument of the invoked method.</typeparam> /// <typeparam name="T2">The type of the second argument of the invoked method.</typeparam> /// <typeparam name="T3">The type of the third argument of the invoked method.</typeparam> /// <typeparam name="T4">The type of the fourth argument of the invoked method.</typeparam> /// <typeparam name="T5">The type of the fifth argument of the invoked method.</typeparam> /// <typeparam name="T6">The type of the sixth argument of the invoked method.</typeparam> /// <typeparam name="T7">The type of the seventh argument of the invoked method.</typeparam> /// <typeparam name="T8">The type of the eighth argument of the invoked method.</typeparam> /// <typeparam name="T9">The type of the ninth argument of the invoked method.</typeparam> /// <typeparam name="T10">The type of the tenth argument of the invoked method.</typeparam> /// <typeparam name="T11">The type of the eleventh argument of the invoked method.</typeparam> /// <typeparam name="T12">The type of the twelfth argument of the invoked method.</typeparam> /// <param name="action">The callback method to invoke.</param> /// <returns>A reference to <see cref="ICallbackResult"/> interface.</returns> /// <example> /// Invokes the given callback with the concrete invocation arguments values. /// <para> /// Notice how the specific arguments are retrieved by simply declaring /// them as part of the lambda expression for the callback: /// </para> /// <code> /// mock.Setup(x => x.Execute( /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;())) /// .Callback((string arg1, string arg2, string arg3, string arg4, string arg5, string arg6, string arg7, string arg8, string arg9, string arg10, string arg11, string arg12) => Console.WriteLine(arg1 + arg2 + arg3 + arg4 + arg5 + arg6 + arg7 + arg8 + arg9 + arg10 + arg11 + arg12)); /// </code> /// </example> ICallbackResult Callback<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12>(Action<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12> action); /// <summary> /// Specifies a callback to invoke when the method is called that receives the original arguments. /// </summary> /// <typeparam name="T1">The type of the first argument of the invoked method.</typeparam> /// <typeparam name="T2">The type of the second argument of the invoked method.</typeparam> /// <typeparam name="T3">The type of the third argument of the invoked method.</typeparam> /// <typeparam name="T4">The type of the fourth argument of the invoked method.</typeparam> /// <typeparam name="T5">The type of the fifth argument of the invoked method.</typeparam> /// <typeparam name="T6">The type of the sixth argument of the invoked method.</typeparam> /// <typeparam name="T7">The type of the seventh argument of the invoked method.</typeparam> /// <typeparam name="T8">The type of the eighth argument of the invoked method.</typeparam> /// <typeparam name="T9">The type of the ninth argument of the invoked method.</typeparam> /// <typeparam name="T10">The type of the tenth argument of the invoked method.</typeparam> /// <typeparam name="T11">The type of the eleventh argument of the invoked method.</typeparam> /// <typeparam name="T12">The type of the twelfth argument of the invoked method.</typeparam> /// <typeparam name="T13">The type of the thirteenth argument of the invoked method.</typeparam> /// <param name="action">The callback method to invoke.</param> /// <returns>A reference to <see cref="ICallbackResult"/> interface.</returns> /// <example> /// Invokes the given callback with the concrete invocation arguments values. /// <para> /// Notice how the specific arguments are retrieved by simply declaring /// them as part of the lambda expression for the callback: /// </para> /// <code> /// mock.Setup(x => x.Execute( /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;())) /// .Callback((string arg1, string arg2, string arg3, string arg4, string arg5, string arg6, string arg7, string arg8, string arg9, string arg10, string arg11, string arg12, string arg13) => Console.WriteLine(arg1 + arg2 + arg3 + arg4 + arg5 + arg6 + arg7 + arg8 + arg9 + arg10 + arg11 + arg12 + arg13)); /// </code> /// </example> ICallbackResult Callback<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13>(Action<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13> action); /// <summary> /// Specifies a callback to invoke when the method is called that receives the original arguments. /// </summary> /// <typeparam name="T1">The type of the first argument of the invoked method.</typeparam> /// <typeparam name="T2">The type of the second argument of the invoked method.</typeparam> /// <typeparam name="T3">The type of the third argument of the invoked method.</typeparam> /// <typeparam name="T4">The type of the fourth argument of the invoked method.</typeparam> /// <typeparam name="T5">The type of the fifth argument of the invoked method.</typeparam> /// <typeparam name="T6">The type of the sixth argument of the invoked method.</typeparam> /// <typeparam name="T7">The type of the seventh argument of the invoked method.</typeparam> /// <typeparam name="T8">The type of the eighth argument of the invoked method.</typeparam> /// <typeparam name="T9">The type of the ninth argument of the invoked method.</typeparam> /// <typeparam name="T10">The type of the tenth argument of the invoked method.</typeparam> /// <typeparam name="T11">The type of the eleventh argument of the invoked method.</typeparam> /// <typeparam name="T12">The type of the twelfth argument of the invoked method.</typeparam> /// <typeparam name="T13">The type of the thirteenth argument of the invoked method.</typeparam> /// <typeparam name="T14">The type of the fourteenth argument of the invoked method.</typeparam> /// <param name="action">The callback method to invoke.</param> /// <returns>A reference to <see cref="ICallbackResult"/> interface.</returns> /// <example> /// Invokes the given callback with the concrete invocation arguments values. /// <para> /// Notice how the specific arguments are retrieved by simply declaring /// them as part of the lambda expression for the callback: /// </para> /// <code> /// mock.Setup(x => x.Execute( /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;())) /// .Callback((string arg1, string arg2, string arg3, string arg4, string arg5, string arg6, string arg7, string arg8, string arg9, string arg10, string arg11, string arg12, string arg13, string arg14) => Console.WriteLine(arg1 + arg2 + arg3 + arg4 + arg5 + arg6 + arg7 + arg8 + arg9 + arg10 + arg11 + arg12 + arg13 + arg14)); /// </code> /// </example> ICallbackResult Callback<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14>(Action<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14> action); /// <summary> /// Specifies a callback to invoke when the method is called that receives the original arguments. /// </summary> /// <typeparam name="T1">The type of the first argument of the invoked method.</typeparam> /// <typeparam name="T2">The type of the second argument of the invoked method.</typeparam> /// <typeparam name="T3">The type of the third argument of the invoked method.</typeparam> /// <typeparam name="T4">The type of the fourth argument of the invoked method.</typeparam> /// <typeparam name="T5">The type of the fifth argument of the invoked method.</typeparam> /// <typeparam name="T6">The type of the sixth argument of the invoked method.</typeparam> /// <typeparam name="T7">The type of the seventh argument of the invoked method.</typeparam> /// <typeparam name="T8">The type of the eighth argument of the invoked method.</typeparam> /// <typeparam name="T9">The type of the ninth argument of the invoked method.</typeparam> /// <typeparam name="T10">The type of the tenth argument of the invoked method.</typeparam> /// <typeparam name="T11">The type of the eleventh argument of the invoked method.</typeparam> /// <typeparam name="T12">The type of the twelfth argument of the invoked method.</typeparam> /// <typeparam name="T13">The type of the thirteenth argument of the invoked method.</typeparam> /// <typeparam name="T14">The type of the fourteenth argument of the invoked method.</typeparam> /// <typeparam name="T15">The type of the fifteenth argument of the invoked method.</typeparam> /// <param name="action">The callback method to invoke.</param> /// <returns>A reference to <see cref="ICallbackResult"/> interface.</returns> /// <example> /// Invokes the given callback with the concrete invocation arguments values. /// <para> /// Notice how the specific arguments are retrieved by simply declaring /// them as part of the lambda expression for the callback: /// </para> /// <code> /// mock.Setup(x => x.Execute( /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;())) /// .Callback((string arg1, string arg2, string arg3, string arg4, string arg5, string arg6, string arg7, string arg8, string arg9, string arg10, string arg11, string arg12, string arg13, string arg14, string arg15) => Console.WriteLine(arg1 + arg2 + arg3 + arg4 + arg5 + arg6 + arg7 + arg8 + arg9 + arg10 + arg11 + arg12 + arg13 + arg14 + arg15)); /// </code> /// </example> ICallbackResult Callback<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15>(Action<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15> action); /// <summary> /// Specifies a callback to invoke when the method is called that receives the original arguments. /// </summary> /// <typeparam name="T1">The type of the first argument of the invoked method.</typeparam> /// <typeparam name="T2">The type of the second argument of the invoked method.</typeparam> /// <typeparam name="T3">The type of the third argument of the invoked method.</typeparam> /// <typeparam name="T4">The type of the fourth argument of the invoked method.</typeparam> /// <typeparam name="T5">The type of the fifth argument of the invoked method.</typeparam> /// <typeparam name="T6">The type of the sixth argument of the invoked method.</typeparam> /// <typeparam name="T7">The type of the seventh argument of the invoked method.</typeparam> /// <typeparam name="T8">The type of the eighth argument of the invoked method.</typeparam> /// <typeparam name="T9">The type of the ninth argument of the invoked method.</typeparam> /// <typeparam name="T10">The type of the tenth argument of the invoked method.</typeparam> /// <typeparam name="T11">The type of the eleventh argument of the invoked method.</typeparam> /// <typeparam name="T12">The type of the twelfth argument of the invoked method.</typeparam> /// <typeparam name="T13">The type of the thirteenth argument of the invoked method.</typeparam> /// <typeparam name="T14">The type of the fourteenth argument of the invoked method.</typeparam> /// <typeparam name="T15">The type of the fifteenth argument of the invoked method.</typeparam> /// <typeparam name="T16">The type of the sixteenth argument of the invoked method.</typeparam> /// <param name="action">The callback method to invoke.</param> /// <returns>A reference to <see cref="ICallbackResult"/> interface.</returns> /// <example> /// Invokes the given callback with the concrete invocation arguments values. /// <para> /// Notice how the specific arguments are retrieved by simply declaring /// them as part of the lambda expression for the callback: /// </para> /// <code> /// mock.Setup(x => x.Execute( /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;())) /// .Callback((string arg1, string arg2, string arg3, string arg4, string arg5, string arg6, string arg7, string arg8, string arg9, string arg10, string arg11, string arg12, string arg13, string arg14, string arg15, string arg16) => Console.WriteLine(arg1 + arg2 + arg3 + arg4 + arg5 + arg6 + arg7 + arg8 + arg9 + arg10 + arg11 + arg12 + arg13 + arg14 + arg15 + arg16)); /// </code> /// </example> ICallbackResult Callback<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16>(Action<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16> action); } partial interface ICallback<TMock, TResult> where TMock : class { /// <summary> /// Specifies a callback to invoke when the method is called that receives the original /// arguments. /// </summary> /// <typeparam name="T1">The type of the first argument of the invoked method.</typeparam> /// <typeparam name="T2">The type of the second argument of the invoked method.</typeparam> /// <param name="action">The callback method to invoke.</param> /// <returns>A reference to <see cref="IReturnsThrows{TMock, TResult}"/> interface.</returns> /// <example> /// Invokes the given callback with the concrete invocation arguments values. /// <para> /// Notice how the specific arguments are retrieved by simply declaring /// them as part of the lambda expression for the callback: /// </para> /// <code> /// mock.Setup(x => x.Execute( /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;())) /// .Callback((arg1, arg2) => Console.WriteLine(arg1 + arg2)); /// </code> /// </example> IReturnsThrows<TMock, TResult> Callback<T1, T2>(Action<T1, T2> action); /// <summary> /// Specifies a callback to invoke when the method is called that receives the original /// arguments. /// </summary> /// <typeparam name="T1">The type of the first argument of the invoked method.</typeparam> /// <typeparam name="T2">The type of the second argument of the invoked method.</typeparam> /// <typeparam name="T3">The type of the third argument of the invoked method.</typeparam> /// <param name="action">The callback method to invoke.</param> /// <returns>A reference to <see cref="IReturnsThrows{TMock, TResult}"/> interface.</returns> /// <example> /// Invokes the given callback with the concrete invocation arguments values. /// <para> /// Notice how the specific arguments are retrieved by simply declaring /// them as part of the lambda expression for the callback: /// </para> /// <code> /// mock.Setup(x => x.Execute( /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;())) /// .Callback((arg1, arg2, arg3) => Console.WriteLine(arg1 + arg2 + arg3)); /// </code> /// </example> IReturnsThrows<TMock, TResult> Callback<T1, T2, T3>(Action<T1, T2, T3> action); /// <summary> /// Specifies a callback to invoke when the method is called that receives the original /// arguments. /// </summary> /// <typeparam name="T1">The type of the first argument of the invoked method.</typeparam> /// <typeparam name="T2">The type of the second argument of the invoked method.</typeparam> /// <typeparam name="T3">The type of the third argument of the invoked method.</typeparam> /// <typeparam name="T4">The type of the fourth argument of the invoked method.</typeparam> /// <param name="action">The callback method to invoke.</param> /// <returns>A reference to <see cref="IReturnsThrows{TMock, TResult}"/> interface.</returns> /// <example> /// Invokes the given callback with the concrete invocation arguments values. /// <para> /// Notice how the specific arguments are retrieved by simply declaring /// them as part of the lambda expression for the callback: /// </para> /// <code> /// mock.Setup(x => x.Execute( /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;())) /// .Callback((arg1, arg2, arg3, arg4) => Console.WriteLine(arg1 + arg2 + arg3 + arg4)); /// </code> /// </example> IReturnsThrows<TMock, TResult> Callback<T1, T2, T3, T4>(Action<T1, T2, T3, T4> action); /// <summary> /// Specifies a callback to invoke when the method is called that receives the original /// arguments. /// </summary> /// <typeparam name="T1">The type of the first argument of the invoked method.</typeparam> /// <typeparam name="T2">The type of the second argument of the invoked method.</typeparam> /// <typeparam name="T3">The type of the third argument of the invoked method.</typeparam> /// <typeparam name="T4">The type of the fourth argument of the invoked method.</typeparam> /// <typeparam name="T5">The type of the fifth argument of the invoked method.</typeparam> /// <param name="action">The callback method to invoke.</param> /// <returns>A reference to <see cref="IReturnsThrows{TMock, TResult}"/> interface.</returns> /// <example> /// Invokes the given callback with the concrete invocation arguments values. /// <para> /// Notice how the specific arguments are retrieved by simply declaring /// them as part of the lambda expression for the callback: /// </para> /// <code> /// mock.Setup(x => x.Execute( /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;())) /// .Callback((arg1, arg2, arg3, arg4, arg5) => Console.WriteLine(arg1 + arg2 + arg3 + arg4 + arg5)); /// </code> /// </example> IReturnsThrows<TMock, TResult> Callback<T1, T2, T3, T4, T5>(Action<T1, T2, T3, T4, T5> action); /// <summary> /// Specifies a callback to invoke when the method is called that receives the original /// arguments. /// </summary> /// <typeparam name="T1">The type of the first argument of the invoked method.</typeparam> /// <typeparam name="T2">The type of the second argument of the invoked method.</typeparam> /// <typeparam name="T3">The type of the third argument of the invoked method.</typeparam> /// <typeparam name="T4">The type of the fourth argument of the invoked method.</typeparam> /// <typeparam name="T5">The type of the fifth argument of the invoked method.</typeparam> /// <typeparam name="T6">The type of the sixth argument of the invoked method.</typeparam> /// <param name="action">The callback method to invoke.</param> /// <returns>A reference to <see cref="IReturnsThrows{TMock, TResult}"/> interface.</returns> /// <example> /// Invokes the given callback with the concrete invocation arguments values. /// <para> /// Notice how the specific arguments are retrieved by simply declaring /// them as part of the lambda expression for the callback: /// </para> /// <code> /// mock.Setup(x => x.Execute( /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;())) /// .Callback((arg1, arg2, arg3, arg4, arg5, arg6) => Console.WriteLine(arg1 + arg2 + arg3 + arg4 + arg5 + arg6)); /// </code> /// </example> IReturnsThrows<TMock, TResult> Callback<T1, T2, T3, T4, T5, T6>(Action<T1, T2, T3, T4, T5, T6> action); /// <summary> /// Specifies a callback to invoke when the method is called that receives the original /// arguments. /// </summary> /// <typeparam name="T1">The type of the first argument of the invoked method.</typeparam> /// <typeparam name="T2">The type of the second argument of the invoked method.</typeparam> /// <typeparam name="T3">The type of the third argument of the invoked method.</typeparam> /// <typeparam name="T4">The type of the fourth argument of the invoked method.</typeparam> /// <typeparam name="T5">The type of the fifth argument of the invoked method.</typeparam> /// <typeparam name="T6">The type of the sixth argument of the invoked method.</typeparam> /// <typeparam name="T7">The type of the seventh argument of the invoked method.</typeparam> /// <param name="action">The callback method to invoke.</param> /// <returns>A reference to <see cref="IReturnsThrows{TMock, TResult}"/> interface.</returns> /// <example> /// Invokes the given callback with the concrete invocation arguments values. /// <para> /// Notice how the specific arguments are retrieved by simply declaring /// them as part of the lambda expression for the callback: /// </para> /// <code> /// mock.Setup(x => x.Execute( /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;())) /// .Callback((arg1, arg2, arg3, arg4, arg5, arg6, arg7) => Console.WriteLine(arg1 + arg2 + arg3 + arg4 + arg5 + arg6 + arg7)); /// </code> /// </example> IReturnsThrows<TMock, TResult> Callback<T1, T2, T3, T4, T5, T6, T7>(Action<T1, T2, T3, T4, T5, T6, T7> action); /// <summary> /// Specifies a callback to invoke when the method is called that receives the original /// arguments. /// </summary> /// <typeparam name="T1">The type of the first argument of the invoked method.</typeparam> /// <typeparam name="T2">The type of the second argument of the invoked method.</typeparam> /// <typeparam name="T3">The type of the third argument of the invoked method.</typeparam> /// <typeparam name="T4">The type of the fourth argument of the invoked method.</typeparam> /// <typeparam name="T5">The type of the fifth argument of the invoked method.</typeparam> /// <typeparam name="T6">The type of the sixth argument of the invoked method.</typeparam> /// <typeparam name="T7">The type of the seventh argument of the invoked method.</typeparam> /// <typeparam name="T8">The type of the eighth argument of the invoked method.</typeparam> /// <param name="action">The callback method to invoke.</param> /// <returns>A reference to <see cref="IReturnsThrows{TMock, TResult}"/> interface.</returns> /// <example> /// Invokes the given callback with the concrete invocation arguments values. /// <para> /// Notice how the specific arguments are retrieved by simply declaring /// them as part of the lambda expression for the callback: /// </para> /// <code> /// mock.Setup(x => x.Execute( /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;())) /// .Callback((arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8) => Console.WriteLine(arg1 + arg2 + arg3 + arg4 + arg5 + arg6 + arg7 + arg8)); /// </code> /// </example> IReturnsThrows<TMock, TResult> Callback<T1, T2, T3, T4, T5, T6, T7, T8>(Action<T1, T2, T3, T4, T5, T6, T7, T8> action); /// <summary> /// Specifies a callback to invoke when the method is called that receives the original /// arguments. /// </summary> /// <typeparam name="T1">The type of the first argument of the invoked method.</typeparam> /// <typeparam name="T2">The type of the second argument of the invoked method.</typeparam> /// <typeparam name="T3">The type of the third argument of the invoked method.</typeparam> /// <typeparam name="T4">The type of the fourth argument of the invoked method.</typeparam> /// <typeparam name="T5">The type of the fifth argument of the invoked method.</typeparam> /// <typeparam name="T6">The type of the sixth argument of the invoked method.</typeparam> /// <typeparam name="T7">The type of the seventh argument of the invoked method.</typeparam> /// <typeparam name="T8">The type of the eighth argument of the invoked method.</typeparam> /// <typeparam name="T9">The type of the ninth argument of the invoked method.</typeparam> /// <param name="action">The callback method to invoke.</param> /// <returns>A reference to <see cref="IReturnsThrows{TMock, TResult}"/> interface.</returns> /// <example> /// Invokes the given callback with the concrete invocation arguments values. /// <para> /// Notice how the specific arguments are retrieved by simply declaring /// them as part of the lambda expression for the callback: /// </para> /// <code> /// mock.Setup(x => x.Execute( /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;())) /// .Callback((arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9) => Console.WriteLine(arg1 + arg2 + arg3 + arg4 + arg5 + arg6 + arg7 + arg8 + arg9)); /// </code> /// </example> IReturnsThrows<TMock, TResult> Callback<T1, T2, T3, T4, T5, T6, T7, T8, T9>(Action<T1, T2, T3, T4, T5, T6, T7, T8, T9> action); /// <summary> /// Specifies a callback to invoke when the method is called that receives the original /// arguments. /// </summary> /// <typeparam name="T1">The type of the first argument of the invoked method.</typeparam> /// <typeparam name="T2">The type of the second argument of the invoked method.</typeparam> /// <typeparam name="T3">The type of the third argument of the invoked method.</typeparam> /// <typeparam name="T4">The type of the fourth argument of the invoked method.</typeparam> /// <typeparam name="T5">The type of the fifth argument of the invoked method.</typeparam> /// <typeparam name="T6">The type of the sixth argument of the invoked method.</typeparam> /// <typeparam name="T7">The type of the seventh argument of the invoked method.</typeparam> /// <typeparam name="T8">The type of the eighth argument of the invoked method.</typeparam> /// <typeparam name="T9">The type of the ninth argument of the invoked method.</typeparam> /// <typeparam name="T10">The type of the tenth argument of the invoked method.</typeparam> /// <param name="action">The callback method to invoke.</param> /// <returns>A reference to <see cref="IReturnsThrows{TMock, TResult}"/> interface.</returns> /// <example> /// Invokes the given callback with the concrete invocation arguments values. /// <para> /// Notice how the specific arguments are retrieved by simply declaring /// them as part of the lambda expression for the callback: /// </para> /// <code> /// mock.Setup(x => x.Execute( /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;())) /// .Callback((arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10) => Console.WriteLine(arg1 + arg2 + arg3 + arg4 + arg5 + arg6 + arg7 + arg8 + arg9 + arg10)); /// </code> /// </example> IReturnsThrows<TMock, TResult> Callback<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10>(Action<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10> action); /// <summary> /// Specifies a callback to invoke when the method is called that receives the original /// arguments. /// </summary> /// <typeparam name="T1">The type of the first argument of the invoked method.</typeparam> /// <typeparam name="T2">The type of the second argument of the invoked method.</typeparam> /// <typeparam name="T3">The type of the third argument of the invoked method.</typeparam> /// <typeparam name="T4">The type of the fourth argument of the invoked method.</typeparam> /// <typeparam name="T5">The type of the fifth argument of the invoked method.</typeparam> /// <typeparam name="T6">The type of the sixth argument of the invoked method.</typeparam> /// <typeparam name="T7">The type of the seventh argument of the invoked method.</typeparam> /// <typeparam name="T8">The type of the eighth argument of the invoked method.</typeparam> /// <typeparam name="T9">The type of the ninth argument of the invoked method.</typeparam> /// <typeparam name="T10">The type of the tenth argument of the invoked method.</typeparam> /// <typeparam name="T11">The type of the eleventh argument of the invoked method.</typeparam> /// <param name="action">The callback method to invoke.</param> /// <returns>A reference to <see cref="IReturnsThrows{TMock, TResult}"/> interface.</returns> /// <example> /// Invokes the given callback with the concrete invocation arguments values. /// <para> /// Notice how the specific arguments are retrieved by simply declaring /// them as part of the lambda expression for the callback: /// </para> /// <code> /// mock.Setup(x => x.Execute( /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;())) /// .Callback((arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11) => Console.WriteLine(arg1 + arg2 + arg3 + arg4 + arg5 + arg6 + arg7 + arg8 + arg9 + arg10 + arg11)); /// </code> /// </example> IReturnsThrows<TMock, TResult> Callback<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11>(Action<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11> action); /// <summary> /// Specifies a callback to invoke when the method is called that receives the original /// arguments. /// </summary> /// <typeparam name="T1">The type of the first argument of the invoked method.</typeparam> /// <typeparam name="T2">The type of the second argument of the invoked method.</typeparam> /// <typeparam name="T3">The type of the third argument of the invoked method.</typeparam> /// <typeparam name="T4">The type of the fourth argument of the invoked method.</typeparam> /// <typeparam name="T5">The type of the fifth argument of the invoked method.</typeparam> /// <typeparam name="T6">The type of the sixth argument of the invoked method.</typeparam> /// <typeparam name="T7">The type of the seventh argument of the invoked method.</typeparam> /// <typeparam name="T8">The type of the eighth argument of the invoked method.</typeparam> /// <typeparam name="T9">The type of the ninth argument of the invoked method.</typeparam> /// <typeparam name="T10">The type of the tenth argument of the invoked method.</typeparam> /// <typeparam name="T11">The type of the eleventh argument of the invoked method.</typeparam> /// <typeparam name="T12">The type of the twelfth argument of the invoked method.</typeparam> /// <param name="action">The callback method to invoke.</param> /// <returns>A reference to <see cref="IReturnsThrows{TMock, TResult}"/> interface.</returns> /// <example> /// Invokes the given callback with the concrete invocation arguments values. /// <para> /// Notice how the specific arguments are retrieved by simply declaring /// them as part of the lambda expression for the callback: /// </para> /// <code> /// mock.Setup(x => x.Execute( /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;())) /// .Callback((arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12) => Console.WriteLine(arg1 + arg2 + arg3 + arg4 + arg5 + arg6 + arg7 + arg8 + arg9 + arg10 + arg11 + arg12)); /// </code> /// </example> IReturnsThrows<TMock, TResult> Callback<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12>(Action<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12> action); /// <summary> /// Specifies a callback to invoke when the method is called that receives the original /// arguments. /// </summary> /// <typeparam name="T1">The type of the first argument of the invoked method.</typeparam> /// <typeparam name="T2">The type of the second argument of the invoked method.</typeparam> /// <typeparam name="T3">The type of the third argument of the invoked method.</typeparam> /// <typeparam name="T4">The type of the fourth argument of the invoked method.</typeparam> /// <typeparam name="T5">The type of the fifth argument of the invoked method.</typeparam> /// <typeparam name="T6">The type of the sixth argument of the invoked method.</typeparam> /// <typeparam name="T7">The type of the seventh argument of the invoked method.</typeparam> /// <typeparam name="T8">The type of the eighth argument of the invoked method.</typeparam> /// <typeparam name="T9">The type of the ninth argument of the invoked method.</typeparam> /// <typeparam name="T10">The type of the tenth argument of the invoked method.</typeparam> /// <typeparam name="T11">The type of the eleventh argument of the invoked method.</typeparam> /// <typeparam name="T12">The type of the twelfth argument of the invoked method.</typeparam> /// <typeparam name="T13">The type of the thirteenth argument of the invoked method.</typeparam> /// <param name="action">The callback method to invoke.</param> /// <returns>A reference to <see cref="IReturnsThrows{TMock, TResult}"/> interface.</returns> /// <example> /// Invokes the given callback with the concrete invocation arguments values. /// <para> /// Notice how the specific arguments are retrieved by simply declaring /// them as part of the lambda expression for the callback: /// </para> /// <code> /// mock.Setup(x => x.Execute( /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;())) /// .Callback((arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13) => Console.WriteLine(arg1 + arg2 + arg3 + arg4 + arg5 + arg6 + arg7 + arg8 + arg9 + arg10 + arg11 + arg12 + arg13)); /// </code> /// </example> IReturnsThrows<TMock, TResult> Callback<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13>(Action<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13> action); /// <summary> /// Specifies a callback to invoke when the method is called that receives the original /// arguments. /// </summary> /// <typeparam name="T1">The type of the first argument of the invoked method.</typeparam> /// <typeparam name="T2">The type of the second argument of the invoked method.</typeparam> /// <typeparam name="T3">The type of the third argument of the invoked method.</typeparam> /// <typeparam name="T4">The type of the fourth argument of the invoked method.</typeparam> /// <typeparam name="T5">The type of the fifth argument of the invoked method.</typeparam> /// <typeparam name="T6">The type of the sixth argument of the invoked method.</typeparam> /// <typeparam name="T7">The type of the seventh argument of the invoked method.</typeparam> /// <typeparam name="T8">The type of the eighth argument of the invoked method.</typeparam> /// <typeparam name="T9">The type of the ninth argument of the invoked method.</typeparam> /// <typeparam name="T10">The type of the tenth argument of the invoked method.</typeparam> /// <typeparam name="T11">The type of the eleventh argument of the invoked method.</typeparam> /// <typeparam name="T12">The type of the twelfth argument of the invoked method.</typeparam> /// <typeparam name="T13">The type of the thirteenth argument of the invoked method.</typeparam> /// <typeparam name="T14">The type of the fourteenth argument of the invoked method.</typeparam> /// <param name="action">The callback method to invoke.</param> /// <returns>A reference to <see cref="IReturnsThrows{TMock, TResult}"/> interface.</returns> /// <example> /// Invokes the given callback with the concrete invocation arguments values. /// <para> /// Notice how the specific arguments are retrieved by simply declaring /// them as part of the lambda expression for the callback: /// </para> /// <code> /// mock.Setup(x => x.Execute( /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;())) /// .Callback((arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14) => Console.WriteLine(arg1 + arg2 + arg3 + arg4 + arg5 + arg6 + arg7 + arg8 + arg9 + arg10 + arg11 + arg12 + arg13 + arg14)); /// </code> /// </example> IReturnsThrows<TMock, TResult> Callback<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14>(Action<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14> action); /// <summary> /// Specifies a callback to invoke when the method is called that receives the original /// arguments. /// </summary> /// <typeparam name="T1">The type of the first argument of the invoked method.</typeparam> /// <typeparam name="T2">The type of the second argument of the invoked method.</typeparam> /// <typeparam name="T3">The type of the third argument of the invoked method.</typeparam> /// <typeparam name="T4">The type of the fourth argument of the invoked method.</typeparam> /// <typeparam name="T5">The type of the fifth argument of the invoked method.</typeparam> /// <typeparam name="T6">The type of the sixth argument of the invoked method.</typeparam> /// <typeparam name="T7">The type of the seventh argument of the invoked method.</typeparam> /// <typeparam name="T8">The type of the eighth argument of the invoked method.</typeparam> /// <typeparam name="T9">The type of the ninth argument of the invoked method.</typeparam> /// <typeparam name="T10">The type of the tenth argument of the invoked method.</typeparam> /// <typeparam name="T11">The type of the eleventh argument of the invoked method.</typeparam> /// <typeparam name="T12">The type of the twelfth argument of the invoked method.</typeparam> /// <typeparam name="T13">The type of the thirteenth argument of the invoked method.</typeparam> /// <typeparam name="T14">The type of the fourteenth argument of the invoked method.</typeparam> /// <typeparam name="T15">The type of the fifteenth argument of the invoked method.</typeparam> /// <param name="action">The callback method to invoke.</param> /// <returns>A reference to <see cref="IReturnsThrows{TMock, TResult}"/> interface.</returns> /// <example> /// Invokes the given callback with the concrete invocation arguments values. /// <para> /// Notice how the specific arguments are retrieved by simply declaring /// them as part of the lambda expression for the callback: /// </para> /// <code> /// mock.Setup(x => x.Execute( /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;())) /// .Callback((arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15) => Console.WriteLine(arg1 + arg2 + arg3 + arg4 + arg5 + arg6 + arg7 + arg8 + arg9 + arg10 + arg11 + arg12 + arg13 + arg14 + arg15)); /// </code> /// </example> IReturnsThrows<TMock, TResult> Callback<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15>(Action<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15> action); /// <summary> /// Specifies a callback to invoke when the method is called that receives the original /// arguments. /// </summary> /// <typeparam name="T1">The type of the first argument of the invoked method.</typeparam> /// <typeparam name="T2">The type of the second argument of the invoked method.</typeparam> /// <typeparam name="T3">The type of the third argument of the invoked method.</typeparam> /// <typeparam name="T4">The type of the fourth argument of the invoked method.</typeparam> /// <typeparam name="T5">The type of the fifth argument of the invoked method.</typeparam> /// <typeparam name="T6">The type of the sixth argument of the invoked method.</typeparam> /// <typeparam name="T7">The type of the seventh argument of the invoked method.</typeparam> /// <typeparam name="T8">The type of the eighth argument of the invoked method.</typeparam> /// <typeparam name="T9">The type of the ninth argument of the invoked method.</typeparam> /// <typeparam name="T10">The type of the tenth argument of the invoked method.</typeparam> /// <typeparam name="T11">The type of the eleventh argument of the invoked method.</typeparam> /// <typeparam name="T12">The type of the twelfth argument of the invoked method.</typeparam> /// <typeparam name="T13">The type of the thirteenth argument of the invoked method.</typeparam> /// <typeparam name="T14">The type of the fourteenth argument of the invoked method.</typeparam> /// <typeparam name="T15">The type of the fifteenth argument of the invoked method.</typeparam> /// <typeparam name="T16">The type of the sixteenth argument of the invoked method.</typeparam> /// <param name="action">The callback method to invoke.</param> /// <returns>A reference to <see cref="IReturnsThrows{TMock, TResult}"/> interface.</returns> /// <example> /// Invokes the given callback with the concrete invocation arguments values. /// <para> /// Notice how the specific arguments are retrieved by simply declaring /// them as part of the lambda expression for the callback: /// </para> /// <code> /// mock.Setup(x => x.Execute( /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;(), /// It.IsAny&lt;string&gt;())) /// .Callback((arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16) => Console.WriteLine(arg1 + arg2 + arg3 + arg4 + arg5 + arg6 + arg7 + arg8 + arg9 + arg10 + arg11 + arg12 + arg13 + arg14 + arg15 + arg16)); /// </code> /// </example> IReturnsThrows<TMock, TResult> Callback<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16>(Action<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16> action); } }
61.165217
376
0.613563
[ "BSD-3-Clause" ]
niubi007/Moq
Source/Language/ICallback.Generated.cs
70,342
C#
// <auto-generated> // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. // </auto-generated> namespace Gov.Lclb.Cllb.Interfaces { using Microsoft.Rest; using Models; using System.Collections; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; /// <summary> /// Extension methods for Applicationtypeadoxioproratedlicencefeescheduleapplicationtype. /// </summary> public static partial class ApplicationtypeadoxioproratedlicencefeescheduleapplicationtypeExtensions { /// <summary> /// Get /// adoxio_applicationtype_adoxio_proratedlicencefeeschedule_ApplicationType /// from adoxio_applicationtypes /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='adoxioApplicationtypeid'> /// key: adoxio_applicationtypeid of adoxio_applicationtype /// </param> /// <param name='top'> /// </param> /// <param name='skip'> /// </param> /// <param name='search'> /// </param> /// <param name='filter'> /// </param> /// <param name='count'> /// </param> /// <param name='orderby'> /// Order items by property values /// </param> /// <param name='select'> /// Select properties to be returned /// </param> /// <param name='expand'> /// Expand related entities /// </param> public static MicrosoftDynamicsCRMadoxioProratedlicencefeescheduleCollection Get(this IApplicationtypeadoxioproratedlicencefeescheduleapplicationtype operations, string adoxioApplicationtypeid, int? top = default(int?), int? skip = default(int?), string search = default(string), string filter = default(string), bool? count = default(bool?), IList<string> orderby = default(IList<string>), IList<string> select = default(IList<string>), IList<string> expand = default(IList<string>)) { return operations.GetAsync(adoxioApplicationtypeid, top, skip, search, filter, count, orderby, select, expand).GetAwaiter().GetResult(); } /// <summary> /// Get /// adoxio_applicationtype_adoxio_proratedlicencefeeschedule_ApplicationType /// from adoxio_applicationtypes /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='adoxioApplicationtypeid'> /// key: adoxio_applicationtypeid of adoxio_applicationtype /// </param> /// <param name='top'> /// </param> /// <param name='skip'> /// </param> /// <param name='search'> /// </param> /// <param name='filter'> /// </param> /// <param name='count'> /// </param> /// <param name='orderby'> /// Order items by property values /// </param> /// <param name='select'> /// Select properties to be returned /// </param> /// <param name='expand'> /// Expand related entities /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<MicrosoftDynamicsCRMadoxioProratedlicencefeescheduleCollection> GetAsync(this IApplicationtypeadoxioproratedlicencefeescheduleapplicationtype operations, string adoxioApplicationtypeid, int? top = default(int?), int? skip = default(int?), string search = default(string), string filter = default(string), bool? count = default(bool?), IList<string> orderby = default(IList<string>), IList<string> select = default(IList<string>), IList<string> expand = default(IList<string>), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetWithHttpMessagesAsync(adoxioApplicationtypeid, top, skip, search, filter, count, orderby, select, expand, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Get /// adoxio_applicationtype_adoxio_proratedlicencefeeschedule_ApplicationType /// from adoxio_applicationtypes /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='adoxioApplicationtypeid'> /// key: adoxio_applicationtypeid of adoxio_applicationtype /// </param> /// <param name='top'> /// </param> /// <param name='skip'> /// </param> /// <param name='search'> /// </param> /// <param name='filter'> /// </param> /// <param name='count'> /// </param> /// <param name='orderby'> /// Order items by property values /// </param> /// <param name='select'> /// Select properties to be returned /// </param> /// <param name='expand'> /// Expand related entities /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> public static HttpOperationResponse<MicrosoftDynamicsCRMadoxioProratedlicencefeescheduleCollection> GetWithHttpMessages(this IApplicationtypeadoxioproratedlicencefeescheduleapplicationtype operations, string adoxioApplicationtypeid, int? top = default(int?), int? skip = default(int?), string search = default(string), string filter = default(string), bool? count = default(bool?), IList<string> orderby = default(IList<string>), IList<string> select = default(IList<string>), IList<string> expand = default(IList<string>), Dictionary<string, List<string>> customHeaders = null) { return operations.GetWithHttpMessagesAsync(adoxioApplicationtypeid, top, skip, search, filter, count, orderby, select, expand, customHeaders, CancellationToken.None).ConfigureAwait(false).GetAwaiter().GetResult(); } /// <summary> /// Get /// adoxio_applicationtype_adoxio_proratedlicencefeeschedule_ApplicationType /// from adoxio_applicationtypes /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='adoxioApplicationtypeid'> /// key: adoxio_applicationtypeid of adoxio_applicationtype /// </param> /// <param name='adoxioProratedlicencefeescheduleid'> /// key: adoxio_proratedlicencefeescheduleid of /// adoxio_proratedlicencefeeschedule /// </param> /// <param name='select'> /// Select properties to be returned /// </param> /// <param name='expand'> /// Expand related entities /// </param> public static MicrosoftDynamicsCRMadoxioProratedlicencefeeschedule ApplicationTypeByKey(this IApplicationtypeadoxioproratedlicencefeescheduleapplicationtype operations, string adoxioApplicationtypeid, string adoxioProratedlicencefeescheduleid, IList<string> select = default(IList<string>), IList<string> expand = default(IList<string>)) { return operations.ApplicationTypeByKeyAsync(adoxioApplicationtypeid, adoxioProratedlicencefeescheduleid, select, expand).GetAwaiter().GetResult(); } /// <summary> /// Get /// adoxio_applicationtype_adoxio_proratedlicencefeeschedule_ApplicationType /// from adoxio_applicationtypes /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='adoxioApplicationtypeid'> /// key: adoxio_applicationtypeid of adoxio_applicationtype /// </param> /// <param name='adoxioProratedlicencefeescheduleid'> /// key: adoxio_proratedlicencefeescheduleid of /// adoxio_proratedlicencefeeschedule /// </param> /// <param name='select'> /// Select properties to be returned /// </param> /// <param name='expand'> /// Expand related entities /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<MicrosoftDynamicsCRMadoxioProratedlicencefeeschedule> ApplicationTypeByKeyAsync(this IApplicationtypeadoxioproratedlicencefeescheduleapplicationtype operations, string adoxioApplicationtypeid, string adoxioProratedlicencefeescheduleid, IList<string> select = default(IList<string>), IList<string> expand = default(IList<string>), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ApplicationTypeByKeyWithHttpMessagesAsync(adoxioApplicationtypeid, adoxioProratedlicencefeescheduleid, select, expand, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Get /// adoxio_applicationtype_adoxio_proratedlicencefeeschedule_ApplicationType /// from adoxio_applicationtypes /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='adoxioApplicationtypeid'> /// key: adoxio_applicationtypeid of adoxio_applicationtype /// </param> /// <param name='adoxioProratedlicencefeescheduleid'> /// key: adoxio_proratedlicencefeescheduleid of /// adoxio_proratedlicencefeeschedule /// </param> /// <param name='select'> /// Select properties to be returned /// </param> /// <param name='expand'> /// Expand related entities /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> public static HttpOperationResponse<MicrosoftDynamicsCRMadoxioProratedlicencefeeschedule> ApplicationTypeByKeyWithHttpMessages(this IApplicationtypeadoxioproratedlicencefeescheduleapplicationtype operations, string adoxioApplicationtypeid, string adoxioProratedlicencefeescheduleid, IList<string> select = default(IList<string>), IList<string> expand = default(IList<string>), Dictionary<string, List<string>> customHeaders = null) { return operations.ApplicationTypeByKeyWithHttpMessagesAsync(adoxioApplicationtypeid, adoxioProratedlicencefeescheduleid, select, expand, customHeaders, CancellationToken.None).ConfigureAwait(false).GetAwaiter().GetResult(); } } }
52.071429
590
0.600051
[ "Apache-2.0" ]
brianorwhatever/jag-lcrb-carla-public
cllc-interfaces/Dynamics-Autorest/ApplicationtypeadoxioproratedlicencefeescheduleapplicationtypeExtensions.cs
11,664
C#
namespace PSX.Devices.Optical; public readonly struct TrackPosition { public int M { get; } public int S { get; } public int F { get; } public TrackPosition(int m, int s, int f) { if (m is < 0 or > 99) throw new ArgumentOutOfRangeException(nameof(m), s, null); if (s is < 0 or > 59) throw new ArgumentOutOfRangeException(nameof(s), s, null); if (f is < 0 or > 74) throw new ArgumentOutOfRangeException(nameof(f), f, null); M = m; S = s; F = f; } public override string ToString() { return $"{M:D2}:{S:D2}:{F:D2}"; } public int ToInt32() { return M * 60 * 75 + S * 75 + F; } }
20.361111
70
0.518417
[ "MIT" ]
aybe/ProjectPSX
PSX.Devices.Optical/TrackPosition.cs
735
C#
// // assign.cs: Assignments. // // Author: // Miguel de Icaza (miguel@ximian.com) // Martin Baulig (martin@ximian.com) // Marek Safar (marek.safar@gmail.com) // // Dual licensed under the terms of the MIT X11 or GNU GPL // // Copyright 2001, 2002, 2003 Ximian, Inc. // Copyright 2004-2008 Novell, Inc // using System; #if STATIC using IKVM.Reflection.Emit; #else using System.Reflection.Emit; #endif namespace Mono.CSharp { /// <summary> /// This interface is implemented by expressions that can be assigned to. /// </summary> /// <remarks> /// This interface is implemented by Expressions whose values can not /// store the result on the top of the stack. /// /// Expressions implementing this (Properties, Indexers and Arrays) would /// perform an assignment of the Expression "source" into its final /// location. /// /// No values on the top of the stack are expected to be left by /// invoking this method. /// </remarks> public interface IAssignMethod { // // This is an extra version of Emit. If leave_copy is `true' // A copy of the expression will be left on the stack at the // end of the code generated for EmitAssign // void Emit (EmitContext ec, bool leave_copy); // // This method does the assignment // `source' will be stored into the location specified by `this' // if `leave_copy' is true, a copy of `source' will be left on the stack // if `prepare_for_load' is true, when `source' is emitted, there will // be data on the stack that it can use to compuatate its value. This is // for expressions like a [f ()] ++, where you can't call `f ()' twice. // void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load); /* For simple assignments, this interface is very simple, EmitAssign is called with source as the source expression and leave_copy and prepare_for_load false. For compound assignments it gets complicated. EmitAssign will be called as before, however, prepare_for_load will be true. The @source expression will contain an expression which calls Emit. So, the calls look like: this.EmitAssign (ec, source, false, true) -> source.Emit (ec); -> [...] -> this.Emit (ec, false); -> end this.Emit (ec, false); -> end [...] end source.Emit (ec); end this.EmitAssign (ec, source, false, true) When prepare_for_load is true, EmitAssign emits a `token' on the stack that Emit will use for its state. Let's take FieldExpr as an example. assume we are emitting f ().y += 1; Here is the call tree again. This time, each call is annotated with the IL it produces: this.EmitAssign (ec, source, false, true) call f dup Binary.Emit () this.Emit (ec, false); ldfld y end this.Emit (ec, false); IntConstant.Emit () ldc.i4.1 end IntConstant.Emit add end Binary.Emit () stfld end this.EmitAssign (ec, source, false, true) Observe two things: 1) EmitAssign left a token on the stack. It was the result of f (). 2) This token was used by Emit leave_copy (in both EmitAssign and Emit) tells the compiler to leave a copy of the expression at that point in evaluation. This is used for pre/post inc/dec and for a = x += y. Let's do the above example with leave_copy true in EmitAssign this.EmitAssign (ec, source, true, true) call f dup Binary.Emit () this.Emit (ec, false); ldfld y end this.Emit (ec, false); IntConstant.Emit () ldc.i4.1 end IntConstant.Emit add end Binary.Emit () dup stloc temp stfld ldloc temp end this.EmitAssign (ec, source, true, true) And with it true in Emit this.EmitAssign (ec, source, false, true) call f dup Binary.Emit () this.Emit (ec, true); ldfld y dup stloc temp end this.Emit (ec, true); IntConstant.Emit () ldc.i4.1 end IntConstant.Emit add end Binary.Emit () stfld ldloc temp end this.EmitAssign (ec, source, false, true) Note that these two examples are what happens for ++x and x++, respectively. */ } /// <summary> /// An Expression to hold a temporary value. /// </summary> /// <remarks> /// The LocalTemporary class is used to hold temporary values of a given /// type to "simulate" the expression semantics. The local variable is /// never captured. /// /// The local temporary is used to alter the normal flow of code generation /// basically it creates a local variable, and its emit instruction generates /// code to access this value, return its address or save its value. /// /// If `is_address' is true, then the value that we store is the address to the /// real value, and not the value itself. /// /// This is needed for a value type, because otherwise you just end up making a /// copy of the value on the stack and modifying it. You really need a pointer /// to the origional value so that you can modify it in that location. This /// Does not happen with a class because a class is a pointer -- so you always /// get the indirection. /// /// </remarks> public class LocalTemporary : Expression, IMemoryLocation, IAssignMethod { LocalBuilder builder; public LocalTemporary (TypeSpec t) { type = t; eclass = ExprClass.Value; } public LocalTemporary (LocalBuilder b, TypeSpec t) : this (t) { builder = b; } public void Release (EmitContext ec) { ec.FreeTemporaryLocal (builder, type); builder = null; } public override Expression CreateExpressionTree (ResolveContext ec) { Arguments args = new Arguments (1); args.Add (new Argument (this)); return CreateExpressionFactoryCall (ec, "Constant", args); } protected override Expression DoResolve (ResolveContext ec) { return this; } public override Expression DoResolveLValue (ResolveContext ec, Expression right_side) { return this; } public override void Emit (EmitContext ec) { if (builder == null) throw new InternalErrorException ("Emit without Store, or after Release"); ec.Emit (OpCodes.Ldloc, builder); } #region IAssignMethod Members public void Emit (EmitContext ec, bool leave_copy) { Emit (ec); if (leave_copy) Emit (ec); } public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load) { if (prepare_for_load) throw new NotImplementedException (); source.Emit (ec); Store (ec); if (leave_copy) Emit (ec); } #endregion public LocalBuilder Builder { get { return builder; } } public void Store (EmitContext ec) { if (builder == null) builder = ec.GetTemporaryLocal (type); ec.Emit (OpCodes.Stloc, builder); } public void AddressOf (EmitContext ec, AddressOp mode) { if (builder == null) builder = ec.GetTemporaryLocal (type); if (builder.LocalType.IsByRef) { // // if is_address, than this is just the address anyways, // so we just return this. // ec.Emit (OpCodes.Ldloc, builder); } else { ec.Emit (OpCodes.Ldloca, builder); } } } /// <summary> /// The Assign node takes care of assigning the value of source into /// the expression represented by target. /// </summary> public abstract class Assign : ExpressionStatement { protected Expression target, source; protected Assign (Expression target, Expression source, Location loc) { this.target = target; this.source = source; this.loc = loc; } public override Expression CreateExpressionTree (ResolveContext ec) { ec.Report.Error (832, loc, "An expression tree cannot contain an assignment operator"); return null; } public Expression Target { get { return target; } } public Expression Source { get { return source; } } protected override Expression DoResolve (ResolveContext ec) { bool ok = true; source = source.Resolve (ec); if (source == null) { ok = false; source = EmptyExpression.Null; } target = target.ResolveLValue (ec, source); if (target == null || !ok) return null; TypeSpec target_type = target.Type; TypeSpec source_type = source.Type; eclass = ExprClass.Value; type = target_type; if (!(target is IAssignMethod)) { Error_ValueAssignment (ec, loc); return null; } if (target_type != source_type) { Expression resolved = ResolveConversions (ec); if (resolved != this) return resolved; } return this; } #if NET_4_0 public override System.Linq.Expressions.Expression MakeExpression (BuilderContext ctx) { var tassign = target as IDynamicAssign; if (tassign == null) throw new InternalErrorException (target.GetType () + " does not support dynamic assignment"); var target_object = tassign.MakeAssignExpression (ctx, source); // // Some hacking is needed as DLR does not support void type and requires // always have object convertible return type to support caching and chaining // // We do this by introducing an explicit block which returns RHS value when // available or null // if (target_object.NodeType == System.Linq.Expressions.ExpressionType.Block) return target_object; System.Linq.Expressions.UnaryExpression source_object; if (ctx.HasSet (BuilderContext.Options.CheckedScope)) { source_object = System.Linq.Expressions.Expression.ConvertChecked (source.MakeExpression (ctx), target_object.Type); } else { source_object = System.Linq.Expressions.Expression.Convert (source.MakeExpression (ctx), target_object.Type); } return System.Linq.Expressions.Expression.Assign (target_object, source_object); } #endif protected virtual Expression ResolveConversions (ResolveContext ec) { source = Convert.ImplicitConversionRequired (ec, source, target.Type, loc); if (source == null) return null; return this; } void Emit (EmitContext ec, bool is_statement) { IAssignMethod t = (IAssignMethod) target; t.EmitAssign (ec, source, !is_statement, this is CompoundAssign); } public override void Emit (EmitContext ec) { Emit (ec, false); } public override void EmitStatement (EmitContext ec) { Emit (ec, true); } protected override void CloneTo (CloneContext clonectx, Expression t) { Assign _target = (Assign) t; _target.target = target.Clone (clonectx); _target.source = source.Clone (clonectx); } } public class SimpleAssign : Assign { public SimpleAssign (Expression target, Expression source) : this (target, source, target.Location) { } public SimpleAssign (Expression target, Expression source, Location loc) : base (target, source, loc) { } bool CheckEqualAssign (Expression t) { if (source is Assign) { Assign a = (Assign) source; if (t.Equals (a.Target)) return true; return a is SimpleAssign && ((SimpleAssign) a).CheckEqualAssign (t); } return t.Equals (source); } protected override Expression DoResolve (ResolveContext ec) { Expression e = base.DoResolve (ec); if (e == null || e != this) return e; if (CheckEqualAssign (target)) ec.Report.Warning (1717, 3, loc, "Assignment made to same variable; did you mean to assign something else?"); return this; } } public class RuntimeExplicitAssign : Assign { public RuntimeExplicitAssign (Expression target, Expression source) : base (target, source, target.Location) { } protected override Expression ResolveConversions (ResolveContext ec) { source = EmptyCast.Create (source, target.Type); return this; } } // // Compiler generated assign // class CompilerAssign : Assign { public CompilerAssign (Expression target, Expression source, Location loc) : base (target, source, loc) { } public void UpdateSource (Expression source) { base.source = source; } } // // Implements fields and events class initializers // public class FieldInitializer : Assign { // // Field initializers are tricky for partial classes. They have to // share same constructor (block) for expression trees resolve but // they have they own resolve scope // sealed class FieldInitializerContext : ResolveContext { ExplicitBlock ctor_block; public FieldInitializerContext (IMemberContext mc, ResolveContext constructorContext) : base (mc, Options.FieldInitializerScope | Options.ConstructorScope) { this.ctor_block = constructorContext.CurrentBlock.Explicit; } public override ExplicitBlock ConstructorBlock { get { return ctor_block; } } } // // Keep resolved value because field initializers have their own rules // ExpressionStatement resolved; IMemberContext mc; public FieldInitializer (FieldSpec spec, Expression expression, IMemberContext mc) : base (new FieldExpr (spec, expression.Location), expression, expression.Location) { this.mc = mc; if (!spec.IsStatic) ((FieldExpr)target).InstanceExpression = CompilerGeneratedThis.Instance; } protected override Expression DoResolve (ResolveContext ec) { // Field initializer can be resolved (fail) many times if (source == null) return null; if (resolved == null) { var ctx = new FieldInitializerContext (mc, ec); resolved = base.DoResolve (ctx) as ExpressionStatement; } return resolved; } public override void EmitStatement (EmitContext ec) { if (resolved == null) return; if (resolved != this) resolved.EmitStatement (ec); else base.EmitStatement (ec); } public bool IsComplexInitializer { get { return !(source is Constant); } } public bool IsDefaultInitializer { get { Constant c = source as Constant; if (c == null) return false; FieldExpr fe = (FieldExpr)target; return c.IsDefaultInitializer (fe.Type); } } } // // This class is used for compound assignments. // public class CompoundAssign : Assign { // This is just a hack implemented for arrays only public sealed class TargetExpression : Expression { Expression child; public TargetExpression (Expression child) { this.child = child; this.loc = child.Location; } public override Expression CreateExpressionTree (ResolveContext ec) { throw new NotSupportedException ("ET"); } protected override Expression DoResolve (ResolveContext ec) { type = child.Type; eclass = ExprClass.Value; return this; } public override void Emit (EmitContext ec) { child.Emit (ec); } } // Used for underlying binary operator readonly Binary.Operator op; Expression right; Expression left; public CompoundAssign (Binary.Operator op, Expression target, Expression source, Location loc) : base (target, source, loc) { right = source; this.op = op; } public CompoundAssign (Binary.Operator op, Expression target, Expression source, Expression left, Location loc) : this (op, target, source, loc) { this.left = left; } protected override Expression DoResolve (ResolveContext ec) { right = right.Resolve (ec); if (right == null) return null; MemberAccess ma = target as MemberAccess; using (ec.Set (ResolveContext.Options.CompoundAssignmentScope)) { target = target.Resolve (ec); } if (target == null) return null; if (target is MethodGroupExpr){ ec.Report.Error (1656, loc, "Cannot assign to `{0}' because it is a `{1}'", ((MethodGroupExpr)target).Name, target.ExprClassName); return null; } var event_expr = target as EventExpr; if (event_expr != null) { source = Convert.ImplicitConversionRequired (ec, right, target.Type, loc); if (source == null) return null; Expression rside; if (op == Binary.Operator.Addition) rside = EmptyExpression.EventAddition; else if (op == Binary.Operator.Subtraction) rside = EmptyExpression.EventSubtraction; else rside = null; target = target.ResolveLValue (ec, rside); if (target == null) return null; eclass = ExprClass.Value; type = event_expr.Operator.ReturnType; return this; } // // Only now we can decouple the original source/target // into a tree, to guarantee that we do not have side // effects. // if (left == null) left = new TargetExpression (target); source = new Binary (op, left, right, true, loc); if (target is DynamicMemberAssignable) { Arguments targs = ((DynamicMemberAssignable) target).Arguments; source = source.Resolve (ec); Arguments args = new Arguments (targs.Count + 1); args.AddRange (targs); args.Add (new Argument (source)); var binder_flags = CSharpBinderFlags.ValueFromCompoundAssignment; // // Compound assignment does target conversion using additional method // call, set checked context as the binary operation can overflow // if (ec.HasSet (ResolveContext.Options.CheckedScope)) binder_flags |= CSharpBinderFlags.CheckedContext; if (target is DynamicMemberBinder) { source = new DynamicMemberBinder (ma.Name, binder_flags, args, loc).Resolve (ec); // Handles possible event addition/subtraction if (op == Binary.Operator.Addition || op == Binary.Operator.Subtraction) { args = new Arguments (targs.Count + 1); args.AddRange (targs); args.Add (new Argument (right)); string method_prefix = op == Binary.Operator.Addition ? Event.AEventAccessor.AddPrefix : Event.AEventAccessor.RemovePrefix; var invoke = DynamicInvocation.CreateSpecialNameInvoke ( new MemberAccess (right, method_prefix + ma.Name, loc), args, loc).Resolve (ec); args = new Arguments (targs.Count); args.AddRange (targs); source = new DynamicEventCompoundAssign (ma.Name, args, (ExpressionStatement) source, (ExpressionStatement) invoke, loc).Resolve (ec); } } else { source = new DynamicIndexBinder (binder_flags, args, loc).Resolve (ec); } return source; } return base.DoResolve (ec); } protected override Expression ResolveConversions (ResolveContext ec) { // // LAMESPEC: Under dynamic context no target conversion is happening // This allows more natual dynamic behaviour but breaks compatibility // with static binding // if (target is RuntimeValueExpression) return this; TypeSpec target_type = target.Type; // // 1. the return type is implicitly convertible to the type of target // if (Convert.ImplicitConversionExists (ec, source, target_type)) { source = Convert.ImplicitConversion (ec, source, target_type, loc); return this; } // // Otherwise, if the selected operator is a predefined operator // Binary b = source as Binary; if (b == null && source is ReducedExpression) b = ((ReducedExpression) source).OriginalExpression as Binary; if (b != null) { // // 2a. the operator is a shift operator // // 2b. the return type is explicitly convertible to the type of x, and // y is implicitly convertible to the type of x // if ((b.Oper & Binary.Operator.ShiftMask) != 0 || Convert.ImplicitConversionExists (ec, right, target_type)) { source = Convert.ExplicitConversion (ec, source, target_type, loc); return this; } } if (source.Type == InternalType.Dynamic) { Arguments arg = new Arguments (1); arg.Add (new Argument (source)); return new SimpleAssign (target, new DynamicConversion (target_type, CSharpBinderFlags.ConvertExplicit, arg, loc), loc).Resolve (ec); } right.Error_ValueCannotBeConverted (ec, loc, target_type, false); return null; } protected override void CloneTo (CloneContext clonectx, Expression t) { CompoundAssign ctarget = (CompoundAssign) t; ctarget.right = ctarget.source = source.Clone (clonectx); ctarget.target = target.Clone (clonectx); } } }
25.942931
137
0.680832
[ "Apache-2.0" ]
Sectoid/debian-mono
mcs/mcs/assign.cs
20,002
C#
singleton Material(clothframe_clothframe) { mapTo = "clothframe"; diffuseMap[0] = "./tex_clothframe_dif.dds"; normalMap[0] = "./tex_clothframe_nrm.dds"; diffuseColor[0] = "1 1 1 1"; specular[0] = "0.9 0.9 0.9 1"; specularPower[0] = 29; doubleSided = false; translucent = false; translucentBlendOp = "None"; pixelSpecular[0] = "1"; materialTag0 = "props"; }; singleton Material(Cloth) { mapTo = "unmapped_mat"; diffuseMap[0] = "./sheerfabric_diffuse.dds"; normalMap[0] = "./sheerfabric_normal.png"; doubleSided = "1"; materialTag0 = "RoadAndPath"; translucent = "1"; translucentBlendOp = "None"; alphaTest = "1"; alphaRef = "161"; }; singleton Material(clothframe_ColorEffectR225G87B143_material) { mapTo = "ColorEffectR225G87B143-material"; diffuseMap[0] = ""; normalMap[0] = ""; specularMap[0] = ""; diffuseColor[0] = "0.882353 0.341177 0.560784 1"; specular[0] = "1 1 1 1"; specularPower[0] = 10; doubleSided = false; translucent = false; translucentBlendOp = "None"; }; singleton Material(clothframe_ColorEffectR154G154B229_material) { mapTo = "ColorEffectR154G154B229-material"; diffuseColor[0] = "0.603922 0.603922 0.898039 1"; specularPower[0] = "10"; translucentBlendOp = "None"; };
22.175439
63
0.678797
[ "MIT" ]
Torque3D-GameEngine/T3D-Demos
data/FPSGameplay/pacific/art/shapes/props/cloth/materials.cs
1,264
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("ProviderBase.Web")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("ProviderBase.Web")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("e28ce6b3-4986-4e71-a6fa-e7a87ffe5330")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
37.972973
84
0.745196
[ "MIT" ]
ch604aru/ProviderBase
ProviderBase.Web/Properties/AssemblyInfo.cs
1,408
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Uroboros.syntax.variables.abstracts; namespace Uroboros.syntax.expressions.bools { class BoolTernary : DefaultBoolable { private IBoolable condition; private IBoolable leftValue; private IBoolable rightValue; public BoolTernary(IBoolable condition, IBoolable leftValue, IBoolable rightValue) { this.condition = condition; this.leftValue = leftValue; this.rightValue = rightValue; } public override bool ToBool() { return condition.ToBool() ? leftValue.ToBool() : rightValue.ToBool(); } } }
26.607143
91
0.62953
[ "MIT" ]
nathaliefil/uroboros
MetaFileManager/syntax/expressions/bools/BoolTernary.cs
747
C#
using Microsoft.CodeAnalysis; namespace InlineMapping.Extensions; internal static class SyntaxNodeExtensions { internal static T FindParent<T>(this SyntaxNode self) where T : SyntaxNode { var parent = self.Parent; while (parent is not T && parent is not null) { parent = parent.Parent; } return (T)(parent!); } }
17.631579
54
0.713433
[ "MIT" ]
JasonBock/InlineMapping
src/InlineMapping/Extensions/SyntaxNodeExtensions.cs
337
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("MidiToMGBA")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("MidiToMGBA")] [assembly: AssemblyCopyright("Copyright © 2018")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("5b36e77f-b147-418d-a5d8-c2ef7475be7f")] // 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.1.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
37.648649
84
0.744436
[ "MIT" ]
0x0ade/MidiToBGB
Properties/AssemblyInfo.cs
1,396
C#
using System; using System.Collections.Generic; using System.Text; namespace GameProject { class UserValidationManager : IUserValidation { public bool Validate(Gamer gamer) { if (gamer.BirthYear== 2001 && gamer.FirstName== "Ahsen" && gamer.LastName=="Kıpçak" && gamer.IdentityNumber==1223333331); { return true; } return false; } } }
22.095238
133
0.543103
[ "MIT" ]
Ahsenkpck/KampIntro
GameProject/UserValidationManager.cs
468
C#
namespace NatureShot.Services.Data.Tests.PhotoPosts { using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Moq; using NatureShot.Data.Common.Repositories; using NatureShot.Data.Models; using NatureShot.Services.Data; using NatureShot.Services.Data.NormalPosts; using NatureShot.Services.Data.PhotoPosts; using NatureShot.Services.Data.PhotoPosts.Contracts; using Xunit; public class PhotoPostsLeastDislikesTests { public PhotoPostsLeastDislikesTests() { } [Fact] public void GetImagePostsLeastDislikesShouldReturnFirstTwoElementsWhenThereAreTwoOrMore() { var list = new List<Post>() { new Post { Id = 1, Likes = 0, Dislikes = 3, CreatedOn = new DateTime(2000, 11, 20), AddedByUser = new ApplicationUser { UserName = "Pesho", }, Tags = new List<PostTag> { new PostTag { Tag = new Tag { Name = "#first", }, }, new PostTag { Tag = new Tag { Name = "#second", }, }, }, Type = new PostType { Name = "Image", }, Caption = "testCaption", Location = new Location { Name = "Plovdiv/Bulgaria", }, Camera = new Camera { Model = "Iphone6", }, Image = new Image { ImageUrl = "https://test1", Type = new ImageType { Name = "horizontal", }, }, }, new Post { Id = 2, Likes = 0, Dislikes = 2, CreatedOn = new DateTime(2000, 11, 21), AddedByUser = new ApplicationUser { UserName = "Pesho2", }, Tags = new List<PostTag> { new PostTag { Tag = new Tag { Name = "#first2", }, }, new PostTag { Tag = new Tag { Name = "#second2", }, }, }, Type = new PostType { Name = "Image", }, Caption = "testCaption2", Location = new Location { Name = "Plovdiv/Bulgaria", }, Camera = new Camera { Model = "Iphone6", }, Image = new Image { ImageUrl = "https://test1", Type = new ImageType { Name = "horizontal", }, }, }, new Post { Id = 3, Likes = 0, Dislikes = 1, CreatedOn = new DateTime(2000, 11, 22), AddedByUser = new ApplicationUser { UserName = "Pesho3", }, Tags = new List<PostTag> { new PostTag { Tag = new Tag { Name = "#first3", }, }, new PostTag { Tag = new Tag { Name = "#second3", }, }, }, Type = new PostType { Name = "Image", }, Caption = "testCaption3", Location = new Location { Name = "Plovdiv/Bulgaria", }, Camera = new Camera { Model = "Iphone6", }, Image = new Image { ImageUrl = "https://test1", Type = new ImageType { Name = "horizontal", }, }, }, new Post { Id = 4, Likes = 0, Dislikes = 0, CreatedOn = new DateTime(2000, 11, 23), AddedByUser = new ApplicationUser { UserName = "Pesho4", }, Tags = new List<PostTag> { new PostTag { Tag = new Tag { Name = "#first4", }, }, new PostTag { Tag = new Tag { Name = "#second4", }, }, }, Type = new PostType { Name = "Image", }, Caption = "testCaption4", Location = new Location { Name = "Plovdiv/Bulgaria", }, Camera = new Camera { Model = "Iphone6", }, Image = new Image { ImageUrl = "https://test1", Type = new ImageType { Name = "horizontal", }, }, }, new Post { Id = 5, Likes = 0, Dislikes = 4, CreatedOn = new DateTime(2000, 11, 24), AddedByUser = new ApplicationUser { UserName = "Pesho5", }, Tags = new List<PostTag> { new PostTag { Tag = new Tag { Name = "#first5", }, }, new PostTag { Tag = new Tag { Name = "#second5", }, }, }, Type = new PostType { Name = "Image", }, Caption = "testCaption5", Location = new Location { Name = "Plovdiv/Bulgaria", }, Camera = new Camera { Model = "Iphone6", }, Image = new Image { ImageUrl = "https://test1", Type = new ImageType { Name = "horizontal", }, }, }, }; var repository = new Mock<IDeletableEntityRepository<Post>>(); repository.Setup(r => r.AllAsNoTracking()).Returns(() => list.AsQueryable()); var service = new PhotoPostsLeastDislikes(repository.Object); var posts = service.GetImagePostsLeastDislikes(0, 2).ToList(); Assert.Equal(2, posts.Count()); Assert.Equal(list[3].Id, posts[0].ImageId); Assert.Equal(list[2].Id, posts[1].ImageId); repository.Verify(x => x.AllAsNoTracking(), Times.AtMost(2)); } [Fact] public void GetImagePostsLeastDislikesShouldReturnSecondTwoElementsWhenThereAreFourOrMore() { var list = new List<Post>() { new Post { Id = 1, Likes = 0, Dislikes = 3, CreatedOn = new DateTime(2000, 11, 20), AddedByUser = new ApplicationUser { UserName = "Pesho", }, Tags = new List<PostTag> { new PostTag { Tag = new Tag { Name = "#first", }, }, new PostTag { Tag = new Tag { Name = "#second", }, }, }, Type = new PostType { Name = "Image", }, Caption = "testCaption", Location = new Location { Name = "Plovdiv/Bulgaria", }, Camera = new Camera { Model = "Iphone6", }, Image = new Image { ImageUrl = "https://test1", Type = new ImageType { Name = "horizontal", }, }, }, new Post { Id = 2, Likes = 0, Dislikes = 2, CreatedOn = new DateTime(2000, 11, 21), AddedByUser = new ApplicationUser { UserName = "Pesho2", }, Tags = new List<PostTag> { new PostTag { Tag = new Tag { Name = "#first2", }, }, new PostTag { Tag = new Tag { Name = "#second2", }, }, }, Type = new PostType { Name = "Image", }, Caption = "testCaption2", Location = new Location { Name = "Plovdiv/Bulgaria", }, Camera = new Camera { Model = "Iphone6", }, Image = new Image { ImageUrl = "https://test1", Type = new ImageType { Name = "horizontal", }, }, }, new Post { Id = 3, Likes = 0, Dislikes = 1, CreatedOn = new DateTime(2000, 11, 22), AddedByUser = new ApplicationUser { UserName = "Pesho3", }, Tags = new List<PostTag> { new PostTag { Tag = new Tag { Name = "#first3", }, }, new PostTag { Tag = new Tag { Name = "#second3", }, }, }, Type = new PostType { Name = "Image", }, Caption = "testCaption3", Location = new Location { Name = "Plovdiv/Bulgaria", }, Camera = new Camera { Model = "Iphone6", }, Image = new Image { ImageUrl = "https://test1", Type = new ImageType { Name = "horizontal", }, }, }, new Post { Id = 4, Likes = 0, Dislikes = 0, CreatedOn = new DateTime(2000, 11, 23), AddedByUser = new ApplicationUser { UserName = "Pesho4", }, Tags = new List<PostTag> { new PostTag { Tag = new Tag { Name = "#first4", }, }, new PostTag { Tag = new Tag { Name = "#second4", }, }, }, Type = new PostType { Name = "Image", }, Caption = "testCaption4", Location = new Location { Name = "Plovdiv/Bulgaria", }, Camera = new Camera { Model = "Iphone6", }, Image = new Image { ImageUrl = "https://test1", Type = new ImageType { Name = "horizontal", }, }, }, new Post { Id = 5, Likes = 0, Dislikes = 4, CreatedOn = new DateTime(2000, 11, 24), AddedByUser = new ApplicationUser { UserName = "Pesho5", }, Tags = new List<PostTag> { new PostTag { Tag = new Tag { Name = "#first5", }, }, new PostTag { Tag = new Tag { Name = "#second5", }, }, }, Type = new PostType { Name = "Image", }, Caption = "testCaption5", Location = new Location { Name = "Plovdiv/Bulgaria", }, Camera = new Camera { Model = "Iphone6", }, Image = new Image { ImageUrl = "https://test1", Type = new ImageType { Name = "horizontal", }, }, }, }; var repository = new Mock<IDeletableEntityRepository<Post>>(); repository.Setup(r => r.AllAsNoTracking()).Returns(() => list.AsQueryable()); var service = new PhotoPostsLeastDislikes(repository.Object); var posts = service.GetImagePostsLeastDislikes(1, 2).ToList(); Assert.Equal(2, posts.Count()); Assert.Equal(list[1].Id, posts[0].ImageId); Assert.Equal(list[0].Id, posts[1].ImageId); repository.Verify(x => x.AllAsNoTracking(), Times.AtMost(2)); } [Fact] public void GetImagePostsLeastDislikesShouldReturnFirstElementWhenThereAreLessThanTwo() { var list = new List<Post>() { new Post { Id = 1, Likes = 0, Dislikes = 3, CreatedOn = new DateTime(2000, 11, 20), AddedByUser = new ApplicationUser { UserName = "Pesho", }, Tags = new List<PostTag> { new PostTag { Tag = new Tag { Name = "#first", }, }, new PostTag { Tag = new Tag { Name = "#second", }, }, }, Type = new PostType { Name = "Image", }, Caption = "testCaption", Location = new Location { Name = "Plovdiv/Bulgaria", }, Camera = new Camera { Model = "Iphone6", }, Image = new Image { ImageUrl = "https://test1", Type = new ImageType { Name = "horizontal", }, }, }, }; var repository = new Mock<IDeletableEntityRepository<Post>>(); repository.Setup(r => r.AllAsNoTracking()).Returns(() => list.AsQueryable()); var service = new PhotoPostsLeastDislikes(repository.Object); var posts = service.GetImagePostsLeastDislikes(0, 2).ToList(); Assert.Single(posts); Assert.Equal(list[0].Id, posts[0].ImageId); repository.Verify(x => x.AllAsNoTracking(), Times.AtMost(2)); } [Fact] public void GetImagePostsLeastDislikesShouldReturnThirdElementWhenThereAreThree() { var list = new List<Post>() { new Post { Id = 1, Likes = 0, Dislikes = 3, CreatedOn = new DateTime(2000, 11, 20), AddedByUser = new ApplicationUser { UserName = "Pesho", }, Tags = new List<PostTag> { new PostTag { Tag = new Tag { Name = "#first", }, }, new PostTag { Tag = new Tag { Name = "#second", }, }, }, Type = new PostType { Name = "Image", }, Caption = "testCaption", Location = new Location { Name = "Plovdiv/Bulgaria", }, Camera = new Camera { Model = "Iphone6", }, Image = new Image { ImageUrl = "https://test1", Type = new ImageType { Name = "horizontal", }, }, }, new Post { Id = 2, Likes = 0, Dislikes = 2, CreatedOn = new DateTime(2000, 11, 21), AddedByUser = new ApplicationUser { UserName = "Pesho2", }, Tags = new List<PostTag> { new PostTag { Tag = new Tag { Name = "#first2", }, }, new PostTag { Tag = new Tag { Name = "#second2", }, }, }, Type = new PostType { Name = "Image", }, Caption = "testCaption2", Location = new Location { Name = "Plovdiv/Bulgaria", }, Camera = new Camera { Model = "Iphone6", }, Image = new Image { ImageUrl = "https://test1", Type = new ImageType { Name = "horizontal", }, }, }, new Post { Id = 3, Likes = 0, Dislikes = 1, CreatedOn = new DateTime(2000, 11, 22), AddedByUser = new ApplicationUser { UserName = "Pesho3", }, Tags = new List<PostTag> { new PostTag { Tag = new Tag { Name = "#first3", }, }, new PostTag { Tag = new Tag { Name = "#second3", }, }, }, Type = new PostType { Name = "Image", }, Caption = "testCaption3", Location = new Location { Name = "Plovdiv/Bulgaria", }, Camera = new Camera { Model = "Iphone6", }, Image = new Image { ImageUrl = "https://test1", Type = new ImageType { Name = "horizontal", }, }, }, }; var repository = new Mock<IDeletableEntityRepository<Post>>(); repository.Setup(r => r.AllAsNoTracking()).Returns(() => list.AsQueryable()); var service = new PhotoPostsLeastDislikes(repository.Object); var posts = service.GetImagePostsLeastDislikes(1, 2).ToList(); Assert.Single(posts); Assert.Equal(list[0].Id, posts[0].ImageId); repository.Verify(x => x.AllAsNoTracking(), Times.AtMost(2)); } [Fact] public void GetImagePostsLeastDislikesShouldReturnZeroWhenEmpty() { var list = new List<Post>(); var repository = new Mock<IDeletableEntityRepository<Post>>(); repository.Setup(r => r.AllAsNoTracking()).Returns(() => list.AsQueryable()); var service = new PhotoPostsLeastDislikes(repository.Object); var posts = service.GetImagePostsLeastDislikes(0, 2).ToList(); Assert.Empty(posts); repository.Verify(x => x.AllAsNoTracking(), Times.Once); } [Fact] public void SearchByCaptionShouldReturnFirstTwoElementsWhenThereAreTwoOrMore() { var list = new List<Post>() { new Post { Id = 1, Likes = 0, Dislikes = 3, CreatedOn = new DateTime(2000, 11, 20), AddedByUser = new ApplicationUser { UserName = "Pesho", }, Tags = new List<PostTag> { new PostTag { Tag = new Tag { Name = "#first", }, }, new PostTag { Tag = new Tag { Name = "#second", }, }, }, Type = new PostType { Name = "Image", }, Caption = "testCaption", Location = new Location { Name = "Plovdiv/Bulgaria", }, Camera = new Camera { Model = "Iphone6", }, Image = new Image { ImageUrl = "https://test1", Type = new ImageType { Name = "horizontal", }, }, }, new Post { Id = 2, Likes = 0, Dislikes = 2, CreatedOn = new DateTime(2000, 11, 21), AddedByUser = new ApplicationUser { UserName = "Pesho2", }, Tags = new List<PostTag> { new PostTag { Tag = new Tag { Name = "#first2", }, }, new PostTag { Tag = new Tag { Name = "#second2", }, }, }, Type = new PostType { Name = "Image", }, Caption = "testCaption2", Location = new Location { Name = "Plovdiv/Bulgaria", }, Camera = new Camera { Model = "Iphone6", }, Image = new Image { ImageUrl = "https://test1", Type = new ImageType { Name = "horizontal", }, }, }, new Post { Id = 3, Likes = 0, Dislikes = 1, CreatedOn = new DateTime(2000, 11, 22), AddedByUser = new ApplicationUser { UserName = "Pesho3", }, Tags = new List<PostTag> { new PostTag { Tag = new Tag { Name = "#first3", }, }, new PostTag { Tag = new Tag { Name = "#second3", }, }, }, Type = new PostType { Name = "Image", }, Caption = "testCaption3", Location = new Location { Name = "Plovdiv/Bulgaria", }, Camera = new Camera { Model = "Iphone6", }, Image = new Image { ImageUrl = "https://test1", Type = new ImageType { Name = "horizontal", }, }, }, new Post { Id = 4, Likes = 0, Dislikes = 0, CreatedOn = new DateTime(2000, 11, 23), AddedByUser = new ApplicationUser { UserName = "Pesho4", }, Tags = new List<PostTag> { new PostTag { Tag = new Tag { Name = "#first4", }, }, new PostTag { Tag = new Tag { Name = "#second4", }, }, }, Type = new PostType { Name = "Image", }, Caption = "testCaption4", Location = new Location { Name = "Plovdiv/Bulgaria", }, Camera = new Camera { Model = "Iphone6", }, Image = new Image { ImageUrl = "https://test1", Type = new ImageType { Name = "horizontal", }, }, }, new Post { Id = 5, Likes = 0, Dislikes = 4, CreatedOn = new DateTime(2000, 11, 24), AddedByUser = new ApplicationUser { UserName = "Pesho5", }, Tags = new List<PostTag> { new PostTag { Tag = new Tag { Name = "#first5", }, }, new PostTag { Tag = new Tag { Name = "#second5", }, }, }, Type = new PostType { Name = "Image", }, Caption = "testCaption5", Location = new Location { Name = "Plovdiv/Bulgaria", }, Camera = new Camera { Model = "Iphone6", }, Image = new Image { ImageUrl = "https://test1", Type = new ImageType { Name = "horizontal", }, }, }, }; var repository = new Mock<IDeletableEntityRepository<Post>>(); repository.Setup(r => r.AllAsNoTracking()).Returns(() => list.AsQueryable()); var service = new PhotoPostsLeastDislikes(repository.Object); var posts = service.SearchByCaption(0, "testCaption", 2).ToList(); Assert.Equal(2, posts.Count()); Assert.Equal(list[3].Id, posts[0].ImageId); Assert.Equal(list[2].Id, posts[1].ImageId); repository.Verify(x => x.AllAsNoTracking(), Times.AtMost(2)); } [Fact] public void SearchByCaptionShouldReturnSecondTwoElementsWhenThereAreFourOrMore() { var list = new List<Post>() { new Post { Id = 1, Likes = 0, Dislikes = 3, CreatedOn = new DateTime(2000, 11, 20), AddedByUser = new ApplicationUser { UserName = "Pesho", }, Tags = new List<PostTag> { new PostTag { Tag = new Tag { Name = "#first", }, }, new PostTag { Tag = new Tag { Name = "#second", }, }, }, Type = new PostType { Name = "Image", }, Caption = "testCaption", Location = new Location { Name = "Plovdiv/Bulgaria", }, Camera = new Camera { Model = "Iphone6", }, Image = new Image { ImageUrl = "https://test1", Type = new ImageType { Name = "horizontal", }, }, }, new Post { Id = 2, Likes = 0, Dislikes = 2, CreatedOn = new DateTime(2000, 11, 21), AddedByUser = new ApplicationUser { UserName = "Pesho2", }, Tags = new List<PostTag> { new PostTag { Tag = new Tag { Name = "#first2", }, }, new PostTag { Tag = new Tag { Name = "#second2", }, }, }, Type = new PostType { Name = "Image", }, Caption = "testCaption2", Location = new Location { Name = "Plovdiv/Bulgaria", }, Camera = new Camera { Model = "Iphone6", }, Image = new Image { ImageUrl = "https://test1", Type = new ImageType { Name = "horizontal", }, }, }, new Post { Id = 3, Likes = 0, Dislikes = 1, CreatedOn = new DateTime(2000, 11, 22), AddedByUser = new ApplicationUser { UserName = "Pesho3", }, Tags = new List<PostTag> { new PostTag { Tag = new Tag { Name = "#first3", }, }, new PostTag { Tag = new Tag { Name = "#second3", }, }, }, Type = new PostType { Name = "Image", }, Caption = "testCaption3", Location = new Location { Name = "Plovdiv/Bulgaria", }, Camera = new Camera { Model = "Iphone6", }, Image = new Image { ImageUrl = "https://test1", Type = new ImageType { Name = "horizontal", }, }, }, new Post { Id = 4, Likes = 0, Dislikes = 0, CreatedOn = new DateTime(2000, 11, 23), AddedByUser = new ApplicationUser { UserName = "Pesho4", }, Tags = new List<PostTag> { new PostTag { Tag = new Tag { Name = "#first4", }, }, new PostTag { Tag = new Tag { Name = "#second4", }, }, }, Type = new PostType { Name = "Image", }, Caption = "testCaption4", Location = new Location { Name = "Plovdiv/Bulgaria", }, Camera = new Camera { Model = "Iphone6", }, Image = new Image { ImageUrl = "https://test1", Type = new ImageType { Name = "horizontal", }, }, }, new Post { Id = 5, Likes = 0, Dislikes = 4, CreatedOn = new DateTime(2000, 11, 24), AddedByUser = new ApplicationUser { UserName = "Pesho5", }, Tags = new List<PostTag> { new PostTag { Tag = new Tag { Name = "#first5", }, }, new PostTag { Tag = new Tag { Name = "#second5", }, }, }, Type = new PostType { Name = "Image", }, Caption = "testCaption5", Location = new Location { Name = "Plovdiv/Bulgaria", }, Camera = new Camera { Model = "Iphone6", }, Image = new Image { ImageUrl = "https://test1", Type = new ImageType { Name = "horizontal", }, }, }, }; var repository = new Mock<IDeletableEntityRepository<Post>>(); repository.Setup(r => r.AllAsNoTracking()).Returns(() => list.AsQueryable()); var service = new PhotoPostsLeastDislikes(repository.Object); var posts = service.SearchByCaption(1, "testCaption", 2).ToList(); Assert.Equal(2, posts.Count()); Assert.Equal(list[1].Id, posts[0].ImageId); Assert.Equal(list[0].Id, posts[1].ImageId); repository.Verify(x => x.AllAsNoTracking(), Times.AtMost(2)); } [Fact] public void SearchByCaptionShouldReturnFirstElementWhenThereAreLessThanTwo() { var list = new List<Post>() { new Post { Id = 1, Likes = 0, Dislikes = 3, CreatedOn = new DateTime(2000, 11, 20), AddedByUser = new ApplicationUser { UserName = "Pesho", }, Tags = new List<PostTag> { new PostTag { Tag = new Tag { Name = "#first", }, }, new PostTag { Tag = new Tag { Name = "#second", }, }, }, Type = new PostType { Name = "Image", }, Caption = "testCaption", Location = new Location { Name = "Plovdiv/Bulgaria", }, Camera = new Camera { Model = "Iphone6", }, Image = new Image { ImageUrl = "https://test1", Type = new ImageType { Name = "horizontal", }, }, }, }; var repository = new Mock<IDeletableEntityRepository<Post>>(); repository.Setup(r => r.AllAsNoTracking()).Returns(() => list.AsQueryable()); var service = new PhotoPostsLeastDislikes(repository.Object); var posts = service.SearchByCaption(0, "testCaption", 2).ToList(); Assert.Single(posts); Assert.Equal(list[0].Id, posts[0].ImageId); repository.Verify(x => x.AllAsNoTracking(), Times.AtMost(2)); } [Fact] public void SearchByCaptionShouldReturnThirdElementWhenThereLessThanFour() { var list = new List<Post>() { new Post { Id = 1, Likes = 0, Dislikes = 3, CreatedOn = new DateTime(2000, 11, 20), AddedByUser = new ApplicationUser { UserName = "Pesho", }, Tags = new List<PostTag> { new PostTag { Tag = new Tag { Name = "#first", }, }, new PostTag { Tag = new Tag { Name = "#second", }, }, }, Type = new PostType { Name = "Image", }, Caption = "testCaption", Location = new Location { Name = "Plovdiv/Bulgaria", }, Camera = new Camera { Model = "Iphone6", }, Image = new Image { ImageUrl = "https://test1", Type = new ImageType { Name = "horizontal", }, }, }, new Post { Id = 2, Likes = 0, Dislikes = 2, CreatedOn = new DateTime(2000, 11, 21), AddedByUser = new ApplicationUser { UserName = "Pesho2", }, Tags = new List<PostTag> { new PostTag { Tag = new Tag { Name = "#first2", }, }, new PostTag { Tag = new Tag { Name = "#second2", }, }, }, Type = new PostType { Name = "Image", }, Caption = "testCaption2", Location = new Location { Name = "Plovdiv/Bulgaria", }, Camera = new Camera { Model = "Iphone6", }, Image = new Image { ImageUrl = "https://test1", Type = new ImageType { Name = "horizontal", }, }, }, new Post { Id = 3, Likes = 0, Dislikes = 1, CreatedOn = new DateTime(2000, 11, 22), AddedByUser = new ApplicationUser { UserName = "Pesho3", }, Tags = new List<PostTag> { new PostTag { Tag = new Tag { Name = "#first3", }, }, new PostTag { Tag = new Tag { Name = "#second3", }, }, }, Type = new PostType { Name = "Image", }, Caption = "testCaption3", Location = new Location { Name = "Plovdiv/Bulgaria", }, Camera = new Camera { Model = "Iphone6", }, Image = new Image { ImageUrl = "https://test1", Type = new ImageType { Name = "horizontal", }, }, }, }; var repository = new Mock<IDeletableEntityRepository<Post>>(); repository.Setup(r => r.AllAsNoTracking()).Returns(() => list.AsQueryable()); var service = new PhotoPostsLeastDislikes(repository.Object); var posts = service.SearchByCaption(1, "testCaption", 2).ToList(); Assert.Single(posts); Assert.Equal(list[0].Id, posts[0].ImageId); repository.Verify(x => x.AllAsNoTracking(), Times.AtMost(2)); } [Fact] public void SearchByCaptionShouldReturnZeroElementsWhenEmpty() { var list = new List<Post>(); var repository = new Mock<IDeletableEntityRepository<Post>>(); repository.Setup(r => r.AllAsNoTracking()).Returns(() => list.AsQueryable()); var service = new PhotoPostsLeastDislikes(repository.Object); var posts = service.SearchByCaption(0, "testCaption", 2).ToList(); Assert.Empty(posts); repository.Verify(x => x.AllAsNoTracking(), Times.Once); } [Fact] public void SearchByTagsShouldReturnFirstTwoElementsWhenThereAreTwoOrMore() { var list = new List<Post>() { new Post { Id = 1, Likes = 0, Dislikes = 3, CreatedOn = new DateTime(2000, 11, 20), AddedByUser = new ApplicationUser { UserName = "Pesho", }, Tags = new List<PostTag> { new PostTag { Tag = new Tag { Name = "#first", }, }, new PostTag { Tag = new Tag { Name = "#second", }, }, }, Type = new PostType { Name = "Image", }, Caption = "testCaption", Location = new Location { Name = "Plovdiv/Bulgaria", }, Camera = new Camera { Model = "Iphone6", }, Image = new Image { ImageUrl = "https://test1", Type = new ImageType { Name = "horizontal", }, }, }, new Post { Id = 2, Likes = 0, Dislikes = 2, CreatedOn = new DateTime(2000, 11, 21), AddedByUser = new ApplicationUser { UserName = "Pesho2", }, Tags = new List<PostTag> { new PostTag { Tag = new Tag { Name = "#first2", }, }, new PostTag { Tag = new Tag { Name = "#second2", }, }, }, Type = new PostType { Name = "Image", }, Caption = "testCaption2", Location = new Location { Name = "Plovdiv/Bulgaria", }, Camera = new Camera { Model = "Iphone6", }, Image = new Image { ImageUrl = "https://test1", Type = new ImageType { Name = "horizontal", }, }, }, new Post { Id = 3, Likes = 0, Dislikes = 1, CreatedOn = new DateTime(2000, 11, 22), AddedByUser = new ApplicationUser { UserName = "Pesho3", }, Tags = new List<PostTag> { new PostTag { Tag = new Tag { Name = "#first3", }, }, new PostTag { Tag = new Tag { Name = "#second3", }, }, }, Type = new PostType { Name = "Image", }, Caption = "testCaption3", Location = new Location { Name = "Plovdiv/Bulgaria", }, Camera = new Camera { Model = "Iphone6", }, Image = new Image { ImageUrl = "https://test1", Type = new ImageType { Name = "horizontal", }, }, }, new Post { Id = 4, Likes = 0, Dislikes = 0, CreatedOn = new DateTime(2000, 11, 23), AddedByUser = new ApplicationUser { UserName = "Pesho4", }, Tags = new List<PostTag> { new PostTag { Tag = new Tag { Name = "#first4", }, }, new PostTag { Tag = new Tag { Name = "#second4", }, }, }, Type = new PostType { Name = "Image", }, Caption = "testCaption4", Location = new Location { Name = "Plovdiv/Bulgaria", }, Camera = new Camera { Model = "Iphone6", }, Image = new Image { ImageUrl = "https://test1", Type = new ImageType { Name = "horizontal", }, }, }, new Post { Id = 5, Likes = 0, Dislikes = 4, CreatedOn = new DateTime(2000, 11, 24), AddedByUser = new ApplicationUser { UserName = "Pesho5", }, Tags = new List<PostTag> { new PostTag { Tag = new Tag { Name = "#first", }, }, new PostTag { Tag = new Tag { Name = "#second5", }, }, }, Type = new PostType { Name = "Image", }, Caption = "testCaption5", Location = new Location { Name = "Plovdiv/Bulgaria", }, Camera = new Camera { Model = "Iphone6", }, Image = new Image { ImageUrl = "https://test1", Type = new ImageType { Name = "horizontal", }, }, }, }; var repository = new Mock<IDeletableEntityRepository<Post>>(); repository.Setup(r => r.AllAsNoTracking()).Returns(() => list.AsQueryable()); var service = new PhotoPostsLeastDislikes(repository.Object); var posts = service.SearchByTags(0, "#first", 2).ToList(); Assert.Equal(2, posts.Count()); Assert.Equal(list[0].Id, posts[0].ImageId); Assert.Equal(list[4].Id, posts[1].ImageId); repository.Verify(x => x.AllAsNoTracking(), Times.AtMost(2)); } [Fact] public void SearchByTagsShouldReturnSecondTwoElementsWhenThereAreFourOrMore() { var list = new List<Post>() { new Post { Id = 1, Likes = 0, Dislikes = 3, CreatedOn = new DateTime(2000, 11, 20), AddedByUser = new ApplicationUser { UserName = "Pesho", }, Tags = new List<PostTag> { new PostTag { Tag = new Tag { Name = "#first", }, }, new PostTag { Tag = new Tag { Name = "#second", }, }, }, Type = new PostType { Name = "Image", }, Caption = "testCaption", Location = new Location { Name = "Plovdiv/Bulgaria", }, Camera = new Camera { Model = "Iphone6", }, Image = new Image { ImageUrl = "https://test1", Type = new ImageType { Name = "horizontal", }, }, }, new Post { Id = 2, Likes = 0, Dislikes = 2, CreatedOn = new DateTime(2000, 11, 21), AddedByUser = new ApplicationUser { UserName = "Pesho2", }, Tags = new List<PostTag> { new PostTag { Tag = new Tag { Name = "#first", }, }, new PostTag { Tag = new Tag { Name = "#second2", }, }, }, Type = new PostType { Name = "Image", }, Caption = "testCaption2", Location = new Location { Name = "Plovdiv/Bulgaria", }, Camera = new Camera { Model = "Iphone6", }, Image = new Image { ImageUrl = "https://test1", Type = new ImageType { Name = "horizontal", }, }, }, new Post { Id = 3, Likes = 0, Dislikes = 1, CreatedOn = new DateTime(2000, 11, 22), AddedByUser = new ApplicationUser { UserName = "Pesho3", }, Tags = new List<PostTag> { new PostTag { Tag = new Tag { Name = "#first", }, }, new PostTag { Tag = new Tag { Name = "#second3", }, }, }, Type = new PostType { Name = "Image", }, Caption = "testCaption3", Location = new Location { Name = "Plovdiv/Bulgaria", }, Camera = new Camera { Model = "Iphone6", }, Image = new Image { ImageUrl = "https://test1", Type = new ImageType { Name = "horizontal", }, }, }, new Post { Id = 4, Likes = 0, Dislikes = 0, CreatedOn = new DateTime(2000, 11, 23), AddedByUser = new ApplicationUser { UserName = "Pesho4", }, Tags = new List<PostTag> { new PostTag { Tag = new Tag { Name = "#first", }, }, new PostTag { Tag = new Tag { Name = "#second4", }, }, }, Type = new PostType { Name = "Image", }, Caption = "testCaption4", Location = new Location { Name = "Plovdiv/Bulgaria", }, Camera = new Camera { Model = "Iphone6", }, Image = new Image { ImageUrl = "https://test1", Type = new ImageType { Name = "horizontal", }, }, }, new Post { Id = 5, Likes = 0, Dislikes = 4, CreatedOn = new DateTime(2000, 11, 24), AddedByUser = new ApplicationUser { UserName = "Pesho5", }, Tags = new List<PostTag> { new PostTag { Tag = new Tag { Name = "#first5", }, }, new PostTag { Tag = new Tag { Name = "#second5", }, }, }, Type = new PostType { Name = "Image", }, Caption = "testCaption5", Location = new Location { Name = "Plovdiv/Bulgaria", }, Camera = new Camera { Model = "Iphone6", }, Image = new Image { ImageUrl = "https://test1", Type = new ImageType { Name = "horizontal", }, }, }, }; var repository = new Mock<IDeletableEntityRepository<Post>>(); repository.Setup(r => r.AllAsNoTracking()).Returns(() => list.AsQueryable()); var service = new PhotoPostsLeastDislikes(repository.Object); var posts = service.SearchByTags(1, "#first", 2).ToList(); Assert.Equal(2, posts.Count()); Assert.Equal(list[1].Id, posts[0].ImageId); Assert.Equal(list[0].Id, posts[1].ImageId); repository.Verify(x => x.AllAsNoTracking(), Times.AtMost(2)); } [Fact] public void SearchByTagsShouldReturnFirstElementWhenThereAreLessThanTwo() { var list = new List<Post>() { new Post { Id = 1, Likes = 0, Dislikes = 3, CreatedOn = new DateTime(2000, 11, 20), AddedByUser = new ApplicationUser { UserName = "Pesho", }, Tags = new List<PostTag> { new PostTag { Tag = new Tag { Name = "#first", }, }, new PostTag { Tag = new Tag { Name = "#second", }, }, }, Type = new PostType { Name = "Image", }, Caption = "testCaption", Location = new Location { Name = "Plovdiv/Bulgaria", }, Camera = new Camera { Model = "Iphone6", }, Image = new Image { ImageUrl = "https://test1", Type = new ImageType { Name = "horizontal", }, }, }, new Post { Id = 2, Likes = 0, Dislikes = 2, CreatedOn = new DateTime(2000, 11, 21), AddedByUser = new ApplicationUser { UserName = "Pesho2", }, Tags = new List<PostTag> { new PostTag { Tag = new Tag { Name = "#first2", }, }, new PostTag { Tag = new Tag { Name = "#second2", }, }, }, Type = new PostType { Name = "Image", }, Caption = "testCaption2", Location = new Location { Name = "Plovdiv/Bulgaria", }, Camera = new Camera { Model = "Iphone6", }, Image = new Image { ImageUrl = "https://test1", Type = new ImageType { Name = "horizontal", }, }, }, new Post { Id = 3, Likes = 0, Dislikes = 1, CreatedOn = new DateTime(2000, 11, 22), AddedByUser = new ApplicationUser { UserName = "Pesho3", }, Tags = new List<PostTag> { new PostTag { Tag = new Tag { Name = "#first3", }, }, new PostTag { Tag = new Tag { Name = "#second3", }, }, }, Type = new PostType { Name = "Image", }, Caption = "testCaption3", Location = new Location { Name = "Plovdiv/Bulgaria", }, Camera = new Camera { Model = "Iphone6", }, Image = new Image { ImageUrl = "https://test1", Type = new ImageType { Name = "horizontal", }, }, }, new Post { Id = 4, Likes = 0, Dislikes = 0, CreatedOn = new DateTime(2000, 11, 23), AddedByUser = new ApplicationUser { UserName = "Pesho4", }, Tags = new List<PostTag> { new PostTag { Tag = new Tag { Name = "#first4", }, }, new PostTag { Tag = new Tag { Name = "#second4", }, }, }, Type = new PostType { Name = "Image", }, Caption = "testCaption4", Location = new Location { Name = "Plovdiv/Bulgaria", }, Camera = new Camera { Model = "Iphone6", }, Image = new Image { ImageUrl = "https://test1", Type = new ImageType { Name = "horizontal", }, }, }, new Post { Id = 5, Likes = 0, Dislikes = 4, CreatedOn = new DateTime(2000, 11, 24), AddedByUser = new ApplicationUser { UserName = "Pesho5", }, Tags = new List<PostTag> { new PostTag { Tag = new Tag { Name = "#first5", }, }, new PostTag { Tag = new Tag { Name = "#second5", }, }, }, Type = new PostType { Name = "Image", }, Caption = "testCaption5", Location = new Location { Name = "Plovdiv/Bulgaria", }, Camera = new Camera { Model = "Iphone6", }, Image = new Image { ImageUrl = "https://test1", Type = new ImageType { Name = "horizontal", }, }, }, }; var repository = new Mock<IDeletableEntityRepository<Post>>(); repository.Setup(r => r.AllAsNoTracking()).Returns(() => list.AsQueryable()); var service = new PhotoPostsLeastDislikes(repository.Object); var posts = service.SearchByTags(0, "#first", 2).ToList(); Assert.Single(posts); Assert.Equal(list[0].Id, posts[0].ImageId); repository.Verify(x => x.AllAsNoTracking(), Times.AtMost(2)); } [Fact] public void SearchByTagsShouldReturnThirdElementWhenThereAreLessThanFour() { var list = new List<Post>() { new Post { Id = 1, Likes = 0, Dislikes = 3, CreatedOn = new DateTime(2000, 11, 20), AddedByUser = new ApplicationUser { UserName = "Pesho", }, Tags = new List<PostTag> { new PostTag { Tag = new Tag { Name = "#first", }, }, new PostTag { Tag = new Tag { Name = "#second", }, }, }, Type = new PostType { Name = "Image", }, Caption = "testCaption", Location = new Location { Name = "Plovdiv/Bulgaria", }, Camera = new Camera { Model = "Iphone6", }, Image = new Image { ImageUrl = "https://test1", Type = new ImageType { Name = "horizontal", }, }, }, new Post { Id = 2, Likes = 0, Dislikes = 2, CreatedOn = new DateTime(2000, 11, 21), AddedByUser = new ApplicationUser { UserName = "Pesho2", }, Tags = new List<PostTag> { new PostTag { Tag = new Tag { Name = "#first", }, }, new PostTag { Tag = new Tag { Name = "#second2", }, }, }, Type = new PostType { Name = "Image", }, Caption = "testCaption2", Location = new Location { Name = "Plovdiv/Bulgaria", }, Camera = new Camera { Model = "Iphone6", }, Image = new Image { ImageUrl = "https://test1", Type = new ImageType { Name = "horizontal", }, }, }, new Post { Id = 3, Likes = 0, Dislikes = 1, CreatedOn = new DateTime(2000, 11, 22), AddedByUser = new ApplicationUser { UserName = "Pesho3", }, Tags = new List<PostTag> { new PostTag { Tag = new Tag { Name = "#first", }, }, new PostTag { Tag = new Tag { Name = "#second3", }, }, }, Type = new PostType { Name = "Image", }, Caption = "testCaption3", Location = new Location { Name = "Plovdiv/Bulgaria", }, Camera = new Camera { Model = "Iphone6", }, Image = new Image { ImageUrl = "https://test1", Type = new ImageType { Name = "horizontal", }, }, }, new Post { Id = 4, Likes = 0, Dislikes = 0, CreatedOn = new DateTime(2000, 11, 23), AddedByUser = new ApplicationUser { UserName = "Pesho4", }, Tags = new List<PostTag> { new PostTag { Tag = new Tag { Name = "#first4", }, }, new PostTag { Tag = new Tag { Name = "#second4", }, }, }, Type = new PostType { Name = "Image", }, Caption = "testCaption4", Location = new Location { Name = "Plovdiv/Bulgaria", }, Camera = new Camera { Model = "Iphone6", }, Image = new Image { ImageUrl = "https://test1", Type = new ImageType { Name = "horizontal", }, }, }, new Post { Id = 5, Likes = 0, Dislikes = 4, CreatedOn = new DateTime(2000, 11, 24), AddedByUser = new ApplicationUser { UserName = "Pesho5", }, Tags = new List<PostTag> { new PostTag { Tag = new Tag { Name = "#first5", }, }, new PostTag { Tag = new Tag { Name = "#second5", }, }, }, Type = new PostType { Name = "Image", }, Caption = "testCaption5", Location = new Location { Name = "Plovdiv/Bulgaria", }, Camera = new Camera { Model = "Iphone6", }, Image = new Image { ImageUrl = "https://test1", Type = new ImageType { Name = "horizontal", }, }, }, }; var repository = new Mock<IDeletableEntityRepository<Post>>(); repository.Setup(r => r.AllAsNoTracking()).Returns(() => list.AsQueryable()); var service = new PhotoPostsLeastDislikes(repository.Object); var posts = service.SearchByTags(1, "#first", 2).ToList(); Assert.Single(posts); Assert.Equal(list[0].Id, posts[0].ImageId); repository.Verify(x => x.AllAsNoTracking(), Times.AtMost(2)); } [Fact] public void SearchByTagsShouldReturnZeroWhenThereIsNone() { var list = new List<Post>() { new Post { Id = 1, Likes = 0, Dislikes = 3, CreatedOn = new DateTime(2000, 11, 20), AddedByUser = new ApplicationUser { UserName = "Pesho", }, Tags = new List<PostTag> { new PostTag { Tag = new Tag { Name = "#first", }, }, new PostTag { Tag = new Tag { Name = "#second", }, }, }, Type = new PostType { Name = "Image", }, Caption = "testCaption", Location = new Location { Name = "Plovdiv/Bulgaria", }, Camera = new Camera { Model = "Iphone6", }, Image = new Image { ImageUrl = "https://test1", Type = new ImageType { Name = "horizontal", }, }, }, new Post { Id = 2, Likes = 0, Dislikes = 2, CreatedOn = new DateTime(2000, 11, 21), AddedByUser = new ApplicationUser { UserName = "Pesho2", }, Tags = new List<PostTag> { new PostTag { Tag = new Tag { Name = "#first2", }, }, new PostTag { Tag = new Tag { Name = "#second2", }, }, }, Type = new PostType { Name = "Image", }, Caption = "testCaption2", Location = new Location { Name = "Plovdiv/Bulgaria", }, Camera = new Camera { Model = "Iphone6", }, Image = new Image { ImageUrl = "https://test1", Type = new ImageType { Name = "horizontal", }, }, }, new Post { Id = 3, Likes = 0, Dislikes = 1, CreatedOn = new DateTime(2000, 11, 22), AddedByUser = new ApplicationUser { UserName = "Pesho3", }, Tags = new List<PostTag> { new PostTag { Tag = new Tag { Name = "#first3", }, }, new PostTag { Tag = new Tag { Name = "#second3", }, }, }, Type = new PostType { Name = "Image", }, Caption = "testCaption3", Location = new Location { Name = "Plovdiv/Bulgaria", }, Camera = new Camera { Model = "Iphone6", }, Image = new Image { ImageUrl = "https://test1", Type = new ImageType { Name = "horizontal", }, }, }, new Post { Id = 4, Likes = 0, Dislikes = 0, CreatedOn = new DateTime(2000, 11, 23), AddedByUser = new ApplicationUser { UserName = "Pesho4", }, Tags = new List<PostTag> { new PostTag { Tag = new Tag { Name = "#first4", }, }, new PostTag { Tag = new Tag { Name = "#second4", }, }, }, Type = new PostType { Name = "Image", }, Caption = "testCaption4", Location = new Location { Name = "Plovdiv/Bulgaria", }, Camera = new Camera { Model = "Iphone6", }, Image = new Image { ImageUrl = "https://test1", Type = new ImageType { Name = "horizontal", }, }, }, new Post { Id = 5, Likes = 0, Dislikes = 4, CreatedOn = new DateTime(2000, 11, 24), AddedByUser = new ApplicationUser { UserName = "Pesho5", }, Tags = new List<PostTag> { new PostTag { Tag = new Tag { Name = "#first5", }, }, new PostTag { Tag = new Tag { Name = "#second5", }, }, }, Type = new PostType { Name = "Image", }, Caption = "testCaption5", Location = new Location { Name = "Plovdiv/Bulgaria", }, Camera = new Camera { Model = "Iphone6", }, Image = new Image { ImageUrl = "https://test1", Type = new ImageType { Name = "horizontal", }, }, }, }; var repository = new Mock<IDeletableEntityRepository<Post>>(); repository.Setup(r => r.AllAsNoTracking()).Returns(() => list.AsQueryable()); var service = new PhotoPostsLeastDislikes(repository.Object); var posts = service.SearchByTags(0, "#zero", 2).ToList(); Assert.Empty(posts); repository.Verify(x => x.AllAsNoTracking(), Times.Once); } [Fact] public void SearchByUsernameShouldReturnFirstTwoElementsWhenThereAreTwoOrMore() { var list = new List<Post>() { new Post { Id = 1, Likes = 0, Dislikes = 3, CreatedOn = new DateTime(2000, 11, 20), AddedByUser = new ApplicationUser { UserName = "Pesho", }, Tags = new List<PostTag> { new PostTag { Tag = new Tag { Name = "#first", }, }, new PostTag { Tag = new Tag { Name = "#second", }, }, }, Type = new PostType { Name = "Image", }, Caption = "testCaption", Location = new Location { Name = "Plovdiv/Bulgaria", }, Camera = new Camera { Model = "Iphone6", }, Image = new Image { ImageUrl = "https://test1", Type = new ImageType { Name = "horizontal", }, }, }, new Post { Id = 2, Likes = 0, Dislikes = 2, CreatedOn = new DateTime(2000, 11, 21), AddedByUser = new ApplicationUser { UserName = "Pesho2", }, Tags = new List<PostTag> { new PostTag { Tag = new Tag { Name = "#first2", }, }, new PostTag { Tag = new Tag { Name = "#second2", }, }, }, Type = new PostType { Name = "Image", }, Caption = "testCaption2", Location = new Location { Name = "Plovdiv/Bulgaria", }, Camera = new Camera { Model = "Iphone6", }, Image = new Image { ImageUrl = "https://test1", Type = new ImageType { Name = "horizontal", }, }, }, new Post { Id = 3, Likes = 0, Dislikes = 1, CreatedOn = new DateTime(2000, 11, 22), AddedByUser = new ApplicationUser { UserName = "Pesho3", }, Tags = new List<PostTag> { new PostTag { Tag = new Tag { Name = "#first3", }, }, new PostTag { Tag = new Tag { Name = "#second3", }, }, }, Type = new PostType { Name = "Image", }, Caption = "testCaption3", Location = new Location { Name = "Plovdiv/Bulgaria", }, Camera = new Camera { Model = "Iphone6", }, Image = new Image { ImageUrl = "https://test1", Type = new ImageType { Name = "horizontal", }, }, }, new Post { Id = 4, Likes = 0, Dislikes = 0, CreatedOn = new DateTime(2000, 11, 23), AddedByUser = new ApplicationUser { UserName = "Pesho4", }, Tags = new List<PostTag> { new PostTag { Tag = new Tag { Name = "#first4", }, }, new PostTag { Tag = new Tag { Name = "#second4", }, }, }, Type = new PostType { Name = "Image", }, Caption = "testCaption4", Location = new Location { Name = "Plovdiv/Bulgaria", }, Camera = new Camera { Model = "Iphone6", }, Image = new Image { ImageUrl = "https://test1", Type = new ImageType { Name = "horizontal", }, }, }, new Post { Id = 5, Likes = 0, Dislikes = 4, CreatedOn = new DateTime(2000, 11, 24), AddedByUser = new ApplicationUser { UserName = "Pesho5", }, Tags = new List<PostTag> { new PostTag { Tag = new Tag { Name = "#first5", }, }, new PostTag { Tag = new Tag { Name = "#second5", }, }, }, Type = new PostType { Name = "Image", }, Caption = "testCaption5", Location = new Location { Name = "Plovdiv/Bulgaria", }, Camera = new Camera { Model = "Iphone6", }, Image = new Image { ImageUrl = "https://test1", Type = new ImageType { Name = "horizontal", }, }, }, }; var repository = new Mock<IDeletableEntityRepository<Post>>(); repository.Setup(r => r.AllAsNoTracking()).Returns(() => list.AsQueryable()); var service = new PhotoPostsLeastDislikes(repository.Object); var posts = service.SearchByUsername(0, "pesho", 2).ToList(); Assert.Equal(2, posts.Count()); Assert.Equal(list[3].Id, posts[0].ImageId); Assert.Equal(list[2].Id, posts[1].ImageId); repository.Verify(x => x.AllAsNoTracking(), Times.AtMost(2)); } [Fact] public void SearchByUsernameShouldReturnSecondTwoElementsWhenThereAreFourOrMore() { var list = new List<Post>() { new Post { Id = 1, Likes = 0, Dislikes = 3, CreatedOn = new DateTime(2000, 11, 20), AddedByUser = new ApplicationUser { UserName = "Pesho", }, Tags = new List<PostTag> { new PostTag { Tag = new Tag { Name = "#first", }, }, new PostTag { Tag = new Tag { Name = "#second", }, }, }, Type = new PostType { Name = "Image", }, Caption = "testCaption", Location = new Location { Name = "Plovdiv/Bulgaria", }, Camera = new Camera { Model = "Iphone6", }, Image = new Image { ImageUrl = "https://test1", Type = new ImageType { Name = "horizontal", }, }, }, new Post { Id = 2, Likes = 0, Dislikes = 2, CreatedOn = new DateTime(2000, 11, 21), AddedByUser = new ApplicationUser { UserName = "Pesho2", }, Tags = new List<PostTag> { new PostTag { Tag = new Tag { Name = "#first2", }, }, new PostTag { Tag = new Tag { Name = "#second2", }, }, }, Type = new PostType { Name = "Image", }, Caption = "testCaption2", Location = new Location { Name = "Plovdiv/Bulgaria", }, Camera = new Camera { Model = "Iphone6", }, Image = new Image { ImageUrl = "https://test1", Type = new ImageType { Name = "horizontal", }, }, }, new Post { Id = 3, Likes = 0, Dislikes = 1, CreatedOn = new DateTime(2000, 11, 22), AddedByUser = new ApplicationUser { UserName = "Pesho3", }, Tags = new List<PostTag> { new PostTag { Tag = new Tag { Name = "#first3", }, }, new PostTag { Tag = new Tag { Name = "#second3", }, }, }, Type = new PostType { Name = "Image", }, Caption = "testCaption3", Location = new Location { Name = "Plovdiv/Bulgaria", }, Camera = new Camera { Model = "Iphone6", }, Image = new Image { ImageUrl = "https://test1", Type = new ImageType { Name = "horizontal", }, }, }, new Post { Id = 4, Likes = 0, Dislikes = 0, CreatedOn = new DateTime(2000, 11, 23), AddedByUser = new ApplicationUser { UserName = "Pesho4", }, Tags = new List<PostTag> { new PostTag { Tag = new Tag { Name = "#first4", }, }, new PostTag { Tag = new Tag { Name = "#second4", }, }, }, Type = new PostType { Name = "Image", }, Caption = "testCaption4", Location = new Location { Name = "Plovdiv/Bulgaria", }, Camera = new Camera { Model = "Iphone6", }, Image = new Image { ImageUrl = "https://test1", Type = new ImageType { Name = "horizontal", }, }, }, new Post { Id = 5, Likes = 0, Dislikes = 4, CreatedOn = new DateTime(2000, 11, 24), AddedByUser = new ApplicationUser { UserName = "Pesho5", }, Tags = new List<PostTag> { new PostTag { Tag = new Tag { Name = "#first5", }, }, new PostTag { Tag = new Tag { Name = "#second5", }, }, }, Type = new PostType { Name = "Image", }, Caption = "testCaption5", Location = new Location { Name = "Plovdiv/Bulgaria", }, Camera = new Camera { Model = "Iphone6", }, Image = new Image { ImageUrl = "https://test1", Type = new ImageType { Name = "horizontal", }, }, }, }; var repository = new Mock<IDeletableEntityRepository<Post>>(); repository.Setup(r => r.AllAsNoTracking()).Returns(() => list.AsQueryable()); var service = new PhotoPostsLeastDislikes(repository.Object); var posts = service.SearchByUsername(1, "pesho", 2).ToList(); Assert.Equal(2, posts.Count()); Assert.Equal(list[1].Id, posts[0].ImageId); Assert.Equal(list[0].Id, posts[1].ImageId); repository.Verify(x => x.AllAsNoTracking(), Times.AtMost(2)); } [Fact] public void SearchByUsernameShouldReturnFirstElementWhenThereAreLessThanTwo() { var list = new List<Post>() { new Post { Id = 1, Likes = 0, Dislikes = 3, CreatedOn = new DateTime(2000, 11, 20), AddedByUser = new ApplicationUser { UserName = "Pesho1", }, Tags = new List<PostTag> { new PostTag { Tag = new Tag { Name = "#first", }, }, new PostTag { Tag = new Tag { Name = "#second", }, }, }, Type = new PostType { Name = "Image", }, Caption = "testCaption", Location = new Location { Name = "Plovdiv/Bulgaria", }, Camera = new Camera { Model = "Iphone6", }, Image = new Image { ImageUrl = "https://test1", Type = new ImageType { Name = "horizontal", }, }, }, new Post { Id = 2, Likes = 0, Dislikes = 2, CreatedOn = new DateTime(2000, 11, 21), AddedByUser = new ApplicationUser { UserName = "Pesho2", }, Tags = new List<PostTag> { new PostTag { Tag = new Tag { Name = "#first2", }, }, new PostTag { Tag = new Tag { Name = "#second2", }, }, }, Type = new PostType { Name = "Image", }, Caption = "testCaption2", Location = new Location { Name = "Plovdiv/Bulgaria", }, Camera = new Camera { Model = "Iphone6", }, Image = new Image { ImageUrl = "https://test1", Type = new ImageType { Name = "horizontal", }, }, }, new Post { Id = 3, Likes = 0, Dislikes = 1, CreatedOn = new DateTime(2000, 11, 22), AddedByUser = new ApplicationUser { UserName = "Pesho3", }, Tags = new List<PostTag> { new PostTag { Tag = new Tag { Name = "#first3", }, }, new PostTag { Tag = new Tag { Name = "#second3", }, }, }, Type = new PostType { Name = "Image", }, Caption = "testCaption3", Location = new Location { Name = "Plovdiv/Bulgaria", }, Camera = new Camera { Model = "Iphone6", }, Image = new Image { ImageUrl = "https://test1", Type = new ImageType { Name = "horizontal", }, }, }, new Post { Id = 4, Likes = 0, Dislikes = 0, CreatedOn = new DateTime(2000, 11, 23), AddedByUser = new ApplicationUser { UserName = "Pesho4", }, Tags = new List<PostTag> { new PostTag { Tag = new Tag { Name = "#first4", }, }, new PostTag { Tag = new Tag { Name = "#second4", }, }, }, Type = new PostType { Name = "Image", }, Caption = "testCaption4", Location = new Location { Name = "Plovdiv/Bulgaria", }, Camera = new Camera { Model = "Iphone6", }, Image = new Image { ImageUrl = "https://test1", Type = new ImageType { Name = "horizontal", }, }, }, new Post { Id = 5, Likes = 0, Dislikes = 4, CreatedOn = new DateTime(2000, 11, 24), AddedByUser = new ApplicationUser { UserName = "Pesho5", }, Tags = new List<PostTag> { new PostTag { Tag = new Tag { Name = "#first5", }, }, new PostTag { Tag = new Tag { Name = "#second5", }, }, }, Type = new PostType { Name = "Image", }, Caption = "testCaption5", Location = new Location { Name = "Plovdiv/Bulgaria", }, Camera = new Camera { Model = "Iphone6", }, Image = new Image { ImageUrl = "https://test1", Type = new ImageType { Name = "horizontal", }, }, }, }; var repository = new Mock<IDeletableEntityRepository<Post>>(); repository.Setup(r => r.AllAsNoTracking()).Returns(() => list.AsQueryable()); var service = new PhotoPostsLeastDislikes(repository.Object); var posts = service.SearchByUsername(0, "pesho1", 2).ToList(); Assert.Single(posts); Assert.Equal(list[0].Id, posts[0].ImageId); repository.Verify(x => x.AllAsNoTracking(), Times.AtMost(2)); } [Fact] public void SearchByCaptionShouldReturnThirElementWhenThereLessThanFour() { var list = new List<Post>() { new Post { Id = 1, Likes = 0, Dislikes = 3, CreatedOn = new DateTime(2000, 11, 20), AddedByUser = new ApplicationUser { UserName = "Pesho1", }, Tags = new List<PostTag> { new PostTag { Tag = new Tag { Name = "#first", }, }, new PostTag { Tag = new Tag { Name = "#second", }, }, }, Type = new PostType { Name = "Image", }, Caption = "testCaption", Location = new Location { Name = "Plovdiv/Bulgaria", }, Camera = new Camera { Model = "Iphone6", }, Image = new Image { ImageUrl = "https://test1", Type = new ImageType { Name = "horizontal", }, }, }, new Post { Id = 2, Likes = 0, Dislikes = 2, CreatedOn = new DateTime(2000, 11, 21), AddedByUser = new ApplicationUser { UserName = "Pesho2", }, Tags = new List<PostTag> { new PostTag { Tag = new Tag { Name = "#first2", }, }, new PostTag { Tag = new Tag { Name = "#second2", }, }, }, Type = new PostType { Name = "Image", }, Caption = "testCaption2", Location = new Location { Name = "Plovdiv/Bulgaria", }, Camera = new Camera { Model = "Iphone6", }, Image = new Image { ImageUrl = "https://test1", Type = new ImageType { Name = "horizontal", }, }, }, new Post { Id = 3, Likes = 0, Dislikes = 1, CreatedOn = new DateTime(2000, 11, 22), AddedByUser = new ApplicationUser { UserName = "Pesho3", }, Tags = new List<PostTag> { new PostTag { Tag = new Tag { Name = "#first3", }, }, new PostTag { Tag = new Tag { Name = "#second3", }, }, }, Type = new PostType { Name = "Image", }, Caption = "testCaption3", Location = new Location { Name = "Plovdiv/Bulgaria", }, Camera = new Camera { Model = "Iphone6", }, Image = new Image { ImageUrl = "https://test1", Type = new ImageType { Name = "horizontal", }, }, }, new Post { Id = 4, Likes = 0, Dislikes = 0, CreatedOn = new DateTime(2000, 11, 23), AddedByUser = new ApplicationUser { UserName = "Pesho1", }, Tags = new List<PostTag> { new PostTag { Tag = new Tag { Name = "#first4", }, }, new PostTag { Tag = new Tag { Name = "#second4", }, }, }, Type = new PostType { Name = "Image", }, Caption = "testCaption4", Location = new Location { Name = "Plovdiv/Bulgaria", }, Camera = new Camera { Model = "Iphone6", }, Image = new Image { ImageUrl = "https://test1", Type = new ImageType { Name = "horizontal", }, }, }, new Post { Id = 5, Likes = 0, Dislikes = 4, CreatedOn = new DateTime(2000, 11, 24), AddedByUser = new ApplicationUser { UserName = "Pesho1", }, Tags = new List<PostTag> { new PostTag { Tag = new Tag { Name = "#first5", }, }, new PostTag { Tag = new Tag { Name = "#second5", }, }, }, Type = new PostType { Name = "Image", }, Caption = "testCaption5", Location = new Location { Name = "Plovdiv/Bulgaria", }, Camera = new Camera { Model = "Iphone6", }, Image = new Image { ImageUrl = "https://test1", Type = new ImageType { Name = "horizontal", }, }, }, }; var repository = new Mock<IDeletableEntityRepository<Post>>(); repository.Setup(r => r.AllAsNoTracking()).Returns(() => list.AsQueryable()); var service = new PhotoPostsLeastDislikes(repository.Object); var posts = service.SearchByUsername(1, "pesho1", 2).ToList(); Assert.Single(posts); Assert.Equal(list[4].Id, posts[0].ImageId); repository.Verify(x => x.AllAsNoTracking(), Times.AtMost(2)); } [Fact] public void SearchByUsernameShouldReturnZeroWhenNone() { var list = new List<Post>() { new Post { Id = 1, Likes = 0, Dislikes = 3, CreatedOn = new DateTime(2000, 11, 20), AddedByUser = new ApplicationUser { UserName = "Pesho", }, Tags = new List<PostTag> { new PostTag { Tag = new Tag { Name = "#first", }, }, new PostTag { Tag = new Tag { Name = "#second", }, }, }, Type = new PostType { Name = "Image", }, Caption = "testCaption", Location = new Location { Name = "Plovdiv/Bulgaria", }, Camera = new Camera { Model = "Iphone6", }, Image = new Image { ImageUrl = "https://test1", Type = new ImageType { Name = "horizontal", }, }, }, new Post { Id = 2, Likes = 0, Dislikes = 2, CreatedOn = new DateTime(2000, 11, 21), AddedByUser = new ApplicationUser { UserName = "Pesho2", }, Tags = new List<PostTag> { new PostTag { Tag = new Tag { Name = "#first2", }, }, new PostTag { Tag = new Tag { Name = "#second2", }, }, }, Type = new PostType { Name = "Image", }, Caption = "testCaption2", Location = new Location { Name = "Plovdiv/Bulgaria", }, Camera = new Camera { Model = "Iphone6", }, Image = new Image { ImageUrl = "https://test1", Type = new ImageType { Name = "horizontal", }, }, }, new Post { Id = 3, Likes = 0, Dislikes = 1, CreatedOn = new DateTime(2000, 11, 22), AddedByUser = new ApplicationUser { UserName = "Pesho3", }, Tags = new List<PostTag> { new PostTag { Tag = new Tag { Name = "#first3", }, }, new PostTag { Tag = new Tag { Name = "#second3", }, }, }, Type = new PostType { Name = "Image", }, Caption = "testCaption3", Location = new Location { Name = "Plovdiv/Bulgaria", }, Camera = new Camera { Model = "Iphone6", }, Image = new Image { ImageUrl = "https://test1", Type = new ImageType { Name = "horizontal", }, }, }, new Post { Id = 4, Likes = 0, Dislikes = 0, CreatedOn = new DateTime(2000, 11, 23), AddedByUser = new ApplicationUser { UserName = "Pesho4", }, Tags = new List<PostTag> { new PostTag { Tag = new Tag { Name = "#first4", }, }, new PostTag { Tag = new Tag { Name = "#second4", }, }, }, Type = new PostType { Name = "Image", }, Caption = "testCaption4", Location = new Location { Name = "Plovdiv/Bulgaria", }, Camera = new Camera { Model = "Iphone6", }, Image = new Image { ImageUrl = "https://test1", Type = new ImageType { Name = "horizontal", }, }, }, new Post { Id = 5, Likes = 0, Dislikes = 4, CreatedOn = new DateTime(2000, 11, 24), AddedByUser = new ApplicationUser { UserName = "Pesho5", }, Tags = new List<PostTag> { new PostTag { Tag = new Tag { Name = "#first5", }, }, new PostTag { Tag = new Tag { Name = "#second5", }, }, }, Type = new PostType { Name = "Image", }, Caption = "testCaption5", Location = new Location { Name = "Plovdiv/Bulgaria", }, Camera = new Camera { Model = "Iphone6", }, Image = new Image { ImageUrl = "https://test1", Type = new ImageType { Name = "horizontal", }, }, }, }; var repository = new Mock<IDeletableEntityRepository<Post>>(); repository.Setup(r => r.AllAsNoTracking()).Returns(() => list.AsQueryable()); var service = new PhotoPostsLeastDislikes(repository.Object); var posts = service.SearchByUsername(0, "gosho", 2).ToList(); Assert.Empty(posts); repository.Verify(x => x.AllAsNoTracking(), Times.Once); } [Fact] public void SearchByCameraShouldReturnTwoElementWhenThereMoreThanTwo() { var list = new List<Post>() { new Post { Id = 1, Likes = 0, Dislikes = 3, CreatedOn = new DateTime(2000, 11, 20), AddedByUser = new ApplicationUser { UserName = "Pesho1", }, Tags = new List<PostTag> { new PostTag { Tag = new Tag { Name = "#first", }, }, new PostTag { Tag = new Tag { Name = "#second", }, }, }, Type = new PostType { Name = "Image", }, Caption = "testCaption", Location = new Location { Name = "Plovdiv/Bulgaria", }, Camera = new Camera { Model = "Iphone6", }, Image = new Image { ImageUrl = "https://test1", Type = new ImageType { Name = "horizontal", }, }, }, new Post { Id = 2, Likes = 0, Dislikes = 2, CreatedOn = new DateTime(2000, 11, 21), AddedByUser = new ApplicationUser { UserName = "Pesho2", }, Tags = new List<PostTag> { new PostTag { Tag = new Tag { Name = "#first2", }, }, new PostTag { Tag = new Tag { Name = "#second2", }, }, }, Type = new PostType { Name = "Image", }, Caption = "testCaption2", Location = new Location { Name = "Plovdiv/Bulgaria", }, Camera = new Camera { Model = "Iphone6", }, Image = new Image { ImageUrl = "https://test1", Type = new ImageType { Name = "horizontal", }, }, }, new Post { Id = 3, Likes = 0, Dislikes = 1, CreatedOn = new DateTime(2000, 11, 22), AddedByUser = new ApplicationUser { UserName = "Pesho3", }, Tags = new List<PostTag> { new PostTag { Tag = new Tag { Name = "#first3", }, }, new PostTag { Tag = new Tag { Name = "#second3", }, }, }, Type = new PostType { Name = "Image", }, Caption = "testCaption3", Location = new Location { Name = "Plovdiv/Bulgaria", }, Camera = new Camera { Model = "Iphone6", }, Image = new Image { ImageUrl = "https://test1", Type = new ImageType { Name = "horizontal", }, }, }, new Post { Id = 4, Likes = 0, Dislikes = 0, CreatedOn = new DateTime(2000, 11, 23), AddedByUser = new ApplicationUser { UserName = "Pesho1", }, Tags = new List<PostTag> { new PostTag { Tag = new Tag { Name = "#first4", }, }, new PostTag { Tag = new Tag { Name = "#second4", }, }, }, Type = new PostType { Name = "Image", }, Caption = "testCaption4", Location = new Location { Name = "Plovdiv/Bulgaria", }, Camera = new Camera { Model = "Iphone6", }, Image = new Image { ImageUrl = "https://test1", Type = new ImageType { Name = "horizontal", }, }, }, new Post { Id = 5, Likes = 0, Dislikes = 4, CreatedOn = new DateTime(2000, 11, 24), AddedByUser = new ApplicationUser { UserName = "Pesho1", }, Tags = new List<PostTag> { new PostTag { Tag = new Tag { Name = "#first5", }, }, new PostTag { Tag = new Tag { Name = "#second5", }, }, }, Type = new PostType { Name = "Image", }, Caption = "testCaption5", Location = new Location { Name = "Plovdiv/Bulgaria", }, Camera = new Camera { Model = "Iphone6", }, Image = new Image { ImageUrl = "https://test1", Type = new ImageType { Name = "horizontal", }, }, }, }; var repository = new Mock<IDeletableEntityRepository<Post>>(); repository.Setup(r => r.AllAsNoTracking()).Returns(() => list.AsQueryable()); var service = new PhotoPostsLeastDislikes(repository.Object); var posts = service.SearchByCamera(0, "Iphone", 2).ToList(); Assert.Equal(2, posts.Count); Assert.Equal(list[3].Id, posts[0].ImageId); Assert.Equal(list[2].Id, posts[1].ImageId); repository.Verify(x => x.AllAsNoTracking(), Times.AtMost(2)); } [Fact] public void SearchByCameraShouldReturnSecondTwoElementWhenThereMoreThanFour() { var list = new List<Post>() { new Post { Id = 1, Likes = 0, Dislikes = 3, CreatedOn = new DateTime(2000, 11, 20), AddedByUser = new ApplicationUser { UserName = "Pesho1", }, Tags = new List<PostTag> { new PostTag { Tag = new Tag { Name = "#first", }, }, new PostTag { Tag = new Tag { Name = "#second", }, }, }, Type = new PostType { Name = "Image", }, Caption = "testCaption", Location = new Location { Name = "Plovdiv/Bulgaria", }, Camera = new Camera { Model = "Iphone6", }, Image = new Image { ImageUrl = "https://test1", Type = new ImageType { Name = "horizontal", }, }, }, new Post { Id = 2, Likes = 0, Dislikes = 2, CreatedOn = new DateTime(2000, 11, 21), AddedByUser = new ApplicationUser { UserName = "Pesho2", }, Tags = new List<PostTag> { new PostTag { Tag = new Tag { Name = "#first2", }, }, new PostTag { Tag = new Tag { Name = "#second2", }, }, }, Type = new PostType { Name = "Image", }, Caption = "testCaption2", Location = new Location { Name = "Plovdiv/Bulgaria", }, Camera = new Camera { Model = "Iphone6", }, Image = new Image { ImageUrl = "https://test1", Type = new ImageType { Name = "horizontal", }, }, }, new Post { Id = 3, Likes = 0, Dislikes = 1, CreatedOn = new DateTime(2000, 11, 22), AddedByUser = new ApplicationUser { UserName = "Pesho3", }, Tags = new List<PostTag> { new PostTag { Tag = new Tag { Name = "#first3", }, }, new PostTag { Tag = new Tag { Name = "#second3", }, }, }, Type = new PostType { Name = "Image", }, Caption = "testCaption3", Location = new Location { Name = "Plovdiv/Bulgaria", }, Camera = new Camera { Model = "Iphone6", }, Image = new Image { ImageUrl = "https://test1", Type = new ImageType { Name = "horizontal", }, }, }, new Post { Id = 4, Likes = 0, Dislikes = 0, CreatedOn = new DateTime(2000, 11, 23), AddedByUser = new ApplicationUser { UserName = "Pesho1", }, Tags = new List<PostTag> { new PostTag { Tag = new Tag { Name = "#first4", }, }, new PostTag { Tag = new Tag { Name = "#second4", }, }, }, Type = new PostType { Name = "Image", }, Caption = "testCaption4", Location = new Location { Name = "Plovdiv/Bulgaria", }, Camera = new Camera { Model = "Iphone6", }, Image = new Image { ImageUrl = "https://test1", Type = new ImageType { Name = "horizontal", }, }, }, new Post { Id = 5, Likes = 0, Dislikes = 4, CreatedOn = new DateTime(2000, 11, 24), AddedByUser = new ApplicationUser { UserName = "Pesho1", }, Tags = new List<PostTag> { new PostTag { Tag = new Tag { Name = "#first5", }, }, new PostTag { Tag = new Tag { Name = "#second5", }, }, }, Type = new PostType { Name = "Image", }, Caption = "testCaption5", Location = new Location { Name = "Plovdiv/Bulgaria", }, Camera = new Camera { Model = "Iphone6", }, Image = new Image { ImageUrl = "https://test1", Type = new ImageType { Name = "horizontal", }, }, }, }; var repository = new Mock<IDeletableEntityRepository<Post>>(); repository.Setup(r => r.AllAsNoTracking()).Returns(() => list.AsQueryable()); var service = new PhotoPostsLeastDislikes(repository.Object); var posts = service.SearchByCamera(1, "Iphone", 2).ToList(); Assert.Equal(2, posts.Count); Assert.Equal(list[1].Id, posts[0].ImageId); Assert.Equal(list[0].Id, posts[1].ImageId); repository.Verify(x => x.AllAsNoTracking(), Times.AtMost(2)); } [Fact] public void SearchByCameraShouldReturnFirstElementWhenThereLessThanTwo() { var list = new List<Post>() { new Post { Id = 1, Likes = 0, Dislikes = 3, CreatedOn = new DateTime(2000, 11, 20), AddedByUser = new ApplicationUser { UserName = "Pesho1", }, Tags = new List<PostTag> { new PostTag { Tag = new Tag { Name = "#first", }, }, new PostTag { Tag = new Tag { Name = "#second", }, }, }, Type = new PostType { Name = "Image", }, Caption = "testCaption", Location = new Location { Name = "Plovdiv/Bulgaria", }, Camera = new Camera { Model = "Huawei", }, Image = new Image { ImageUrl = "https://test1", Type = new ImageType { Name = "horizontal", }, }, }, new Post { Id = 2, Likes = 0, Dislikes = 2, CreatedOn = new DateTime(2000, 11, 21), AddedByUser = new ApplicationUser { UserName = "Pesho2", }, Tags = new List<PostTag> { new PostTag { Tag = new Tag { Name = "#first2", }, }, new PostTag { Tag = new Tag { Name = "#second2", }, }, }, Type = new PostType { Name = "Image", }, Caption = "testCaption2", Location = new Location { Name = "Plovdiv/Bulgaria", }, Camera = new Camera { Model = "Iphone6", }, Image = new Image { ImageUrl = "https://test1", Type = new ImageType { Name = "horizontal", }, }, }, new Post { Id = 3, Likes = 0, Dislikes = 1, CreatedOn = new DateTime(2000, 11, 22), AddedByUser = new ApplicationUser { UserName = "Pesho3", }, Tags = new List<PostTag> { new PostTag { Tag = new Tag { Name = "#first3", }, }, new PostTag { Tag = new Tag { Name = "#second3", }, }, }, Type = new PostType { Name = "Image", }, Caption = "testCaption3", Location = new Location { Name = "Plovdiv/Bulgaria", }, Camera = new Camera { Model = "Iphone6", }, Image = new Image { ImageUrl = "https://test1", Type = new ImageType { Name = "horizontal", }, }, }, new Post { Id = 4, Likes = 0, Dislikes = 0, CreatedOn = new DateTime(2000, 11, 23), AddedByUser = new ApplicationUser { UserName = "Pesho1", }, Tags = new List<PostTag> { new PostTag { Tag = new Tag { Name = "#first4", }, }, new PostTag { Tag = new Tag { Name = "#second4", }, }, }, Type = new PostType { Name = "Image", }, Caption = "testCaption4", Location = new Location { Name = "Plovdiv/Bulgaria", }, Camera = new Camera { Model = "Iphone6", }, Image = new Image { ImageUrl = "https://test1", Type = new ImageType { Name = "horizontal", }, }, }, new Post { Id = 5, Likes = 0, Dislikes = 4, CreatedOn = new DateTime(2000, 11, 24), AddedByUser = new ApplicationUser { UserName = "Pesho1", }, Tags = new List<PostTag> { new PostTag { Tag = new Tag { Name = "#first5", }, }, new PostTag { Tag = new Tag { Name = "#second5", }, }, }, Type = new PostType { Name = "Image", }, Caption = "testCaption5", Location = new Location { Name = "Plovdiv/Bulgaria", }, Camera = new Camera { Model = "Iphone6", }, Image = new Image { ImageUrl = "https://test1", Type = new ImageType { Name = "horizontal", }, }, }, }; var repository = new Mock<IDeletableEntityRepository<Post>>(); repository.Setup(r => r.AllAsNoTracking()).Returns(() => list.AsQueryable()); var service = new PhotoPostsLeastDislikes(repository.Object); var posts = service.SearchByCamera(0, "Huawei", 2).ToList(); Assert.Single(posts); Assert.Equal(list[0].Id, posts[0].ImageId); repository.Verify(x => x.AllAsNoTracking(), Times.AtMost(2)); } [Fact] public void SearchByCameraShouldReturnThirElementWhenThereLessThanFour() { var list = new List<Post>() { new Post { Id = 1, Likes = 0, Dislikes = 3, CreatedOn = new DateTime(2000, 11, 20), AddedByUser = new ApplicationUser { UserName = "Pesho1", }, Tags = new List<PostTag> { new PostTag { Tag = new Tag { Name = "#first", }, }, new PostTag { Tag = new Tag { Name = "#second", }, }, }, Type = new PostType { Name = "Image", }, Caption = "testCaption", Location = new Location { Name = "Plovdiv/Bulgaria", }, Camera = new Camera { Model = "Iphone6", }, Image = new Image { ImageUrl = "https://test1", Type = new ImageType { Name = "horizontal", }, }, }, new Post { Id = 2, Likes = 0, Dislikes = 2, CreatedOn = new DateTime(2000, 11, 21), AddedByUser = new ApplicationUser { UserName = "Pesho2", }, Tags = new List<PostTag> { new PostTag { Tag = new Tag { Name = "#first2", }, }, new PostTag { Tag = new Tag { Name = "#second2", }, }, }, Type = new PostType { Name = "Image", }, Caption = "testCaption2", Location = new Location { Name = "Plovdiv/Bulgaria", }, Camera = new Camera { Model = "Iphone6", }, Image = new Image { ImageUrl = "https://test1", Type = new ImageType { Name = "horizontal", }, }, }, new Post { Id = 3, Likes = 0, Dislikes = 1, CreatedOn = new DateTime(2000, 11, 22), AddedByUser = new ApplicationUser { UserName = "Pesho3", }, Tags = new List<PostTag> { new PostTag { Tag = new Tag { Name = "#first3", }, }, new PostTag { Tag = new Tag { Name = "#second3", }, }, }, Type = new PostType { Name = "Image", }, Caption = "testCaption3", Location = new Location { Name = "Plovdiv/Bulgaria", }, Camera = new Camera { Model = "Iphone6", }, Image = new Image { ImageUrl = "https://test1", Type = new ImageType { Name = "horizontal", }, }, }, new Post { Id = 4, Likes = 0, Dislikes = 0, CreatedOn = new DateTime(2000, 11, 23), AddedByUser = new ApplicationUser { UserName = "Pesho1", }, Tags = new List<PostTag> { new PostTag { Tag = new Tag { Name = "#first4", }, }, new PostTag { Tag = new Tag { Name = "#second4", }, }, }, Type = new PostType { Name = "Image", }, Caption = "testCaption4", Location = new Location { Name = "Plovdiv/Bulgaria", }, Camera = new Camera { Model = "Iphone7", }, Image = new Image { ImageUrl = "https://test1", Type = new ImageType { Name = "horizontal", }, }, }, new Post { Id = 5, Likes = 0, Dislikes = 4, CreatedOn = new DateTime(2000, 11, 24), AddedByUser = new ApplicationUser { UserName = "Pesho1", }, Tags = new List<PostTag> { new PostTag { Tag = new Tag { Name = "#first5", }, }, new PostTag { Tag = new Tag { Name = "#second5", }, }, }, Type = new PostType { Name = "Image", }, Caption = "testCaption5", Location = new Location { Name = "Plovdiv/Bulgaria", }, Camera = new Camera { Model = "Iphone7", }, Image = new Image { ImageUrl = "https://test1", Type = new ImageType { Name = "horizontal", }, }, }, }; var repository = new Mock<IDeletableEntityRepository<Post>>(); repository.Setup(r => r.AllAsNoTracking()).Returns(() => list.AsQueryable()); var service = new PhotoPostsLeastDislikes(repository.Object); var posts = service.SearchByCamera(1, "Iphone6", 2).ToList(); Assert.Single(posts); Assert.Equal(list[0].Id, posts[0].ImageId); repository.Verify(x => x.AllAsNoTracking(), Times.AtMost(2)); } [Fact] public void SearchByCameraShouldReturnZeroElementWhenThereNone() { var list = new List<Post>() { new Post { Id = 1, Likes = 0, Dislikes = 3, CreatedOn = new DateTime(2000, 11, 20), AddedByUser = new ApplicationUser { UserName = "Pesho1", }, Tags = new List<PostTag> { new PostTag { Tag = new Tag { Name = "#first", }, }, new PostTag { Tag = new Tag { Name = "#second", }, }, }, Type = new PostType { Name = "Image", }, Caption = "testCaption", Location = new Location { Name = "Plovdiv/Bulgaria", }, Camera = new Camera { Model = "Iphone6", }, Image = new Image { ImageUrl = "https://test1", Type = new ImageType { Name = "horizontal", }, }, }, new Post { Id = 2, Likes = 0, Dislikes = 2, CreatedOn = new DateTime(2000, 11, 21), AddedByUser = new ApplicationUser { UserName = "Pesho2", }, Tags = new List<PostTag> { new PostTag { Tag = new Tag { Name = "#first2", }, }, new PostTag { Tag = new Tag { Name = "#second2", }, }, }, Type = new PostType { Name = "Image", }, Caption = "testCaption2", Location = new Location { Name = "Plovdiv/Bulgaria", }, Camera = new Camera { Model = "Iphone6", }, Image = new Image { ImageUrl = "https://test1", Type = new ImageType { Name = "horizontal", }, }, }, new Post { Id = 3, Likes = 0, Dislikes = 1, CreatedOn = new DateTime(2000, 11, 22), AddedByUser = new ApplicationUser { UserName = "Pesho3", }, Tags = new List<PostTag> { new PostTag { Tag = new Tag { Name = "#first3", }, }, new PostTag { Tag = new Tag { Name = "#second3", }, }, }, Type = new PostType { Name = "Image", }, Caption = "testCaption3", Location = new Location { Name = "Plovdiv/Bulgaria", }, Camera = new Camera { Model = "Iphone6", }, Image = new Image { ImageUrl = "https://test1", Type = new ImageType { Name = "horizontal", }, }, }, new Post { Id = 4, Likes = 0, Dislikes = 0, CreatedOn = new DateTime(2000, 11, 23), AddedByUser = new ApplicationUser { UserName = "Pesho1", }, Tags = new List<PostTag> { new PostTag { Tag = new Tag { Name = "#first4", }, }, new PostTag { Tag = new Tag { Name = "#second4", }, }, }, Type = new PostType { Name = "Image", }, Caption = "testCaption4", Location = new Location { Name = "Plovdiv/Bulgaria", }, Camera = new Camera { Model = "Iphone6", }, Image = new Image { ImageUrl = "https://test1", Type = new ImageType { Name = "horizontal", }, }, }, new Post { Id = 5, Likes = 0, Dislikes = 4, CreatedOn = new DateTime(2000, 11, 24), AddedByUser = new ApplicationUser { UserName = "Pesho1", }, Tags = new List<PostTag> { new PostTag { Tag = new Tag { Name = "#first5", }, }, new PostTag { Tag = new Tag { Name = "#second5", }, }, }, Type = new PostType { Name = "Image", }, Caption = "testCaption5", Location = new Location { Name = "Plovdiv/Bulgaria", }, Camera = new Camera { Model = "Iphone6", }, Image = new Image { ImageUrl = "https://test1", Type = new ImageType { Name = "horizontal", }, }, }, }; var repository = new Mock<IDeletableEntityRepository<Post>>(); repository.Setup(r => r.AllAsNoTracking()).Returns(() => list.AsQueryable()); var service = new PhotoPostsLeastDislikes(repository.Object); var posts = service.SearchByCamera(1, "Samsung", 2).ToList(); Assert.Empty(posts); repository.Verify(x => x.AllAsNoTracking(), Times.Once); } [Fact] public void SearchByLocationShouldReturnTwoElementWhenThereMoreThanTwo() { var list = new List<Post>() { new Post { Id = 1, Likes = 0, Dislikes = 3, CreatedOn = new DateTime(2000, 11, 20), AddedByUser = new ApplicationUser { UserName = "Pesho1", }, Tags = new List<PostTag> { new PostTag { Tag = new Tag { Name = "#first", }, }, new PostTag { Tag = new Tag { Name = "#second", }, }, }, Type = new PostType { Name = "Image", }, Caption = "testCaption", Location = new Location { Name = "Plovdiv/Bulgaria", }, Camera = new Camera { Model = "Iphone6", }, Image = new Image { ImageUrl = "https://test1", Type = new ImageType { Name = "horizontal", }, }, }, new Post { Id = 2, Likes = 0, Dislikes = 2, CreatedOn = new DateTime(2000, 11, 21), AddedByUser = new ApplicationUser { UserName = "Pesho2", }, Tags = new List<PostTag> { new PostTag { Tag = new Tag { Name = "#first2", }, }, new PostTag { Tag = new Tag { Name = "#second2", }, }, }, Type = new PostType { Name = "Image", }, Caption = "testCaption2", Location = new Location { Name = "Plovdiv/Bulgaria", }, Camera = new Camera { Model = "Iphone6", }, Image = new Image { ImageUrl = "https://test1", Type = new ImageType { Name = "horizontal", }, }, }, new Post { Id = 3, Likes = 0, Dislikes = 1, CreatedOn = new DateTime(2000, 11, 22), AddedByUser = new ApplicationUser { UserName = "Pesho3", }, Tags = new List<PostTag> { new PostTag { Tag = new Tag { Name = "#first3", }, }, new PostTag { Tag = new Tag { Name = "#second3", }, }, }, Type = new PostType { Name = "Image", }, Caption = "testCaption3", Location = new Location { Name = "Plovdiv/Bulgaria", }, Camera = new Camera { Model = "Iphone6", }, Image = new Image { ImageUrl = "https://test1", Type = new ImageType { Name = "horizontal", }, }, }, new Post { Id = 4, Likes = 0, Dislikes = 0, CreatedOn = new DateTime(2000, 11, 23), AddedByUser = new ApplicationUser { UserName = "Pesho1", }, Tags = new List<PostTag> { new PostTag { Tag = new Tag { Name = "#first4", }, }, new PostTag { Tag = new Tag { Name = "#second4", }, }, }, Type = new PostType { Name = "Image", }, Caption = "testCaption4", Location = new Location { Name = "Plovdiv/Bulgaria", }, Camera = new Camera { Model = "Iphone6", }, Image = new Image { ImageUrl = "https://test1", Type = new ImageType { Name = "horizontal", }, }, }, new Post { Id = 5, Likes = 0, Dislikes = 4, CreatedOn = new DateTime(2000, 11, 24), AddedByUser = new ApplicationUser { UserName = "Pesho1", }, Tags = new List<PostTag> { new PostTag { Tag = new Tag { Name = "#first5", }, }, new PostTag { Tag = new Tag { Name = "#second5", }, }, }, Type = new PostType { Name = "Image", }, Caption = "testCaption5", Location = new Location { Name = "Plovdiv/Bulgaria", }, Camera = new Camera { Model = "Iphone6", }, Image = new Image { ImageUrl = "https://test1", Type = new ImageType { Name = "horizontal", }, }, }, }; var repository = new Mock<IDeletableEntityRepository<Post>>(); repository.Setup(r => r.AllAsNoTracking()).Returns(() => list.AsQueryable()); var service = new PhotoPostsLeastDislikes(repository.Object); var posts = service.SearchByLocation(0, "Plovdiv", 2).ToList(); Assert.Equal(2, posts.Count()); Assert.Equal(list[3].Id, posts[0].ImageId); Assert.Equal(list[2].Id, posts[1].ImageId); repository.Verify(x => x.AllAsNoTracking(), Times.AtMost(2)); } [Fact] public void SearchByLocationShouldReturnSecondTwoElementWhenThereMoreThanFour() { var list = new List<Post>() { new Post { Id = 1, Likes = 0, Dislikes = 3, CreatedOn = new DateTime(2000, 11, 20), AddedByUser = new ApplicationUser { UserName = "Pesho1", }, Tags = new List<PostTag> { new PostTag { Tag = new Tag { Name = "#first", }, }, new PostTag { Tag = new Tag { Name = "#second", }, }, }, Type = new PostType { Name = "Image", }, Caption = "testCaption", Location = new Location { Name = "Plovdiv/Bulgaria", }, Camera = new Camera { Model = "Iphone6", }, Image = new Image { ImageUrl = "https://test1", Type = new ImageType { Name = "horizontal", }, }, }, new Post { Id = 2, Likes = 0, Dislikes = 2, CreatedOn = new DateTime(2000, 11, 21), AddedByUser = new ApplicationUser { UserName = "Pesho2", }, Tags = new List<PostTag> { new PostTag { Tag = new Tag { Name = "#first2", }, }, new PostTag { Tag = new Tag { Name = "#second2", }, }, }, Type = new PostType { Name = "Image", }, Caption = "testCaption2", Location = new Location { Name = "Plovdiv/Bulgaria", }, Camera = new Camera { Model = "Iphone6", }, Image = new Image { ImageUrl = "https://test1", Type = new ImageType { Name = "horizontal", }, }, }, new Post { Id = 3, Likes = 0, Dislikes = 1, CreatedOn = new DateTime(2000, 11, 22), AddedByUser = new ApplicationUser { UserName = "Pesho3", }, Tags = new List<PostTag> { new PostTag { Tag = new Tag { Name = "#first3", }, }, new PostTag { Tag = new Tag { Name = "#second3", }, }, }, Type = new PostType { Name = "Image", }, Caption = "testCaption3", Location = new Location { Name = "Plovdiv/Bulgaria", }, Camera = new Camera { Model = "Iphone6", }, Image = new Image { ImageUrl = "https://test1", Type = new ImageType { Name = "horizontal", }, }, }, new Post { Id = 4, Likes = 0, Dislikes = 0, CreatedOn = new DateTime(2000, 11, 23), AddedByUser = new ApplicationUser { UserName = "Pesho1", }, Tags = new List<PostTag> { new PostTag { Tag = new Tag { Name = "#first4", }, }, new PostTag { Tag = new Tag { Name = "#second4", }, }, }, Type = new PostType { Name = "Image", }, Caption = "testCaption4", Location = new Location { Name = "Plovdiv/Bulgaria", }, Camera = new Camera { Model = "Iphone6", }, Image = new Image { ImageUrl = "https://test1", Type = new ImageType { Name = "horizontal", }, }, }, new Post { Id = 5, Likes = 0, Dislikes = 4, CreatedOn = new DateTime(2000, 11, 24), AddedByUser = new ApplicationUser { UserName = "Pesho1", }, Tags = new List<PostTag> { new PostTag { Tag = new Tag { Name = "#first5", }, }, new PostTag { Tag = new Tag { Name = "#second5", }, }, }, Type = new PostType { Name = "Image", }, Caption = "testCaption5", Location = new Location { Name = "Plovdiv/Bulgaria", }, Camera = new Camera { Model = "Iphone6", }, Image = new Image { ImageUrl = "https://test1", Type = new ImageType { Name = "horizontal", }, }, }, }; var repository = new Mock<IDeletableEntityRepository<Post>>(); repository.Setup(r => r.AllAsNoTracking()).Returns(() => list.AsQueryable()); var service = new PhotoPostsLeastDislikes(repository.Object); var posts = service.SearchByLocation(1, "Plovdiv", 2).ToList(); Assert.Equal(2, posts.Count()); Assert.Equal(list[1].Id, posts[0].ImageId); Assert.Equal(list[0].Id, posts[1].ImageId); repository.Verify(x => x.AllAsNoTracking(), Times.AtMost(2)); } [Fact] public void SearchByLocationShouldReturnFirstElementWhenThereLessThanTwo() { var list = new List<Post>() { new Post { Id = 1, Likes = 0, Dislikes = 3, CreatedOn = new DateTime(2000, 11, 20), AddedByUser = new ApplicationUser { UserName = "Pesho1", }, Tags = new List<PostTag> { new PostTag { Tag = new Tag { Name = "#first", }, }, new PostTag { Tag = new Tag { Name = "#second", }, }, }, Type = new PostType { Name = "Image", }, Caption = "testCaption", Location = new Location { Name = "Sofia/Bulgaria", }, Camera = new Camera { Model = "Iphone6", }, Image = new Image { ImageUrl = "https://test1", Type = new ImageType { Name = "horizontal", }, }, }, new Post { Id = 2, Likes = 0, Dislikes = 2, CreatedOn = new DateTime(2000, 11, 21), AddedByUser = new ApplicationUser { UserName = "Pesho2", }, Tags = new List<PostTag> { new PostTag { Tag = new Tag { Name = "#first2", }, }, new PostTag { Tag = new Tag { Name = "#second2", }, }, }, Type = new PostType { Name = "Image", }, Caption = "testCaption2", Location = new Location { Name = "Plovdiv/Bulgaria", }, Camera = new Camera { Model = "Iphone6", }, Image = new Image { ImageUrl = "https://test1", Type = new ImageType { Name = "horizontal", }, }, }, new Post { Id = 3, Likes = 0, Dislikes = 1, CreatedOn = new DateTime(2000, 11, 22), AddedByUser = new ApplicationUser { UserName = "Pesho3", }, Tags = new List<PostTag> { new PostTag { Tag = new Tag { Name = "#first3", }, }, new PostTag { Tag = new Tag { Name = "#second3", }, }, }, Type = new PostType { Name = "Image", }, Caption = "testCaption3", Location = new Location { Name = "Plovdiv/Bulgaria", }, Camera = new Camera { Model = "Iphone6", }, Image = new Image { ImageUrl = "https://test1", Type = new ImageType { Name = "horizontal", }, }, }, new Post { Id = 4, Likes = 0, Dislikes = 0, CreatedOn = new DateTime(2000, 11, 23), AddedByUser = new ApplicationUser { UserName = "Pesho1", }, Tags = new List<PostTag> { new PostTag { Tag = new Tag { Name = "#first4", }, }, new PostTag { Tag = new Tag { Name = "#second4", }, }, }, Type = new PostType { Name = "Image", }, Caption = "testCaption4", Location = new Location { Name = "Plovdiv/Bulgaria", }, Camera = new Camera { Model = "Iphone6", }, Image = new Image { ImageUrl = "https://test1", Type = new ImageType { Name = "horizontal", }, }, }, new Post { Id = 5, Likes = 0, Dislikes = 4, CreatedOn = new DateTime(2000, 11, 24), AddedByUser = new ApplicationUser { UserName = "Pesho1", }, Tags = new List<PostTag> { new PostTag { Tag = new Tag { Name = "#first5", }, }, new PostTag { Tag = new Tag { Name = "#second5", }, }, }, Type = new PostType { Name = "Image", }, Caption = "testCaption5", Location = new Location { Name = "Plovdiv/Bulgaria", }, Camera = new Camera { Model = "Iphone6", }, Image = new Image { ImageUrl = "https://test1", Type = new ImageType { Name = "horizontal", }, }, }, }; var repository = new Mock<IDeletableEntityRepository<Post>>(); repository.Setup(r => r.AllAsNoTracking()).Returns(() => list.AsQueryable()); var service = new PhotoPostsLeastDislikes(repository.Object); var posts = service.SearchByLocation(0, "Sofia", 2).ToList(); Assert.Single(posts); Assert.Equal(list[0].Id, posts[0].ImageId); repository.Verify(x => x.AllAsNoTracking(), Times.AtMost(2)); } [Fact] public void SearchByLocationShouldReturnThirdElementWhenThereLessThanFour() { var list = new List<Post>() { new Post { Id = 1, Likes = 0, Dislikes = 3, CreatedOn = new DateTime(2000, 11, 20), AddedByUser = new ApplicationUser { UserName = "Pesho1", }, Tags = new List<PostTag> { new PostTag { Tag = new Tag { Name = "#first", }, }, new PostTag { Tag = new Tag { Name = "#second", }, }, }, Type = new PostType { Name = "Image", }, Caption = "testCaption", Location = new Location { Name = "Plovdiv/Bulgaria", }, Camera = new Camera { Model = "Iphone6", }, Image = new Image { ImageUrl = "https://test1", Type = new ImageType { Name = "horizontal", }, }, }, new Post { Id = 2, Likes = 0, Dislikes = 2, CreatedOn = new DateTime(2000, 11, 21), AddedByUser = new ApplicationUser { UserName = "Pesho2", }, Tags = new List<PostTag> { new PostTag { Tag = new Tag { Name = "#first2", }, }, new PostTag { Tag = new Tag { Name = "#second2", }, }, }, Type = new PostType { Name = "Image", }, Caption = "testCaption2", Location = new Location { Name = "Plovdiv/Bulgaria", }, Camera = new Camera { Model = "Iphone6", }, Image = new Image { ImageUrl = "https://test1", Type = new ImageType { Name = "horizontal", }, }, }, new Post { Id = 3, Likes = 0, Dislikes = 1, CreatedOn = new DateTime(2000, 11, 22), AddedByUser = new ApplicationUser { UserName = "Pesho3", }, Tags = new List<PostTag> { new PostTag { Tag = new Tag { Name = "#first3", }, }, new PostTag { Tag = new Tag { Name = "#second3", }, }, }, Type = new PostType { Name = "Image", }, Caption = "testCaption3", Location = new Location { Name = "Plovdiv/Bulgaria", }, Camera = new Camera { Model = "Iphone6", }, Image = new Image { ImageUrl = "https://test1", Type = new ImageType { Name = "horizontal", }, }, }, new Post { Id = 4, Likes = 0, Dislikes = 0, CreatedOn = new DateTime(2000, 11, 23), AddedByUser = new ApplicationUser { UserName = "Pesho1", }, Tags = new List<PostTag> { new PostTag { Tag = new Tag { Name = "#first4", }, }, new PostTag { Tag = new Tag { Name = "#second4", }, }, }, Type = new PostType { Name = "Image", }, Caption = "testCaption4", Location = new Location { Name = "Sofia/Bulgaria", }, Camera = new Camera { Model = "Iphone6", }, Image = new Image { ImageUrl = "https://test1", Type = new ImageType { Name = "horizontal", }, }, }, new Post { Id = 5, Likes = 0, Dislikes = 4, CreatedOn = new DateTime(2000, 11, 24), AddedByUser = new ApplicationUser { UserName = "Pesho1", }, Tags = new List<PostTag> { new PostTag { Tag = new Tag { Name = "#first5", }, }, new PostTag { Tag = new Tag { Name = "#second5", }, }, }, Type = new PostType { Name = "Image", }, Caption = "testCaption5", Location = new Location { Name = "Sofia/Bulgaria", }, Camera = new Camera { Model = "Iphone6", }, Image = new Image { ImageUrl = "https://test1", Type = new ImageType { Name = "horizontal", }, }, }, }; var repository = new Mock<IDeletableEntityRepository<Post>>(); repository.Setup(r => r.AllAsNoTracking()).Returns(() => list.AsQueryable()); var service = new PhotoPostsLeastDislikes(repository.Object); var posts = service.SearchByLocation(1, "Plovdiv", 2).ToList(); Assert.Single(posts); Assert.Equal(list[0].Id, posts[0].ImageId); repository.Verify(x => x.AllAsNoTracking(), Times.AtMost(2)); } [Fact] public void SearchByLocationShouldReturnZeroElementsWhenThereAreNone() { var list = new List<Post>() { new Post { Id = 1, Likes = 0, Dislikes = 3, CreatedOn = new DateTime(2000, 11, 20), AddedByUser = new ApplicationUser { UserName = "Pesho1", }, Tags = new List<PostTag> { new PostTag { Tag = new Tag { Name = "#first", }, }, new PostTag { Tag = new Tag { Name = "#second", }, }, }, Type = new PostType { Name = "Image", }, Caption = "testCaption", Location = new Location { Name = "Plovdiv/Bulgaria", }, Camera = new Camera { Model = "Iphone6", }, Image = new Image { ImageUrl = "https://test1", Type = new ImageType { Name = "horizontal", }, }, }, new Post { Id = 2, Likes = 0, Dislikes = 2, CreatedOn = new DateTime(2000, 11, 21), AddedByUser = new ApplicationUser { UserName = "Pesho2", }, Tags = new List<PostTag> { new PostTag { Tag = new Tag { Name = "#first2", }, }, new PostTag { Tag = new Tag { Name = "#second2", }, }, }, Type = new PostType { Name = "Image", }, Caption = "testCaption2", Location = new Location { Name = "Plovdiv/Bulgaria", }, Camera = new Camera { Model = "Iphone6", }, Image = new Image { ImageUrl = "https://test1", Type = new ImageType { Name = "horizontal", }, }, }, new Post { Id = 3, Likes = 0, Dislikes = 1, CreatedOn = new DateTime(2000, 11, 22), AddedByUser = new ApplicationUser { UserName = "Pesho3", }, Tags = new List<PostTag> { new PostTag { Tag = new Tag { Name = "#first3", }, }, new PostTag { Tag = new Tag { Name = "#second3", }, }, }, Type = new PostType { Name = "Image", }, Caption = "testCaption3", Location = new Location { Name = "Plovdiv/Bulgaria", }, Camera = new Camera { Model = "Iphone6", }, Image = new Image { ImageUrl = "https://test1", Type = new ImageType { Name = "horizontal", }, }, }, new Post { Id = 4, Likes = 0, Dislikes = 0, CreatedOn = new DateTime(2000, 11, 23), AddedByUser = new ApplicationUser { UserName = "Pesho1", }, Tags = new List<PostTag> { new PostTag { Tag = new Tag { Name = "#first4", }, }, new PostTag { Tag = new Tag { Name = "#second4", }, }, }, Type = new PostType { Name = "Image", }, Caption = "testCaption4", Location = new Location { Name = "Plovdiv/Bulgaria", }, Camera = new Camera { Model = "Iphone6", }, Image = new Image { ImageUrl = "https://test1", Type = new ImageType { Name = "horizontal", }, }, }, new Post { Id = 5, Likes = 0, Dislikes = 4, CreatedOn = new DateTime(2000, 11, 24), AddedByUser = new ApplicationUser { UserName = "Pesho1", }, Tags = new List<PostTag> { new PostTag { Tag = new Tag { Name = "#first5", }, }, new PostTag { Tag = new Tag { Name = "#second5", }, }, }, Type = new PostType { Name = "Image", }, Caption = "testCaption5", Location = new Location { Name = "Plovdiv/Bulgaria", }, Camera = new Camera { Model = "Iphone6", }, Image = new Image { ImageUrl = "https://test1", Type = new ImageType { Name = "horizontal", }, }, }, }; var repository = new Mock<IDeletableEntityRepository<Post>>(); repository.Setup(r => r.AllAsNoTracking()).Returns(() => list.AsQueryable()); var service = new PhotoPostsLeastDislikes(repository.Object); var posts = service.SearchByLocation(1, "Burgas", 2).ToList(); Assert.Empty(posts); repository.Verify(x => x.AllAsNoTracking(), Times.Once); } } }
34.042855
99
0.240192
[ "MIT" ]
DimitarKazakov/NatureShotWebSite
Nature_Shot/Tests/NatureShot.Services.Data.Tests/PhotoPosts/PhotoPostsLeastDislikesTests.cs
232,753
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // <auto-generated/> #nullable disable using System; namespace Azure.ResourceManager.Workloads.Models { internal static partial class DiskStorageTypeExtensions { public static string ToSerialString(this DiskStorageType value) => value switch { DiskStorageType.PremiumLrs => "Premium_LRS", DiskStorageType.StandardLrs => "Standard_LRS", DiskStorageType.StandardSsdLrs => "StandardSSD_LRS", _ => throw new ArgumentOutOfRangeException(nameof(value), value, "Unknown DiskStorageType value.") }; public static DiskStorageType ToDiskStorageType(this string value) { if (string.Equals(value, "Premium_LRS", StringComparison.InvariantCultureIgnoreCase)) return DiskStorageType.PremiumLrs; if (string.Equals(value, "Standard_LRS", StringComparison.InvariantCultureIgnoreCase)) return DiskStorageType.StandardLrs; if (string.Equals(value, "StandardSSD_LRS", StringComparison.InvariantCultureIgnoreCase)) return DiskStorageType.StandardSsdLrs; throw new ArgumentOutOfRangeException(nameof(value), value, "Unknown DiskStorageType value."); } } }
41.645161
140
0.718048
[ "MIT" ]
damodaravadhani/azure-sdk-for-net
sdk/workloads/Azure.ResourceManager.Workloads/src/Generated/Models/DiskStorageType.Serialization.cs
1,291
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 DependencyInjection { public partial class _Default { } }
25.882353
81
0.418182
[ "MIT" ]
chiennt1612/DependencyInjection
Default.aspx.designer.cs
442
C#
// // Copyright (c) 2006-2018 Erik Ylvisaker // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // using AgateLib.Display; using AgateLib.Quality; using Microsoft.Xna.Framework; using System; namespace AgateLib.Diagnostics.ConsoleAppearance { /// <summary> /// Static class which contains themes for the console window. /// </summary> public static class ConsoleThemes { private static IConsoleTheme defaultTheme; static ConsoleThemes() { Paper = Validate(new ConsoleTheme { BackgroundColor = new Color(0xff, 0xfe, 0xd3), EntryColor = new Color(0x40, 0x30, 0x1a), EntryBackgroundColor = new Color(0xff, 0xff, 0xe3), MessageThemes = { { ConsoleMessageType.Text, new MessageTheme(new Color(0x60, 0x50, 0x2a)) }, { ConsoleMessageType.UserInput, new MessageTheme(new Color(0x40, 0x30, 0x1a), new Color(0xff, 0xff, 0xe3)) }, { ConsoleMessageType.Temporary, new MessageTheme(Color.Red, new Color(0xff, 0xff, 0xe8)) } } }); Green = Validate(new ConsoleTheme { BackgroundColor = new Color(0x20, 0x20, 0x20), EntryPrefix = "$ ", EntryColor = ColorX.FromHsv(120, 0.8, 1), EntryBackgroundColor = new Color(0x30, 0x30, 0x30), MessageThemes = { {ConsoleMessageType.Text, new MessageTheme(ColorX.FromHsv(120, 1, 0.8)) }, {ConsoleMessageType.UserInput, new MessageTheme(ColorX.FromHsv(120, 0.8, 1), new Color(0x30, 0x30, 0x30)) }, {ConsoleMessageType.Temporary, new MessageTheme(Color.White, new Color(0x50, 0x50, 0x50))} } }); Classic = Validate(new ConsoleTheme { BackgroundColor = new Color(0x33, 0x27, 0x99), EntryColor = new Color(0x70, 0x64, 0xd6), MessageThemes = { { ConsoleMessageType.Text, new MessageTheme(new Color(0x70, 0x64, 0xd6))}, { ConsoleMessageType.UserInput, new MessageTheme(new Color(0x70, 0x64, 0xd6))}, { ConsoleMessageType.Temporary, new MessageTheme(new Color(0xcb, 0xd7, 0x65))} } }); WhiteOnBlack = Validate(new ConsoleTheme { BackgroundColor = Color.Black, EntryColor = Color.Yellow, MessageThemes = { { ConsoleMessageType.Text, new MessageTheme(Color.White) }, { ConsoleMessageType.UserInput, new MessageTheme(Color.Yellow) }, { ConsoleMessageType.Temporary, new MessageTheme(Color.Red, Color.White) } } }); Default = Green; } /// <summary> /// /// </summary> public static IConsoleTheme Default { get => defaultTheme; set { Require.ArgumentNotNull(value, nameof(Default)); defaultTheme = value; } } /// <summary> /// /// </summary> public static IConsoleTheme Paper { get; } /// <summary> /// /// </summary> public static IConsoleTheme Classic { get; } /// <summary> /// /// </summary> public static IConsoleTheme Green { get; } /// <summary> /// /// </summary> public static IConsoleTheme WhiteOnBlack { get; } private static IConsoleTheme Validate(ConsoleTheme consoleTheme) { if (consoleTheme.IsComplete == false) { throw new InvalidOperationException("Console theme was incomplete."); } return consoleTheme; } } }
37.160584
129
0.566686
[ "MIT" ]
eylvisaker/AgateLib
src/AgateLib/Diagnostics/ConsoleAppearance/ConsoleThemes.cs
5,093
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. using Steeltoe.Connector.Services; using Xunit; namespace Steeltoe.Connector.MongoDb.Test { public class MongoDbProviderConfigurerTest { [Fact] public void UpdateConfiguration_WithNullMongoDbServiceInfo_ReturnsExpected() { var configurer = new MongoDbProviderConfigurer(); var config = new MongoDbConnectorOptions() { Server = "localhost", Port = 1234, Username = "username", Password = "password", Database = "database" }; configurer.UpdateConfiguration(null, config); Assert.Equal("localhost", config.Server); Assert.Equal(1234, config.Port); Assert.Equal("username", config.Username); Assert.Equal("password", config.Password); Assert.Equal("database", config.Database); Assert.Null(config.ConnectionString); } [Fact] public void UpdateConfiguration_WithMongoDbServiceInfo_ReturnsExpected() { var configurer = new MongoDbProviderConfigurer(); var config = new MongoDbConnectorOptions() { Server = "localhost", Port = 1234, Username = "username", Password = "password", Database = "database" }; var si = new MongoDbServiceInfo("MyId", "mongodb://Dd6O1BPXUHdrmzbP:7E1LxXnlH2hhlPVt@192.168.0.90:27017/cf_b4f8d2fa_a3ea_4e3a_a0e8_2cd040790355"); configurer.UpdateConfiguration(si, config); Assert.Equal("192.168.0.90", config.Server); Assert.Equal(27017, config.Port); Assert.Equal("Dd6O1BPXUHdrmzbP", config.Username); Assert.Equal("7E1LxXnlH2hhlPVt", config.Password); Assert.Equal("cf_b4f8d2fa_a3ea_4e3a_a0e8_2cd040790355", config.Database); } [Fact] public void Configure_NoServiceInfo_ReturnsExpected() { // arrange var config = new MongoDbConnectorOptions() { Server = "localhost", Port = 1234, Username = "username", Password = "password", Database = "database" }; var configurer = new MongoDbProviderConfigurer(); // act var connString = configurer.Configure(null, config); // assert Assert.Equal("mongodb://username:password@localhost:1234/database", connString); } [Fact] public void Configure_ServiceInfoOveridesConfig_ReturnsExpected() { var config = new MongoDbConnectorOptions() { Server = "localhost", Port = 1234, Username = "username", Password = "password", Database = "database" }; var configurer = new MongoDbProviderConfigurer(); var si = new MongoDbServiceInfo("MyId", "mongodb://Dd6O1BPXUHdrmzbP:7E1LxXnlH2hhlPVt@192.168.0.90:27017/cf_b4f8d2fa_a3ea_4e3a_a0e8_2cd040790355"); var connString = configurer.Configure(si, config); Assert.Equal("192.168.0.90", config.Server); Assert.Equal(27017, config.Port); Assert.Equal("Dd6O1BPXUHdrmzbP", config.Username); Assert.Equal("7E1LxXnlH2hhlPVt", config.Password); Assert.Equal("cf_b4f8d2fa_a3ea_4e3a_a0e8_2cd040790355", config.Database); Assert.Equal("mongodb://Dd6O1BPXUHdrmzbP:7E1LxXnlH2hhlPVt@192.168.0.90:27017/cf_b4f8d2fa_a3ea_4e3a_a0e8_2cd040790355", connString); } } }
37.533333
158
0.589698
[ "Apache-2.0" ]
Chatina73/steeltoe
src/Connectors/test/ConnectorBase.Test/MongoDb/MongoDbProviderConfigurerTest.cs
3,943
C#
// File generated from our OpenAPI spec namespace Stripe { using System; using System.Collections.Generic; using Newtonsoft.Json; using Stripe.Infrastructure; /// <summary> /// This object represents a customer of your business. It lets you create recurring charges /// and track payments that belong to the same customer. /// /// Related guide: <a href="https://stripe.com/docs/payments/save-during-payment">Save a /// card during payment</a>. /// </summary> public class Customer : StripeEntity<Customer>, IHasId, IHasMetadata, IHasObject { /// <summary> /// Unique identifier for the object. /// </summary> [JsonProperty("id")] public string Id { get; set; } /// <summary> /// String representing the object's type. Objects of the same type share the same value. /// </summary> [JsonProperty("object")] public string Object { get; set; } /// <summary> /// The customer's address. /// </summary> [JsonProperty("address")] public Address Address { get; set; } /// <summary> /// Current balance, if any, being stored on the customer. If negative, the customer has /// credit to apply to their next invoice. If positive, the customer has an amount owed that /// will be added to their next invoice. The balance does not refer to any unpaid invoices; /// it solely takes into account amounts that have yet to be successfully applied to any /// invoice. This balance is only taken into account as invoices are finalized. /// </summary> [JsonProperty("balance")] public long Balance { get; set; } /// <summary> /// The current funds being held by Stripe on behalf of the customer. These funds can be /// applied towards payment intents with source "cash_balance".The /// settings[reconciliation_mode] field describes whether these funds are applied to such /// payment intents manually or automatically. /// </summary> [JsonProperty("cash_balance")] public CashBalance CashBalance { get; set; } /// <summary> /// Time at which the object was created. Measured in seconds since the Unix epoch. /// </summary> [JsonProperty("created")] [JsonConverter(typeof(UnixDateTimeConverter))] public DateTime Created { get; set; } = Stripe.Infrastructure.DateTimeUtils.UnixEpoch; /// <summary> /// Three-letter <a href="https://stripe.com/docs/currencies">ISO code for the currency</a> /// the customer can be charged in for recurring billing purposes. /// </summary> [JsonProperty("currency")] public string Currency { get; set; } #region Expandable DefaultSource /// <summary> /// (ID of the IPaymentSource) /// ID of the default payment source for the customer. /// /// If you are using payment methods created via the PaymentMethods API, see the <a /// href="https://stripe.com/docs/api/customers/object#customer_object-invoice_settings-default_payment_method">invoice_settings.default_payment_method</a> /// field instead. /// </summary> [JsonIgnore] public string DefaultSourceId { get => this.InternalDefaultSource?.Id; set => this.InternalDefaultSource = SetExpandableFieldId(value, this.InternalDefaultSource); } /// <summary> /// (Expanded) /// ID of the default payment source for the customer. /// /// If you are using payment methods created via the PaymentMethods API, see the <a /// href="https://stripe.com/docs/api/customers/object#customer_object-invoice_settings-default_payment_method">invoice_settings.default_payment_method</a> /// field instead. /// /// For more information, see the <a href="https://stripe.com/docs/expand">expand documentation</a>. /// </summary> [JsonIgnore] public IPaymentSource DefaultSource { get => this.InternalDefaultSource?.ExpandedObject; set => this.InternalDefaultSource = SetExpandableFieldObject(value, this.InternalDefaultSource); } [JsonProperty("default_source")] [JsonConverter(typeof(ExpandableFieldConverter<IPaymentSource>))] internal ExpandableField<IPaymentSource> InternalDefaultSource { get; set; } #endregion /// <summary> /// Warning: this is not in the documentation. /// </summary> [JsonProperty("default_source_type")] public string DefaultSourceType { get; set; } /// <summary> /// Whether this object is deleted or not. /// </summary> [JsonProperty("deleted", NullValueHandling = NullValueHandling.Ignore)] public bool? Deleted { get; set; } /// <summary> /// When the customer's latest invoice is billed by charging automatically, /// <c>delinquent</c> is <c>true</c> if the invoice's latest charge failed. When the /// customer's latest invoice is billed by sending an invoice, <c>delinquent</c> is /// <c>true</c> if the invoice isn't paid by its due date. /// /// If an invoice is marked uncollectible by <a /// href="https://stripe.com/docs/billing/automatic-collection">dunning</a>, /// <c>delinquent</c> doesn't get reset to <c>false</c>. /// </summary> [JsonProperty("delinquent")] public bool Delinquent { get; set; } /// <summary> /// An arbitrary string attached to the object. Often useful for displaying to users. /// </summary> [JsonProperty("description")] public string Description { get; set; } /// <summary> /// Describes the current discount active on the customer, if there is one. /// </summary> [JsonProperty("discount")] public Discount Discount { get; set; } /// <summary> /// The customer's email address. /// </summary> [JsonProperty("email")] public string Email { get; set; } /// <summary> /// The prefix for the customer used to generate unique invoice numbers. /// </summary> [JsonProperty("invoice_prefix")] public string InvoicePrefix { get; set; } [JsonProperty("invoice_settings")] public CustomerInvoiceSettings InvoiceSettings { get; set; } /// <summary> /// Has the value <c>true</c> if the object exists in live mode or the value <c>false</c> if /// the object exists in test mode. /// </summary> [JsonProperty("livemode")] public bool Livemode { get; set; } /// <summary> /// Set of <a href="https://stripe.com/docs/api/metadata">key-value pairs</a> that you can /// attach to an object. This can be useful for storing additional information about the /// object in a structured format. /// </summary> [JsonProperty("metadata")] public Dictionary<string, string> Metadata { get; set; } /// <summary> /// The customer's full name or business name. /// </summary> [JsonProperty("name")] public string Name { get; set; } /// <summary> /// The suffix of the customer's next invoice number, e.g., 0001. /// </summary> [JsonProperty("next_invoice_sequence")] public long NextInvoiceSequence { get; set; } /// <summary> /// The customer's phone number. /// </summary> [JsonProperty("phone")] public string Phone { get; set; } /// <summary> /// The customer's preferred locales (languages), ordered by preference. /// </summary> [JsonProperty("preferred_locales")] public List<string> PreferredLocales { get; set; } /// <summary> /// Mailing and shipping address for the customer. Appears on invoices emailed to this /// customer. /// </summary> [JsonProperty("shipping")] public Shipping Shipping { get; set; } /// <summary> /// The customer's payment sources, if any. /// </summary> [JsonProperty("sources")] public StripeList<IPaymentSource> Sources { get; set; } /// <summary> /// The customer's current subscriptions, if any. /// </summary> [JsonProperty("subscriptions")] public StripeList<Subscription> Subscriptions { get; set; } [JsonProperty("tax")] public CustomerTax Tax { get; set; } /// <summary> /// Describes the customer's tax exemption status. One of <c>none</c>, <c>exempt</c>, or /// <c>reverse</c>. When set to <c>reverse</c>, invoice and receipt PDFs include the text /// <strong>"Reverse charge"</strong>. /// One of: <c>exempt</c>, <c>none</c>, or <c>reverse</c>. /// </summary> [JsonProperty("tax_exempt")] public string TaxExempt { get; set; } /// <summary> /// The customer's tax IDs. /// </summary> [JsonProperty("tax_ids")] public StripeList<TaxId> TaxIds { get; set; } #region Expandable TestClock /// <summary> /// (ID of the TestHelpers.TestClock) /// ID of the test clock this customer belongs to. /// </summary> [JsonIgnore] public string TestClockId { get => this.InternalTestClock?.Id; set => this.InternalTestClock = SetExpandableFieldId(value, this.InternalTestClock); } /// <summary> /// (Expanded) /// ID of the test clock this customer belongs to. /// /// For more information, see the <a href="https://stripe.com/docs/expand">expand documentation</a>. /// </summary> [JsonIgnore] public TestHelpers.TestClock TestClock { get => this.InternalTestClock?.ExpandedObject; set => this.InternalTestClock = SetExpandableFieldObject(value, this.InternalTestClock); } [JsonProperty("test_clock")] [JsonConverter(typeof(ExpandableFieldConverter<TestHelpers.TestClock>))] internal ExpandableField<TestHelpers.TestClock> InternalTestClock { get; set; } #endregion } }
39.261194
163
0.599316
[ "Apache-2.0" ]
ScriptBox99/stripe-dotnet
src/Stripe.net/Entities/Customers/Customer.cs
10,522
C#
using MediatR; using System.Threading; using System.Threading.Tasks; namespace PresenceLight.Core.HueServices.HueService { public class SetColorHandler : IRequestHandler<SetColorCommand, Unit> { IHueService _service; public SetColorHandler(IHueService hueService) { _service = hueService; } public async Task<Unit> Handle(SetColorCommand command, CancellationToken cancellationToken) { await _service.SetColor(command.Availability, command.Activity, command.LightID); return default; } } }
26.043478
101
0.677796
[ "MIT" ]
JMilthaler/presencelight
src/PresenceLight.Core/Lights/HueServices/SetColor/SetColorHandler.cs
601
C#
namespace Paillave.Etl.Core { public class NoFileValueConnectors : IFileValueConnectors { public IFileValueProvider GetProvider(string code) => new NoFileValueProvider(code); public IFileValueProcessor GetProcessor(string code) => new NoFileValueProcessor(code); } }
36.75
95
0.751701
[ "MIT" ]
fundprocess/Etl.Net
src/Paillave.Etl/Core/NoFileValueConnectors.cs
294
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class MovePlatform : MonoBehaviour { [SerializeField] private GameObject tilemap; [SerializeField] private GameObject floorTile; float t; Vector3 startPosition, startPosition2, startPosition3; Vector3 target; float timeToReachTarget; // Start is called before the first frame update void Start() { t = 0; startPosition = target = transform.position; startPosition2 = tilemap.transform.position; startPosition3 = floorTile.transform.position; timeToReachTarget = 3; target = new Vector3(26.4f, -40.49f, 0f); } // Update is called once per frame void Update() { if (GetComponent<Animator>().GetBool("leverFlipped") ) { //&& moved == false Vector3 temp = new Vector3(0,-3,0); tilemap.transform.position = Vector3.Lerp(startPosition2, temp, t); floorTile.transform.position = Vector3.Lerp(startPosition3, temp, t); t += Time.deltaTime / timeToReachTarget; transform.position = Vector3.Lerp(startPosition, target, t); } } }
28.255814
81
0.640329
[ "Apache-2.0" ]
Akisukei/Dinonaut
Assets/Scripts/MovePlatform.cs
1,217
C#
using Harmony; using RimWorld; using System; using System.Collections.Generic; using Verse; using Verse.AI; namespace AnimalsLogic { /* * Changes egg laying logic to try find a sleeping spot to lay egg there instead of leaving it who knows where. Prevents forbidding of the egg if spot is not found. */ [HarmonyPatch(typeof(JobGiver_LayEgg), "TryGiveJob", new Type[] { typeof(Pawn) })] static class JobGiver_LayEgg_TryGiveJob_Patch { static bool Prefix(ref Job __result, Pawn pawn) { CompEggLayer compEggLayer = pawn.TryGetComp<CompEggLayer>(); if (compEggLayer == null || !compEggLayer.CanLayNow) { return false; } IntVec3 c; Building_Bed bed = RestUtility.FindBedFor(pawn); if (bed != null) c = bed.Position; else c = RCellFinder.RandomWanderDestFor(pawn, pawn.Position, 5f, null, Danger.Some); __result = new Job(JobDefOf.LayEgg, c); return false; } } [HarmonyPatch(typeof(JobDriver_LayEgg), "MakeNewToils", new Type[0])] static class JobDriver_LayEgg_MakeNewToils_Patch { static bool Prefix(ref IEnumerable<Toil> __result, JobDriver_LayEgg __instance) { __result = new List<Toil> { Toils_Goto.GotoCell(TargetIndex.A, PathEndMode.OnCell), Toils_General.Wait(500), Toils_General.Do(delegate { Pawn actor = __instance.pawn; Thing egg = GenSpawn.Spawn(actor.GetComp<CompEggLayer>().ProduceEgg(), actor.Position, __instance.pawn.Map); if (actor.Faction == null || actor.Faction != Faction.OfPlayerSilentFail) { egg.SetForbiddenIfOutsideHomeArea(); } }), }; return false; } } }
35.362069
169
0.554364
[ "MIT" ]
Vulnoxx/RimworldMods
AnimalsLogic/Source/AnimalsLogic/LayEggsInNests.cs
2,053
C#
using Microsoft.Win32; using Playnite.Web; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; namespace GogLibrary { public class Gog { public const string EnStoreLocaleString = "US_USD_en-US"; public static string ClientExecPath { get { var path = InstallationPath; return string.IsNullOrEmpty(path) ? string.Empty : Path.Combine(path, "GalaxyClient.exe"); } } public static bool IsInstalled { get { if (string.IsNullOrEmpty(InstallationPath) || !Directory.Exists(InstallationPath)) { return false; } else { return true; } } } public static string InstallationPath { get { RegistryKey key; key = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\WOW6432Node\GOG.com\GalaxyClient\paths"); if (key == null) { Registry.LocalMachine.OpenSubKey(@"SOFTWARE\GOG.com\GalaxyClient\paths"); } if (key == null) { return string.Empty; } return key.GetValue("client").ToString(); } } public static string GetLoginUrl() { var loginUrl = string.Empty; var mainPage = HttpDownloader.DownloadString("https://www.gog.com/").Split('\n'); foreach (var line in mainPage) { if (line.TrimStart().StartsWith("var galaxyAccounts")) { var match = Regex.Match(line, "'(.*)','(.*)'"); if (match.Success) { loginUrl = match.Groups[1].Value; } } } return loginUrl; } } }
27.402439
108
0.449933
[ "MIT" ]
KuroThing/Playnite
source/Plugins/GogLibrary/Gog.cs
2,249
C#
using AlpineClubBansko.Data.Models; using AlpineClubBansko.Services.Contracts; using AlpineClubBansko.Services.Models.AlbumViewModels; using AlpineClubBansko.Web.Models; using MagicStrings; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace AlpineClubBansko.Web.Controllers.Albums { public class AlbumsController : BaseController { private readonly IAlbumService albumService; private readonly ICloudService cloudService; private readonly ILogger<AlbumsController> logger; public AlbumsController(IAlbumService albumService, ICloudService cloudService, UserManager<User> userManager, ILogger<AlbumsController> logger) : base(userManager) { this.logger = logger; this.albumService = albumService; this.cloudService = cloudService; this.CurrentController = this.GetType().Name; } [HttpGet] public IActionResult Index() { try { List<AlbumViewModel> list = albumService.GetAllAlbumsAsViewModels().ToList(); return View(list); } catch (System.Exception e) { logger.LogError(string.Format(SetLog.Error, CurrentUser.UserName, CurrentController, e.Message)); AddDangerNotification(string.Format(Notifications.Fail)); return Redirect("/"); } } [HttpPost] [Authorize] public async Task<IActionResult> Create(CreateAlbumInputModel model) { try { if (this.ModelState.IsValid) { string albumId = await this.albumService.CreateAsync(model.Title, CurrentUser); if (string.IsNullOrEmpty(albumId)) { AddDangerNotification(string.Format(Notifications.CreatedFail, model.Title)); return Redirect("/Albums"); } logger.LogInformation( string.Format(SetLog.CreatedSuccess, CurrentUser.UserName, CurrentController, albumId )); AddWarningNotification(string.Format(Notifications.CreatedSuccess, model.Title)); return Redirect($"/Albums/Update/{albumId}"); } else { logger.LogInformation(string.Format(SetLog.CreatedFail, CurrentUser.UserName, CurrentController)); AddDangerNotification(string.Format(Notifications.CreatedFail, model.Title)); return View(model); } } catch (System.Exception e) { logger.LogError(string.Format(SetLog.Error, CurrentUser.UserName, CurrentController, e.Message)); AddDangerNotification(string.Format(Notifications.Fail)); return Redirect("/Albums"); } } [HttpGet] public IActionResult Details(string id) { try { AlbumViewModel model = this.albumService.GetAlbumByIdAsViewModel(id); if (model == null) { AddWarningNotification(Notifications.NotFound); return Redirect("/"); } return View(model); } catch (System.Exception e) { logger.LogError(string.Format(SetLog.Error, CurrentUser.UserName, CurrentController, e.Message)); AddDangerNotification(string.Format(Notifications.Fail)); return Redirect("/Albums"); } } [HttpGet] [Authorize] public IActionResult Update(string id) { if (!CurrentUser.Albums.Any(r => r.Id == id)) { if (!User.IsInRole("Administrator")) { logger.LogInformation( string.Format(SetLog.NotTheAuthor, CurrentUser.UserName, CurrentController, id )); AddDangerNotification(string.Format(Notifications.OnlyAuthor)); return Redirect($"/Albums/Details/{id}"); } } try { AlbumViewModel model = this.albumService.GetAlbumByIdAsViewModel(id); if (model == null) { AddWarningNotification(Notifications.NotFound); return Redirect("/Albums"); } return View(model); } catch (System.Exception e) { logger.LogError(string.Format(SetLog.Error, CurrentUser.UserName, CurrentController, e.Message)); AddDangerNotification(string.Format(Notifications.Fail)); return Redirect("/Albums"); } } [HttpPost] [Authorize] public async Task<IActionResult> Update(AlbumViewModel model) { if (!CurrentUser.Albums.Any(r => r.Id == model.Id)) { if (!User.IsInRole("Administrator")) { logger.LogInformation( string.Format(SetLog.NotTheAuthor, CurrentUser.UserName, CurrentController, model.Id )); AddDangerNotification(string.Format(Notifications.NotTheAuthor, model.Title)); return Redirect($"/Albums/Details/{model.Id}"); } } try { if (ModelState.IsValid) { await this.albumService.UpdateAsync(model); logger.LogInformation( string.Format(SetLog.UpdateSuccess, CurrentUser.UserName, CurrentController, model.Id )); AddSuccessNotification(string.Format(Notifications.UpdateSuccess, model.Title)); return Redirect($"/Albums/Details/{model.Id}"); } else { AddDangerNotification(string.Format(Notifications.Fail)); return View(model); } } catch (System.Exception e) { logger.LogError(string.Format(SetLog.Error, CurrentUser.UserName, CurrentController, e.Message)); AddDangerNotification(string.Format(Notifications.Fail)); return Redirect("/Albums"); } } [HttpGet] [Authorize] public async Task<IActionResult> Delete(string id) { if (!CurrentUser.Albums.Any(r => r.Id == id)) { if (!User.IsInRole("Administrator")) { logger.LogInformation( string.Format(SetLog.NotTheAuthor, CurrentUser.UserName, CurrentController, id )); AddDangerNotification(string.Format(Notifications.DeleteFail)); return Redirect($"/Albums/Details/{id}"); } } try { var result = await this.albumService.DeleteAsync(id); if (!result) { AddDangerNotification(Notifications.Fail); return Redirect("/Albums"); } logger.LogInformation( string.Format(SetLog.Delete, CurrentUser.UserName, CurrentController, id )); AddSuccessNotification(Notifications.Delete); return Redirect($"/Albums"); } catch (System.Exception e) { logger.LogError(string.Format(SetLog.Error, CurrentUser.UserName, CurrentController, e.Message)); AddDangerNotification(Notifications.Fail); return Redirect($"/Albums"); } } [HttpPost] [Authorize] public async Task<ViewComponentResult> UploadPhoto(IFormFile file, PhotoViewModel model) { try { if (ModelState.IsValid) { model.Author = CurrentUser; model.Album = this.albumService.GetAlbumById(model.AlbumId); var isUploaded = await this.cloudService.UploadImage(file, model); if (!isUploaded) AddDangerNotification(Notifications.Fail); } AlbumViewModel album = this.albumService.GetAlbumByIdAsViewModel(model.AlbumId); return ViewComponent("ViewPhotos", new { model = album.Photos, page = 1 }); } catch (System.Exception e) { logger.LogError(string.Format(SetLog.Error, CurrentUser.UserName, CurrentController, e.Message)); AddDangerNotification(Notifications.Fail); return null; } } [HttpPost] [Authorize] public async Task<ViewComponentResult> DeletePhoto(string photoId, string albumId) { try { await this.cloudService.DeleteImage(photoId); AlbumViewModel album = this.albumService.GetAlbumByIdAsViewModel(albumId); return ViewComponent("ViewPhotos", new { model = album.Photos, page = 1 }); } catch (System.Exception e) { logger.LogError(string.Format(SetLog.Error, CurrentUser.UserName, CurrentController, e.Message)); AddDangerNotification(Notifications.Fail); return null; } } [HttpPost] [Authorize] public async Task<IActionResult> CreateComment(string albumId, string content) { try { await this.albumService.CreateCommentAsync(albumId, content, CurrentUser); logger.LogInformation( string.Format(SetLog.CreatedSuccess, CurrentUser.UserName, CurrentController, $"AlbumCommentFor-{albumId}" )); AlbumViewModel model = albumService.GetAlbumByIdAsViewModel(albumId); return PartialView("_AlbumComments", model.Comments); } catch (System.Exception e) { logger.LogError(string.Format(SetLog.Error, CurrentUser.UserName, CurrentController, e.Message)); AddDangerNotification(Notifications.Fail); return null; } } [HttpPost] [Authorize] public async Task<IActionResult> DeleteComment(string commentId, string albumId) { try { await this.albumService.DeleteCommentAsync(commentId); logger.LogInformation( string.Format(SetLog.Delete, CurrentUser.UserName, CurrentController, $"AlbumCommentFor-{albumId}" )); AlbumViewModel model = albumService.GetAlbumByIdAsViewModel(albumId); return PartialView("_AlbumComments", model.Comments); } catch (System.Exception e) { logger.LogError(string.Format(SetLog.Error, CurrentUser.UserName, CurrentController, e.Message)); AddDangerNotification(Notifications.Fail); return null; } } [HttpGet] public IActionResult FilterAlbums(string searchCriteria, string sortOrder, int page) { try { List<AlbumViewModel> list = this.albumService.GetAllAlbumsAsViewModels().ToList(); return ViewComponent("ViewAlbums", new { model = list, searchCriteria, sortOrder, page }); } catch (System.Exception e) { logger.LogError(string.Format(SetLog.Error, CurrentUser.UserName, CurrentController, e.Message)); AddDangerNotification(Notifications.Fail); return null; } } [HttpGet] public IActionResult FilterPhotos(int page, string albumId) { try { List<PhotoViewModel> list = this.albumService.GetAlbumByIdAsViewModel(albumId).Photos; return ViewComponent("UpdatePhotos", new { model = list, page }); } catch (System.Exception e) { logger.LogError(string.Format(SetLog.Error, CurrentUser.UserName, CurrentController, e.Message)); AddDangerNotification(Notifications.Fail); return null; } } [HttpPost] public async Task<bool> AddViewed(string albumId) { try { bool result = await this.albumService.AddViewedAsync(albumId); return result; } catch (System.Exception e) { logger.LogError(string.Format(SetLog.Error, CurrentUser.UserName, CurrentController, e.Message)); AddDangerNotification(Notifications.Fail); return false; } } [HttpPost] [Authorize] public async Task<bool> Favorite(string albumId) { try { bool result = await this.albumService.FavoriteAsync(albumId, CurrentUser); return result; } catch (System.Exception e) { logger.LogError(string.Format(SetLog.Error, CurrentUser.UserName, CurrentController, e.Message)); AddDangerNotification(Notifications.Fail); return false; } } [HttpGet] public IActionResult RefreshStats(string albumId) { try { AlbumViewModel model = this.albumService.GetAlbumByIdAsViewModel(albumId); return ViewComponent("AlbumOptions", model); } catch (System.Exception e) { logger.LogError(string.Format(SetLog.Error, CurrentUser.UserName, CurrentController, e.Message)); AddDangerNotification(Notifications.Fail); return null; } } } }
32.163569
102
0.460529
[ "MIT" ]
codacy-badger/AlpineClubBansko
src/Web/AlpineClubBansko.Web/Controllers/Albums/AlbumsController.cs
17,306
C#
// Prexonite // // Copyright (c) 2014, Christian Klauser // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // The names of the contributors may be used to endorse or // promote products derived from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. // IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, // INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, // WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING // IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using Prexonite.Compiler.Cil; using Prexonite.Types; namespace Prexonite.Commands.List; public class Skip : CoroutineCommand, ICilCompilerAware { #region Singleton private Skip() { } public static Skip Instance { get; } = new(); #endregion protected override IEnumerable<PValue> CoroutineRun(ContextCarrier sctxCarrier, PValue[] args) { return CoroutineRunStatically(sctxCarrier, args); } [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Coroutine")] protected static IEnumerable<PValue> CoroutineRunStatically(ContextCarrier sctxCarrier, PValue[] args) { if (sctxCarrier == null) throw new ArgumentNullException(nameof(sctxCarrier)); if (args == null) throw new ArgumentNullException(nameof(args)); var sctx = sctxCarrier.StackContext; var i = 0; if (args.Length < 1) throw new PrexoniteException("Skip requires at least one argument."); var index = (int) args[0].ConvertTo(sctx, PType.Int, true).Value; for (var j = 1; j < args.Length; j++) { var arg = args[j]; var set = Map._ToEnumerable(sctx, arg); if (set == null) throw new PrexoniteException(arg + " is neither a list nor a coroutine."); foreach (var value in set) { if (i++ >= index) yield return value; } } } public static PValue RunStatically(StackContext sctx, PValue[] args) { var carrier = new ContextCarrier(); var corctx = new CoroutineContext(sctx, CoroutineRunStatically(carrier, args)); carrier.StackContext = corctx; return sctx.CreateNativePValue(new Coroutine(corctx)); } #region ICilCompilerAware Members /// <summary> /// Asses qualification and preferences for a certain instruction. /// </summary> /// <param name = "ins">The instruction that is about to be compiled.</param> /// <returns>A set of <see cref = "CompilationFlags" />.</returns> CompilationFlags ICilCompilerAware.CheckQualification(Instruction ins) { return CompilationFlags.PrefersRunStatically; } /// <summary> /// Provides a custom compiler routine for emitting CIL byte code for a specific instruction. /// </summary> /// <param name = "state">The compiler state.</param> /// <param name = "ins">The instruction to compile.</param> void ICilCompilerAware.ImplementInCil(CompilerState state, Instruction ins) { throw new NotSupportedException(); } #endregion }
39.234783
102
0.658466
[ "BSD-3-Clause" ]
SealedSun/prx
Prexonite/Commands/List/Skip.cs
4,512
C#
/* * * (c) Copyright Ascensio System Limited 2010-2020 * * 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; namespace ASC.Mail.Core.Entities { public class ServerAddress { public int Id { get; set; } public string AddressName { get; set; } public int Tenant { get; set; } public int DomainId { get; set; } public int MailboxId { get; set; } public bool IsMailGroup { get; set; } public bool IsAlias { get; set; } public DateTime DateCreated { get; set; } } }
31.058824
75
0.675189
[ "Apache-2.0" ]
Ektai-Solution-Pty-Ltd/CommunityServer
module/ASC.Mail/ASC.Mail/Core/Entities/ServerAddress.cs
1,056
C#
using Alocha.Api.DTOs.SowDTOs; using Alocha.Domain.Entities; using Alocha.Domain.Interfaces; using AutoMapper; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Alocha.Api.Services { public class SowService : ISowService { private readonly IUnitOfWork _unitOfWork; private readonly IMapper _mapper; public SowService(IUnitOfWork unitOfWork, IMapper mapper) { _unitOfWork = unitOfWork; _mapper = mapper; } public async Task<IEnumerable<SowDTO>> GetAllSowsAsync(string email) { var user = await _unitOfWork.User.FindOneAsync(u => u.Email == email); if (user != null) { var sows = user.Sows.Where(s => !s.IsRemoved); var dto = _mapper.Map<IEnumerable<SowDTO>>(sows); return dto; } return null; } public async Task<SowOneDTO> GetOneSowAsync(string email, int sowId) { var user = await _unitOfWork.User.FindOneAsync(u => u.Email == email); if (user != null) { var sow = user.Sows.Where(s => s.SowId == sowId && !s.IsRemoved).First(); var dto = _mapper.Map<SowOneDTO>(sow); return dto; } return null; } public async Task<SowOneDTO> AddSowAsync(SowCreateDTO dto, string email) { var user = await _unitOfWork.User.FindOneAsync(u => u.Email == email); if(user != null) { if (!user.Sows.Any(s => s.Number == dto.Number)) { var sow = _mapper.Map<Sow>(dto); sow.UserId = user.Id; _unitOfWork.Sow.Add(sow); await _unitOfWork.SaveChangesAsync(); return await GetOneSowAsync(email, sow.SowId); } } return null; } public async Task<bool> EditSowAsync(SowOneDTO dto, string email) { var user = await _unitOfWork.User.FindOneAsync(u => u.Email == email); if (user != null) { var sow = user.Sows.Where(s => s.SowId == dto.SowId && !s.IsRemoved).First(); _mapper.Map(dto, sow); return await _unitOfWork.SaveChangesAsync(); } return false; } public async Task<bool> RemoveSowAync(string email, int sowId) { var user = await _unitOfWork.User.FindOneAsync(u => u.Email == email); if(user != null) { var sow = user.Sows.Where(s => s.SowId == sowId).First(); if(sow != null) { sow.IsRemoved = true; return await _unitOfWork.SaveChangesAsync(); } } return false; } public async Task<IEnumerable<SowDTO>> GetPregnantSows(string email) { var user = await _unitOfWork.User.FindOneAsync(u => u.Email == email); if(user != null) { var sows = user.Sows.Where(s => s.Status == "Prośna" && !s.IsRemoved); return _mapper.Map<IEnumerable<SowDTO>>(sows); } return null; } public async Task<bool> VaccinateSow(int sowId, string email) { var user = await _unitOfWork.User.FindOneAsync(u => u.Email == email); if(user != null) { var sow = user.Sows.Where(s => s.SowId == sowId && !s.IsRemoved).FirstOrDefault(); if (sow != null) { if (!sow.IsVaccinated) { sow.IsVaccinated = true; return await _unitOfWork.SaveChangesAsync(); } return true; } } return false; } } }
33.409836
98
0.494848
[ "MIT" ]
kamil0508/Alocha.core
Alocha.Api/Services/SowService.cs
4,079
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.IO; namespace DVD3 { class Program { const int NmbOfBranches = 3; const int maxPlayers = 50; static void Main(string[] args) { string[] clubs = new string[maxPlayers]; Branch[] branches = new Branch[NmbOfBranches]; int branchCount = 0; string[] filePath = Directory.GetFiles(Directory.GetCurrentDirectory(), "*.csv"); foreach (string file in filePath) { branchCount = Read(file, branches, branchCount); } MemberContainer partList = PartisipatingList(branches); PrintParticipants(partList); MemberContainer forward = Forwards(branches, "puolejas"); PrintForwards(forward); MemberContainer invitedPlayers = Invited(branches); PrintInvitedPlayers(@"..\..\Rinktinė.csv", invitedPlayers); printCampPart(branches); } /// <summary> /// gauna branches masyvo elementa kuris atitinka start ir end datas /// </summary> /// <param name="branches">masyvas saugantis zaideju ir personalo konteinerius</param> /// <param name="start">stovyklos pradzios data</param> /// <param name="end">stovyklos pabaigos data</param> /// <returns></returns> private static Branch GetBranchByYear(Branch[] branches, DateTime start, DateTime end) { for (int i = 0; i < NmbOfBranches; i++) { if (branches[i].start == start && branches[i].end == end) { return branches[i]; } } return null; } /// <summary> /// Nuskaitymo funkcija /// </summary> /// <param name="file">duomenu failo pavadinimas</param> /// <param name="branches">masyvas saugantis zaideju ir personalo konteinerius</param> /// <param name="branchCount">branches amsyvo skaitliukas</param> /// <returns>grazina branshes skaitliuko reiksme</returns> private static int Read(string file, Branch[] branches, int branchCount) { DateTime start = new DateTime(); using (StreamReader reader = new StreamReader(file)) { string line = null; line = reader.ReadLine(); if (line != null) { start = DateTime.Parse(line); } line = reader.ReadLine(); DateTime end = DateTime.Parse(line); branches[branchCount++] = new Branch(start, end); Branch branch = GetBranchByYear(branches, start, end); while ((line = reader.ReadLine()) != null) { string[] values = line.Split(' '); char type = Convert.ToChar(line[0]); string name = values[1]; string surname = values[2]; DateTime birth = DateTime.Parse(values[3]); if (type == 'K') { double height = double.Parse(values[4]); string position = values[5]; string club = values[6]; bool invitation = bool.Parse(values[7]); bool indication = bool.Parse(values[8]); Players player = new Players(name, surname, birth, height, position, club, invitation, indication); branch.players.AddMember(player); } else { string duty = values[4]; Personalas staff = new Personalas(name, surname, birth, duty); branch.staff.AddMember(staff); } } } return branchCount; } /// <summary> /// sudro dalyviu sarasa /// </summary> /// <param name="branches">masyvas saugantis zaideju ir personalo konteinerius</param> /// <returns>dalyviu konteineri</returns> static MemberContainer PartisipatingList(Branch[] branches) { MemberContainer partList = new MemberContainer(maxPlayers); for (int i = 0; i < branches[0].players.Count; i++) { for (int j = 0; j < branches[1].players.Count; j++) { if (branches[0].players.GetMember(i).name == branches[1].players.GetMember(j).name) { for (int k = 0; k < branches[2].players.Count; k++) { if (branches[0].players.GetMember(i).name == branches[2].players.GetMember(k).name) { partList.AddMember(branches[0].players.GetMember(i)); } } } } } for (int i = 0; i < branches[0].staff.Count; i++) { for (int j = 0; j < branches[1].staff.Count; j++) { if (branches[0].staff.GetMember(i).name == branches[1].staff.GetMember(j).name) { for (int k = 0; k < branches[2].staff.Count; k++) { if (branches[0].staff.GetMember(i).name == branches[2].staff.GetMember(k).name) { partList.AddMember(branches[0].staff.GetMember(i)); } } } } } return partList; } /// <summary> /// spausdina dalyviu sarasa /// </summary> /// <param name="partList">dalyviu konteineris</param> static void PrintParticipants(MemberContainer partList) { Console.WriteLine("Zaidejai dalyvave visose 3 stovyklose: "); for (int i = 0; i < partList.Count; i++) { Console.WriteLine("Nr. {0}: {1}", (i + 1), partList.GetMember(i).ToString()); } } /// <summary> /// sudaro puoleju konteineri /// </summary> /// <param name="branches">masyvas saugantis zaideju ir personalo konteinerius</param> /// <param name="position">pozicija(puolejas)</param> /// <returns>puoleju konteineris</returns> static MemberContainer Forwards(Branch[] branches, string position) { MemberContainer forward = new MemberContainer(maxPlayers); for (int k = 0; k < 3; k++) { for (int i = 0; i < branches[k].players.Count; i++) { Players player = branches[k].players.GetMember(i) as Players; if (player.position == position) { if (!AlreadyHave(forward, branches[k].players.GetMember(i).name)) forward.AddMember(player); } } } return forward; } /// <summary> /// tikrina ar puoleju konteineris jau turi tikrinama puoleja /// </summary> /// <param name="forward">puoleju konteineris</param> /// <param name="plName">tikrinamas puolejas</param> /// <returns>ar turi ar ne</returns> static bool AlreadyHave(MemberContainer forward, string plName) { for (int i = 0; i < forward.Count; i++) { if (forward.GetMember(i).name == plName) { return true; } } return false; } /// <summary> /// spausdina puolejus /// </summary> /// <param name="forward">puoleju konteineris</param> static void PrintForwards(MemberContainer forward) { Console.WriteLine("Puoleju sarasas: "); for (int i = 0; i < forward.Count; i++) { Players player = forward.GetMember(i) as Players; Console.WriteLine("Nr. {0}: {1, -10} {2, -10} {3, -5}", (i + 1), forward.GetMember(i).name, forward.GetMember(i).surname, player.height); } } /// <summary> /// sudaro pakviestuju konteineri /// </summary> /// <param name="branches">masyvas saugantis zaideju ir personalo konteinerius</param> /// <returns>pakviestuju konteineris</returns> static MemberContainer Invited(Branch[] branches) { MemberContainer invitedPlayers = new MemberContainer(maxPlayers); for (int k = 0; k < 3; k++) { for (int i = 0; i < branches[k].players.Count; i++) { Players player = branches[k].players.GetMember(i) as Players; if (player.invitation == true) { if (!AlreadyHave(invitedPlayers, branches[k].players.GetMember(i).name)) invitedPlayers.AddMember(player); } } } return invitedPlayers; } /// <summary> /// spausdina pakviestuosius /// </summary> /// <param name="file">failo i kuri spausdinti pavadinimas</param> /// <param name="invited">pakviestuju konteineris</param> static void PrintInvitedPlayers(string file, MemberContainer invited) { using (StreamWriter writer = new StreamWriter(file)) { for (int i = 0; i < invited.Count; i++) { writer.WriteLine("{0}", invited.GetMember(i).ToString()); } } } /// <summary> /// sudaro stovykloje dalyvavusiu konteineri /// </summary> /// <param name="branch">masyvas saugantis zaideju ir personalo konteinerius</param> /// <returns>pakviestuju konteineris</returns> static MemberContainer makeCmapPart(Branch branch) { MemberContainer campPart = new MemberContainer(maxPlayers); for (int i = 0; i < branch.players.Count; i++) { Players player = branch.players.GetMember(i) as Players; campPart.AddMember(player); } for (int j = 0; j < branch.staff.Count; j++) { Personalas staff = branch.staff.GetMember(j) as Personalas; campPart.AddMember(staff); } campPart = sortPart(campPart); return campPart; } /// <summary> /// rikiuoja stovykloje dalyvavusiu sarasa /// </summary> /// <param name="campPart">stovyklos dalyviu konteineris</param> /// <returns>isrikiotas stovyklos dalyviu sarasas</returns> static MemberContainer sortPart(MemberContainer campPart) { for (int i = 0; i < campPart.Count; i++) { for (int j = 1; j < campPart.Count; j++) { if (campPart.GetMember(j - 1).birth > campPart.GetMember(j).birth) { DateTime a = campPart.GetMember(j - 1).birth; campPart.GetMember(j - 1).birth = campPart.GetMember(j).birth; campPart.GetMember(j).birth = a; } } } return campPart; } /// <summary> /// spausdina stovyklos dalyvius /// </summary> /// <param name="branches">masyvas saugantis zaideju ir personalo konteinerius</param> static void printCampPart(Branch[] branches) { MemberContainer Campers = new MemberContainer(maxPlayers); for (int i = 0; i < NmbOfBranches; i++) { Console.WriteLine("{0} stovyklos sarasas:", (i + 1)); Campers = makeCmapPart(branches[i]); for (int j = 0; j < Campers.Count; j++) { Console.WriteLine("{0, -10}|{1, -10}|{2}", Campers.GetMember(j).name, Campers.GetMember(j).surname, Campers.GetMember(j).birth); } } } } }
40.745981
123
0.488242
[ "MIT" ]
sandybridge9/KTU-darbai-ir-ataskaitos
KTU/Objektinis Programavimas 1/DeivioDarbai/DVD3/DVD3/Program.cs
12,675
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // <auto-generated/> #nullable disable using System.Collections.Generic; using System.Text.Json; using Azure.Core; namespace Azure.Analytics.Synapse.Artifacts.Models { public partial class CustomActivity : IUtf8JsonSerializable { void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) { writer.WriteStartObject(); if (Optional.IsDefined(LinkedServiceName)) { writer.WritePropertyName("linkedServiceName"); writer.WriteObjectValue(LinkedServiceName); } if (Optional.IsDefined(Policy)) { writer.WritePropertyName("policy"); writer.WriteObjectValue(Policy); } writer.WritePropertyName("name"); writer.WriteStringValue(Name); writer.WritePropertyName("type"); writer.WriteStringValue(Type); if (Optional.IsDefined(Description)) { writer.WritePropertyName("description"); writer.WriteStringValue(Description); } if (Optional.IsCollectionDefined(DependsOn)) { writer.WritePropertyName("dependsOn"); writer.WriteStartArray(); foreach (var item in DependsOn) { writer.WriteObjectValue(item); } writer.WriteEndArray(); } if (Optional.IsCollectionDefined(UserProperties)) { writer.WritePropertyName("userProperties"); writer.WriteStartArray(); foreach (var item in UserProperties) { writer.WriteObjectValue(item); } writer.WriteEndArray(); } writer.WritePropertyName("typeProperties"); writer.WriteStartObject(); writer.WritePropertyName("command"); writer.WriteObjectValue(Command); if (Optional.IsDefined(ResourceLinkedService)) { writer.WritePropertyName("resourceLinkedService"); writer.WriteObjectValue(ResourceLinkedService); } if (Optional.IsDefined(FolderPath)) { writer.WritePropertyName("folderPath"); writer.WriteObjectValue(FolderPath); } if (Optional.IsDefined(ReferenceObjects)) { writer.WritePropertyName("referenceObjects"); writer.WriteObjectValue(ReferenceObjects); } if (Optional.IsCollectionDefined(ExtendedProperties)) { writer.WritePropertyName("extendedProperties"); writer.WriteStartObject(); foreach (var item in ExtendedProperties) { writer.WritePropertyName(item.Key); writer.WriteObjectValue(item.Value); } writer.WriteEndObject(); } if (Optional.IsDefined(RetentionTimeInDays)) { writer.WritePropertyName("retentionTimeInDays"); writer.WriteObjectValue(RetentionTimeInDays); } writer.WriteEndObject(); foreach (var item in AdditionalProperties) { writer.WritePropertyName(item.Key); writer.WriteObjectValue(item.Value); } writer.WriteEndObject(); } internal static CustomActivity DeserializeCustomActivity(JsonElement element) { Optional<LinkedServiceReference> linkedServiceName = default; Optional<ActivityPolicy> policy = default; string name = default; string type = default; Optional<string> description = default; Optional<IList<ActivityDependency>> dependsOn = default; Optional<IList<UserProperty>> userProperties = default; object command = default; Optional<LinkedServiceReference> resourceLinkedService = default; Optional<object> folderPath = default; Optional<CustomActivityReferenceObject> referenceObjects = default; Optional<IDictionary<string, object>> extendedProperties = default; Optional<object> retentionTimeInDays = default; IDictionary<string, object> additionalProperties = default; Dictionary<string, object> additionalPropertiesDictionary = new Dictionary<string, object>(); foreach (var property in element.EnumerateObject()) { if (property.NameEquals("linkedServiceName")) { linkedServiceName = LinkedServiceReference.DeserializeLinkedServiceReference(property.Value); continue; } if (property.NameEquals("policy")) { policy = ActivityPolicy.DeserializeActivityPolicy(property.Value); continue; } if (property.NameEquals("name")) { name = property.Value.GetString(); continue; } if (property.NameEquals("type")) { type = property.Value.GetString(); continue; } if (property.NameEquals("description")) { description = property.Value.GetString(); continue; } if (property.NameEquals("dependsOn")) { List<ActivityDependency> array = new List<ActivityDependency>(); foreach (var item in property.Value.EnumerateArray()) { array.Add(ActivityDependency.DeserializeActivityDependency(item)); } dependsOn = array; continue; } if (property.NameEquals("userProperties")) { List<UserProperty> array = new List<UserProperty>(); foreach (var item in property.Value.EnumerateArray()) { array.Add(UserProperty.DeserializeUserProperty(item)); } userProperties = array; continue; } if (property.NameEquals("typeProperties")) { foreach (var property0 in property.Value.EnumerateObject()) { if (property0.NameEquals("command")) { command = property0.Value.GetObject(); continue; } if (property0.NameEquals("resourceLinkedService")) { resourceLinkedService = LinkedServiceReference.DeserializeLinkedServiceReference(property0.Value); continue; } if (property0.NameEquals("folderPath")) { folderPath = property0.Value.GetObject(); continue; } if (property0.NameEquals("referenceObjects")) { referenceObjects = CustomActivityReferenceObject.DeserializeCustomActivityReferenceObject(property0.Value); continue; } if (property0.NameEquals("extendedProperties")) { Dictionary<string, object> dictionary = new Dictionary<string, object>(); foreach (var property1 in property0.Value.EnumerateObject()) { dictionary.Add(property1.Name, property1.Value.GetObject()); } extendedProperties = dictionary; continue; } if (property0.NameEquals("retentionTimeInDays")) { retentionTimeInDays = property0.Value.GetObject(); continue; } } continue; } additionalPropertiesDictionary.Add(property.Name, property.Value.GetObject()); } additionalProperties = additionalPropertiesDictionary; return new CustomActivity(name, type, description.Value, Optional.ToList(dependsOn), Optional.ToList(userProperties), additionalProperties, linkedServiceName.Value, policy.Value, command, resourceLinkedService.Value, folderPath.Value, referenceObjects.Value, Optional.ToDictionary(extendedProperties), retentionTimeInDays.Value); } } }
43.102326
341
0.517535
[ "MIT" ]
AbelHu/azure-sdk-for-net
sdk/synapse/Azure.Analytics.Synapse.Artifacts/src/Generated/Models/CustomActivity.Serialization.cs
9,267
C#
using Newtonsoft.Json; namespace OpenBots.Agent.Core.Model { public class NugetPackageSource { [JsonProperty("Enabled")] public bool? Enabled { get; set; } [JsonProperty("Package Name")] public string PackageName { get; set; } [JsonProperty("Package Source")] public string PackageSource { get; set; } } }
21.764706
49
0.618919
[ "Apache-2.0" ]
OpenBotsAI/OpenBots.Agent
OpenBots.Agent.Core/Model/NugetPackageSource.cs
372
C#
using Azure.Mobile.Server.Extensions; using Azure.Mobile.Server.Utils; using Microsoft.AspNet.OData; using Microsoft.AspNet.OData.Builder; using Microsoft.AspNet.OData.Query; using Microsoft.AspNet.OData.Routing; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http.Extensions; using Microsoft.AspNetCore.Mvc; using Microsoft.OData.Edm; using System; using System.Data; using System.Globalization; using System.Linq; using System.Threading.Tasks; namespace Azure.Mobile.Server { /// <summary> /// Provides a common <see cref="Controller"/> abstraction for the REST API controllers /// that implement table access. /// </summary> /// <typeparam name="TEntity">The model type for the served entities.</typeparam> public class TableController<TEntity> : ControllerBase where TEntity : class, ITableData { /// <summary> /// The table repository that handles storage of entities in this table controller /// </summary> private ITableRepository<TEntity> tableRepository = null; /// <summary> /// The EdmModel for the entity, used in OData processing. /// </summary> private IEdmModel EdmModel { get; set; } /// <summary> /// Initialze a new instance of the <see cref="TableController{TEntity}"/> class. /// </summary> protected TableController() { var modelBuilder = new ODataConventionModelBuilder(); modelBuilder.AddEntityType(typeof(TEntity)); EdmModel = modelBuilder.GetEdmModel(); } /// <summary> /// Initializes a new instance of the <see cref="TableController{TEntity}"/> class with /// a given <paramref name="tableRepository"/>. /// </summary> /// <param name="tableRepository">The <see cref="ITableRepository{TEntity}"/> for the backend store.</param> protected TableController(ITableRepository<TEntity> tableRepository): this() { if (tableRepository == null) { throw new ArgumentNullException(nameof(tableRepository)); } this.tableRepository = tableRepository; } /// <summary> /// The <see cref="ITableRepository{TEntity}"/> to be used for accessing the backend store. /// </summary> public ITableRepository<TEntity> TableRepository { get { if (tableRepository == null) { throw new InvalidOperationException("TableRepository must be set before use."); } return tableRepository; } set { if (value == null) { throw new ArgumentNullException(nameof(value)); } if (tableRepository != null) { throw new InvalidOperationException("TableRepository cannot be set twice."); } tableRepository = value; } } /// <summary> /// Returns true if the user is authorized to perform the operation on the specified entity. /// </summary> /// <param name="operation">The <see cref="TableOperation"/> that is being performed</param> /// <param name="item">The item that is being accessed (or null for a list operation).</param> /// <returns>true if the user is allowed to perform the operation.</returns> public virtual bool IsAuthorized(TableOperation operation, TEntity item) => true; /// <summary> /// Prepares the item for storing into the backend store. This is a opportunity for the application /// to add additional meta-data that is not passed back to the client (such as the user ID in a /// personal data store). /// </summary> /// <param name="item">The item to be prepared</param> /// <returns>The prepared item</returns> public virtual TEntity PrepareItemForStore(TEntity item) => item; /// <summary> /// The <see cref="TableControllerOptions{T}"/> for this controller. This is used to specify /// the data view, soft-delete, and list limits. /// </summary> public TableControllerOptions<TEntity> TableControllerOptions { get; set; } = new TableControllerOptions<TEntity>(); /// <summary> /// List operation: GET {path}?{odata-filters} /// /// Additional Query Parameters: /// __includedeleted = true Include deleted records in a soft-delete situation. /// </summary> /// <returns>200 OK with the results of the list (paged)</returns> [HttpGet] [ProducesResponseType(StatusCodes.Status200OK)] [ProducesResponseType(StatusCodes.Status404NotFound)] public virtual IActionResult GetItems() { if (!IsAuthorized(TableOperation.List, null)) { return NotFound(); } var dataView = TableRepository.AsQueryable() .ApplyDeletedFilter(TableControllerOptions, Request) .Where(TableControllerOptions.DataView); // Construct the OData context and parse the query var queryContext = new ODataQueryContext(EdmModel, typeof(TEntity), new ODataPath()); var odataOptions = new ODataQueryOptions<TEntity>(queryContext, Request); odataOptions.Validate(new ODataValidationSettings { MaxTop = TableControllerOptions.MaxTop }); var odataSettings = new ODataQuerySettings { PageSize = TableControllerOptions.PageSize }; var odataQuery = odataOptions.ApplyTo(dataView.AsQueryable(), odataSettings); return Ok(odataQuery); } /// <summary> /// Create operation: POST {path} /// </summary> /// <param name="item">The item submitted for creation</param> /// <returns>201 response with the item that was added (if successful)</returns> [HttpPost] [ProducesResponseType(StatusCodes.Status201Created)] [ProducesResponseType(StatusCodes.Status401Unauthorized)] [ProducesResponseType(StatusCodes.Status409Conflict)] [ProducesResponseType(StatusCodes.Status412PreconditionFailed)] public virtual async Task<IActionResult> CreateItemAsync([FromBody] TEntity item) { if (item.Id == null) { item.Id = Guid.NewGuid().ToString("N"); } if (!IsAuthorized(TableOperation.Create, item)) { return Unauthorized(); } var entity = await TableRepository.LookupAsync(item.Id).ConfigureAwait(false); var preconditionStatusCode = ETag.EvaluatePreconditions(entity, Request.GetTypedHeaders()); if (preconditionStatusCode != StatusCodes.Status200OK) { return StatusCode(preconditionStatusCode, entity); } if (entity != null) { AddHeadersToResponse(entity); return Conflict(entity); } var createdEntity = await TableRepository.CreateAsync(PrepareItemForStore(item)).ConfigureAwait(false); AddHeadersToResponse(createdEntity); var uri = $"{Request.GetEncodedUrl()}/{createdEntity.Id}"; return Created(uri, createdEntity); } /// <summary> /// Delete operation: DELETE {path}/{id} /// </summary> /// <param name="id">The ID of the entity to be deleted</param> /// <returns>204 No Content response</returns> [HttpDelete("{id}")] [ProducesResponseType(StatusCodes.Status200OK)] [ProducesResponseType(StatusCodes.Status404NotFound)] [ProducesResponseType(StatusCodes.Status412PreconditionFailed)] public virtual async Task<IActionResult> DeleteItemAsync(string id) { var entity = await TableRepository.LookupAsync(id).ConfigureAwait(false); if (entity == null || entity.Deleted || !IsAuthorized(TableOperation.Delete, entity)) { return NotFound(); } var preconditionStatusCode = ETag.EvaluatePreconditions(entity, Request.GetTypedHeaders()); if (preconditionStatusCode != StatusCodes.Status200OK) { return StatusCode(preconditionStatusCode, entity); } if (TableControllerOptions.SoftDeleteEnabled) { entity.Deleted = true; await TableRepository.ReplaceAsync(PrepareItemForStore(entity)).ConfigureAwait(false); } else { await TableRepository.DeleteAsync(entity.Id).ConfigureAwait(false); } return NoContent(); } /// <summary> /// Read operation: GET {path}/{id} /// </summary> /// <param name="id">The ID of the entity to be deleted</param> /// <returns>200 OK with the entity in the body</returns> [HttpGet("{id}")] [ProducesResponseType(StatusCodes.Status200OK)] [ProducesResponseType(StatusCodes.Status304NotModified)] [ProducesResponseType(StatusCodes.Status404NotFound)] [ProducesResponseType(StatusCodes.Status412PreconditionFailed)] public virtual async Task<IActionResult> ReadItemAsync(string id) { var entity = await TableRepository.LookupAsync(id).ConfigureAwait(false); if (entity == null || entity.Deleted || !IsAuthorized(TableOperation.Read, entity)) { return NotFound(); } var preconditionStatusCode = ETag.EvaluatePreconditions(entity, Request.GetTypedHeaders(), true); if (preconditionStatusCode != StatusCodes.Status200OK) { if (preconditionStatusCode == StatusCodes.Status304NotModified) { AddHeadersToResponse(entity); } return StatusCode(preconditionStatusCode, entity); } AddHeadersToResponse(entity); return Ok(entity); } /// <summary> /// Replaces the item in the dataset. The ID within the item must match the id provided on the path. /// </summary> /// <param name="id">The ID of the entity to replace</param> /// <param name="item">The new entity contents</param> /// <returns>200 OK with the new entity within the body</returns> [HttpPut("{id}")] [ProducesResponseType(StatusCodes.Status200OK)] [ProducesResponseType(StatusCodes.Status400BadRequest)] [ProducesResponseType(StatusCodes.Status404NotFound)] [ProducesResponseType(StatusCodes.Status412PreconditionFailed)] public virtual async Task<IActionResult> ReplaceItemAsync(string id, [FromBody] TEntity item) { if (item.Id != id) { return BadRequest(); } var entity = await TableRepository.LookupAsync(id).ConfigureAwait(false); if (entity == null || entity.Deleted || !IsAuthorized(TableOperation.Replace, entity)) { return NotFound(); } var preconditionStatusCode = ETag.EvaluatePreconditions(entity, Request.GetTypedHeaders()); if (preconditionStatusCode != StatusCodes.Status200OK) { AddHeadersToResponse(entity); return StatusCode(preconditionStatusCode, entity); } var replacement = await TableRepository.ReplaceAsync(PrepareItemForStore(item)).ConfigureAwait(false); AddHeadersToResponse(replacement); return Ok(replacement); } #if SUPPORTS_PATCH /// <summary> /// Patch operation: PATCH {path}/{id} /// /// Note that unlike most of the other operations, this one works all the time on soft-deleted records, as long /// as you are undeleting the record.. /// </summary> /// <remarks> /// Disabling JSON Patch Support until Microsoft.AspNetCore.JsonPatch support System.Text.Json /// </remarks> /// <param name="id">The ID of the entity to be patched</param> /// <param name="patchDocument">A patch operation document (see RFC 6901, RFC 6902)</param> /// <returns>200 OK with the new entity in the body</returns> [HttpPatch("{id}")] [ProducesResponseType(StatusCodes.Status200OK)] [ProducesResponseType(StatusCodes.Status400BadRequest)] [ProducesResponseType(StatusCodes.Status404NotFound)] [ProducesResponseType(StatusCodes.Status412PreconditionFailed)] public virtual async Task<IActionResult> PatchItemAsync(string id, [FromBody] JsonPatchDocument<TEntity> patchDocument) { var entity = await TableRepository.LookupAsync(id).ConfigureAwait(false); if (entity == null || !IsAuthorized(TableOperation.Patch, entity)) { return NotFound(); } var entityIsDeleted = (TableControllerOptions.SoftDeleteEnabled && entity.Deleted); var preconditionStatusCode = ETag.EvaluatePreconditions(entity, Request.GetTypedHeaders()); if (preconditionStatusCode != StatusCodes.Status200OK) { AddHeadersToResponse(entity); return StatusCode(preconditionStatusCode, entity); } patchDocument.ApplyTo(entity); if (entity.Id != id) { return BadRequest(); } // Special Case: // If SoftDelete is enabled, and the original record is DELETED, then you can // continue as long as one of the operations is an undelete operation. if (entityIsDeleted && entity.Deleted) { return NotFound(); } var replacement = await TableRepository.ReplaceAsync(PrepareItemForStore(entity)).ConfigureAwait(false); AddHeadersToResponse(replacement); return Ok(replacement); } #endif /// <summary> /// Adds any necessary response headers, such as ETag and Last-Modified /// </summary> /// <param name="item">The item being returned</param> private void AddHeadersToResponse(TEntity item) { if (item != null) { Response.Headers["ETag"] = ETag.FromByteArray(item.Version); Response.Headers["Last-Modified"] = item.UpdatedAt.ToString(DateTimeFormatInfo.InvariantInfo.RFC1123Pattern); } } } }
41.815126
127
0.605105
[ "MIT" ]
BenBtg/azure-mobile-apps
dotnet/server/src/Azure.Mobile.Server/TableController.cs
14,930
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.InteropServices.WindowsRuntime; using Windows.Foundation; using Windows.Foundation.Collections; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Controls.Primitives; using Windows.UI.Xaml.Data; using Windows.UI.Xaml.Input; using Windows.UI.Xaml.Media; using Windows.UI.Xaml.Navigation; // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409 namespace NavigationView { /// <summary> /// An empty page that can be used on its own or navigated to within a Frame. /// </summary> public sealed partial class MainPage : Page { public MainPage() { this.InitializeComponent(); HomeFrame.Navigate(typeof(Page1)); } private void HomeButton_Click(object sender, RoutedEventArgs e) { HomeFrame.Navigate(typeof(Page1)); } private void BackButton_Click(object sender, RoutedEventArgs e) { if (HomeFrame.CanGoBack) { HomeFrame.GoBack(); } } private void ForwardButton_Click(object sender, RoutedEventArgs e) { if (HomeFrame.CanGoForward) { HomeFrame.GoForward(); } } private void NavigateButton_Click(object sender, RoutedEventArgs e) { this.Frame.Navigate(typeof(Page2)); } } }
25.112903
106
0.631985
[ "Apache-2.0" ]
Tanamo-Inc/UWP
NavigationView/MainPage.xaml.cs
1,559
C#
using System; using System.CodeDom; namespace ClientGenerator { internal interface ICodeNamespaceGenerator { /// <summary> /// Creates a <see cref="CodeNamespaceCollection"/> containing the <paramref name="types"/> /// </summary> /// <param name="types"> /// Types used to create the <see cref="CodeNamespaceCollection"/> /// </param> /// <returns> /// A <see cref="CodeNamespaceCollection"/> containing the <paramref name="types"/> /// </returns> CodeNamespaceCollection GenerateNamespaceCollection(Type[] types); } internal interface ICodeTypeDeclarationGenerator { CodeTypeDeclaration GenerateTypeDeclaration(Type type); } }
30.875
99
0.639676
[ "MIT" ]
spelltwister/ClientGenerator
ClientGenerator/ICodeNamespaceGenerator.cs
741
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. namespace Microsoft.AspNetCore.Mvc.Analyzers { [ApiConventionType(typeof(object))] [ApiController] [ApiConventionType(typeof(string))] public class GetAttributes_BaseTypeWithAttributesBase { } [ApiConventionType(typeof(int))] public class GetAttributes_BaseTypeWithAttributesDerived : GetAttributes_BaseTypeWithAttributesBase { } }
28.444444
103
0.755859
[ "MIT" ]
48355746/AspNetCore
src/Mvc/Mvc.Analyzers/test/TestFiles/CodeAnalysisExtensionsTest/GetAttributes_BaseTypeWithAttributes.cs
514
C#
using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Linq; using System.Text; using Yuebon.Commons.Cache; using Yuebon.Commons.Json; using Yuebon.Commons.Mapping; using Yuebon.Commons.Tree; using Yuebon.Security.Dtos; using Yuebon.Security.IRepositories; using Yuebon.Security.Models; using Yuebon.Security.Repositories; namespace Yuebon.Security.Application { /// <summary> /// 地区 /// </summary> public class AreaApp { private IAreaRepository service = new AreaRepository(); #region 适配于管理后端 /// <summary> /// 树形展开treeview需要,数据字典管理页面 /// </summary> /// <returns></returns> public List<TreeViewModel> ItemsTreeViewJson() { List<TreeViewModel> list = new List<TreeViewModel>(); List<Area> listFunction = service.GetListWhere("Layers in (0,1,2)").OrderBy(t => t.SortCode).ToList(); list = TreeViewJson(listFunction, ""); return list; } //public List<TreeViewModel> AreaTreeViewJson() //{ //string where = "1=1 and Layers in(0,1,2)"; //bool order = orderByDir == "asc" ? false : true; //if (!string.IsNullOrEmpty(keywords)) //{ // where += string.Format(" and (FullName like '%{0}%' or EnCode like '%{0}%')", keywords); //} //List<AreaOutputDto> list = iService.GetListWhere(where).OrderBy(t => t.SortCode).ToList().MapTo<AreaOutputDto>(); //return ToJsonContent(list); //List<TreeViewModel> list = new List<TreeViewModel>(); //List<Area> listFunction = service.GetListWhere("Layers in (3,4)").OrderBy(t => t.SortCode).ToList(); //list = TreeViewJson(listFunction, ""); //return list; //} /// <summary> /// /// </summary> /// <param name="data"></param> /// <param name="parentId"></param> /// <returns></returns> public List<TreeViewModel> TreeViewJson(List<Area> data, string parentId) { List<TreeViewModel> list = new List<TreeViewModel>(); var ChildNodeList = data.FindAll(t => t.ParentId == parentId).ToList(); foreach (Area entity in ChildNodeList) { TreeViewModel treeViewModel = new TreeViewModel(); treeViewModel.nodeId = entity.Id; treeViewModel.pid = entity.ParentId; treeViewModel.text = entity.FullName; treeViewModel.nodes = ChildrenTreeViewList(data, entity.Id); treeViewModel.tags = entity.Id; list.Add(treeViewModel); } return list; } /// <summary> /// /// </summary> /// <param name="data"></param> /// <param name="parentId"></param> /// <returns></returns> public List<TreeViewModel> ChildrenTreeViewList(List<Area> data, string parentId) { List<TreeViewModel> listChildren = new List<TreeViewModel>(); var ChildNodeList = data.FindAll(t => t.ParentId == parentId).ToList(); foreach (Area entity in ChildNodeList) { TreeViewModel treeViewModel = new TreeViewModel(); treeViewModel.nodeId = entity.Id; treeViewModel.pid = entity.ParentId; treeViewModel.text = entity.FullName; treeViewModel.nodes = ChildrenTreeViewList(data, entity.Id); treeViewModel.tags = entity.Id; listChildren.Add(treeViewModel); } return listChildren; } #endregion #region 用于uniapp下拉选项 /// <summary> /// 获取所有可用的地区,用于uniapp下拉选项 /// </summary> /// <returns></returns> public List<AreaPickerOutputDto> GetAllByEnable() { List<AreaPickerOutputDto> list = new List<AreaPickerOutputDto>(); YuebonCacheHelper yuebonCacheHelper = new YuebonCacheHelper(); list=JsonConvert.DeserializeObject<List<AreaPickerOutputDto>>(yuebonCacheHelper.Get("Area_Enable_Uniapp").ToJson()); if (list == null||list.Count<=0) { List<Area> listFunction = service.GetAllByIsNotDeleteAndEnabledMark("Layers in (0,1,2)").OrderBy(t => t.SortCode).ToList(); list = UniappViewJson(listFunction, ""); yuebonCacheHelper.Add("Area_Enable_Uniapp", list); } return list; } /// <summary> /// 获取省、市、县/区三级可用的地区,用于uniapp下拉选项 /// </summary> /// <returns></returns> public List<AreaPickerOutputDto> GetProvinceToAreaByEnable() { List<AreaPickerOutputDto> list = new List<AreaPickerOutputDto>(); YuebonCacheHelper yuebonCacheHelper = new YuebonCacheHelper(); list = JsonConvert.DeserializeObject<List<AreaPickerOutputDto>>(yuebonCacheHelper.Get("Area_ProvinceToArea_Enable_Uniapp").ToJson()); if (list == null || list.Count <= 0) { List<Area> listFunctionTemp = service.GetAllByIsNotDeleteAndEnabledMark("Layers in (1,2,3)").OrderBy(t => t.Id).ToList(); List<Area> listFunction = new List<Area>(); foreach (Area item in listFunctionTemp) { if (item.Layers == 1) { item.ParentId = ""; } listFunction.Add(item); } list = UniappViewJson(listFunction, ""); yuebonCacheHelper.Add("Area_ProvinceToArea_Enable_Uniapp", list); } return list; } /// <summary> /// /// </summary> /// <param name="data"></param> /// <param name="parentId"></param> /// <returns></returns> public List<AreaPickerOutputDto> UniappViewJson(List<Area> data, string parentId) { List<AreaPickerOutputDto> list = new List<AreaPickerOutputDto>(); var ChildNodeList = data.FindAll(t => t.ParentId == parentId).ToList(); foreach (Area entity in ChildNodeList) { AreaPickerOutputDto treeViewModel = new AreaPickerOutputDto(); treeViewModel.value = entity.Id; treeViewModel.label = entity.FullName; treeViewModel.children = ChildrenUniappViewList(data, entity.Id); list.Add(treeViewModel); } return list; } /// <summary> /// /// </summary> /// <param name="data"></param> /// <param name="parentId"></param> /// <returns></returns> public List<AreaPickerOutputDto> ChildrenUniappViewList(List<Area> data, string parentId) { List<AreaPickerOutputDto> listChildren = new List<AreaPickerOutputDto>(); var ChildNodeList = data.FindAll(t => t.ParentId == parentId).ToList(); foreach (Area entity in ChildNodeList) { AreaPickerOutputDto treeViewModel = new AreaPickerOutputDto(); treeViewModel.value = entity.Id; treeViewModel.label = entity.FullName; treeViewModel.children = ChildrenUniappViewList(data, entity.Id); listChildren.Add(treeViewModel); } return listChildren; } #endregion #region 适用于select2省市县区级联选择 /// <summary> /// 获取省可用的地区,用于select2下拉选项 /// </summary> /// <returns></returns> public List<AreaSelect2OutDto> GetProvinceAll() { List<AreaSelect2OutDto> list = new List<AreaSelect2OutDto>(); YuebonCacheHelper yuebonCacheHelper = new YuebonCacheHelper(); list = JsonConvert.DeserializeObject<List<AreaSelect2OutDto>>(yuebonCacheHelper.Get("Area_ProvinceToArea_Select2").ToJson()); if (list == null || list.Count <= 0) { list = service.GetAllByIsNotDeleteAndEnabledMark("Layers =1").OrderBy(t => t.Id).ToList().MapTo<AreaSelect2OutDto>(); yuebonCacheHelper.Add("Area_ProvinceToArea_Select2", list); } return list; } /// <summary> /// 获取城市,用于select2下拉选项 /// </summary> /// <param name="id">省份Id</param> /// <returns></returns> public List<AreaSelect2OutDto> GetCityByProvinceId(string id) { List<AreaSelect2OutDto> list = new List<AreaSelect2OutDto>(); YuebonCacheHelper yuebonCacheHelper = new YuebonCacheHelper(); list = JsonConvert.DeserializeObject<List<AreaSelect2OutDto>>(yuebonCacheHelper.Get("Area_CityToArea_Enable_Select2"+id).ToJson()); if (list == null || list.Count <= 0) { string sqlWhere = string.Format("ParentId='{0}'", id); list = service.GetAllByIsNotDeleteAndEnabledMark(sqlWhere).OrderBy(t => t.Id).ToList().MapTo<AreaSelect2OutDto>(); yuebonCacheHelper.Add("Area_CityToArea_Enable_Select2"+id, list); } return list; } /// <summary> /// 获取县区,用于select2下拉选项 /// </summary> /// <param name="id">城市Id</param> /// <returns></returns> public List<AreaSelect2OutDto> GetDistrictByCityId(string id) { List<AreaSelect2OutDto> list = new List<AreaSelect2OutDto>(); YuebonCacheHelper yuebonCacheHelper = new YuebonCacheHelper(); list = JsonConvert.DeserializeObject<List<AreaSelect2OutDto>>(yuebonCacheHelper.Get("Area_DistrictToArea_Enable_Select2"+id).ToJson()); if (list == null || list.Count <= 0) { string sqlWhere = string.Format("ParentId='{0}'", id); list = service.GetAllByIsNotDeleteAndEnabledMark(sqlWhere).OrderBy(t => t.Id).ToList().MapTo<AreaSelect2OutDto>(); yuebonCacheHelper.Add("Area_DistrictToArea_Enable_Select2"+id, list); } return list; } #endregion } }
41.673469
147
0.574143
[ "MIT" ]
JonasChan2020/DataProcess
Yuebon.NetCore/Yuebon.Security.Core/Application/AreaApp.cs
10,450
C#
// ------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. // ------------------------------------------------------------ namespace Microsoft.Azure.Cosmos.Serialization.HybridRowGenerator { using System; using System.Collections.Generic; using System.Linq; using Microsoft.Azure.Cosmos.Core; using Microsoft.Azure.Cosmos.Serialization.HybridRow; using Microsoft.Azure.Cosmos.Serialization.HybridRow.Schemas; public class SchemaGenerator { private readonly RandomGenerator rand; private readonly HybridRowGeneratorConfig config; private readonly HybridRowValueGenerator generator; public SchemaGenerator(RandomGenerator rand, HybridRowGeneratorConfig config, HybridRowValueGenerator generator) { this.rand = rand; this.config = config; this.generator = generator; } public Namespace InitializeRandomNamespace() { Namespace ns = new Namespace() { Name = this.generator.GenerateIdentifier(), }; return ns; } public Schema InitializeRandomSchema(Namespace ns, int depth) { string name = HybridRowValueGenerator.GenerateExclusive( this.generator.GenerateIdentifier, from s1 in ns.Schemas select s1.Name, this.config.ConflictRetryAttempts); SchemaId sid = HybridRowValueGenerator.GenerateExclusive( this.generator.GenerateSchemaId, from s1 in ns.Schemas select s1.SchemaId, this.config.ConflictRetryAttempts); // Allocate and insert the schema *before* recursing to allocate properties. This ensures that nested structure // doesn't conflict with name or id constraints. Schema s = new Schema() { Name = name, SchemaId = sid, Type = TypeKind.Schema, Comment = this.generator.GenerateComment(), Options = this.InitializeRandomSchemaOptions(), }; ns.Schemas.Add(s); // Recurse and allocate its properties. s.Properties = this.InitializeRandomProperties(ns, TypeKind.Schema, depth); return s; } private List<Property> InitializeRandomProperties(Namespace ns, TypeKind scope, int depth) { int length = this.config.NumTableProperties.Next(this.rand); // Introduce some decay rate for the number of properties in nested contexts // to limit the depth of schemas. if (depth > 0) { double scaled = Math.Floor(length * Math.Exp(depth * this.config.DepthDecayFactor)); Contract.Assert(scaled <= length); length = (int)scaled; } List<Property> properties = new List<Property>(length); for (int i = 0; i < length; i++) { PropertyType propType = this.InitializeRandomPropertyType(ns, scope, depth); string path = HybridRowValueGenerator.GenerateExclusive( this.generator.GenerateIdentifier, from s1 in properties select s1.Path, this.config.ConflictRetryAttempts); Property prop = new Property() { Comment = this.generator.GenerateComment(), Path = path, PropertyType = propType, }; properties.Add(prop); } return properties; } private PropertyType InitializeRandomPropertyType(Namespace ns, TypeKind scope, int depth) { TypeKind type = this.generator.GenerateTypeKind(); PropertyType propType; switch (type) { case TypeKind.Object: propType = new ObjectPropertyType() { Immutable = this.generator.GenerateBool(), // TODO: add properties to object scopes. // Properties = this.InitializeRandomProperties(ns, type, depth + 1), }; break; case TypeKind.Array: propType = new ArrayPropertyType() { Immutable = this.generator.GenerateBool(), Items = this.InitializeRandomPropertyType(ns, type, depth + 1), }; break; case TypeKind.Set: propType = new SetPropertyType() { Immutable = this.generator.GenerateBool(), Items = this.InitializeRandomPropertyType(ns, type, depth + 1), }; break; case TypeKind.Map: propType = new MapPropertyType() { Immutable = this.generator.GenerateBool(), Keys = this.InitializeRandomPropertyType(ns, type, depth + 1), Values = this.InitializeRandomPropertyType(ns, type, depth + 1), }; break; case TypeKind.Tuple: int numItems = this.config.NumTupleItems.Next(this.rand); List<PropertyType> itemTypes = new List<PropertyType>(numItems); for (int i = 0; i < numItems; i++) { itemTypes.Add(this.InitializeRandomPropertyType(ns, type, depth + 1)); } propType = new TuplePropertyType() { Immutable = this.generator.GenerateBool(), Items = itemTypes, }; break; case TypeKind.Tagged: int numTagged = this.config.NumTaggedItems.Next(this.rand); List<PropertyType> taggedItemTypes = new List<PropertyType>(numTagged); for (int i = 0; i < numTagged; i++) { taggedItemTypes.Add(this.InitializeRandomPropertyType(ns, type, depth + 1)); } propType = new TaggedPropertyType() { Immutable = this.generator.GenerateBool(), Items = taggedItemTypes, }; break; case TypeKind.Schema: Schema udt = this.InitializeRandomSchema(ns, depth + 1); propType = new UdtPropertyType() { Immutable = this.generator.GenerateBool(), Name = udt.Name, }; break; default: StorageKind storage = (scope == TypeKind.Schema) ? this.generator.GenerateStorageKind() : StorageKind.Sparse; switch (storage) { case StorageKind.Sparse: // All types are supported in Sparse. break; case StorageKind.Fixed: switch (type) { case TypeKind.Null: case TypeKind.Boolean: case TypeKind.Int8: case TypeKind.Int16: case TypeKind.Int32: case TypeKind.Int64: case TypeKind.UInt8: case TypeKind.UInt16: case TypeKind.UInt32: case TypeKind.UInt64: case TypeKind.Float32: case TypeKind.Float64: case TypeKind.Float128: case TypeKind.Decimal: case TypeKind.DateTime: case TypeKind.UnixDateTime: case TypeKind.Guid: case TypeKind.MongoDbObjectId: case TypeKind.Utf8: case TypeKind.Binary: // Only these types are supported with fixed storage today. break; default: storage = StorageKind.Sparse; break; } break; case StorageKind.Variable: switch (type) { case TypeKind.Binary: case TypeKind.Utf8: case TypeKind.VarInt: case TypeKind.VarUInt: // Only these types are supported with variable storage today. break; default: storage = StorageKind.Sparse; break; } break; } propType = new PrimitivePropertyType() { Length = storage == StorageKind.Sparse ? 0 : this.config.PrimitiveFieldValueLength.Next(this.rand), Storage = storage, }; break; } propType.ApiType = this.generator.GenerateIdentifier(); propType.Type = type; switch (scope) { case TypeKind.Array: case TypeKind.Map: case TypeKind.Set: case TypeKind.Tuple: case TypeKind.Tagged: propType.Nullable = this.generator.GenerateBool(); break; default: propType.Nullable = true; break; } return propType; } private SchemaOptions InitializeRandomSchemaOptions() { SchemaOptions o = new SchemaOptions() { DisallowUnschematized = this.generator.GenerateBool(), }; return o; } } }
39.129496
129
0.45422
[ "MIT" ]
microsoft/HybridRow
src/Serialization/HybridRowGenerator/SchemaGenerator.cs
10,880
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace BAGCST.api.RightsSystem.Exception { public class RightIDNotFoundException: System.Exception { public string RightPath { get; private set; } public RightIDNotFoundException(string rightPath): base () { this.RightPath = rightPath; } } }
24.5
68
0.69898
[ "MIT" ]
KreLou/BAGCST
api/api/RightsSystem/Exceptions/RightIDNotFoundException.cs
394
C#
using MovieMeter.WebHarvester.Contracts; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using MovieMeter.Model; namespace MovieMeter.WebHarvester.Harvester { public class Harvester : IHarvester { private IParser _parser; public Harvester(IParser parser) { _parser = parser; } public async Task<List<IProgramInfo>> Harvest() { var programs = new List<IProgramInfo>(); using (var loader = HarvesterFactory.GetSeleniumLoader()) { var pages = await loader.GetProgramPagesHtml(); foreach (var page in pages) { programs.Add(_parser.Parse(page)); } } return programs; } } }
24.378378
70
0.552106
[ "MIT" ]
brugi82/MovieMeter
MovieMeter/MovieMeter.WebHarvester/Harvester/Harvester.cs
904
C#
using System.Linq; namespace VitDeck.Validator { public static class XketAssetData { public static string[] GUIDs = Vket5OfficialAssetData.GUIDs.Concat(new[] { #region ゲーミング波紋シェーダー "678cdccda61385b4fa012a33b9183b53", "837a3cbdac0378e43a33c8fe66d31250", "0167df56538378a43b4a733f5a152d52", "a02bed6b566d9164b9ed56ddb8889b22", "59b5423c83501554080ddecda0d88400", "f6344b557c865f740ba02e0ee82b60e8", "5f94a00059794d8469e1ec8b94e48a09", "bc6048cc78f66194a8e162f2d79ba974", #endregion #region NamakoXket2Shader.unitypackage "6e06ec2e5359bc044a2187d0071d3dba", "10fec87cd50d79c4c8fcc04d81d74141", "4709c495f53a23d4fae32ab452cda011", "30d609dc4d65be34599e9cb0a9df6dff", "e3c24b0000abac044ae1aab455d7256a", "ef66e9958b88aae4aaeae069759a20a8", "c06303d38bec91b4a9f4577574371eb3", "eceaa9f87b7c73745b543355917bd7ce", "cd3be97009175464e906dbca1a60c7ac", "2bad451a64f7a7f41a4271dbeec9f1fe", "1fe14209bb3638d40a8ea3d902a08387", "a218b31773bba334290791f447e9fbbf", "8affc986b6861b44b89ee55df9ef018e", "4889730dec3cad9428dd5467e31f1adf", "9c03ee8d35db3f2408e6491c64becebf", "0b3dbe8007dd0d749a3e8cf6c66f28bd", "cec8b6ff2c6ebb94b98082fdced52a6e", #endregion #region noribenQuestWaterシェーダー "12d05ea3116dd364cb401c318a753912", "50ce8b1b6d9112243aaf6fb4e39635f5", "a8380f17eb815f740b8f070b0af2edaa", "92e4b24d71db4e946a2fbbf4ab519c4d", "f37658f453acdef42be51fc5a26d9bb2", "e78e27bb74f7ba34cbfc1b6bcc5fb67d", "6ae273697d288074d9257f8a66afd052", "e4e7c92103289a04db55f7cd35ea7f3f", "b05e8486f2188774296b0e7fecc5ca33", "4660d9c95eb9e14448132e3c6060918b", "27798e884c23c71419c98c6c2053ddb8", "4e316c84b6113124585c49b7601495c1", "eacfe4d521dedb943ad40be45ad37414", "8c235d73d794d7240ae0e60873593580", "c8c2befe2310980488c5b12442951599", #endregion #region text-template "02567ef9c767fa941a9cffaabc25c635", "d430eeeaf818b3544ad140d4c03d4e64", "32e1a70dd7f6b3d4dbf59f88f57276f6", "691ad3e9b2fd50243b327ef42e5bbd9b", "52d6b00ad242d41419f549e802f7be60", "36371dcb50975dc49b6244b4e871ce93", "d3bf680baa6baac44b5f8eba8edb49a1", "c88fabbf0a8f42446b22b70f204bf7ec", "26c26099a0765d943863409f4a539669", "0f29c5d8d1d3cf1408f8c287949700bf", "3d804a353ae10334abbd7d946703314a", "28a77ed9794d04d4ca69d1dba6c0f545", "9327bb9376788884f948037daac9cabc", "e55918467baa21041ba5f5d4ce5a5c17", #endregion #region Oculus LipSync "9672c993270b3764a9739e1065b5d67a", "a671bd453c0b47b438476dd2ce40b6cd", "404b6b1044f864c83becc58f44a8dff5", "7b2d242d170b44fc3b3a1b9ba4adc0a7", "3e1d42ccc29c54bf68636db8acf2eed8", "76b873b07f695cb4cb6515ecf670c814", "e21cea670b0f32c428ee862e590a7108", "1ccea2acd443f4ad4bb9a9f33fc960c0", "7152fa4bbe0044f12886bfb6274626bf", "73f38d977e4ed45f48b632a00fb9c579", "a7d01b0eb149d9945a23728e5c7f5fcb", "08b0ff764adc142d79bfae7dd917cc16", "c2d166626e0b34a40b774467cc6c5868", "fe1e90827fcfcac4883e383c51a78ddd", "196133c6d4044404698c27b5d1724e2a", "cbaf1c32e7ec84f10a51be1b09c0ef46", "e59519b819b1843cb94acf4e281e8c45", "466d221c743ab400a8318afe7b830593", "e2d7f58dd4c84431b994602bf58090de", "5df7ce8a60c93cc4e888052b7977b6a9", "dab49ccccea81c4469fd0901d806845b", "fd2bb13164cc64a2087f565d8c66af4f", "e906d4c6bf3304d5dac06eee4fe24c54", "d0455a0ebc21e4c758037cb4b82bebd2", "c11eea25db1a81c429314ae5ac32dc48", "76f25b997543f432bbe00737485b392e", "0ad01ecbcffbb4c91af7ffa1ebc14f74", "3d380053edac948aa9d428fce6a5288b", "a4624e55b9bd82444bf4687fee7e9346", "5c06354455999f94ea26114e261dde6d", "5e6531e8f56b42547b8d2ddf7a7363d1", "ffbd7db31d3ad6e4a97a2f312babdcb6", "29a06a0eefee1b542a7c286f1689ffab", "5563aa34057c347499c480ea33c5d593", "49ba9bfa609aed54ea6d5d1c1390bc15", "ad60c8114191fdf41aa0ea64e132add9", "ba0b9f69af91c5f46b490346e5552136", "9c21cf8c4dffca9418cebd0a578972b4", "5f658e6e48970d340b4491a5fc959251", "660be1fdb8590b14bab012a991bdeb86", "bea5b996ab6235c4aaa1be9b11aea8c4", "f82b1e3c015abaa409d91ab8eb628ac4", "6d47a54f2b89a59459fd7561d360bab2", "46b2920291e9b8c4888ad3fe3f5e5e69", "31e6326c0bd6143479322c5b4a5fe949", "d14bb80824ed25b44a65ddfc7f591e29", "6c05c00fcd925e1469ab8cab6316329f", "b8f002f88e9d7e847b5306f3338f80db", "5290b3a55eaa1b7458665dc2d856c042", "0cd9cc8c2d1778943869a1c67c9da38f", "bbaa933ce12896e4eb67e30b96d795e9", "1be7ff64e219f4e44b17e7a42f13247b", "c1eb8c88592ff744ca29ebf826bb58e1", "57850b02365448041958df056264b3e3", "f3ffa7a9d7a87466691fa59d187d0f5a", "f5b1c127a92bb426f8f5636c5ea8ab34", "7bdb12c9252924dd0bf9d2809e01adaf", "a6504b8c29dd76d4388eef4c5458c108", "79c2e7f7b1a214443ab64ef151d6bd36", "1c5d549bd7e8f2142b88f679c5b3d73e", "cffe8c2b7142fa3438fc1b6ccaeda372", "4b22c2612a8292646806a50f38127837", "e4c63fc874ed2ed42b7808b1a310238a", "4dd277bd9572488489906165e0931952", "0d336f164a5a4454db3960b2f9fc7a85", "8dc55266323c0ad439967b2975af7840", "e63268aff72466742ada144924d3f899", "0a5206cd53b21be4588ef635952929e9", "a59ddab39a70b984f94af4f1ceb261d2", "50cd36abe38c57646bcd09be2353f905", "8a6c32d06b48d244b9c65729404d2afe", "c62f9b5ef85d22f449e72c67c610059d", "a96f219c252e0cc4eb074d5b7bbda9b3", "82aa5cb7a870de440baadff9083be41c", "f43c520a9bad8a3489109c869f454576", "c0d528b758a004fcaac677043e8de6ad", "e073e338e215b4ae9a7fcdf6891e7955", "b0b97b38f2f1fd24185315141a6c6a56", "bc30a49f30010eb42a8b59ec685eac57", "02d5ed157083b494e85013bad8fd5e12", "354250b5dc6a14f49b541724e9dd3c37", "27d84f95a4766db44a26aea09cc67373", "c60ad94815c68aa41a786306cd588495", "7537accd8e2c6024c860b20e3e7e3424", "edde1cb2a78471f409fce5084e6c720c", #endregion #region PhysSound "516e3a4ab7529d24caf2243b8c0c481e", "d27998a9f2d1ea34da750fd71ef1ea1c", "2f72b921183954c41b6ac01ceac16ccc", "f844d0d6aec23a243abd2ac9ee2c77ec", "0b58b277751de7644a9d029eeac88990", "c21e10a0ceb7c9d419a24c5a7a294491", "93939afa1cbabdb498f30fb8b7da4592", "0c31a13c15798d94aac153097f821cd2", "23ae4d21aaedad74d9233241c9411ec6", "71b2d33b531c8fd4ba606bd1b6323a78", "e3fd64d5e2ad635468e8104dd9f7ec2f", "911a10cbaefb55248a823c7461002714", "be01abacc6be0c1428144758e8653c72", "a59d9ac9ac2b53043b7d54871ae2e06f", "6b8a72627fc65c341885a56706edd829", "dc6cf0b37012d484893a37dfc27170e9", "a164cdb3838286449af1a88c75896674", "4312855ac381b914f9558f9b42c69504", "1e71e50ad3547284f9237aa2fc872b9a", "0e0e518e4d00b3448bf0fc5509ab493f", "c995e6614677d594691c76fafdd6ca2a", "927125c4662156b4cbc20609a2346c18", "bdac02d039e6c2f4dae6e3e57d2da17d", "07842165f0453464aab2d1894d79deca", "6782dcc302077e24f814003b9956fd5f", "93ae0b59410fee64abe696fe568cc558", "51b1186b78d34404cb8f8b26c18eb35d", "a7af3440b48952d4c9add9b8bbd05fdf", "dae91f503d4b06f45962baeefd994352", "4ef586fd4e4d3f14a93850ef81ab965d", "94dc3627b2a5424468fd0a29a45eccb3", "7b1edfa54a30cc14c80480c6c21ab6af", "880bbe89bb329404bbfd54395efe5fc9", "dc381ff9aee31ba4485b519cd21cd0bb", "0ae5895f39eaec3489f46b74be48fe8a", "07c9db3aa6451ba448b7e2312a40ec1a", "d1af5ba5cf63ccd4691b9165d0e2743e", "e271dd0dd4db34c4399362eedc9eb814", "f9b58bc297d651843bca2cb720a743ca", "7e06b4ddba04bdd4282fabf3bac913f1", "212908ab48c469246a1fa3c110d3ff0f", "77711f677035ce640998fd0811305b5f", "c728d5ae1fc69a34cacebe7ab17b6d00", "35eaf9bc12ac83d4cbb64e0b7b559154", "43fbea5a4fa39914caf87583c9f0a215", "55e29cfc82dd7fd4eb76c2bd278b4c2a", "4c4aba3def01a094d91403627e8c2590", "52bbe199a4a7c794499dbb74f2d0ea51", "92e1f5d43019ce34fb640a8f8b80675a", "887f648090ad1814ca29c755e388e761", "e9b2ebc743f64f54e88a6d7b0c22735c", "24d70d8d5dd91ce4788dffa0b8d52499", "5c099903d219d5e4894f2fceb00794c7", "a64db8d64c5ee9846b2fec1892b2a82f", "94619f80dd09282429d4923bd1353207", "ea477303edc05924e9ac2b601b8d21ab", "6898ead3978f3f24abde360099bc5ad2", "26310e1685b61dd49949544ac7b81735", "00c6aca58d785ce41b7e5f77205818cd", "8235cc474e2aa644887d4bd26e664729", "bd68277d513e5474b9c8b3422406cec0", "ef3e8320fd4310747a758671194f5681", "9a532385e5f2c8b4fbd8a76c22fa5862", "427ea2c8918d7ef4b94cf59013ae59eb", "a6f70ffd42221a347a842d7fb84d02c1", "694a53fae45622f4c8d2269c4d647399", "037d5049bd713dd448f545820951fe1d", "e5c1f2ea7a813a7408be7faed3e6967e", "edec9285c162b2b42aa839316ac69bfd", "980bc450974b2f747943e6819b67d206", "3b61dca4647f61f4f9051378fa810e5c", "1bb4e41ab7a6e9e449b95085d9c8cbb8", "421ed7e0506406741a0aef0d6e3ef3eb", "2602c211fbeb62d4e9503d67d85bcb39", "dc3b059c7c4ee6f4c9ddc7802e1df77a", "23d13f52b5a01964e82ea27791642175", "37dc13e7cd58a0c42a0ba1ebbc1a5175", "5e00459b4da2cb944bf653bf97849419", "db9b5d1b73592c84483d812421922982", "57d16b0b78483ab41b8e3df634f1e223", "b39000c375328374aac59ca984ec0ada", "8d4b635fea136904f9c0f437997a6928", "3ed8a64dd8cd0024eb58e1dea09ed8df", "491955361a775dd48af1c1cf0f8c593b", "d1a46b85acec488479294b28044c0b36", "ddb9295558debd040818c61f2f32bdc5", "7148ab476afc6254489966e0e8058a40", "153334e5978d5554ba1cb364e1de3e57", "7ab2dae0165ff71449b26623bdb9298e", "38c5d2aa4ec230a48a6528251486010a", "2c99c62bd3cd5874cbb4de411e40b4a8", "78d7742e5be23fe41aa89d5ba4e82589", "4d21af99d5fe64949a113308138b8c45", "f464a4fb36175d849a9a8079f7279ffc", "0b1e4a817bdc70146bb52d4bb337ea8e", "34451acac578b4f48abbf7e03b23278b", "939a77ca1a9770d48adcdedac0a107ea", "91c0dc3ffa247314b8af35444e57e413", "faf106e9a3829d74baf962938d1875f8", "41a3dd51253c37d46ab6ce54bba685f5", "4697a3cc5a2abfd489fe746ed2509cf4", "84968e40525482047959b1fe1d6b8950", #endregion #region Unlit_WF_ShaderSuite_20210101_Core.unitypackage "9bb25feaa2a612d4f8016e2dff545f95", "b8bbbd51c2e41dd4bbcb0da1b7a48808", "4ebc920fe2745624bbed02e79a222e3d", "3a6edc45e5f76964c9679f43d3839c28", "b71e250f3c9f9a54cac228148bc800f7", "6b1a45934e0846141979f322772dc3b8", "052a5a21704733543a9cbbf6369ca43c", "3ca4c3d3a4488214db9818862a2eff69", "4f0275352c196ca4d864b6611897bfd7", "e3269783b9ab81e4f85d813345bc1a7e", "975bd523d795c144fab0af1c55f7b20e", "2a4dc116efeb0db4192f11f17d555b87", "c02ebf9b7a5d66c4ead5f94ef99b20c8", "54ed4f64546b23741987a94ff9769567", "b8e19d3beb8c169458f9b150a00f40ec", "a6e5dce22330ea542a4cfbb7031863da", "c7e5995223250464cac205689e058693", "58bb80b63bec29d4384e105c53ca6970", "2210f95a2274e9d4faf8a14dac933fdb", "c0f75d3ed420fd144a74722588d3bc21", "21f6eaa1dd1f25c4cb29a42c4ff5d98f", "4ba701b07ccc81e4aae7f053bf332eab", "f3f80636c64e389498b3b19e2ee218da", "90cac9ec3b2a7524eb99b36ab87f25f1", "871fd7a51a8ea3e4980c3fe7b8347619", "58ccf9c912b226146a25726b8a1f04db", "af51615040dcdad4cb01c29ea34dbb03", "4bd76f6599a5b8e4d88d81300fb74c37", "d279a88eda1ae0e4c89e92539639eb16", "e0b93fdad2eeedf42baccbc0975cdd1d", "af3422dc9372a89449a9f44d409d9714", "0a7a6cdca16a38548a5d81aca8d4e3ba", "4e4be4aab63a2bd4fbcea2390ae92fdf", "a3678756e883b9349ac22fce33313139", "4eef00f52cc21b04e9e34e4caefa6bbf", "64bf3ca653a7b274fab3e8a87016bfb0", "660abd485057f4740ac9050f7ab3237d", "a5ae7f40ac53e274ea0bc1262e1f6895", "ab4eb87c406a22f46887cf72178e2685", "5523e041d29d259439fa14bd131f5c82", "5498b01615002d948bea7542f55e0c07", "9350854c6e88f3f4eb873d2f94ff3328", "ad88000744b4fb241835ba6ec106caf4", "0733cfc88032e8d4eafce250263c497c", "2cf66b0706c40744baab089297afa895", "747bf283d686334469fb662b2fc4a5c2", "d242cb83664caae4f957030870dd801d", "dd3a683002b3a6f43bdb6c97bd0985c1", "94ee7f8988740fd4887f8b1ce41f0c1c", "3bde56820d1aece41bd22966876a061c", "78d2e3fa0b8eb674aa9cf9e048f79c93", "8c7888a4ac175584f81e0b6e7d4af5a7", "15212414cba0c7a4aac92d94a4ae8750", "d1e7b0a18e221a1409ad59065ec157e4", "2efe527cfcbf0e1408b67463225f552f", "0b53cf0bcd0f9db4fa9d1297d255d06d", "d01a5c313ada49e488b2ef8c6b00f56d", "a220e3e0675cc3f4f817a485688788d6", "2d294f328149d944eb0899b452ff879c", "1435581bcf13e7a47b5bf5636f8d8252", "e7263331a8ee0a04aa4a271fc1fef104", "0299954f2a9b0994f8c9587945948766", "06e9294a93df4474cac2f4157b5e1d1d", "dfb821bc7afadc14591e4338a8ec865f", "0380b1621ab524c43aeb10eba3346ea6", "578346e318940304389ae3dda992ac86", "2762fae01792d2745ad5d02376392d52", "ef1a901a2feeb0a45859ecc184e2e3e2", "b892a7ae3359eb0428b2f8aebf24d314", "45af0d16a1af0a947b445e08dd6dead4", "34a1cdb7cd82cd045a521aa2db90ba27", "77ee5292cc4f46649a13611c8d76c85b", "e33666b113c868d41bfa058f5bc50d9c", "be668f2e5a5e4ef46838001f79babcef", "22546fe6fb0bed84e8db3fc80b0b2302", "93e68367384c3bd42a3a37868cc25554", "8e439fa11883d4b429904a7fc398851e", "afa8b2842288b044b9cdccd7508670a7", "074195645f64a224d9482cb666563c89", "bf91baf439ae72542bd718eb51378f5a", "ad9922cd501663b4cbfbef594d1b22d0", "95ae3c73098e55148862b3125c46785e", "bad784f674c77404f8234c8d284656d2", #endregion }).ToArray(); } }
45.301676
80
0.662967
[ "MIT" ]
cross-market/VitDeck-for-xket
Assets/VitDeck/Validator/Rules/Xket/XketAssetData.cs
16,252
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 System; using System.Collections.Generic; using System.Reflection; using Microsoft.Extensions.Internal; namespace Microsoft.AspNetCore.Mvc.ViewFeatures.Internal { public static class ViewDataAttributePropertyProvider { public static IReadOnlyList<LifecycleProperty> GetViewDataProperties(Type type) { List<LifecycleProperty> results = null; var propertyHelpers = PropertyHelper.GetVisibleProperties(type: type); for (var i = 0; i < propertyHelpers.Length; i++) { var propertyHelper = propertyHelpers[i]; var property = propertyHelper.Property; var tempDataAttribute = property.GetCustomAttribute<ViewDataAttribute>(); if (tempDataAttribute != null) { if (results == null) { results = new List<LifecycleProperty>(); } var key = tempDataAttribute.Key; if (string.IsNullOrEmpty(key)) { key = property.Name; } results.Add(new LifecycleProperty(property, key)); } } return results; } } }
32.8
111
0.563008
[ "Apache-2.0" ]
Kartikexp/MvcDotnet
src/Microsoft.AspNetCore.Mvc.ViewFeatures/Internal/ViewDataAttributePropertyProvider.cs
1,478
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.Datadog.Inputs { public sealed class DashboardWidgetQueryTableDefinitionRequestLogQueryArgs : Pulumi.ResourceArgs { [Input("computeQuery")] public Input<Inputs.DashboardWidgetQueryTableDefinitionRequestLogQueryComputeQueryArgs>? ComputeQuery { get; set; } [Input("groupBies")] private InputList<Inputs.DashboardWidgetQueryTableDefinitionRequestLogQueryGroupByArgs>? _groupBies; public InputList<Inputs.DashboardWidgetQueryTableDefinitionRequestLogQueryGroupByArgs> GroupBies { get => _groupBies ?? (_groupBies = new InputList<Inputs.DashboardWidgetQueryTableDefinitionRequestLogQueryGroupByArgs>()); set => _groupBies = value; } [Input("index", required: true)] public Input<string> Index { get; set; } = null!; [Input("multiComputes")] private InputList<Inputs.DashboardWidgetQueryTableDefinitionRequestLogQueryMultiComputeArgs>? _multiComputes; public InputList<Inputs.DashboardWidgetQueryTableDefinitionRequestLogQueryMultiComputeArgs> MultiComputes { get => _multiComputes ?? (_multiComputes = new InputList<Inputs.DashboardWidgetQueryTableDefinitionRequestLogQueryMultiComputeArgs>()); set => _multiComputes = value; } [Input("searchQuery")] public Input<string>? SearchQuery { get; set; } public DashboardWidgetQueryTableDefinitionRequestLogQueryArgs() { } } }
40.377778
147
0.721519
[ "ECL-2.0", "Apache-2.0" ]
pulumi/pulumi-datadog
sdk/dotnet/Inputs/DashboardWidgetQueryTableDefinitionRequestLogQueryArgs.cs
1,817
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.Azure.MySql.Outputs { [OutputType] public sealed class ServerStorageProfile { /// <summary> /// Defines whether autogrow is enabled or disabled for the storage. Valid values are `Enabled` or `Disabled`. /// </summary> public readonly string? AutoGrow; /// <summary> /// Backup retention days for the server, supported values are between `7` and `35` days. /// </summary> public readonly int? BackupRetentionDays; /// <summary> /// Enable Geo-redundant or not for server backup. Valid values for this property are `Enabled` or `Disabled`, not supported for the `basic` tier. /// </summary> public readonly string? GeoRedundantBackup; /// <summary> /// Max storage allowed for a server. Possible values are between `5120` MB(5GB) and `1048576` MB(1TB) for the Basic SKU and between `5120` MB(5GB) and `4194304` MB(4TB) for General Purpose/Memory Optimized SKUs. For more information see the [product documentation](https://docs.microsoft.com/en-us/rest/api/mysql/servers/create#StorageProfile). /// </summary> public readonly int StorageMb; [OutputConstructor] private ServerStorageProfile( string? autoGrow, int? backupRetentionDays, string? geoRedundantBackup, int storageMb) { AutoGrow = autoGrow; BackupRetentionDays = backupRetentionDays; GeoRedundantBackup = geoRedundantBackup; StorageMb = storageMb; } } }
38.42
353
0.652264
[ "ECL-2.0", "Apache-2.0" ]
AdminTurnedDevOps/pulumi-azure
sdk/dotnet/MySql/Outputs/ServerStorageProfile.cs
1,921
C#
using System.Security.Cryptography; using System; using System.Text; using System.IO; using Aries; class SimpleAES { private ICryptoTransform EncryptorTransform, DecryptorTransform; private UTF8Encoding UTFEncoder; public byte[] Key; //Modified http://stackoverflow.com/questions/165808/simple-2-way-encryption-for-c /// <summary> /// AES Class /// </summary> public SimpleAES() { /*PasswordDeriveBytes derived = new PasswordDeriveBytes( Encoding.Default.GetBytes(new Random().Next(5000, 10000).ToString()), Encoding.Default.GetBytes(new Random().Next(5000, 10000).ToString()));*/ //This is our encryption method RijndaelManaged rm = new RijndaelManaged(); Key = Encoding.UTF8.GetBytes(Util.getRandNum(32)); byte[] Vector = Encoding.Default.GetBytes("Ijd0!$FDdg8s(*&J"); //Create an encryptor and a decryptor using our encryption method, key, and vector. EncryptorTransform = rm.CreateEncryptor(Key, Vector); DecryptorTransform = rm.CreateDecryptor(Key, Vector); //Used to translate bytes to text and vice versa UTFEncoder = new UTF8Encoding(); } /// -------------- Two Utility Methods (not used but may be useful) ----------- /// Generates an encryption key. static public byte[] GenerateEncryptionKey() { //Generate a Key. RijndaelManaged rm = new RijndaelManaged(); rm.GenerateKey(); return rm.Key; } /// Generates a unique encryption vector static public byte[] GenerateEncryptionVector() { //Generate a Vector RijndaelManaged rm = new RijndaelManaged(); rm.GenerateIV(); return rm.IV; } /// ----------- The commonly used methods ------------------------------ /// Encrypt some text and return a string suitable for passing in a URL. public string EncryptToString(string TextValue) { return Encoding.Default.GetString(Encrypt(TextValue)); } /// Encrypt some text and return an encrypted byte array. public byte[] Encrypt(string TextValue) { //Translates our text value into a byte array. Byte[] bytes = UTFEncoder.GetBytes(TextValue); //Used to stream the data in and out of the CryptoStream. MemoryStream memoryStream = new MemoryStream(); /* * We will have to write the unencrypted bytes to the stream, * then read the encrypted result back from the stream. */ #region Write the decrypted value to the encryption stream CryptoStream cs = new CryptoStream(memoryStream, EncryptorTransform, CryptoStreamMode.Write); cs.Write(bytes, 0, bytes.Length); cs.FlushFinalBlock(); #endregion #region Read encrypted value back out of the stream memoryStream.Position = 0; byte[] encrypted = new byte[memoryStream.Length]; memoryStream.Read(encrypted, 0, encrypted.Length); #endregion //Clean up. cs.Close(); memoryStream.Close(); return encrypted; } /// The other side: Decryption methods public string DecryptString(string EncryptedString) { return Decrypt(StrToByteArray(EncryptedString)); } /// Decryption when working with byte arrays. public string Decrypt(byte[] EncryptedValue) { #region Write the encrypted value to the decryption stream MemoryStream encryptedStream = new MemoryStream(); CryptoStream decryptStream = new CryptoStream(encryptedStream, DecryptorTransform, CryptoStreamMode.Write); decryptStream.Write(EncryptedValue, 0, EncryptedValue.Length); decryptStream.FlushFinalBlock(); #endregion #region Read the decrypted value from the stream. encryptedStream.Position = 0; Byte[] decryptedBytes = new Byte[encryptedStream.Length]; encryptedStream.Read(decryptedBytes, 0, decryptedBytes.Length); encryptedStream.Close(); #endregion return UTFEncoder.GetString(decryptedBytes); } /// Convert a string to a byte array. NOTE: Normally we'd create a Byte Array from a string using an ASCII encoding (like so). // However, this results in character values that cannot be passed in a URL. So, instead, I just // lay out all of the byte values in a long string of numbers (three per - must pad numbers less than 100). public byte[] StrToByteArray(string str) { if (str.Length == 0) throw new Exception("Invalid string value in StrToByteArray"); byte val; byte[] byteArr = new byte[str.Length / 3]; int i = 0; int j = 0; do { val = byte.Parse(str.Substring(i, 3)); byteArr[j++] = val; i += 3; } while (i < str.Length); return byteArr; } // Same comment as above. Normally the conversion would use an ASCII encoding in the other direction: // System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding(); // return enc.GetString(byteArr); public string ByteArrToString(byte[] byteArr) { byte val; string tempStr = ""; for (int i = 0; i <= byteArr.GetUpperBound(0); i++) { val = byteArr[i]; if (val < (byte)10) tempStr += "00" + val.ToString(); else if (val < (byte)100) tempStr += "0" + val.ToString(); else tempStr += val.ToString(); } return tempStr; } }
35.031056
131
0.620567
[ "MIT" ]
EAXrec/Aries
Aries/Aries/Aries/SimpleAES.cs
5,642
C#
namespace PiRhoSoft.Utilities { public class RequiredAttribute : PropertyTraitAttribute { public string Message { get; private set; } public MessageBoxType Type { get; private set; } public RequiredAttribute(string message, MessageBoxType type = MessageBoxType.Warning) : base(ValidatePhase, 0) { Message = message; Type = type; } } }
25.357143
113
0.735211
[ "MIT" ]
janmikusch/PiRhoUtilities
Assets/PiRhoUtilities/Runtime/Attributes/Traits/RequiredAttribute.cs
357
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 ec2-2014-10-01.normal.json service model. */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Net; using System.Text; using System.Xml.Serialization; using Amazon.EC2.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; namespace Amazon.EC2.Model.Internal.MarshallTransformations { /// <summary> /// Response Unmarshaller for VpnGateway Object /// </summary> public class VpnGatewayUnmarshaller : IUnmarshaller<VpnGateway, XmlUnmarshallerContext>, IUnmarshaller<VpnGateway, JsonUnmarshallerContext> { public VpnGateway Unmarshall(XmlUnmarshallerContext context) { VpnGateway unmarshalledObject = new VpnGateway(); int originalDepth = context.CurrentDepth; int targetDepth = originalDepth + 1; if (context.IsStartOfDocument) targetDepth += 2; while (context.ReadAtDepth(originalDepth)) { if (context.IsStartElement || context.IsAttribute) { if (context.TestExpression("availabilityZone", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; unmarshalledObject.AvailabilityZone = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("state", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; unmarshalledObject.State = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("tagSet/item", targetDepth)) { var unmarshaller = TagUnmarshaller.Instance; var item = unmarshaller.Unmarshall(context); unmarshalledObject.Tags.Add(item); continue; } if (context.TestExpression("type", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; unmarshalledObject.Type = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("attachments/item", targetDepth)) { var unmarshaller = VpcAttachmentUnmarshaller.Instance; var item = unmarshaller.Unmarshall(context); unmarshalledObject.VpcAttachments.Add(item); continue; } if (context.TestExpression("vpnGatewayId", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; unmarshalledObject.VpnGatewayId = unmarshaller.Unmarshall(context); continue; } } else if (context.IsEndElement && context.CurrentDepth < originalDepth) { return unmarshalledObject; } } return unmarshalledObject; } public VpnGateway Unmarshall(JsonUnmarshallerContext context) { return null; } private static VpnGatewayUnmarshaller _instance = new VpnGatewayUnmarshaller(); public static VpnGatewayUnmarshaller Instance { get { return _instance; } } } }
38.155172
143
0.565296
[ "Apache-2.0" ]
amazon-archives/aws-sdk-xamarin
AWS.XamarinSDK/AWSSDK_Android/Amazon.EC2/Model/Internal/MarshallTransformations/VpnGatewayUnmarshaller.cs
4,426
C#
// Copyright © 2018, Meta Company. All rights reserved. // // Redistribution and use of this software (the "Software") in binary form, without modification, is // permitted provided that the following conditions are met: // // 1. Redistributions of the unmodified Software in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // 2. The name of Meta Company (“Meta”) may not be used to endorse or promote products derived // from this Software without specific prior written permission from Meta. // 3. LIMITATION TO META PLATFORM: Use of the Software is limited to use on or in connection // with Meta-branded devices or Meta-branded software development kits. For example, a bona // fide recipient of the Software may incorporate an unmodified binary version of the // Software into an application limited to use on or in connection with a Meta-branded // device, while he or she may not incorporate an unmodified binary version of the Software // into an application designed or offered for use on a non-Meta-branded device. // // For the sake of clarity, the Software may not be redistributed under any circumstances in source // code form, or in the form of modified binary code – and nothing in this License shall be construed // to permit such redistribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, // INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A // PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL META COMPANY BE LIABLE FOR ANY DIRECT, // INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT // LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. using Meta.HandInput; using UnityEngine; namespace Meta { /// <summary> /// The delegate for hands state-transitions for objects. /// </summary> /// <param name="target">The GameObject which had the state transition</param> /// <param name="fromState">The state before the transition</param> /// <param name="toState">The state after the transition</param> internal delegate void HandObjectTransition(GameObject target, PalmState fromState , PalmState toState); /// <summary> /// Facade for Meta Hands complex subsystem. /// An implementor defines the criteria for when objects incur major or minor changes /// </summary> internal interface IHandObjectReferences { void AddListener(HandObjectTransition action); void RemoveListener(HandObjectTransition action); void AcceptStateTransitionForObject(GameObject target, PalmState fromState, PalmState toState); } }
54.440678
108
0.733499
[ "MIT" ]
JDZ-3/MXRManipulation
Assets/MetaSDK/Meta/Hands/HandInput/Scripts/IHandObjectReferences.cs
3,229
C#
using OA.Core; using System.Collections.Generic; using UnityEngine; namespace OA.Ultima.Core.Graphics { public class SpriteBatch3D { const int MAX_VERTICES_PER_DRAW = 0x4000; const int INITIAL_TEXTURE_COUNT = 0x800; const float MAX_ACCURATE_SINGLE_FLOAT = 65536; // this number is somewhat arbitrary; it's the number at which the // difference between two subsequent integers is +/-0.005. See http://stackoverflow.com/questions/872544/precision-of-floating-point float _z; readonly object _game; //readonly Effect _effect; readonly short[] _indexBuffer; static Bounds _viewportArea; readonly Queue<List<VertexPositionNormalTextureHue>> _vertexListQueue; readonly List<Dictionary<Texture2DInfo, List<VertexPositionNormalTextureHue>>> _drawQueue; readonly VertexPositionNormalTextureHue[] _vertexArray; public SpriteBatch3D(object game) { _game = game; _drawQueue = new List<Dictionary<Texture2DInfo, List<VertexPositionNormalTextureHue>>>((int)Techniques.All); for (var i = 0; i <= (int)Techniques.All; i++) _drawQueue.Add(new Dictionary<Texture2DInfo, List<VertexPositionNormalTextureHue>>(INITIAL_TEXTURE_COUNT)); _indexBuffer = CreateIndexBuffer(MAX_VERTICES_PER_DRAW); _vertexArray = new VertexPositionNormalTextureHue[MAX_VERTICES_PER_DRAW]; _vertexListQueue = new Queue<List<VertexPositionNormalTextureHue>>(INITIAL_TEXTURE_COUNT); //_effect = _game.Content.Load<Effect>("Shaders/IsometricWorld"); } public object GraphicsDevice { get { if (_game == null) return null; return null; // _game.GraphicsDevice; } } public Matrix4x4 ProjectionMatrixWorld { get { return Matrix4x4.identity; } } //public Matrix4x4 ProjectionMatrixScreen //{ // get { return Matrix4x4.CreateOrthographicOffCenter(0, GraphicsDevice.Viewport.Width, GraphicsDevice.Viewport.Height, 0f, short.MinValue, short.MaxValue); } //} public void Reset(bool setZHigh = false) { _z = setZHigh ? MAX_ACCURATE_SINGLE_FLOAT : 0; //_viewportArea = new Bounds(new Vector3(0, 0, int.MinValue), new Vector3(_game.GraphicsDevice.Viewport.Width, _game.GraphicsDevice.Viewport.Height, int.MaxValue)); } public virtual float GetNextUniqueZ() { return _z++; } /// <summary> /// Draws a quad on screen with the specified texture and vertices. /// </summary> /// <param name="texture"></param> /// <param name="vertices"></param> /// <returns>True if the object was drawn, false otherwise.</returns> public bool DrawSprite(Texture2DInfo texture, VertexPositionNormalTextureHue[] vertices, Techniques effect = Techniques.Default) { var draw = false; // Sanity: do not draw if there is no texture to draw with. if (texture == null) return false; // Check: only draw if the texture is within the visible area. for (var i = 0; i < 4; i++) // only draws a 2 triangle tristrip. //if (_viewportArea.Contains(vertices[i].Position) == ContainmentType.Contains) { draw = true; break; } if (!draw) return false; // Set the draw position's z value, and increment the z value for the next drawn object. vertices[0].Position.z = vertices[1].Position.z = vertices[2].Position.z = vertices[3].Position.z = GetNextUniqueZ(); // Get the vertex list for this texture. if none exists, dequeue existing or create a new vertex list. var vertexList = GetVertexList(texture, effect); // Add the drawn object to the vertex list. for (var i = 0; i < vertices.Length; i++) vertexList.Add(vertices[i]); return true; } /// <summary> /// Draws a special 'shadow' sprite, automatically skewing the passed vertices. /// </summary> /// <param name="texture">The texture to draw with.</param> /// <param name="vertices">An array of four vertices. Note: modified by this routine.</param> /// <param name="drawPosition">The draw position at which this sprite begins (should be the center of an isometric tile for non-moving sprites).</param> /// <param name="flipVertices">See AEntityView.Draw(); this is equivalent to DrawFlip.</param> /// <param name="z">The z depth at which the shadow sprite should be placed.</param> public void DrawShadow(Texture2DInfo texture, VertexPositionNormalTextureHue[] vertices, Vector2 drawPosition, bool flipVertices, float z) { // Sanity: do not draw if there is no texture to draw with. if (texture == null) return; // set proper z depth for this shadow. vertices[0].Position.z = vertices[1].Position.z = vertices[2].Position.z = vertices[3].Position.z = z; // skew texture var skewHorizTop = (vertices[0].Position.y - drawPosition.y) * .5f; var skewHorizBottom = (vertices[3].Position.y - drawPosition.y) * .5f; vertices[0].Position.x -= skewHorizTop; vertices[0].Position.y -= skewHorizTop; vertices[flipVertices ? 2 : 1].Position.x -= skewHorizTop; vertices[flipVertices ? 2 : 1].Position.y -= skewHorizTop; vertices[flipVertices ? 1 : 2].Position.x -= skewHorizBottom; vertices[flipVertices ? 1 : 2].Position.y -= skewHorizBottom; vertices[3].Position.x -= skewHorizBottom; vertices[3].Position.y -= skewHorizBottom; var vertexList = GetVertexList(texture, Techniques.ShadowSet); for (var i = 0; i < vertices.Length; i++) vertexList.Add(vertices[i]); } public void DrawStencil(Texture2DInfo texture, VertexPositionNormalTextureHue[] vertices) { // Sanity: do not draw if there is no texture to draw with. if (texture == null) return; // set proper z depth for this shadow. vertices[0].Position.z = vertices[1].Position.z = vertices[2].Position.z = vertices[3].Position.z = GetNextUniqueZ(); } public void FlushSprites(bool doLighting) { // set up graphics device and texture sampling. //GraphicsDevice.BlendState = BlendState.AlphaBlend; //GraphicsDevice.RasterizerState = RasterizerState.CullNone; //GraphicsDevice.SamplerStates[0] = SamplerState.PointClamp; // the sprite texture sampler. //GraphicsDevice.SamplerStates[1] = SamplerState.PointClamp; // hue sampler (1/2) //GraphicsDevice.SamplerStates[2] = SamplerState.PointClamp; // hue sampler (2/2) //GraphicsDevice.SamplerStates[3] = SamplerState.PointWrap; // the minimap sampler. //// We use lighting parameters to shade vertexes when we're drawing the world. //_effect.Parameters["DrawLighting"].SetValue(doLighting); //// set up viewport. //_effect.Parameters["ProjectionMatrix"].SetValue(ProjectionMatrixScreen); //_effect.Parameters["WorldMatrix"].SetValue(ProjectionMatrixWorld); //_effect.Parameters["Viewport"].SetValue(new Vector2(GraphicsDevice.Viewport.Width, GraphicsDevice.Viewport.Height)); // enable depth sorting, disable the stencil //SetDepthStencilState(true, false); DrawAllVertices(Techniques.FirstDrawn, Techniques.LastDrawn); } private void DrawAllVertices(Techniques first, Techniques last) { // draw normal objects for (var effect = first; effect <= last; effect++) { //switch (effect) //{ // case Techniques.Hued: _effect.CurrentTechnique = _effect.Techniques["HueTechnique"]; break; // case Techniques.MiniMap: _effect.CurrentTechnique = _effect.Techniques["MiniMapTechnique"]; break; // case Techniques.Grayscale: _effect.CurrentTechnique = _effect.Techniques["GrayscaleTechnique"]; break; // case Techniques.ShadowSet: _effect.CurrentTechnique = _effect.Techniques["ShadowSetTechnique"]; SetDepthStencilState(true, true); break; // case Techniques.StencilSet: // do nothing; break; // default: Utils.Critical("Unknown effect in SpriteBatch3D.Flush(). Effect index is {effect}"); break; //} //_effect.CurrentTechnique.Passes[0].Apply(); var vertexEnumerator = _drawQueue[(int)effect].GetEnumerator(); while (vertexEnumerator.MoveNext()) { var texture = vertexEnumerator.Current.Key; var vertexList = vertexEnumerator.Current.Value; //GraphicsDevice.Textures[0] = texture; //GraphicsDevice.DrawUserIndexedPrimitives(PrimitiveType.TriangleList, CopyVerticesToArray(vertexList), 0, Math.Min(vertexList.Count, MAX_VERTICES_PER_DRAW), _indexBuffer, 0, vertexList.Count / 2); vertexList.Clear(); _vertexListQueue.Enqueue(vertexList); } _drawQueue[(int)effect].Clear(); } } private VertexPositionNormalTextureHue[] CopyVerticesToArray(List<VertexPositionNormalTextureHue> vertices) { var max = vertices.Count <= MAX_VERTICES_PER_DRAW ? vertices.Count : MAX_VERTICES_PER_DRAW; vertices.CopyTo(0, _vertexArray, 0, max); return _vertexArray; } public void SetLightDirection(Vector3 direction) { //_effect.Parameters["lightDirection"].SetValue(direction); } public void SetLightIntensity(float intensity) { //_effect.Parameters["lightIntensity"].SetValue(intensity); } //private void SetDepthStencilState(bool depth, bool stencil) //{ // // depth is currently ignored. // var dss = new DepthStencilState(); // dss.DepthBufferEnable = true; // dss.DepthBufferWriteEnable = true; // if (stencil) // { // dss.StencilEnable = true; // dss.StencilFunction = CompareFunction.Equal; // dss.ReferenceStencil = 0; // dss.StencilPass = StencilOperation.Increment; // dss.StencilFail = StencilOperation.Keep; // } // GraphicsDevice.DepthStencilState = dss; //} private List<VertexPositionNormalTextureHue> GetVertexList(Texture2DInfo texture, Techniques effect) { List<VertexPositionNormalTextureHue> vertexList; if (_drawQueue[(int)effect].ContainsKey(texture)) vertexList = _drawQueue[(int)effect][texture]; else { if (_vertexListQueue.Count > 0) { vertexList = _vertexListQueue.Dequeue(); vertexList.Clear(); } else vertexList = new List<VertexPositionNormalTextureHue>(1024); _drawQueue[(int)effect].Add(texture, vertexList); } return vertexList; } private short[] CreateIndexBuffer(int primitiveCount) { var indices = new short[primitiveCount * 6]; for (var i = 0; i < primitiveCount; i++) { indices[i * 6] = (short)(i * 4); indices[i * 6 + 1] = (short)(i * 4 + 1); indices[i * 6 + 2] = (short)(i * 4 + 2); indices[i * 6 + 3] = (short)(i * 4 + 2); indices[i * 6 + 4] = (short)(i * 4 + 1); indices[i * 6 + 5] = (short)(i * 4 + 3); } return indices; } } }
49.893281
218
0.584172
[ "MIT" ]
BclEx/object-assets
src/ObjectManager/Object.Ultima.Game/Core/Graphics/SpriteBatch3D.cs
12,625
C#
using System; using Firepuma.Api.Abstractions.Actor; using Firepuma.Api.Abstractions.Errors; using Microsoft.Extensions.DependencyInjection; namespace Firepuma.HttpRequestAuditing.Mongo.Extensions { public static class ServiceCollectionExtensions { public static void AddRequestAuditingService<TActor>(this IServiceCollection services) where TActor : IActorIdentity { using (var scope = services.BuildServiceProvider().CreateScope()) { if (scope.ServiceProvider.GetService<IErrorReportingService>() == null) { throw new Exception($"Please register IErrorReportingService service before calling {nameof(AddRequestAuditingService)}"); } if (scope.ServiceProvider.GetService<IActorProviderHolder<TActor>>() == null) { throw new Exception($"Please register IActorProviderHolder<TActor> service before calling {nameof(AddRequestAuditingService)}"); } services.AddScoped<IRequestAuditingService, RequestAuditingService<TActor>>(); } } } }
42.888889
148
0.66494
[ "Apache-2.0" ]
fire-puma/Firepuma.HttpRequestAuditing.Mongo
src/Extensions/ServiceCollectionExtensions.cs
1,158
C#
// <auto-generated /> namespace AdminLteMvc.Migrations { using System.CodeDom.Compiler; using System.Data.Entity.Migrations; using System.Data.Entity.Migrations.Infrastructure; using System.Resources; [GeneratedCode("EntityFramework.Migrations", "6.1.3-40302")] public sealed partial class Booking10 : IMigrationMetadata { private readonly ResourceManager Resources = new ResourceManager(typeof(Booking10)); string IMigrationMetadata.Id { get { return "202011100808371_Booking10"; } } string IMigrationMetadata.Source { get { return null; } } string IMigrationMetadata.Target { get { return Resources.GetString("Target"); } } } }
27
92
0.617284
[ "MIT" ]
ataharasystemsolutions/KTI_TEST
AdminLteMvc/AdminLteMvc/Migrations/202011100808371_Booking10.Designer.cs
810
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using Microsoft.DotNet.XHarness.Common.Utilities; using Microsoft.DotNet.XHarness.iOS.Shared.Execution; using Xunit; namespace Microsoft.DotNet.XHarness.iOS.Shared.Tests.Execution { public class MlaunchArgumentsTests { public class CommandLineDataTestSource { private static readonly string s_listDevFile = "/my/listdev.txt"; private static readonly string s_listSimFile = "/my/listsim.txt"; private static readonly string s_xmlOutputType = "XML"; public static IEnumerable<object[]> CommandLineArgs => new[] { new object[] { new MlaunchArgument[] { new ListDevicesArgument (s_listDevFile) }, $"--listdev={s_listDevFile}" }, new object[] { new MlaunchArgument[] { new ListSimulatorsArgument (s_listSimFile) }, $"--listsim={s_listSimFile}" }, new object[] { new MlaunchArgument[] { new XmlOutputFormatArgument () }, $"--output-format={s_xmlOutputType}" }, new object[] { new MlaunchArgument[] { new ListExtraDataArgument () }, "--list-extra-data" }, new object[] { new MlaunchArgument[] { new DownloadCrashReportToArgument ("/path/with spaces.txt"), new DeviceNameArgument ("Test iPad") }, $"\"--download-crash-report-to=/path/with spaces.txt\" --devname \"Test iPad\"" }, new object[] { new MlaunchArgument[] { new SetEnvVariableArgument ("SOME_PARAM", "true"), new SetEnvVariableArgument ("NUNIT_LOG_FILE", "/another space/path.txt") }, $"-setenv=SOME_PARAM=true \"-setenv=NUNIT_LOG_FILE=/another space/path.txt\"" }, new object[] { new MlaunchArgument[] { new ListDevicesArgument (s_listDevFile), new XmlOutputFormatArgument (), new ListExtraDataArgument () }, $"--listdev={s_listDevFile} --output-format={s_xmlOutputType} --list-extra-data" }, }; }; [Theory] [MemberData(nameof(CommandLineDataTestSource.CommandLineArgs), MemberType = typeof(CommandLineDataTestSource))] public void AsCommandLineTest(MlaunchArgument[] args, string expected) => Assert.Equal(expected, new MlaunchArguments(args).AsCommandLine()); [Fact] public void MlaunchArgumentAndProcessManagerTest() { var oldArgs = new List<string>() { "--download-crash-report-to=/path/with spaces.txt", "--sdkroot", "/path to xcode/spaces", "--devname", "Premek's iPhone", }; var newArgs = new MlaunchArguments() { new DownloadCrashReportToArgument ("/path/with spaces.txt"), new SdkRootArgument ("/path to xcode/spaces"), new DeviceNameArgument ("Premek's iPhone"), }; var oldWayOfPassingArgs = StringUtils.FormatArguments(oldArgs); var newWayOfPassingArgs = newArgs.AsCommandLine(); Assert.Equal(oldWayOfPassingArgs, newWayOfPassingArgs); } [Fact] public void MlaunchArgumentEqualityTest() { var arg1 = new DownloadCrashReportToArgument("/path/with spaces.txt"); var arg2 = new DownloadCrashReportToArgument("/path/with spaces.txt"); var arg3 = new DownloadCrashReportToArgument("/path/with.txt"); Assert.Equal(arg1, arg2); Assert.NotEqual(arg1, arg3); } [Fact] public void MlaunchArgumentsEqualityTest() { var args1 = new MlaunchArgument[] { new ListDevicesArgument ("foo"), new ListSimulatorsArgument ("bar") }; var args2 = new MlaunchArgument[] { new ListDevicesArgument ("foo"), new ListSimulatorsArgument ("bar") }; var args3 = new MlaunchArgument[] { new ListDevicesArgument ("foo"), new ListSimulatorsArgument ("xyz") }; Assert.Equal(args1, args2); Assert.NotEqual(args1, args3); } } }
37.77037
149
0.521867
[ "MIT" ]
Daniel-Genkin/xharness
tests/Microsoft.DotNet.XHarness.iOS.Shared.Tests/Execution/MlaunchArgumentsTests.cs
5,101
C#
#region License /* * HttpHeaderInfo.cs * * The MIT License * * Copyright (c) 2013-2014 sta.blockhead * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #endregion namespace WebSocketSharp.Net { internal class HttpHeaderInfo { #region Private Fields private string _name; private HttpHeaderType _type; #endregion #region Internal Constructors internal HttpHeaderInfo (string name, HttpHeaderType type) { _name = name; _type = type; } #endregion #region Internal Properties internal bool IsMultiValueInRequest { get { return (_type & HttpHeaderType.MultiValueInRequest) == HttpHeaderType.MultiValueInRequest; } } internal bool IsMultiValueInResponse { get { return (_type & HttpHeaderType.MultiValueInResponse) == HttpHeaderType.MultiValueInResponse; } } #endregion #region Public Properties public bool IsRequest { get { return (_type & HttpHeaderType.Request) == HttpHeaderType.Request; } } public bool IsResponse { get { return (_type & HttpHeaderType.Response) == HttpHeaderType.Response; } } public string Name { get { return _name; } } public HttpHeaderType Type { get { return _type; } } #endregion #region Public Methods public bool IsMultiValue (bool response) { return (_type & HttpHeaderType.MultiValue) == HttpHeaderType.MultiValue ? (response ? IsResponse : IsRequest) : (response ? IsMultiValueInResponse : IsMultiValueInRequest); } public bool IsRestricted (bool response) { return (_type & HttpHeaderType.Restricted) == HttpHeaderType.Restricted ? (response ? IsResponse : IsRequest) : false; } #endregion } }
25.831858
100
0.675916
[ "Apache-2.0" ]
DoctorDump/AsyncChromeDriver
WebSocket/websocket-sharp/Net/HttpHeaderInfo.cs
2,919
C#
/* * Copyright (c) 2008, openmetaverse.org * All rights reserved. * * - Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * - Neither the name of the Second Life Reverse Engineering Team nor the names * of its contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Text; using OpenMetaverse; namespace OpenMetaverse.Packets { /// <summary> /// Thrown when a packet could not be successfully deserialized /// </summary> public class MalformedDataException : ApplicationException { /// <summary> /// Default constructor /// </summary> public MalformedDataException() { } /// <summary> /// Constructor that takes an additional error message /// </summary> /// <param name="Message">An error message to attach to this exception</param> public MalformedDataException(string Message) : base(Message) { this.Source = "Packet decoding"; } } /// <summary> /// The header of a message template packet. Either 5, 6, or 8 bytes in /// length at the beginning of the packet, and encapsulates any /// appended ACKs at the end of the packet as well /// </summary> public abstract class Header { /// <summary>Raw header data, does not include appended ACKs</summary> public byte[] Data; /// <summary>Raw value of the flags byte</summary> public byte Flags { get { return Data[0]; } set { Data[0] = value; } } /// <summary>Reliable flag, whether this packet requires an ACK</summary> public bool Reliable { get { return (Data[0] & Helpers.MSG_RELIABLE) != 0; } set { if (value) { Data[0] |= (byte)Helpers.MSG_RELIABLE; } else { byte mask = (byte)Helpers.MSG_RELIABLE ^ 0xFF; Data[0] &= mask; } } } /// <summary>Resent flag, whether this same packet has already been /// sent</summary> public bool Resent { get { return (Data[0] & Helpers.MSG_RESENT) != 0; } set { if (value) { Data[0] |= (byte)Helpers.MSG_RESENT; } else { byte mask = (byte)Helpers.MSG_RESENT ^ 0xFF; Data[0] &= mask; } } } /// <summary>Zerocoded flag, whether this packet is compressed with /// zerocoding</summary> public bool Zerocoded { get { return (Data[0] & Helpers.MSG_ZEROCODED) != 0; } set { if (value) { Data[0] |= (byte)Helpers.MSG_ZEROCODED; } else { byte mask = (byte)Helpers.MSG_ZEROCODED ^ 0xFF; Data[0] &= mask; } } } /// <summary>Appended ACKs flag, whether this packet has ACKs appended /// to the end</summary> public bool AppendedAcks { get { return (Data[0] & Helpers.MSG_APPENDED_ACKS) != 0; } set { if (value) { Data[0] |= (byte)Helpers.MSG_APPENDED_ACKS; } else { byte mask = (byte)Helpers.MSG_APPENDED_ACKS ^ 0xFF; Data[0] &= mask; } } } /// <summary>Packet sequence number</summary> public uint Sequence { get { return (uint)((Data[1] << 24) + (Data[2] << 16) + (Data[3] << 8) + Data[4]); } set { Data[1] = (byte)(value >> 24); Data[2] = (byte)(value >> 16); Data[3] = (byte)(value >> 8); Data[4] = (byte)(value % 256); } } /// <summary>Numeric ID number of this packet</summary> public abstract ushort ID { get; set; } /// <summary>Frequency classification of this packet, Low Medium or /// High</summary> public abstract PacketFrequency Frequency { get; } /// <summary>Convert this header to a byte array, not including any /// appended ACKs</summary> public abstract void ToBytes(byte[] bytes, ref int i); /// <summary>Array containing all the appended ACKs of this packet</summary> public uint[] AckList; public abstract void FromBytes(byte[] bytes, ref int pos, ref int packetEnd); /// <summary> /// Convert the AckList to a byte array, used for packet serializing /// </summary> /// <param name="bytes">Reference to the target byte array</param> /// <param name="i">Beginning position to start writing to in the byte /// array, will be updated with the ending position of the ACK list</param> public void AcksToBytes(byte[] bytes, ref int i) { foreach (uint ack in AckList) { bytes[i++] = (byte)((ack >> 24) % 256); bytes[i++] = (byte)((ack >> 16) % 256); bytes[i++] = (byte)((ack >> 8) % 256); bytes[i++] = (byte)(ack % 256); } if (AckList.Length > 0) { bytes[i++] = (byte)AckList.Length; } } /// <summary> /// /// </summary> /// <param name="bytes"></param> /// <param name="pos"></param> /// <param name="packetEnd"></param> /// <returns></returns> public static Header BuildHeader(byte[] bytes, ref int pos, ref int packetEnd) { if (bytes[6] == 0xFF) { if (bytes[7] == 0xFF) { return new LowHeader(bytes, ref pos, ref packetEnd); } else { return new MediumHeader(bytes, ref pos, ref packetEnd); } } else { return new HighHeader(bytes, ref pos, ref packetEnd); } } /// <summary> /// /// </summary> /// <param name="bytes"></param> /// <param name="packetEnd"></param> protected void CreateAckList(byte[] bytes, ref int packetEnd) { if (AppendedAcks) { try { int count = bytes[packetEnd--]; AckList = new uint[count]; for (int i = 0; i < count; i++) { AckList[i] = (uint)( (bytes[(packetEnd - i * 4) - 3] << 24) | (bytes[(packetEnd - i * 4) - 2] << 16) | (bytes[(packetEnd - i * 4) - 1] << 8) | (bytes[(packetEnd - i * 4) ])); } packetEnd -= (count * 4); } catch (Exception) { AckList = new uint[0]; throw new MalformedDataException(); } } else { AckList = new uint[0]; } } } /// <summary> /// /// </summary> public class LowHeader : Header { /// <summary></summary> public override ushort ID { get { return (ushort)((Data[8] << 8) + Data[9]); } set { Data[8] = (byte)(value >> 8); Data[9] = (byte)(value % 256); } } /// <summary></summary> public override PacketFrequency Frequency { get { return PacketFrequency.Low; } } /// <summary> /// /// </summary> public LowHeader() { Data = new byte[10]; Data[6] = Data[7] = 0xFF; AckList = new uint[0]; } /// <summary> /// /// </summary> /// <param name="bytes"></param> /// <param name="pos"></param> /// <param name="packetEnd"></param> public LowHeader(byte[] bytes, ref int pos, ref int packetEnd) { FromBytes(bytes, ref pos, ref packetEnd); } override public void FromBytes(byte[] bytes, ref int pos, ref int packetEnd) { if (bytes.Length < 10) { throw new MalformedDataException(); } Data = new byte[10]; Buffer.BlockCopy(bytes, 0, Data, 0, 10); if ((bytes[0] & Helpers.MSG_ZEROCODED) != 0 && bytes[8] == 0) { if (bytes[9] == 1) { Data[9] = bytes[10]; } else { throw new MalformedDataException(); } } pos = 10; CreateAckList(bytes, ref packetEnd); } /// <summary> /// /// </summary> /// <param name="bytes"></param> /// <param name="i"></param> public override void ToBytes(byte[] bytes, ref int i) { Buffer.BlockCopy(Data, 0, bytes, i, 10); i += 10; } } /// <summary> /// /// </summary> public class MediumHeader : Header { /// <summary></summary> public override ushort ID { get { return (ushort)Data[7]; } set { Data[7] = (byte)value; } } /// <summary></summary> public override PacketFrequency Frequency { get { return PacketFrequency.Medium; } } /// <summary> /// /// </summary> public MediumHeader() { Data = new byte[8]; Data[6] = 0xFF; AckList = new uint[0]; } /// <summary> /// /// </summary> /// <param name="bytes"></param> /// <param name="pos"></param> /// <param name="packetEnd"></param> public MediumHeader(byte[] bytes, ref int pos, ref int packetEnd) { FromBytes(bytes, ref pos, ref packetEnd); } override public void FromBytes(byte[] bytes, ref int pos, ref int packetEnd) { if (bytes.Length < 8) { throw new MalformedDataException(); } Data = new byte[8]; Buffer.BlockCopy(bytes, 0, Data, 0, 8); pos = 8; CreateAckList(bytes, ref packetEnd); } /// <summary> /// /// </summary> /// <param name="bytes"></param> /// <param name="i"></param> public override void ToBytes(byte[] bytes, ref int i) { Buffer.BlockCopy(Data, 0, bytes, i, 8); i += 8; } } /// <summary> /// /// </summary> public class HighHeader : Header { /// <summary></summary> public override ushort ID { get { return (ushort)Data[6]; } set { Data[6] = (byte)value; } } /// <summary></summary> public override PacketFrequency Frequency { get { return PacketFrequency.High; } } /// <summary> /// /// </summary> public HighHeader() { Data = new byte[7]; AckList = new uint[0]; } /// <summary> /// /// </summary> /// <param name="bytes"></param> /// <param name="pos"></param> /// <param name="packetEnd"></param> public HighHeader(byte[] bytes, ref int pos, ref int packetEnd) { FromBytes(bytes, ref pos, ref packetEnd); } override public void FromBytes(byte[] bytes, ref int pos, ref int packetEnd) { if (bytes.Length < 7) { throw new MalformedDataException(); } Data = new byte[7]; Buffer.BlockCopy(bytes, 0, Data, 0, 7); pos = 7; CreateAckList(bytes, ref packetEnd); } /// <summary> /// /// </summary> /// <param name="bytes"></param> /// <param name="i"></param> public override void ToBytes(byte[] bytes, ref int i) { Buffer.BlockCopy(Data, 0, bytes, i, 7); i += 7; } } /// <summary> /// A block of data in a packet. Packets are composed of one or more blocks, /// each block containing one or more fields /// </summary> public abstract class PacketBlock { /// <summary>Current length of the data in this packet</summary> public abstract int Length { get; } /// <summary> /// Create a block from a byte array /// </summary> /// <param name="bytes">Byte array containing the serialized block</param> /// <param name="i">Starting position of the block in the byte array. /// This will point to the data after the end of the block when the /// call returns</param> public abstract void FromBytes(byte[] bytes, ref int i); /// <summary> /// Serialize this block into a byte array /// </summary> /// <param name="bytes">Byte array to serialize this block into</param> /// <param name="i">Starting position in the byte array to serialize to. /// This will point to the position directly after the end of the /// serialized block when the call returns</param> public abstract void ToBytes(byte[] bytes, ref int i); }
34.874693
156
0.5124
[ "BSD-3-Clause" ]
jhs/libopenmetaverse
Programs/mapgenerator/template.cs
14,194
C#
/* * Prime Developer Trial * * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) * * The version of the OpenAPI document: v1 * Generated by: https://github.com/openapitools/openapi-generator.git */ using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using Newtonsoft.Json.Linq; using System.ComponentModel.DataAnnotations; using OpenAPIDateConverter = FactSet.SDK.StocksAPIforDigitalPortals.Client.OpenAPIDateConverter; namespace FactSet.SDK.StocksAPIforDigitalPortals.Model { /// <summary> /// Specifies the markets from which a notation may originate. /// </summary> [DataContract(Name = "_stock_notation_screener_search_data_validation_market_selection_restrict")] public partial class StockNotationScreenerSearchDataValidationMarketSelectionRestrict : IEquatable<StockNotationScreenerSearchDataValidationMarketSelectionRestrict>, IValidatableObject { /// <summary> /// Initializes a new instance of the <see cref="StockNotationScreenerSearchDataValidationMarketSelectionRestrict" /> class. /// </summary> /// <param name="ids">Set of market identifiers..</param> public StockNotationScreenerSearchDataValidationMarketSelectionRestrict(List<decimal> ids = default(List<decimal>)) { this.Ids = ids; } /// <summary> /// Set of market identifiers. /// </summary> /// <value>Set of market identifiers.</value> [DataMember(Name = "ids", EmitDefaultValue = false)] public List<decimal> Ids { get; set; } /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { StringBuilder sb = new StringBuilder(); sb.Append("class StockNotationScreenerSearchDataValidationMarketSelectionRestrict {\n"); sb.Append(" Ids: ").Append(Ids).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public virtual string ToJson() { return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="input">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object input) { return this.Equals(input as StockNotationScreenerSearchDataValidationMarketSelectionRestrict); } /// <summary> /// Returns true if StockNotationScreenerSearchDataValidationMarketSelectionRestrict instances are equal /// </summary> /// <param name="input">Instance of StockNotationScreenerSearchDataValidationMarketSelectionRestrict to be compared</param> /// <returns>Boolean</returns> public bool Equals(StockNotationScreenerSearchDataValidationMarketSelectionRestrict input) { if (input == null) { return false; } return ( this.Ids == input.Ids || this.Ids != null && input.Ids != null && this.Ids.SequenceEqual(input.Ids) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { unchecked // Overflow is fine, just wrap { int hashCode = 41; if (this.Ids != null) { hashCode = (hashCode * 59) + this.Ids.GetHashCode(); } return hashCode; } } /// <summary> /// To validate all properties of the instance /// </summary> /// <param name="validationContext">Validation context</param> /// <returns>Validation Result</returns> public IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> Validate(ValidationContext validationContext) { yield break; } } }
36.122137
188
0.62109
[ "Apache-2.0" ]
factset/enterprise-sdk
code/dotnet/StocksAPIforDigitalPortals/v2/src/FactSet.SDK.StocksAPIforDigitalPortals/Model/StockNotationScreenerSearchDataValidationMarketSelectionRestrict.cs
4,732
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 MediaCaptureWpfXamlIslands.Properties { using System; /// <summary> /// A strongly-typed resource class, for looking up localized strings, etc. /// </summary> // This class was auto-generated by the StronglyTypedResourceBuilder // class via a tool like ResGen or Visual Studio. // To add or remove a member, edit your .ResX file then rerun ResGen // with the /str option, or rebuild your VS project. [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "16.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> /// Returns the cached ResourceManager instance used by this class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Resources.ResourceManager ResourceManager { get { if (object.ReferenceEquals(resourceMan, null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("MediaCaptureWpfXamlIslands.Properties.Resources", typeof(Resources).Assembly); resourceMan = temp; } return resourceMan; } } /// <summary> /// Overrides the current thread's CurrentUICulture property for all /// resource lookups using this strongly typed resource class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } } }
44
192
0.617543
[ "MIT" ]
knaufinator/IMU-Drive-Recorder
MediaCaptureWpfXamlIslands/Properties/Resources.Designer.cs
2,818
C#
using System.Collections.Generic; using System.IO; using System.Linq; namespace DNSProfileChecker.Common.Implementation { public sealed class SessionFoldersSequenceValidator : IValidator<DirectoryInfo[]> { private DirectoryInfo[] missedFolders; public bool Validate(DirectoryInfo[] sessions) { Ensure.Argument.NotNull(sessions, "sessions cannot be a null."); bool result = true; if (sessions.Length == 0) return result; string parentFolder = sessions[sessions.Length - 1].Parent.FullName; int[] values = new int[sessions.Length]; for (int i = 0; i < sessions.Length; i++) { values[i] = int.Parse(sessions[i].Name.Remove(0, "session".Length)); } List<DirectoryInfo> missed = new List<DirectoryInfo>(); foreach (var missedIndx in Enumerable.Range(1, values.Last()).Except(values)) { missed.Add(new DirectoryInfo(Path.Combine(parentFolder, "session" + missedIndx))); } if (missed.Count > 0) { result = false; missedFolders = missed.ToArray(); } return result; } public DirectoryInfo[] MissedValues { get { return missedFolders; } } } }
26.690476
86
0.694915
[ "Apache-2.0" ]
OleksandrKulchytskyi/ProfileChecker
DNSProfileChecker.Common/Implementation/SessionFoldersSequenceValidator.cs
1,123
C#
namespace Mercurial.Net.Gui { /// <summary> /// Implements the TortoiseHg "about" command: /// Show the "About TortoiseHg" dialog. /// </summary> public sealed class AboutGuiCommand : GuiCommandBase<AboutGuiCommand> { /// <summary> /// Initializes a new instance of the <see cref="AboutGuiCommand"/> class. /// </summary> public AboutGuiCommand() : base("about") { // Do nothing here } } }
27.166667
82
0.560327
[ "MIT" ]
rexsacrorum/Hg.Client
src/Mercurial.Net/Gui/AboutGuiCommand.cs
489
C#
using Microsoft.EntityFrameworkCore.Migrations; namespace FavourPal.Domain.Migrations { public partial class Recreatedb : Migration { protected override void Up(MigrationBuilder migrationBuilder) { } protected override void Down(MigrationBuilder migrationBuilder) { } } }
18.722222
71
0.670623
[ "MIT" ]
RomansPacjuks27/FavourPal
FavourPal.Domain/Migrations/20191015230015_Recreate db.cs
339
C#
/* * FactSet Procure to Pay API * * Allows for Provisioning and Entitlement of FactSet accounts. Authentication is provided via FactSet's [API Key System](https://developer.factset.com/authentication) Please note that the on-page \"Try it out\" features do not function. You must authorize against our API and make requests directly againt the endpoints. * * The version of the OpenAPI document: 1S * Generated by: https://github.com/openapitools/openapi-generator.git */ using System; using System.Collections.Generic; using System.Net; using System.Security.Cryptography.X509Certificates; using FactSet.SDK.Utils.Authentication; namespace FactSet.SDK.ProcuretoPayProvisioning.Client { /// <summary> /// Represents a readable-only configuration contract. /// </summary> public interface IReadableConfiguration { /// <summary> /// Gets the OAuth2Client /// </summary> /// <value>FactSet OAuth2 Client</value> IOAuth2Client OAuth2Client { get; } /// <summary> /// Gets the access token. /// </summary> /// <value>Access token.</value> string AccessToken { get; } /// <summary> /// Gets the API key. /// </summary> /// <value>API key.</value> IDictionary<string, string> ApiKey { get; } /// <summary> /// Gets the API key prefix. /// </summary> /// <value>API key prefix.</value> IDictionary<string, string> ApiKeyPrefix { get; } /// <summary> /// Gets the base path. /// </summary> /// <value>Base path.</value> string BasePath { get; } /// <summary> /// Gets the date time format. /// </summary> /// <value>Date time format.</value> string DateTimeFormat { get; } /// <summary> /// Gets the default header. /// </summary> /// <value>Default header.</value> [Obsolete("Use DefaultHeaders instead.")] IDictionary<string, string> DefaultHeader { get; } /// <summary> /// Gets the default headers. /// </summary> /// <value>Default headers.</value> IDictionary<string, string> DefaultHeaders { get; } /// <summary> /// Gets the temp folder path. /// </summary> /// <value>Temp folder path.</value> string TempFolderPath { get; } /// <summary> /// Gets the HTTP connection timeout (in milliseconds) /// </summary> /// <value>HTTP connection timeout.</value> int Timeout { get; } /// <summary> /// Gets the proxy. /// </summary> /// <value>Proxy.</value> WebProxy Proxy { get; } /// <summary> /// Gets the user agent. /// </summary> /// <value>User agent.</value> string UserAgent { get; } /// <summary> /// Gets the username. /// </summary> /// <value>Username.</value> string Username { get; } /// <summary> /// Gets the password. /// </summary> /// <value>Password.</value> string Password { get; } /// <summary> /// Gets the API key with prefix. /// </summary> /// <param name="apiKeyIdentifier">API key identifier (authentication scheme).</param> /// <returns>API key with prefix.</returns> string GetApiKeyWithPrefix(string apiKeyIdentifier); /// <summary> /// Gets certificate collection to be sent with requests. /// </summary> /// <value>X509 Certificate collection.</value> X509CertificateCollection ClientCertificates { get; } } }
30.504065
332
0.561301
[ "Apache-2.0" ]
factset/enterprise-sdk
code/dotnet/ProcuretoPayProvisioning/v1/src/FactSet.SDK.ProcuretoPayProvisioning/Client/IReadableConfiguration.cs
3,752
C#
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Internal; using Microsoft.EntityFrameworkCore.Storage; namespace Microsoft.EntityFrameworkCore.Specification.Tests { public abstract class UpdatesRelationalTestBase<TFixture, TTestStore> : UpdatesTestBase<TFixture, TTestStore> where TFixture : UpdatesFixtureBase<TTestStore> where TTestStore : TestStore { protected UpdatesRelationalTestBase(TFixture fixture) : base(fixture) { } protected override void UseTransaction(DatabaseFacade facade, IDbContextTransaction transaction) => facade.UseTransaction(transaction.GetDbTransaction()); protected override string UpdateConcurrencyMessage => RelationalStrings.UpdateConcurrencyException(1, 0); } }
38.807692
113
0.750248
[ "Apache-2.0" ]
Mattlk13/EntityFramework
src/Microsoft.EntityFrameworkCore.Relational.Specification.Tests/UpdatesRelationalTestBase.cs
1,011
C#
using FrameworkTester.ViewModels.Interfaces; using GalaSoft.MvvmLight.Command; namespace FrameworkTester.DesignTimes { public sealed class WinBioLocateSensorWithCallbackViewModel : WinBioViewModel, IWinBioLocateSensorWithCallbackViewModel, IWinBioAsyncSessionViewModel { public RelayCommand CancelCommand { get; } public bool EnableWait { get; set; } public uint UnitId { get; } public IHandleRepositoryViewModel<ISessionHandleViewModel> HandleRepository { get; } } }
20.484848
154
0.585799
[ "MIT" ]
poseidonjm/WinBiometricDotNet
examples/FrameworkTester/DesignTimes/WinBioLocateSensorWithCallbackViewModel.cs
678
C#
using System; using System.Threading.Tasks; namespace Chroomsoft.Queries.Tests { public class TestQueryHandler : IQueryHandler<TestQuery, Guid> { private readonly Guid guid; public TestQueryHandler(Guid guid) { this.guid = guid; } public Task<Guid> HandleAsync(TestQuery query) { return Task.FromResult(guid); } } }
20.55
66
0.603406
[ "MIT" ]
rneeft/patterns
src/Queries/Tests/TestQueryHandler.cs
413
C#
using System; using System.Collections.Generic; namespace QSWidgetLib { public static class CommonValues { public static Dictionary<string, string> Ownerships = new Dictionary<string, string> { {"ООО", "Общество с ограниченной ответственностью"}, {"ЗАО", "Закрытое акционерное общество"}, {"ОАО", "Открытое акционерное общество"}, {"ГорПО", "Городское потребительское общество"}, {"РайПО", "Районное потребительское общество"}, {"СельПО", "Сельское потребительское общество"}, {"НКО", "Некоммерческая организация"}, {"ИП", "Индивидуальный предприниматель"}, {"ОДО", "Общество с дополнительной ответственностью"}, {"ПТ", "Полное товарищество"}, {"АО", "Акционерное общество"}, {"КТ", "Коммандитное товарищество"}, {"ХП", "Хозяйственное партнерство"}, {"КФХ", "Крестьянское (фермерское) хозяйство"}, {"НП", "Некоммерческое партнерство"}, {"ПК", "Потребительский кооператив"}, {"ТСН", "Товарищество собственников недвижимости"}, {"АНО", "Автономная некоммерческая организация"}, {"ФГУП", "Федеральное государственное унитарное предприятие"}, {"ГУП", "Государственное унитарное предприятие"}, {"МУП", "Муниципальное унитарное предприятие"}, {"ГП", "Государственное предприятие"}, {"СНТ", "Садоводческое некоммерческое товарищество"}, {"ДНТ", "Дачное некоммерческое товарищество"}, {"ОНТ", "Огородническое некоммерческое товарищество"}, {"СНП", "Садоводческое некоммерческое партнерство"}, {"ДНП", "Дачное некоммерческое партнерство"}, {"ОНП", "Огородническое некоммерческое партнерство"}, {"СПК", "Садоводческий потребительский кооператив"}, {"ДПК", "Дачный потребительский кооператив"}, {"ОПК", "Огороднический потребительский кооператив"} }; } }
38.844444
88
0.70595
[ "Apache-2.0" ]
Art8m/QSProjects
QSWidgetLib/CommonValues.cs
2,826
C#
using FluentAssertions; using Xunit; namespace CSharpFunctionalExtensions.Tests.MaybeTests { public class ExtensionsTests { [Fact] public void Unwrap_extracts_value_if_not_null() { var instance = new MyClass(); Maybe<MyClass> maybe = instance; MyClass myClass = maybe.Unwrap(); myClass.Should().Be(instance); } [Fact] public void Unwrap_extracts_null_if_no_value() { Maybe<MyClass> maybe = null; MyClass myClass = maybe.Unwrap(); myClass.Should().BeNull(); } [Fact] public void Can_use_selector_in_Unwrap() { Maybe<MyClass> maybe = new MyClass { Property = "Some value" }; string value = maybe.Unwrap(x => x.Property); value.Should().Be("Some value"); } [Fact] public void Can_use_default_value_in_Unwrap() { Maybe<string> maybe = null; string value = maybe.Unwrap(""); value.Should().Be(""); } [Fact] public void ToResult_returns_success_if_value_exists() { var instance = new MyClass(); Maybe<MyClass> maybe = instance; Result<MyClass> result = maybe.ToResult("Error"); result.IsSuccess.Should().BeTrue(); result.Value.Should().Be(instance); } [Fact] public void ToResult_returns_failure_if_no_value() { Maybe<MyClass> maybe = null; Result<MyClass> result = maybe.ToResult("Error"); result.IsSuccess.Should().BeFalse(); result.Error.Should().Be("Error"); } [Fact] public void ToResult_with_custom_error_type_returns_success_if_value_exists() { var instance = new MyClass(); Maybe<MyClass> maybe = instance; Result<MyClass, MyErrorClass> result = maybe.ToResult(new MyErrorClass()); result.IsSuccess.Should().BeTrue(); result.Value.Should().Be(instance); } [Fact] public void ToResult_with_custom_error_type_returns_custom_failure_if_no_value() { Maybe<MyClass> maybe = null; var errorInstance = new MyErrorClass(); Result<MyClass, MyErrorClass> result = maybe.ToResult(errorInstance); result.IsSuccess.Should().BeFalse(); result.Error.Should().Be(errorInstance); } [Fact] public void Where_returns_value_if_predicate_returns_true() { var instance = new MyClass { Property = "Some value" }; Maybe<MyClass> maybe = instance; Maybe<MyClass> maybe2 = maybe.Where(x => x.Property == "Some value"); maybe2.HasValue.Should().BeTrue(); maybe2.Value.Should().Be(instance); } [Fact] public void Where_returns_no_value_if_predicate_returns_false() { var instance = new MyClass { Property = "Some value" }; Maybe<MyClass> maybe = instance; Maybe<MyClass> maybe2 = maybe.Where(x => x.Property == "Different value"); maybe2.HasValue.Should().BeFalse(); } [Fact] public void Where_returns_no_value_if_initial_maybe_is_null() { Maybe<MyClass> maybe = null; Maybe<MyClass> maybe2 = maybe.Where(x => x.Property == "Some value"); maybe2.HasValue.Should().BeFalse(); } [Fact] public void Select_returns_new_maybe() { Maybe<MyClass> maybe = new MyClass { Property = "Some value" }; Maybe<string> maybe2 = maybe.Select(x => x.Property); maybe2.HasValue.Should().BeTrue(); maybe2.Value.Should().Be("Some value"); } [Fact] public void Select_returns_no_value_if_no_value_passed_in() { Maybe<MyClass> maybe = null; Maybe<string> maybe2 = maybe.Select(x => x.Property); maybe2.HasValue.Should().BeFalse(); } [Fact] public void Bind_returns_new_maybe() { Maybe<MyClass> maybe = new MyClass { Property = "Some value" }; Maybe<string> maybe2 = maybe.Select(x => GetPropertyIfExists(x)); maybe2.HasValue.Should().BeTrue(); maybe2.Value.Should().Be("Some value"); } [Fact] public void Bind_returns_no_value_if_internal_method_returns_no_value() { Maybe<MyClass> maybe = new MyClass { Property = null }; Maybe<string> maybe2 = maybe.Select(x => GetPropertyIfExists(x)); maybe2.HasValue.Should().BeFalse(); } [Fact] public void Execute_executes_action() { string property = null; Maybe<MyClass> maybe = new MyClass { Property = "Some value" }; maybe.Execute(x => property = x.Property); property.Should().Be("Some value"); } [Fact] public void Unwrap_supports_NET_value_types() { Maybe<MyClass> maybe = new MyClass { IntProperty = 42 }; int integer = maybe.Select(x => x.IntProperty).Unwrap(); integer.Should().Be(42); } [Fact] public void Unwrap_returns_default_for_NET_value_types() { Maybe<MyClass> maybe = null; int integer = maybe.Select(x => x.IntProperty).Unwrap(); integer.Should().Be(0); } private static Maybe<string> GetPropertyIfExists(MyClass myClass) { return myClass.Property; } private class MyClass { public string Property { get; set; } public int IntProperty { get; set; } } private class MyErrorClass { } } }
27.0181
88
0.553676
[ "MIT" ]
CarlHA/CSharpFunctionalExtensions
CSharpFunctionalExtensions.Tests/MaybeTests/ExtensionsTests.cs
5,973
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace TrellisControl { public static class ExtensionMethods { public static bool IsNullWhitespaceOrEmpty(this string target) { return string.IsNullOrEmpty(target) || string.IsNullOrWhiteSpace(target); } public static void ToolStripStatusInvokeAction<TControlType>(this TControlType control, Action<TControlType> del) where TControlType : ToolStripStatusLabel { if (control.GetCurrentParent().InvokeRequired) control.GetCurrentParent().Invoke(new Action(() => del(control))); else del(control); } } }
29
121
0.673052
[ "MIT" ]
kfechter/TrellisControl
TrellisControl/ExtensionMethods.cs
785
C#
using System.Collections.Generic; using System.ComponentModel; using System.Runtime.CompilerServices; using System.Text.RegularExpressions; using System.Windows; using System.Windows.Controls; namespace IPUserControls { /// <summary> /// Interaction logic for IpPort.xaml /// </summary> public partial class IpPort : INotifyPropertyChanged { public IpPort() { InitializeComponent(); } // Exposed Properties // -------------------------------------- public ushort PortNumber { get => (ushort)GetValue(PortNumberProperty); set { SetValue(PortNumberProperty, value); OnPropertyChanged(); } } public static readonly DependencyProperty PortNumberProperty = DependencyProperty.Register ( "PortNumber", typeof(ushort), typeof(IpPort), new FrameworkPropertyMetadata ( ushort.MinValue, new PropertyChangedCallback(PortNumberChangedCallback) ) {BindsTwoWayByDefault = true}); // Event Handlers // -------------------------------------- private static void PortNumberChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e) { var Uc = (IpPort) d; Uc.PortNumber = (ushort)e.NewValue; } private void PortNumber_TextChanged(object sender, TextChangedEventArgs e) { if (PortNrTextBox.Text == PortNumber.ToString()) return; if (PortNrTextBox.Text == "") { PortNumber = 0; PortNrTextBox.Text = 0.ToString(); PortNrTextBox.SelectAll(); return; } if (!PortNrTextBox.Text.IsUShort()) PortNrTextBox.Text = PortNumber.ToString(); else { PortNumber = ushort.Parse(PortNrTextBox.Text); PortNrTextBox.Text = PortNumber.ToString(); } } private void PortNrTextBox_GotKeyboardFocus(object sender, System.Windows.Input.KeyboardFocusChangedEventArgs e) => PortNrTextBox.SelectAll(); #region Property Notifications public event PropertyChangedEventHandler PropertyChanged; protected void OnPropertyChanged([CallerMemberName] string propertyName = null) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } protected bool SetProperty<T>(ref T field, T value, [CallerMemberName] string propertyName = null) { if (EqualityComparer<T>.Default.Equals(field, value)) return false; field = value; OnPropertyChanged(propertyName); return true; } #endregion Property Notifications } }
31.468085
150
0.570994
[ "MIT" ]
mariugul/IPUserControls
IPUserControls/IpPort.xaml.cs
2,960
C#
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using Microsoft.CloudMine.Core.Collectors.Cache; using Microsoft.CloudMine.Core.Collectors.Telemetry; using System; using System.Collections.Generic; using System.Threading.Tasks; namespace Microsoft.CloudMine.Core.Collectors.Collector { public abstract class CachingCollector<TCollectionNode, TEndpointProgressTableEntity> where TCollectionNode : CollectionNode where TEndpointProgressTableEntity : ProgressTableEntity { private readonly CollectorBase<TCollectionNode> collector; private readonly ITelemetryClient telemetryClient; private readonly List<Exception> exceptions; public Exception Exception { get; private set; } public CachingCollector(CollectorBase<TCollectionNode> collector, ITelemetryClient telemetryClient) { this.collector = collector; this.telemetryClient = telemetryClient; this.exceptions = new List<Exception>(); } public async Task<bool> ProcessAndCacheAsync(TCollectionNode collectionNode, TEndpointProgressTableEntity progressRecord, bool ignoreCache, bool scheduledCollection) { if (!ignoreCache && !scheduledCollection) { // If ignoreCache == true, then skip cache check and force (re-)collection. // If scheduledCollection == true, then skip cache check (no need since by design there should not be any cache entry for it) and force collection. TEndpointProgressTableEntity cachedProgressRecord = await this.RetrieveAsync(progressRecord).ConfigureAwait(false); if (cachedProgressRecord != null && cachedProgressRecord.Succeeded) { // If the cache includes the progress record and record.Succeeded is true, skip re-collection since this endpoint was previously collected successfully. Dictionary<string, string> properties = new Dictionary<string, string>() { { "ApiName", collectionNode.ApiName }, { "RecordType", collectionNode.RecordType }, }; this.telemetryClient.TrackEvent("SkippedCollection", properties); return true; } } progressRecord.Succeeded = false; try { await this.collector.ProcessAsync(collectionNode).ConfigureAwait(false); progressRecord.Succeeded = true; await this.CacheAsync(progressRecord).ConfigureAwait(false); return true; } catch (Exception exception) { this.Exception = exception; this.exceptions.Add(exception); this.telemetryClient.TrackException(exception, $"Failed to process and cache endpoint '{collectionNode.ApiName}'."); await this.CacheAsync(progressRecord).ConfigureAwait(false); return false; } } protected abstract Task<TEndpointProgressTableEntity> RetrieveAsync(TEndpointProgressTableEntity progressRecord); protected abstract Task CacheAsync(TEndpointProgressTableEntity progressRecord); public void FinalizeCollection() { if (this.exceptions.Count == 0) { return; } throw new AggregateException(this.exceptions); } } }
43.759036
173
0.626101
[ "MIT" ]
microsoft/CEDAR.Core.Collector
Core.Collectors/Collector/CachingCollector.cs
3,634
C#
// ReSharper disable All namespace OpenTl.Schema.Messages { using System; using System.Collections; using OpenTl.Schema; public interface IStickers : IObject { } }
12.466667
40
0.68984
[ "MIT" ]
zzz8415/OpenTl.Schema
src/OpenTl.Schema/_generated/Messages/Stickers/IStickers.cs
189
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. // LICENSE: https://github.com/dotnet/wpf/blob/main/LICENSE.TXT using System; using System.Windows; using System.Windows.Media; namespace FullControls.Core.Services { internal static class DpiHelper { [ThreadStatic] private static Matrix _transformToDevice; [ThreadStatic] private static Matrix _transformToDip; /// <summary> /// Convert a point in device independent pixels (1/96") to a point in the system coordinates. /// </summary> /// <param name="logicalPoint">A point in the logical coordinate system.</param> /// <param name="dpiScaleX"></param> /// <param name="dpiScaleY"></param> /// <returns>Returns the parameter converted to the system's coordinates.</returns> internal static Point LogicalPixelsToDevice(Point logicalPoint, double dpiScaleX, double dpiScaleY) { _transformToDevice = Matrix.Identity; _transformToDevice.Scale(dpiScaleX, dpiScaleY); return _transformToDevice.Transform(logicalPoint); } /// <summary> /// Convert a point in system coordinates to a point in device independent pixels (1/96"). /// </summary> /// <param name="devicePoint">A point in the physical coordinate system.</param> /// <param name="dpiScaleX"></param> /// <param name="dpiScaleY"></param> /// <returns>Returns the parameter converted to the device independent coordinate system.</returns> internal static Point DevicePixelsToLogical(Point devicePoint, double dpiScaleX, double dpiScaleY) { _transformToDip = Matrix.Identity; _transformToDip.Scale(1d / dpiScaleX, 1d / dpiScaleY); return _transformToDip.Transform(devicePoint); } internal static Rect LogicalRectToDevice(Rect logicalRectangle, double dpiScaleX, double dpiScaleY) { Point topLeft = LogicalPixelsToDevice(new Point(logicalRectangle.Left, logicalRectangle.Top), dpiScaleX, dpiScaleY); Point bottomRight = LogicalPixelsToDevice(new Point(logicalRectangle.Right, logicalRectangle.Bottom), dpiScaleX, dpiScaleY); return new Rect(topLeft, bottomRight); } internal static Rect DeviceRectToLogical(Rect deviceRectangle, double dpiScaleX, double dpiScaleY) { Point topLeft = DevicePixelsToLogical(new Point(deviceRectangle.Left, deviceRectangle.Top), dpiScaleX, dpiScaleY); Point bottomRight = DevicePixelsToLogical(new Point(deviceRectangle.Right, deviceRectangle.Bottom), dpiScaleX, dpiScaleY); return new Rect(topLeft, bottomRight); } internal static Size LogicalSizeToDevice(Size logicalSize, double dpiScaleX, double dpiScaleY) { Point pt = LogicalPixelsToDevice(new Point(logicalSize.Width, logicalSize.Height), dpiScaleX, dpiScaleY); return new Size { Width = pt.X, Height = pt.Y }; } internal static Size DeviceSizeToLogical(Size deviceSize, double dpiScaleX, double dpiScaleY) { Point pt = DevicePixelsToLogical(new Point(deviceSize.Width, deviceSize.Height), dpiScaleX, dpiScaleY); return new Size(pt.X, pt.Y); } internal static Thickness LogicalThicknessToDevice(Thickness logicalThickness, double dpiScaleX, double dpiScaleY) { Point topLeft = LogicalPixelsToDevice(new Point(logicalThickness.Left, logicalThickness.Top), dpiScaleX, dpiScaleY); Point bottomRight = LogicalPixelsToDevice(new Point(logicalThickness.Right, logicalThickness.Bottom), dpiScaleX, dpiScaleY); return new Thickness(topLeft.X, topLeft.Y, bottomRight.X, bottomRight.Y); } } }
46.395349
136
0.683208
[ "MIT" ]
devpelux/fullcontrols
FullControls/Core/Services/DpiHelper.cs
3,992
C#
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="AboutDialog.xaml.cs" company="Chris Dziemborowicz"> // Copyright (c) Chris Dziemborowicz. All rights reserved. // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Hourglass.Windows { using System; using System.Diagnostics; using System.Windows; using System.Windows.Navigation; using Hourglass.Managers; /// <summary> /// A window that displays information about the app. /// </summary> public partial class AboutDialog { /// <summary> /// The instance of the <see cref="AboutDialog"/> that is showing, or null if there is no instance showing. /// </summary> private static AboutDialog instance; /// <summary> /// Initializes a new instance of the <see cref="AboutDialog"/> class. /// </summary> public AboutDialog() { this.InitializeComponent(); this.InitializeMaxSize(); } /// <summary> /// A string describing the app's copyright. /// </summary> public static string Copyright { get { // Finds the copyright line in the license string. Perhaps overkill, but doing it this way means there's // one less place to update the copyright notice. string[] lines = License.Split('\r', '\n'); foreach (string line in lines) { if (line.StartsWith("Copyright")) { return line; } } throw new Exception("Could not find copyright line in license."); } } /// <summary> /// A string containing the app's license. /// </summary> public static string License => Properties.Resources.License; /// <summary> /// A string describing the app's version. /// </summary> public static string Version { get { Version version = UpdateManager.Instance.CurrentVersion; if (version.Revision != 0) { return version.ToString(); } else if (version.Build != 0) { return version.ToString(3 /* fieldCount */); } else { return version.ToString(2 /* fieldCount */); } } } /// <summary> /// Shows or activates the <see cref="AboutDialog"/>. Call this method instead of the constructor to prevent /// multiple instances of the dialog. /// </summary> public static void ShowOrActivate() { if (AboutDialog.instance == null) { AboutDialog.instance = new AboutDialog(); AboutDialog.instance.Show(); } else { AboutDialog.instance.Activate(); } } /// <summary> /// Initializes the <see cref="Window.MaxWidth"/> and <see cref="Window.MaxHeight"/> properties. /// </summary> private void InitializeMaxSize() { this.MaxWidth = 0.75 * SystemParameters.WorkArea.Width; this.MaxHeight = 0.75 * SystemParameters.WorkArea.Height; } /// <summary> /// Invoked when the about dialog is closed. /// </summary> /// <param name="sender">The about dialog.</param> /// <param name="e">The event data.</param> private void AboutDialogClosed(object sender, EventArgs e) { AboutDialog.instance = null; } /// <summary> /// Invoked when navigation events are requested. /// </summary> /// <param name="sender">The hyperlink requesting navigation.</param> /// <param name="e">The event data.</param> private void HyperlinkRequestNavigate(object sender, RequestNavigateEventArgs e) { if (e.Uri.Scheme != "https") { throw new ArgumentException(); } Process.Start(e.Uri.ToString()); } /// <summary> /// Invoked when the close button is clicked. /// </summary> /// <param name="sender">The close button.</param> /// <param name="e">The event data.</param> private void CloseButtonClick(object sender, RoutedEventArgs e) { this.Close(); } } }
32.601351
120
0.484767
[ "MIT" ]
BeReasonable/hourglass
Hourglass/Windows/AboutDialog.xaml.cs
4,827
C#
namespace PeterPedia.Services; public interface ITheMovieDatabaseService { Task<string> GetImageUrlAsync(string? path, string size = "w185"); Task<TMDbMovie?> GetMovieAsync(int id, string? etag); Task<TMDbShow?> GetTvShowAsync(int id, string? etag); }
24.272727
70
0.741573
[ "MIT" ]
peter-andersson/PeterPedia
src/PeterPedia.Services/Interface/ITheMovieDatabaseService.cs
267
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.AI; // This script will be attached to a Procedural Generation object in scenes that want a // random distribution of items - a forest with randomly placed trees for example. Also // supports placement of items at a constant y offset - like a level with platforms overhead public class RandomMapMaker : MonoBehaviour { // public vars public GameObject player; // the player object to instantiate public GameObject reticle; // onscreen representation of the mouse public GameObject[] npcs; // list of the NPC characters we could instantiate public GameObject[] floor; // list of floor prefabs public GameObject[] groundItems; // list of grounded item prefabs public GameObject[] inAirItems; // list of items with the given y offset public float groundItemProb; // probability of placing a grounded item public float inAirItemProb; // probability of placing an item in air public float minScaling; // minScaling possible tileSize multiplier public float maxScaling; // highest possible tileSize multiplier public int mapWidth; // width of map in number of floor tiles public int mapHeight; // height of map in number of floor tiles public float tileSize; // tileSize of one side of square floor patch public float yOffset; // distance inAirItems are off the ground public bool shouldStack; // true if in air items can go on top of ground items // private vars GameObject[,] mapFloor; // type of floor to place in room GameObject[,] mapItems; // whether and where to place items on the ground GameObject[,] mapInAirItems; // whether and where to place in air items Vector3 mapCenter; // position of center of map // Use this for initialization void Start() { // initialize variables if (tileSize == 0f) tileSize = 3.2f; // assume this size if none given mapCenter = new Vector3(mapWidth * tileSize / 2, 1f, mapHeight * tileSize / 2); // call functions to lay out a 2D array representation of the map, // instantiate the environment layoutMap(); fillMap(); // with the scene complete, put in NPCs placeNpcs(); // place the player at the center of the room and add the crosshairs to the screen Instantiate(player, mapCenter, Quaternion.identity); Instantiate(reticle); } // Figure out where floor and items should go in world void layoutMap() { // initialize the tileSize of the map mapFloor = new GameObject[mapWidth, mapHeight]; mapItems = new GameObject[mapWidth, mapHeight]; mapInAirItems = new GameObject[mapWidth, mapHeight]; // fill in the arrays with patches of grass and possibly trees for (int i = 0; i < mapWidth; i++) for (int j = 0; j < mapHeight; j++) { // tiles for the floor mapFloor[i, j] = floor[Random.Range(0, floor.GetLength(0))]; // add grounded items according to density if (Random.value < groundItemProb) mapItems[i, j] = groundItems[Random.Range(0, groundItems.GetLength(0))]; else mapItems[i, j] = null; // add in air items according to density, stacking over grounded items if allowed if (Random.value < inAirItemProb) { mapInAirItems[i, j] = inAirItems[Random.Range(0, inAirItems.GetLength(0))]; if (!shouldStack && mapItems[i, j] != null) mapInAirItems[i, j] = null; } else mapInAirItems[i, j] = null; } } // Lay down the floors and items in the world void fillMap() { // go through arrays and place floor/items as they're written // adjust position according to i, j multiplied by the tileSize for (int i = 0; i < mapWidth; i++) for (int j = 0; j < mapHeight; j++) { // get prefabs to be placed GameObject floorObj = mapFloor[i, j]; GameObject groundItemObj = mapItems[i, j]; GameObject inAirItemObj = mapInAirItems[i, j]; // create floor instances and space according to tile size Instantiate(floorObj, new Vector3(i * tileSize, 0.0f, j * tileSize), Quaternion.identity); // place ground items if they're not null - scale and position properly if (groundItemObj != null) { float scale = Random.Range(minScaling, maxScaling); Vector3 scaling = new Vector3(scale, scale, scale); GameObject t = Instantiate(groundItemObj, new Vector3(i * tileSize, groundItemObj.transform.position.y, j * tileSize), Quaternion.identity); t.transform.localScale += scaling; } // place in air items if not null if (inAirItemObj != null) Instantiate(inAirItemObj, new Vector3(i * tileSize, yOffset + inAirItemObj.transform.position.y, j * tileSize), Quaternion.identity); } } // put down NPCs at some random locations in the room void placeNpcs() { // go through each of the NPCs attached to the script and randomly instantiate them foreach (GameObject npc in npcs) { float xbound = (mapWidth - 1) * tileSize; float ybound = (mapHeight - 1) * tileSize; Instantiate(npc, new Vector3(Random.Range(0f, xbound), 0f, Random.Range(0f, ybound)), Quaternion.identity); } } // create the NavMesh at run time after map is generated void bakeNavMesh() { // lots of BS about the scene that will need editing at some point I'm sure Bounds b = new Bounds(mapCenter, mapCenter + new Vector3(0f, 10f, 0f)); List<NavMeshBuildSource> sources = new List<NavMeshBuildSource>(); List<NavMeshBuildMarkup> markups = new List<NavMeshBuildMarkup>(); NavMeshBuilder.CollectSources(b, 0, NavMeshCollectGeometry.RenderMeshes, 0, markups, sources); NavMeshBuildSettings settings = NavMesh.CreateSettings(); // here's the actual important line NavMeshBuilder.BuildNavMeshData(settings, sources, b, mapCenter, Quaternion.identity); } }
46.3
103
0.589633
[ "MIT" ]
Donut-Studios/Unity3D-AI-and-Procedural-Generation-Framework
src/Procedural Generation/RandomMapMaker.cs
6,947
C#
using System.Collections.Generic; using System.Linq; using DataTanker.Versioning; namespace Tests.Emulation { public class SnapshotData : ISnapshotData { private readonly List<int> _rolledBackTransactions; private readonly List<int> _commitedTransactions; public bool IsComittedTransaction(int number) { return _commitedTransactions.Contains(number); } public bool IsRolledBackTransaction(int number) { return _rolledBackTransactions.Contains(number); } public SnapshotData(IEnumerable<int> commitedTransactions) { _commitedTransactions = commitedTransactions.ToList(); _rolledBackTransactions = new List<int>(); } public SnapshotData(IEnumerable<int> commitedTransactions, IEnumerable<int> rolledBackTransactions) { _rolledBackTransactions = rolledBackTransactions.ToList(); _commitedTransactions = commitedTransactions.ToList(); } } }
29.685714
107
0.673725
[ "MIT" ]
VictorScherbakov/DataTanker
DataTanker/Tests/Unit/Emulation/SnapshotData.cs
1,039
C#
using System; namespace BlazorGenUI.Tests.testdtos { public class TestPrimitiveDto { public string Name { get; set; } public bool IsFestival { get; set; } public DateTime Date { get; set; } public DateTimeOffset DateOffset { get; set; } public Single SingleNumber { get; set; } public float FloatNumber { get; set; } public double DoubleNumber { get; set; } public decimal DecimalNumber { get; set; } public int IntNumber { get; set; } public EnumType MyEnum { get; set; } } }
27.285714
54
0.609075
[ "MIT" ]
Elders/blazorgenui
tests/RenderableContentTests/TestDtos/TestPrimitiveDto.cs
575
C#
#region Apache License Version 2.0 /*---------------------------------------------------------------- Copyright 2022 Jeffrey Su & Suzhou Senparc Network Technology Co.,Ltd. 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. Detail: https://github.com/JeffreySu/WeiXinMPSDK/blob/master/license.md ----------------------------------------------------------------*/ #endregion Apache License Version 2.0 /*---------------------------------------------------------------- Copyright (C) 2022 Senparc 文件名:CheckRequestHandler.cs 文件功能描述:对账单下载接口 创建标识:Senparc - 20150211 修改标识:Senparc - 20150303 修改描述:整理接口 ----------------------------------------------------------------*/ using System.Collections; using System.Text; using Senparc.CO2NET.Helpers; #if NET462 using System.Web; #else using Microsoft.AspNetCore.Http; #endif namespace Senparc.Weixin.TenPay.V2 { public class CheckRequestHandler : ClientRequestHandler { /// <summary> /// 对账单下载接口 /// </summary> /// <param name="httpContext"></param> public CheckRequestHandler(HttpContext httpContext) : base(httpContext) { this.SetGateUrl("http://mch.tenpay.com/cgi-bin/mchdown_real_new.cgi"); } protected override void CreateSign() { StringBuilder sb = new StringBuilder(); ArrayList akeys = new ArrayList(); akeys.Add("spid"); akeys.Add("trans_time"); akeys.Add("stamp"); akeys.Add("cft_signtype"); akeys.Add("mchtype"); foreach (string k in akeys) { string v = (string)Parameters[k]; if (null != v && "".CompareTo(v) != 0 && "sign".CompareTo(k) != 0 && "key".CompareTo(k) != 0) { sb.Append(k + "=" + v + "&"); } } sb.Append("key=" + this.GetKey()); string sign = EncryptHelper.GetMD5(sb.ToString(), GetCharset()).ToLower(); this.SetParameter("sign", sign); //debug信息 this.SetDebugInfo(sb.ToString() + " => sign:" + sign); } } }
28.712766
90
0.544276
[ "Apache-2.0" ]
AaronWu666/WeiXinMPSDK
src/Senparc.Weixin.TenPay/Senparc.Weixin.TenPay/V2/CheckRequestHandler.cs
2,793
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.md file in the project root for more information. using Moq; namespace Microsoft.VisualStudio.ProjectSystem { internal static class IUnconfiguredProjectCommonServicesFactory { public static IUnconfiguredProjectCommonServices Create(UnconfiguredProject? project = null, IProjectThreadingService? threadingService = null, ConfiguredProject? configuredProject = null, ProjectProperties? projectProperties = null, IProjectAccessor? projectAccessor = null) { var mock = new Mock<IUnconfiguredProjectCommonServices>(); if (project != null) mock.Setup(s => s.Project) .Returns(project); if (threadingService != null) mock.Setup(s => s.ThreadingService) .Returns(threadingService); if (configuredProject != null) mock.Setup(s => s.ActiveConfiguredProject) .Returns(configuredProject); if (projectProperties != null) mock.Setup(s => s.ActiveConfiguredProjectProperties) .Returns(projectProperties); if (projectAccessor != null) mock.Setup(s => s.ProjectAccessor) .Returns(projectAccessor); return mock.Object; } } }
41.846154
201
0.568627
[ "MIT" ]
77-A/.Net-Project
tests/Microsoft.VisualStudio.ProjectSystem.Managed.UnitTests/Mocks/IUnconfiguredProjectCommonServicesFactory.cs
1,596
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; using Es.InkPainter; [RequireComponent(typeof(InkCanvas))] public class Wave : MonoBehaviour { public Material waveMaterial; private Texture2D init; private RenderTexture input; private RenderTexture prev; private RenderTexture prev2; private RenderTexture result; private new Renderer renderer; [Range(1, 10)] public int updateFrameTiming = 3; public bool debug; void Start () { GetComponent<InkCanvas>().OnInitializedAfter += canvas => { // initialize for setting up Textures init = new Texture2D(1, 1); init.SetPixel(0, 0, new Color(0, 0, 0, 0)); init.Apply(); input = canvas.GetPaintMainTexture("Reflect Plane"); prev = new RenderTexture(input.width, input.height, 0, RenderTextureFormat.R8); prev2 = new RenderTexture(input.width, input.height, 0, RenderTextureFormat.R8); result = new RenderTexture(input.width, input.height, 0, RenderTextureFormat.R8); // brush var r8Init = new Texture2D(1, 1); r8Init.SetPixel(0, 0, new Color(0.5f, 0, 0, 1)); r8Init.Apply(); Graphics.Blit(r8Init, prev); Graphics.Blit(r8Init, prev2); }; renderer = GetComponent<Renderer>(); } private void OnWillRenderObject() { UpdateWave(); } void UpdateWave () { if (Time.frameCount % updateFrameTiming != 0 || input == null) return; waveMaterial.SetTexture("_InputTex", input); waveMaterial.SetTexture("_PrevTex", prev); waveMaterial.SetTexture("_Prev2Tex", prev2); // Store formula result to result tex Graphics.Blit(null, result, waveMaterial); // update prev var tmp = prev2; prev2 = prev; prev = result; result = tmp; // update to renderer Graphics.Blit(init, input); renderer.sharedMaterial.SetTexture("_WaveTex", prev); } private void OnGUI() { if (debug) { var h = Screen.height / 3; const int StrWidth = 20; GUI.Box(new Rect(0, 0, h, h * 3), ""); GUI.DrawTexture(new Rect(0, 0 * h, h, h), Texture2D.whiteTexture); GUI.DrawTexture(new Rect(0, 0 * h, h, h), input); GUI.DrawTexture(new Rect(0, 1 * h, h, h), prev); GUI.DrawTexture(new Rect(0, 2 * h, h, h), prev2); GUI.Box(new Rect(0, 1 * h - StrWidth, h, StrWidth), "INPUT"); GUI.Box(new Rect(0, 2 * h - StrWidth, h, StrWidth), "PREV"); GUI.Box(new Rect(0, 3 * h - StrWidth, h, StrWidth), "PREV2"); } } }
29.606383
92
0.577434
[ "MIT" ]
yanagiragi/Unity_Shader_Learn
Assets/Resources/Es Wave Shader/Scripts/Wave.cs
2,785
C#
using System; using System.Collections.Generic; using System.Linq; namespace Neutronium.Example.ViewModel { public class FakeViewModel { private static readonly Random Random = new Random(); public FakeViewModel[] Children { get; } public int One => 1; public int Two => 2; public int RandomNumber { get; } private static int _Count = 0; public FakeViewModel(IEnumerable<FakeViewModel> children = null ) { _Count++; RandomNumber = Random.Next(); Children = children?.ToArray(); } } }
22.592593
73
0.598361
[ "MIT" ]
David-Desmaisons/MVVM.CEF.Glue
Examples/Neutronium.Example.ViewModel/FakeViewModel.cs
612
C#
using System; using System.Linq; namespace Nikulden_s_Charity { class Program { static void Main(string[] args) { string text = Console.ReadLine(); string input = Console.ReadLine(); while (input != "Finish") { string[] commands = input.Split().ToArray(); if (commands.Contains("Replace")) { char currentChar = char.Parse(commands[1]); char newChar = char.Parse(commands[2]); text = text.Replace(currentChar, newChar); Console.WriteLine(text); } else if (commands.Contains("Cut")) { int startIndex = int.Parse(commands[1]); int endIndex = int.Parse(commands[2]); if (startIndex > 0 && startIndex < text.Length && endIndex > 0 && endIndex < text.Length) { text = text.Remove(startIndex, endIndex); Console.WriteLine(text); } else { Console.WriteLine("Invalid indexes!"); } } else if (commands.Contains("Make")) { if (commands[1] == "Upper") { text = text.ToUpper(); Console.WriteLine(text); } else if (commands[1] == "Lower") { text = text.ToLower(); Console.WriteLine(text); } } else if (commands.Contains("Check")) { string strings = commands[1]; if (text.Contains(strings)) { Console.WriteLine($"Message contains {strings}"); } else { Console.WriteLine($"Message doesn't contain {strings}"); } } else if (commands.Contains("Sum")) { int startIndex = int.Parse(commands[1]); int endIndex = int.Parse(commands[2]); if (startIndex > 0 && startIndex < text.Length && endIndex > 0 && endIndex < text.Length) { string substring = text.Substring(startIndex, endIndex); int value = 0; for (int i = 0; i < substring.Length; i++) { char current = substring[i]; value += (int)(current); } Console.WriteLine(value); } else { Console.WriteLine("Invalid indexes!"); } } input = Console.ReadLine(); } } } }
33.0625
109
0.370825
[ "MIT" ]
martinsivanov/CSharp-Fundamentals---May-2020
Exams/Programming Fundamentals Final Exam - 07 December 2019 Group 2/Nikulden's Charity/Program.cs
3,176
C#
using Avalonia.Controls; using Avalonia.Controls.Templates; using System; using System.Collections.Generic; using System.Text; using System.Windows.Input; namespace Mechanism.AvaloniaUI.Controls { public interface IToolStripItem { IControlTemplate Template { get; set; } string DisplayName { get; set; } bool AllowDuplicates { get; set; } ToolStrip Owner { get; set; } } }
20.095238
47
0.691943
[ "MIT" ]
Splitwirez/Mechanism-for-Avalonia
Mechanism.AvaloniaUI.Controls/Controls/ToolStrip/IToolStripItem.cs
424
C#
using Kasa.Vchasno.Client; using Kasa.Vchasno.Client.Models; using Kasa.Vchasno.Client.Models.Requests; using Kasa.Vchasno.Client.Models.Responses; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Options; using Moq; using RichardSzalay.MockHttp; using System.Collections.Generic; using System.Text.Json; using System.Threading.Tasks; using Xunit; namespace Vchasno.Client.Tests { public class SerializationTests { private static class TestData { public static IEnumerable<object[]> GetRequests() { var mock = new Mock<IOptionsSnapshot<VchasnoOptions>>(); mock.Setup(x => x.Value).Returns(new VchasnoOptions() { Token = "tokem", Device = "device", Source = "source" }); var f = new VchasnoRequesFactory(mock.Object); yield return new object[] { f.OpenShift() }; yield return new object[] { f.ServiceOut(new ServiceCash(100m)) }; yield return new object[] { f.ServiceIn(new ServiceCash(100m)) }; yield return new object[] { f.Return(new Receipt() { Pays = new List<ReceiptPayment>() { new ReceiptPayment(PaymentTypes.Cash,100), }, CommentDown = "CommentDown", CommentUp = "CommentUp", Round = 0m, Rows = new List<Good>() { new Good() { Code = "code", Code1 = "code1", Code2 = "code2", Code3 = "code3", CodeA = "codea", CodeAA = new []{"codeaa" }, Comment = "comment", Cost = 100, Count = 1, Discount = 0, Name = "name", Price = 100, TaxGroup = DefaultVchasnoTaxGroups.Without_VAT, } }, Sum = 100, }) }; yield return new object[] { f.Sale(new Receipt() { Pays = new List<ReceiptPayment>() { new ReceiptPayment(PaymentTypes.Cash,100), }, CommentDown = "CommentDown", CommentUp = "CommentUp", Round = 0m, Rows = new List<Good>() { new Good() { Code = "code", Code1 = "code1", Code2 = "code2", Code3 = "code3", CodeA = "codea", CodeAA = new []{"codeaa" }, Comment = "comment", Cost = 100, Count = 1, Discount = 0, Name = "name", Price = 100, TaxGroup = DefaultVchasnoTaxGroups.Without_VAT, } }, Sum = 100, }) }; yield return new object[] { f.XReport() }; yield return new object[] { f.ZReport() }; } } [Theory] [MemberData(nameof(TestData.GetRequests), MemberType = typeof(TestData))] public async Task Should_serialize_without_errors(Request request) { var url = "http://localhost:3939"; var data = new Response<BaseInfoResponse>(); var mockHttp = new MockHttpMessageHandler(); using var sp = new ServiceCollection() .AddVchasnoIntegration(new System.Uri(url), (o) => { o.Token = "token"; o.Device = "device"; o.Source = "service"; }).ConfigurePrimaryHttpMessageHandler(() => mockHttp) .Services.BuildServiceProvider(); var factory = sp.GetRequiredService<IVchasnoRequesFactory>(); var client = sp.GetRequiredService<IVchasnoHttpClient>(); var jsonOptions = sp.GetRequiredService<IJsonSerializerOptionsProvider>(); mockHttp.When($"{url}/dm/execute").Respond("application/json", JsonSerializer.Serialize(data, jsonOptions.Options)); var result = await client.CoreExecuteAsync<BaseInfoResponse>(request); Assert.NotNull(result); } } }
36.762963
128
0.434415
[ "MIT" ]
ramonesz297/Kasa.Vchasno
Kasa.Vchasno.Client.Tests/SerializationTests.cs
4,965
C#
using System; using System.Collections.Generic; using System.Text; using SAEA.Sockets.Interface; namespace SAEASocket.Custom { /// <summary> /// Header size is 8 bytes, store 4 data (each data is 2 byte(ushort)) /// CMD1 ushort /// DataSize ushort /// MainCmd ushort /// SubCmd ushort /// </summary> public class Unpacker : IUnpacker { public static int HeaderSize = 8; List<byte> _cache = new List<byte>(); public void Clear() { _cache.Clear(); } public void Unpack(byte[] data, Action<ISocketProtocal> unpackCallback, Action<DateTime> onHeart = null, Action<byte[]> onFile = null) { throw new NotImplementedException(); } public void Unpack(byte[] data, Action<Package> unpackCallBack) { _cache.AddRange(data); while (_cache.Count >= HeaderSize) { byte[] buffer = _cache.ToArray(); int messageLength = GetLength(buffer); if (buffer.Length >= messageLength) { Package myPackage = GetPackage(buffer, messageLength); _cache.RemoveRange(0, messageLength); unpackCallBack?.Invoke(myPackage); } else { return; } } } private int GetLength(byte[] data) { // the size store in the header is icluding the header size int dataSize = BitConverter.ToUInt16(data, 2); return dataSize; } private Package GetPackage(byte[] buffer, int length) { Package package = new Package(); package.CMD1 = BitConverter.ToUInt16(buffer, 0); package.MainKey = BitConverter.ToUInt16(buffer, 4); package.SubKey = BitConverter.ToUInt16(buffer, 6); package.Body = Encoding.UTF8.GetString(buffer, HeaderSize, length - HeaderSize); return package; } } }
31.462687
142
0.537951
[ "MIT" ]
cmwong/LearnSuperSocket
SocketServer/SAEASocket/Custom/Unpacker.cs
2,110
C#
using System; using Microsoft.VisualStudio.TestTools.UnitTesting; using System.Management.Automation.Runspaces; namespace PnP.PowerShell.Tests.Graph { [TestClass] public class ResetUnifiedGroupExpirationTests { #region Test Setup/CleanUp [ClassInitialize] public static void Initialize(TestContext testContext) { // This runs on class level once before all tests run //using (var ctx = TestCommon.CreateClientContext()) //{ //} } [ClassCleanup] public static void Cleanup(TestContext testContext) { // This runs on class level once //using (var ctx = TestCommon.CreateClientContext()) //{ //} } [TestInitialize] public void Initialize() { using (var scope = new PSTestScope()) { // Example // scope.ExecuteCommand("cmdlet", new CommandParameter("param1", prop)); } } [TestCleanup] public void Cleanup() { using (var scope = new PSTestScope()) { try { // Do Test Setup - Note, this runs PER test } catch (Exception) { // Describe Exception } } } #endregion #region Scaffolded Cmdlet Tests //TODO: This is a scaffold of the cmdlet - complete the unit test //[TestMethod] public void ResetPnPUnifiedGroupExpirationTest() { using (var scope = new PSTestScope(true)) { // Complete writing cmd parameters // This is a mandatory parameter // From Cmdlet Help: The Identity of the Office 365 Group var identity = ""; var results = scope.ExecuteCommand("Reset-PnPUnifiedGroupExpiration", new CommandParameter("Identity", identity)); Assert.IsNotNull(results); } } #endregion } }
27.679487
88
0.515053
[ "MIT" ]
AndersRask/powershell
src/Tests/Graph/ResetPnPUnifiedGroupExpirationTests.cs
2,159
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 1.0.1.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.Monitor.Management.Models { using Microsoft.Azure; using Microsoft.Azure.Management; using Microsoft.Azure.Management.Monitor; using Microsoft.Azure.Management.Monitor.Management; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using System.Runtime; using System.Runtime.Serialization; /// <summary> /// Defines values for MetricStatisticType. /// </summary> [JsonConverter(typeof(StringEnumConverter))] public enum MetricStatisticType { [EnumMember(Value = "Average")] Average, [EnumMember(Value = "Min")] Min, [EnumMember(Value = "Max")] Max, [EnumMember(Value = "Sum")] Sum } }
29.75
74
0.68254
[ "MIT" ]
azuresdkci1x/azure-sdk-for-net-1722
src/SDKs/Monitor/Management.Monitor/Generated/Management/Monitor/Models/MetricStatisticType.cs
1,071
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> //------------------------------------------------------------------------------ using System; using System.Reflection; [assembly: Microsoft.AspNetCore.Mvc.ApplicationParts.RelatedAssemblyAttribute("test.Views")] // Generated by the MSBuild WriteCodeFragment class.
32.5
92
0.529915
[ "MIT" ]
TrevorTheAmazing/Capstone
test/obj/Debug/netcoreapp3.0/test.RazorAssemblyInfo.cs
585
C#
using System.Collections.Generic; namespace Backpack.SqlBuilder { public static class SelectExtentions { public static IAcceptsJoin Join(this IAcceptsJoin @this, TableOrSubQuery source, string constraint) { @this.Accept(new JoinClause(source, constraint)); return @this; } public static IAcceptsJoin Join(this IAcceptsJoin @this, string tableName, string constraint) { @this.Accept(new JoinClause(new TableOrSubQuery(tableName), constraint)); return @this; } public static IAcceptsJoin Join(this IAcceptsJoin @this, string tableName, string constraint, string alias) { @this.Accept(new JoinClause(tableName, constraint, alias)); return @this; } public static IAcceptsJoin LeftJoin(this IAcceptsJoin @this, TableOrSubQuery source, string constraint) { @this.Accept(new JoinClause(source, constraint) { JoinType = "LEFT" }); return @this; } public static IAcceptsJoin LeftJoin(this IAcceptsJoin @this, string tableName, string constraint) { @this.Accept(new JoinClause(new TableOrSubQuery(tableName), constraint) { JoinType = "LEFT" }); return @this; } public static IAcceptsJoin LeftJoin(this IAcceptsJoin @this, string tableName, string constraint, string alias) { @this.Accept(new JoinClause(tableName, constraint, alias) { JoinType = "LEFT" }); return @this; } public static IAcceptsGroupBy Where(this IAcceptsWhere @this, string expression) { @this.Accept(new WhereClause(expression)); return @this; } public static IAcceptsOrderBy GroupBy(this IAcceptsGroupBy @this, IEnumerable<string> terms) { @this.Accept(new GroupByClause(terms)); return @this; } public static IAcceptsOrderBy GroupBy(this IAcceptsGroupBy @this, params string[] termArgs) { @this.Accept(new GroupByClause(termArgs)); return @this; } public static IAcceptsLimit OrderBy(this IAcceptsOrderBy @this, IEnumerable<string> terms) { @this.Accept(new OrderByClause(terms)); return @this; } public static IAcceptsLimit OrderBy(this IAcceptsOrderBy @this, params string[] termArgs) { @this.Accept(new OrderByClause(termArgs)); return @this; } public static void Limit(this IAcceptsLimit @this, int limit, int offset) { @this.Accept(new LimitClause(limit, offset)); //return @this; } } }
34.848101
119
0.614602
[ "MIT" ]
BenCamps/Backpack.SqlBuilder
src/Backpack.SqlBuilder/Interfaces/SelectExtentions.cs
2,755
C#
using System; using System.Collections.Generic; using System.ComponentModel; using System.Net.Http.Headers; namespace TWS.RestApi.Areas.HelpPage { /// <summary> /// This is used to identify the place where the sample should be applied. /// </summary> public class HelpPageSampleKey { /// <summary> /// Creates a new <see cref="HelpPageSampleKey"/> based on media type. /// </summary> /// <param name="mediaType">The media type.</param> public HelpPageSampleKey(MediaTypeHeaderValue mediaType) { if (mediaType == null) { throw new ArgumentNullException("mediaType"); } ActionName = String.Empty; ControllerName = String.Empty; MediaType = mediaType; ParameterNames = new HashSet<string>(StringComparer.OrdinalIgnoreCase); } /// <summary> /// Creates a new <see cref="HelpPageSampleKey"/> based on media type and CLR type. /// </summary> /// <param name="mediaType">The media type.</param> /// <param name="type">The CLR type.</param> public HelpPageSampleKey(MediaTypeHeaderValue mediaType, Type type) : this(mediaType) { if (type == null) { throw new ArgumentNullException("type"); } ParameterType = type; } /// <summary> /// Creates a new <see cref="HelpPageSampleKey"/> based on <see cref="SampleDirection"/>, controller name, action name and parameter names. /// </summary> /// <param name="sampleDirection">The <see cref="SampleDirection"/>.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public HelpPageSampleKey(SampleDirection sampleDirection, string controllerName, string actionName, IEnumerable<string> parameterNames) { if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection)) { throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection)); } if (controllerName == null) { throw new ArgumentNullException("controllerName"); } if (actionName == null) { throw new ArgumentNullException("actionName"); } if (parameterNames == null) { throw new ArgumentNullException("parameterNames"); } ControllerName = controllerName; ActionName = actionName; ParameterNames = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase); SampleDirection = sampleDirection; } /// <summary> /// Creates a new <see cref="HelpPageSampleKey"/> based on media type, <see cref="SampleDirection"/>, controller name, action name and parameter names. /// </summary> /// <param name="mediaType">The media type.</param> /// <param name="sampleDirection">The <see cref="SampleDirection"/>.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public HelpPageSampleKey(MediaTypeHeaderValue mediaType, SampleDirection sampleDirection, string controllerName, string actionName, IEnumerable<string> parameterNames) : this(sampleDirection, controllerName, actionName, parameterNames) { if (mediaType == null) { throw new ArgumentNullException("mediaType"); } MediaType = mediaType; } /// <summary> /// Gets the name of the controller. /// </summary> /// <value> /// The name of the controller. /// </value> public string ControllerName { get; private set; } /// <summary> /// Gets the name of the action. /// </summary> /// <value> /// The name of the action. /// </value> public string ActionName { get; private set; } /// <summary> /// Gets the media type. /// </summary> /// <value> /// The media type. /// </value> public MediaTypeHeaderValue MediaType { get; private set; } /// <summary> /// Gets the parameter names. /// </summary> public HashSet<string> ParameterNames { get; private set; } public Type ParameterType { get; private set; } /// <summary> /// Gets the <see cref="SampleDirection"/>. /// </summary> public SampleDirection? SampleDirection { get; private set; } public override bool Equals(object obj) { HelpPageSampleKey otherKey = obj as HelpPageSampleKey; if (otherKey == null) { return false; } return String.Equals(ControllerName, otherKey.ControllerName, StringComparison.OrdinalIgnoreCase) && String.Equals(ActionName, otherKey.ActionName, StringComparison.OrdinalIgnoreCase) && (MediaType == otherKey.MediaType || (MediaType != null && MediaType.Equals(otherKey.MediaType))) && ParameterType == otherKey.ParameterType && SampleDirection == otherKey.SampleDirection && ParameterNames.SetEquals(otherKey.ParameterNames); } public override int GetHashCode() { int hashCode = ControllerName.ToUpperInvariant().GetHashCode() ^ ActionName.ToUpperInvariant().GetHashCode(); if (MediaType != null) { hashCode ^= MediaType.GetHashCode(); } if (SampleDirection != null) { hashCode ^= SampleDirection.GetHashCode(); } if (ParameterType != null) { hashCode ^= ParameterType.GetHashCode(); } foreach (string parameterName in ParameterNames) { hashCode ^= parameterName.ToUpperInvariant().GetHashCode(); } return hashCode; } } }
37.427746
175
0.569575
[ "MIT" ]
Telerik-Team-Lychee/TeamWorkSystem
TeamWorkSystem/TWS.RestApi/Areas/HelpPage/SampleGeneration/HelpPageSampleKey.cs
6,475
C#
// <auto-generated> This file has been auto generated by EF Core Power Tools. </auto-generated> using System; using System.Collections.Generic; #nullable disable namespace T0002.Models { public partial class CxFlowSwrInfo { public string Bu { get; set; } public string CurrentOwner { get; set; } public string CurrentProcess { get; set; } public string CurrentStatus { get; set; } public string Customer { get; set; } public string EngDeptName { get; set; } public DateTime? FpmSignTime { get; set; } public string NewPn { get; set; } public string OldPn { get; set; } public DateTime? PmcSignTime { get; set; } public string Process { get; set; } public string ReworkComment { get; set; } public string ReworkDetialInfo { get; set; } public decimal? ReworkQty { get; set; } public string So { get; set; } public string Spec { get; set; } public DateTime? SubmitDate { get; set; } public string SubmitEmp { get; set; } public string SwrNo { get; set; } public DateTime? TwSignTime { get; set; } public string WorkOrder { get; set; } public DateTime? UpdateDate { get; set; } } }
38.294118
97
0.599846
[ "MIT" ]
twoutlook/BlazorServerDbContextExample
BlazorServerEFCoreSample/T0002/Models/CxFlowSwrInfo.cs
1,304
C#
 using Microsoft.AspNetCore.Components; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Blazui.Component; namespace Blazui.ServerRender.Demo.Table { public class AutoGenerateColumnTableBase : ComponentBase { protected List<AutoGenerateColumnTestData> Datas = new List<AutoGenerateColumnTestData>(); [Inject] MessageService MessageService { get; set; } protected override void OnInitialized() { Datas.Add(new AutoGenerateColumnTestData() { Address = "地址1", Name = "张三", Time = DateTime.Now }); Datas.Add(new AutoGenerateColumnTestData() { Address = "地址2", Name = "张三1", Time = DateTime.Now }); Datas.Add(new AutoGenerateColumnTestData() { Address = "地址3", Name = "张三3", Time = DateTime.Now, Yes = true }); } public void Edit(object testData) { MessageService.Show($"正在编辑 " + ((AutoGenerateColumnTestData)testData).Name); } public void Del(object testData) { MessageService.Show($"正在删除 " + ((AutoGenerateColumnTestData)testData).Name, MessageType.Warning); } } }
27.862745
109
0.547502
[ "MIT" ]
188867052/Element-Blazor
src/Samples/Blazui/Blazui.ServerRender/Demo/Table/AutoGenerateColumnTableBase.cs
1,463
C#
using System; using System.Collections.Generic; using System.Data; using System.Data.Entity; using System.Data.Entity.Infrastructure; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using System.Web.Http.Description; using MeuPonto.DAL; using MeuPonto.Models; namespace MeuPonto.WebAPI.Controller { public class DiasTrabalhoController : ApiController { private Contexto db = new Contexto(); // GET: api/DiasTrabalho public IQueryable<DiaTrabalho> GetDiasTrabalho() { return db.DiasTrabalho; } // GET: api/DiasTrabalho/5 [ResponseType(typeof(DiaTrabalho))] public IHttpActionResult GetDiaTrabalho(int id) { DiaTrabalho diaTrabalho = db.DiasTrabalho.Find(id); if (diaTrabalho == null) { return NotFound(); } return Ok(diaTrabalho); } // PUT: api/DiasTrabalho/5 [ResponseType(typeof(void))] public IHttpActionResult PutDiaTrabalho(int id, DiaTrabalho diaTrabalho) { if (!ModelState.IsValid) { return BadRequest(ModelState); } if (id != diaTrabalho.Id) { return BadRequest(); } db.Entry(diaTrabalho).State = EntityState.Modified; try { db.SaveChanges(); } catch (DbUpdateConcurrencyException) { if (!DiaTrabalhoExists(id)) { return NotFound(); } else { throw; } } return StatusCode(HttpStatusCode.NoContent); } // POST: api/DiasTrabalho [ResponseType(typeof(DiaTrabalho))] public IHttpActionResult PostDiaTrabalho(DiaTrabalho diaTrabalho) { if (!ModelState.IsValid) { return BadRequest(ModelState); } db.DiasTrabalho.Add(diaTrabalho); db.SaveChanges(); return CreatedAtRoute("DefaultApi", new { id = diaTrabalho.Id }, diaTrabalho); } // DELETE: api/DiasTrabalho/5 [ResponseType(typeof(DiaTrabalho))] public IHttpActionResult DeleteDiaTrabalho(int id) { DiaTrabalho diaTrabalho = db.DiasTrabalho.Find(id); if (diaTrabalho == null) { return NotFound(); } db.DiasTrabalho.Remove(diaTrabalho); db.SaveChanges(); return Ok(diaTrabalho); } protected override void Dispose(bool disposing) { if (disposing) { db.Dispose(); } base.Dispose(disposing); } private bool DiaTrabalhoExists(int id) { return db.DiasTrabalho.Count(e => e.Id == id) > 0; } } }
25.663866
90
0.522921
[ "Apache-2.0" ]
bernardolm/MeuPonto.API
MeuPonto.WebAPI/Controller/DiasTrabalhoController.cs
3,056
C#
using System.Collections.Generic; using System.Windows.Controls; using Codeer.TestAssistant.GeneratorToolKit; namespace RM.Friendly.WPFStandardControls.Generator { [CaptureCodeGenerator("RM.Friendly.WPFStandardControls.WPFPasswordBox")] public class WPFPasswordBoxGenerator : CaptureCodeGeneratorBase { PasswordBox _control; protected override void Attach() { _control = (PasswordBox)ControlObject; _control.PasswordChanged += PasswordChanged; } protected override void Detach() { _control.PasswordChanged -= PasswordChanged; } void PasswordChanged(object sender, System.Windows.RoutedEventArgs e) { if (_control.IsFocused) { var literal = GenerateUtility.ToLiteral(_control.Password); AddSentence(new TokenName(), ".EmulateChangePassword(", literal, new TokenAsync(CommaType.Before), ");"); } } public override void Optimize(List<Sentence> code) { GenerateUtility.RemoveDuplicationFunction(this, code, "EmulateChangePassword"); } } }
30.690476
91
0.591932
[ "Apache-2.0" ]
Roommetro/Friendly.WPFStandardControls
Project/RM.Friendly.WPFStandardControls.3.0.Generator/WPFPasswordBoxGenerator.cs
1,291
C#
/* * Copyright (c) 2016 Samsung Electronics Co., Ltd All Rights Reserved * * Licensed under the Apache License, Version 2.0 (the License); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an AS IS BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Text; using System.Threading; using System.Net; using System.Runtime.InteropServices; using System.Collections.Generic; namespace Tizen.Network.Nsd { internal class DnssdInitializer { internal DnssdInitializer() { Globals.DnssdInitialize(); } ~DnssdInitializer() { int ret = Interop.Nsd.Dnssd.Deinitialize(); if (ret != (int)DnssdError.None) { Log.Error(Globals.LogTag, "Failed to deinitialize Dnssd, Error - " + (DnssdError)ret); } } } /// <summary> /// This class is used for managing the local service registration and its properties using DNS-SD. /// </summary> /// <since_tizen> 4 </since_tizen> public class DnssdService : INsdService { private uint _serviceHandle; private string _serviceType; private ushort _dnsRecordtype = 16; private Interop.Nsd.Dnssd.ServiceRegisteredCallback _serviceRegisteredCallback; /// <summary> /// The constructor to create the DnssdService instance that sets the serviceType to a given value. /// </summary> /// <since_tizen> 4 </since_tizen> /// <param name="serviceType">The DNS-SD service type. It is expressed as a type followed by the protocol, separated by a dot (For example, "_ftp._tcp"). /// It must begin with an underscore followed by 1-15 characters, which may be letters, digits, or hyphens. /// </param> /// <feature>http://tizen.org/feature/network.service_discovery.dnssd</feature> /// <exception cref="NotSupportedException">Thrown while setting this property when DNS-SD is not supported.</exception> /// <exception cref="ArgumentException">Thrown when the serviceType is set to null.</exception> public DnssdService(string serviceType) { _serviceType = serviceType; DnssdInitializeCreateService(); } internal DnssdService(uint service) { _serviceHandle = service; } internal void DnssdInitializeCreateService() { DnssdInitializer dnssdInit = Globals.s_threadDns.Value; Log.Info(Globals.LogTag, "Initialize ThreadLocal<DnssdInitializer> instance = " + dnssdInit); int ret = Interop.Nsd.Dnssd.CreateService(_serviceType, out _serviceHandle); if (ret != (int)DnssdError.None) { Log.Error(Globals.LogTag, "Failed to create a local Dnssd service handle, Error - " + (DnssdError)ret); NsdErrorFactory.ThrowDnssdException(ret); } } /// <summary> /// Name of the DNS-SD service. /// </summary> /// <remarks> /// Set the name for only an unregistered service created locally. /// It may be up to 63 bytes. /// In case of an error, null will be returned during get and exception will be thrown during set. /// </remarks> /// <since_tizen> 4 </since_tizen> /// <feature>http://tizen.org/feature/network.service_discovery.dnssd</feature> /// <exception cref="NotSupportedException">Thrown while setting this property when DNS-SD is not supported.</exception> /// <exception cref="ArgumentException">Thrown when the name value is set to null.</exception> /// <exception cref="InvalidOperationException">Thrown while setting this property when any other error occurred.</exception> public string Name { get { string name; int ret = Interop.Nsd.Dnssd.GetName(_serviceHandle, out name); if (ret != (int)DnssdError.None) { Log.Error(Globals.LogTag, "Failed to get name of service, Error: " + (DnssdError)ret); return null; } return name; } set { if (!Globals.s_threadDns.IsValueCreated) { DnssdInitializeCreateService(); } int ret = Interop.Nsd.Dnssd.SetName(_serviceHandle, value); if (ret != (int)DnssdError.None) { Log.Error(Globals.LogTag, "Failed to set name of service, Error: " + (DnssdError)ret); NsdErrorFactory.ThrowDnssdException(ret); } } } /// <summary> /// Type of the DNS-SD local or remote service. /// </summary> /// <remarks> /// It is expressed as a type followed by the protocol, separated by a dot (For example, "_ftp._tcp"). /// It must begin with an underscore followed by 1-15 characters, which may be letters, digits, or hyphens. /// In case of an error, null will be returned. /// </remarks> /// <since_tizen> 4 </since_tizen> public string Type { get { string type; int ret = Interop.Nsd.Dnssd.GetType(_serviceHandle, out type); if (ret != (int)DnssdError.None) { Log.Error(Globals.LogTag, "Failed to get type of service, Error: " + (DnssdError)ret); return null; } return type; } } /// <summary> /// Port number of the DNS-SD local or remote service. /// </summary> /// <remarks> /// Set the port for only an unregistered service created locally. The default value of the port is 0. /// In case of an error, -1 will be returned during get and exception will be thrown during set. /// </remarks> /// <since_tizen> 4 </since_tizen> /// <feature>http://tizen.org/feature/network.service_discovery.dnssd</feature> /// <exception cref="NotSupportedException">Thrown while setting this property when DNS-SD is not supported.</exception> /// <exception cref="ArgumentException">Thrown if the value of port is set to less than 0 or more than 65535.</exception> /// <exception cref="InvalidOperationException">Thrown while setting this property when any other error occurred.</exception> public int Port { get { int port; int ret = Interop.Nsd.Dnssd.GetPort(_serviceHandle, out port); if (ret != (int)DnssdError.None) { Log.Error(Globals.LogTag, "Failed to get port number of Dnssd service, Error: " + (DnssdError)ret); return -1; } return port; } set { if (!Globals.s_threadDns.IsValueCreated) { DnssdInitializeCreateService(); } int ret = Interop.Nsd.Dnssd.SetPort(_serviceHandle, value); if (ret != (int)DnssdError.None) { Log.Error(Globals.LogTag, "Failed to set port number of Dnssd service, Error: " + (DnssdError)ret); NsdErrorFactory.ThrowDnssdException(ret); } } } /// <summary> /// IP address of the DNS-SD remote service. /// </summary> /// <remarks> /// If the remote service has no IPv4 Address, then IPv4Address would contain null and if it has no IPv6 Address, then IPv6Address would contain null. /// In case of an error, null object will be returned. /// </remarks> /// <since_tizen> 4 </since_tizen> public IPAddressInformation IP { get { string IPv4, IPv6; int ret = Interop.Nsd.Dnssd.GetIP(_serviceHandle, out IPv4, out IPv6); if (ret != (int)DnssdError.None) { Log.Error(Globals.LogTag, "Failed to get the IP of Dnssd remote service, Error: " + (DnssdError)ret); return null; } IPAddressInformation IPAddressInstance = new IPAddressInformation(IPv4, IPv6); return IPAddressInstance; } } /// <summary> /// Returns raw TXT records. /// </summary> /// <returns>Returns empty bytes array in case TXT record has not been set, else returns raw TXT record.</returns> /// <since_tizen> 9 </since_tizen> /// <feature>http://tizen.org/feature/network.service_discovery.dnssd</feature> /// <exception cref="NotSupportedException">Thrown when DNS-SD is not supported.</exception> /// <exception cref="InvalidOperationException">Thrown when any other error occurred.</exception> public byte[] GetRawTXTRecords() { int ret = Interop.Nsd.Dnssd.GetAllTxtRecord(_serviceHandle, out ushort length, out IntPtr data); if (ret != (int)DnssdError.None) { Log.Error(Globals.LogTag, "Failed to get the TXT record, Error: " + (DnssdError)ret); NsdErrorFactory.ThrowDnssdException(ret); } byte[] value = Array.Empty<byte>(); if (length > 0) { value = new byte[length]; Marshal.Copy(data, value, 0, length); Interop.Libc.Free(data); } return value; } /// <summary> /// Adds the TXT record. /// </summary> /// <remarks> /// TXT record should be added after registering the local service using RegisterService(). /// </remarks> /// <since_tizen> 4 </since_tizen> /// <param name="key">The key of the TXT record. It must be a null-terminated string with 9 characters or fewer excluding null. It is case insensitive.</param> /// <param name="value">The value of the TXT record. If null, then "key" will be added with no value. If non-null but the value_length is zero, then "key=" will be added with an empty value.</param> /// <feature>http://tizen.org/feature/network.service_discovery.dnssd</feature> /// <exception cref="NotSupportedException">Thrown when DNS-SD is not supported.</exception> /// <exception cref="ArgumentException">Thrown when the value of the key is null.</exception> /// <exception cref="InvalidOperationException">Thrown when any other error occurred.</exception> public void AddTXTRecord(string key, string value) { byte[] byteValue = Encoding.UTF8.GetBytes(value); ushort length = Convert.ToUInt16(byteValue.Length); int ret = Interop.Nsd.Dnssd.AddTxtRecord(_serviceHandle, key, length, byteValue); if (ret != (int)DnssdError.None) { Log.Error(Globals.LogTag, "Failed to add the TXT record, Error: " + (DnssdError)ret); NsdErrorFactory.ThrowDnssdException(ret); } byte[] txtValue = GetRawTXTRecords(); ret = Interop.Nsd.Dnssd.SetRecord(_serviceHandle, _dnsRecordtype, (ushort)txtValue.Length, txtValue); if (ret != (int)DnssdError.None) { Log.Error(Globals.LogTag, "Failed to set the DNS resource record, Error: " + (DnssdError)ret); NsdErrorFactory.ThrowDnssdException(ret); } } /// <summary> /// Removes the TXT record. /// </summary> /// <since_tizen> 4 </since_tizen> /// <param name="key">The key of the TXT record to be removed.</param> /// <feature>http://tizen.org/feature/network.service_discovery.dnssd</feature> /// <exception cref="NotSupportedException">Thrown when DNS-SD is not supported.</exception> /// <exception cref="ArgumentException">Thrown when the value of the key is null.</exception> /// <exception cref="InvalidOperationException">Thrown when any other error occurred.</exception> public void RemoveTXTRecord(string key) { int ret = Interop.Nsd.Dnssd.RemoveTxtRecord(_serviceHandle, key); if (ret != (int)DnssdError.None) { Log.Error(Globals.LogTag, "Failed to remove the TXT record, Error: " + (DnssdError)ret); NsdErrorFactory.ThrowDnssdException(ret); } } /// <summary> /// Registers the DNS-SD local service for publishing. /// </summary> /// Name of the service must be set. /// <since_tizen> 4 </since_tizen> /// <privilege>http://tizen.org/privilege/internet</privilege> /// <feature>http://tizen.org/feature/network.service_discovery.dnssd</feature> /// <exception cref="InvalidOperationException">Thrown when any other error occurred.</exception> /// <exception cref="NotSupportedException">Thrown when DNS-SD is not supported.</exception> /// <exception cref="UnauthorizedAccessException">Thrown when the permission is denied.</exception> public void RegisterService() { if (!Globals.s_threadDns.IsValueCreated) { DnssdInitializeCreateService(); } _serviceRegisteredCallback = (DnssdError result, uint service, IntPtr userData) => { if (result != DnssdError.None) { Log.Error(Globals.LogTag, "Failed to finish the registration of Dnssd local service, Error: " + result); NsdErrorFactory.ThrowDnssdException((int)result); } }; int ret = Interop.Nsd.Dnssd.RegisterService(_serviceHandle, _serviceRegisteredCallback, IntPtr.Zero); if (ret != (int)DnssdError.None) { Log.Error(Globals.LogTag, "Failed to register the Dnssd local service, Error: " + (DnssdError)ret); NsdErrorFactory.ThrowDnssdException(ret); } } /// <summary> /// Deregisters the DNS-SD local service. /// </summary> /// <remarks> /// A local service registered using RegisterService() must be passed. /// </remarks> /// <since_tizen> 4 </since_tizen> /// <feature>http://tizen.org/feature/network.service_discovery.dnssd</feature> /// <exception cref="InvalidOperationException">Thrown when any other error occurred.</exception> /// <exception cref="NotSupportedException">Thrown when DNS-SD is not supported.</exception> public void DeregisterService() { int ret = Interop.Nsd.Dnssd.DeregisterService(_serviceHandle); if (ret != (int)DnssdError.None) { Log.Error(Globals.LogTag, "Failed to deregister the Dnssd local service, Error: " + (DnssdError)ret); NsdErrorFactory.ThrowDnssdException(ret); } } #region IDisposable Support private bool _disposedValue = false; // To detect redundant calls private void Dispose(bool disposing) { if (!_disposedValue) { if (disposing) { if (_serviceHandle != 0) { int ret = Interop.Nsd.Dnssd.DestroyService(_serviceHandle); if (ret != (int)DnssdError.None) { Log.Error(Globals.LogTag, "Failed to destroy the local Dnssd service handle, Error - " + (DnssdError)ret); } } } _disposedValue = true; } } /// <summary> /// Destroys the DnssdService object. /// </summary> ~DnssdService() { Dispose(false); } /// <summary> /// Disposes the memory allocated to unmanaged resources. /// </summary> /// <since_tizen> 4 </since_tizen> public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } #endregion } /// <summary> /// This class manages the IP address properties of the DNS-SD service. /// </summary> /// <since_tizen> 4 </since_tizen> public class IPAddressInformation { private string _ipv4, _ipv6; internal IPAddressInformation() { } internal IPAddressInformation(string ipv4, string ipv6) { _ipv4 = ipv4; _ipv6 = ipv6; } /// <summary> /// The IP version 4 address of the DNS-SD service. /// </summary> /// <since_tizen> 4 </since_tizen> public IPAddress IPv4Address { get { if (_ipv4 == null) return IPAddress.Parse("0.0.0.0"); return IPAddress.Parse(_ipv4); } } /// <summary> /// The IP version 6 address of the DNS-SD service. /// </summary> /// <since_tizen> 4 </since_tizen> public IPAddress IPv6Address { get { if (_ipv6 == null) return IPAddress.Parse("0:0:0:0:0:0:0:0"); return IPAddress.Parse(_ipv6); } } } }
41.079186
206
0.567605
[ "Apache-2.0", "MIT" ]
Inhong/TizenFX
src/Tizen.Network.Nsd/Tizen.Network.Nsd/DnssdService.cs
18,157
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 HorizontalSubtractInt32() { var test = new HorizontalBinaryOpTest__HorizontalSubtractInt32(); 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 class works test.RunClassLclFldScenario(); // Validates passing an instance member of a class works test.RunClassFldScenario(); // Validates passing the field of a local struct works test.RunStructLclFldScenario(); // Validates passing an instance member of a struct works test.RunStructFldScenario(); } 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 HorizontalBinaryOpTest__HorizontalSubtractInt32 { private struct TestStruct { public Vector128<Int32> _fld1; public Vector128<Int32> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref testStruct._fld1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref testStruct._fld2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>()); return testStruct; } public void RunStructFldScenario(HorizontalBinaryOpTest__HorizontalSubtractInt32 testClass) { var result = Ssse3.HorizontalSubtract(_fld1, _fld2); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } } private static readonly int LargestVectorSize = 16; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Int32>>() / sizeof(Int32); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<Int32>>() / sizeof(Int32); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Int32>>() / sizeof(Int32); private static Int32[] _data1 = new Int32[Op1ElementCount]; private static Int32[] _data2 = new Int32[Op2ElementCount]; private static Vector128<Int32> _clsVar1; private static Vector128<Int32> _clsVar2; private Vector128<Int32> _fld1; private Vector128<Int32> _fld2; private HorizontalBinaryOpTest__DataTable<Int32, Int32, Int32> _dataTable; static HorizontalBinaryOpTest__HorizontalSubtractInt32() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _clsVar1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _clsVar2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>()); } public HorizontalBinaryOpTest__HorizontalSubtractInt32() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _fld1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _fld2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); } _dataTable = new HorizontalBinaryOpTest__DataTable<Int32, Int32, Int32>(_data1, _data2, new Int32[RetElementCount], LargestVectorSize); } public bool IsSupported => Ssse3.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Ssse3.HorizontalSubtract( Unsafe.Read<Vector128<Int32>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Int32>>(_dataTable.inArray2Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = Ssse3.HorizontalSubtract( Sse2.LoadVector128((Int32*)(_dataTable.inArray1Ptr)), Sse2.LoadVector128((Int32*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned)); var result = Ssse3.HorizontalSubtract( Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArray1Ptr)), Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(Ssse3).GetMethod(nameof(Ssse3.HorizontalSubtract), new Type[] { typeof(Vector128<Int32>), typeof(Vector128<Int32>) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<Int32>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Int32>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int32>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(Ssse3).GetMethod(nameof(Ssse3.HorizontalSubtract), new Type[] { typeof(Vector128<Int32>), typeof(Vector128<Int32>) }) .Invoke(null, new object[] { Sse2.LoadVector128((Int32*)(_dataTable.inArray1Ptr)), Sse2.LoadVector128((Int32*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int32>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned)); var result = typeof(Ssse3).GetMethod(nameof(Ssse3.HorizontalSubtract), new Type[] { typeof(Vector128<Int32>), typeof(Vector128<Int32>) }) .Invoke(null, new object[] { Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArray1Ptr)), Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int32>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Ssse3.HorizontalSubtract( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var left = Unsafe.Read<Vector128<Int32>>(_dataTable.inArray1Ptr); var right = Unsafe.Read<Vector128<Int32>>(_dataTable.inArray2Ptr); var result = Ssse3.HorizontalSubtract(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var left = Sse2.LoadVector128((Int32*)(_dataTable.inArray1Ptr)); var right = Sse2.LoadVector128((Int32*)(_dataTable.inArray2Ptr)); var result = Ssse3.HorizontalSubtract(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned)); var left = Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArray1Ptr)); var right = Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArray2Ptr)); var result = Ssse3.HorizontalSubtract(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new HorizontalBinaryOpTest__HorizontalSubtractInt32(); var result = Ssse3.HorizontalSubtract(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Ssse3.HorizontalSubtract(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Ssse3.HorizontalSubtract(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector128<Int32> left, Vector128<Int32> right, void* result, [CallerMemberName] string method = "") { Int32[] inArray1 = new Int32[Op1ElementCount]; Int32[] inArray2 = new Int32[Op2ElementCount]; Int32[] outArray = new Int32[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref inArray1[0]), left); Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref inArray2[0]), right); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int32>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* left, void* right, void* result, [CallerMemberName] string method = "") { Int32[] inArray1 = new Int32[Op1ElementCount]; Int32[] inArray2 = new Int32[Op2ElementCount]; Int32[] outArray = new Int32[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), (uint)Unsafe.SizeOf<Vector128<Int32>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), (uint)Unsafe.SizeOf<Vector128<Int32>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int32>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Int32[] left, Int32[] right, Int32[] result, [CallerMemberName] string method = "") { bool succeeded = true; for (var outer = 0; outer < (LargestVectorSize / 16); outer++) { for (var inner = 0; inner < (8 / sizeof(Int32)); inner++) { var i1 = (outer * (16 / sizeof(Int32))) + inner; var i2 = i1 + (8 / sizeof(Int32)); var i3 = (outer * (16 / sizeof(Int32))) + (inner * 2); if (result[i1] != (int)(left[i3] - left[i3 + 1])) { succeeded = false; break; } if (result[i2] != (int)(right[i3] - right[i3 + 1])) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Ssse3)}.{nameof(Ssse3.HorizontalSubtract)}<Int32>(Vector128<Int32>, Vector128<Int32>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})"); TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
43.739857
187
0.596388
[ "MIT" ]
AlexejLiebenthal/coreclr
tests/src/JIT/HardwareIntrinsics/X86/Ssse3/HorizontalSubtract.Int32.cs
18,327
C#
// Copyright (C) 2003-2010 Xtensive LLC. // All rights reserved. // For conditions of distribution and use, see license. // Created by: Alex Yakunin // Created: 2009.12.18 using System.Collections; using System.Collections.Generic; using System.Diagnostics; using Xtensive.Collections; namespace Xtensive.Orm.Services { /// <summary> /// Public API to cached state of <see cref="Orm.EntitySet{TItem}"/> /// (see <see cref="DirectStateAccessor"/>). /// </summary> [DebuggerDisplay("Count = {Count}")] public struct EntitySetStateAccessor : IEnumerable<Key> { private readonly EntitySetBase entitySet; /// <summary> /// Gets the entity set this accessor is bound to. /// </summary> public EntitySetBase EntitySet { get { return entitySet; } } /// <summary> /// Gets the number of cached items. /// </summary> public long Count { get { var state = EntitySet.State; return state==null ? 0 : state.CachedItemCount; } } /// <summary> /// Gets a value indicating whether an attempt to read /// <see cref="EntitySetBase.Count"/> won't hit the database. /// </summary> public bool IsCountAvailable { get { var state = EntitySet.State; return state==null ? false : state.TotalItemCount.HasValue; } } /// <summary> /// Gets a value indicating whether <see cref="EntitySet"/> is fully loaded, /// so any read request to it won't hit the database. /// </summary> public bool IsFullyLoaded { get { var state = EntitySet.State; return state==null ? false : state.IsFullyLoaded; } } /// <summary> /// Indicates whether a specified <paramref name="key"/> is cached or not. /// </summary> /// <param name="key">The key to check.</param> /// <returns> /// <see langword="true"/> if the specified key is cached; /// otherwise, <see langword="false"/>. /// </returns> public bool Contains(Key key) { var state = EntitySet.State; return state==null ? false : state.Contains(key); } /// <inheritdoc/> IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } /// <inheritdoc/> public IEnumerator<Key> GetEnumerator() { var state = EntitySet.State; return state==null ? EnumerableUtils<Key>.EmptyEnumerator : state.GetEnumerator(); } // Constructors internal EntitySetStateAccessor(EntitySetBase entitySet) { this.entitySet = entitySet; } } }
27.265306
89
0.596557
[ "MIT" ]
SergeiPavlov/dataobjects-net
DataObjects/Orm/Services/Old/EntitySetStateAccessor.cs
2,672
C#
using System; using System.Linq; namespace TextrudeInteractive { /// <summary> /// Holds all the input necessary to run a template rendering pass /// </summary> /// <remarks> </remarks> public record EngineInputSet { public static EngineInputSet EmptyYaml = new(string.Empty, Array.Empty<ModelText>(), string.Empty, string.Empty); public EngineInputSet(string template, ModelText[] models, string definitionsText, string includes) { Template = template; Models = models; Definitions = definitionsText .Split('\r', '\n') .Select(l => l.Trim()) .Where(l => l.Length > 0) .ToArray(); IncludePaths = includes.Split(Environment.NewLine, StringSplitOptions.TrimEntries | StringSplitOptions.RemoveEmptyEntries); } //Required for deserialisation public EngineInputSet() { } /// <summary> /// </summary> public string[] Definitions { get; init; } = Array.Empty<string>(); public string[] IncludePaths { get; init; } = Array.Empty<string>(); public ModelText[] Models { get; init; } = Array.Empty<ModelText>(); public string Template { get; init; } = string.Empty; } }
29.652174
90
0.567449
[ "MIT" ]
highstreeto/Textrude
TextrudeInteractive/EngineInputSet.cs
1,366
C#
using System.CodeDom.Compiler; using System.Collections.Generic; using System.Collections; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.Serialization; using System.Text.RegularExpressions; using System.Text; using System; class Solution { static void Main(string[] args) { int[][] arr = new int[6][]; List<int> result = new List<int>(); for (int i = 0; i < 6; i++) { arr[i] = Array.ConvertAll(Console.ReadLine().Split(' '), arrTemp => Convert.ToInt32(arrTemp)); } for (int i = 0; i < 4; i++) { for (int j = 0; j < 4; j++) { var hourglass = arr[i][j] + arr[i][j + 1] + arr[i][j + 2] + arr[i + 1][j + 1] + arr[i + 2][j] + arr[i + 2][j + 1] + arr[i + 2][j + 2]; result.Add(hourglass); } } Console.WriteLine(result.Max()); } }
25
106
0.496522
[ "Unlicense" ]
iliyalesani/HackerRank-Daily-Challenges
11 - 2D Arrays.cs
1,150
C#
using Infiniminer; using Lidgren.Network; using Microsoft.Xna.Framework; using Plexiglass.Client.Engine; using System.Collections.Generic; namespace Plexiglass.Client { public interface IPropertyBag { void PlaySound(InfiniminerSound sound); void PlaySound(InfiniminerSound sound, Vector3 position); void SetPlayerClass(PlayerClass playerClass); void KillPlayer(string deathMessage); PlayerContainer PlayerContainer { get; set; } SettingsContainer SettingsContainer { get; set; } ChatContainer ChatContainer { get; set; } TeamContainer TeamContainer { get; set; } GameTime CurrentGameTime { get; set; } bool[,] MapLoadProgress { get; set; } NetClient NetClient { get; set; } Dictionary<uint, Player> PlayerList { get; set; } void RegisterEngine<T>(T engine, string engineName) where T: IEngine; T GetEngine<T>(string engineName) where T: IEngine; } }
28.742857
65
0.668986
[ "MIT" ]
CalmBit/infiniminer
code/Plexiglass/Client/IPropertyBag.cs
1,008
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Fluid; using Microsoft.AspNetCore.Routing; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Localization; using Microsoft.Extensions.Options; using Newtonsoft.Json.Linq; using OrchardCore.Autoroute.Models; using OrchardCore.Autoroute.ViewModels; using OrchardCore.ContentLocalization; using OrchardCore.ContentManagement; using OrchardCore.ContentManagement.Handlers; using OrchardCore.ContentManagement.Metadata; using OrchardCore.ContentManagement.Records; using OrchardCore.ContentManagement.Routing; using OrchardCore.Environment.Cache; using OrchardCore.Liquid; using OrchardCore.Localization; using OrchardCore.Settings; using YesSql; using YesSql.Services; namespace OrchardCore.Autoroute.Handlers { public class AutoroutePartHandler : ContentPartHandler<AutoroutePart> { private readonly IAutorouteEntries _entries; private readonly AutorouteOptions _options; private readonly ILiquidTemplateManager _liquidTemplateManager; private readonly IContentDefinitionManager _contentDefinitionManager; private readonly ISiteService _siteService; private readonly ITagCache _tagCache; private readonly ISession _session; private readonly IServiceProvider _serviceProvider; private readonly IStringLocalizer S; private IContentManager _contentManager; public AutoroutePartHandler( IAutorouteEntries entries, IOptions<AutorouteOptions> options, ILiquidTemplateManager liquidTemplateManager, IContentDefinitionManager contentDefinitionManager, ISiteService siteService, ITagCache tagCache, ISession session, IServiceProvider serviceProvider, IStringLocalizer<AutoroutePartHandler> stringLocalizer) { _entries = entries; _options = options.Value; _liquidTemplateManager = liquidTemplateManager; _contentDefinitionManager = contentDefinitionManager; _siteService = siteService; _tagCache = tagCache; _session = session; _serviceProvider = serviceProvider; S = stringLocalizer; } public override async Task PublishedAsync(PublishContentContext context, AutoroutePart part) { if (!String.IsNullOrWhiteSpace(part.Path)) { if (part.RouteContainedItems) { _contentManager ??= _serviceProvider.GetRequiredService<IContentManager>(); var containedAspect = await _contentManager.PopulateAspectAsync<ContainedContentItemsAspect>(context.PublishingItem); await CheckContainedHomeRouteAsync(part.ContentItem.ContentItemId, containedAspect, context.PublishingItem.Content); } // Update entries from the index table after the session is committed. await _entries.UpdateEntriesAsync(); } if (!String.IsNullOrWhiteSpace(part.Path) && !part.Disabled && part.SetHomepage) { await SetHomeRouteAsync(part, homeRoute => { homeRoute[_options.ContentItemIdKey] = context.ContentItem.ContentItemId; homeRoute[_options.JsonPathKey] = ""; }); } // Evict any dependent item from cache await RemoveTagAsync(part); } public override async Task UnpublishedAsync(PublishContentContext context, AutoroutePart part) { if (!String.IsNullOrWhiteSpace(part.Path)) { // Update entries from the index table after the session is committed. await _entries.UpdateEntriesAsync(); // Evict any dependent item from cache await RemoveTagAsync(part); } } public override async Task RemovedAsync(RemoveContentContext context, AutoroutePart part) { if (!String.IsNullOrWhiteSpace(part.Path) && context.NoActiveVersionLeft) { // Update entries from the index table after the session is committed. await _entries.UpdateEntriesAsync(); // Evict any dependent item from cache await RemoveTagAsync(part); } } public override async Task ValidatingAsync(ValidateContentContext context, AutoroutePart part) { // Only validate the path if it's not empty. if (String.IsNullOrWhiteSpace(part.Path)) { return; } foreach (var item in part.ValidatePathFieldValue(S)) { context.Fail(item); } if (!await IsAbsolutePathUniqueAsync(part.Path, part.ContentItem.ContentItemId)) { context.Fail(S["Your permalink is already in use."], nameof(part.Path)); } } public override async Task UpdatedAsync(UpdateContentContext context, AutoroutePart part) { await GenerateContainerPathFromPatternAsync(part); await GenerateContainedPathsFromPatternAsync(context.UpdatingItem, part); } public async override Task CloningAsync(CloneContentContext context, AutoroutePart part) { var clonedPart = context.CloneContentItem.As<AutoroutePart>(); clonedPart.Path = await GenerateUniqueAbsolutePathAsync(part.Path, context.CloneContentItem.ContentItemId); clonedPart.SetHomepage = false; clonedPart.Apply(); await GenerateContainedPathsFromPatternAsync(context.CloneContentItem, part); } public override Task GetContentItemAspectAsync(ContentItemAspectContext context, AutoroutePart part) { return context.ForAsync<RouteHandlerAspect>(aspect => { var contentTypeDefinition = _contentDefinitionManager.GetTypeDefinition(part.ContentItem.ContentType); var contentTypePartDefinition = contentTypeDefinition.Parts.FirstOrDefault(x => String.Equals(x.PartDefinition.Name, "AutoroutePart")); var settings = contentTypePartDefinition.GetSettings<AutoroutePartSettings>(); if (settings.ManageContainedItemRoutes) { aspect.Path = part.Path; aspect.Absolute = part.Absolute; aspect.Disabled = part.Disabled; } return Task.CompletedTask; }); } private async Task SetHomeRouteAsync(AutoroutePart part, Action<RouteValueDictionary> action) { var site = await _siteService.LoadSiteSettingsAsync(); if (site.HomeRoute == null) { site.HomeRoute = new RouteValueDictionary(); } var homeRoute = site.HomeRoute; foreach (var entry in _options.GlobalRouteValues) { homeRoute[entry.Key] = entry.Value; } action.Invoke(homeRoute); // Once we took the flag into account we can dismiss it. part.SetHomepage = false; part.Apply(); await _siteService.UpdateSiteSettingsAsync(site); } private Task RemoveTagAsync(AutoroutePart part) { return _tagCache.RemoveTagAsync($"slug:{part.Path}"); } private async Task CheckContainedHomeRouteAsync(string containerContentItemId, ContainedContentItemsAspect containedAspect, JObject content) { foreach (var accessor in containedAspect.Accessors) { var jItems = accessor.Invoke(content); foreach (JObject jItem in jItems) { var contentItem = jItem.ToObject<ContentItem>(); var handlerAspect = await _contentManager.PopulateAspectAsync<RouteHandlerAspect>(contentItem); if (!handlerAspect.Disabled) { // Only an autoroute part, not a default handler aspect can set itself as the homepage. var autoroutePart = contentItem.As<AutoroutePart>(); if (autoroutePart != null && autoroutePart.SetHomepage) { await SetHomeRouteAsync(autoroutePart, homeRoute => { homeRoute[_options.ContentItemIdKey] = containerContentItemId; homeRoute[_options.JsonPathKey] = jItem.Path; }); break; } } } } } private async Task GenerateContainedPathsFromPatternAsync(ContentItem contentItem, AutoroutePart part) { // Validate contained content item routes if container has valid path. if (!String.IsNullOrWhiteSpace(part.Path) || !part.RouteContainedItems) { return; } _contentManager ??= _serviceProvider.GetRequiredService<IContentManager>(); var containedAspect = await _contentManager.PopulateAspectAsync<ContainedContentItemsAspect>(contentItem); // Build the entries for this content item to evaluate for duplicates. var entries = new List<AutorouteEntry>(); await PopulateContainedContentItemRoutesAsync(entries, part.ContentItem.ContentItemId, containedAspect, contentItem.Content, part.Path); await ValidateContainedContentItemRoutesAsync(entries, part.ContentItem.ContentItemId, containedAspect, contentItem.Content, part.Path); } private async Task PopulateContainedContentItemRoutesAsync(List<AutorouteEntry> entries, string containerContentItemId, ContainedContentItemsAspect containedContentItemsAspect, JObject content, string basePath) { foreach (var accessor in containedContentItemsAspect.Accessors) { var jItems = accessor.Invoke(content); foreach (JObject jItem in jItems) { var contentItem = jItem.ToObject<ContentItem>(); var handlerAspect = await _contentManager.PopulateAspectAsync<RouteHandlerAspect>(contentItem); if (!handlerAspect.Disabled) { var path = handlerAspect.Path; if (!handlerAspect.Absolute) { path = (basePath.EndsWith('/') ? basePath : basePath + '/') + handlerAspect.Path; } entries.Add(new AutorouteEntry(containerContentItemId, path, contentItem.ContentItemId, jItem.Path) { DocumentId = contentItem.Id }); } var itemBasePath = (basePath.EndsWith('/') ? basePath : basePath + '/') + handlerAspect.Path; var childrenAspect = await _contentManager.PopulateAspectAsync<ContainedContentItemsAspect>(contentItem); await PopulateContainedContentItemRoutesAsync(entries, containerContentItemId, childrenAspect, jItem, itemBasePath); } } } private async Task ValidateContainedContentItemRoutesAsync(List<AutorouteEntry> entries, string containerContentItemId, ContainedContentItemsAspect containedContentItemsAspect, JObject content, string basePath) { foreach (var accessor in containedContentItemsAspect.Accessors) { var jItems = accessor.Invoke(content); foreach (JObject jItem in jItems) { var contentItem = jItem.ToObject<ContentItem>(); var containedAutoroutePart = contentItem.As<AutoroutePart>(); // This is only relevant if the content items have an autoroute part as we adjust the part value as required to guarantee a unique route. // Content items routed only through the handler aspect already guarantee uniqueness. if (containedAutoroutePart != null && !containedAutoroutePart.Disabled) { var path = containedAutoroutePart.Path; if (containedAutoroutePart.Absolute && !await IsAbsolutePathUniqueAsync(path, contentItem.ContentItemId)) { path = await GenerateUniqueAbsolutePathAsync(path, contentItem.ContentItemId); containedAutoroutePart.Path = path; containedAutoroutePart.Apply(); // Merge because we have disconnected the content item from it's json owner. jItem.Merge(contentItem.Content, new JsonMergeSettings { MergeArrayHandling = MergeArrayHandling.Replace, MergeNullValueHandling = MergeNullValueHandling.Merge }); } else { var currentItemBasePath = basePath.EndsWith('/') ? basePath : basePath + '/'; path = currentItemBasePath + containedAutoroutePart.Path; if (!IsRelativePathUnique(entries, path, containedAutoroutePart)) { path = GenerateRelativeUniquePath(entries, path, containedAutoroutePart); // Remove base path and update part path. containedAutoroutePart.Path = path.Substring(currentItemBasePath.Length); containedAutoroutePart.Apply(); // Merge because we have disconnected the content item from it's json owner. jItem.Merge(contentItem.Content, new JsonMergeSettings { MergeArrayHandling = MergeArrayHandling.Replace, MergeNullValueHandling = MergeNullValueHandling.Merge }); } path = path.Substring(currentItemBasePath.Length); } var containedItemBasePath = (basePath.EndsWith('/') ? basePath : basePath + '/') + path; var childItemAspect = await _contentManager.PopulateAspectAsync<ContainedContentItemsAspect>(contentItem); await ValidateContainedContentItemRoutesAsync(entries, containerContentItemId, childItemAspect, jItem, containedItemBasePath); } } } } private static bool IsRelativePathUnique(List<AutorouteEntry> entries, string path, AutoroutePart context) { var result = !entries.Any(e => context.ContentItem.ContentItemId != e.ContainedContentItemId && String.Equals(e.Path, path, StringComparison.OrdinalIgnoreCase)); return result; } private string GenerateRelativeUniquePath(List<AutorouteEntry> entries, string path, AutoroutePart context) { var version = 1; var unversionedPath = path; var versionSeparatorPosition = path.LastIndexOf('-'); if (versionSeparatorPosition > -1 && Int32.TryParse(path.Substring(versionSeparatorPosition).TrimStart('-'), out version)) { unversionedPath = path.Substring(0, versionSeparatorPosition); } while (true) { // Unversioned length + separator char + version length. var quantityCharactersToTrim = unversionedPath.Length + 1 + version.ToString().Length - AutoroutePart.MaxPathLength; if (quantityCharactersToTrim > 0) { unversionedPath = unversionedPath.Substring(0, unversionedPath.Length - quantityCharactersToTrim); } var versionedPath = $"{unversionedPath}-{version++}"; if (IsRelativePathUnique(entries, versionedPath, context)) { var entry = entries.FirstOrDefault(e => e.ContainedContentItemId == context.ContentItem.ContentItemId); entry.Path = versionedPath; return versionedPath; } } } private async Task GenerateContainerPathFromPatternAsync(AutoroutePart part) { // Compute the Path only if it's empty if (!String.IsNullOrWhiteSpace(part.Path)) { return; } var pattern = GetPattern(part); if (!String.IsNullOrEmpty(pattern)) { var model = new AutoroutePartViewModel() { Path = part.Path, AutoroutePart = part, ContentItem = part.ContentItem }; _contentManager ??= _serviceProvider.GetRequiredService<IContentManager>(); var cultureAspect = await _contentManager.PopulateAspectAsync(part.ContentItem, new CultureAspect()); using (CultureScope.Create(cultureAspect.Culture)) { part.Path = await _liquidTemplateManager.RenderAsync(pattern, NullEncoder.Default, model, scope => scope.SetValue(nameof(ContentItem), model.ContentItem)); } part.Path = part.Path.Replace("\r", String.Empty).Replace("\n", String.Empty); if (part.Path?.Length > AutoroutePart.MaxPathLength) { part.Path = part.Path.Substring(0, AutoroutePart.MaxPathLength); } if (!await IsAbsolutePathUniqueAsync(part.Path, part.ContentItem.ContentItemId)) { part.Path = await GenerateUniqueAbsolutePathAsync(part.Path, part.ContentItem.ContentItemId); } part.Apply(); } } /// <summary> /// Get the pattern from the AutoroutePartSettings property for its type /// </summary> private string GetPattern(AutoroutePart part) { var contentTypeDefinition = _contentDefinitionManager.GetTypeDefinition(part.ContentItem.ContentType); var contentTypePartDefinition = contentTypeDefinition.Parts.FirstOrDefault(x => String.Equals(x.PartDefinition.Name, nameof(AutoroutePart))); var pattern = contentTypePartDefinition.GetSettings<AutoroutePartSettings>().Pattern; return pattern; } private async Task<string> GenerateUniqueAbsolutePathAsync(string path, string contentItemId) { var version = 1; var unversionedPath = path; var versionSeparatorPosition = path.LastIndexOf('-'); if (versionSeparatorPosition > -1 && Int32.TryParse(path.Substring(versionSeparatorPosition).TrimStart('-'), out version)) { unversionedPath = path.Substring(0, versionSeparatorPosition); } while (true) { // Unversioned length + separator char + version length. var quantityCharactersToTrim = unversionedPath.Length + 1 + version.ToString().Length - AutoroutePart.MaxPathLength; if (quantityCharactersToTrim > 0) { unversionedPath = unversionedPath.Substring(0, unversionedPath.Length - quantityCharactersToTrim); } var versionedPath = $"{unversionedPath}-{version++}"; if (await IsAbsolutePathUniqueAsync(versionedPath, contentItemId)) { return versionedPath; } } } private async Task<bool> IsAbsolutePathUniqueAsync(string path, string contentItemId) { path = path.Trim('/'); var paths = new string[] { path, "/" + path, path + "/", "/" + path + "/" }; var possibleConflicts = await _session.QueryIndex<AutoroutePartIndex>(o => (o.Published || o.Latest) && o.Path.IsIn(paths)).ListAsync(); if (possibleConflicts.Any()) { if (possibleConflicts.Any(x => x.ContentItemId != contentItemId) || possibleConflicts.Any(x => !String.IsNullOrEmpty(x.ContainedContentItemId) && x.ContainedContentItemId != contentItemId)) { return false; } } return true; } } }
44.322917
218
0.590787
[ "BSD-3-Clause" ]
Tsjerno/OrchardCore
src/OrchardCore.Modules/OrchardCore.Autoroute/Handlers/AutoroutePartHandler.cs
21,275
C#
using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Text; using Dapper; using Dragon.Data; namespace Dapper { public static partial class SqlMapperExtensions { public static bool ExistsTable<T>(this IDbConnection connection, IDbTransaction transaction = null, int? commandTimeout = null) where T : class { var type = typeof(T); var values = new Dictionary<string, object>(); var metadata = MetadataFor(type); var sql = TSQLGenerator.BuildExistsTable(metadata); return connection.Query(sql, transaction: transaction, commandTimeout: commandTimeout).Any(); } #region TableDropper public static void DropTableIfExists<T>(this IDbConnection connection, IDbTransaction transaction = null, int? commandTimeout = null) where T : class { DropTable<T>(connection, true, transaction, commandTimeout); } public static void DropTableIfExists(this IDbConnection connection, string name, IDbTransaction transaction = null, int? commandTimeout = null) { DropTable(connection, name, true, transaction, commandTimeout); } public static void DropTable<T>(this IDbConnection connection, bool onlyIfExists, IDbTransaction transaction = null, int? commandTimeout = null) where T : class { var sql = DropTableSQL<T>(onlyIfExists); connection.Execute(sql, transaction: transaction, commandTimeout: commandTimeout); } public static void DropTable(this IDbConnection connection, string name, bool onlyIfExists, IDbTransaction transaction = null, int? commandTimeout = null) { var sql = DropTableSQL(name, onlyIfExists); connection.Execute(sql, transaction: transaction, commandTimeout: commandTimeout); } private static string DropTableSQL<T>(bool onlyIfExists) where T : class { var type = typeof(T); var metadata = MetadataFor(typeof (T)); return DropTableSQL(metadata.TableName, onlyIfExists); } private static string DropTableSQL(string name, bool onlyIfExists) { StringBuilder sqlDrop = new StringBuilder(); if (onlyIfExists) { sqlDrop.AppendFormat("IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = '{0}')", name); } sqlDrop.AppendFormat("DROP TABLE [dbo].[{0}]", name); return sqlDrop.ToString(); } #endregion #region TableCreator public static void CreateTableIfNotExists<T>(this IDbConnection connection, IDbTransaction transaction = null, int? commandTimeout = null) where T : class { CreateTable<T>(connection, true, transaction, commandTimeout); } public static void CreateTable<T>(this IDbConnection connection, bool onlyIfNotExists, IDbTransaction transaction = null, int? commandTimeout = null) where T : class { var type = typeof(T); var values = new Dictionary<string, object>(); var metadata = MetadataFor(type); var sql = TSQLGenerator.BuildCreate(metadata, onlyIfNotExists: onlyIfNotExists); connection.Execute(sql, transaction: transaction, commandTimeout: commandTimeout); } #endregion } }
35.752577
173
0.651096
[ "MIT" ]
aduggleby/dragon
proj-core/Data/Dragon.Data/DapperExtensions/SqlMapperExtensions_TableCreatorDropper.cs
3,470
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.RecoveryServices.V20210201.Outputs { [OutputType] public sealed class DailyRetentionFormatResponse { /// <summary> /// List of days of the month. /// </summary> public readonly ImmutableArray<Outputs.DayResponse> DaysOfTheMonth; [OutputConstructor] private DailyRetentionFormatResponse(ImmutableArray<Outputs.DayResponse> daysOfTheMonth) { DaysOfTheMonth = daysOfTheMonth; } } }
28.607143
96
0.696629
[ "Apache-2.0" ]
pulumi-bot/pulumi-azure-native
sdk/dotnet/RecoveryServices/V20210201/Outputs/DailyRetentionFormatResponse.cs
801
C#
using System; using System.Collections.Generic; using IntegrationTests.Typecast; using VSharp.Test; namespace IntegrationTests { public interface IKeeper<in T> { void Keep(T obj); } public class Bag<T> : IKeeper<T> { private Queue<T> _queue; public Bag() { _queue = new Queue<T>(); } public void Keep(T obj) { _queue.Enqueue(obj); } } [TestSvmFixture] public static class GenericInitialize<T, U, P, K, N, Z> where T : U where U : IKeeper<P> where P : struct, IKeeper<T> where K : class, IKeeper<U> where N : IKeeper<K> where Z : List<int> { public static class NonGenericClassInsideGenericClass { public static K GenericMethodOfNonGenericType(K k) { return k; } } [TestSvm] public static LinkedList<int> RetDictionary() { return new LinkedList<int>(); } [TestSvm] public static List<double> RetList() { return new List<double>(); } [TestSvm] public static T RetT(T t) { return t; } } [TestSvmFixture] public static class GenericTest<T, U, P, K, N, Z> where T : U where U : IKeeper<P> where P : struct, IKeeper<T> where K : class, IKeeper<U> where N : IKeeper<K> where Z : List<int> { [TestSvm] public static T RetT(T t) { return t; } [TestSvm] public static U RetU(U u) { return u; } [TestSvm] public static P RetP(P p) { return p; } [TestSvm] public static K RetK(K k) { return k; } [TestSvm] public static N RetN(N n) { return n; } [TestSvm] public static Z RetZ(Z z) { return z; } } [TestSvmFixture] public static class GenericClass<R, V> where R : class where V : struct { [TestSvm] public static R RetR(R r) { return r; } public static object Ret0(R r) { return 0; } [TestSvm] public static V RetV(V v) { return v; } } [TestSvmFixture] public static class SpecializeGenerics { [TestSvm] public static object RetConstructedRWithInt() { return GenericClass<object, int>.RetR(0); } // [TestSvm] // public static object RetConstructedRWithInt2() // { // return GenericClass<int, int>.RetR(0, 0); // } [TestSvm] public static object RetConstructedR0() { return GenericClass<object, int>.Ret0(0); } [TestSvm] public static object RetConstructedRWithObject() { return GenericClass<object, int>.RetR(new object()); } [TestSvm] public static int RetConstructedVWithInt() { return GenericClass<object, int>.RetV(0); } [TestSvm] public static SimpleStruct Test_OnlyGenericMethod_1() { return GenericMethodInsideGenericType<object, object, int>.OnlyGenericMethod<SimpleStruct>(new SimpleStruct()); } [TestSvm] public static object Test_OnlyGenericMethod_2() { var obj = 1; return GenericMethodInsideGenericType<object, object, int>.OnlyGenericMethod<object>(obj); } [TestSvm] public static int Test_MixedGenericParameterAndTypeGenerics_RetW_1() { int w = 1; object t = new object(); object r = new object(); int v = 2; return GenericMethodInsideGenericType<object, object, int>.MixedGenericParameterAndTypeGenerics_RetW<int>(w, t, r, v); } [TestSvm] public static object Test_MixedGenericParameterAndTypeGenerics_RetT_1() { int w = 1; object t = new object(); object r = new object(); int v = 2; return GenericMethodInsideGenericType<object, object, int>.MixedGenericParameterAndTypeGenerics_RetT<int>(w, t, r, v); } [TestSvm] public static object Test_MixedGenericParameterAndTypeGenerics_RetT_2() { int w = 1; object t = new object(); int v = 2; return GenericMethodInsideGenericType<object, object, int>.MixedGenericParameterAndTypeGenerics_RetT<int>(w, t, t, v); } [TestSvm] public static int Test_MixedGenericParameterAndTypeGenerics_RetV_1() { int w = 1; object t = new object(); object r = new object(); int v = 2; return GenericMethodInsideGenericType<object, object, int>.MixedGenericParameterAndTypeGenerics_RetV<int>(w, t, r, v); } [TestSvm] public static int Test_RetDuplicateV_1() { int v = 1; return GenericMethodInsideGenericType<IKeeper<int>, IKeeper<object>, SimpleStruct>.RetDuplicateV<int>(v); } } [TestSvmFixture] public static class GenericMethodInsideGenericType<T, R, V> where R : class where V : struct { public static W OnlyGenericMethod<W>(W w) { return w; } public static W MixedGenericParameterAndTypeGenerics_RetW<W>(W w, T t, R r, V v) { return w; } public static T MixedGenericParameterAndTypeGenerics_RetT<W>(W w, T t, R r, V v) { return t; } public static T MixedGenericParameterAndTypeGenerics_RetT<W>(W w, V r, T t, V v) { return t; } public static V MixedGenericParameterAndTypeGenerics_RetV<W>(W w, T t, R r, V v) { return v; } // this type parameter duplication is done intentionally public static V RetDuplicateV<V>(V v) { return v; } } [TestSvmFixture] public class Foo<T, U> { private T _field; public Foo() { } [TestSvm] public T GetFields() { return _field; } [TestSvm] public void SetField(T f) { _field = f; } } [TestSvmFixture] public static class GenericMethod { [TestSvm(100)] public static int TestFoo(Foo<int, Piece> f) { if (f == null) return 0; return f.GetFields(); } } [TestSvmFixture] public static class TestUnion { public static Coord RetCoord(Object obj, Coord coord, int field) { if (obj is BlackPawn) { coord.X = 42; } if (obj is Pawn) { coord.X += 66; } return coord; } public static Object Ret(Object obj) { var f = obj as BlackPawn; if (f != null) { f.SetNewField(42); } var a = obj as Pawn; if (a != null) { int b = a.GetNewField(); a.SetNewField(b + 66); } return obj; } [TestSvm(100)] public static int RetWorked(Object obj, int a) { if (obj as BlackPawn != null) { a = 5; } if (obj as Pawn != null) { a = a + 6; } return a; } } // public static class GenericCast // { // public static void FilterAndKeep(List<Pawn> listPawn, IKeeper<Pawn> bag) // { // foreach (var pawn in listPawn) // { // if (pawn.GetNewField() > 5) // { // bag.Keep(pawn); // } // } // } // // public static void TestFilterAndKeep() // { // IKeeper<Piece> myKeeper = new Bag<Piece>(); // List<Pawn> myList = new List<Pawn>(); // FilterAndKeep(myList, myKeeper); // } // // public static void TestContrvarianceAndCovariance() // { // Func<Piece, Pawn> func = (x => new Pawn(x.GetCoord(), x.GetRate())); // Func<Pawn, Piece> newFunc = func; // } // } // public interface IFooTest<T, U> // where T : IFoo<U> // where U : IFoo<T> // { // // } // // public class FooFoo<T, U> {} // public interface IFoo<out T> where T : Typecast.Piece {} // // public interface IFooOne : IFoo<IFooTwo> {} // // public interface IFooTwo : IFoo<IFooOne> {} // // public class RecFoo : Foo<RecFoo> {} // public class RecFooOne : Foo<RecFooTwo> {} // public class RecFooTwo : Foo<RecFooOne> {} // // public class Ret<T, U> // where T : Foo<U>, new() // where U : Foo<T> // { //TODO: don't parse, need fix // public delegate Object MyDelegateOne(String obj); // // public delegate Object MyDelegateTwo(Object obj); // // public T PropT { get; set; } // public U PropU { get; set; } // // public bool TestCheckCast(RecFooOne obj1, RecFooTwo obj2) // { // return obj1 is T && obj2 is U; // } // } }
23.875306
130
0.493292
[ "Apache-2.0" ]
mxprshn/VSharp
VSharp.Test/Tests/Generic.cs
9,767
C#