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.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
namespace PathLib
{
/// <summary>
/// Pure paths do not implement any IO operations and may be
/// used cross-platform.
/// </summary>
[TypeConverter(typeof(PurePathFactoryConverter))]
public interface IPurePath
{
/// <summary>
/// Get the path's directory (between the root and the file).
/// </summary>
string Dirname { get; }
/// <summary>
/// Get the path's full directory name (including root). For
/// those expecting a similar output as
/// <see cref="System.IO.Path.GetDirectoryName"/>.
/// </summary>
string Directory { get; }
/// <summary>
/// Get the path's filename (basename + extension).
/// </summary>
string Filename { get; }
/// <summary>
/// Returns the filename minus the final extension.
/// </summary>
string Basename { get; }
/// <summary>
/// Returns the filename minus all extensions.
/// </summary>
string BasenameWithoutExtensions { get; }
/// <summary>
/// <para>Gets the path's last extension.</para>
/// <para>Extensions are prepended with a '.'</para>
/// </summary>
string Extension { get; }
/// <summary>
/// <para>
/// Get each of the path's extensions, in order from first to last
/// (inner to outer).
/// </para>
/// <para>
/// Extensions are prepended with a '.'
/// </para>
/// </summary>
string[] Extensions { get; }
/// <summary>
/// Gets the path
/// </summary>
string Root { get; }
/// <summary>
/// The drive value of the path (eg. c:).
/// Empty string on Posix machines.
/// </summary>
string Drive { get; }
/// <summary>
/// Concatenation of drive and root (eg. c:\)
/// </summary>
string Anchor { get; }
/// <summary>
/// Return the string representation of the path as a Posix
/// path (eg. using forward slashes).
/// </summary>
/// <returns>Posix string representation of the path.</returns>
string ToPosix();
/// <summary>
/// Returns true if the given path is absolute.
/// </summary>
/// <returns></returns>
bool IsAbsolute();
/// <summary>
/// Return true if the path is considered reserved (on Windows). Other
/// platforms do not have reserved paths. Filesystem calls on reserved
/// paths may fail mysteriously or have unintended effects.
/// </summary>
/// <returns></returns>
bool IsReserved();
/// <summary>
/// Join the current path with the provided paths, in turn.
/// </summary>
/// <param name="paths"></param>
/// <returns></returns>
IPurePath Join(params string[] paths);
/// <summary>
/// Join the current path with the provided paths, in turn.
/// </summary>
/// <param name="paths"></param>
/// <returns></returns>
IPurePath Join(params IPurePath[] paths);
/// <summary>
/// Join the current path with the provided path. In addition,
/// the joined path is not allowed to traverse outside the directory
/// of the original path. After combining, the result is checked to
/// ensure the first N characters (where N is the length of the
/// original path) is byte-for-byte equal to the original.
/// </summary>
/// <param name="relativePath"></param>
/// <param name="joined"></param>
/// <returns></returns>
bool TrySafeJoin(string relativePath, out IPurePath joined);
/// <summary>
/// Join the current path with the provided path. In addition,
/// the joined path is not allowed to traverse outside the directory
/// of the original path. After combining, the result is checked to
/// ensure the first N characters (where N is the length of the
/// original path) is byte-for-byte equal to the original.
/// </summary>
/// <param name="relativePath"></param>
/// <param name="joined"></param>
/// <returns></returns>
bool TrySafeJoin(IPurePath relativePath, out IPurePath joined);
/// <summary>
/// <para>
/// Test whether the path matches the given
/// glob pattern (* and ? are wildcards).
/// </para>
/// <para>
/// If pattern is relative, path can be either
/// relative or absolute. If absolute, the whole
/// path must match.
/// </para>
/// <para>
/// Matching is case insensitive on NT machines.
/// </para>
/// </summary>
/// <param name="pattern"></param>
/// <returns></returns>
bool Match(string pattern);
/// <summary>
/// Iterator through the individual directory/file parts of
/// the path (the parts separated by the path separator).
/// </summary>
IEnumerable<string> Parts { get; }
/// <summary>
/// Normalize the case of the path using the current program culture.
/// On case-insensitive platforms, will return the path lowercased,
/// otherwise the path is returned unchanged.
/// </summary>
/// <returns></returns>
IPurePath NormCase();
/// <summary>
/// Normalize the case of the path. On case-insensitive platforms,
/// will return the path lowercased, otherwise the path is returned
/// unchanged.
/// </summary>
/// <returns></returns>
IPurePath NormCase(CultureInfo currentCulture);
/// <summary>
/// Returns the parent directory of the current path.
/// </summary>
/// <returns></returns>
IPurePath Parent();
/// <summary>
/// Returns the nth parent directory of the current path.
/// </summary>
/// <param name="nthParent"></param>
/// <returns></returns>
IPurePath Parent(int nthParent);
/// <summary>
/// Iterate over the path's parents from most to least specific.
/// </summary>
/// <returns></returns>
IEnumerable<IPurePath> Parents();
/// <summary>
/// Return the current path as a URI.
/// </summary>
/// <exception cref="InvalidOperationException">
/// Thrown if attempting to create a URI from a relative path.
/// </exception>
/// <returns></returns>
Uri ToUri();
/// <summary>
/// Return the page stripped of its drive and root, if any.
/// </summary>
/// <returns></returns>
IPurePath Relative();
/// <summary>
/// Compute a version of this path relative to the
/// path represented by "parent".
/// </summary>
/// <param name="parent"></param>
/// <returns></returns>
IPurePath RelativeTo(IPurePath parent);
/// <summary>
/// Returns a new path with the directory name changed.
/// The drive, root, and filename all stay the same.
/// </summary>
/// <param name="newDirName"></param>
/// <returns></returns>
IPurePath WithDirname(string newDirName);
/// <summary>
/// Returns a new path with the directory name changed.
/// The drive, root, and filename all stay the same.
/// </summary>
/// <param name="newDirName"></param>
/// <returns></returns>
IPurePath WithDirname(IPurePath newDirName);
/// <summary>
/// Returns a new path with filename changed.
/// </summary>
/// <param name="newFilename"></param>
/// <returns></returns>
IPurePath WithFilename(string newFilename);
/// <summary>
/// Changes the extension of the current path.
/// </summary>
/// <param name="newExtension"></param>
/// <returns></returns>
IPurePath WithExtension(string newExtension);
/// <summary>
/// Return true if the path contains any of the specified components.
/// </summary>
/// <param name="components"></param>
/// <returns></returns>
bool HasComponents(PathComponent components);
/// <summary>
/// Return a string composed of all specified components.
/// </summary>
/// <param name="components">
/// The specified component(s).
/// </param>
/// <returns></returns>
string GetComponents(PathComponent components);
}
/// <summary>
/// Pure paths do not implement any IO operations and may be
/// used cross-platform.
/// </summary>
public interface IPurePath<TPath> : IPurePath
where TPath : IPurePath
{
/// <summary>
/// Join the current path with the provided paths, in turn.
/// </summary>
/// <param name="paths"></param>
/// <returns></returns>
new TPath Join(params string[] paths);
/// <summary>
/// Join the current path with the provided paths, in turn.
/// </summary>
/// <param name="paths"></param>
/// <returns></returns>
new TPath Join(params IPurePath[] paths);
/// <summary>
/// Join the current path with the provided path. In addition,
/// the joined path is not allowed to traverse outside the directory
/// of the original path. After combining, the result is checked to
/// ensure the first N characters (where N is the length of the
/// original path) is byte-for-byte equal to the original.
/// </summary>
/// <param name="path"></param>
/// <param name="joined"></param>
/// <returns></returns>
bool TrySafeJoin(string path, out TPath joined);
/// <summary>
/// Join the current path with the provided path. In addition,
/// the joined path is not allowed to traverse outside the directory
/// of the original path. After combining, the result is checked to
/// ensure the first N characters (where N is the length of the
/// original path) is byte-for-byte equal to the original.
/// </summary>
/// <param name="path"></param>
/// <param name="joined"></param>
/// <returns></returns>
bool TrySafeJoin(IPurePath path, out TPath joined);
/// <summary>
/// Normalize the case of the path using the current platform culture.
/// On case-insensitive platforms, will return the path lowercased,
/// otherwise the path is returned unchanged.
/// </summary>
/// <returns></returns>
new TPath NormCase();
/// <summary>
/// Normalize the case of the path. On case-insensitive platforms,
/// will return the path lowercased, otherwise the path is returned
/// unchanged.
/// </summary>
/// <returns></returns>
new TPath NormCase(CultureInfo currentCulture);
/// <summary>
/// Returns the parent directory of the current path.
/// </summary>
/// <returns></returns>
new TPath Parent();
/// <summary>
/// Returns the nth parent directory of the current path.
/// </summary>
/// <param name="nthParent"></param>
/// <returns></returns>
new TPath Parent(int nthParent);
/// <summary>
/// Iterate over the path's parents from most to least specific.
/// </summary>
/// <returns></returns>
new IEnumerable<TPath> Parents();
/// <summary>
/// Return the page stripped of its drive and root, if any.
/// </summary>
/// <returns></returns>
new TPath Relative();
/// <summary>
/// Compute a version of this path relative to the
/// path represented by "parent".
/// </summary>
/// <param name="parent"></param>
/// <returns></returns>
new TPath RelativeTo(IPurePath parent);
/// <summary>
/// Returns a new path with the directory name changed.
/// The drive, root, and filename all stay the same.
/// </summary>
/// <param name="newDirName"></param>
/// <returns></returns>
new TPath WithDirname(string newDirName);
/// <summary>
/// Returns a new path with the directory name changed.
/// The drive, root, and filename all stay the same.
/// </summary>
/// <param name="newDirName"></param>
/// <returns></returns>
new TPath WithDirname(IPurePath newDirName);
/// <summary>
/// Returns a new path with filename changed.
/// </summary>
/// <param name="newFilename"></param>
/// <returns></returns>
new TPath WithFilename(string newFilename);
/// <summary>
/// Changes the extension of the current path.
/// </summary>
/// <param name="newExtension"></param>
/// <returns></returns>
new TPath WithExtension(string newExtension);
}
}
| 35.696658 | 80 | 0.535503 | [
"MIT"
] | nemec/pathlib | PathLib/IPurePath.cs | 13,888 | C# |
// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information.
// Ported from um/shellapi.h in the Windows SDK for Windows 10.0.20348.0
// Original source is Copyright © Microsoft. All rights reserved.
namespace TerraFX.Interop.Windows;
/// <include file='NC_ADDRESS.xml' path='doc/member[@name="NC_ADDRESS"]/*' />
public unsafe partial struct NC_ADDRESS
{
/// <include file='NC_ADDRESS.xml' path='doc/member[@name="NC_ADDRESS.pAddrInfo"]/*' />
[NativeTypeName("struct NET_ADDRESS_INFO_ *")]
public NET_ADDRESS_INFO* pAddrInfo;
/// <include file='NC_ADDRESS.xml' path='doc/member[@name="NC_ADDRESS.PortNumber"]/*' />
public ushort PortNumber;
/// <include file='NC_ADDRESS.xml' path='doc/member[@name="NC_ADDRESS.PrefixLength"]/*' />
public byte PrefixLength;
}
| 41.809524 | 145 | 0.720957 | [
"MIT"
] | IngmarBitter/terrafx.interop.windows | sources/Interop/Windows/Windows/um/shellapi/NC_ADDRESS.cs | 880 | C# |
using UnityEngine;
public class SensorManager : MonoBehaviour
{
public DistanceSensor m_DistanceSensorPrefab;
public int m_Number = 8;
private DistanceSensor[] m_Sensors;
public void Start()
{
float angle = 360 / (float)m_Number;
for (int i = 0; i < m_Number; i++)
{
DistanceSensor sensor = Instantiate(m_DistanceSensorPrefab);
sensor.transform.position = transform.position;
sensor.transform.rotation = Quaternion.Euler(0, 0, angle * i);
sensor.transform.parent = transform;
}
m_Sensors = GetComponentsInChildren<DistanceSensor>();
}
public float[] ToArray()
{
float[] array = new float[m_Sensors.Length];
for (int i = 0; i < m_Sensors.Length; i++)
array[i] = m_Sensors[i].Distance;
return array;
}
}
| 25.588235 | 74 | 0.606897 | [
"MIT"
] | kleberandrade/evolve-asteroids | Assets/Scripts/SensorManager.cs | 872 | C# |
/*
This code is derived from jgit (http://eclipse.org/jgit).
Copyright owners are documented in jgit's IP log.
This program and the accompanying materials are made available
under the terms of the Eclipse Distribution License v1.0 which
accompanies this distribution, is reproduced below, and is
available at http://www.eclipse.org/org/documents/edl-v10.php
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 the Eclipse Foundation, Inc. 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.Text;
using NGit.Revwalk;
using NGit.Util;
using Sharpen;
namespace NGit.Revwalk
{
/// <summary>Single line at the end of a message, such as a "Signed-off-by: someone".
/// </summary>
/// <remarks>
/// Single line at the end of a message, such as a "Signed-off-by: someone".
/// <p>
/// These footer lines tend to be used to represent additional information about
/// a commit, like the path it followed through reviewers before finally being
/// accepted into the project's main repository as an immutable commit.
/// </remarks>
/// <seealso cref="RevCommit.GetFooterLines()">RevCommit.GetFooterLines()</seealso>
public sealed class FooterLine
{
private readonly byte[] buffer;
private readonly Encoding enc;
private readonly int keyStart;
private readonly int keyEnd;
private readonly int valStart;
private readonly int valEnd;
internal FooterLine(byte[] b, Encoding e, int ks, int ke, int vs, int ve)
{
buffer = b;
enc = e;
keyStart = ks;
keyEnd = ke;
valStart = vs;
valEnd = ve;
}
/// <param name="key">key to test this line's key name against.</param>
/// <returns>
/// true if
/// <code>key.getName().equalsIgnorecase(getKey())</code>
/// .
/// </returns>
public bool Matches(FooterKey key)
{
byte[] kRaw = key.raw;
int len = kRaw.Length;
int bPtr = keyStart;
if (keyEnd - bPtr != len)
{
return false;
}
for (int kPtr = 0; kPtr < len; )
{
byte b = buffer[bPtr++];
if ('A' <= b && ((sbyte)b) <= 'Z')
{
b += (byte)('a') - (byte)('A');
}
if (b != kRaw[kPtr++])
{
return false;
}
}
return true;
}
/// <returns>
/// key name of this footer; that is the text before the ":" on the
/// line footer's line. The text is decoded according to the commit's
/// specified (or assumed) character encoding.
/// </returns>
public string GetKey()
{
return RawParseUtils.Decode(enc, buffer, keyStart, keyEnd);
}
/// <returns>
/// value of this footer; that is the text after the ":" and any
/// leading whitespace has been skipped. May be the empty string if
/// the footer has no value (line ended with ":"). The text is
/// decoded according to the commit's specified (or assumed)
/// character encoding.
/// </returns>
public string GetValue()
{
return RawParseUtils.Decode(enc, buffer, valStart, valEnd);
}
/// <summary>Extract the email address (if present) from the footer.</summary>
/// <remarks>
/// Extract the email address (if present) from the footer.
/// <p>
/// If there is an email address looking string inside of angle brackets
/// (e.g. "<a@b>"), the return value is the part extracted from inside the
/// brackets. If no brackets are found, then
/// <see cref="GetValue()">GetValue()</see>
/// is returned
/// if the value contains an '@' sign. Otherwise, null.
/// </remarks>
/// <returns>email address appearing in the value of this footer, or null.</returns>
public string GetEmailAddress()
{
int lt = RawParseUtils.NextLF(buffer, valStart, '<');
if (valEnd <= lt)
{
int at = RawParseUtils.NextLF(buffer, valStart, '@');
if (valStart < at && at < valEnd)
{
return GetValue();
}
return null;
}
int gt = RawParseUtils.NextLF(buffer, lt, '>');
if (valEnd < gt)
{
return null;
}
return RawParseUtils.Decode(enc, buffer, lt, gt - 1);
}
public override string ToString()
{
return GetKey() + ": " + GetValue();
}
}
}
| 30.594286 | 86 | 0.688831 | [
"BSD-3-Clause"
] | Kavisha90/IIT-4th-year | NGit/NGit.Revwalk/FooterLine.cs | 5,354 | C# |
using System;
namespace Microsoft.Maui.Controls
{
public sealed class RowDefinition : BindableObject, IDefinition
{
public static readonly BindableProperty HeightProperty = BindableProperty.Create("Height", typeof(GridLength), typeof(RowDefinition), new GridLength(1, GridUnitType.Star),
propertyChanged: (bindable, oldValue, newValue) => ((RowDefinition)bindable).OnSizeChanged());
public RowDefinition()
{
MinimumHeight = -1;
}
public GridLength Height
{
get { return (GridLength)GetValue(HeightProperty); }
set { SetValue(HeightProperty, value); }
}
internal double ActualHeight { get; set; }
internal double MinimumHeight { get; set; }
public event EventHandler SizeChanged;
void OnSizeChanged()
{
EventHandler eh = SizeChanged;
if (eh != null)
eh(this, EventArgs.Empty);
}
}
} | 24.676471 | 173 | 0.72348 | [
"MIT"
] | JanNepras/maui | src/Controls/src/Core/RowDefinition.cs | 839 | C# |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.Azure.WebJobs.Host.Executors;
using Microsoft.Azure.WebJobs.Host.TestCommon;
using Xunit;
namespace Microsoft.Azure.WebJobs.Host.UnitTests.Executors
{
public class TaskMethodInvokerTests
{
[Fact]
public void InvokeAsync_DelegatesToLambda()
{
// Arrange
object expectedInstance = new object();
object[] expectedArguments = new object[0];
bool invoked = false;
object instance = null;
object[] arguments = null;
Func<object, object[], Task> lambda = (i, a) =>
{
invoked = true;
instance = i;
arguments = a;
return Task.FromResult(0);
};
IMethodInvoker<object> invoker = CreateProductUnderTest(lambda);
// Act
Task task = invoker.InvokeAsync(expectedInstance, expectedArguments);
// Assert
Assert.NotNull(task);
task.GetAwaiter().GetResult();
Assert.True(invoked);
Assert.Same(expectedInstance, instance);
Assert.Same(expectedArguments, arguments);
}
[Fact]
public async Task InvokeAsync_IfLambdaThrows_PropogatesException()
{
// Arrange
InvalidOperationException expectedException = new InvalidOperationException();
Func<object, object[], Task> lambda = (i1, i2) =>
{
throw expectedException;
};
IMethodInvoker<object> invoker = CreateProductUnderTest(lambda);
object instance = null;
object[] arguments = null;
// Act & Assert
InvalidOperationException exception = await Assert.ThrowsAsync<InvalidOperationException>(
() => invoker.InvokeAsync(instance, arguments));
Assert.Same(expectedException, exception);
}
[Fact]
public void InvokeAsync_IfLambdaReturnsCanceledTask_ReturnsCanceledTask()
{
// Arrange
Func<object, object[], Task> lambda = (i1, i2) =>
{
TaskCompletionSource<object> source = new TaskCompletionSource<object>();
source.SetCanceled();
return source.Task;
};
IMethodInvoker<object> invoker = CreateProductUnderTest(lambda);
object instance = null;
object[] arguments = null;
// Act
Task task = invoker.InvokeAsync(instance, arguments);
// Assert
Assert.NotNull(task);
task.WaitUntilCompleted();
Assert.Equal(TaskStatus.Canceled, task.Status);
}
[Fact]
public void InvokeAsync_IfLambdaReturnsFaultedTask_ReturnsFaultedTask()
{
// Arrange
Exception expectedException = new InvalidOperationException();
Func<object, object[], Task> lambda = (i1, i2) =>
{
TaskCompletionSource<object> source = new TaskCompletionSource<object>();
source.SetException(expectedException);
return source.Task;
};
IMethodInvoker<object> invoker = CreateProductUnderTest(lambda);
object instance = null;
object[] arguments = null;
// Act
Task task = invoker.InvokeAsync(instance, arguments);
// Assert
Assert.NotNull(task);
task.WaitUntilCompleted();
Assert.Equal(TaskStatus.Faulted, task.Status);
Assert.NotNull(task.Exception);
Assert.Same(expectedException, task.Exception.InnerException);
}
[Fact]
public void InvokeAsync_IfLambdaReturnsNull_ReturnsNull()
{
// Arrange
Func<object, object[], Task> lambda = (i1, i2) => null;
IMethodInvoker<object> invoker = CreateProductUnderTest(lambda);
object instance = null;
object[] arguments = null;
// Act
Task task = invoker.InvokeAsync(instance, arguments);
// Assert
Assert.Null(task);
}
[Fact]
public void InvokeAsync_IfLambdaReturnsNonGenericTask_ReturnsCompletedTask()
{
// Arrange
Func<object, object[], Task> lambda = (i1, i2) =>
{
Task innerTask = new Task(() => { });
innerTask.Start();
Assert.False(innerTask.GetType().IsGenericType); // Guard
return innerTask;
};
IMethodInvoker<object> invoker = CreateProductUnderTest(lambda);
object instance = null;
object[] arguments = null;
// Act
Task task = invoker.InvokeAsync(instance, arguments);
// Assert
Assert.NotNull(task);
task.WaitUntilCompleted();
Assert.Equal(TaskStatus.RanToCompletion, task.Status);
}
[Fact]
public void InvokeAsync_IfLambdaReturnsNestedTask_Throws()
{
// Arrange
Func<object, object[], Task> lambda = (i1, i2) =>
{
TaskCompletionSource<Task> source = new TaskCompletionSource<Task>();
source.SetResult(null);
return source.Task;
};
IMethodInvoker<object> invoker = CreateProductUnderTest(lambda);
object instance = null;
object[] arguments = null;
// Act & Assert
ExceptionAssert.ThrowsInvalidOperation(() => invoker.InvokeAsync(instance, arguments),
"Returning a nested Task is not supported. Did you mean to await or Unwrap the task instead of " +
"returning it?");
}
private static TaskMethodInvoker<object> CreateProductUnderTest(Func<object, object[], Task> lambda)
{
return new TaskMethodInvoker<object>(lambda);
}
}
}
| 34.282609 | 114 | 0.564204 | [
"MIT"
] | Bjakes1950/azure-webjobs-sdk | test/Microsoft.Azure.WebJobs.Host.UnitTests/Executors/TaskMethodInvokerTests.cs | 6,310 | C# |
using System;
using System.Linq;
using System.Threading.Tasks;
using GoApi;
using GoApi.Core;
using GoApi.Core.Global;
using GoApi.Import;
using GoApi.Party;
using GoApi.Products;
using GoApi.SalesOrders;
namespace ImportDemo
{
public class SalesOrderImport
{
/// <summary>
/// This is is very simple demo of how to create a sales order import.
/// </summary>
public static async Task SalesOrderImportDemo()
{
// Set up authorization settings
var authorizationSettings = new AuthorizationSettings
{
ApplicationKey = "<You Application Key Here>",
ClientKey = "<PowerOffice Go Client Key Here>",
TokenStore = new BasicInMemoryTokenStore(),
EndPointHost = Settings.EndPointMode.Production //For authorization against the demo environment - Change this to Settings.EndPointMode.Demo
};
// Initialize the PowerOffice Go API and request authorization
var api = await Go.CreateAsync(authorizationSettings);
//First we need to make sure that all customers that we're using are created in PowerOffice Go
//For more a more detailed example on how to do changes to customers, check out the CustomerDemo on https://github.com/PowerOffice/go-api/tree/master/Examples
UpsertCustomers(api);
//Then we need to make sure that all products that we're using are created in PowerOffice Go
//For more a more detailed example on how to do changes to products, check out the ProductDemo on https://github.com/PowerOffice/go-api/tree/master/Examples
UpsertProducts(api);
//Now it's time to import the sales orders
// Create the import object and upload it to the server
var import = CreateAndSaveImport(api);
// List un-posted imports
ListUnpostedImports(api);
// The user can post the journal manually from the PowerOffice GO user interface,
// or the journal can be posted by code.
PostImport(api, import);
Console.WriteLine("Demo finished! Press any key to exit...");
Console.ReadKey();
}
private static void UpsertCustomers(Go api)
{
//Query for all customers in PowerOffice
var allCustomers = api.Customer.Get();
//Trying to get customer that is beeing used in this example
var customer = allCustomers.FirstOrDefault(c => c.Code == 12345);
//Checking if the customer we're gonna use exist in PowerOffice Go
if (customer != null)
{
//Customer exists already in Go - we can update it if needed
customer.Name = "Edited customer name";
Console.WriteLine("Saving changes to customer with customer code " + customer.Code +
" to PowerOffice Go.");
api.Customer.Save(customer);
}
else
{
//Customer does not exist in Go, we then create a new one
customer = new Customer
{
Code = 12345,
Name = "Customer 12345",
VatNumber = "999999999"
};
Console.WriteLine("Saving customer " + customer.Name + " to PowerOffice Go.");
api.Customer.Save(customer);
}
}
/// <summary>
/// Upserts the products.
/// </summary>
/// <param name="api">The API.</param>
private static void UpsertProducts(Go api)
{
//Query for all products in PowerOffice
var allProducts = api.Product.Get();
//Trying to get product that is used in this example
var product = allProducts.FirstOrDefault(p => p.Code == "240");
//Checking if the product i'm gonna use exist in PowerOffice Go
if (product != null)
{
//Product exists already in Go - we can update it then if needed
product.Name = "Edited testproduct 240";
Console.WriteLine("Saving changes to product with product code " + product.Code + " to PowerOffice Go.");
api.Product.Save(product);
}
else
{
//Product does not exist in Go - we then create it
product = new Product
{
Code = "240",
Name = "Testproduct 240",
Description = "Description for testproduct 240",
SalesAccount = 3000,
VatExemptSalesAccount = 3100,
SalesPrice = 250,
CostPrice = 100
};
Console.WriteLine("Saving product " + product.Name + " to PowerOffice Go.");
api.Product.Save(product);
}
}
private static void ListUnpostedImports(Go api)
{
// Get list of imports
Console.WriteLine("List of unposted imports:");
var imports = api.Import.Get().Where(i => i.IsPosted == false);
foreach (var import in imports)
Console.WriteLine("{0}: {1} {2} {3}", import.Id, import.Type, import.Description,
import.IsPosted ? "[POSTED]" : "");
Console.WriteLine();
}
/// <summary>
/// Posts the import.
/// </summary>
/// <param name="api">The API.</param>
/// <param name="import">The import.</param>
private static void PostImport(Go api, Import import)
{
Console.WriteLine("Posting journal...");
api.Import.Post(import);
Console.WriteLine("Done...");
}
private static Import CreateAndSaveImport(Go api)
{
// Set up a journal for import
Console.WriteLine("Creating Sales Order import");
// Create the import "header"
var import = new Import
{
Description = "Sample Sales Order Import",
Date = DateTime.Now
};
Console.WriteLine("Adding sales orders");
//Creating a sales order
var salesOrder = new SalesOrder(1234, DateTime.Now, 12345)
{
Reference = "Sales order reference",
PaymentTerms = 14,
Currency = "NOK"
};
//Creating a sales order line for 5x product 240 with 10% discount
var firstOrderLine = new SalesOrderLine("240", 5, 10);
//By setting SalesOrderLineUnitPrice we can override product price for this sales order line
firstOrderLine.SalesOrderLineUnitPrice = 1000;
salesOrder.AddSalesOrderLine(firstOrderLine);
//Optional: Creating a sales order description line
var firstDescriptionLine = new SalesOrderLine("This is a description that will appear on the order");
salesOrder.AddSalesOrderLine(firstDescriptionLine);
//Adding Sales order to import object
import.SalesOrders.Add(salesOrder);
// Save the journal to the server. When this call has finished, the order import will
// appear in the Journal Import list in PowerOffice Go.
Console.WriteLine("Saving journal...");
//Saves the import
api.Import.Save(import);
Console.WriteLine("Journal was saved and assign the Id: " + import.Id);
return import;
}
}
} | 39.386139 | 171 | 0.546757 | [
"MIT"
] | PowerOffice/go-api | Examples/ImportDemo/SalesOrderImport.cs | 7,958 | C# |
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Dynamic;
namespace ConnectionFactory
{
public static class CfExtensions
{
public static dynamic ToExpando(this IDataReader reader)
{
var dictionary = new ExpandoObject() as IDictionary<string, object>;
for (int i = 0; i < reader.FieldCount; i++)
dictionary.Add(reader.GetName(i), reader[i] == DBNull.Value ? null : reader[i]);
return dictionary as ExpandoObject;
}
#region QueryForList
public static IList<T> QueryForList<T>(this DbConnection db,
string cmdText, object cmdParms, int commandTimeout = -1) where T : new()
{
using(var conn = new CfConnection(db))
{
var cmd = conn.CreateCfCommand(commandTimeout);
return cmd.QueryForList<T>(cmdText, cmdParms);
}
}
public static IList<dynamic> QueryForList(this DbConnection db,
string cmdText, object cmdParms, int commandTimeout = -1)
{
using (var conn = new CfConnection(db))
{
var cmd = conn.CreateCfCommand(commandTimeout);
return cmd.QueryForList(cmdText, cmdParms);
}
}
#endregion
#region QueryForObject
public static T QueryForObject<T>(this DbConnection db,
string cmdText, object cmdParms, int commandTimeout = -1) where T : new()
{
using (var conn = new CfConnection(db))
{
var cmd = conn.CreateCfCommand(commandTimeout);
return cmd.QueryForObject<T>(cmdText, cmdParms);
}
}
public static dynamic QueryForObject(this DbConnection db,
string cmdText, object cmdParms, int commandTimeout = -1)
{
using (var conn = new CfConnection(db))
{
var cmd = conn.CreateCfCommand(commandTimeout);
return cmd.QueryForObject(cmdText, cmdParms);
}
}
#endregion
}
}
| 33.384615 | 96 | 0.571889 | [
"MIT"
] | afernandes/ConnectionFactory.NetCore | src/CfExtensions.cs | 2,172 | C# |
namespace Demo.OAuth2.WebApi.Areas.HelpPage
{
/// <summary>
/// Indicates whether the sample is used for request or response
/// </summary>
public enum SampleDirection
{
Request = 0,
Response
}
} | 21.363636 | 68 | 0.612766 | [
"Apache-2.0"
] | bluedoctor/PWMIS.OAuth2.0 | Demo.OAuth2.WebApi/Areas/HelpPage/SampleGeneration/SampleDirection.cs | 235 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace geniikw.DataRenderer2D
{
/// <summary>
/// no render line.
/// </summary>
public class GizmoLine : MonoBehaviour
{
public Spline line;
public Color color = Color.white;
public bool isOnlyViewSelected = true;
public bool debugColor = false;
private void OnDrawGizmos()
{
if (isOnlyViewSelected)
return;
DrawLine();
}
private void OnDrawGizmosSelected()
{
if (!isOnlyViewSelected)
return;
DrawLine();
}
public Vector3 GetPosition(float r)
{
return transform.TransformPoint( line.GetPosition(r));
}
public Vector3 GetDirection(float r)
{
return line.GetDirection(r);
}
private void DrawLine()
{
var colorStore = Gizmos.color;
foreach (var pair in line.TargetPairList)
{
var dt = pair.GetDT(line.option.DivideLength);
for (float t = pair.start; t < pair.end; t+=dt)
{
var p0 = transform.TransformPoint(Curve.Auto(pair.n0, pair.n1, t));
var p1 = transform.TransformPoint(Curve.Auto(pair.n0, pair.n1, t+dt));
if (debugColor)
Gizmos.color = new Color(Random.Range(0f, 1f), Random.Range(0f, 1f), Random.Range(0f, 1f));
else
Gizmos.color = color;
Gizmos.DrawLine(p0,p1);
}
}
Gizmos.color = colorStore;
}
}
} | 27.873016 | 115 | 0.503986 | [
"MIT"
] | Lanboost/LanboostPathfindingSharp | UnityExample/PathFinderExample/Assets/DataRenderer2D/Line/Scripts/Component/GizmoLine.cs | 1,758 | C# |
using System;
using System.Collections.Generic;
using System.Data.Common;
using Abp.Data;
using Abp.Dependency;
using Abp.Domain.Repositories;
using Abp.Domain.Uow;
using Abp.Extensions;
using Abp.MultiTenancy;
using Abp.Runtime.Security;
using Abp.Pdnf.EntityFrameworkCore;
using Abp.Pdnf.EntityFrameworkCore.Seed;
using Abp.Pdnf.MultiTenancy;
namespace Abp.Pdnf.Migrator
{
public class MultiTenantMigrateExecuter : ITransientDependency
{
private readonly Log _log;
private readonly AbpZeroDbMigrator _migrator;
private readonly IRepository<Tenant> _tenantRepository;
private readonly IDbPerTenantConnectionStringResolver _connectionStringResolver;
public MultiTenantMigrateExecuter(
AbpZeroDbMigrator migrator,
IRepository<Tenant> tenantRepository,
Log log,
IDbPerTenantConnectionStringResolver connectionStringResolver)
{
_log = log;
_migrator = migrator;
_tenantRepository = tenantRepository;
_connectionStringResolver = connectionStringResolver;
}
public bool Run(bool skipConnVerification)
{
var hostConnStr = CensorConnectionString(_connectionStringResolver.GetNameOrConnectionString(new ConnectionStringResolveArgs(MultiTenancySides.Host)));
if (hostConnStr.IsNullOrWhiteSpace())
{
_log.Write("Configuration file should contain a connection string named 'Default'");
return false;
}
_log.Write("Host database: " + ConnectionStringHelper.GetConnectionString(hostConnStr));
if (!skipConnVerification)
{
_log.Write("Continue to migration for this host database and all tenants..? (Y/N): ");
var command = Console.ReadLine();
if (!command.IsIn("Y", "y"))
{
_log.Write("Migration canceled.");
return false;
}
}
_log.Write("HOST database migration started...");
try
{
_migrator.CreateOrMigrateForHost(SeedHelper.SeedHostDb);
}
catch (Exception ex)
{
_log.Write("An error occured during migration of host database:");
_log.Write(ex.ToString());
_log.Write("Canceled migrations.");
return false;
}
_log.Write("HOST database migration completed.");
_log.Write("--------------------------------------------------------");
var migratedDatabases = new HashSet<string>();
var tenants = _tenantRepository.GetAllList(t => t.ConnectionString != null && t.ConnectionString != "");
for (var i = 0; i < tenants.Count; i++)
{
var tenant = tenants[i];
_log.Write(string.Format("Tenant database migration started... ({0} / {1})", (i + 1), tenants.Count));
_log.Write("Name : " + tenant.Name);
_log.Write("TenancyName : " + tenant.TenancyName);
_log.Write("Tenant Id : " + tenant.Id);
_log.Write("Connection string : " + SimpleStringCipher.Instance.Decrypt(tenant.ConnectionString));
if (!migratedDatabases.Contains(tenant.ConnectionString))
{
try
{
_migrator.CreateOrMigrateForTenant(tenant);
}
catch (Exception ex)
{
_log.Write("An error occured during migration of tenant database:");
_log.Write(ex.ToString());
_log.Write("Skipped this tenant and will continue for others...");
}
migratedDatabases.Add(tenant.ConnectionString);
}
else
{
_log.Write("This database has already migrated before (you have more than one tenant in same database). Skipping it....");
}
_log.Write(string.Format("Tenant database migration completed. ({0} / {1})", (i + 1), tenants.Count));
_log.Write("--------------------------------------------------------");
}
_log.Write("All databases have been migrated.");
return true;
}
private static string CensorConnectionString(string connectionString)
{
var builder = new DbConnectionStringBuilder { ConnectionString = connectionString };
var keysToMask = new[] { "password", "pwd", "user id", "uid" };
foreach (var key in keysToMask)
{
if (builder.ContainsKey(key))
{
builder[key] = "*****";
}
}
return builder.ToString();
}
}
}
| 38.151515 | 163 | 0.540707 | [
"MIT"
] | wenzhongxu/DotNetCorePro | aspnet-core/src/Abp.Pdnf.Migrator/MultiTenantMigrateExecuter.cs | 5,036 | C# |
using System;
using System.IO;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Serilog;
using Serilog.Events;
using Serilog.Sinks.Elasticsearch;
namespace InternalGateway.Host
{
public class Program
{
public static int Main(string[] args)
{
try
{
Log.Information("Starting IdentityService.Host.");
CreateHostBuilder(args).Build().Run();
return 0;
}
catch (Exception ex)
{
Log.Fatal(ex, "IdentityService.Host terminated unexpectedly!");
return 1;
}
finally
{
Log.CloseAndFlush();
}
}
internal static IHostBuilder CreateHostBuilder(string[] args) =>
Microsoft.Extensions.Hosting.Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
})
.UseAutofac()
.UseSerilog();
}
}
| 26.883721 | 79 | 0.538927 | [
"MIT"
] | nbnbnb/official-abp-samples | MicroserviceDemo/gateways/InternalGateway.Host/Program.cs | 1,158 | 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 TfsDeployer.Web.Views
{
public partial class UptimeView
{
}
}
| 24.722222 | 81 | 0.417978 | [
"MIT"
] | mitchdenny/tfsdeployer | src/TfsDeployer.Web/Views/UptimeView.ascx.designer.cs | 447 | C# |
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Windows;
// 有关程序集的一般信息由以下
// 控制。更改这些特性值可修改
// 与程序集关联的信息。
[assembly: AssemblyTitle("Magnesium.Wpf")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Magnesium.Wpf")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
//将 ComVisible 设置为 false 将使此程序集中的类型
//对 COM 组件不可见。 如果需要从 COM 访问此程序集中的类型,
//请将此类型的 ComVisible 特性设置为 true。
[assembly: ComVisible(false)]
//若要开始生成可本地化的应用程序,请
//<PropertyGroup> 中的 .csproj 文件中
//例如,如果您在源文件中使用的是美国英语,
//使用的是美国英语,请将 <UICulture> 设置为 en-US。 然后取消
//对以下 NeutralResourceLanguage 特性的注释。 更新
//以下行中的“en-US”以匹配项目文件中的 UICulture 设置。
//[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)]
[assembly: ThemeInfo(
ResourceDictionaryLocation.None, //主题特定资源词典所处位置
//(当资源未在页面
//或应用程序资源字典中找到时使用)
ResourceDictionaryLocation.SourceAssembly //常规资源词典所处位置
//(当资源未在页面
//、应用程序或任何主题专用资源字典中找到时使用)
)]
// 程序集的版本信息由下列四个值组成:
//
// 主版本
// 次版本
// 生成号
// 修订号
//
//可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值,
// 方法是按如下所示使用“*”: :
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 27.910714 | 91 | 0.658349 | [
"MIT"
] | KureFM/Magnesium | Magnesium.Wpf/Properties/AssemblyInfo.cs | 2,206 | C# |
// -----------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// 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.
// -----------------------------------------------------------------------------
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.34209
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace Microsoft.Azure.Commands.Batch.Models
{
using System;
using System.Collections;
using System.Collections.Generic;
using Microsoft.Azure.Batch;
public class PSTaskConstraints
{
internal Microsoft.Azure.Batch.TaskConstraints omObject;
public PSTaskConstraints(System.Nullable<System.TimeSpan> maxWallClockTime, System.Nullable<System.TimeSpan> retentionTime, System.Nullable<int> maxTaskRetryCount)
{
this.omObject = new Microsoft.Azure.Batch.TaskConstraints(maxWallClockTime, retentionTime, maxTaskRetryCount);
}
internal PSTaskConstraints(Microsoft.Azure.Batch.TaskConstraints omObject)
{
if ((omObject == null))
{
throw new System.ArgumentNullException("omObject");
}
this.omObject = omObject;
}
public System.TimeSpan? MaxWallClockTime
{
get
{
return this.omObject.MaxWallClockTime;
}
}
public System.TimeSpan? RetentionTime
{
get
{
return this.omObject.RetentionTime;
}
}
public System.Int32? MaxTaskRetryCount
{
get
{
return this.omObject.MaxTaskRetryCount;
}
}
}
}
| 35.026316 | 172 | 0.52592 | [
"MIT"
] | KinaMarie/azure-powershell | src/ResourceManager/AzureBatch/Commands.Batch/Models.Generated/PSTaskConstraints.cs | 2,613 | C# |
using Abp.Domain.Entities;
using Abp.Domain.Repositories;
using Abp.EntityFrameworkCore;
using Abp.EntityFrameworkCore.Repositories;
namespace MySuperStats.EntityFrameworkCore.Repositories
{
/// <summary>
/// Base class for custom repositories of the application.
/// </summary>
/// <typeparam name="TEntity">Entity type</typeparam>
/// <typeparam name="TPrimaryKey">Primary key type of the entity</typeparam>
public abstract class MySuperStatsRepositoryBase<TEntity, TPrimaryKey> : EfCoreRepositoryBase<MySuperStatsDbContext, TEntity, TPrimaryKey>
where TEntity : class, IEntity<TPrimaryKey>
{
protected MySuperStatsRepositoryBase(IDbContextProvider<MySuperStatsDbContext> dbContextProvider)
: base(dbContextProvider)
{
}
// Add your common methods for all repositories
}
/// <summary>
/// Base class for custom repositories of the application.
/// This is a shortcut of <see cref="MySuperStatsRepositoryBase{TEntity,TPrimaryKey}"/> for <see cref="int"/> primary key.
/// </summary>
/// <typeparam name="TEntity">Entity type</typeparam>
public abstract class MySuperStatsRepositoryBase<TEntity> : MySuperStatsRepositoryBase<TEntity, int>, IRepository<TEntity>
where TEntity : class, IEntity<int>
{
protected MySuperStatsRepositoryBase(IDbContextProvider<MySuperStatsDbContext> dbContextProvider)
: base(dbContextProvider)
{
}
// Do not add any method here, add to the class above (since this inherits it)!!!
}
}
| 39.65 | 142 | 0.708071 | [
"MIT"
] | ykirkanahtar/MySuperStats | aspnet-core/src/MySuperStats.EntityFrameworkCore/EntityFrameworkCore/Repositories/MySuperStatsRepositoryBase.cs | 1,588 | C# |
namespace Microsoft.ApplicationInsights.Metrics.Extensibility
{
using System;
using System.Collections.Generic;
/// <summary>@ToDo: Complete documentation before stable release. {390}</summary>
/// @PublicExposureCandidate
internal class AggregationPeriodSummary
{
/// <summary>@ToDo: Complete documentation before stable release. {487}</summary>
/// <param name="persistentAggregates">@ToDo: Complete documentation before stable release. {672}</param>
/// <param name="nonpersistentAggregates">@ToDo: Complete documentation before stable release. {290}</param>
public AggregationPeriodSummary(IReadOnlyList<MetricAggregate> persistentAggregates, IReadOnlyList<MetricAggregate> nonpersistentAggregates)
{
this.PersistentAggregates = persistentAggregates;
this.NonpersistentAggregates = nonpersistentAggregates;
}
/// <summary>Gets @ToDo: Complete documentation before stable release. {315}</summary>
public IReadOnlyList<MetricAggregate> PersistentAggregates { get; }
/// <summary>Gets @ToDo: Complete documentation before stable release. {776}</summary>
public IReadOnlyList<MetricAggregate> NonpersistentAggregates { get; }
}
}
| 48.692308 | 148 | 0.721959 | [
"MIT"
] | armanik11/ApplicationInsights-dotnet | src/Microsoft.ApplicationInsights/Metrics/Extensibility/AggregationPeriodSummary.cs | 1,268 | C# |
// Copyright (C) 2012 Winterleaf Entertainment L,L,C.
//
// THE SOFTW ARE IS PROVIDED ON AN “ AS IS” BASIS, WITHOUT W ARRANTY OF ANY KIND,
// INCLUDING WITHOUT LIMIT ATION THE W ARRANTIES OF MERCHANT ABILITY, FITNESS
// FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT . THE ENTIRE RISK AS TO THE
// QUALITY AND PERFORMANCE OF THE SOFTW ARE IS THE RESPONSIBILITY OF LICENSEE.
// SHOULD THE SOFTW ARE PROVE DEFECTIVE IN ANY RESPECT , LICENSEE AND NOT LICEN -
// SOR OR ITS SUPPLIERS OR RESELLERS ASSUMES THE ENTIRE COST OF AN Y SERVICE AND
// REPAIR. THIS DISCLAIMER OF W ARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS
// AGREEMENT. NO USE OF THE SOFTW ARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
// THIS DISCLAIMER.
//
// The use of the WinterLeaf Entertainment LLC DotNetT orque (“DNT ”) and DotNetT orque
// Customizer (“DNTC”)is governed by this license agreement (“ Agreement”).
//
// R E S T R I C T I O N S
//
// (a) Licensee may not: (i) create any derivative works of DNTC, including but not
// limited to translations, localizations, technology add-ons, or game making software
// other than Games; (ii) reverse engineer , or otherwise attempt to derive the algorithms
// for DNT or DNTC (iii) redistribute, encumber , sell, rent, lease, sublicense, or otherwise
// transfer rights to DNTC; or (iv) remove or alter any tra demark, logo, copyright
// or other proprietary notices, legends, symbols or labels in DNT or DNTC; or (iiv) use
// the Software to develop or distribute any software that compete s with the Software
// without WinterLeaf Entertainment’s prior written consent; or (i iiv) use the Software for
// any illegal purpose.
// (b) Licensee may not distribute the DNTC in any manner.
//
// LI C E N S E G R A N T .
// This license allows companies of any size, government entities or individuals to cre -
// ate, sell, rent, lease, or otherwise profit commercially from, games using executables
// created from the source code of DNT
//
// **********************************************************************************
// **********************************************************************************
// **********************************************************************************
// THE SOURCE CODE GENERATED BY DNTC CAN BE DISTRIBUTED PUBLICLY PROVIDED THAT THE
// DISTRIBUTOR PROVIDES THE GENERATE SOURCE CODE FREE OF CHARGE.
//
// THIS SOURCE CODE (DNT) CAN BE DISTRIBUTED PUBLICLY PROVIDED THAT THE DISTRIBUTOR
// PROVIDES THE SOURCE CODE (DNT) FREE OF CHARGE.
// **********************************************************************************
// **********************************************************************************
// **********************************************************************************
//
// Please visit http://www.winterleafentertainment.com for more information about the project and latest updates.
//
//
//
#region
using WinterLeaf;
using WinterLeaf.Classes;
using WinterLeaf.tsObjects;
#endregion
namespace DNT_FPS_Demo_Game_Dll.Scripts.Client
{
public partial class Main : TorqueScriptTemplate
{
[Torque_Decorations.TorqueCallBack("", "", "initbaselighting", "", 0, 65000, true)]
public void initbaselighting()
{
/*
* client/lighting/advanced/shaders.cs 60000
* client/lighting/advanced/lightViz.cs 61000
* client/lighting/advanced/shadowViz.cs 62000
* client/lighting/advanced/shadowViz.gui 63000
* client/lighting/advanced/init.cs 64000
* client/lighting/basic/init.cs 65000
* client/lighting/basic/shadowFilter 66000
* client/lighting/shadowMaps/init 67000
*/
dnt.DoScriptInjection(ScriptType.Client, 66000, 66999);
#region singleton GFXStateBlockData( BL_ProjectedShadowSBData )
TorqueSingleton ts = new TorqueSingleton("GFXStateBlockData", "BL_ProjectedShadowSBData");
ts.Props.Add("blendDefined", "true");
ts.Props.Add("blendEnable", "true");
ts.Props.Add("blendSrc", "GFXBlendDestColor");
ts.Props.Add("blendDest", "GFXBlendZero");
ts.Props.Add("zDefined", "true");
ts.Props.Add("zEnable", "true");
ts.Props.Add("zWriteEnable", "false");
ts.Props.Add("samplersDefined", "true");
ts.Props.Add("samplerStates[0]", "SamplerClampLinear");
ts.Props.Add("vertexColorEnable", "true");
ts.Create();
#endregion
#region singleton ShaderData( BL_ProjectedShadowShaderData )
ts = new TorqueSingleton("ShaderData", "BL_ProjectedShadowShaderData");
ts.PropsAddString("DXVertexShaderFile", "shaders/common/projectedShadowV.hlsl");
ts.PropsAddString("DXPixelShaderFile", "shaders/common/projectedShadowP.hlsl");
ts.PropsAddString("OGLVertexShaderFile", "shaders/common/gl/projectedShadowV.glsl");
ts.PropsAddString("OGLPixelShaderFile", "shaders/common/gl/projectedShadowP.glsl");
ts.Props.Add("pixVersion", "2.0");
ts.Create();
#endregion
#region singleton CustomMaterial( BL_ProjectedShadowMaterial )
ts = new TorqueSingleton("CustomMaterial", "BL_ProjectedShadowMaterial");
ts.PropsAddString(@"sampler[""inputTex""]", "$miscbuff");
ts.Props.Add("shader", "BL_ProjectedShadowShaderData");
ts.Props.Add("stateBlock", "BL_ProjectedShadowSBData");
ts.Props.Add("version", "2.0");
ts.Props.Add("forwardLit", "true");
ts.Create();
#endregion
}
[Torque_Decorations.TorqueCallBack("", "", "onActivateBasicLM", "", 0, 65100, false)]
public void onActivateBasicLM()
{
// If HDR is enabled... enable the special format token.
if ((sGlobal["$platform"] == "macos") || ((coPostEffect)"HDRPostFx").isEnabledX())
((coGFXStateBlockData)"AL_FormatToken").call("enable");
// Create render pass for projected shadow.
coRenderPassManager BL_ProjectedShadowRPM = new Torque_Class_Helper("RenderPassManager", "BL_ProjectedShadowRPM").Create();
// Create the mesh bin and add it to the manager.
coRenderMeshMgr meshbin = new Torque_Class_Helper("RenderMeshMgr").Create();
BL_ProjectedShadowRPM.addManager(meshbin);
// Add both to the root group so that it doesn't
// end up in the MissionCleanup instant group.
coSimSet rootGroup = "RootGroup";
rootGroup.pushToBack(BL_ProjectedShadowRPM);
rootGroup.pushToBack(meshbin);
}
[Torque_Decorations.TorqueCallBack("", "", "onDeactivateBasicLM", "", 0, 65200, false)]
public void onDeactivateBasicLM()
{
// Delete the pass manager which also deletes the bin.
"BL_ProjectedShadowRPM".delete();
}
[Torque_Decorations.TorqueCallBack("", "", "setBasicLighting", "", 0, 65300, false)]
public void setBasicLighting()
{
Util.setLightManager("Basic Lighting");
}
}
} | 46.782609 | 136 | 0.590813 | [
"Unlicense"
] | Winterleaf/DNT-Torque3D-V1.1-MIT-3.0 | Templates/Full/DNT FPS Demo Dll No Core/Scripts/Client/Enviroment/Lighting/Basic/init.cs | 7,392 | 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 machinelearning-2014-12-12.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.MachineLearning.Model
{
/// <summary>
/// Container for the parameters to the CreateDataSourceFromRDS operation.
/// Creates a <code>DataSource</code> object from an <a href="http://aws.amazon.com/rds/">
/// Amazon Relational Database Service</a> (Amazon RDS). A <code>DataSource</code> references
/// data that can be used to perform <code>CreateMLModel</code>, <code>CreateEvaluation</code>,
/// or <code>CreateBatchPrediction</code> operations.
///
///
/// <para>
/// <code>CreateDataSourceFromRDS</code> is an asynchronous operation. In response to
/// <code>CreateDataSourceFromRDS</code>, Amazon Machine Learning (Amazon ML) immediately
/// returns and sets the <code>DataSource</code> status to <code>PENDING</code>. After
/// the <code>DataSource</code> is created and ready for use, Amazon ML sets the <code>Status</code>
/// parameter to <code>COMPLETED</code>. <code>DataSource</code> in the <code>COMPLETED</code>
/// or <code>PENDING</code> state can be used only to perform <code>>CreateMLModel</code>>,
/// <code>CreateEvaluation</code>, or <code>CreateBatchPrediction</code> operations.
/// </para>
///
/// <para>
/// If Amazon ML cannot accept the input source, it sets the <code>Status</code> parameter
/// to <code>FAILED</code> and includes an error message in the <code>Message</code> attribute
/// of the <code>GetDataSource</code> operation response.
/// </para>
/// </summary>
public partial class CreateDataSourceFromRDSRequest : AmazonMachineLearningRequest
{
private bool? _computeStatistics;
private string _dataSourceId;
private string _dataSourceName;
private RDSDataSpec _rdsData;
private string _roleARN;
/// <summary>
/// Gets and sets the property ComputeStatistics.
/// <para>
/// The compute statistics for a <code>DataSource</code>. The statistics are generated
/// from the observation data referenced by a <code>DataSource</code>. Amazon ML uses
/// the statistics internally during <code>MLModel</code> training. This parameter must
/// be set to <code>true</code> if the <code></code>DataSource<code></code> needs to be
/// used for <code>MLModel</code> training.
/// </para>
/// </summary>
public bool ComputeStatistics
{
get { return this._computeStatistics.GetValueOrDefault(); }
set { this._computeStatistics = value; }
}
// Check to see if ComputeStatistics property is set
internal bool IsSetComputeStatistics()
{
return this._computeStatistics.HasValue;
}
/// <summary>
/// Gets and sets the property DataSourceId.
/// <para>
/// A user-supplied ID that uniquely identifies the <code>DataSource</code>. Typically,
/// an Amazon Resource Number (ARN) becomes the ID for a <code>DataSource</code>.
/// </para>
/// </summary>
public string DataSourceId
{
get { return this._dataSourceId; }
set { this._dataSourceId = value; }
}
// Check to see if DataSourceId property is set
internal bool IsSetDataSourceId()
{
return this._dataSourceId != null;
}
/// <summary>
/// Gets and sets the property DataSourceName.
/// <para>
/// A user-supplied name or description of the <code>DataSource</code>.
/// </para>
/// </summary>
public string DataSourceName
{
get { return this._dataSourceName; }
set { this._dataSourceName = value; }
}
// Check to see if DataSourceName property is set
internal bool IsSetDataSourceName()
{
return this._dataSourceName != null;
}
/// <summary>
/// Gets and sets the property RDSData.
/// <para>
/// The data specification of an Amazon RDS <code>DataSource</code>:
/// </para>
/// <ul> <li>
/// <para>
/// DatabaseInformation - <ul> <li> <code>DatabaseName</code> - The name of the Amazon
/// RDS database.</li> <li> <code>InstanceIdentifier </code> - A unique identifier for
/// the Amazon RDS database instance.</li> </ul>
/// </para>
/// </li> <li>
/// <para>
/// DatabaseCredentials - AWS Identity and Access Management (IAM) credentials that are
/// used to connect to the Amazon RDS database.
/// </para>
/// </li> <li>
/// <para>
/// ResourceRole - A role (DataPipelineDefaultResourceRole) assumed by an EC2 instance
/// to carry out the copy task from Amazon RDS to Amazon Simple Storage Service (Amazon
/// S3). For more information, see <a href="http://docs.aws.amazon.com/datapipeline/latest/DeveloperGuide/dp-iam-roles.html">Role
/// templates</a> for data pipelines.
/// </para>
/// </li> <li>
/// <para>
/// ServiceRole - A role (DataPipelineDefaultRole) assumed by the AWS Data Pipeline service
/// to monitor the progress of the copy task from Amazon RDS to Amazon S3. For more information,
/// see <a href="http://docs.aws.amazon.com/datapipeline/latest/DeveloperGuide/dp-iam-roles.html">Role
/// templates</a> for data pipelines.
/// </para>
/// </li> <li>
/// <para>
/// SecurityInfo - The security information to use to access an RDS DB instance. You need
/// to set up appropriate ingress rules for the security entity IDs provided to allow
/// access to the Amazon RDS instance. Specify a [<code>SubnetId</code>, <code>SecurityGroupIds</code>]
/// pair for a VPC-based RDS DB instance.
/// </para>
/// </li> <li>
/// <para>
/// SelectSqlQuery - A query that is used to retrieve the observation data for the <code>Datasource</code>.
/// </para>
/// </li> <li>
/// <para>
/// S3StagingLocation - The Amazon S3 location for staging Amazon RDS data. The data retrieved
/// from Amazon RDS using <code>SelectSqlQuery</code> is stored in this location.
/// </para>
/// </li> <li>
/// <para>
/// DataSchemaUri - The Amazon S3 location of the <code>DataSchema</code>.
/// </para>
/// </li> <li>
/// <para>
/// DataSchema - A JSON string representing the schema. This is not required if <code>DataSchemaUri</code>
/// is specified.
/// </para>
/// </li> <li>
/// <para>
/// DataRearrangement - A JSON string that represents the splitting and rearrangement
/// requirements for the <code>Datasource</code>.
/// </para>
///
/// <para>
/// Sample - <code> "{\"splitting\":{\"percentBegin\":10,\"percentEnd\":60}}"</code>
///
/// </para>
/// </li> </ul>
/// </summary>
public RDSDataSpec RDSData
{
get { return this._rdsData; }
set { this._rdsData = value; }
}
// Check to see if RDSData property is set
internal bool IsSetRDSData()
{
return this._rdsData != null;
}
/// <summary>
/// Gets and sets the property RoleARN.
/// <para>
/// The role that Amazon ML assumes on behalf of the user to create and activate a data
/// pipeline in the user's account and copy data using the <code>SelectSqlQuery</code>
/// query from Amazon RDS to Amazon S3.
/// </para>
///
/// <para>
///
/// </para>
/// </summary>
public string RoleARN
{
get { return this._roleARN; }
set { this._roleARN = value; }
}
// Check to see if RoleARN property is set
internal bool IsSetRoleARN()
{
return this._roleARN != null;
}
}
} | 40.213333 | 137 | 0.593833 | [
"Apache-2.0"
] | Bio2hazard/aws-sdk-net | sdk/src/Services/MachineLearning/Generated/Model/CreateDataSourceFromRDSRequest.cs | 9,048 | C# |
//-----------------------------------------------------------------------------
// FILE: NodeDefinition.cs
// CONTRIBUTOR: Jeff Lill
// COPYRIGHT: Copyright (c) 2005-2022 by neonFORGE LLC. 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.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics.Contracts;
using System.IO;
using System.Net;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Serialization;
using YamlDotNet.Serialization;
using Neon.Common;
using Neon.Net;
namespace Neon.Kube
{
/// <summary>
/// Describes a cluster node.
/// </summary>
public class NodeDefinition
{
//---------------------------------------------------------------------
// Static methods
/// <summary>
/// Parses a <see cref="NodeDefinition"/> from Kubernetes node labels.
/// </summary>
/// <param name="labels">The node labels.</param>
/// <returns>The parsed <see cref="NodeDefinition"/>.</returns>
public static NodeDefinition ParseFromLabels(Dictionary<string, string> labels)
{
var node = new NodeDefinition();
return node;
}
//---------------------------------------------------------------------
// Instance methods
private string name;
/// <summary>
/// Constructor.
/// </summary>
public NodeDefinition()
{
Labels = new NodeLabels(this);
}
/// <summary>
/// Uniquely identifies the node within the cluster.
/// </summary>
/// <remarks>
/// <note>
/// The name may include only letters, numbers, periods, dashes, and underscores and
/// also that all names will be converted to lowercase.
/// </note>
/// </remarks>
[JsonProperty(PropertyName = "Name", Required = Required.Default, DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate)]
[YamlMember(Alias = "name", ApplyNamingConventions = false)]
[DefaultValue(null)]
public string Name
{
get { return name; }
set
{
if (value != null)
{
name = value.ToLowerInvariant();
}
else
{
name = null;
}
}
}
/// <summary>
/// The node's IP address or <c>null</c> if one has not been assigned yet.
/// Note that an node's IP address cannot be changed once the node has
/// been added to the cluster.
/// </summary>
[JsonProperty(PropertyName = "Address", Required = Required.Default)]
[YamlMember(Alias = "address", ApplyNamingConventions = false)]
[DefaultValue(null)]
public string Address { get; set; } = null;
/// <summary>
/// Indicates that the node will act as a master node (defaults to <c>false</c>).
/// </summary>
/// <remarks>
/// <para>
/// Master nodes are reponsible for managing service discovery and coordinating
/// pod deployment across the cluster.
/// </para>
/// <para>
/// An odd number of master nodes must be deployed in a cluster (to help prevent
/// split-brain). One master node may be deployed for non-production environments,
/// but to enable high-availability, three or five master nodes may be deployed.
/// </para>
/// </remarks>
[JsonIgnore]
[YamlIgnore]
public bool IsMaster
{
get { return Role.Equals(NodeRole.Master, StringComparison.InvariantCultureIgnoreCase); }
}
/// <summary>
/// Returns <c>true</c> for worker nodes.
/// </summary>
[JsonIgnore]
[YamlIgnore]
public bool IsWorker
{
get { return Role.Equals(NodeRole.Worker, StringComparison.InvariantCultureIgnoreCase); }
}
/// <summary>
/// Returns the node's <see cref="NodeRole"/>. This defaults to <see cref="NodeRole.Worker"/>.
/// </summary>
[JsonProperty(PropertyName = "Role", Required = Required.Default, DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate)]
[YamlMember(Alias = "role", ApplyNamingConventions = false)]
[DefaultValue(NodeRole.Worker)]
public string Role { get; set; } = NodeRole.Worker;
/// <summary>
/// <para>
/// Indicates whether this node should be configured to accept external network traffic
/// on node ports and route that into the cluster. This defaults to <c>false</c>.
/// </para>
/// <note>
/// If all nodes have <see cref="Ingress"/> set to <c>false</c> and the cluster defines
/// one or more <see cref="NetworkOptions.IngressRules"/> then neonKUBE will choose a
/// reasonable set of nodes to accept inbound traffic.
/// </note>
/// </summary>
[JsonProperty(PropertyName = "Ingress", Required = Required.Default, DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate)]
[YamlMember(Alias = "ingress", ApplyNamingConventions = false)]
[DefaultValue(false)]
public bool Ingress { get; set; } = false;
/// <summary>
/// <para>
/// Indicates that this node will provide a cStor block device for the cStorPool
/// maintained by the cluster OpenEBS service that provides cloud optimized storage.
/// This defaults to <c>false</c>
/// </para>
/// <note>
/// If all nodes have <see cref="OpenEbsStorage"/> set to <c>false</c> then most neonKUBE
/// hosting managers will automatically choose the nodes that will host the cStor
/// block devices by configuring up to three nodes to do this, favoring worker nodes
/// over masters when possible.
/// </note>
/// <note>
/// The <see cref="HostingEnvironment.BareMetal"/> hosting manager works a bit differently
/// from the others. It requires that at least one node have <see cref="OpenEbsStorage"/><c>=true</c>
/// and that node must have an empty unpartitioned block device available to be provisoned
/// as an cStor.
/// </note>
/// </summary>
[JsonProperty(PropertyName = "OpenEbsStorage", Required = Required.Default, DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate)]
[YamlMember(Alias = "openEbsStorage", ApplyNamingConventions = false)]
[DefaultValue(false)]
public bool OpenEbsStorage { get; set; } = false;
/// <summary>
/// Specifies the labels to be assigned to the cluster node. These can describe
/// details such as the host CPU, RAM, storage, etc. <see cref="NodeLabels"/>
/// for more information.
/// </summary>
[JsonProperty(PropertyName = "Labels")]
[YamlMember(Alias = "labels", ApplyNamingConventions = false)]
[DefaultValue(null)]
public NodeLabels Labels { get; set; }
/// <summary>
/// Specifies the taints to be assigned to the cluster node.
/// </summary>
[JsonProperty(PropertyName = "Taints")]
[YamlMember(Alias = "taints", ApplyNamingConventions = false)]
[DefaultValue(null)]
public List<string> Taints { get; set; }
/// <summary>
/// Hypervisor hosting related options for environments like Hyper-V and XenServer.
/// </summary>
[JsonProperty(PropertyName = "Vm")]
[YamlMember(Alias = "vm", ApplyNamingConventions = false)]
[DefaultValue(null)]
public VmNodeOptions Vm { get; set; }
/// <summary>
/// Azure provisioning options for this node, or <c>null</c> to use reasonable defaults.
/// </summary>
[JsonProperty(PropertyName = "Azure")]
[YamlMember(Alias = "azure", ApplyNamingConventions = false)]
[DefaultValue(null)]
public AzureNodeOptions Azure { get; set; }
/// <summary>
/// AWS provisioning options for this node, or <c>null</c> to use reasonable defaults.
/// </summary>
[JsonProperty(PropertyName = "Aws")]
[YamlMember(Alias = "aws", ApplyNamingConventions = false)]
[DefaultValue(null)]
public AwsNodeOptions Aws { get; set; }
/// <summary>
/// Returns the size of the operating system boot disk as a string with optional
/// <see cref="ByteUnits"/> unit suffix.
/// </summary>
/// <param name="clusterDefinition">The cluster definition.</param>
/// <returns>The disk size.</returns>
public string GetOsDiskSize(ClusterDefinition clusterDefinition)
{
Covenant.Requires<ArgumentNullException>(clusterDefinition != null, nameof(clusterDefinition));
switch (clusterDefinition.Hosting.Environment)
{
case HostingEnvironment.Aws:
return Aws.VolumeSize ?? clusterDefinition.Hosting.Aws.DefaultVolumeSize;
case HostingEnvironment.Azure:
return Azure.DiskSize ?? clusterDefinition.Hosting.Azure.DefaultDiskSize;
case HostingEnvironment.BareMetal:
throw new NotImplementedException();
case HostingEnvironment.Google:
throw new NotImplementedException();
case HostingEnvironment.HyperV:
case HostingEnvironment.XenServer:
return Vm.GetOsDisk(clusterDefinition).ToString();
default:
throw new NotImplementedException();
}
}
/// <summary>
/// Returns the size of the data disk as a string with optional <see cref="ByteUnits"/> unit suffix.
/// </summary>
/// <param name="clusterDefinition">The cluster definition.</param>
/// <returns>The disk size or <c>null</c> when the node has no data disk.</returns>
public string GetDataDiskSize(ClusterDefinition clusterDefinition)
{
Covenant.Requires<ArgumentNullException>(clusterDefinition != null, nameof(clusterDefinition));
switch (clusterDefinition.Hosting.Environment)
{
case HostingEnvironment.Aws:
return Aws.OpenEBSVolumeSize ?? clusterDefinition.Hosting.Aws.DefaultOpenEBSVolumeSize;
case HostingEnvironment.Azure:
return Azure.OpenEBSDiskSize ?? clusterDefinition.Hosting.Azure.DefaultOpenEBSDiskSize;
case HostingEnvironment.BareMetal:
throw new NotImplementedException();
case HostingEnvironment.Google:
throw new NotImplementedException();
case HostingEnvironment.HyperV:
case HostingEnvironment.XenServer:
return Vm.GetOsDisk(clusterDefinition).ToString();
default:
throw new NotImplementedException();
}
}
/// <summary>
/// Validates the node definition.
/// </summary>
/// <param name="clusterDefinition">The cluster definition.</param>
/// <exception cref="ArgumentException">Thrown if the definition is not valid.</exception>
public void Validate(ClusterDefinition clusterDefinition)
{
Covenant.Requires<ArgumentNullException>(clusterDefinition != null, nameof(clusterDefinition));
var nodeDefinitionPrefix = $"{nameof(ClusterDefinition.NodeDefinitions)}";
// Ensure that the labels are wired up to the parent node.
if (Labels == null)
{
Labels = new NodeLabels(this);
}
else
{
Labels.Node = this;
}
if (Name == null)
{
throw new ClusterDefinitionException($"The [{nodeDefinitionPrefix}.{nameof(Name)}] property is required.");
}
if (!ClusterDefinition.IsValidName(Name))
{
throw new ClusterDefinitionException($"The [{nodeDefinitionPrefix}.{nameof(Name)}={Name}] property is not valid. Only letters, numbers, periods, dashes, and underscores are allowed.");
}
if (name == "localhost")
{
throw new ClusterDefinitionException($"The [{nodeDefinitionPrefix}.{nameof(Name)}={Name}] property is not valid. [localhost] is reserved.");
}
if (Name.StartsWith("neon-", StringComparison.InvariantCultureIgnoreCase) && !clusterDefinition.IsSpecialNeonCluster)
{
throw new ClusterDefinitionException($"The [{nodeDefinitionPrefix}.{nameof(Name)}={Name}] property is not valid because node names starting with [neon-] are reserved.");
}
if (name.Equals("cluster", StringComparison.InvariantCultureIgnoreCase))
{
// $hack(jefflill):
//
// The node name [cluster] is reserved because we want to persist the
// global cluster log file as [cluster.log] and we don't want this to
// conflict with any of the node log files.
//
// See: KubeConst.ClusterSetupLogName
throw new ClusterDefinitionException($"The [{nodeDefinitionPrefix}.{nameof(Name)}={Name}] property is not valid because the node name [cluster] is reserved.");
}
if (string.IsNullOrEmpty(Role))
{
Role = NodeRole.Worker;
}
if (!Role.Equals(NodeRole.Master, StringComparison.InvariantCultureIgnoreCase) && !Role.Equals(NodeRole.Worker, StringComparison.InvariantCultureIgnoreCase))
{
throw new ClusterDefinitionException($"[{nodeDefinitionPrefix}.{nameof(Name)}={Name}] has invalid [{nameof(Role)}={Role}]. This must be [{NodeRole.Master}] or [{NodeRole.Worker}].");
}
// We don't need to check the node address for cloud providers.
if (clusterDefinition.Hosting.IsOnPremiseProvider)
{
if (string.IsNullOrEmpty(Address))
{
throw new ClusterDefinitionException($"[{nodeDefinitionPrefix}.{nameof(Name)}={Name}] requires [{nameof(Address)}] when hosting in an on-premise facility.");
}
if (!NetHelper.TryParseIPv4Address(Address, out var nodeAddress))
{
throw new ClusterDefinitionException($"[{nodeDefinitionPrefix}.{nameof(Name)}={Name}] has invalid IP address [{Address}].");
}
}
switch (clusterDefinition.Hosting.Environment)
{
case HostingEnvironment.Aws:
Aws = Aws ?? new AwsNodeOptions();
Aws.Validate(clusterDefinition, this.Name);
break;
case HostingEnvironment.Azure:
Azure = Azure ?? new AzureNodeOptions();
Azure.Validate(clusterDefinition, this.Name);
break;
case HostingEnvironment.BareMetal:
// No machine options to check at this time.
break;
case HostingEnvironment.Google:
// $todo(jefflill: Implement this
break;
case HostingEnvironment.HyperV:
case HostingEnvironment.XenServer:
Vm = Vm ?? new VmNodeOptions();
Vm.Validate(clusterDefinition, this.Name);
break;
default:
throw new NotImplementedException($"Hosting environment [{clusterDefinition.Hosting.Environment}] hosting option check is not implemented.");
}
}
}
}
| 39.317757 | 201 | 0.58266 | [
"Apache-2.0"
] | jefflill/neonKUBE | Lib/Neon.Kube/Model/ClusterDefinition/Node/NodeDefinition.cs | 16,830 | 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 SolidCP.Portal {
public partial class SettingsPackageSummaryLetter {
/// <summary>
/// chkEnableLetter control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.CheckBox chkEnableLetter;
/// <summary>
/// lblFrom control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Label lblFrom;
/// <summary>
/// txtFrom control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox txtFrom;
/// <summary>
/// lblCC control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Label lblCC;
/// <summary>
/// txtCC control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox txtCC;
/// <summary>
/// lblSubject control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Label lblSubject;
/// <summary>
/// txtSubject control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox txtSubject;
/// <summary>
/// lblPriority control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Label lblPriority;
/// <summary>
/// ddlPriority control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.DropDownList ddlPriority;
/// <summary>
/// lblHtmlBody control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Label lblHtmlBody;
/// <summary>
/// txtHtmlBody control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox txtHtmlBody;
/// <summary>
/// lblTextBody control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Label lblTextBody;
/// <summary>
/// txtTextBody control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox txtTextBody;
}
}
| 34.81203 | 84 | 0.536285 | [
"BSD-3-Clause"
] | Alirexaa/SolidCP | SolidCP/Sources/SolidCP.WebPortal/DesktopModules/SolidCP/SettingsPackageSummaryLetter.ascx.designer.cs | 4,630 | C# |
namespace Xamarin.Forms.Controls.GalleryPages.VisualStateManagerGalleries
{
public partial class DeviceStateTriggerGallery : ContentPage
{
public DeviceStateTriggerGallery()
{
InitializeComponent();
}
}
} | 21.7 | 74 | 0.792627 | [
"MIT"
] | Alan-love/Xamarin.Forms | Xamarin.Forms.Controls/GalleryPages/VisualStateManagerGalleries/DeviceStateTriggerGallery.xaml.cs | 219 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
namespace Alza.Web
{
/// <summary>
/// Program class.
/// </summary>
public class Program
{
/// <summary>
/// Main method.
/// </summary>
/// <param name="args">An array of input arguments.</param>
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
/// <summary>
/// Creates the Host builder.
/// </summary>
/// <param name="args">An array of input arguments.</param>
/// <returns></returns>
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
}
}
| 27.461538 | 70 | 0.582633 | [
"MIT"
] | petrnejedly/AlzaCz | Alza/Presentation/Alza.Web/Program.cs | 1,071 | C# |
using System;
using NHibernate;
namespace MaterialCMS.DbConfiguration
{
public class PublishedFilterDisabler : IDisposable
{
private readonly ISession _session;
private readonly bool _filterEnabled;
public PublishedFilterDisabler(ISession session)
{
_session = session;
_filterEnabled = _session.GetEnabledFilter("PublishedFilter") != null;
if (_filterEnabled)
{
_session.DisableFilter("PublishedFilter");
}
}
public void Dispose()
{
if (_filterEnabled)
{
_session.EnableFilter("PublishedFilter");
}
}
}
} | 23.8 | 82 | 0.568627 | [
"MIT"
] | DucThanhNguyen/MaterialCMS | MaterialCMS/DbConfiguration/PublishedFilterDisabler.cs | 716 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Azure.Core.TestFramework;
using NUnit.Framework;
namespace Azure.AI.TextAnalytics.Tests
{
public class RecognizeHealthcareEntitiesTests : TextAnalyticsClientLiveTestBase
{
public RecognizeHealthcareEntitiesTests(bool isAsync) : base(isAsync) { }
private static List<string> s_batchConvenienceDocuments = new List<string>
{
"Subject is taking 100mg of ibuprofen twice daily",
"Can cause rapid or irregular heartbeat, delirium, panic, psychosis, and heart failure."
};
private static List<TextDocumentInput> s_batchDocuments = new List<TextDocumentInput>
{
new TextDocumentInput("1", "Subject is taking 100mg of ibuprofen twice daily")
{
Language = "en",
},
new TextDocumentInput("2", "Can cause rapid or irregular heartbeat, delirium, panic, psychosis, and heart failure.")
{
Language = "en",
}
};
private static readonly List<string> s_document1ExpectedEntitiesOutput = new List<string>
{
"ibuprofen",
"100mg",
"twice daily"
};
private static readonly List<string> s_document2ExpectedEntitiesOutput = new List<string>
{
"rapid",
"irregular heartbeat",
"delirium",
"panic",
"psychosis",
"heart failure"
};
[Test]
public async Task RecognizeHealthcareEntitiesTest()
{
TextAnalyticsClient client = GetClient();
AnalyzeHealthcareEntitiesOperation operation = await client.StartAnalyzeHealthcareEntitiesAsync(s_batchDocuments);
await operation.WaitForCompletionAsync(PollingInterval);
ValidateOperationProperties(operation);
List<AnalyzeHealthcareEntitiesResultCollection> resultInPages = operation.Value.ToEnumerableAsync().Result;
Assert.AreEqual(1, resultInPages.Count);
//Take the first page
var resultCollection = resultInPages.FirstOrDefault();
Assert.AreEqual(s_batchDocuments.Count, resultCollection.Count);
AnalyzeHealthcareEntitiesResult result1 = resultCollection[0];
Assert.AreEqual(s_document1ExpectedEntitiesOutput.Count, result1.Entities.Count);
Assert.IsNotNull(result1.Id);
Assert.AreEqual("1", result1.Id);
foreach (HealthcareEntity entity in result1.Entities)
{
Assert.IsTrue(s_document1ExpectedEntitiesOutput.Contains(entity.Text));
if (entity.Text == "ibuprofen")
{
var linksList = new List<string> { "UMLS", "AOD", "ATC", "CCPSS", "CHV", "CSP", "DRUGBANK", "GS", "LCH_NW", "LNC", "MEDCIN", "MMSL", "MSH", "MTHSPL", "NCI", "NCI_CTRP", "NCI_DCP", "NCI_DTP", "NCI_FDA", "NCI_NCI-GLOSS", "NDDF", "PDQ", "RCD", "RXNORM", "SNM", "SNMI", "SNOMEDCT_US", "USP", "USPMG", "VANDF" };
foreach (EntityDataSource entityDataSource in entity.DataSources)
Assert.IsTrue(linksList.Contains(entityDataSource.Name));
}
if (entity.Text == "100mg")
{
Assert.AreEqual(18, entity.Offset);
Assert.AreEqual("Dosage", entity.Category);
Assert.AreEqual(5, entity.Length);
}
}
Assert.AreEqual(2, result1.EntityRelations.Count());
foreach (HealthcareEntityRelation relation in result1.EntityRelations)
{
if (relation.RelationType == "DosageOfMedication")
{
var role = relation.Roles.ElementAt(0);
Assert.IsNotNull(relation.Roles);
Assert.AreEqual(2, relation.Roles.Count());
Assert.AreEqual("Attribute", role.Name);
Assert.AreEqual("100mg", role.Entity.Text);
Assert.AreEqual(18, role.Entity.Offset);
Assert.AreEqual("Dosage", role.Entity.Category);
Assert.AreEqual(5, role.Entity.Length);
}
}
}
[Ignore("Waiting for service to deploy to WestU2. Issue https://github.com/Azure/azure-sdk-for-net/issues/19152")]
[Test]
public async Task RecognizeHealthcareEntitiesTestWithAssertions()
{
TextAnalyticsClient client = GetClient();
IReadOnlyCollection<string> batchDocuments = new List<string>() { "Baby not likely to have Meningitis. in case of fever in the mother, consider Penicillin for the baby too." };
IReadOnlyCollection<string> expectedEntitiesOutput = new List<string>
{
"Baby",
"Meningitis",
"fever",
"mother",
"Penicillin",
"baby"
};
AnalyzeHealthcareEntitiesOperation operation = await client.StartAnalyzeHealthcareEntitiesAsync(batchDocuments);
await operation.WaitForCompletionAsync(PollingInterval);
ValidateOperationProperties(operation);
List<AnalyzeHealthcareEntitiesResultCollection> resultInPages = operation.Value.ToEnumerableAsync().Result;
Assert.AreEqual(1, resultInPages.Count);
var resultCollection = resultInPages.FirstOrDefault();
Assert.AreEqual(batchDocuments.Count, resultCollection.Count);
AnalyzeHealthcareEntitiesResult result1 = resultCollection[0];
Assert.AreEqual(expectedEntitiesOutput.Count, result1.Entities.Count);
foreach (HealthcareEntity entity in result1.Entities)
{
Assert.IsTrue(expectedEntitiesOutput.Contains(entity.Text));
if (entity.Text == "Baby")
{
var linksList = new List<string> { "UMLS", "AOD", "CCPSS", "CHV", "DXP", "LCH", "LCH_NW", "LNC", "MDR", "MSH", "NCI", "NCI_FDA", "NCI_NICHD", "SNOMEDCT_US" };
foreach (EntityDataSource entityDataSource in entity.DataSources)
Assert.IsTrue(linksList.Contains(entityDataSource.Name));
Assert.AreEqual("Infant", entity.NormalizedText);
}
if (entity.Text == "Meningitis")
{
Assert.AreEqual(24, entity.Offset);
Assert.AreEqual("Diagnosis", entity.Category);
Assert.AreEqual(10, entity.Length);
Assert.IsNotNull(entity.Assertion);
Assert.AreEqual(Certainty.NegativePossible, entity.Assertion.Certainty.Value);
}
if (entity.Text == "Penicillin")
{
Assert.AreEqual("MedicationName", entity.Category);
Assert.AreEqual(10, entity.Length);
Assert.IsNotNull(entity.Assertion);
Assert.AreEqual(Certainty.NeutralPossible, entity.Assertion.Certainty.Value);
}
}
}
[Test]
public async Task RecognizeHealthcareEntitiesWithLanguageTest()
{
TextAnalyticsClient client = GetClient();
AnalyzeHealthcareEntitiesOperation operation = await client.StartAnalyzeHealthcareEntitiesAsync(s_batchConvenienceDocuments, "en");
await operation.WaitForCompletionAsync(PollingInterval);
ValidateOperationProperties(operation);
//Take the first page
AnalyzeHealthcareEntitiesResultCollection resultCollection = operation.Value.ToEnumerableAsync().Result.FirstOrDefault();
var expectedOutput = new Dictionary<string, List<string>>()
{
{ "0", s_document1ExpectedEntitiesOutput },
{ "1", s_document2ExpectedEntitiesOutput },
};
ValidateBatchDocumentsResult(resultCollection, expectedOutput);
}
[Test]
public async Task RecognizeHealthcareEntitiesBatchWithErrorTest()
{
TextAnalyticsClient client = GetClient();
var documents = new List<string>
{
"Subject is taking 100mg of ibuprofen twice daily",
"Can cause rapid or irregular heartbeat, delirium, panic, psychosis, and heart failure.",
"",
};
AnalyzeHealthcareEntitiesOperation operation = await client.StartAnalyzeHealthcareEntitiesAsync(documents);
await operation.WaitForCompletionAsync(PollingInterval);
ValidateOperationProperties(operation);
//Take the first page
AnalyzeHealthcareEntitiesResultCollection resultCollection = operation.Value.ToEnumerableAsync().Result.FirstOrDefault();
Assert.IsNotNull(resultCollection[2].Id);
Assert.IsTrue(!resultCollection[0].HasError);
Assert.IsTrue(!resultCollection[1].HasError);
Assert.IsTrue(resultCollection[2].HasError);
InvalidOperationException ex = Assert.Throws<InvalidOperationException>(() => resultCollection[2].Entities.GetType());
Assert.AreEqual(TextAnalyticsErrorCode.InvalidDocument, resultCollection[2].Error.ErrorCode.ToString());
}
[Test]
public async Task RecognizeHealthcareEntitiesBatchConvenienceTest()
{
TextAnalyticsClient client = GetClient();
AnalyzeHealthcareEntitiesOperation operation = await client.StartAnalyzeHealthcareEntitiesAsync(s_batchConvenienceDocuments);
await operation.WaitForCompletionAsync(PollingInterval);
ValidateOperationProperties(operation);
//Take the first page
AnalyzeHealthcareEntitiesResultCollection resultCollection = operation.Value.ToEnumerableAsync().Result.FirstOrDefault();
var expectedOutput = new Dictionary<string, List<string>>()
{
{ "0", s_document1ExpectedEntitiesOutput },
{ "1", s_document2ExpectedEntitiesOutput },
};
ValidateBatchDocumentsResult(resultCollection, expectedOutput);
}
[Test]
public async Task RecognizeHealthcareEntitiesBatchConvenienceWithStatisticsTest()
{
TextAnalyticsClient client = GetClient();
AnalyzeHealthcareEntitiesOptions options = new AnalyzeHealthcareEntitiesOptions()
{
IncludeStatistics = true
};
AnalyzeHealthcareEntitiesOperation operation = await client.StartAnalyzeHealthcareEntitiesAsync(s_batchConvenienceDocuments, "en", options);
await operation.WaitForCompletionAsync(PollingInterval);
ValidateOperationProperties(operation);
//Take the first page
AnalyzeHealthcareEntitiesResultCollection resultCollection = operation.Value.ToEnumerableAsync().Result.FirstOrDefault();
var expectedOutput = new Dictionary<string, List<string>>()
{
{ "0", s_document1ExpectedEntitiesOutput },
{ "1", s_document2ExpectedEntitiesOutput },
};
ValidateBatchDocumentsResult(resultCollection, expectedOutput, true);
}
[Test]
public async Task RecognizeHealthcareEntitiesBatchTest()
{
TextAnalyticsClient client = GetClient();
AnalyzeHealthcareEntitiesOperation operation = await client.StartAnalyzeHealthcareEntitiesAsync(s_batchDocuments);
await operation.WaitForCompletionAsync(PollingInterval);
ValidateOperationProperties(operation);
//Take the first page
AnalyzeHealthcareEntitiesResultCollection resultCollection = operation.Value.ToEnumerableAsync().Result.FirstOrDefault();
var expectedOutput = new Dictionary<string, List<string>>()
{
{ "1", s_document1ExpectedEntitiesOutput },
{ "2", s_document2ExpectedEntitiesOutput },
};
ValidateBatchDocumentsResult(resultCollection, expectedOutput);
}
[Test]
public async Task RecognizeHealthcareEntitiesBatchWithStatisticsTest()
{
TextAnalyticsClient client = GetClient();
AnalyzeHealthcareEntitiesOptions options = new AnalyzeHealthcareEntitiesOptions()
{
IncludeStatistics = true
};
AnalyzeHealthcareEntitiesOperation operation = await client.StartAnalyzeHealthcareEntitiesAsync(s_batchDocuments, options);
await operation.WaitForCompletionAsync(PollingInterval);
ValidateOperationProperties(operation);
//Take the first page
AnalyzeHealthcareEntitiesResultCollection resultCollection = operation.Value.ToEnumerableAsync().Result.FirstOrDefault();
var expectedOutput = new Dictionary<string, List<string>>()
{
{ "1", s_document1ExpectedEntitiesOutput },
{ "2", s_document2ExpectedEntitiesOutput },
};
ValidateBatchDocumentsResult(resultCollection, expectedOutput, true);
}
[Test]
public async Task RecognizeHealthcareEntitiesBatchWithCancellation()
{
TextAnalyticsClient client = GetClient();
string document = @"RECORD #333582770390100 | MH | 85986313 | | 054351 | 2/14/2001 12:00:00 AM | CORONARY ARTERY DISEASE | Signed | DIS |";
var batchDocuments = new List<string>();
for (var i = 0; i < 10; i++)
{
batchDocuments.Add(document);
}
AnalyzeHealthcareEntitiesOperation operation = await client.StartAnalyzeHealthcareEntitiesAsync(batchDocuments, "en");
await operation.CancelAsync();
RequestFailedException ex = Assert.ThrowsAsync<RequestFailedException>(async () => await operation.WaitForCompletionAsync());
Assert.IsTrue(ex.Message.Contains("The operation was canceled so no value is available."));
Assert.IsTrue(operation.HasCompleted);
Assert.IsFalse(operation.HasValue);
Assert.AreEqual(200, operation.GetRawResponse().Status);
Assert.AreEqual(TextAnalyticsOperationStatus.Cancelled, operation.Status);
try
{
Assert.IsNull(operation.Value);
}
catch (RequestFailedException exception)
{
Assert.IsTrue(exception.Message.Contains("The operation was canceled so no value is available."));
}
}
[Test]
public async Task AnalyzeHealthcareEntitiesPagination()
{
TextAnalyticsClient client = GetClient();
AnalyzeHealthcareEntitiesOperation operation = await client.StartAnalyzeHealthcareEntitiesAsync(s_batchDocuments);
Assert.IsFalse(operation.HasCompleted);
Assert.IsFalse(operation.HasValue);
Assert.ThrowsAsync<InvalidOperationException>(async () => await Task.Run(() => operation.Value));
Assert.Throws<InvalidOperationException>(() => operation.GetValues());
await operation.WaitForCompletionAsync(PollingInterval);
Assert.IsTrue(operation.HasCompleted);
Assert.IsTrue(operation.HasValue);
ValidateOperationProperties(operation);
// try async
//There most be 1 page
List<AnalyzeHealthcareEntitiesResultCollection> asyncPages = operation.Value.ToEnumerableAsync().Result;
Assert.AreEqual(1, asyncPages.Count);
// First page should have 2 results
Assert.AreEqual(2, asyncPages[0].Count);
// try sync
//There most be 1 page
List<AnalyzeHealthcareEntitiesResultCollection> pages = operation.GetValues().AsEnumerable().ToList();
Assert.AreEqual(1, pages.Count);
// First page should have 2 results
Assert.AreEqual(2, pages[0].Count);
}
private void ValidateInDocumenResult(IReadOnlyCollection<HealthcareEntity> entities, List<string> minimumExpectedOutput)
{
Assert.GreaterOrEqual(entities.Count, minimumExpectedOutput.Count);
foreach (HealthcareEntity entity in entities)
{
Assert.That(entity.Text, Is.Not.Null.And.Not.Empty);
Assert.IsNotNull(entity.Category);
Assert.GreaterOrEqual(entity.ConfidenceScore, 0.0);
Assert.GreaterOrEqual(entity.Offset, 0);
Assert.Greater(entity.Length, 0);
if (entity.SubCategory != null)
{
Assert.IsNotEmpty(entity.SubCategory);
}
}
}
private void ValidateBatchDocumentsResult(AnalyzeHealthcareEntitiesResultCollection results, Dictionary<string, List<string>> minimumExpectedOutput, bool includeStatistics = default)
{
Assert.That(results.ModelVersion, Is.Not.Null.And.Not.Empty);
if (includeStatistics)
{
Assert.IsNotNull(results.Statistics);
Assert.Greater(results.Statistics.DocumentCount, 0);
Assert.Greater(results.Statistics.TransactionCount, 0);
Assert.GreaterOrEqual(results.Statistics.InvalidDocumentCount, 0);
Assert.GreaterOrEqual(results.Statistics.ValidDocumentCount, 0);
}
else
Assert.IsNull(results.Statistics);
foreach (AnalyzeHealthcareEntitiesResult entitiesInDocument in results)
{
Assert.That(entitiesInDocument.Id, Is.Not.Null.And.Not.Empty);
Assert.False(entitiesInDocument.HasError);
//Even though statistics are not asked for, TA 5.0.0 shipped with Statistics default always present.
Assert.IsNotNull(entitiesInDocument.Statistics);
if (includeStatistics)
{
Assert.GreaterOrEqual(entitiesInDocument.Statistics.CharacterCount, 0);
Assert.Greater(entitiesInDocument.Statistics.TransactionCount, 0);
}
else
{
Assert.AreEqual(0, entitiesInDocument.Statistics.CharacterCount);
Assert.AreEqual(0, entitiesInDocument.Statistics.TransactionCount);
}
Assert.IsNotNull(entitiesInDocument.Warnings);
ValidateInDocumenResult(entitiesInDocument.Entities, minimumExpectedOutput[entitiesInDocument.Id]);
}
}
private void ValidateOperationProperties(AnalyzeHealthcareEntitiesOperation operation)
{
Assert.AreNotEqual(new DateTimeOffset(), operation.CreatedOn);
Assert.AreNotEqual(new DateTimeOffset(), operation.LastModified);
if (operation.ExpiresOn.HasValue)
{
Assert.AreNotEqual(new DateTimeOffset(), operation.ExpiresOn.Value);
}
}
}
}
| 41.098947 | 327 | 0.619762 | [
"MIT"
] | xaliciayang/azure-sdk-for-ne | sdk/textanalytics/Azure.AI.TextAnalytics/tests/RecognizeHealthcareEntitiesTests.cs | 19,524 | C# |
using EmploymentsShared;
using MongoDB.Bson;
using MongoDB.Bson.Serialization.Attributes;
using MongoDB.Driver;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using ContactsShared;
namespace SoftwareManagementMongoDbCoreRepository
{
[BsonIgnoreExtraElements]
public class EmploymentState : TimeStampedEntityState, IEmploymentState
{
public Guid ContactGuid { get; set; }
public Guid CompanyRoleGuid { get; set; }
public DateTime? StartDate { get; set; }
public DateTime? EndDate { get; set; }
public string ContactName { get; set; }
}
public class EmploymentStateRepository: IEmploymentStateRepository
{
private const string CommandStatesCollection = "CommandStates";
private const string ProjectStatesCollection = "ProjectStates";
private const string ContactStatesCollection = "ContactStates";
private const string CompanyStatesCollection = "CompanyStates";
private const string EmploymentStatesCollection = "EmploymentStates";
private const string ProjectRoleAssignmentStatesCollection = "ProjectRoleAssignmentStates";
private IMongoClient _client;
private IMongoDatabase _database;
private Dictionary<Guid, IEmploymentState> _employmentStates;
private List<Guid> _deletedEmploymentStates;
public EmploymentStateRepository(IMongoClient client)
{
_client = client;
_database = _client.GetDatabase("SoftwareManagement");
_employmentStates = new Dictionary<Guid, IEmploymentState>();
_deletedEmploymentStates = new List<Guid>();
}
public IEmploymentState CreateEmploymentState(Guid guid, Guid linkGuid, Guid companyRoleGuid)
{
var state = new EmploymentState()
{
Guid = guid,
ContactGuid = linkGuid,
CompanyRoleGuid = companyRoleGuid
};
_employmentStates.Add(state.Guid, state);
return state;
}
public void DeleteEmploymentState(Guid guid)
{
_deletedEmploymentStates.Add(guid);
}
public IEnumerable<IContactState> GetContactsByCompanyRoleGuid(Guid companyRoleGuid)
{
throw new NotImplementedException();
}
// todo: this can probably be done more efficiently
public IEnumerable<IEmploymentState> GetEmploymentsByCompanyRoleGuid(Guid companyRoleGuid)
{
var collection = _database.GetCollection<EmploymentState>(EmploymentStatesCollection);
var filter = Builders<EmploymentState>.Filter.Eq("CompanyRoleGuid", companyRoleGuid);
var states = collection.Find(filter);
if (states != null)
{
var linksCollection = _database.GetCollection<ContactState>(ContactStatesCollection);
var linkGuids = states.ToList().Select(s => s.ContactGuid).ToList();
var filterDef = new FilterDefinitionBuilder<ContactState>();
var linksFilter = filterDef.In(x => x.Guid, linkGuids);
var linkStates = linksCollection.Find(linksFilter).ToList();
var employmentStates = states.ToList();
foreach (var state in linkStates)
{
var employmentState = employmentStates.FirstOrDefault(s => s.ContactGuid == state.Guid);
if (employmentState != null)
{
employmentState.ContactName = state.Name;
}
}
}
return states?.ToList();
}
public IEnumerable<IEmploymentState> GetEmploymentsByContactGuid(Guid linkGuid)
{
var collection = _database.GetCollection<EmploymentState>(ContactStatesCollection);
var filter = Builders<EmploymentState>.Filter.Eq("ContactRoleGuid", linkGuid);
var states = collection.Find(filter);
return states?.ToList();
}
public IEmploymentState GetEmploymentState(Guid guid)
{
if (!_employmentStates.TryGetValue(guid, out IEmploymentState state))
{
var collection = _database.GetCollection<EmploymentState>(EmploymentStatesCollection);
var filter = Builders<EmploymentState>.Filter.Eq("Guid", guid);
state = collection.Find(filter).FirstOrDefault();
}
return state;
}
public IEnumerable<IEmploymentState> GetEmploymentStates()
{
var collection = _database.GetCollection<EmploymentState>(EmploymentStatesCollection);
var filter = new BsonDocument();
var states = collection.Find(filter);
return states?.ToList();
}
public void PersistChanges()
{
PersistEmployments();
}
private void PersistEmployments()
{
// inserts
if (_employmentStates.Values.Any())
{
var collection = _database.GetCollection<EmploymentState>(EmploymentStatesCollection);
var entities = _employmentStates.Values.Select(s => s as EmploymentState).ToList();
collection.InsertMany(entities);
_employmentStates.Clear();
}
// deletes
if (_deletedEmploymentStates.Any())
{
var collection = _database.GetCollection<EmploymentState>(EmploymentStatesCollection);
foreach (var guid in _deletedEmploymentStates)
{
var filter = Builders<EmploymentState>.Filter.Eq("Guid", guid);
collection.DeleteOne(filter, null, CancellationToken.None);
}
_deletedEmploymentStates.Clear();
}
}
}
}
| 36.658537 | 108 | 0.618097 | [
"MIT"
] | niwrA/Software-Management-Core | SoftwareManagementMongoDbCoreRepository/EmploymentStateRepository.cs | 6,014 | C# |
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="ContainerExtensionsTest.cs">
// Copyright (c) 2017. All rights reserved. Licensed under the MIT license. See LICENSE file in
// the project root for full license information.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace Spritely.Foundations.WebApi.Test
{
using Microsoft.Owin.Builder;
using NSubstitute;
using NUnit.Framework;
using Owin;
[TestFixture]
public class ContainerExtensionsTest
{
[Test]
public void UserContainerInitializer_registers_method_for_callback_on_container_creation()
{
var app = Substitute.For<IAppBuilder>();
var initializeContainer = Substitute.For<InitializeContainer>();
app.UseContainerInitializer(initializeContainer);
app.GetContainer();
initializeContainer.ReceivedWithAnyArgs(requiredNumberOfCalls: 1);
}
[Test]
public void GetInstanceOfT_returns_expected_result()
{
var expected = new TestType();
var app = new AppBuilder();
InitializeContainer initializeContainer = container =>
{
container.Register<TestType>(() => expected);
};
app.UseContainerInitializer(initializeContainer);
Assert.That(app.GetInstance<TestType>(), Is.SameAs(expected));
}
[Test]
public void GetInstance_returns_expected_result()
{
var expected = new TestType();
var app = new AppBuilder();
InitializeContainer initializeContainer = container =>
{
container.Register<TestType>(() => expected);
};
app.UseContainerInitializer(initializeContainer);
Assert.That(app.GetInstance(typeof(TestType)), Is.SameAs(expected));
}
private class TestType
{
// Irrelevant
};
}
}
| 31.275362 | 120 | 0.542169 | [
"MIT"
] | spritely/Foundations.WebApi | Foundations.WebApi.Test/AppBuilder/ContainerExtensionsTest.cs | 2,160 | C# |
using System;
using System.ComponentModel;
namespace QF.GraphDesigner
{
public static class ViewModelExtensions
{
public static System.Action SubscribeToProperty<TViewModel>(this TViewModel vm, string propertyName, Action<TViewModel> action) where TViewModel : ViewModel
{
PropertyChangedEventHandler handler = (sender, args) =>
{
action(sender as TViewModel);
};;
vm.PropertyChanged += handler;
return ()=> { vm.PropertyChanged -= handler; };
}
}
} | 29.631579 | 164 | 0.623446 | [
"MIT"
] | GameAnt/QFramework | Assets/QFramework/Framework/6.EditorToolKit/Editor/uFrame.Editor/Systems/GraphUI/ViewModels/ViewModelExtensions.cs | 563 | C# |
// ===========
// DO NOT EDIT - this file is automatically regenerated.
// ===========
using Improbable.Gdk.Core;
using Improbable.Worker.CInterop;
namespace Improbable.Gdk.Tests.ComponentsWithNoFields
{
public partial class ComponentWithNoFields
{
public class DiffComponentDeserializer : IComponentDiffDeserializer
{
public uint GetComponentId()
{
return ComponentId;
}
public void AddUpdateToDiff(ComponentUpdateOp op, ViewDiff diff, uint updateId)
{
var update = global::Improbable.Gdk.Tests.ComponentsWithNoFields.ComponentWithNoFields.Serialization.DeserializeUpdate(op.Update.SchemaData.Value);
diff.AddComponentUpdate(update, op.EntityId, op.Update.ComponentId, updateId);
}
public void AddComponentToDiff(AddComponentOp op, ViewDiff diff)
{
var data = Serialization.DeserializeUpdate(op.Data.SchemaData.Value);
diff.AddComponent(data, op.EntityId, op.Data.ComponentId);
}
}
public class ComponentSerializer : IComponentSerializer
{
public uint GetComponentId()
{
return ComponentId;
}
public void Serialize(MessagesToSend messages, SerializedMessagesToSend serializedMessages)
{
var storage = messages.GetComponentDiffStorage(ComponentId);
var updates = ((IDiffUpdateStorage<Update>) storage).GetUpdates();
for (int i = 0; i < updates.Count; ++i)
{
ref readonly var update = ref updates[i];
var schemaUpdate = new SchemaComponentUpdate(ComponentId);
var componentUpdate = new ComponentUpdate(schemaUpdate);
Serialization.SerializeUpdate(update.Update, schemaUpdate);
serializedMessages.AddComponentUpdate(componentUpdate, update.EntityId.Id);
}
}
}
}
}
| 35.982759 | 163 | 0.601342 | [
"MIT"
] | gdk-for-unity-bot/gdk-for-unity | test-project/Assets/Generated/Source/improbable/gdk/tests/componentswithnofields/ComponentWithNoFieldsComponentDiffDeserializer.cs | 2,087 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data;
using System.Data.Entity;
using System.Data.Entity.ModelConfiguration;
using System.Data.Entity.ModelConfiguration.Conventions;
using System.Linq;
using System.Globalization;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using APPBASE.Helpers;
using APPBASE.Models;
using APPBASE.Svcapp;
using Omu.ValueInjecter;
namespace APPBASE.Models
{
public class MonthCRUD
{
private DBMAINContext db;
private Month oModel;
public int? ID { get; set; }
public Boolean isERR { get; set; }
public string ERRMSG { get; set; }
//Constructor 1
public MonthCRUD() { this.db = new DBMAINContext(); } //End public MonthCRUD()
//Constructor 2
public MonthCRUD(DBMAINContext poDB)
{ this.db = poDB; } //End public MonthCRUD()
public void Create(MonthVM poViewModel)
{
try
{
this.oModel = new Month();
//Map Form Data
this.oModel.InjectFrom(poViewModel);
//Set Field Header
this.oModel.setFIELD_HEADER(hlpFlags_CRUDOption.CREATE);
//Set DTA_STS
//this.oModel.DTA_STS = valFLAG.FLAG_DTA_STS_CREATE;
//Process CRUD
this.db.Months.Add(this.oModel);
//this.db.SaveChanges();
//this.ID = this.oModel.ID;
} //End try
catch (Exception e) { isERR = true; this.ERRMSG = "CRUD - Create: " + e.Message; } //End catch
} //End public void Create
public void Update(MonthVM poViewModel)
{
try
{
this.oModel = this.db.Months.AsNoTracking().SingleOrDefault(fld => fld.ID == poViewModel.ID);
//Map Form Data
this.oModel.InjectFrom(poViewModel);
//Set Field Header
this.oModel.setFIELD_HEADER(hlpFlags_CRUDOption.UPDATE);
//Set DTA_STS
//this.oModel.DTA_STS = valFLAG.FLAG_DTA_STS_UPDATE;
//Process CRUD
this.db.Entry(this.oModel).State = EntityState.Modified;
//this.db.SaveChanges();
//this.ID = this.oModel.ID;
} //End try
catch (Exception e) { isERR = true; this.ERRMSG = "CRUD - Update" + e.Message; } //End catch
} //End public void Update
public void Delete(int? id)
{
try
{
this.oModel = this.db.Months.Find(id);
this.db.Months.Remove(this.oModel);
//this.db.SaveChanges();
//this.ID = this.oModel.ID;
} //End try
catch (Exception e) { isERR = true; this.ERRMSG = "CRUD - Delete" + e.Message; } //End catch
} //End public void Delete
public void Commit()
{
this.db.SaveChanges();
this.ID = this.oModel.ID;
} //End public void Commit()
} //End public class MonthCRUD
} //End namespace APPBASE.Models
| 36.269663 | 109 | 0.568463 | [
"MIT"
] | arinsuga/posup | APPBASE/BASEMST/Month/ModelsServices/MonthCRUD_Services.cs | 3,230 | C# |
#nullable enable
using Content.Server.GameObjects.Components.Items.Storage;
using Content.Server.Interfaces.Chat;
using Content.Server.Interfaces.GameObjects;
using Content.Server.Utility;
using Content.Shared.GameObjects.Components.Morgue;
using Content.Shared.GameObjects.EntitySystems;
using Content.Shared.GameObjects.EntitySystems.ActionBlocker;
using Content.Shared.GameObjects.Verbs;
using Content.Shared.Interfaces;
using Content.Shared.Interfaces.GameObjects.Components;
using Robust.Shared.GameObjects;
using Robust.Shared.Localization;
using Robust.Shared.Utility;
using Robust.Shared.ViewVariables;
using System.Threading;
using Content.Server.Interfaces.GameTicking;
using Content.Server.Players;
using Robust.Server.GameObjects;
using Robust.Server.Player;
using Robust.Shared.IoC;
namespace Content.Server.GameObjects.Components.Morgue
{
[RegisterComponent]
[ComponentReference(typeof(MorgueEntityStorageComponent))]
[ComponentReference(typeof(EntityStorageComponent))]
[ComponentReference(typeof(IActivate))]
[ComponentReference(typeof(IStorageComponent))]
public class CrematoriumEntityStorageComponent : MorgueEntityStorageComponent, IExamine, ISuicideAct
{
public override string Name => "CrematoriumEntityStorage";
[ViewVariables]
public bool Cooking { get; private set; }
[ViewVariables(VVAccess.ReadWrite)]
private int _burnMilis = 3000;
private CancellationTokenSource? _cremateCancelToken;
void IExamine.Examine(FormattedMessage message, bool inDetailsRange)
{
if (Appearance == null) return;
if (inDetailsRange)
{
if (Appearance.TryGetData(CrematoriumVisuals.Burning, out bool isBurning) && isBurning)
{
message.AddMarkup(Loc.GetString("The {0:theName} is [color=red]active[/color]!\n", Owner));
}
if (Appearance.TryGetData(MorgueVisuals.HasContents, out bool hasContents) && hasContents)
{
message.AddMarkup(Loc.GetString("The content light is [color=green]on[/color], there's something in here."));
}
else
{
message.AddText(Loc.GetString("The content light is off, there's nothing in here."));
}
}
}
public override bool CanOpen(IEntity user, bool silent = false)
{
if (Cooking)
{
if (!silent) Owner.PopupMessage(user, Loc.GetString("Safety first, not while it's active!"));
return false;
}
return base.CanOpen(user, silent);
}
public void TryCremate()
{
if (Cooking) return;
if (Open) return;
Cremate();
}
public void Cremate()
{
if (Open)
CloseStorage();
Appearance?.SetData(CrematoriumVisuals.Burning, true);
Cooking = true;
_cremateCancelToken?.Cancel();
_cremateCancelToken = new CancellationTokenSource();
Owner.SpawnTimer(_burnMilis, () =>
{
if (Owner.Deleted)
return;
Appearance?.SetData(CrematoriumVisuals.Burning, false);
Cooking = false;
if (Contents.ContainedEntities.Count > 0)
{
for (var i = Contents.ContainedEntities.Count - 1; i >= 0; i--)
{
var item = Contents.ContainedEntities[i];
Contents.Remove(item);
item.Delete();
}
var ash = Owner.EntityManager.SpawnEntity("Ash", Owner.Transform.Coordinates);
Contents.Insert(ash);
}
TryOpenStorage(Owner);
EntitySystem.Get<AudioSystem>().PlayFromEntity("/Audio/Machines/ding.ogg", Owner);
}, _cremateCancelToken.Token);
}
SuicideKind ISuicideAct.Suicide(IEntity victim, IChatManager chat)
{
var mind = victim.PlayerSession()?.ContentData()?.Mind;
if (mind != null)
{
IoCManager.Resolve<IGameTicker>().OnGhostAttempt(mind, false);
mind.OwnedEntity.PopupMessage(Loc.GetString("You cremate yourself!"));
}
victim.PopupMessageOtherClients(Loc.GetString("{0:theName} is cremating {0:themself}!", victim));
EntitySystem.Get<SharedStandingStateSystem>().Down(victim, false, false, true);
if (CanInsert(victim))
{
Insert(victim);
}
else
{
victim.Delete();
}
Cremate();
return SuicideKind.Heat;
}
[Verb]
private sealed class CremateVerb : Verb<CrematoriumEntityStorageComponent>
{
protected override void GetData(IEntity user, CrematoriumEntityStorageComponent component, VerbData data)
{
if (!ActionBlockerSystem.CanInteract(user) || component.Cooking || component.Open)
{
data.Visibility = VerbVisibility.Invisible;
return;
}
data.Text = Loc.GetString("Cremate");
}
/// <inheritdoc />
protected override void Activate(IEntity user, CrematoriumEntityStorageComponent component)
{
component.TryCremate();
}
}
}
}
| 33.662722 | 129 | 0.582703 | [
"MIT"
] | GraniteSidewalk/space-station-14 | Content.Server/GameObjects/Components/Morgue/CrematoriumEntityStorageComponent.cs | 5,691 | 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.Text;
namespace NuGet
{
/// <summary>
/// Provides a resource pool that enables reusing instances of <see cref="StringBuilder"/> instances.
/// </summary>
/// <remarks>
/// <para>
/// Renting and returning buffers with an <see cref="StringBuilderPool"/> can increase performance
/// in situations where <see cref="StringBuilder"/> instances are created and destroyed frequently,
/// resulting in significant memory pressure on the garbage collector.
/// </para>
/// <para>
/// This class is thread-safe. All members may be used by multiple threads concurrently.
/// </para>
/// </remarks>
internal class StringBuilderPool
{
private const int MaxPoolSize = 256;
private readonly SimplePool<StringBuilder> _pool = new(() => new StringBuilder(MaxPoolSize));
/// <summary>
/// Retrieves a shared <see cref="StringBuilderPool"/> instance.
/// </summary>
public static readonly StringBuilderPool Shared = new();
private StringBuilderPool()
{
}
/// <summary>
/// Retrieves a <see cref="StringBuilder"/> that is at least the requested length.
/// </summary>
/// <param name="minimumCapacity">The minimum capacity of the <see cref="StringBuilder"/> needed.</param>
/// <returns>
/// A <see cref="StringBuilder"/> that is at least <paramref name="minimumCapacity"/> in length.
/// </returns>
/// <remarks>
/// This buffer is loaned to the caller and should be returned to the same pool via
/// <see cref="Return"/> so that it may be reused in subsequent usage of <see cref="Rent"/>.
/// It is not a fatal error to not return a rented string builder, but failure to do so may lead to
/// decreased application performance, as the pool may need to create a new instance to replace
/// the one lost.
/// </remarks>
public StringBuilder Rent(int minimumCapacity)
{
if (minimumCapacity <= MaxPoolSize)
{
return _pool.Allocate();
}
return new StringBuilder(minimumCapacity);
}
/// <summary>
/// Returns to the pool an array that was previously obtained via <see cref="Rent"/> on the same
/// <see cref="StringBuilderPool"/> instance.
/// </summary>
/// <param name="builder">
/// The <see cref="StringBuilder"/> previously obtained from <see cref="Rent"/> to return to the pool.
/// </param>
/// <remarks>
/// Once a <see cref="StringBuilder"/> has been returned to the pool, the caller gives up all ownership
/// of the instance and must not use it. The reference returned from a given call to <see cref="Rent"/>
/// must only be returned via <see cref="Return"/> once. The default <see cref="StringBuilderPool"/>
/// may hold onto the returned instance in order to rent it again, or it may release the returned instance
/// if it's determined that the pool already has enough instances stored.
/// </remarks>
public void Return(StringBuilder builder)
{
if (builder.Capacity <= MaxPoolSize)
{
builder.Clear();
_pool.Free(builder);
}
}
}
}
| 42.364706 | 114 | 0.613163 | [
"Apache-2.0"
] | AntonC9018/NuGet.Client | build/Shared/StringBuilderPool.cs | 3,601 | C# |
using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("AWSSDK.Signer")]
[assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (3.5) - AWS Signer. With code signing for IoT, you can sign code that you create for any IoT device that is supported by Amazon Web Services (AWS). Code signing is available through Amazon FreeRTOS and AWS IoT Device Management, and integrated with AWS Certificate Manager (ACM).")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyProduct("Amazon Web Services SDK for .NET")]
[assembly: AssemblyCompany("Amazon.com, Inc")]
[assembly: AssemblyCopyright("Copyright 2009-2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("3.3")]
[assembly: AssemblyFileVersion("3.3.102.43")] | 50.71875 | 351 | 0.752927 | [
"Apache-2.0"
] | SVemulapalli/aws-sdk-net | sdk/code-analysis/ServiceAnalysis/Signer/Properties/AssemblyInfo.cs | 1,623 | C# |
using System;
using System.Collections.Generic;
namespace Memoria
{
internal sealed class CmdInfoEqualityComparer : IEqualityComparer<CMD_INFO>
{
public static readonly CmdInfoEqualityComparer Instance = new CmdInfoEqualityComparer();
public Boolean Equals(CMD_INFO x, CMD_INFO y)
{
if (ReferenceEquals(x, y)) return true;
if (ReferenceEquals(x, null)) return false;
if (ReferenceEquals(y, null)) return false;
if (x.GetType() != y.GetType()) return false;
return x.cursor == y.cursor && x.def_cur == y.def_cur && x.sub_win == y.sub_win && x.vfx_no == y.vfx_no && x.sfx_no == y.sfx_no && x.dead == y.dead && x.def_cam == y.def_cam && x.def_dead == y.def_dead;
}
public Int32 GetHashCode(CMD_INFO obj)
{
unchecked
{
var hashCode = obj.cursor.GetHashCode();
hashCode = (hashCode * 397) ^ obj.def_cur.GetHashCode();
hashCode = (hashCode * 397) ^ obj.sub_win.GetHashCode();
hashCode = (hashCode * 397) ^ obj.vfx_no.GetHashCode();
hashCode = (hashCode * 397) ^ obj.sfx_no.GetHashCode();
hashCode = (hashCode * 397) ^ obj.dead.GetHashCode();
hashCode = (hashCode * 397) ^ obj.def_cam.GetHashCode();
hashCode = (hashCode * 397) ^ obj.def_dead.GetHashCode();
return hashCode;
}
}
}
} | 42.457143 | 214 | 0.570659 | [
"MIT"
] | BigDWilly73/FFIX | Memoria/Resources/Grahpics/Export/Battle/CmdInfoEqualityComparer.cs | 1,486 | C# |
using AutoFixture;
using AutoFixture.Xunit2;
using FluentAssertions;
using NHibernate.Linq;
using NHibernate.UserTypes.NodaTime.Test.Infrastructure;
using NodaTime;
using Xunit;
namespace NHibernate.UserTypes.NodaTime.Test.WithNormalMappings
{
[Collection("Database collection")]
public class NodaTimeOffsetDateTimeTest
{
private readonly ISessionFactory sessionFactory;
public NodaTimeOffsetDateTimeTest(DatabaseFixture databaseFixture)
{
sessionFactory = databaseFixture.SessionFactory;
}
[Theory, NodaTimeAutoData]
public void NullableOffsetDateTime_returns_expected_results(NodaTimeOffsetDateTime nodaTime)
{
PopulateDatabase(sessionFactory, nodaTime);
using (var session = sessionFactory.OpenSession())
{
var sut = session.Load<NodaTimeOffsetDateTime>(nodaTime.Id);
sut.NullableOffsetDateTime.Should().BeEquivalentTo(nodaTime.NullableOffsetDateTime);
}
CleanDatabase(sessionFactory);
}
[Theory, NodaTimeAutoData]
public void NullableOffsetDateTimeWithNull_returns_expected_results(NodaTimeOffsetDateTime nodaTime)
{
PopulateDatabase(sessionFactory, nodaTime);
using (var session = sessionFactory.OpenSession())
{
var sut = session.Load<NodaTimeOffsetDateTime>(nodaTime.Id);
sut.NullableOffsetDateTimeWithNull.Should().BeEquivalentTo(nodaTime.NullableOffsetDateTimeWithNull);
}
CleanDatabase(sessionFactory);
}
[Theory, NodaTimeAutoData]
public void OffsetDateTime_returns_expected_results(NodaTimeOffsetDateTime nodaTime)
{
PopulateDatabase(sessionFactory, nodaTime);
using (var session = sessionFactory.OpenSession())
{
var sut = session.Load<NodaTimeOffsetDateTime>(nodaTime.Id);
sut.OffsetDateTime.Should().BeEquivalentTo(nodaTime.OffsetDateTime);
}
CleanDatabase(sessionFactory);
}
private static void CleanDatabase(ISessionFactory sessionFactory)
{
using var session = sessionFactory.OpenSession();
session.Query<NodaTimeOffsetDateTime>().Delete();
session.Flush();
}
private static void PopulateDatabase(ISessionFactory sessionFactory, NodaTimeOffsetDateTime nodaTime)
{
using var session = sessionFactory.OpenSession();
session.Save(nodaTime);
session.Flush();
}
private class NodaTimeAutoDataAttribute : AutoDataAttribute
{
public NodaTimeAutoDataAttribute() : base(() => new Fixture().Customize(new Customisation()))
{
}
}
private class Customisation : ICustomization
{
public void Customize(IFixture fixture)
{
var instant1 = Instant.FromUtc(2016, 5, 6, 1, 2, 3);
var instant2 = Instant.FromUtc(2017, 7, 8, 4, 5, 6);
fixture.Register(() => new NodaTimeOffsetDateTime
{
OffsetDateTime = new OffsetDateTime(new LocalDateTime(2015, 9, 10, 7, 8, 9), Offset.FromHours(1)),
NullableOffsetDateTime =
new OffsetDateTime(new LocalDateTime(2016, 10, 11, 8, 9, 10), Offset.FromHours(2)),
NullableOffsetDateTimeWithNull = null
});
}
}
}
} | 34.586538 | 118 | 0.624409 | [
"MIT"
] | jmojiwat/NHibernate.UserTypes.NodaTime | src/NHibernate.UserTypes.NodaTime.Test/WithNormalMappings/NodaTimeOffsetDateTimeTest.cs | 3,599 | C# |
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
namespace CommunityTraining.Presentation.Blazor.Helpers
{
public class Video
{
public static string Preview(string id) => $"https://img.youtube.com/vi/{id}/maxresdefault.jpg";
//https://newbedev.com/how-do-i-get-a-youtube-video-thumbnail-from-the-youtube-api
public static List<string> Images(string id)
{
return new List<string>
{
$"https://img.youtube.com/vi/{id}/0.jpg",
$"https://img.youtube.com/vi/{id}/1.jpg",
$"https://img.youtube.com/vi/{id}/2.jpg",
$"https://img.youtube.com/vi/{id}/3.jpg",
$"https://img.youtube.com/vi/{id}/default.jpg",
$"https://img.youtube.com/vi/{id}/hqdefault.jpg",
$"https://img.youtube.com/vi/{id}/mqdefault.jpg",
$"https://img.youtube.com/vi/{id}/sddefault.jpg",
$"https://img.youtube.com/vi/{id}/maxresdefault.jpg",
};
}
public static string ExtraerId(string Video)
{
string id;
if (Video.ToLower().Contains("http") || Video.ToLower().Contains("youtu"))
{
try
{
Uri uri = new Uri(Video);
id = ExtraerId(uri);
}
catch
{
id = Video;
}
}
else id = Video;
return id;
}
public static string ExtraerId(Uri uri)
{
NameValueCollection query = HttpUtility.ParseQueryString(uri.Query);
return query["v"];
}
}
}
| 31.949153 | 104 | 0.491247 | [
"Unlicense"
] | drualcman/CommunityTraining | CommunityTraining.Presentation.Blazor/Helpers/Video.cs | 1,887 | C# |
using Microsoft.Extensions.CommandLineUtils;
using System;
namespace DotNetVersioningTool
{
class Program
{
static int Main(string[] args)
{
var app = new CommandLineApplication();
var listCommand = app.Command("list", config =>
{
});
var versionArg = new CommandArgument() { Name = "version", Description = "LTS or Current" };
var updateCommand = app.Command("update", config =>
{
config.Arguments.Add(versionArg);
config.OnExecute(() =>
{
return 0;
});
});
var version = app.Argument("version", "LTS or Current");
app.OnExecute(() =>
{
return 0;
});
return app.Execute(args);
}
}
} | 22.692308 | 104 | 0.465537 | [
"MIT"
] | leecow/DotNetVersioningTool | src/dotnet-package-versions/Program.cs | 887 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MainGameManager_Contra : SingletonBehaviour<MainGameManager_Contra>
{
private int sectionSpawned = 0;
private void OnEnable()
{
EventManager.OnSectionSpawned += OnSectionSpawned;
}
private void OnDisable()
{
EventManager.OnSectionSpawned -= OnSectionSpawned;
}
private void Start()
{
SectionManager.Instance.SpawnBoss();
}
private void OnSectionSpawned (Section section)
{
sectionSpawned++;
if (sectionSpawned == 3)
{
SectionManager.Instance.SpawnBoss();
sectionSpawned = 0;
}
}
}
| 20.828571 | 81 | 0.626886 | [
"Apache-2.0"
] | finalspace/LD46 | LilFire/Assets/Scripts/Prototype/Contra/MainGameManager_Contra.cs | 731 | C# |
using IoTSharp.Data;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace IoTSharp.Extensions
{
public static class DeviceExtension
{
/// <summary>
/// When creating a device, all the things that need to be done here are done
/// </summary>
/// <param name="_context"></param>
/// <param name="device"></param>
public static void AfterCreateDevice(this ApplicationDbContext _context, Device device)
{
if (device.Customer == null || device.Tenant == null || string.IsNullOrEmpty(device.Name))
{
throw new Exception("Customer or Tenant or Name is null or empty!");
}
else
{
_context.DeviceIdentities.Add(new DeviceIdentity()
{
Device = device,
IdentityType = IdentityType.AccessToken,
IdentityId = Guid.NewGuid().ToString().Replace("-", "")
});
Dictionary<string, object> pairs = new Dictionary<string, object>();
pairs.Add("CreateDateTime", DateTime.Now);
_context.PreparingData<AttributeLatest, AttributeData>(pairs, device, DataSide.ServerSide);
}
}
}
}
| 36.081081 | 107 | 0.56779 | [
"MIT"
] | masterchen/IoTSharp | IoTSharp/Extensions/DeviceExtension.cs | 1,337 | C# |
namespace gpmrw
{
partial class wstgOptimizations
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Component Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(wstgOptimizations));
this.label1 = new System.Windows.Forms.Label();
this.chkCombine = new System.Windows.Forms.CheckBox();
this.chkCollapse = new System.Windows.Forms.CheckBox();
this.label2 = new System.Windows.Forms.Label();
this.label3 = new System.Windows.Forms.Label();
this.SuspendLayout();
//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(3, 14);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(279, 13);
this.label1.TabIndex = 0;
this.label1.Text = "Select optimizations that you would like GPMR to perform:";
//
// chkCombine
//
this.chkCombine.AutoSize = true;
this.chkCombine.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.chkCombine.Location = new System.Drawing.Point(44, 48);
this.chkCombine.Name = "chkCombine";
this.chkCombine.Size = new System.Drawing.Size(224, 17);
this.chkCombine.TabIndex = 1;
this.chkCombine.Text = "Class Combination (Recommended)";
this.chkCombine.UseVisualStyleBackColor = true;
//
// chkCollapse
//
this.chkCollapse.AutoSize = true;
this.chkCollapse.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.chkCollapse.Location = new System.Drawing.Point(44, 155);
this.chkCollapse.Name = "chkCollapse";
this.chkCollapse.Size = new System.Drawing.Size(237, 17);
this.chkCollapse.TabIndex = 2;
this.chkCollapse.Text = "Class Collapsing (Not Recommended)";
this.chkCollapse.UseVisualStyleBackColor = true;
//
// label2
//
this.label2.Location = new System.Drawing.Point(64, 68);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(330, 84);
this.label2.TabIndex = 3;
this.label2.Text = resources.GetString("label2.Text");
//
// label3
//
this.label3.Location = new System.Drawing.Point(64, 175);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(330, 97);
this.label3.TabIndex = 4;
this.label3.Text = resources.GetString("label3.Text");
//
// wstgOptimizations
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.Controls.Add(this.label3);
this.Controls.Add(this.label2);
this.Controls.Add(this.chkCollapse);
this.Controls.Add(this.chkCombine);
this.Controls.Add(this.label1);
this.Name = "wstgOptimizations";
this.Size = new System.Drawing.Size(442, 293);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.Label label1;
private System.Windows.Forms.CheckBox chkCombine;
private System.Windows.Forms.CheckBox chkCollapse;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.Label label3;
}
}
| 43.396396 | 171 | 0.567366 | [
"Apache-2.0"
] | MohawkMEDIC/everest | gpmr/gpmrw/wstgOptimizations.Designer.cs | 4,819 | C# |
using Domain.Context.Entities;
using Domain.Repositories;
using Infra.Data;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Infra.Repositories
{
public class UsuariosRepository : IUsuariosRepository
{
private readonly DataContext _context;
public UsuariosRepository(DataContext context)
{
_context = context;
}
public async Task<List<Usuarios>> ObterTodos()
{
return await _context.Usuarios
.AsNoTracking()
.ToListAsync();
}
public async Task CriarUsuario(Usuarios usuarios)
{
_context.Add(usuarios);
await _context.SaveChangesAsync();
}
public async Task<Usuarios> LoginUsuario(string email, string senha)
{
return await _context.Usuarios
.AsNoTracking()
.Where(p => p.Email == email && p.Senha == senha)
.SingleOrDefaultAsync();
}
public async Task<string> ObterFuncaoIdPorUsuarioId(string usuarioId)
{
return await _context.Usuarios
.AsNoTracking()
.Where(p => p.Id == usuarioId)
.Select(p => p.FuncaoId)
.FirstOrDefaultAsync();
}
public async Task<Usuarios> ObterPorId(string usuarioId)
{
return await _context.Usuarios
.AsNoTracking()
.Where(p => p.Id == usuarioId)
.FirstOrDefaultAsync();
}
public async Task<Usuarios> ObterPorEmail(string email)
{
return await _context.Usuarios
.AsNoTracking()
.Where(p => p.Email == email)
.FirstOrDefaultAsync();
}
public async Task<bool> EmailExistente(string email)
{
return await _context.Usuarios
.AsNoTracking()
.Where(p => p.Email == email)
.AnyAsync();
}
}
}
| 28.171053 | 77 | 0.55348 | [
"Apache-2.0"
] | ThalyaMedeiros/DesafioTODO | Infra/Repositories/UsuariosRepository.cs | 2,143 | C# |
using System.Collections.Generic;
using System.Linq;
namespace AutomatedLab
{
/// <summary>
/// New external switch has a name collision with an already exisitng private or internal one.
/// </summary>
public class DuplicateAddressAssigned : LabValidator, IValidate
{
public DuplicateAddressAssigned()
{
messageContainer = RunValidation();
}
public override IEnumerable<ValidationMessage> Validate()
{
var dupliateAddresses = lab.Machines.SelectMany(m => m.NetworkAdapters)
.SelectMany(n => n.Ipv4Address)
.GroupBy(ip => ip.IpAddress)
.Where(group => group.Count() > 1);
if (dupliateAddresses.Count() == 0)
yield break;
foreach (var dupliateAddress in dupliateAddresses)
{
yield return new ValidationMessage
{
Message = string.Format("The IP address {0} is assigned multiple times", dupliateAddress.Key),
TargetObject = dupliateAddress.ToList().Select(ip => ip.IpAddress.AddressAsString)
.Aggregate((a, b) => a + ", " + b),
Type = MessageType.Error
};
}
}
}
} | 34.315789 | 114 | 0.555215 | [
"MIT"
] | AutomatedLab/AutomatedLab | LabXml/Validator/Network/DuplicateAddressAssigned.cs | 1,306 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NUnit.Framework;
using OpenQA.Selenium;
using OpenQA.Selenium.Firefox;
using OpenQA.Selenium.Support.UI;
namespace WebAddressbookTests
{
[TestFixture]
public class GroupModificationTests : GroupTestBase
{
[Test]
public void GroupModificationTest()
{
app.Navigator.GoToGroupsPage();
if (!app.Groups.IsElementPresentByClassName())
{
GroupData group = new GroupData("ddddd");
group.Header = "ffffff";
group.Footer = "gggggggg";
app.Groups.Create(group);
}
GroupData newData = new GroupData("zzz");
newData.Header = null;
newData.Footer = null;
List<GroupData> oldGroups = GroupData.GetAll();
GroupData toBeModified = oldGroups[0];
app.Groups.Modify(toBeModified, newData);
Assert.AreEqual(oldGroups.Count, app.Groups.GetGroupCount());
List<GroupData> newGroups = GroupData.GetAll();
oldGroups[0].Name = newData.Name;
oldGroups.Sort();
newGroups.Sort();
Assert.AreEqual(oldGroups, newGroups);
foreach (GroupData group in newGroups)
{
if (group.Id == toBeModified.Id)
{
Assert.AreEqual(newData.Name, group.Name);
}
}
}
}
}
| 27.803571 | 73 | 0.567759 | [
"Apache-2.0"
] | anastasiyaburaya/charp_training | addressbook-web-tests/addressbook-web-tests/tests/GroupModificationTests.cs | 1,559 | C# |
using Verse;
using RimWorld;
using System.Collections.Generic;
namespace TorannMagic
{
[StaticConstructorOnStartup]
public class Building_TMHeater : Building_WorkTable
{
private int nextSearch = 0;
private bool initialized = false;
public bool defensive = false;
public bool buffWarm = false;
public bool boostJoy = false;
public override void Tick()
{
if (!initialized)
{
this.nextSearch = Find.TickManager.TicksGame + Rand.Range(280, 320);
initialized = true;
}
if (Find.TickManager.TicksGame >= this.nextSearch)
{
this.nextSearch = Find.TickManager.TicksGame + Rand.Range(280, 320);
if (defensive)
{
Pawn e = TM_Calc.FindNearbyEnemy(this.Position, this.Map, this.Faction, 20, 0);
if (e != null && TM_Calc.HasLoSFromTo(this.Position, e, this, 0, 20))
{
Projectile firebolt = ThingMaker.MakeThing(ThingDef.Named("Projectile_Firebolt"), null) as Projectile;
TM_CopyAndLaunchProjectile.CopyAndLaunchProjectile(firebolt, this, e, e, ProjectileHitFlags.All, null);
}
}
if (buffWarm)
{
List<Pawn> pList = TM_Calc.FindAllPawnsAround(this.Map, this.Position, 7, this.Faction, true);
if (pList != null && pList.Count > 0)
{
for (int i = 0; i < pList.Count; i++)
{
Pawn p = pList[i];
if (p.health != null && p.health.hediffSet != null)
{
HealthUtility.AdjustSeverity(p, TorannMagicDefOf.TM_WarmHD, 0.18f);
}
}
}
}
if (boostJoy)
{
List<Pawn> pList = TM_Calc.FindAllPawnsAround(this.Map, this.Position, 7, this.Faction, true);
if (pList != null && pList.Count > 0)
{
for (int i = 0; i < pList.Count; i++)
{
Pawn p = pList[i];
if (p.needs != null && p.needs.joy != null)
{
Need joy = p.needs.TryGetNeed(NeedDefOf.Joy);
if (joy != null)
{
joy.CurLevel += Rand.Range(.01f, .02f);
}
}
}
}
}
}
base.Tick();
}
public override void ExposeData()
{
Scribe_Values.Look<bool>(ref this.defensive, "defensive", false, false);
Scribe_Values.Look<bool>(ref this.boostJoy, "boostJoy", false, false);
Scribe_Values.Look<bool>(ref this.buffWarm, "buffWarm", false, false);
base.ExposeData();
}
}
}
| 38.761905 | 127 | 0.435811 | [
"BSD-3-Clause"
] | Evyatar108/TMagic-Optimized | Source/TMagic/TMagic/Building_TMHeater.cs | 3,258 | C# |
using System;
using System.Threading.Tasks;
using Windows.Storage;
using Windows.System;
using Windows.UI.Xaml.Controls;
namespace DysproseTwo.Helpers
{
public static class ReviewHelper
{
const string launchCountSettingsValue = "launchCount";
const string noMorePromptsSettingsValue = "noMorePrompts";
static ApplicationDataContainer localSettings = ApplicationData.Current.LocalSettings;
static ReviewHelper()
{
TryUpdateLaunchCount();
}
private static void TryUpdateLaunchCount()
{
if (localSettings.Values[noMorePromptsSettingsValue] == null)
{
localSettings.Values[noMorePromptsSettingsValue] = false;
localSettings.Values[launchCountSettingsValue] = (byte)1;
}
else if ((bool)localSettings.Values[noMorePromptsSettingsValue] == false)
{
{
byte oldValue = (byte)localSettings.Values[launchCountSettingsValue];
localSettings.Values[launchCountSettingsValue] = (byte)(oldValue + 1);
}
}
}
// Recommended: Run this when you navigate app's "Home Page" or "Shell".
public static async Task TryRequestReviewAsync()
{
if (CheckIfTimeForReview())
{
var reviewDialog = new ContentDialog()
{
Title = "Enjoying the app?",
Content = "It would be lovely if you left a review! 😊",
PrimaryButtonText = "Review",
CloseButtonText = "Later"
};
reviewDialog.Closed += ReviewDialog_Closed;
await reviewDialog.ShowAsync();
}
}
private static async void ReviewDialog_Closed(ContentDialog sender, ContentDialogClosedEventArgs args)
{
if (args.Result == ContentDialogResult.Primary)
{
RemovePromptsForever();
await Launcher.LaunchUriAsync(new Uri("ms-windows-store://review/?ProductId=9NNZQ38B48ZJ"));
}
else
{
await ShowFeedbackDialog();
}
}
private static void RemovePromptsForever()
{
localSettings.Values[noMorePromptsSettingsValue] = true;
}
private async static Task ShowFeedbackDialog()
{
try
{
var feedbackDialog = new ContentDialog()
{
Title = "Feedback",
Content = "Your feedback is valuable. It improves your experience!",
PrimaryButtonText = "Give Feedback",
CloseButtonText = "Later",
};
feedbackDialog.Closed += FeedbackDialog_Closed;
await feedbackDialog.ShowAsync();
}
catch (Exception)
{
}
}
private async static void FeedbackDialog_Closed(ContentDialog sender, ContentDialogClosedEventArgs args)
{
if (args.Result == ContentDialogResult.Primary)
{
await Launcher.LaunchUriAsync(new Uri("mailto:colinkiama@gmail.com?subject=Dysprose%20Feedback&body=<Write%20your%20feedback%20here>"));
}
}
private static bool CheckIfTimeForReview()
{
bool isTimeToReview = false;
if ((bool)localSettings.Values[noMorePromptsSettingsValue] == false)
{
if ((byte)localSettings.Values[launchCountSettingsValue] == (byte)2)
{
isTimeToReview = true;
localSettings.Values[launchCountSettingsValue] = (byte)0;
}
}
return isTimeToReview;
}
}
}
| 32.180328 | 152 | 0.547631 | [
"MIT"
] | colinkiama/DysproseTwo | DysproseTwo/Helpers/ReviewHelper.cs | 3,931 | 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.
//
// Revision history:
//
// BD - June 2013 - Created this file.
//
using System;
using System.Linq.Expressions;
namespace Reaqtor
{
/// <summary>
/// Exposes reactive processing metadata discovery operations using a provider to perform service-side operations.
/// </summary>
public class ReactiveMetadata : ReactiveMetadataBase
{
#region Constructor & fields
private readonly IReactiveMetadataEngineProvider _provider;
private readonly IReactiveExpressionServices _expressionServices;
/// <summary>
/// Creates a new reactive processing metadata object using the specified metadata operations provider.
/// </summary>
/// <param name="provider">Metadata operations provider.</param>
/// <param name="expressionServices">Expression services object, used to perform expression tree manipulations.</param>
public ReactiveMetadata(IReactiveMetadataEngineProvider provider, IReactiveExpressionServices expressionServices)
{
_provider = provider ?? throw new ArgumentNullException(nameof(provider));
_expressionServices = expressionServices ?? throw new ArgumentNullException(nameof(expressionServices));
var thisParameter = ResourceNaming.GetThisReferenceExpression(this);
expressionServices.RegisterObject(this, thisParameter);
}
#endregion
#region Methods
/// <summary>
/// Executes the specified expression.
/// </summary>
/// <typeparam name="TResult">Result type of the expression.</typeparam>
/// <param name="expression">Expression to execute.</param>
/// <returns>Result of executing the expression.</returns>
protected override TResult Execute<TResult>(Expression expression)
{
var expr = _expressionServices.Normalize(expression);
return _provider.Provider.Execute<TResult>(expr);
}
#endregion
}
}
| 37.288136 | 127 | 0.688182 | [
"MIT"
] | Botcoin-com/reaqtor | Reaqtor/Core/Service/Reaqtor.Service/Reaqtor/ReactiveMetadata.cs | 2,202 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FiguresLi
{
class Point
{
}
}
| 13.076923 | 33 | 0.723529 | [
"MIT"
] | adrskw/zgadywanka-lab4n | zajecia/lab3/FiguresLab/FiguresLi/Point.cs | 172 | C# |
using CharlieBackend.Panel.Models.Homework;
using CharlieBackend.Core.DTO.Homework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace CharlieBackend.Panel.Services.Interfaces
{
public interface IHomeworkService
{
Task<IList<HomeworkViewModel>> GetHomeworks();
Task<HomeworkViewModel> GetHomeworkById(long id);
Task AddHomeworkEndpoint(HomeworkDto homeworkDto);
Task UpdateHomeworkEndpoint(long id, HomeworkDto homeworkDto);
}
}
| 29.5 | 70 | 0.768362 | [
"MIT"
] | ita-social-projects/WhatBackend | CharlieBackend.Panel/Services/Interfaces/IHomeworkService.cs | 533 | C# |
using Car.DAL.Entities;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
namespace Car.DAL.EntityConfigurations
{
internal class UserPreferencesConfiguration : IEntityTypeConfiguration<UserPreferences>
{
public void Configure(EntityTypeBuilder<UserPreferences> builder)
{
builder.HasKey(preferences => preferences.Id);
builder.HasOne(preferences => preferences.Owner)
.WithOne(user => user.UserPreferences)
.HasForeignKey<UserPreferences>(userPreferences => userPreferences.UserId);
}
}
}
| 33 | 91 | 0.709729 | [
"MIT"
] | UMuryn/car-back | CarBackEnd/Car.DAL/EntityConfigurations/UserPreferencesConfiguration.cs | 629 | C# |
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;
namespace Inixe.InixDialogs.Demo
{
/// <summary>
/// Interaction logic for App.xaml
/// </summary>
public partial class App : Application
{
}
}
| 17.666667 | 39 | 0.748428 | [
"MIT"
] | Arsenico95/InixDialogs | Source/Inixe.InixDialogs.Demo/App.xaml.cs | 320 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Assets.JusticeFramework.UI.Components {
class ListButton {
}
}
| 18.090909 | 49 | 0.768844 | [
"MIT"
] | RobertStivanson/Justice-Framework | UI/Components/ListButton.cs | 201 | C# |
// Copyright (C) 2015 Google, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using System.Collections.Generic;
using GoogleMobileAds.Api.Mediation;
namespace GoogleMobileAds.Api
{
public class AdRequest
{
public const string Version = "4.2.1";
public const string TestDeviceSimulator = "SIMULATOR";
private AdRequest(Builder builder)
{
this.TestDevices = new List<string>(builder.TestDevices);
this.Keywords = new HashSet<string>(builder.Keywords);
this.Birthday = builder.Birthday;
this.Gender = builder.Gender;
this.TagForChildDirectedTreatment = builder.ChildDirectedTreatmentTag;
this.Extras = new Dictionary<string, string>(builder.Extras);
this.MediationExtras = builder.MediationExtras;
}
public List<string> TestDevices { get; private set; }
public HashSet<string> Keywords { get; private set; }
public DateTime? Birthday { get; private set; }
public Gender? Gender { get; private set; }
public bool? TagForChildDirectedTreatment { get; private set; }
public Dictionary<string, string> Extras { get; private set; }
public List<MediationExtras> MediationExtras { get; private set; }
public class Builder
{
public Builder()
{
this.TestDevices = new List<string>();
this.Keywords = new HashSet<string>();
this.Birthday = null;
this.Gender = null;
this.ChildDirectedTreatmentTag = null;
this.Extras = new Dictionary<string, string>();
this.MediationExtras = new List<MediationExtras>();
}
internal List<string> TestDevices { get; private set; }
internal HashSet<string> Keywords { get; private set; }
internal DateTime? Birthday { get; private set; }
internal Gender? Gender { get; private set; }
internal bool? ChildDirectedTreatmentTag { get; private set; }
internal Dictionary<string, string> Extras { get; private set; }
internal List<MediationExtras> MediationExtras { get; private set; }
public Builder AddKeyword(string keyword)
{
this.Keywords.Add(keyword);
return this;
}
public Builder AddTestDevice(string deviceId)
{
this.TestDevices.Add(deviceId);
return this;
}
public AdRequest Build()
{
return new AdRequest(this);
}
public Builder SetBirthday(DateTime birthday)
{
this.Birthday = birthday;
return this;
}
public Builder SetGender(Gender gender)
{
this.Gender = gender;
return this;
}
public Builder AddMediationExtras(MediationExtras extras)
{
this.MediationExtras.Add(extras);
return this;
}
public Builder TagForChildDirectedTreatment(bool tagForChildDirectedTreatment)
{
this.ChildDirectedTreatmentTag = tagForChildDirectedTreatment;
return this;
}
public Builder AddExtra(string key, string value)
{
this.Extras.Add(key, value);
return this;
}
}
}
}
| 32.101563 | 90 | 0.584327 | [
"MIT"
] | AaqeelorShahid/Clone-of-AA-game---Unity | Assets/GoogleMobileAds/Api/AdRequest.cs | 4,109 | C# |
using System.Collections.Generic;
using System.Linq;
using MailCheck.Dmarc.Contracts.SharedDomain;
using MailCheck.DomainStatus.Contracts;
using Message = MailCheck.Dmarc.Contracts.SharedDomain.Message;
namespace MailCheck.Dmarc.Entity.Entity.DomainStatus
{
public interface IDomainStatusEvaluator
{
Status GetStatus(List<Message> messages);
}
public class DomainStatusEvaluator : IDomainStatusEvaluator
{
public Status GetStatus(List<Message> messages)
{
if (messages is null)
{
return Status.Success;
}
IEnumerable<MessageType> statuses = messages.Select(x => x.MessageType).ToList();
Status status = Status.Success;
if (statuses.Any(x => x == MessageType.error))
{
status = Status.Error;
}
else if (statuses.Any(x => x == MessageType.warning))
{
status = Status.Warning;
}
else if (statuses.Any(x => x == MessageType.info))
{
status = Status.Info;
}
return status;
}
}
}
| 26.840909 | 93 | 0.570703 | [
"Apache-2.0"
] | ukncsc/MailCheck.Public.Dmarc | src/MailCheck.Dmarc.Entity/Entity/DomainStatus/DomainStatusEvaluator.cs | 1,183 | C# |
using UppsalaApi.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Security.Claims;
namespace UppsalaApi.Services
{
public interface IUserService
{
Task<PagedResults<UserResource>> GetUsersAsync(
PagingOptions pagingOptions,
SortOptions<UserResource, UserEntity> sortOptions,
SearchOptions<UserResource, UserEntity> searchOptions,
CancellationToken ct);
Task<(bool Succeeded, string Error)> CreateUserAsync(RegisterForm form);
Task<Guid?> GetUserIdAsync(ClaimsPrincipal principal);
Task<UserResource> GetUserByIdAsync(Guid userId, CancellationToken ct);
Task<UserResource> GetUserAsync(ClaimsPrincipal user);
}
}
| 28.964286 | 80 | 0.72873 | [
"MIT"
] | mimustafa/UppsalaApi | UppsalaApi/Services/IUserService.cs | 813 | C# |
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Windows;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle( "Connect4" )]
[assembly: AssemblyDescription( "" )]
[assembly: AssemblyConfiguration( "" )]
[assembly: AssemblyCompany( "" )]
[assembly: AssemblyProduct( "Connect4" )]
[assembly: AssemblyCopyright( "Copyright © 2017" )]
[assembly: AssemblyTrademark( "" )]
[assembly: AssemblyCulture( "" )]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible( false )]
//In order to begin building localizable applications, set
//<UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file
//inside a <PropertyGroup>. For example, if you are using US english
//in your source files, set the <UICulture> to en-US. Then uncomment
//the NeutralResourceLanguage attribute below. Update the "en-US" in
//the line below to match the UICulture setting in the project file.
//[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)]
[assembly: ThemeInfo(
ResourceDictionaryLocation.None , //where theme specific resource dictionaries are located
//(used if a resource is not found in the page,
// or application resource dictionaries)
ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located
//(used if a resource is not found in the page,
// app, or any theme specific resource dictionaries)
)]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion( "1.0.0.0" )]
[assembly: AssemblyFileVersion( "1.0.0.0" )]
| 41.392857 | 94 | 0.722606 | [
"Apache-2.0"
] | PValgento/Connect-4 | Connect4/Connect4/Properties/AssemblyInfo.cs | 2,321 | C# |
namespace TaskManager.Migrations
{
using System;
using System.Collections.Generic;
using System.Data.Entity.Infrastructure.Annotations;
using System.Data.Entity.Migrations;
public partial class InitialMigrations : DbMigration
{
public override void Up()
{
CreateTable(
"dbo.AbpAuditLogs",
c => new
{
Id = c.Long(nullable: false, identity: true),
TenantId = c.Int(),
UserId = c.Long(),
ServiceName = c.String(maxLength: 256),
MethodName = c.String(maxLength: 256),
Parameters = c.String(maxLength: 1024),
ExecutionTime = c.DateTime(nullable: false),
ExecutionDuration = c.Int(nullable: false),
ClientIpAddress = c.String(maxLength: 64),
ClientName = c.String(maxLength: 128),
BrowserInfo = c.String(maxLength: 512),
Exception = c.String(maxLength: 2000),
ImpersonatorUserId = c.Long(),
ImpersonatorTenantId = c.Int(),
CustomData = c.String(maxLength: 2000),
},
annotations: new Dictionary<string, object>
{
{ "DynamicFilter_AuditLog_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
})
.PrimaryKey(t => t.Id);
CreateTable(
"dbo.AbpBackgroundJobs",
c => new
{
Id = c.Long(nullable: false, identity: true),
JobType = c.String(nullable: false, maxLength: 512),
JobArgs = c.String(nullable: false),
TryCount = c.Short(nullable: false),
NextTryTime = c.DateTime(nullable: false),
LastTryTime = c.DateTime(),
IsAbandoned = c.Boolean(nullable: false),
Priority = c.Byte(nullable: false),
CreationTime = c.DateTime(nullable: false),
CreatorUserId = c.Long(),
})
.PrimaryKey(t => t.Id)
.Index(t => new { t.IsAbandoned, t.NextTryTime });
CreateTable(
"dbo.AbpFeatures",
c => new
{
Id = c.Long(nullable: false, identity: true),
TenantId = c.Int(),
Name = c.String(nullable: false, maxLength: 128),
Value = c.String(nullable: false, maxLength: 2000),
CreationTime = c.DateTime(nullable: false),
CreatorUserId = c.Long(),
EditionId = c.Int(),
Discriminator = c.String(nullable: false, maxLength: 128),
},
annotations: new Dictionary<string, object>
{
{ "DynamicFilter_EditionFeatureSetting_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
{ "DynamicFilter_FeatureSetting_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
{ "DynamicFilter_TenantFeatureSetting_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.AbpEditions", t => t.EditionId, cascadeDelete: true)
.Index(t => t.EditionId);
CreateTable(
"dbo.AbpEditions",
c => new
{
Id = c.Int(nullable: false, identity: true),
Name = c.String(nullable: false, maxLength: 32),
DisplayName = c.String(nullable: false, maxLength: 64),
IsDeleted = c.Boolean(nullable: false),
DeleterUserId = c.Long(),
DeletionTime = c.DateTime(),
LastModificationTime = c.DateTime(),
LastModifierUserId = c.Long(),
CreationTime = c.DateTime(nullable: false),
CreatorUserId = c.Long(),
},
annotations: new Dictionary<string, object>
{
{ "DynamicFilter_Edition_SoftDelete", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
})
.PrimaryKey(t => t.Id);
CreateTable(
"dbo.AbpLanguages",
c => new
{
Id = c.Int(nullable: false, identity: true),
TenantId = c.Int(),
Name = c.String(nullable: false, maxLength: 10),
DisplayName = c.String(nullable: false, maxLength: 64),
Icon = c.String(maxLength: 128),
IsDisabled = c.Boolean(nullable: false),
IsDeleted = c.Boolean(nullable: false),
DeleterUserId = c.Long(),
DeletionTime = c.DateTime(),
LastModificationTime = c.DateTime(),
LastModifierUserId = c.Long(),
CreationTime = c.DateTime(nullable: false),
CreatorUserId = c.Long(),
},
annotations: new Dictionary<string, object>
{
{ "DynamicFilter_ApplicationLanguage_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
{ "DynamicFilter_ApplicationLanguage_SoftDelete", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
})
.PrimaryKey(t => t.Id);
CreateTable(
"dbo.AbpLanguageTexts",
c => new
{
Id = c.Long(nullable: false, identity: true),
TenantId = c.Int(),
LanguageName = c.String(nullable: false, maxLength: 10),
Source = c.String(nullable: false, maxLength: 128),
Key = c.String(nullable: false, maxLength: 256),
Value = c.String(nullable: false),
LastModificationTime = c.DateTime(),
LastModifierUserId = c.Long(),
CreationTime = c.DateTime(nullable: false),
CreatorUserId = c.Long(),
},
annotations: new Dictionary<string, object>
{
{ "DynamicFilter_ApplicationLanguageText_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
})
.PrimaryKey(t => t.Id);
CreateTable(
"dbo.AbpNotifications",
c => new
{
Id = c.Guid(nullable: false),
NotificationName = c.String(nullable: false, maxLength: 96),
Data = c.String(),
DataTypeName = c.String(maxLength: 512),
EntityTypeName = c.String(maxLength: 250),
EntityTypeAssemblyQualifiedName = c.String(maxLength: 512),
EntityId = c.String(maxLength: 96),
Severity = c.Byte(nullable: false),
UserIds = c.String(),
ExcludedUserIds = c.String(),
TenantIds = c.String(),
CreationTime = c.DateTime(nullable: false),
CreatorUserId = c.Long(),
})
.PrimaryKey(t => t.Id);
CreateTable(
"dbo.AbpNotificationSubscriptions",
c => new
{
Id = c.Guid(nullable: false),
TenantId = c.Int(),
UserId = c.Long(nullable: false),
NotificationName = c.String(maxLength: 96),
EntityTypeName = c.String(maxLength: 250),
EntityTypeAssemblyQualifiedName = c.String(maxLength: 512),
EntityId = c.String(maxLength: 96),
CreationTime = c.DateTime(nullable: false),
CreatorUserId = c.Long(),
},
annotations: new Dictionary<string, object>
{
{ "DynamicFilter_NotificationSubscriptionInfo_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
})
.PrimaryKey(t => t.Id)
.Index(t => new { t.NotificationName, t.EntityTypeName, t.EntityId, t.UserId });
CreateTable(
"dbo.AbpOrganizationUnits",
c => new
{
Id = c.Long(nullable: false, identity: true),
TenantId = c.Int(),
ParentId = c.Long(),
Code = c.String(nullable: false, maxLength: 95),
DisplayName = c.String(nullable: false, maxLength: 128),
IsDeleted = c.Boolean(nullable: false),
DeleterUserId = c.Long(),
DeletionTime = c.DateTime(),
LastModificationTime = c.DateTime(),
LastModifierUserId = c.Long(),
CreationTime = c.DateTime(nullable: false),
CreatorUserId = c.Long(),
},
annotations: new Dictionary<string, object>
{
{ "DynamicFilter_OrganizationUnit_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
{ "DynamicFilter_OrganizationUnit_SoftDelete", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.AbpOrganizationUnits", t => t.ParentId)
.Index(t => t.ParentId);
CreateTable(
"dbo.AbpPermissions",
c => new
{
Id = c.Long(nullable: false, identity: true),
TenantId = c.Int(),
Name = c.String(nullable: false, maxLength: 128),
IsGranted = c.Boolean(nullable: false),
CreationTime = c.DateTime(nullable: false),
CreatorUserId = c.Long(),
RoleId = c.Int(),
UserId = c.Long(),
Discriminator = c.String(nullable: false, maxLength: 128),
},
annotations: new Dictionary<string, object>
{
{ "DynamicFilter_PermissionSetting_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
{ "DynamicFilter_RolePermissionSetting_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
{ "DynamicFilter_UserPermissionSetting_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.AbpUsers", t => t.UserId, cascadeDelete: true)
.ForeignKey("dbo.AbpRoles", t => t.RoleId, cascadeDelete: true)
.Index(t => t.RoleId)
.Index(t => t.UserId);
CreateTable(
"dbo.AbpRoles",
c => new
{
Id = c.Int(nullable: false, identity: true),
Description = c.String(),
TenantId = c.Int(),
Name = c.String(nullable: false, maxLength: 32),
DisplayName = c.String(nullable: false, maxLength: 64),
IsStatic = c.Boolean(nullable: false),
IsDefault = c.Boolean(nullable: false),
IsDeleted = c.Boolean(nullable: false),
DeleterUserId = c.Long(),
DeletionTime = c.DateTime(),
LastModificationTime = c.DateTime(),
LastModifierUserId = c.Long(),
CreationTime = c.DateTime(nullable: false),
CreatorUserId = c.Long(),
},
annotations: new Dictionary<string, object>
{
{ "DynamicFilter_Role_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
{ "DynamicFilter_Role_SoftDelete", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.AbpUsers", t => t.CreatorUserId)
.ForeignKey("dbo.AbpUsers", t => t.DeleterUserId)
.ForeignKey("dbo.AbpUsers", t => t.LastModifierUserId)
.Index(t => t.DeleterUserId)
.Index(t => t.LastModifierUserId)
.Index(t => t.CreatorUserId);
CreateTable(
"dbo.AbpUsers",
c => new
{
Id = c.Long(nullable: false, identity: true),
AuthenticationSource = c.String(maxLength: 64),
UserName = c.String(nullable: false, maxLength: 256),
TenantId = c.Int(),
EmailAddress = c.String(nullable: false, maxLength: 256),
Name = c.String(nullable: false, maxLength: 32),
Surname = c.String(nullable: false, maxLength: 32),
Password = c.String(nullable: false, maxLength: 128),
EmailConfirmationCode = c.String(maxLength: 328),
PasswordResetCode = c.String(maxLength: 328),
LockoutEndDateUtc = c.DateTime(),
AccessFailedCount = c.Int(nullable: false),
IsLockoutEnabled = c.Boolean(nullable: false),
PhoneNumber = c.String(maxLength: 32),
IsPhoneNumberConfirmed = c.Boolean(nullable: false),
SecurityStamp = c.String(maxLength: 128),
IsTwoFactorEnabled = c.Boolean(nullable: false),
IsEmailConfirmed = c.Boolean(nullable: false),
IsActive = c.Boolean(nullable: false),
LastLoginTime = c.DateTime(),
IsDeleted = c.Boolean(nullable: false),
DeleterUserId = c.Long(),
DeletionTime = c.DateTime(),
LastModificationTime = c.DateTime(),
LastModifierUserId = c.Long(),
CreationTime = c.DateTime(nullable: false),
CreatorUserId = c.Long(),
},
annotations: new Dictionary<string, object>
{
{ "DynamicFilter_User_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
{ "DynamicFilter_User_SoftDelete", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.AbpUsers", t => t.CreatorUserId)
.ForeignKey("dbo.AbpUsers", t => t.DeleterUserId)
.ForeignKey("dbo.AbpUsers", t => t.LastModifierUserId)
.Index(t => t.DeleterUserId)
.Index(t => t.LastModifierUserId)
.Index(t => t.CreatorUserId);
CreateTable(
"dbo.AbpUserClaims",
c => new
{
Id = c.Long(nullable: false, identity: true),
TenantId = c.Int(),
UserId = c.Long(nullable: false),
ClaimType = c.String(maxLength: 256),
ClaimValue = c.String(),
CreationTime = c.DateTime(nullable: false),
CreatorUserId = c.Long(),
},
annotations: new Dictionary<string, object>
{
{ "DynamicFilter_UserClaim_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.AbpUsers", t => t.UserId, cascadeDelete: true)
.Index(t => t.UserId);
CreateTable(
"dbo.AbpUserLogins",
c => new
{
Id = c.Long(nullable: false, identity: true),
TenantId = c.Int(),
UserId = c.Long(nullable: false),
LoginProvider = c.String(nullable: false, maxLength: 128),
ProviderKey = c.String(nullable: false, maxLength: 256),
},
annotations: new Dictionary<string, object>
{
{ "DynamicFilter_UserLogin_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.AbpUsers", t => t.UserId, cascadeDelete: true)
.Index(t => t.UserId);
CreateTable(
"dbo.AbpUserRoles",
c => new
{
Id = c.Long(nullable: false, identity: true),
TenantId = c.Int(),
UserId = c.Long(nullable: false),
RoleId = c.Int(nullable: false),
CreationTime = c.DateTime(nullable: false),
CreatorUserId = c.Long(),
},
annotations: new Dictionary<string, object>
{
{ "DynamicFilter_UserRole_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.AbpUsers", t => t.UserId, cascadeDelete: true)
.Index(t => t.UserId);
CreateTable(
"dbo.AbpSettings",
c => new
{
Id = c.Long(nullable: false, identity: true),
TenantId = c.Int(),
UserId = c.Long(),
Name = c.String(nullable: false, maxLength: 256),
Value = c.String(maxLength: 2000),
LastModificationTime = c.DateTime(),
LastModifierUserId = c.Long(),
CreationTime = c.DateTime(nullable: false),
CreatorUserId = c.Long(),
},
annotations: new Dictionary<string, object>
{
{ "DynamicFilter_Setting_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.AbpUsers", t => t.UserId)
.Index(t => t.UserId);
CreateTable(
"dbo.AbpTenantNotifications",
c => new
{
Id = c.Guid(nullable: false),
TenantId = c.Int(),
NotificationName = c.String(nullable: false, maxLength: 96),
Data = c.String(),
DataTypeName = c.String(maxLength: 512),
EntityTypeName = c.String(maxLength: 250),
EntityTypeAssemblyQualifiedName = c.String(maxLength: 512),
EntityId = c.String(maxLength: 96),
Severity = c.Byte(nullable: false),
CreationTime = c.DateTime(nullable: false),
CreatorUserId = c.Long(),
},
annotations: new Dictionary<string, object>
{
{ "DynamicFilter_TenantNotificationInfo_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
})
.PrimaryKey(t => t.Id);
CreateTable(
"dbo.AbpTenants",
c => new
{
Id = c.Int(nullable: false, identity: true),
EditionId = c.Int(),
TenancyName = c.String(nullable: false, maxLength: 64),
Name = c.String(nullable: false, maxLength: 128),
ConnectionString = c.String(maxLength: 1024),
IsActive = c.Boolean(nullable: false),
IsDeleted = c.Boolean(nullable: false),
DeleterUserId = c.Long(),
DeletionTime = c.DateTime(),
LastModificationTime = c.DateTime(),
LastModifierUserId = c.Long(),
CreationTime = c.DateTime(nullable: false),
CreatorUserId = c.Long(),
},
annotations: new Dictionary<string, object>
{
{ "DynamicFilter_Tenant_SoftDelete", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.AbpUsers", t => t.CreatorUserId)
.ForeignKey("dbo.AbpUsers", t => t.DeleterUserId)
.ForeignKey("dbo.AbpEditions", t => t.EditionId)
.ForeignKey("dbo.AbpUsers", t => t.LastModifierUserId)
.Index(t => t.EditionId)
.Index(t => t.DeleterUserId)
.Index(t => t.LastModifierUserId)
.Index(t => t.CreatorUserId);
CreateTable(
"dbo.AbpUserAccounts",
c => new
{
Id = c.Long(nullable: false, identity: true),
TenantId = c.Int(),
UserId = c.Long(nullable: false),
UserLinkId = c.Long(),
UserName = c.String(maxLength: 256),
EmailAddress = c.String(maxLength: 256),
LastLoginTime = c.DateTime(),
IsDeleted = c.Boolean(nullable: false),
DeleterUserId = c.Long(),
DeletionTime = c.DateTime(),
LastModificationTime = c.DateTime(),
LastModifierUserId = c.Long(),
CreationTime = c.DateTime(nullable: false),
CreatorUserId = c.Long(),
},
annotations: new Dictionary<string, object>
{
{ "DynamicFilter_UserAccount_SoftDelete", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
})
.PrimaryKey(t => t.Id);
CreateTable(
"dbo.AbpUserLoginAttempts",
c => new
{
Id = c.Long(nullable: false, identity: true),
TenantId = c.Int(),
TenancyName = c.String(maxLength: 64),
UserId = c.Long(),
UserNameOrEmailAddress = c.String(maxLength: 255),
ClientIpAddress = c.String(maxLength: 64),
ClientName = c.String(maxLength: 128),
BrowserInfo = c.String(maxLength: 512),
Result = c.Byte(nullable: false),
CreationTime = c.DateTime(nullable: false),
},
annotations: new Dictionary<string, object>
{
{ "DynamicFilter_UserLoginAttempt_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
})
.PrimaryKey(t => t.Id)
.Index(t => new { t.UserId, t.TenantId })
.Index(t => new { t.TenancyName, t.UserNameOrEmailAddress, t.Result });
CreateTable(
"dbo.AbpUserNotifications",
c => new
{
Id = c.Guid(nullable: false),
TenantId = c.Int(),
UserId = c.Long(nullable: false),
TenantNotificationId = c.Guid(nullable: false),
State = c.Int(nullable: false),
CreationTime = c.DateTime(nullable: false),
},
annotations: new Dictionary<string, object>
{
{ "DynamicFilter_UserNotificationInfo_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
})
.PrimaryKey(t => t.Id)
.Index(t => new { t.UserId, t.State, t.CreationTime });
CreateTable(
"dbo.AbpUserOrganizationUnits",
c => new
{
Id = c.Long(nullable: false, identity: true),
TenantId = c.Int(),
UserId = c.Long(nullable: false),
OrganizationUnitId = c.Long(nullable: false),
IsDeleted = c.Boolean(nullable: false),
CreationTime = c.DateTime(nullable: false),
CreatorUserId = c.Long(),
},
annotations: new Dictionary<string, object>
{
{ "DynamicFilter_UserOrganizationUnit_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
{ "DynamicFilter_UserOrganizationUnit_SoftDelete", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
})
.PrimaryKey(t => t.Id);
}
public override void Down()
{
DropForeignKey("dbo.AbpTenants", "LastModifierUserId", "dbo.AbpUsers");
DropForeignKey("dbo.AbpTenants", "EditionId", "dbo.AbpEditions");
DropForeignKey("dbo.AbpTenants", "DeleterUserId", "dbo.AbpUsers");
DropForeignKey("dbo.AbpTenants", "CreatorUserId", "dbo.AbpUsers");
DropForeignKey("dbo.AbpPermissions", "RoleId", "dbo.AbpRoles");
DropForeignKey("dbo.AbpRoles", "LastModifierUserId", "dbo.AbpUsers");
DropForeignKey("dbo.AbpRoles", "DeleterUserId", "dbo.AbpUsers");
DropForeignKey("dbo.AbpRoles", "CreatorUserId", "dbo.AbpUsers");
DropForeignKey("dbo.AbpSettings", "UserId", "dbo.AbpUsers");
DropForeignKey("dbo.AbpUserRoles", "UserId", "dbo.AbpUsers");
DropForeignKey("dbo.AbpPermissions", "UserId", "dbo.AbpUsers");
DropForeignKey("dbo.AbpUserLogins", "UserId", "dbo.AbpUsers");
DropForeignKey("dbo.AbpUsers", "LastModifierUserId", "dbo.AbpUsers");
DropForeignKey("dbo.AbpUsers", "DeleterUserId", "dbo.AbpUsers");
DropForeignKey("dbo.AbpUsers", "CreatorUserId", "dbo.AbpUsers");
DropForeignKey("dbo.AbpUserClaims", "UserId", "dbo.AbpUsers");
DropForeignKey("dbo.AbpOrganizationUnits", "ParentId", "dbo.AbpOrganizationUnits");
DropForeignKey("dbo.AbpFeatures", "EditionId", "dbo.AbpEditions");
DropIndex("dbo.AbpUserNotifications", new[] { "UserId", "State", "CreationTime" });
DropIndex("dbo.AbpUserLoginAttempts", new[] { "TenancyName", "UserNameOrEmailAddress", "Result" });
DropIndex("dbo.AbpUserLoginAttempts", new[] { "UserId", "TenantId" });
DropIndex("dbo.AbpTenants", new[] { "CreatorUserId" });
DropIndex("dbo.AbpTenants", new[] { "LastModifierUserId" });
DropIndex("dbo.AbpTenants", new[] { "DeleterUserId" });
DropIndex("dbo.AbpTenants", new[] { "EditionId" });
DropIndex("dbo.AbpSettings", new[] { "UserId" });
DropIndex("dbo.AbpUserRoles", new[] { "UserId" });
DropIndex("dbo.AbpUserLogins", new[] { "UserId" });
DropIndex("dbo.AbpUserClaims", new[] { "UserId" });
DropIndex("dbo.AbpUsers", new[] { "CreatorUserId" });
DropIndex("dbo.AbpUsers", new[] { "LastModifierUserId" });
DropIndex("dbo.AbpUsers", new[] { "DeleterUserId" });
DropIndex("dbo.AbpRoles", new[] { "CreatorUserId" });
DropIndex("dbo.AbpRoles", new[] { "LastModifierUserId" });
DropIndex("dbo.AbpRoles", new[] { "DeleterUserId" });
DropIndex("dbo.AbpPermissions", new[] { "UserId" });
DropIndex("dbo.AbpPermissions", new[] { "RoleId" });
DropIndex("dbo.AbpOrganizationUnits", new[] { "ParentId" });
DropIndex("dbo.AbpNotificationSubscriptions", new[] { "NotificationName", "EntityTypeName", "EntityId", "UserId" });
DropIndex("dbo.AbpFeatures", new[] { "EditionId" });
DropIndex("dbo.AbpBackgroundJobs", new[] { "IsAbandoned", "NextTryTime" });
DropTable("dbo.AbpUserOrganizationUnits",
removedAnnotations: new Dictionary<string, object>
{
{ "DynamicFilter_UserOrganizationUnit_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
{ "DynamicFilter_UserOrganizationUnit_SoftDelete", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
});
DropTable("dbo.AbpUserNotifications",
removedAnnotations: new Dictionary<string, object>
{
{ "DynamicFilter_UserNotificationInfo_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
});
DropTable("dbo.AbpUserLoginAttempts",
removedAnnotations: new Dictionary<string, object>
{
{ "DynamicFilter_UserLoginAttempt_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
});
DropTable("dbo.AbpUserAccounts",
removedAnnotations: new Dictionary<string, object>
{
{ "DynamicFilter_UserAccount_SoftDelete", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
});
DropTable("dbo.AbpTenants",
removedAnnotations: new Dictionary<string, object>
{
{ "DynamicFilter_Tenant_SoftDelete", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
});
DropTable("dbo.AbpTenantNotifications",
removedAnnotations: new Dictionary<string, object>
{
{ "DynamicFilter_TenantNotificationInfo_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
});
DropTable("dbo.AbpSettings",
removedAnnotations: new Dictionary<string, object>
{
{ "DynamicFilter_Setting_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
});
DropTable("dbo.AbpUserRoles",
removedAnnotations: new Dictionary<string, object>
{
{ "DynamicFilter_UserRole_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
});
DropTable("dbo.AbpUserLogins",
removedAnnotations: new Dictionary<string, object>
{
{ "DynamicFilter_UserLogin_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
});
DropTable("dbo.AbpUserClaims",
removedAnnotations: new Dictionary<string, object>
{
{ "DynamicFilter_UserClaim_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
});
DropTable("dbo.AbpUsers",
removedAnnotations: new Dictionary<string, object>
{
{ "DynamicFilter_User_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
{ "DynamicFilter_User_SoftDelete", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
});
DropTable("dbo.AbpRoles",
removedAnnotations: new Dictionary<string, object>
{
{ "DynamicFilter_Role_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
{ "DynamicFilter_Role_SoftDelete", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
});
DropTable("dbo.AbpPermissions",
removedAnnotations: new Dictionary<string, object>
{
{ "DynamicFilter_PermissionSetting_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
{ "DynamicFilter_RolePermissionSetting_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
{ "DynamicFilter_UserPermissionSetting_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
});
DropTable("dbo.AbpOrganizationUnits",
removedAnnotations: new Dictionary<string, object>
{
{ "DynamicFilter_OrganizationUnit_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
{ "DynamicFilter_OrganizationUnit_SoftDelete", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
});
DropTable("dbo.AbpNotificationSubscriptions",
removedAnnotations: new Dictionary<string, object>
{
{ "DynamicFilter_NotificationSubscriptionInfo_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
});
DropTable("dbo.AbpNotifications");
DropTable("dbo.AbpLanguageTexts",
removedAnnotations: new Dictionary<string, object>
{
{ "DynamicFilter_ApplicationLanguageText_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
});
DropTable("dbo.AbpLanguages",
removedAnnotations: new Dictionary<string, object>
{
{ "DynamicFilter_ApplicationLanguage_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
{ "DynamicFilter_ApplicationLanguage_SoftDelete", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
});
DropTable("dbo.AbpEditions",
removedAnnotations: new Dictionary<string, object>
{
{ "DynamicFilter_Edition_SoftDelete", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
});
DropTable("dbo.AbpFeatures",
removedAnnotations: new Dictionary<string, object>
{
{ "DynamicFilter_EditionFeatureSetting_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
{ "DynamicFilter_FeatureSetting_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
{ "DynamicFilter_TenantFeatureSetting_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
});
DropTable("dbo.AbpBackgroundJobs");
DropTable("dbo.AbpAuditLogs",
removedAnnotations: new Dictionary<string, object>
{
{ "DynamicFilter_AuditLog_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
});
}
}
}
| 53.529582 | 141 | 0.499137 | [
"MIT"
] | lucaslsilva/vanhackaton | src/TaskManager.EntityFramework/Migrations/201809270654064_InitialMigrations.cs | 37,096 | C# |
using HarmonyLib;
using System.Reflection;
namespace SpaceMonke.HarmonyPatches
{
/// <summary>
/// Apply and remove all of our Harmony patches through this class
/// </summary>
public class SpaceMonkePatches
{
private static Harmony instance;
public static bool IsPatched { get; private set; }
public const string InstanceId = "com.legoandmars.gorillatag.spacemonke";
internal static void ApplyHarmonyPatches()
{
if (!IsPatched)
{
if (instance == null)
{
instance = new Harmony(InstanceId);
}
instance.PatchAll(Assembly.GetExecutingAssembly());
IsPatched = true;
}
}
internal static void RemoveHarmonyPatches()
{
if (instance != null && IsPatched)
{
instance.UnpatchSelf();
IsPatched = false;
}
}
}
} | 25.794872 | 81 | 0.527833 | [
"MIT"
] | Graicc/SpaceMonke | SpaceMonke/HarmonyPatches/SpaceMonkePatches.cs | 1,008 | C# |
using System;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using NosCore.Packets;
using NosCore.Packets.Enumerations;
using NosCore.Packets.ServerPackets.Login;
using NosCore.ReverseProxy.Configuration;
using NosCore.ReverseProxy.I18N;
using NosCore.ReverseProxy.TcpClient;
using NosCore.ReverseProxy.TcpClientFactory;
using NosCore.Shared.Enumerations;
namespace NosCore.ReverseProxy.TcpProxy
{
public class TcpProxy : IProxy
{
private readonly ILogger _logger;
private readonly ReverseProxyConfiguration _configuration;
private readonly byte[] _packet;
private readonly ITcpClientFactory _tcpClientFactory;
public TcpProxy(ILogger<TcpProxy> logger, ReverseProxyConfiguration configuration, ITcpClientFactory tcpClientFactory)
{
_logger = logger;
_configuration = configuration;
_tcpClientFactory = tcpClientFactory;
var serializer = new Serializer(new[] { typeof(FailcPacket) });
var packetString = serializer.Serialize(new FailcPacket
{
Type = LoginFailType.Maintenance
});
_packet = Encoding.Default.GetBytes($"{packetString} ");
for (var i = 0; i < packetString.Length; i++)
{
_packet[i] = Convert.ToByte(_packet[i] + 15);
}
_packet[^1] = 25;
}
internal async Task HandleClientAsync(CancellationToken stoppingToken, System.Net.Sockets.TcpClient remoteClient, ChannelConfiguration channelConfiguration)
{
_logger.LogTrace(LogLanguage.Instance.GetMessageFromKey(LogLanguageKey.PACKET_RECEIVED), remoteClient.Client.RemoteEndPoint);
var ip = (await Dns.GetHostAddressesAsync(channelConfiguration.RemoteHost ?? string.Empty)).First();
remoteClient.NoDelay = true;
remoteClient.ReceiveTimeout = _configuration.Timeout;
using var client = _tcpClientFactory.CreateTcpClient();
try
{
await client.ConnectAsync(ip, channelConfiguration.RemotePort);
var serverStream = client.GetStream();
var remoteStream = remoteClient.GetStream();
await Task.WhenAny(remoteStream.CopyToAsync(serverStream, stoppingToken), serverStream.CopyToAsync(remoteStream, stoppingToken));
_logger.LogDebug(LogLanguage.Instance.GetMessageFromKey(LogLanguageKey.DISCONNECTED), remoteClient.Client.RemoteEndPoint);
remoteStream.Close();
serverStream.Close();
client.Close();
remoteClient.Client.Close();
}
catch(Exception ex)
{
if (channelConfiguration.ServerType == ServerType.LoginServer)
{
await remoteClient.Client.SendAsync(_packet, SocketFlags.None);
await Task.Delay(1000, stoppingToken);//this prevent sending close too fast
_logger.LogWarning(LogLanguage.Instance.GetMessageFromKey(LogLanguageKey.MAINTENANCE_PACKET_SENT), remoteClient.Client.RemoteEndPoint, ex);
}
}
}
private async Task StartChannelAsync(CancellationToken stoppingToken, ChannelConfiguration channelConfiguration)
{
var server = new TcpListener(IPAddress.Any, channelConfiguration.LocalPort);
server.Start();
_logger.LogInformation(LogLanguage.Instance.GetMessageFromKey(LogLanguageKey.PROXY_STARTED), channelConfiguration.LocalPort, $"{channelConfiguration.RemoteHost}:{channelConfiguration.RemotePort}");
while (!stoppingToken.IsCancellationRequested)
{
try
{
var remoteClient = await server.AcceptTcpClientAsync();
_ = HandleClientAsync(stoppingToken, remoteClient, channelConfiguration);
}
catch (Exception ex)
{
_logger.LogError(LogLanguage.Instance.GetMessageFromKey(LogLanguageKey.ERROR), ex);
}
}
}
public Task Start(CancellationToken stoppingToken)
{
return Task.WhenAll(_configuration.Channels!.Select(s => StartChannelAsync(stoppingToken, s)));
}
}
}
| 43.115385 | 209 | 0.65165 | [
"MIT"
] | NosCoreIO/NosCore.ReverseProxy | src/NosCore.ReverseProxy/TcpProxy/TcpProxy.cs | 4,486 | C# |
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
// **NOTE** This file was generated by a tool and any changes will be overwritten.
// <auto-generated/>
// Template Source: EntityRequestBuilder.cs.tt
namespace Microsoft.Graph2.CallRecords
{
using System;
using System.Collections.Generic;
using System.IO;
/// <summary>
/// The type OptionRequestBuilder.
/// </summary>
public partial class OptionRequestBuilder : Microsoft.Graph.EntityRequestBuilder, IOptionRequestBuilder
{
/// <summary>
/// Constructs a new OptionRequestBuilder.
/// </summary>
/// <param name="requestUrl">The URL for the built request.</param>
/// <param name="client">The <see cref="Microsoft.Graph.IBaseClient"/> for handling requests.</param>
public OptionRequestBuilder(
string requestUrl,
Microsoft.Graph.IBaseClient client)
: base(requestUrl, client)
{
}
/// <summary>
/// Builds the request.
/// </summary>
/// <returns>The built request.</returns>
public new IOptionRequest Request()
{
return this.Request(null);
}
/// <summary>
/// Builds the request.
/// </summary>
/// <param name="options">The query and header options for the request.</param>
/// <returns>The built request.</returns>
public new IOptionRequest Request(IEnumerable<Microsoft.Graph.Option> options)
{
return new OptionRequest(this.RequestUrl, this.Client, options);
}
}
}
| 34.236364 | 153 | 0.565587 | [
"MIT"
] | Dakoni4400/MSGraph-SDK-Code-Generator | test/Typewriter.Test/TestDataCSharp/com/microsoft/graph2/callrecords/requests/OptionRequestBuilder.cs | 1,883 | C# |
using System.ComponentModel.DataAnnotations;
namespace MyDiet.Models.Dtos
{
public class ProductCategoryDto
{
public int Id { get; set; }
[Required]
[MinLength(5)]
public string Description { get; set; }
}
}
| 18.214286 | 47 | 0.619608 | [
"MIT"
] | FrancescoRepo/MyDiet | MyDiet/Models/Dtos/ProductCategoryDto.cs | 257 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.ComponentModel.Composition;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Editor;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.CodeAnalysis.Editor.Xaml;
using Microsoft.CodeAnalysis.Experiments;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.LanguageServer;
using Microsoft.CodeAnalysis.Shared.TestHooks;
using Microsoft.VisualStudio.LanguageServer.Client;
using Microsoft.VisualStudio.LanguageServer.Protocol;
using Microsoft.VisualStudio.LanguageServices.Implementation.LanguageClient;
using Microsoft.VisualStudio.LanguageServices.Xaml.LanguageServer;
using Microsoft.VisualStudio.Shell.Interop;
using Microsoft.VisualStudio.Utilities;
using VSShell = Microsoft.VisualStudio.Shell;
namespace Microsoft.VisualStudio.LanguageServices.Xaml
{
/// <summary>
/// XAML Language Server Client for LiveShare and Codespaces. Unused when
/// <see cref="StringConstants.EnableLspIntelliSense"/> experiment is turned on.
/// Remove this when we are ready to use LSP everywhere
/// </summary>
[DisableUserExperience(true)]
[ContentType(ContentTypeNames.XamlContentType)]
[Export(typeof(ILanguageClient))]
internal class XamlInProcLanguageClientDisableUX : AbstractInProcLanguageClient
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, true)]
public XamlInProcLanguageClientDisableUX(
XamlRequestDispatcherFactory xamlDispatcherFactory,
VisualStudioWorkspace workspace,
IDiagnosticService diagnosticService,
IAsynchronousOperationListenerProvider listenerProvider,
ILspWorkspaceRegistrationService lspWorkspaceRegistrationService,
[Import(typeof(SAsyncServiceProvider))]
VSShell.IAsyncServiceProvider asyncServiceProvider,
IThreadingContext threadingContext
)
: base(
xamlDispatcherFactory,
workspace,
diagnosticService,
listenerProvider,
lspWorkspaceRegistrationService,
asyncServiceProvider,
threadingContext,
diagnosticsClientName: null
) { }
/// <summary>
/// Gets the name of the language client (displayed in yellow bars).
/// </summary>
public override string Name => "XAML Language Server Client for LiveShare and Codespaces";
protected internal override VSServerCapabilities GetCapabilities()
{
var experimentationService =
Workspace.Services.GetRequiredService<IExperimentationService>();
var isLspExperimentEnabled = experimentationService.IsExperimentEnabled(
StringConstants.EnableLspIntelliSense
);
var capabilities = isLspExperimentEnabled
? XamlCapabilities.None
: XamlCapabilities.Current;
// Only turn on CodeAction support for client scenarios. Hosts will get non-LSP lightbulbs automatically.
capabilities.CodeActionProvider = new CodeActionOptions
{
CodeActionKinds = new[] { CodeActionKind.QuickFix, CodeActionKind.Refactor }
};
capabilities.CodeActionsResolveProvider = true;
return capabilities;
}
}
}
| 42.290698 | 117 | 0.708001 | [
"MIT"
] | belav/roslyn | src/VisualStudio/Xaml/Impl/Implementation/LanguageClient/XamlInProcLanguageClientDisableUX.cs | 3,639 | C# |
using System;
using System.Linq.Expressions;
using System.Threading;
using System.Threading.Tasks;
namespace LinqToDB.Linq
{
using SqlQuery;
using Mapping;
using Common.Internal.Cache;
static partial class QueryRunner
{
public static class Insert<T>
{
static Query<int> CreateQuery(IDataContext dataContext, EntityDescriptor descriptor, T obj,string tableName, string databaseName, string schemaName, Type type)
{
var sqlTable = new SqlTable(dataContext.MappingSchema, type);
if (tableName != null) sqlTable.PhysicalName = tableName;
if (databaseName != null) sqlTable.Database = databaseName;
if (schemaName != null) sqlTable.Schema = schemaName;
var insertStatement = new SqlInsertStatement { Insert = { Into = sqlTable } };
var ei = new Query<int>(dataContext, null)
{
Queries = { new QueryInfo { Statement = insertStatement } }
};
foreach (var field in sqlTable.Fields)
{
if (field.Value.IsInsertable && !field.Value.ColumnDescriptor.ShouldSkip(obj, descriptor, SkipModification.Insert))
{
var param = GetParameter(type, dataContext, field.Value);
ei.Queries[0].Parameters.Add(param);
insertStatement.Insert.Items.Add(new SqlSetExpression(field.Value, param.SqlParameter));
}
else if (field.Value.IsIdentity)
{
var sqlb = dataContext.CreateSqlProvider();
var expr = sqlb.GetIdentityExpression(sqlTable);
if (expr != null)
insertStatement.Insert.Items.Add(new SqlSetExpression(field.Value, expr));
}
}
SetNonQueryQuery(ei);
return ei;
}
public static int Query(IDataContext dataContext, T obj, string tableName, string databaseName, string schemaName)
{
if (Equals(default(T), obj))
return 0;
var type = GetType<T>(obj, dataContext);
var entityDescriptor = dataContext.MappingSchema.GetEntityDescriptor(type);
var ei = Common.Configuration.Linq.DisableQueryCache || entityDescriptor.SkipModificationFlags.HasFlag(SkipModification.Insert)
? CreateQuery(dataContext, entityDescriptor, obj, tableName, databaseName, schemaName, type)
: Cache<T>.QueryCache.GetOrCreate(
new { Operation = 'I', dataContext.MappingSchema.ConfigurationID, dataContext.ContextID, tableName, databaseName, schemaName, type },
o =>
{
o.SlidingExpiration = Common.Configuration.Linq.CacheSlidingExpiration;
return CreateQuery(dataContext, entityDescriptor, obj, tableName, databaseName, schemaName, type);
});
return (int)ei.GetElement(dataContext, Expression.Constant(obj), null);
}
public static async Task<int> QueryAsync(
IDataContext dataContext, T obj, string tableName, string databaseName, string schemaName, CancellationToken token)
{
if (Equals(default(T), obj))
return 0;
var type = GetType<T>(obj, dataContext);
var entityDescriptor = dataContext.MappingSchema.GetEntityDescriptor(type);
var ei = Common.Configuration.Linq.DisableQueryCache || entityDescriptor.SkipModificationFlags.HasFlag(SkipModification.Insert)
? CreateQuery(dataContext, entityDescriptor, obj, tableName, databaseName, schemaName, type)
: Cache<T>.QueryCache.GetOrCreate(
new { Operation = 'I', dataContext.MappingSchema.ConfigurationID, dataContext.ContextID, tableName, databaseName, schemaName, type },
o =>
{
o.SlidingExpiration = Common.Configuration.Linq.CacheSlidingExpiration;
return CreateQuery(dataContext, entityDescriptor, obj, tableName, databaseName, schemaName, type);
});
var result = await ei.GetElementAsync(dataContext, Expression.Constant(obj), null, token).ConfigureAwait(Common.Configuration.ContinueOnCapturedContext);
return (int)result;
}
}
}
}
| 39.36 | 163 | 0.693598 | [
"MIT"
] | FrancisChung/linq2db | Source/LinqToDB/Linq/QueryRunner.Insert.cs | 3,839 | C# |
using System;
using System.Threading;
using System.Collections.Generic;
namespace c_sharp
{
class Program
{
static void Main(string[] args)
{
Random aleatorio = new Random();
int teste;
List<string> listaAnimais = new List<string>(){"ABELHA", "AGUIA", "ARANHA", "ATUM", "AVESTRUZ", "BALEIA", "BORBOLETA", "BURRO", "CABRA", "CACHORRO", "CAMELO", "CAVALO", "COELHO", "CORVO"};
List<string> listaNome = new List<string>(){"ALANAH", "SAYURI", "DANIA", "TANIA", "MANUEL", "VANISIA", "ADRIANO", "EDNEY", "SIDNEY", "BRANDAO"};
List<string> listaSeries = new List<string>(){"Redney", "Manuel"};
cabecalho("JOGO DA FORCA");
menu("Animais", "Nome");
int op = leiaOp(1, 2);
Thread.Sleep(1000);
Console.Clear();
switch (op)
{
case 1:
teste = aleatorio.Next(0, listaAnimais.Count - 1);
game(listaAnimais[teste], "ANIMAIS");
break;
case 2:
teste = aleatorio.Next(0, listaNome.Count - 1);
game(listaNome[teste], "NOME");
break;
default:
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("Opção Inválida!!!");
Console.ResetColor();
break;
}
cabecalho("FIM DO JOGO");
}
static void linha()
{
Console.WriteLine("------------------------------");
}
static void center(string teste, int num)
{
int total, esquerda, direita;
string test = "";
total = num - teste.Length;
direita = (total / 2) + teste.Length;
esquerda = num - direita;
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine("{0}{1}", teste.PadLeft(direita, ' '), test.PadRight(esquerda-1, ' '));
Console.ResetColor();
}
static void cabecalho(string txt)
{
linha();
center(txt, 30);
linha();
}
static void menu(params string[]lista)
{
Console.WriteLine("Escolhe sua categoria: ");
int c = 1;
Console.ForegroundColor = ConsoleColor.Blue;
foreach (string item in lista)
{
Console.WriteLine($"{c} - {item}");
c++;
}
Console.ResetColor();
linha();
}
static int leiaOp(int inf, int sup)
{
while (true)
{
Console.Write("Sua opção: ");
int op = Convert.ToInt32(Console.ReadLine());
if(op >= inf && op <= sup)
{
return op;
}
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("ERRO!!! Digite uma opção válida.");
Console.ResetColor();
}
}
static void game(string txt, string msg)
{
cabecalho(msg);
List<char> listaTexto = new List<char>();
List<char> listaSublinhada = new List<char>();
string texto = txt;
int cont = 0;
for (int i = 0; i < texto.Length; i++)
{
listaTexto.Add(texto[i]);
listaSublinhada.Add('_');
}
for (int i = 0; i < listaSublinhada.Count; i++)
{
Console.Write($"{listaSublinhada[i]} ");
}
Console.WriteLine();
while (true)
{
int contV = 0;
Console.Write("Digite uma Letra: ");
string teste = (Console.ReadLine()).ToUpper();
if(txt.IndexOf(teste) < 0)
{
cont++;
}
for (int i = 0; i < listaSublinhada.Count; i++)
{
if(listaTexto[i] == teste[0])
{
listaSublinhada[i] = teste[0];
}
}
for (int i = 0; i < listaSublinhada.Count; i++)
{
if(listaTexto[i] == listaSublinhada[i])
{
contV++;
}
}
Thread.Sleep(1000);
Console.Clear();
cabecalho(msg);
for (int i = 0; i < listaSublinhada.Count; i++)
{
Console.Write($"{listaSublinhada[i]} ");
}
Console.WriteLine();
if(contV == listaTexto.Count || cont == 6)
{
break;
}
Thread.Sleep(800);
}
}
}
}
| 34.62069 | 200 | 0.417729 | [
"MIT"
] | RedneyMonteiro15/Quebra_Cabeca_game | c sharp/Program.cs | 5,030 | C# |
using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Commands.AnalysisServices")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Commands.AnalysisServices")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[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("9688e9d1-7c21-41b7-86de-6056fb60a9f8")]
// 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.1.4")]
[assembly: AssemblyFileVersion("1.1.4")]
| 35.410256 | 85 | 0.727009 | [
"MIT"
] | 3quanfeng/azure-powershell | src/AnalysisServices/AnalysisServices/Properties/AssemblyInfo.cs | 1,344 | C# |
#if UNITY_EDITOR
using System;
using System.Collections.Generic;
using System.Linq;
using UnityEditor;
#endif
using UnityEngine;
#if UNITY_EDITOR
// taken from: https://gamedev.stackexchange.com/a/140799
static class CanDestroyExtension {
private static bool Requires(Type obj, Type req) {
return Attribute.IsDefined(obj, typeof(RequireComponent)) &&
Attribute.GetCustomAttributes(obj, typeof(RequireComponent))
.OfType<RequireComponent>()
.Any(rc => rc.m_Type0.IsAssignableFrom(req));
}
/// <summary>
/// Checks whether the stated component can be destroyed without violating dependencies.
/// </summary>
/// <returns>Is component destroyable?</returns>
/// <param name="t">Component candidate for destruction.</param>
internal static bool CanDestroy(this Component t) {
return !t.gameObject.GetComponents<Component>()
.Any(c => Requires(c.GetType(), t.GetType()));
}
}
#endif
[DisallowMultipleComponent]
[ExecuteInEditMode]
public class Folder : MonoBehaviour {
#if UNITY_EDITOR
private static bool addedSelectionResetCallback;
Folder() {
// add reset callback first in queue
if (!addedSelectionResetCallback) {
Selection.selectionChanged += () => Tools.hidden = false;
addedSelectionResetCallback = true;
}
Selection.selectionChanged += HandleSelection;
}
/// <summary>
/// <para>Hides the transform gizmo if necessary to avoid accidental editing of the
/// position.</para>
///
/// <para>(If multiple objects are selected along with a folder, this turns off all of their
/// gizmos.)</para>
/// </summary>
private void HandleSelection() {
if (this != null) {
Tools.hidden |= Selection.activeGameObject == gameObject;
}
}
private bool AskDelete() {
return EditorUtility.DisplayDialog(
title: "Can't add script",
message: "Folders shouldn't be used with other components. Which component should " +
"be kept?",
ok: "Folder",
cancel: "Component"
);
}
/// <summary>
/// Delete all components regardless of dependency hierarchy.
/// </summary>
/// <param name="comps">Which components to delete.</param>
private void DeleteComponents(IEnumerable<Component> comps) {
var destroyable = comps.Where(c => c != null && c.CanDestroy());
// keep cycling through the list of components until all components are gone.
while (destroyable.Any()) {
foreach (var c in destroyable) {
if (c.CanDestroy()) {
DestroyImmediate(c);
}
}
}
}
private void OnGUI() {
// we are running, don't bother the player.
// also, sometimes `this` might be null for whatever reason.
if (Application.isPlaying || this == null) {
return;
}
var existingComponents = GetComponents<Component>()
.Where(c => c != this && !typeof(Transform).IsAssignableFrom(c.GetType()));
// no items means no actions anyways
if (!existingComponents.Any()) return;
if (AskDelete()) {
DeleteComponents(existingComponents);
} else {
DestroyImmediate(this);
}
}
private void OnEnable() {
tag = "EditorOnly";
// Hide inspector to prevent accidental editing of transform.
this.transform.hideFlags = HideFlags.HideInInspector;
}
private void OnDestroy() {
tag = "Untagged";
}
#endif
/// <summary>
/// Resets the transform properties to their identities, i.e. (0, 0, 0), (0˚, 0˚, 0˚), and
/// (100%, 100%, 100%).
/// </summary>
private void Update() {
transform.position = Vector3.zero;
transform.rotation = Quaternion.identity;
transform.localScale = new Vector3(1, 1, 1);
}
/// <summary>
/// Takes direct children and links them to the parent transform or global.
/// </summary>
public void Flatten() {
// gather first-level children
foreach (Transform child in transform.GetComponentsInChildren<Transform>()) {
if (child.parent == transform) {
child.name = name + '/' + child.name;
child.parent = transform.parent;
}
}
Destroy(gameObject);
}
}
| 32.823944 | 98 | 0.579275 | [
"MIT"
] | phobos2077/unity-hierarchy-folders | Runtime/Folder.cs | 4,523 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Study.Utility
{
public class SublistEnumeration
{
public static IEnumerable<List<T>> EnumerateSublists<T>(List<T> list)
{
int n = list.Count;
foreach (List<bool> inOut in EnumerateShortLex(n))
yield return ExtractSublist(list, inOut);
}
public static IEnumerable<List<T>> EnumerateSublists<T>(List<T> list, int size)
{
int n = list.Count;
foreach (List<bool> inOut in EnumerateShortLex(n, size))
yield return ExtractSublist(list, inOut);
}
public static List<T> NextSublist<T>(List<T> list, int size, ref List<bool> state)
{
int n = list.Count;
bool areMore = NextShortLex(n, size, ref state);
List<T> sublist = ExtractSublist(list, state);
if (!areMore)
{
state = null;
}
return sublist;
}
static List<T> ExtractSublist<T>(List<T> list, List<bool> inOut)
{
List<T> sublist = new List<T>();
for (int i = 0; i < inOut.Count; i++)
{
if (inOut[i])
sublist.Add(list[i]);
}
return sublist;
}
static IEnumerable<List<bool>> EnumerateShortLex(int n, int k)
{
k = Math.Max(0, k);
List<bool> list = new List<bool>(n);
for (int i = 0; i < k; i++)
list.Add(true);
for (int i = k; i < n; i++)
list.Add(false);
do
{
yield return list;
}
while (NextSameTrueCount(list, k));
}
public static IEnumerable<List<bool>> EnumerateShortLex(int n)
{
var list = new List<bool>(n);
for (int i = 0; i < n; i++)
list.Add(false);
do
{
yield return list;
}
while (Next(list));
}
static bool NextShortLex(int n, int k, ref List<bool> state)
{
if (state == null)
{
k = Math.Max(0, k);
state = new List<bool>(n);
for (int i = 0; i < k; i++)
state.Add(true);
for (int i = k; i < n; i++)
state.Add(false);
return k > 0 && k < n;
}
return NextSameTrueCount(state, k);
}
static bool Next(List<bool> list)
{
int trueCount = ((IEnumerable<bool>)list).Count(b => b);
if (trueCount == list.Count)
return false;
int firstHole = FindFirstHole(list);
if (firstHole >= list.Count)
{
for (int i = 0; i < trueCount + 1; i++)
list[i] = true;
for (int i = trueCount + 1; i < list.Count; i++)
list[i] = false;
}
else
{
list[firstHole] = true;
int initialTrues = trueCount;
for (int i = firstHole; i < list.Count; i++)
{
if (list[i])
initialTrues--;
}
for (int i = 0; i < initialTrues; i++)
list[i] = true;
for (int i = initialTrues; i < firstHole; i++)
list[i] = false;
}
return true;
}
static bool NextSameTrueCount(List<bool> list, int trueCount)
{
int firstHole = FindFirstHole(list);
if (firstHole >= list.Count)
return false;
list[firstHole] = true;
int initialTrues = trueCount;
for (int i = firstHole; i < list.Count; i++)
{
if (list[i])
initialTrues--;
}
for (int i = 0; i < initialTrues; i++)
list[i] = true;
for (int i = initialTrues; i < firstHole; i++)
list[i] = false;
return true;
}
static int FindFirstHole(List<bool> list)
{
int i = 0;
while (i < list.Count - 1)
{
if (list[i] && !list[i + 1])
break;
i++;
}
return i + 1;
}
}
}
| 26.54023 | 90 | 0.422477 | [
"MIT"
] | landon/InterviewStudy | Study/Utility/SublistEnumeration.cs | 4,620 | C# |
using System.Windows;
using Microsoft.Practices.ServiceLocation;
using Prism.Modularity;
using Prism.Regions;
using Prism.Unity;
using StatTrack.UI.Services;
using StatTrack.UI.ViewModels;
using StatTrack.UI.Views;
using Syncfusion.Windows.Tools.Controls;
namespace StatTrack.UI
{
public class Bootstrapper : UnityBootstrapper
{
protected override DependencyObject CreateShell()
{
return ServiceLocator.Current.GetInstance<ShellView>();
}
protected override void InitializeShell()
{
Application.Current.MainWindow = (Window) Shell;
Application.Current.MainWindow.Show();
}
protected override void ConfigureContainer()
{
RegisterTypeIfMissing(typeof(IGraphManager), typeof(GraphManager), true);
RegisterTypeIfMissing(typeof(INotifier), typeof(Notifier), true);
RegisterTypeIfMissing(typeof(IOptions), typeof(Options), true);
RegisterTypeIfMissing(typeof(IResults), typeof(Results), true);
RegisterTypeIfMissing(typeof(ISettings), typeof(Settings), true);
RegisterTypeIfMissing(typeof(ITrackerService), typeof(TrackerService), true);
base.ConfigureContainer();
}
protected override RegionAdapterMappings ConfigureRegionAdapterMappings()
{
RegionAdapterMappings mappings = base.ConfigureRegionAdapterMappings();
if (mappings != null)
mappings.RegisterMapping(typeof(DockingManager), Container.TryResolve<DockingAdapter.DockingAdapter>());
return mappings;
}
protected override IModuleCatalog CreateModuleCatalog()
{
ModuleCatalog catalog = new ModuleCatalog();
catalog
.AddModule(typeof(GraphViewModel))
.AddModule(typeof(NotificationsViewModel))
.AddModule(typeof(OptionsViewModel))
.AddModule(typeof(SettingsViewModel))
.AddModule(typeof(ShellViewModel));
return catalog;
}
}
}
| 34.377049 | 120 | 0.660944 | [
"MIT"
] | RedbackThomson/StatTrack | UI/Bootstrapper.cs | 2,099 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.XR.MagicLeap;
public class FingersColliderDetector : MonoBehaviour
{
[SerializeField] private GameEvent moveObjectWithPinchEvent;
[SerializeField] private GameEvent dropObjectWithEvent;
private int colldersCount = 0;
private void OnTriggerEnter(Collider other)
{
FingerTracker fingerTracker = other.GetComponent<FingerTracker>();
if (fingerTracker != null)
colldersCount++;
if (colldersCount == 2)
moveObjectWithPinchEvent.RaiseEvent();
}
private void OnTriggerExit(Collider other)
{
FingerTracker fingerTracker = other.GetComponent<FingerTracker>();
if (fingerTracker != null)
colldersCount--;
if (colldersCount < 0)
colldersCount = 0;
if (colldersCount < 2)
dropObjectWithEvent.RaiseEvent();
}
}
| 25.837838 | 74 | 0.67364 | [
"Apache-2.0"
] | shrma21294/MagicLeapAdvance | Assets/Script/FingersColliderDetector.cs | 958 | C# |
#pragma warning disable 108 // new keyword hiding
#pragma warning disable 114 // new keyword hiding
namespace Windows.ApplicationModel
{
#if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ || __MACOS__
[global::Uno.NotImplemented]
#endif
public partial class LimitedAccessFeatureRequestResult
{
#if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ || __MACOS__
[global::Uno.NotImplemented("__ANDROID__", "__IOS__", "NET461", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__", "__MACOS__")]
public global::System.DateTimeOffset? EstimatedRemovalDate
{
get
{
throw new global::System.NotImplementedException("The member DateTimeOffset? LimitedAccessFeatureRequestResult.EstimatedRemovalDate is not implemented in Uno.");
}
}
#endif
#if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ || __MACOS__
[global::Uno.NotImplemented("__ANDROID__", "__IOS__", "NET461", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__", "__MACOS__")]
public string FeatureId
{
get
{
throw new global::System.NotImplementedException("The member string LimitedAccessFeatureRequestResult.FeatureId is not implemented in Uno.");
}
}
#endif
#if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ || __MACOS__
[global::Uno.NotImplemented("__ANDROID__", "__IOS__", "NET461", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__", "__MACOS__")]
public global::Windows.ApplicationModel.LimitedAccessFeatureStatus Status
{
get
{
throw new global::System.NotImplementedException("The member LimitedAccessFeatureStatus LimitedAccessFeatureRequestResult.Status is not implemented in Uno.");
}
}
#endif
// Forced skipping of method Windows.ApplicationModel.LimitedAccessFeatureRequestResult.FeatureId.get
// Forced skipping of method Windows.ApplicationModel.LimitedAccessFeatureRequestResult.Status.get
// Forced skipping of method Windows.ApplicationModel.LimitedAccessFeatureRequestResult.EstimatedRemovalDate.get
}
}
| 46.377778 | 165 | 0.761859 | [
"Apache-2.0"
] | AbdalaMask/uno | src/Uno.UWP/Generated/3.0.0.0/Windows.ApplicationModel/LimitedAccessFeatureRequestResult.cs | 2,087 | C# |
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 = Cloud.Governance.Client.Client.OpenAPIDateConverter;
namespace Cloud.Governance.Client.Model
{
public enum ExtendType
{
WithConstantValue = 0,
WithinSpecifyLimit = 1
}
}
| 20.3 | 81 | 0.783251 | [
"Apache-2.0"
] | AvePoint/cloud-governance-client | csharp-netstandard/src/Cloud.Governance.Client/Model/ExtendType.cs | 609 | C# |
using System;
using GitTools.Testing;
using LibGit2Sharp;
using NUnit.Framework;
using Shouldly;
using GitVersionExe.Tests.Helpers;
namespace GitVersionExe.Tests
{
[TestFixture]
public class PullRequestInTeamCityTest
{
[TestCase("refs/pull-requests/5/merge")]
[TestCase("refs/pull/5/merge")]
[TestCase("refs/heads/pull/5/head")]
public void GivenARemoteWithATagOnMaster_AndAPullRequestWithTwoCommits_AndBuildIsRunningInTeamCity_VersionIsCalculatedProperly(string pullRequestRef)
{
using (var fixture = new EmptyRepositoryFixture())
{
var remoteRepositoryPath = PathHelper.GetTempPath();
Repository.Init(remoteRepositoryPath);
using (var remoteRepository = new Repository(remoteRepositoryPath))
{
remoteRepository.Config.Set("user.name", "Test");
remoteRepository.Config.Set("user.email", "test@email.com");
fixture.Repository.Network.Remotes.Add("origin", remoteRepositoryPath);
Console.WriteLine("Created git repository at {0}", remoteRepositoryPath);
remoteRepository.MakeATaggedCommit("1.0.3");
var branch = remoteRepository.CreateBranch("FeatureBranch");
Commands.Checkout(remoteRepository, branch);
remoteRepository.MakeCommits(2);
Commands.Checkout(remoteRepository, remoteRepository.Head.Tip.Sha);
//Emulate merge commit
var mergeCommitSha = remoteRepository.MakeACommit().Sha;
Commands.Checkout(remoteRepository, "master"); // HEAD cannot be pointing at the merge commit
remoteRepository.Refs.Add(pullRequestRef, new ObjectId(mergeCommitSha));
// Checkout PR commit
Commands.Fetch((Repository)fixture.Repository, "origin", new string[0], new FetchOptions(), null);
Commands.Checkout(fixture.Repository, mergeCommitSha);
}
var result = GitVersionHelper.ExecuteIn(fixture.RepositoryPath, isTeamCity: true);
result.ExitCode.ShouldBe(0);
result.OutputVariables.FullSemVer.ShouldBe("1.0.4-PullRequest0005.3");
// Cleanup repository files
DirectoryHelper.DeleteDirectory(remoteRepositoryPath);
}
}
}
} | 46.272727 | 158 | 0.610609 | [
"MIT"
] | Thaoden/GitVersion | src/GitVersionExe.Tests/PullRequestInTeamCityTest.cs | 2,493 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WeatherService
{
public struct ApiConstants
{
public const string BaseUrl = "http://api.openweathermap.org";
public const string ImageEndpoint = BaseUrl + "/img";
public const string W = ImageEndpoint + "/w";
public const string DataEndpoint = "/data/2.5";
public const string CurrentWeatherEndpoint = DataEndpoint + "/weather";
public const string ForecastEndpoint = DataEndpoint + "/forecast";
}
}
| 26.909091 | 80 | 0.689189 | [
"Apache-2.0"
] | Codecamv/AlloyDemoKit | src/WeatherService/ApiConstants.cs | 594 | C# |
using System.Reflection;
public class SolutionChecker
{
public virtual bool CheckAnswer(Assembly program)
{
return true;
}
}
| 15.6 | 54 | 0.641026 | [
"MIT"
] | richardkopelow/OperationPegasus | Assets/Code/Missions/SolutionChecker.cs | 158 | C# |
/*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the glacier-2012-06-01.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Text;
namespace Amazon.Glacier.Model
{
/// <summary>
/// Paginators for the Glacier service
///</summary>
public class GlacierPaginatorFactory : IGlacierPaginatorFactory
{
private readonly IAmazonGlacier client;
internal GlacierPaginatorFactory(IAmazonGlacier client)
{
this.client = client;
}
/// <summary>
/// Paginator for ListJobs operation
///</summary>
public IListJobsPaginator ListJobs(ListJobsRequest request)
{
return new ListJobsPaginator(this.client, request);
}
/// <summary>
/// Paginator for ListParts operation
///</summary>
public IListPartsPaginator ListParts(ListPartsRequest request)
{
return new ListPartsPaginator(this.client, request);
}
/// <summary>
/// Paginator for ListVaults operation
///</summary>
public IListVaultsPaginator ListVaults(ListVaultsRequest request)
{
return new ListVaultsPaginator(this.client, request);
}
}
} | 30.096774 | 105 | 0.655949 | [
"Apache-2.0"
] | ChristopherButtars/aws-sdk-net | sdk/src/Services/Glacier/Generated/Model/_bcl45+netstandard/GlacierPaginatorFactory.cs | 1,866 | C# |
using Cindi.Application.Interfaces;
using Cindi.Application.Results;
using Cindi.Application.Services;
using Cindi.Domain.Entities.Metrics;
using Cindi.Domain.Entities.States;
using ConsensusCore.Node;
using MediatR;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace Cindi.Application.Metrics.Queries.GetMetrics
{
public class GetMetricsQueryHandler : IRequestHandler<GetMetricsQuery, QueryResult<object>>
{
ILogger<GetMetricsQueryHandler> _logger;
IEntitiesRepository _entitiesRepository;
IMetricTicksRepository _metricTicksRepository;
public GetMetricsQueryHandler(ILogger<GetMetricsQueryHandler> logger,
IEntitiesRepository entitiesRepository,
IMetricTicksRepository metricTicksRepository)
{
_entitiesRepository = entitiesRepository;
_metricTicksRepository = metricTicksRepository;
_logger = logger;
}
public async Task<QueryResult<object>> Handle(GetMetricsQuery request, CancellationToken cancellationToken)
{
var foundMetric = await _entitiesRepository.GetFirstOrDefaultAsync<Metric>(m => m.MetricName == request.MetricName);
if (foundMetric == null)
{
throw new NotImplementedException("No metric " + request.MetricName);
}
var result = await _metricTicksRepository.GetMetricTicksAsync(request.From, request.To, foundMetric.MetricId, request.Aggs, request.Interval, null, null, request.IncludeSubcategories);
return new QueryResult<object>()
{
Result = result
};
}
}
}
| 35.8 | 196 | 0.707821 | [
"MIT"
] | xucito/cindi | Cindi.Application/Metrics/Queries/GetMetrics/GetMetricsQueryHandler.cs | 1,792 | 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 SocketMeister.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("SocketMeister.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;
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap gear {
get {
object obj = ResourceManager.GetObject("gear", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap icon_gear {
get {
object obj = ResourceManager.GetObject("icon_gear", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
}
}
| 41.904762 | 179 | 0.594034 | [
"MIT"
] | sfellowes/SocketMeister | src/SocketMeister.MiniTestServer/Properties/Resources.Designer.cs | 3,522 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Azure.Management.Compute;
using Microsoft.Azure.Management.Compute.Models;
using Microsoft.Azure.Management.Network;
using Microsoft.Azure.Management.Network.Models;
using Microsoft.Azure.Management.ResourceManager;
using Microsoft.Azure.Management.ResourceManager.Models;
using Microsoft.Azure.Management.Storage;
using Microsoft.Azure.Management.Storage.Models;
using Microsoft.Rest.ClientRuntime.Azure.TestFramework;
using Newtonsoft.Json.Linq;
using Xunit;
using CM = Microsoft.Azure.Management.Compute.Models;
namespace Compute.Tests
{
public class VMScaleSetTestsBase : VMTestBase
{
protected VirtualMachineScaleSetExtension GetTestVMSSVMExtension()
{
var vmExtension = new VirtualMachineScaleSetExtension
{
Name = "vmssext01",
Publisher = "Microsoft.Compute",
Type = "VMAccessAgent",
TypeHandlerVersion = "2.0",
AutoUpgradeMinorVersion = true,
Settings = "{}",
ProtectedSettings = "{}"
};
return vmExtension;
}
protected VirtualMachineScaleSetExtension GetVmssServiceFabricExtension()
{
VirtualMachineScaleSetExtension sfExtension = new VirtualMachineScaleSetExtension
{
Name = "vmsssfext01",
Publisher = "Microsoft.Azure.ServiceFabric",
Type = "ServiceFabricNode",
TypeHandlerVersion = "1.0",
AutoUpgradeMinorVersion = true,
Settings = "{}",
ProtectedSettings = "{}"
};
return sfExtension;
}
protected VirtualMachineScaleSetExtension GetAzureDiskEncryptionExtension()
{
// NOTE: Replace dummy values for AAD credentials and KeyVault urls below by running DiskEncryptionPreRequisites.ps1.
// There is no ARM client implemented for key-vault in swagger test framework yet. These changes need to go sooner to
// unblock powershell cmdlets/API for disk encryption on scale set. So recorded this test by creating required resources
// in prod and replaced them with dummy value before check-in.
//
// Follow below steps to run this test again:
// Step 1: Execute DiskEncryptionPreRequisites.ps1. Use same subscription and region as you are running test in.
// Step 2: Replace aadClientId, aadClientSecret, keyVaultUrl, and keyVaultId values below with the values returned
// by above PS script
// Step 3: Run test and record session
// Step 4: Delete KeyVault, AAD app created by above PS script
// Step 5: Replace values for AAD credentials and KeyVault urls by dummy values before check-in
string aadClientId = Guid.NewGuid().ToString();
string aadClientSecret = Guid.NewGuid().ToString();
string keyVaultUrl = "https://adetestkv1.vault.azure.net/";
string keyVaultId =
"/subscriptions/d0d8594d-65c5-481c-9a58-fea6f203f1e2/resourceGroups/adetest/providers/Microsoft.KeyVault/vaults/adetestkv1";
string settings =
string.Format("\"AADClientID\": \"{0}\", \"KeyVaultURL\": \"{1}\", \"KeyEncryptionKeyURL\": \"\", \"KeyVaultResourceId\":\"{2}\", \"KekVaultResourceId\": \"\", \"KeyEncryptionAlgorithm\": \"{3}\", \"VolumeType\": \"{4}\", \"EncryptionOperation\": \"{5}\"",
aadClientId, keyVaultUrl, keyVaultId, "", "All", "DisableEncryption");
string protectedSettings = string.Format("\"AADClientSecret\": \"{0}\"", aadClientSecret);
var vmExtension = new VirtualMachineScaleSetExtension
{
Name = "adeext1",
Publisher = "Microsoft.Azure.Security",
Type = "ADETest",
TypeHandlerVersion = "2.0",
Settings = new JRaw("{ " + settings + " }"),
ProtectedSettings = new JRaw("{ " + protectedSettings + " }")
};
return vmExtension;
}
protected VirtualMachineScaleSet CreateDefaultVMScaleSetInput(
string rgName,
string storageAccountName,
ImageReference imageRef,
string subnetId,
bool hasManagedDisks = false,
string healthProbeId = null,
string loadBalancerBackendPoolId = null,
IList<string> zones = null)
{
// Generate Container name to hold disk VHds
string containerName = TestUtilities.GenerateName(TestPrefix);
var vhdContainer = "https://" + storageAccountName + ".blob.core.windows.net/" + containerName;
var vmssName = TestUtilities.GenerateName("vmss");
return new VirtualMachineScaleSet()
{
Location = m_location,
Tags = new Dictionary<string, string>() { { "RG", "rg" }, { "testTag", "1" } },
Sku = new CM.Sku()
{
Capacity = 2,
Name = zones == null ? VirtualMachineSizeTypes.StandardA0 : VirtualMachineSizeTypes.StandardA1V2,
},
Zones = zones,
Overprovision = false,
UpgradePolicy = new UpgradePolicy()
{
Mode = UpgradeMode.Automatic
},
VirtualMachineProfile = new VirtualMachineScaleSetVMProfile()
{
StorageProfile = new VirtualMachineScaleSetStorageProfile()
{
ImageReference = imageRef,
OsDisk = hasManagedDisks ? null : new VirtualMachineScaleSetOSDisk
{
Caching = CachingTypes.None,
CreateOption = DiskCreateOptionTypes.FromImage,
Name = "test",
VhdContainers = new List<string>{ vhdContainer }
},
DataDisks = !hasManagedDisks ? null : new List<VirtualMachineScaleSetDataDisk>
{
new VirtualMachineScaleSetDataDisk
{
Lun = 1,
CreateOption = DiskCreateOptionTypes.Empty,
DiskSizeGB = 128
}
}
},
OsProfile = new VirtualMachineScaleSetOSProfile()
{
ComputerNamePrefix = "test",
AdminUsername = "Foo12",
AdminPassword = PLACEHOLDER,
CustomData = Convert.ToBase64String(Encoding.UTF8.GetBytes("Custom data"))
},
NetworkProfile = new VirtualMachineScaleSetNetworkProfile()
{
HealthProbe = healthProbeId == null ? null : new ApiEntityReference
{
Id = healthProbeId
},
NetworkInterfaceConfigurations = new List<VirtualMachineScaleSetNetworkConfiguration>()
{
new VirtualMachineScaleSetNetworkConfiguration()
{
Name = TestUtilities.GenerateName("vmsstestnetconfig"),
Primary = true,
IpConfigurations = new List<VirtualMachineScaleSetIPConfiguration>
{
new VirtualMachineScaleSetIPConfiguration()
{
Name = TestUtilities.GenerateName("vmsstestnetconfig"),
Subnet = new Microsoft.Azure.Management.Compute.Models.ApiEntityReference()
{
Id = subnetId
},
LoadBalancerBackendAddressPools = (loadBalancerBackendPoolId != null) ?
new List<Microsoft.Azure.Management.Compute.Models.SubResource> {
new Microsoft.Azure.Management.Compute.Models.SubResource(loadBalancerBackendPoolId)
} : null,
ApplicationGatewayBackendAddressPools = new List<Microsoft.Azure.Management.Compute.Models.SubResource>(),
}
}
}
}
},
ExtensionProfile = new VirtualMachineScaleSetExtensionProfile(),
}
};
}
protected VirtualMachineScaleSet CreateVMScaleSet_NoAsyncTracking(
string rgName,
string vmssName,
StorageAccount storageAccount,
ImageReference imageRef,
out VirtualMachineScaleSet inputVMScaleSet,
VirtualMachineScaleSetExtensionProfile extensionProfile = null,
Action<VirtualMachineScaleSet> vmScaleSetCustomizer = null,
bool createWithPublicIpAddress = false,
bool createWithManagedDisks = false,
bool createWithHealthProbe = false,
Subnet subnet = null,
IList<string> zones = null)
{
try
{
var createOrUpdateResponse = CreateVMScaleSetAndGetOperationResponse(rgName,
vmssName,
storageAccount,
imageRef,
out inputVMScaleSet,
extensionProfile,
vmScaleSetCustomizer,
createWithPublicIpAddress,
createWithManagedDisks,
createWithHealthProbe,
subnet,
zones);
var getResponse = m_CrpClient.VirtualMachineScaleSets.Get(rgName, vmssName);
return getResponse;
}
catch
{
m_ResourcesClient.ResourceGroups.Delete(rgName);
throw;
}
}
protected VirtualMachineScaleSet CreateVMScaleSet(
string rgName,
string vmssName,
StorageAccount storageAccount,
ImageReference imageRef,
out VirtualMachineScaleSet inputVMScaleSet,
VirtualMachineScaleSetExtensionProfile extensionProfile = null,
Action<VirtualMachineScaleSet> vmScaleSetCustomizer = null,
bool createWithPublicIpAddress = false,
bool createWithManagedDisks = false)
{
try
{
var createOrUpdateResponse = CreateVMScaleSetAndGetOperationResponse(
rgName,
vmssName,
storageAccount,
imageRef,
out inputVMScaleSet,
extensionProfile,
vmScaleSetCustomizer,
createWithPublicIpAddress,
createWithManagedDisks);
var lroResponse = m_CrpClient.VirtualMachineScaleSets.CreateOrUpdate(rgName, inputVMScaleSet.Name, inputVMScaleSet);
var getResponse = m_CrpClient.VirtualMachineScaleSets.Get(rgName, inputVMScaleSet.Name);
return getResponse;
}
catch
{
m_ResourcesClient.ResourceGroups.Delete(rgName);
throw;
}
}
protected void UpdateVMScaleSet(string rgName, string vmssName, VirtualMachineScaleSet inputVMScaleSet)
{
var createOrUpdateResponse = m_CrpClient.VirtualMachineScaleSets.CreateOrUpdate(rgName, vmssName, inputVMScaleSet);
}
// This method is used to Update VM Scale Set but it internally calls PATCH verb instead of PUT.
// PATCH verb is more relaxed and does not puts constraint to specify full parameters.
protected void PatchVMScaleSet(string rgName, string vmssName, VirtualMachineScaleSetUpdate inputVMScaleSet)
{
var patchResponse = m_CrpClient.VirtualMachineScaleSets.Update(rgName, vmssName, inputVMScaleSet);
}
private VirtualMachineScaleSet CreateVMScaleSetAndGetOperationResponse(
string rgName,
string vmssName,
StorageAccount storageAccount,
ImageReference imageRef,
out VirtualMachineScaleSet inputVMScaleSet,
VirtualMachineScaleSetExtensionProfile extensionProfile = null,
Action<VirtualMachineScaleSet> vmScaleSetCustomizer = null,
bool createWithPublicIpAddress = false,
bool createWithManagedDisks = false,
bool createWithHealthProbe = false,
Subnet subnet = null,
IList<string> zones = null)
{
// Create the resource Group, it might have been already created during StorageAccount creation.
var resourceGroup = m_ResourcesClient.ResourceGroups.CreateOrUpdate(
rgName,
new ResourceGroup
{
Location = m_location
});
var getPublicIpAddressResponse = createWithPublicIpAddress ? null : CreatePublicIP(rgName);
var subnetResponse = subnet ?? CreateVNET(rgName);
var nicResponse = CreateNIC(
rgName,
subnetResponse,
getPublicIpAddressResponse != null ? getPublicIpAddressResponse.IpAddress : null);
var loadBalancer = (getPublicIpAddressResponse != null && createWithHealthProbe) ?
CreatePublicLoadBalancerWithProbe(rgName, getPublicIpAddressResponse) : null;
inputVMScaleSet = CreateDefaultVMScaleSetInput(rgName, storageAccount.Name, imageRef, subnetResponse.Id, hasManagedDisks:createWithManagedDisks,
healthProbeId: loadBalancer?.Probes?.FirstOrDefault()?.Id,
loadBalancerBackendPoolId: loadBalancer?.BackendAddressPools?.FirstOrDefault()?.Id, zones: zones);
if (vmScaleSetCustomizer != null)
{
vmScaleSetCustomizer(inputVMScaleSet);
}
inputVMScaleSet.VirtualMachineProfile.ExtensionProfile = extensionProfile;
var createOrUpdateResponse = m_CrpClient.VirtualMachineScaleSets.CreateOrUpdate(rgName, vmssName, inputVMScaleSet);
Assert.True(createOrUpdateResponse.Name == vmssName);
Assert.True(createOrUpdateResponse.Location.ToLower() == inputVMScaleSet.Location.ToLower().Replace(" ", ""));
ValidateVMScaleSet(inputVMScaleSet, createOrUpdateResponse, createWithManagedDisks);
return createOrUpdateResponse;
}
protected void ValidateVMScaleSetInstanceView(VirtualMachineScaleSet vmScaleSet,
VirtualMachineScaleSetInstanceView vmScaleSetInstanceView)
{
Assert.NotNull(vmScaleSetInstanceView.Statuses);
Assert.NotNull(vmScaleSetInstanceView);
if (vmScaleSet.VirtualMachineProfile.ExtensionProfile != null)
{
Assert.NotNull(vmScaleSetInstanceView.Extensions);
int instancesCount = vmScaleSetInstanceView.Extensions.Sum(statusSummary => statusSummary.StatusesSummary.Sum(t => t.Count.Value));
Assert.True(instancesCount == vmScaleSet.Sku.Capacity);
}
}
protected void ValidateVMScaleSet(VirtualMachineScaleSet vmScaleSet, VirtualMachineScaleSet vmScaleSetOut, bool hasManagedDisks = false)
{
Assert.True(!string.IsNullOrEmpty(vmScaleSetOut.ProvisioningState));
Assert.True(vmScaleSetOut.Sku.Name
== vmScaleSet.Sku.Name);
Assert.NotNull(vmScaleSetOut.VirtualMachineProfile.StorageProfile.OsDisk);
if (!hasManagedDisks)
{
Assert.True(vmScaleSetOut.VirtualMachineProfile.StorageProfile.OsDisk.Name
== vmScaleSet.VirtualMachineProfile.StorageProfile.OsDisk.Name);
if (vmScaleSet.VirtualMachineProfile.StorageProfile.OsDisk.Image != null)
{
Assert.True(vmScaleSetOut.VirtualMachineProfile.StorageProfile.OsDisk.Image.Uri
== vmScaleSet.VirtualMachineProfile.StorageProfile.OsDisk.Image.Uri);
}
Assert.True(vmScaleSetOut.VirtualMachineProfile.StorageProfile.OsDisk.Caching
== vmScaleSet.VirtualMachineProfile.StorageProfile.OsDisk.Caching);
}
else
{
Assert.NotNull(vmScaleSetOut.VirtualMachineProfile.StorageProfile.OsDisk.ManagedDisk);
if (vmScaleSet.VirtualMachineProfile.StorageProfile.OsDisk != null)
{
VirtualMachineScaleSetOSDisk osDisk = vmScaleSet.VirtualMachineProfile.StorageProfile.OsDisk;
VirtualMachineScaleSetOSDisk osDiskOut =
vmScaleSetOut.VirtualMachineProfile.StorageProfile.OsDisk;
if (osDisk.Caching != null)
{
Assert.True(osDisk.Caching == osDiskOut.Caching);
}
else
{
Assert.NotNull(osDiskOut.Caching);
}
Assert.NotNull(osDiskOut.ManagedDisk);
if (osDisk.ManagedDisk != null && osDisk.ManagedDisk.StorageAccountType != null)
{
Assert.True(osDisk.ManagedDisk.StorageAccountType == osDiskOut.ManagedDisk.StorageAccountType);
}
else
{
Assert.NotNull(osDiskOut.ManagedDisk.StorageAccountType);
}
if (osDisk.Name != null)
{
Assert.Equal(osDiskOut.Name, osDisk.Name);
}
Assert.True(osDiskOut.CreateOption == DiskCreateOptionTypes.FromImage);
}
if (vmScaleSet.VirtualMachineProfile.StorageProfile.DataDisks != null
&& vmScaleSet.VirtualMachineProfile.StorageProfile.DataDisks.Count > 0)
{
Assert.Equal(
vmScaleSet.VirtualMachineProfile.StorageProfile.DataDisks.Count,
vmScaleSetOut.VirtualMachineProfile.StorageProfile.DataDisks.Count);
foreach (VirtualMachineScaleSetDataDisk dataDisk in vmScaleSet.VirtualMachineProfile.StorageProfile.DataDisks)
{
VirtualMachineScaleSetDataDisk matchingDataDisk
= vmScaleSetOut.VirtualMachineProfile.StorageProfile.DataDisks.FirstOrDefault(disk => disk.Lun == dataDisk.Lun);
Assert.NotNull(matchingDataDisk);
if (dataDisk.Caching != null)
{
Assert.True(dataDisk.Caching == matchingDataDisk.Caching);
}
else
{
Assert.NotNull(matchingDataDisk.Caching);
}
if (dataDisk.ManagedDisk != null && dataDisk.ManagedDisk.StorageAccountType != null)
{
Assert.True(dataDisk.ManagedDisk.StorageAccountType == matchingDataDisk.ManagedDisk.StorageAccountType);
}
else
{
Assert.NotNull(matchingDataDisk.ManagedDisk.StorageAccountType);
}
if (dataDisk.Name != null)
{
Assert.Equal(dataDisk.Name, matchingDataDisk.Name);
}
Assert.True(dataDisk.CreateOption == matchingDataDisk.CreateOption);
}
}
}
if (vmScaleSet.VirtualMachineProfile.OsProfile.Secrets != null &&
vmScaleSet.VirtualMachineProfile.OsProfile.Secrets.Any())
{
foreach (var secret in vmScaleSet.VirtualMachineProfile.OsProfile.Secrets)
{
Assert.NotNull(secret.VaultCertificates);
var secretOut = vmScaleSetOut.VirtualMachineProfile.OsProfile.Secrets.FirstOrDefault(s => string.Equals(secret.SourceVault.Id, s.SourceVault.Id));
Assert.NotNull(secretOut);
// Disabling resharper null-ref check as it doesn't seem to understand the not-null assert above.
// ReSharper disable PossibleNullReferenceException
Assert.NotNull(secretOut.VaultCertificates);
var VaultCertComparer = new VaultCertComparer();
Assert.True(secretOut.VaultCertificates.SequenceEqual(secret.VaultCertificates, VaultCertComparer));
// ReSharper enable PossibleNullReferenceException
}
}
if (vmScaleSet.VirtualMachineProfile.ExtensionProfile != null &&
vmScaleSet.VirtualMachineProfile.ExtensionProfile.Extensions.Any())
{
foreach (var vmExtension in vmScaleSet.VirtualMachineProfile.ExtensionProfile.Extensions)
{
var vmExt = vmScaleSetOut.VirtualMachineProfile.ExtensionProfile.Extensions.FirstOrDefault(s => String.Compare(s.Name, vmExtension.Name, StringComparison.OrdinalIgnoreCase) == 0);
Assert.NotNull(vmExt);
}
}
if (vmScaleSet.VirtualMachineProfile.NetworkProfile != null)
{
if (vmScaleSet.VirtualMachineProfile.NetworkProfile.NetworkInterfaceConfigurations != null && vmScaleSet.VirtualMachineProfile.NetworkProfile.NetworkInterfaceConfigurations.Count > 0)
{
Assert.NotNull(vmScaleSetOut.VirtualMachineProfile.NetworkProfile.NetworkInterfaceConfigurations);
Assert.Equal(
vmScaleSetOut.VirtualMachineProfile.NetworkProfile.NetworkInterfaceConfigurations.Count,
vmScaleSet.VirtualMachineProfile.NetworkProfile.NetworkInterfaceConfigurations.Count);
foreach (var nicconfig in vmScaleSet.VirtualMachineProfile.NetworkProfile.NetworkInterfaceConfigurations)
{
var outnicconfig =
vmScaleSetOut.VirtualMachineProfile.NetworkProfile.NetworkInterfaceConfigurations.First(
nc => string.Equals(nc.Name, nicconfig.Name, StringComparison.OrdinalIgnoreCase));
Assert.NotNull(outnicconfig);
CompareVmssNicConfig(nicconfig, outnicconfig);
}
}
}
else
{
Assert.True((vmScaleSetOut.VirtualMachineProfile.NetworkProfile == null) || (vmScaleSetOut.VirtualMachineProfile.NetworkProfile.NetworkInterfaceConfigurations.Count == 0));
}
if(vmScaleSet.Zones != null)
{
Assert.True(vmScaleSet.Zones.SequenceEqual(vmScaleSetOut.Zones), "Zones don't match");
if(vmScaleSet.ZoneBalance.HasValue)
{
Assert.Equal(vmScaleSet.ZoneBalance, vmScaleSetOut.ZoneBalance);
}
else
{
if (vmScaleSet.Zones.Count > 1)
{
Assert.True(vmScaleSetOut.ZoneBalance.HasValue);
}
else
{
Assert.False(vmScaleSetOut.ZoneBalance.HasValue);
}
}
if (vmScaleSet.PlatformFaultDomainCount.HasValue)
{
Assert.Equal(vmScaleSet.PlatformFaultDomainCount, vmScaleSetOut.PlatformFaultDomainCount);
}
else
{
Assert.True(vmScaleSetOut.PlatformFaultDomainCount.HasValue);
}
}
else
{
Assert.Null(vmScaleSetOut.Zones);
Assert.Null(vmScaleSetOut.ZoneBalance);
Assert.Null(vmScaleSetOut.PlatformFaultDomainCount);
}
}
protected void CompareVmssNicConfig(VirtualMachineScaleSetNetworkConfiguration nicconfig,
VirtualMachineScaleSetNetworkConfiguration outnicconfig)
{
if (nicconfig.IpConfigurations != null && nicconfig.IpConfigurations.Count > 0)
{
Assert.NotNull(outnicconfig.IpConfigurations);
Assert.Equal(nicconfig.IpConfigurations.Count, outnicconfig.IpConfigurations.Count);
foreach (var ipconfig in nicconfig.IpConfigurations)
{
var outipconfig =
outnicconfig.IpConfigurations.First(
ic => string.Equals(ic.Name, ipconfig.Name, StringComparison.OrdinalIgnoreCase));
Assert.NotNull(outipconfig);
CompareIpConfigApplicationGatewayPools(ipconfig, outipconfig);
}
}
else
{
Assert.True((outnicconfig.IpConfigurations == null) || (outnicconfig.IpConfigurations.Count == 0));
}
}
protected void CompareIpConfigApplicationGatewayPools(VirtualMachineScaleSetIPConfiguration ipconfig, VirtualMachineScaleSetIPConfiguration outipconfig)
{
if (ipconfig.ApplicationGatewayBackendAddressPools != null && ipconfig.ApplicationGatewayBackendAddressPools.Count > 0)
{
Assert.NotNull(outipconfig.ApplicationGatewayBackendAddressPools);
Assert.Equal(ipconfig.ApplicationGatewayBackendAddressPools.Count,
outipconfig.ApplicationGatewayBackendAddressPools.Count);
foreach (var pool in ipconfig.ApplicationGatewayBackendAddressPools)
{
var outPool =
outipconfig.ApplicationGatewayBackendAddressPools.First(
p => string.Equals(p.Id, pool.Id, StringComparison.OrdinalIgnoreCase));
Assert.NotNull(outPool);
}
}
else
{
Assert.True((outipconfig.ApplicationGatewayBackendAddressPools == null) || (outipconfig.ApplicationGatewayBackendAddressPools.Count == 0));
}
}
}
}
| 48.424915 | 272 | 0.552032 | [
"MIT"
] | Lusitanian/azure-sdk-for-net | src/SDKs/Compute/Compute.Tests/VMScaleSetTests/VMScaleSetTestsBase.cs | 28,379 | C# |
namespace ParentLoadRO.Business.ERLevel
{
public partial class A09_Region_Child
{
#region OnDeserialized actions
/*/// <summary>
/// This method is called on a newly deserialized object
/// after deserialization is complete.
/// </summary>
/// <param name="context">Serialization context object.</param>
protected override void OnDeserialized(System.Runtime.Serialization.StreamingContext context)
{
base.OnDeserialized(context);
// add your custom OnDeserialized actions here.
}*/
#endregion
#region Implementation of DataPortal Hooks
//partial void OnFetchRead(DataPortalHookArgs args)
//{
// throw new NotImplementedException();
//}
#endregion
}
}
| 26 | 102 | 0.59324 | [
"MIT"
] | CslaGenFork/CslaGenFork | trunk/Samples/DeepLoad/DAL-DR/ParentLoadRO.Business/ERLevel/A09_Region_Child.cs | 858 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace WriteableBitmapExShapeSample.Wpf
{
public partial class MainWindow : Window
{
#region Fields
private WriteableBitmap writeableBmp;
private int shapeCount;
private static Random rand = new Random();
private int frameCounter = 0;
#endregion
#region Contructors
/// <summary>
/// MainPage!
/// </summary>
public MainWindow()
{
InitializeComponent();
}
#endregion
#region Methods
private void Init()
{
// Init WriteableBitmap
writeableBmp = BitmapFactory.New((int)ViewPortContainer.Width, (int)ViewPortContainer.Height);
ImageViewport.Source = writeableBmp;
// Init vars
TxtBoxShapeCount_TextChanged(this, null);
// Start render loop
CompositionTarget.Rendering += new EventHandler(CompositionTarget_Rendering);
}
private void Draw()
{
// What to draw?
if (!RBDrawShapes.IsChecked.Value)
{
this.TxtBoxShapeCount.Visibility = System.Windows.Visibility.Visible;
if (RBDrawShapesAnim.IsChecked.Value)
{
DrawShapes();
}
else if (RBDrawEllipse.IsChecked.Value)
{
DrawEllipses();
}
else
{
this.TxtBoxShapeCount.Visibility = System.Windows.Visibility.Collapsed;
DrawEllipsesFlower();
}
}
}
/// <summary>
/// Draws the different types of shapes.
/// </summary>
private void DrawStaticShapes()
{
// Wrap updates in a GetContext call, to prevent invalidation and nested locking/unlocking during this block
using (writeableBmp.GetBitmapContext())
{
// Init some size vars
int w = this.writeableBmp.PixelWidth - 2;
int h = this.writeableBmp.PixelHeight - 2;
int w3rd = w/3;
int h3rd = h/3;
int w6th = w3rd >> 1;
int h6th = h3rd >> 1;
// Clear
writeableBmp.Clear();
// Draw some points
for (int i = 0; i < 200; i++)
{
writeableBmp.SetPixel(rand.Next(w3rd), rand.Next(h3rd), GetRandomColor());
}
// Draw Standard shapes
writeableBmp.DrawLine(rand.Next(w3rd, w3rd*2), rand.Next(h3rd), rand.Next(w3rd, w3rd*2), rand.Next(h3rd),
GetRandomColor());
writeableBmp.DrawTriangle(rand.Next(w3rd*2, w - w6th), rand.Next(h6th), rand.Next(w3rd*2, w),
rand.Next(h6th, h3rd), rand.Next(w - w6th, w), rand.Next(h3rd),
GetRandomColor());
writeableBmp.DrawQuad(rand.Next(0, w6th), rand.Next(h3rd, h3rd + h6th), rand.Next(w6th, w3rd),
rand.Next(h3rd, h3rd + h6th), rand.Next(w6th, w3rd),
rand.Next(h3rd + h6th, 2*h3rd), rand.Next(0, w6th), rand.Next(h3rd + h6th, 2*h3rd),
GetRandomColor());
writeableBmp.DrawRectangle(rand.Next(w3rd, w3rd + w6th), rand.Next(h3rd, h3rd + h6th),
rand.Next(w3rd + w6th, w3rd*2), rand.Next(h3rd + h6th, 2*h3rd),
GetRandomColor());
// Random polyline
int[] p = new int[rand.Next(7, 10)*2];
for (int j = 0; j < p.Length; j += 2)
{
p[j] = rand.Next(w3rd*2, w);
p[j + 1] = rand.Next(h3rd, 2*h3rd);
}
writeableBmp.DrawPolyline(p, GetRandomColor());
// Random closed polyline
p = new int[rand.Next(6, 9)*2];
for (int j = 0; j < p.Length - 2; j += 2)
{
p[j] = rand.Next(w3rd);
p[j + 1] = rand.Next(2*h3rd, h);
}
p[p.Length - 2] = p[0];
p[p.Length - 1] = p[1];
writeableBmp.DrawPolyline(p, GetRandomColor());
// Ellipses
writeableBmp.DrawEllipse(rand.Next(w3rd, w3rd + w6th), rand.Next(h3rd*2, h - h6th),
rand.Next(w3rd + w6th, w3rd*2), rand.Next(h - h6th, h), GetRandomColor());
writeableBmp.DrawEllipseCentered(w - w6th, h - h6th, w6th >> 1, h6th >> 1, GetRandomColor());
// Draw Grid
writeableBmp.DrawLine(0, h3rd, w, h3rd, Colors.Black);
writeableBmp.DrawLine(0, 2*h3rd, w, 2*h3rd, Colors.Black);
writeableBmp.DrawLine(w3rd, 0, w3rd, h, Colors.Black);
writeableBmp.DrawLine(2*w3rd, 0, 2*w3rd, h, Colors.Black);
// Invalidates on exit of using block
}
}
/// <summary>
/// Draws random shapes.
/// </summary>
private unsafe void DrawShapes()
{
// Wrap updates in a GetContext call, to prevent invalidation and nested locking/unlocking during this block
using (var bitmapContext = writeableBmp.GetBitmapContext())
{
// Init some size vars
int w = this.writeableBmp.PixelWidth - 2;
int h = this.writeableBmp.PixelHeight - 2;
int wh = w >> 1;
int hh = h >> 1;
// Clear
writeableBmp.Clear();
// Draw Shapes and use refs for faster access which speeds up a lot.
int wbmp = writeableBmp.PixelWidth;
int hbmp = writeableBmp.PixelHeight;
var pixels = bitmapContext.Pixels;
for (int i = 0; i < shapeCount/6; i++)
{
// Standard shapes
WriteableBitmapExtensions.DrawLine(bitmapContext, wbmp, hbmp, rand.Next(w), rand.Next(h), rand.Next(w),
rand.Next(h), GetRandomColor());
writeableBmp.DrawTriangle(rand.Next(w), rand.Next(h), rand.Next(w), rand.Next(h), rand.Next(w),
rand.Next(h), GetRandomColor());
writeableBmp.DrawQuad(rand.Next(w), rand.Next(h), rand.Next(w), rand.Next(h), rand.Next(w),
rand.Next(h), rand.Next(w), rand.Next(h), GetRandomColor());
writeableBmp.DrawRectangle(rand.Next(wh), rand.Next(hh), rand.Next(wh, w), rand.Next(hh, h),
GetRandomColor());
writeableBmp.DrawEllipse(rand.Next(wh), rand.Next(hh), rand.Next(wh, w), rand.Next(hh, h),
GetRandomColor());
// Random polyline
int[] p = new int[rand.Next(5, 10)*2];
for (int j = 0; j < p.Length; j += 2)
{
p[j] = rand.Next(w);
p[j + 1] = rand.Next(h);
}
writeableBmp.DrawPolyline(p, GetRandomColor());
}
// Invalidates on end of using block
}
}
/// <summary>
/// Draws random ellipses
/// </summary>
private void DrawEllipses()
{
// Init some size vars
int w = this.writeableBmp.PixelWidth - 2;
int h = this.writeableBmp.PixelHeight - 2;
int wh = w >> 1;
int hh = h >> 1;
// Wrap updates in a GetContext call, to prevent invalidation and nested locking/unlocking during this block
using (writeableBmp.GetBitmapContext())
{
// Clear
writeableBmp.Clear();
// Draw Ellipses
for (int i = 0; i < shapeCount; i++)
{
writeableBmp.DrawEllipse(rand.Next(wh), rand.Next(hh), rand.Next(wh, w), rand.Next(hh, h),
GetRandomColor());
}
// Invalidates on exit of using block
}
}
/// <summary>
/// Draws circles that decrease in size to build a flower that is animated
/// </summary>
private void DrawEllipsesFlower()
{
if (writeableBmp == null)
return;
// Init some size vars
int w = this.writeableBmp.PixelWidth - 2;
int h = this.writeableBmp.PixelHeight - 2;
// Wrap updates in a GetContext call, to prevent invalidation and nested locking/unlocking during this block
using (writeableBmp.GetBitmapContext())
{
// Increment frame counter
if (++frameCounter >= int.MaxValue || frameCounter < 1)
{
frameCounter = 1;
}
double s = Math.Sin(frameCounter*0.01);
if (s < 0)
{
s *= -1;
}
// Clear
writeableBmp.Clear();
// Draw center circle
int xc = w >> 1;
int yc = h >> 1;
// Animate base size with sine
int r0 = (int) ((w + h)*0.07*s) + 10;
writeableBmp.DrawEllipseCentered(xc, yc, r0, r0, Colors.Brown);
// Draw outer circles
int dec = (int) ((w + h)*0.0045f);
int r = (int) ((w + h)*0.025f);
int offset = r0 + r;
for (int i = 1; i < 6 && r > 1; i++)
{
for (double f = 1; f < 7; f += 0.7)
{
// Calc postion based on unit circle
int xc2 = (int) (Math.Sin(frameCounter*0.002*i + f)*offset + xc);
int yc2 = (int) (Math.Cos(frameCounter*0.002*i + f)*offset + yc);
int col = (int) (0xFFFF0000 | (uint) (0x1A*i) << 8 | (uint) (0x20*f));
writeableBmp.DrawEllipseCentered(xc2, yc2, r, r, col);
}
// Next ring
offset += r;
r -= dec;
offset += r;
}
// Invalidates on exit of using block
}
}
/// <summary>
/// Random color fully opaque
/// </summary>
/// <returns></returns>
private static int GetRandomColor()
{
return (int)(0xFF000000 | (uint)rand.Next(0xFFFFFF));
}
#endregion
#region Eventhandler
private void MainWindow_Loaded(object sender, RoutedEventArgs e)
{
Init();
}
private void CompositionTarget_Rendering(object sender, EventArgs e)
{
Draw();
}
private void TxtBoxShapeCount_TextChanged(object sender, TextChangedEventArgs e)
{
int v = 1;
if (int.TryParse(TxtBoxShapeCount.Text, out v))
{
this.shapeCount = v;
TxtBoxShapeCount.Background = null;
frameCounter = 0;
Draw();
}
else
{
TxtBoxShapeCount.Background = new SolidColorBrush(Colors.Red);
}
}
private void RadioButton_Checked(object sender, RoutedEventArgs e)
{
this.TxtBoxShapeCount.Visibility = System.Windows.Visibility.Collapsed;
DrawStaticShapes();
}
#endregion
}
}
| 37.934911 | 124 | 0.455701 | [
"MIT"
] | Chriscolm/WriteableBitmapEx | Source/WriteableBitmapExShapeSample.Wpf/MainWindow.xaml.cs | 12,824 | C# |
using System;
namespace MVCMovieCore.Models
{
public class ErrorViewModel
{
public string RequestId { get; set; }
public bool ShowRequestId => !string.IsNullOrEmpty(RequestId);
}
} | 19.090909 | 70 | 0.671429 | [
"MIT"
] | vilsonmoro/curso-csharp | MVcMovie/MVCMovieCore/Models/ErrorViewModel.cs | 210 | C# |
using Newtonsoft.Json;
namespace TwitchLib.Api.V5.Models.Videos
{
public class VideoPreview
{
#region Large
[JsonProperty(PropertyName = "large")]
public string Large { get; protected set; }
#endregion
#region Medium
[JsonProperty(PropertyName = "medium")]
public string Medium { get; protected set; }
#endregion
#region Small
[JsonProperty(PropertyName = "small")]
public string Small { get; protected set; }
#endregion
#region Template
[JsonProperty(PropertyName = "template")]
public string Template { get; protected set; }
#endregion
}
}
| 27.36 | 54 | 0.603801 | [
"MIT"
] | Teravus/RebootTechChatBot | TwitchLib.Api/TwitchLib.Api.V5.Models/Videos/VideoPreview.cs | 686 | 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 codeartifact-2018-09-22.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.CodeArtifact.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using ThirdParty.Json.LitJson;
namespace Amazon.CodeArtifact.Model.Internal.MarshallTransformations
{
/// <summary>
/// Response Unmarshaller for DescribePackageVersion operation
/// </summary>
public class DescribePackageVersionResponseUnmarshaller : JsonResponseUnmarshaller
{
/// <summary>
/// Unmarshaller the response from the service to the response class.
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
public override AmazonWebServiceResponse Unmarshall(JsonUnmarshallerContext context)
{
DescribePackageVersionResponse response = new DescribePackageVersionResponse();
context.Read();
int targetDepth = context.CurrentDepth;
while (context.ReadAtDepth(targetDepth))
{
if (context.TestExpression("packageVersion", targetDepth))
{
var unmarshaller = PackageVersionDescriptionUnmarshaller.Instance;
response.PackageVersion = unmarshaller.Unmarshall(context);
continue;
}
}
return response;
}
/// <summary>
/// Unmarshaller error response to exception.
/// </summary>
/// <param name="context"></param>
/// <param name="innerException"></param>
/// <param name="statusCode"></param>
/// <returns></returns>
public override AmazonServiceException UnmarshallException(JsonUnmarshallerContext context, Exception innerException, HttpStatusCode statusCode)
{
var errorResponse = JsonErrorResponseUnmarshaller.GetInstance().Unmarshall(context);
errorResponse.InnerException = innerException;
errorResponse.StatusCode = statusCode;
var responseBodyBytes = context.GetResponseBodyBytes();
using (var streamCopy = new MemoryStream(responseBodyBytes))
using (var contextCopy = new JsonUnmarshallerContext(streamCopy, false, null))
{
if (errorResponse.Code != null && errorResponse.Code.Equals("AccessDeniedException"))
{
return AccessDeniedExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("ConflictException"))
{
return ConflictExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("InternalServerException"))
{
return InternalServerExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("ResourceNotFoundException"))
{
return ResourceNotFoundExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("ThrottlingException"))
{
return ThrottlingExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("ValidationException"))
{
return ValidationExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse);
}
}
return new AmazonCodeArtifactException(errorResponse.Message, errorResponse.InnerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, errorResponse.StatusCode);
}
private static DescribePackageVersionResponseUnmarshaller _instance = new DescribePackageVersionResponseUnmarshaller();
internal static DescribePackageVersionResponseUnmarshaller GetInstance()
{
return _instance;
}
/// <summary>
/// Gets the singleton.
/// </summary>
public static DescribePackageVersionResponseUnmarshaller Instance
{
get
{
return _instance;
}
}
}
} | 41.261538 | 195 | 0.644295 | [
"Apache-2.0"
] | DetlefGolze/aws-sdk-net | sdk/src/Services/CodeArtifact/Generated/Model/Internal/MarshallTransformations/DescribePackageVersionResponseUnmarshaller.cs | 5,364 | 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 gamelift-2015-10-01.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.GameLift.Model
{
/// <summary>
/// Container for the parameters to the UpdateGameSession operation.
/// Updates game session properties. This includes the session name, maximum player count,
/// protection policy, which controls whether or not an active game session can be terminated
/// during a scale-down event, and the player session creation policy, which controls
/// whether or not new players can join the session. To update a game session, specify
/// the game session ID and the values you want to change. If successful, an updated <a>GameSession</a>
/// object is returned.
///
///
/// <para>
/// Game-session-related operations include:
/// </para>
/// <ul> <li>
/// <para>
/// <a>CreateGameSession</a>
/// </para>
/// </li> <li>
/// <para>
/// <a>DescribeGameSessions</a>
/// </para>
/// </li> <li>
/// <para>
/// <a>DescribeGameSessionDetails</a>
/// </para>
/// </li> <li>
/// <para>
/// <a>SearchGameSessions</a>
/// </para>
/// </li> <li>
/// <para>
/// <a>UpdateGameSession</a>
/// </para>
/// </li> <li>
/// <para>
/// <a>GetGameSessionLogUrl</a>
/// </para>
/// </li> <li>
/// <para>
/// Game session placements
/// </para>
/// <ul> <li>
/// <para>
/// <a>StartGameSessionPlacement</a>
/// </para>
/// </li> <li>
/// <para>
/// <a>DescribeGameSessionPlacement</a>
/// </para>
/// </li> <li>
/// <para>
/// <a>StopGameSessionPlacement</a>
/// </para>
/// </li> </ul> </li> </ul>
/// </summary>
public partial class UpdateGameSessionRequest : AmazonGameLiftRequest
{
private string _gameSessionId;
private int? _maximumPlayerSessionCount;
private string _name;
private PlayerSessionCreationPolicy _playerSessionCreationPolicy;
private ProtectionPolicy _protectionPolicy;
/// <summary>
/// Gets and sets the property GameSessionId.
/// <para>
/// Unique identifier for the game session to update.
/// </para>
/// </summary>
public string GameSessionId
{
get { return this._gameSessionId; }
set { this._gameSessionId = value; }
}
// Check to see if GameSessionId property is set
internal bool IsSetGameSessionId()
{
return this._gameSessionId != null;
}
/// <summary>
/// Gets and sets the property MaximumPlayerSessionCount.
/// <para>
/// Maximum number of players that can be connected simultaneously to the game session.
/// </para>
/// </summary>
public int MaximumPlayerSessionCount
{
get { return this._maximumPlayerSessionCount.GetValueOrDefault(); }
set { this._maximumPlayerSessionCount = value; }
}
// Check to see if MaximumPlayerSessionCount property is set
internal bool IsSetMaximumPlayerSessionCount()
{
return this._maximumPlayerSessionCount.HasValue;
}
/// <summary>
/// Gets and sets the property Name.
/// <para>
/// Descriptive label that is associated with a game session. Session names do not need
/// to be unique.
/// </para>
/// </summary>
public string Name
{
get { return this._name; }
set { this._name = value; }
}
// Check to see if Name property is set
internal bool IsSetName()
{
return this._name != null;
}
/// <summary>
/// Gets and sets the property PlayerSessionCreationPolicy.
/// <para>
/// Policy determining whether or not the game session accepts new players.
/// </para>
/// </summary>
public PlayerSessionCreationPolicy PlayerSessionCreationPolicy
{
get { return this._playerSessionCreationPolicy; }
set { this._playerSessionCreationPolicy = value; }
}
// Check to see if PlayerSessionCreationPolicy property is set
internal bool IsSetPlayerSessionCreationPolicy()
{
return this._playerSessionCreationPolicy != null;
}
/// <summary>
/// Gets and sets the property ProtectionPolicy.
/// <para>
/// Game session protection policy to apply to this game session only.
/// </para>
/// <ul> <li>
/// <para>
/// <b>NoProtection</b> -- The game session can be terminated during a scale-down event.
/// </para>
/// </li> <li>
/// <para>
/// <b>FullProtection</b> -- If the game session is in an <code>ACTIVE</code> status,
/// it cannot be terminated during a scale-down event.
/// </para>
/// </li> </ul>
/// </summary>
public ProtectionPolicy ProtectionPolicy
{
get { return this._protectionPolicy; }
set { this._protectionPolicy = value; }
}
// Check to see if ProtectionPolicy property is set
internal bool IsSetProtectionPolicy()
{
return this._protectionPolicy != null;
}
}
} | 32.05641 | 107 | 0.577988 | [
"Apache-2.0"
] | Bio2hazard/aws-sdk-net | sdk/src/Services/GameLift/Generated/Model/UpdateGameSessionRequest.cs | 6,251 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Unity.MLAgents;
using Unity.MLAgents.Sensors;
public class DroneAgent : Agent
{
// public variables
[Header("Propeller motors")]
/// <summary>
/// Propeller component of front left propeller of the drone
/// </summary>
[Tooltip("Propeller component of front left propeller of the drone")]
public Propellers frontLeftPropeller;
/// <summary>
/// Propeller component of front right propeller of the drone
/// </summary>
[Tooltip("Propeller component of front right propeller of the drone")]
public Propellers frontRightPropeller;
/// <summary>
/// Propeller component of back left propeller of the drone
/// </summary>
[Tooltip("Propeller component of back left propeller of the drone")]
public Propellers backLeftPropeller;
/// <summary>
/// Propeller component of back right propeller of the drone
/// </summary>
[Tooltip("Propeller component of back right propeller of the drone")]
public Propellers backRightPropeller;
[Header("Movement Variables")]
[Tooltip("The amount the action should me multiplied")]
public float actionMultiplier;
// private variables
private Rigidbody rb;
EnvironmentParameters m_ResetParams;
/// <summary>
/// Called when the scene is initialied
/// </summary>
public override void Initialize()
{
base.Initialize();
rb = this.GetComponent<Rigidbody>();
m_ResetParams = Academy.Instance.EnvironmentParameters;
ResetParameters();
}
/// <summary>
/// Called when the episode begins
/// </summary>
public override void OnEpisodeBegin()
{
base.OnEpisodeBegin();
// reset parameters
ResetParameters();
}
/// <summary>
/// Collects the observations to the sensor and
/// transfers the observations to input of the neural networks
/// </summary>
/// <param name="sensor">The sensor component of the agent</param>
public override void CollectObservations(VectorSensor sensor)
{
base.CollectObservations(sensor);
sensor.AddObservation(1f);
// TODO: implement the observe the environment code
}
/// <summary>
/// Called when the decision maker makes a decision and get the vectorAction
/// from the output of the Neural Network.
/// The Index i of vectorAction represents:
/// Index 0: motor speed of leftFront motor (+1 = increase the speed, -1 decrease speed)
/// Index 1: motor speed of rightFront motor (+1 = increase the speed, -1 decrease speed)
/// Index 2: motor speed of leftBack motor (+1 = increase the speed, -1 decrease speed)
/// Index 3: motor speed of rightBack motor (+1 = increase the speed, -1 decrease speed)
/// </summary>
/// <param name="vectorAction">The actions to be follewed by the agent</param>
public override void OnActionReceived(float[] vectorAction)
{
base.OnActionReceived(vectorAction);
this.frontLeftPropeller.AddForce = vectorAction[0] * actionMultiplier;
this.frontRightPropeller.AddForce = vectorAction[1] * actionMultiplier;
this.backLeftPropeller.AddForce = vectorAction[2] * actionMultiplier;
this.backLeftPropeller.AddForce = vectorAction[3] * actionMultiplier;
}
/// <summary>
/// When behaviour type is set to "heuristic only" on the agent's Behaviour parameters,
/// this function will be called. Its return values will be fed into
/// <see cref="OnActionReceived(float[])"> instead of using the neural networks.
/// </summary>
/// <param name="actionsOut"></param>
public override void Heuristic(float[] actionsOut)
{
float altitude = 0f; // +1 = gain altitude, -1 = lose altitude
float yaw = 0f; // +1 = turn left, -1 = turn right
float pitch = 0f; // +1 to tilt forward, -1 to tilt backward
float roll = 0f; // +1 to roll left, -1 to tilt right
// press w to gain height or s to loss height
if (Input.GetKey(KeyCode.W))
{
altitude = 1f;
}
else if (Input.GetKey(KeyCode.S))
{
altitude = -1f;
}
// press a to turn left or d to turn right
if (Input.GetKey(KeyCode.A))
{
yaw = 1f;
}
else if (Input.GetKey(KeyCode.D))
{
yaw = -1f;
}
// press num 8 to tilt forward or num 2 to tilt backward
if (Input.GetKey(KeyCode.Keypad8))
{
pitch = 1;
}
else if (Input.GetKey(KeyCode.Keypad2))
{
pitch = -1;
}
// press num 4 to roll left or num 6 to roll right
if (Input.GetKey(KeyCode.Keypad4))
{
roll = 1;
}
else if (Input.GetKey(KeyCode.Keypad6))
{
roll = -1;
}
float frontLeft = 0f;
float frontRight = 0f;
float backLeft = 0f;
float backRight = 0f;
if (altitude > 0)
{
frontLeft += 0.25f;
frontRight += 0.25f;
backLeft += 0.25f;
backRight += 0.25f;
}
else if (altitude < 0)
{
frontLeft -= 0.25f;
frontRight -= 0.25f;
backLeft -= 0.25f;
backRight -= 0.25f;
}
if (yaw > 0)
{
frontLeft += !frontLeftPropeller.clockWise ? 0.25f : -0.25f;
frontRight += !frontRightPropeller.clockWise ? 0.25f : -0.25f;
backLeft += !backLeftPropeller.clockWise ? 0.25f : -0.25f;
backRight += !backRightPropeller.clockWise ? 0.25f : -0.25f;
}
else if (yaw < 0)
{
frontLeft += frontLeftPropeller.clockWise ? 0.25f : -0.25f;
frontRight += frontRightPropeller.clockWise ? 0.25f : -0.25f;
backLeft += backLeftPropeller.clockWise ? 0.25f : -0.25f;
backRight += backRightPropeller.clockWise ? 0.25f : -0.25f;
}
if (pitch > 0)
{
frontLeft -= 0.25f;
frontRight -= 0.25f;
backLeft += 0.25f;
backRight += 0.25f;
}
else if (pitch < 0)
{
frontLeft += 0.25f;
frontRight += 0.25f;
backLeft -= 0.25f;
backRight -= 0.25f;
}
if (roll > 0)
{
frontLeft -= 0.25f;
backLeft -= 0.25f;
frontRight += 0.25f;
backRight += 0.25f;
}
else if (roll < 0)
{
frontLeft += 0.25f;
backLeft += 0.25f;
frontRight -= 0.25f;
backRight -= 0.25f;
}
actionsOut[0] = frontLeft;
actionsOut[1] = frontRight;
actionsOut[2] = backLeft;
actionsOut[3] = backRight;
}
/// <summary>
/// Resets the parameters
/// </summary>
void ResetParameters()
{
ResetDrone();
ResetPhysics();
ResetPropellers();
}
/// <summary>
/// Resets the drone varaibles to previous possitions
/// </summary>
void ResetDrone()
{
this.rb.mass = m_ResetParams.GetWithDefault("mass", 0.2f);
this.rb.drag = m_ResetParams.GetWithDefault("drag", 0.2f);
this.rb.angularDrag = m_ResetParams.GetWithDefault("angular_drag", 0.1f);
this.rb.useGravity = true;
float scale = m_ResetParams.GetWithDefault("scale", 1f);
this.transform.localScale = new Vector3(scale, scale, scale);
this.transform.position = new Vector3(0f, 5f, 0f);
this.rb.rotation = Quaternion.identity;
this.rb.velocity = Vector3.zero;
this.rb.angularVelocity = Vector3.zero;
}
/// <summary>
/// Resets the physics varaibles of the scene
/// </summary>
void ResetPhysics()
{
Physics.gravity = new Vector3(0f, m_ResetParams.GetWithDefault("gravity", -9.81f), 0f);
Time.fixedDeltaTime = m_ResetParams.GetWithDefault("update_time", 0.02f);
}
/// <summary>
/// Resets the propeller varaibles
/// </summary>
void ResetPropellers()
{
bool leftDiagonal = 1 == m_ResetParams.GetWithDefault("left_diagonal", 1);
this.frontLeftPropeller.clockWise = leftDiagonal;
this.backRightPropeller.clockWise = leftDiagonal;
this.frontRightPropeller.clockWise = !leftDiagonal;
this.backLeftPropeller.clockWise = !leftDiagonal;
}
/// <summary>
/// Called when the collider of the gameobject detects a collision with other object
/// </summary>
/// <param name="other"></param>
private void OnCollisionEnter(Collision other)
{
Debug.Log("collided with some object. resetting the scene");
this.transform.position = new Vector3(0f, 5f, 0f);
this.rb.rotation = Quaternion.identity;
this.rb.velocity = Vector3.zero;
this.rb.angularVelocity = Vector3.zero;
}
}
| 31.393103 | 95 | 0.585457 | [
"MPL-2.0"
] | Hemanth759/Path-Finder-Drone | Autonomous Drone/Assets/Autonomous Drone/Scripts/AutonomousDrone/DroneAgent.cs | 9,106 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Web.Script.Serialization;
using System.Xml.Serialization;
using NewLife;
using NewLife.Data;
using NewLife.Log;
using NewLife.Model;
using NewLife.Reflection;
using NewLife.Remoting;
using NewLife.Threading;
using NewLife.Web;
using XCode;
using XCode.Cache;
using XCode.Configuration;
using XCode.DataAccessLayer;
using XCode.Membership;
using XCode.Shards;
namespace Company.MyName
{
/// <summary>用户。用户帐号信息</summary>
public partial class User : Entity<User>
{
#region 对象操作
static User()
{
// 累加字段,生成 Update xx Set Count=Count+1234 Where xxx
//var df = Meta.Factory.AdditionalFields;
//df.Add(nameof(Sex));
// 过滤器 UserModule、TimeModule、IPModule
Meta.Modules.Add<UserModule>();
Meta.Modules.Add<TimeModule>();
Meta.Modules.Add<IPModule>();
// 单对象缓存
var sc = Meta.SingleCache;
sc.FindSlaveKeyMethod = k => Find(_.Name == k);
sc.GetSlaveKeyMethod = e => e.Name;
}
/// <summary>验证并修补数据,通过抛出异常的方式提示验证失败。</summary>
/// <param name="isNew">是否插入</param>
public override void Valid(Boolean isNew)
{
// 如果没有脏数据,则不需要进行任何处理
if (!HasDirty) return;
// 这里验证参数范围,建议抛出参数异常,指定参数名,前端用户界面可以捕获参数异常并聚焦到对应的参数输入框
if (Name.IsNullOrEmpty()) throw new ArgumentNullException(nameof(Name), "名称不能为空!");
// 建议先调用基类方法,基类方法会做一些统一处理
base.Valid(isNew);
// 在新插入数据或者修改了指定字段时进行修正
// 处理当前已登录用户信息,可以由UserModule过滤器代劳
/*var user = ManageProvider.User;
if (user != null)
{
if (!Dirtys[nameof(UpdateUserID)]) UpdateUserID = user.ID;
}*/
//if (!Dirtys[nameof(UpdateTime)]) UpdateTime = DateTime.Now;
//if (!Dirtys[nameof(UpdateIP)]) UpdateIP = ManageProvider.UserHost;
// 检查唯一索引
// CheckExist(isNew, nameof(Name));
}
///// <summary>首次连接数据库时初始化数据,仅用于实体类重载,用户不应该调用该方法</summary>
//[EditorBrowsable(EditorBrowsableState.Never)]
//protected override void InitData()
//{
// // InitData一般用于当数据表没有数据时添加一些默认数据,该实体类的任何第一次数据库操作都会触发该方法,默认异步调用
// if (Meta.Session.Count > 0) return;
// if (XTrace.Debug) XTrace.WriteLine("开始初始化User[用户]数据……");
// var entity = new User();
// entity.Name = "abc";
// entity.Password = "abc";
// entity.DisplayName = "abc";
// entity.Sex = 0;
// entity.Mail = "abc";
// entity.Mobile = "abc";
// entity.Code = "abc";
// entity.AreaId = 0;
// entity.Avatar = "abc";
// entity.RoleID = 0;
// entity.RoleIds = "abc";
// entity.DepartmentID = 0;
// entity.Online = true;
// entity.Enable = true;
// entity.Age = 0;
// entity.Birthday = DateTime.Now;
// entity.Logins = 0;
// entity.LastLogin = DateTime.Now;
// entity.LastLoginIP = "abc";
// entity.RegisterTime = DateTime.Now;
// entity.RegisterIP = "abc";
// entity.OnlineTime = 0;
// entity.Ex1 = 0;
// entity.Ex2 = 0;
// entity.Ex3 = 0.0;
// entity.Ex4 = "abc";
// entity.Ex5 = "abc";
// entity.Ex6 = "abc";
// entity.UpdateUser = "abc";
// entity.UpdateUserID = 0;
// entity.UpdateIP = "abc";
// entity.UpdateTime = DateTime.Now;
// entity.Remark = "abc";
// entity.Insert();
// if (XTrace.Debug) XTrace.WriteLine("完成初始化User[用户]数据!");
//}
///// <summary>已重载。基类先调用Valid(true)验证数据,然后在事务保护内调用OnInsert</summary>
///// <returns></returns>
//public override Int32 Insert()
//{
// return base.Insert();
//}
///// <summary>已重载。在事务保护范围内处理业务,位于Valid之后</summary>
///// <returns></returns>
//protected override Int32 OnDelete()
//{
// return base.OnDelete();
//}
#endregion
#region 扩展属性
#endregion
#region 扩展查询
/// <summary>根据编号查找</summary>
/// <param name="id">编号</param>
/// <returns>实体对象</returns>
public static User FindByID(Int32 id)
{
if (id <= 0) return null;
// 实体缓存
if (Meta.Session.Count < 1000) return Meta.Cache.Find(e => e.ID == id);
// 单对象缓存
return Meta.SingleCache[id];
//return Find(_.ID == id);
}
/// <summary>根据名称查找</summary>
/// <param name="name">名称</param>
/// <returns>实体对象</returns>
public static User FindByName(String name)
{
// 实体缓存
if (Meta.Session.Count < 1000) return Meta.Cache.Find(e => e.Name.EqualIgnoreCase(name));
// 单对象缓存
//return Meta.SingleCache.GetItemWithSlaveKey(name) as User;
return Find(_.Name == name);
}
/// <summary>根据邮件查找</summary>
/// <param name="mail">邮件</param>
/// <returns>实体列表</returns>
public static IList<User> FindAllByMail(String mail)
{
// 实体缓存
if (Meta.Session.Count < 1000) return Meta.Cache.FindAll(e => e.Mail.EqualIgnoreCase(mail));
return FindAll(_.Mail == mail);
}
/// <summary>根据手机查找</summary>
/// <param name="mobile">手机</param>
/// <returns>实体列表</returns>
public static IList<User> FindAllByMobile(String mobile)
{
// 实体缓存
if (Meta.Session.Count < 1000) return Meta.Cache.FindAll(e => e.Mobile.EqualIgnoreCase(mobile));
return FindAll(_.Mobile == mobile);
}
/// <summary>根据代码查找</summary>
/// <param name="code">代码</param>
/// <returns>实体列表</returns>
public static IList<User> FindAllByCode(String code)
{
// 实体缓存
if (Meta.Session.Count < 1000) return Meta.Cache.FindAll(e => e.Code.EqualIgnoreCase(code));
return FindAll(_.Code == code);
}
/// <summary>根据角色查找</summary>
/// <param name="roleId">角色</param>
/// <returns>实体列表</returns>
public static IList<User> FindAllByRoleID(Int32 roleId)
{
// 实体缓存
if (Meta.Session.Count < 1000) return Meta.Cache.FindAll(e => e.RoleID == roleId);
return FindAll(_.RoleID == roleId);
}
#endregion
#region 高级查询
/// <summary>高级查询</summary>
/// <param name="name">名称。登录用户名</param>
/// <param name="mail">邮件</param>
/// <param name="mobile">手机</param>
/// <param name="code">代码。身份证、员工编号等</param>
/// <param name="roleId">角色。主要角色</param>
/// <param name="start">更新时间开始</param>
/// <param name="end">更新时间结束</param>
/// <param name="key">关键字</param>
/// <param name="page">分页参数信息。可携带统计和数据权限扩展查询等信息</param>
/// <returns>实体列表</returns>
public static IList<User> Search(String name, String mail, String mobile, String code, Int32 roleId, DateTime start, DateTime end, String key, PageParameter page)
{
var exp = new WhereExpression();
if (!name.IsNullOrEmpty()) exp &= _.Name == name;
if (!mail.IsNullOrEmpty()) exp &= _.Mail == mail;
if (!mobile.IsNullOrEmpty()) exp &= _.Mobile == mobile;
if (!code.IsNullOrEmpty()) exp &= _.Code == code;
if (roleId >= 0) exp &= _.RoleID == roleId;
exp &= _.UpdateTime.Between(start, end);
if (!key.IsNullOrEmpty()) exp &= _.Name.Contains(key) | _.Password.Contains(key) | _.DisplayName.Contains(key) | _.Mail.Contains(key) | _.Mobile.Contains(key) | _.Code.Contains(key) | _.Avatar.Contains(key) | _.RoleIds.Contains(key) | _.LastLoginIP.Contains(key) | _.RegisterIP.Contains(key) | _.Ex4.Contains(key) | _.Ex5.Contains(key) | _.Ex6.Contains(key) | _.UpdateUser.Contains(key) | _.UpdateIP.Contains(key) | _.Remark.Contains(key);
return FindAll(exp, page);
}
// Select Count(ID) as ID,Mail From User Where CreateTime>'2020-01-24 00:00:00' Group By Mail Order By ID Desc limit 20
static readonly FieldCache<User> _MailCache = new FieldCache<User>(nameof(Mail))
{
//Where = _.CreateTime > DateTime.Today.AddDays(-30) & Expression.Empty
};
/// <summary>获取邮件列表,字段缓存10分钟,分组统计数据最多的前20种,用于魔方前台下拉选择</summary>
/// <returns></returns>
public static IDictionary<String, String> GetMailList() => _MailCache.FindAllName();
// Select Count(ID) as ID,Mobile From User Where CreateTime>'2020-01-24 00:00:00' Group By Mobile Order By ID Desc limit 20
static readonly FieldCache<User> _MobileCache = new FieldCache<User>(nameof(Mobile))
{
//Where = _.CreateTime > DateTime.Today.AddDays(-30) & Expression.Empty
};
/// <summary>获取手机列表,字段缓存10分钟,分组统计数据最多的前20种,用于魔方前台下拉选择</summary>
/// <returns></returns>
public static IDictionary<String, String> GetMobileList() => _MobileCache.FindAllName();
// Select Count(ID) as ID,Code From User Where CreateTime>'2020-01-24 00:00:00' Group By Code Order By ID Desc limit 20
static readonly FieldCache<User> _CodeCache = new FieldCache<User>(nameof(Code))
{
//Where = _.CreateTime > DateTime.Today.AddDays(-30) & Expression.Empty
};
/// <summary>获取代码列表,字段缓存10分钟,分组统计数据最多的前20种,用于魔方前台下拉选择</summary>
/// <returns></returns>
public static IDictionary<String, String> GetCodeList() => _CodeCache.FindAllName();
#endregion
#region 业务操作
#endregion
}
} | 36.153025 | 451 | 0.564327 | [
"MIT"
] | qaz734913414/X | XUnitTest.XCode/Code/entity_user_normal_biz.cs | 11,479 | C# |
using System;
using System.Collections.Generic;
using NUnit.Framework;
using Google.Maps.StreetView;
using FluentAssertions.Collections;
using FluentAssertions;
using Google.Maps.Test;
namespace Google.Maps.StreetView
{
[TestFixture]
public class StreetView_uribuilding_Tests
{
Uri gmapsBaseUri = new Uri("http://maps.google.com/");
[Test]
public void BasicUri()
{
//arrange
var expected = Helpers.ParseQueryString("/maps/api/streetview?location=30.1,-60.2&size=512x512");
StreetViewRequest sm = new StreetViewRequest()
{
Location = new LatLng(30.1, -60.2)
,Size = new MapSize(512, 512)
};
//act
Uri actualUri = sm.ToUri();
var actual = Helpers.ParseQueryString(actualUri.PathAndQuery);
//assert
actual.ShouldAllBeEquivalentTo(expected);
}
[Test]
public void BasicUri_heading()
{
//arrange
var expected = Helpers.ParseQueryString("/maps/api/streetview?location=30.1,-60.2&size=512x512&heading=15");
StreetViewRequest sm = new StreetViewRequest()
{
Location = new LatLng(30.1, -60.2)
,Size = new MapSize(512, 512)
,Heading = 15
};
//act
Uri actualUri = sm.ToUri();
var actual = Helpers.ParseQueryString(actualUri.PathAndQuery);
//assert
actual.ShouldAllBeEquivalentTo(expected);
}
[Test]
public void BasicUri_pitch()
{
//arrange
var expected = Helpers.ParseQueryString("/maps/api/streetview?location=30.1,-60.2&size=512x512&pitch=15");
StreetViewRequest sm = new StreetViewRequest()
{
Location = new LatLng(30.1, -60.2)
,Size = new MapSize(512, 512)
,Pitch = 15
};
//act
Uri actualUri = sm.ToUri();
var actual = Helpers.ParseQueryString(actualUri.PathAndQuery);
//assert
actual.ShouldAllBeEquivalentTo(expected);
}
}
}
| 21.829268 | 111 | 0.689385 | [
"Apache-2.0"
] | AlexSkarbo/gmaps-api-net | src/Google.Maps.Test/StreetView/StreetView_uribuilding_Tests.cs | 1,792 | C# |
namespace ClassLib086
{
public class Class037
{
public static string Property => "ClassLib086";
}
}
| 15 | 55 | 0.633333 | [
"MIT"
] | 333fred/performance | src/scenarios/weblarge2.0/src/ClassLib086/Class037.cs | 120 | C# |
using System.Collections.ObjectModel;
namespace PaginaInicial.Areas.HelpPage.ModelDescriptions
{
public class ComplexTypeModelDescription : ModelDescription
{
public ComplexTypeModelDescription()
{
Properties = new Collection<ParameterDescription>();
}
public Collection<ParameterDescription> Properties { get; private set; }
}
} | 27.642857 | 80 | 0.70801 | [
"MIT"
] | esteban1991/TestAsp | PaginaInicial/Areas/HelpPage/ModelDescriptions/ComplexTypeModelDescription.cs | 387 | 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("RabbitDemo.Publisher")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("RabbitDemo.Publisher")]
[assembly: AssemblyCopyright("Copyright © Microsoft 2010")]
[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("825d48f0-e57b-46bb-ae06-5e852c202ed5")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 38.675676 | 84 | 0.749825 | [
"Apache-2.0"
] | code-attic/Symbiote | demo/Rabbit/RabbitDemo.Publisher/Properties/AssemblyInfo.cs | 1,434 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
namespace TickClock.Models.AccountViewModels
{
public class LoginWithRecoveryCodeViewModel
{
[Required]
[DataType(DataType.Text)]
[Display(Name = "Recovery Code")]
public string RecoveryCode { get; set; }
}
}
| 23.352941 | 48 | 0.712846 | [
"Apache-2.0"
] | sonia1013/TickClock | TickClock/Models/AccountViewModels/LoginWithRecoveryCodeViewModel.cs | 399 | C# |
using Foundation;
using UIKit;
namespace TexturedCubeiOS
{
[Register ("AppDelegate")]
public class AppDelegate : UIApplicationDelegate
{
public override UIWindow Window { get; set; }
}
}
| 16.166667 | 49 | 0.747423 | [
"Apache-2.0"
] | G3r3rd/mobile-samples | TexturedCubeES30/TexturedCubeiOS/AppDelegate.cs | 194 | C# |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the MIT license. See License.txt in the project root for license information.
namespace FunctionalTests.Model
{
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel.DataAnnotations;
public class Product
{
public virtual int ProductID { get; set; }
public virtual string Name { get; set; }
public virtual string ProductNumber { get; set; }
public virtual bool MakeFlag { get; set; }
public virtual bool FinishedGoodsFlag { get; set; }
public virtual short SafetyStockLevel { get; set; }
public virtual short ReorderPoint { get; set; }
public virtual decimal StandardCost { get; set; }
public virtual decimal ListPrice { get; set; }
public virtual string Size { get; set; }
public virtual decimal? Weight { get; set; }
public virtual int DaysToManufacture { get; set; }
public virtual string ProductLine { get; set; }
public virtual string Class { get; set; }
public virtual int? ProductSubcategoryID
{
get { return _productSubcategoryID; }
set
{
try
{
_settingFK = true;
if (_productSubcategoryID != value)
{
if (ProductSubcategory != null
&& ProductSubcategory.ProductSubcategoryID != value)
{
ProductSubcategory = null;
}
_productSubcategoryID = value;
}
}
finally
{
_settingFK = false;
}
}
}
private int? _productSubcategoryID;
public virtual int? ProductModelID
{
get { return _productModelID; }
set
{
try
{
_settingFK = true;
if (_productModelID != value)
{
if (ProductModel != null
&& ProductModel.ProductModelID != value)
{
ProductModel = null;
}
_productModelID = value;
}
}
finally
{
_settingFK = false;
}
}
}
private int? _productModelID;
public virtual DateTime SellStartDate { get; set; }
[Required]
public virtual DateTime? SellEndDate { get; set; }
public virtual Guid rowguid { get; set; }
public virtual DateTime ModifiedDate { get; set; }
public virtual ICollection<BillOfMaterials> BillOfMaterials
{
get
{
if (_billOfMaterials == null)
{
var newCollection = new FixupCollection<BillOfMaterials>();
newCollection.CollectionChanged += FixupBillOfMaterials;
_billOfMaterials = newCollection;
}
return _billOfMaterials;
}
set
{
if (!ReferenceEquals(_billOfMaterials, value))
{
var previousValue = _billOfMaterials as FixupCollection<BillOfMaterials>;
if (previousValue != null)
{
previousValue.CollectionChanged -= FixupBillOfMaterials;
}
_billOfMaterials = value;
var newValue = value as FixupCollection<BillOfMaterials>;
if (newValue != null)
{
newValue.CollectionChanged += FixupBillOfMaterials;
}
}
}
}
private ICollection<BillOfMaterials> _billOfMaterials;
public virtual ICollection<BillOfMaterials> BillOfMaterials1
{
get
{
if (_billOfMaterials1 == null)
{
var newCollection = new FixupCollection<BillOfMaterials>();
newCollection.CollectionChanged += FixupBillOfMaterials1;
_billOfMaterials1 = newCollection;
}
return _billOfMaterials1;
}
set
{
if (!ReferenceEquals(_billOfMaterials1, value))
{
var previousValue = _billOfMaterials1 as FixupCollection<BillOfMaterials>;
if (previousValue != null)
{
previousValue.CollectionChanged -= FixupBillOfMaterials1;
}
_billOfMaterials1 = value;
var newValue = value as FixupCollection<BillOfMaterials>;
if (newValue != null)
{
newValue.CollectionChanged += FixupBillOfMaterials1;
}
}
}
}
private ICollection<BillOfMaterials> _billOfMaterials1;
public virtual ProductModel ProductModel
{
get { return _productModel; }
set
{
if (!ReferenceEquals(_productModel, value))
{
var previousValue = _productModel;
_productModel = value;
FixupProductModel(previousValue);
}
}
}
private ProductModel _productModel;
public virtual ProductSubcategory ProductSubcategory
{
get { return _productSubcategory; }
set
{
if (!ReferenceEquals(_productSubcategory, value))
{
var previousValue = _productSubcategory;
_productSubcategory = value;
FixupProductSubcategory(previousValue);
}
}
}
private ProductSubcategory _productSubcategory;
public virtual UnitMeasure SizeUnitMeasure { get; set; }
public virtual UnitMeasure WeightUnitMeasure { get; set; }
public virtual ICollection<ProductCostHistory> ProductCostHistories
{
get
{
if (_productCostHistories == null)
{
var newCollection = new FixupCollection<ProductCostHistory>();
newCollection.CollectionChanged += FixupProductCostHistories;
_productCostHistories = newCollection;
}
return _productCostHistories;
}
set
{
if (!ReferenceEquals(_productCostHistories, value))
{
var previousValue = _productCostHistories as FixupCollection<ProductCostHistory>;
if (previousValue != null)
{
previousValue.CollectionChanged -= FixupProductCostHistories;
}
_productCostHistories = value;
var newValue = value as FixupCollection<ProductCostHistory>;
if (newValue != null)
{
newValue.CollectionChanged += FixupProductCostHistories;
}
}
}
}
private ICollection<ProductCostHistory> _productCostHistories;
public virtual ICollection<ProductDocument> ProductDocuments
{
get
{
if (_productDocuments == null)
{
var newCollection = new FixupCollection<ProductDocument>();
newCollection.CollectionChanged += FixupProductDocuments;
_productDocuments = newCollection;
}
return _productDocuments;
}
set
{
if (!ReferenceEquals(_productDocuments, value))
{
var previousValue = _productDocuments as FixupCollection<ProductDocument>;
if (previousValue != null)
{
previousValue.CollectionChanged -= FixupProductDocuments;
}
_productDocuments = value;
var newValue = value as FixupCollection<ProductDocument>;
if (newValue != null)
{
newValue.CollectionChanged += FixupProductDocuments;
}
}
}
}
private ICollection<ProductDocument> _productDocuments;
public virtual ICollection<ProductInventory> ProductInventories
{
get
{
if (_productInventories == null)
{
var newCollection = new FixupCollection<ProductInventory>();
newCollection.CollectionChanged += FixupProductInventories;
_productInventories = newCollection;
}
return _productInventories;
}
set
{
if (!ReferenceEquals(_productInventories, value))
{
var previousValue = _productInventories as FixupCollection<ProductInventory>;
if (previousValue != null)
{
previousValue.CollectionChanged -= FixupProductInventories;
}
_productInventories = value;
var newValue = value as FixupCollection<ProductInventory>;
if (newValue != null)
{
newValue.CollectionChanged += FixupProductInventories;
}
}
}
}
private ICollection<ProductInventory> _productInventories;
public virtual ICollection<ProductListPriceHistory> ProductListPriceHistories
{
get
{
if (_productListPriceHistories == null)
{
var newCollection = new FixupCollection<ProductListPriceHistory>();
newCollection.CollectionChanged += FixupProductListPriceHistories;
_productListPriceHistories = newCollection;
}
return _productListPriceHistories;
}
set
{
if (!ReferenceEquals(_productListPriceHistories, value))
{
var previousValue = _productListPriceHistories as FixupCollection<ProductListPriceHistory>;
if (previousValue != null)
{
previousValue.CollectionChanged -= FixupProductListPriceHistories;
}
_productListPriceHistories = value;
var newValue = value as FixupCollection<ProductListPriceHistory>;
if (newValue != null)
{
newValue.CollectionChanged += FixupProductListPriceHistories;
}
}
}
}
private ICollection<ProductListPriceHistory> _productListPriceHistories;
public virtual ICollection<ProductProductPhoto> ProductProductPhotoes
{
get
{
if (_productProductPhotoes == null)
{
var newCollection = new FixupCollection<ProductProductPhoto>();
newCollection.CollectionChanged += FixupProductProductPhotoes;
_productProductPhotoes = newCollection;
}
return _productProductPhotoes;
}
set
{
if (!ReferenceEquals(_productProductPhotoes, value))
{
var previousValue = _productProductPhotoes as FixupCollection<ProductProductPhoto>;
if (previousValue != null)
{
previousValue.CollectionChanged -= FixupProductProductPhotoes;
}
_productProductPhotoes = value;
var newValue = value as FixupCollection<ProductProductPhoto>;
if (newValue != null)
{
newValue.CollectionChanged += FixupProductProductPhotoes;
}
}
}
}
private ICollection<ProductProductPhoto> _productProductPhotoes;
public virtual ICollection<ProductReview> ProductReviews
{
get
{
if (_productReviews == null)
{
var newCollection = new FixupCollection<ProductReview>();
newCollection.CollectionChanged += FixupProductReviews;
_productReviews = newCollection;
}
return _productReviews;
}
set
{
if (!ReferenceEquals(_productReviews, value))
{
var previousValue = _productReviews as FixupCollection<ProductReview>;
if (previousValue != null)
{
previousValue.CollectionChanged -= FixupProductReviews;
}
_productReviews = value;
var newValue = value as FixupCollection<ProductReview>;
if (newValue != null)
{
newValue.CollectionChanged += FixupProductReviews;
}
}
}
}
private ICollection<ProductReview> _productReviews;
public virtual ICollection<ProductVendor> ProductVendors
{
get
{
if (_productVendors == null)
{
var newCollection = new FixupCollection<ProductVendor>();
newCollection.CollectionChanged += FixupProductVendors;
_productVendors = newCollection;
}
return _productVendors;
}
set
{
if (!ReferenceEquals(_productVendors, value))
{
var previousValue = _productVendors as FixupCollection<ProductVendor>;
if (previousValue != null)
{
previousValue.CollectionChanged -= FixupProductVendors;
}
_productVendors = value;
var newValue = value as FixupCollection<ProductVendor>;
if (newValue != null)
{
newValue.CollectionChanged += FixupProductVendors;
}
}
}
}
private ICollection<ProductVendor> _productVendors;
public virtual ICollection<PurchaseOrderDetail> PurchaseOrderDetails
{
get
{
if (_purchaseOrderDetails == null)
{
var newCollection = new FixupCollection<PurchaseOrderDetail>();
newCollection.CollectionChanged += FixupPurchaseOrderDetails;
_purchaseOrderDetails = newCollection;
}
return _purchaseOrderDetails;
}
set
{
if (!ReferenceEquals(_purchaseOrderDetails, value))
{
var previousValue = _purchaseOrderDetails as FixupCollection<PurchaseOrderDetail>;
if (previousValue != null)
{
previousValue.CollectionChanged -= FixupPurchaseOrderDetails;
}
_purchaseOrderDetails = value;
var newValue = value as FixupCollection<PurchaseOrderDetail>;
if (newValue != null)
{
newValue.CollectionChanged += FixupPurchaseOrderDetails;
}
}
}
}
private ICollection<PurchaseOrderDetail> _purchaseOrderDetails;
public virtual ICollection<ShoppingCartItem> ShoppingCartItems
{
get
{
if (_shoppingCartItems == null)
{
var newCollection = new FixupCollection<ShoppingCartItem>();
newCollection.CollectionChanged += FixupShoppingCartItems;
_shoppingCartItems = newCollection;
}
return _shoppingCartItems;
}
set
{
if (!ReferenceEquals(_shoppingCartItems, value))
{
var previousValue = _shoppingCartItems as FixupCollection<ShoppingCartItem>;
if (previousValue != null)
{
previousValue.CollectionChanged -= FixupShoppingCartItems;
}
_shoppingCartItems = value;
var newValue = value as FixupCollection<ShoppingCartItem>;
if (newValue != null)
{
newValue.CollectionChanged += FixupShoppingCartItems;
}
}
}
}
private ICollection<ShoppingCartItem> _shoppingCartItems;
public virtual ICollection<SpecialOfferProduct> SpecialOfferProducts
{
get
{
if (_specialOfferProducts == null)
{
var newCollection = new FixupCollection<SpecialOfferProduct>();
newCollection.CollectionChanged += FixupSpecialOfferProducts;
_specialOfferProducts = newCollection;
}
return _specialOfferProducts;
}
set
{
if (!ReferenceEquals(_specialOfferProducts, value))
{
var previousValue = _specialOfferProducts as FixupCollection<SpecialOfferProduct>;
if (previousValue != null)
{
previousValue.CollectionChanged -= FixupSpecialOfferProducts;
}
_specialOfferProducts = value;
var newValue = value as FixupCollection<SpecialOfferProduct>;
if (newValue != null)
{
newValue.CollectionChanged += FixupSpecialOfferProducts;
}
}
}
}
private ICollection<SpecialOfferProduct> _specialOfferProducts;
public virtual ICollection<TransactionHistory> TransactionHistories
{
get
{
if (_transactionHistories == null)
{
var newCollection = new FixupCollection<TransactionHistory>();
newCollection.CollectionChanged += FixupTransactionHistories;
_transactionHistories = newCollection;
}
return _transactionHistories;
}
set
{
if (!ReferenceEquals(_transactionHistories, value))
{
var previousValue = _transactionHistories as FixupCollection<TransactionHistory>;
if (previousValue != null)
{
previousValue.CollectionChanged -= FixupTransactionHistories;
}
_transactionHistories = value;
var newValue = value as FixupCollection<TransactionHistory>;
if (newValue != null)
{
newValue.CollectionChanged += FixupTransactionHistories;
}
}
}
}
private ICollection<TransactionHistory> _transactionHistories;
public virtual ICollection<WorkOrder> WorkOrders
{
get
{
if (_workOrders == null)
{
var newCollection = new FixupCollection<WorkOrder>();
newCollection.CollectionChanged += FixupWorkOrders;
_workOrders = newCollection;
}
return _workOrders;
}
set
{
if (!ReferenceEquals(_workOrders, value))
{
var previousValue = _workOrders as FixupCollection<WorkOrder>;
if (previousValue != null)
{
previousValue.CollectionChanged -= FixupWorkOrders;
}
_workOrders = value;
var newValue = value as FixupCollection<WorkOrder>;
if (newValue != null)
{
newValue.CollectionChanged += FixupWorkOrders;
}
}
}
}
private ICollection<WorkOrder> _workOrders;
private bool _settingFK;
private void FixupProductModel(ProductModel previousValue)
{
if (previousValue != null
&& previousValue.Products.Contains(this))
{
previousValue.Products.Remove(this);
}
if (ProductModel != null)
{
if (!ProductModel.Products.Contains(this))
{
ProductModel.Products.Add(this);
}
if (ProductModelID != ProductModel.ProductModelID)
{
ProductModelID = ProductModel.ProductModelID;
}
}
else if (!_settingFK)
{
ProductModelID = null;
}
}
private void FixupProductSubcategory(ProductSubcategory previousValue)
{
if (previousValue != null
&& previousValue.Products.Contains(this))
{
previousValue.Products.Remove(this);
}
if (ProductSubcategory != null)
{
if (!ProductSubcategory.Products.Contains(this))
{
ProductSubcategory.Products.Add(this);
}
if (ProductSubcategoryID != ProductSubcategory.ProductSubcategoryID)
{
ProductSubcategoryID = ProductSubcategory.ProductSubcategoryID;
}
}
else if (!_settingFK)
{
ProductSubcategoryID = null;
}
}
private void FixupBillOfMaterials(object sender, NotifyCollectionChangedEventArgs e)
{
if (e.NewItems != null)
{
foreach (BillOfMaterials item in e.NewItems)
{
item.Product = this;
}
}
if (e.OldItems != null)
{
foreach (BillOfMaterials item in e.OldItems)
{
if (ReferenceEquals(item.Product, this))
{
item.Product = null;
}
}
}
}
private void FixupBillOfMaterials1(object sender, NotifyCollectionChangedEventArgs e)
{
if (e.NewItems != null)
{
foreach (BillOfMaterials item in e.NewItems)
{
item.Product1 = this;
}
}
if (e.OldItems != null)
{
foreach (BillOfMaterials item in e.OldItems)
{
if (ReferenceEquals(item.Product1, this))
{
item.Product1 = null;
}
}
}
}
private void FixupProductCostHistories(object sender, NotifyCollectionChangedEventArgs e)
{
if (e.NewItems != null)
{
foreach (ProductCostHistory item in e.NewItems)
{
item.Product = this;
}
}
if (e.OldItems != null)
{
foreach (ProductCostHistory item in e.OldItems)
{
if (ReferenceEquals(item.Product, this))
{
item.Product = null;
}
}
}
}
private void FixupProductDocuments(object sender, NotifyCollectionChangedEventArgs e)
{
if (e.NewItems != null)
{
foreach (ProductDocument item in e.NewItems)
{
item.Product = this;
}
}
if (e.OldItems != null)
{
foreach (ProductDocument item in e.OldItems)
{
if (ReferenceEquals(item.Product, this))
{
item.Product = null;
}
}
}
}
private void FixupProductInventories(object sender, NotifyCollectionChangedEventArgs e)
{
if (e.NewItems != null)
{
foreach (ProductInventory item in e.NewItems)
{
item.Product = this;
}
}
if (e.OldItems != null)
{
foreach (ProductInventory item in e.OldItems)
{
if (ReferenceEquals(item.Product, this))
{
item.Product = null;
}
}
}
}
private void FixupProductListPriceHistories(object sender, NotifyCollectionChangedEventArgs e)
{
if (e.NewItems != null)
{
foreach (ProductListPriceHistory item in e.NewItems)
{
item.Product = this;
}
}
if (e.OldItems != null)
{
foreach (ProductListPriceHistory item in e.OldItems)
{
if (ReferenceEquals(item.Product, this))
{
item.Product = null;
}
}
}
}
private void FixupProductProductPhotoes(object sender, NotifyCollectionChangedEventArgs e)
{
if (e.NewItems != null)
{
foreach (ProductProductPhoto item in e.NewItems)
{
item.Product = this;
}
}
if (e.OldItems != null)
{
foreach (ProductProductPhoto item in e.OldItems)
{
if (ReferenceEquals(item.Product, this))
{
item.Product = null;
}
}
}
}
private void FixupProductReviews(object sender, NotifyCollectionChangedEventArgs e)
{
if (e.NewItems != null)
{
foreach (ProductReview item in e.NewItems)
{
item.Product = this;
}
}
if (e.OldItems != null)
{
foreach (ProductReview item in e.OldItems)
{
if (ReferenceEquals(item.Product, this))
{
item.Product = null;
}
}
}
}
private void FixupProductVendors(object sender, NotifyCollectionChangedEventArgs e)
{
if (e.NewItems != null)
{
foreach (ProductVendor item in e.NewItems)
{
item.Product = this;
}
}
if (e.OldItems != null)
{
foreach (ProductVendor item in e.OldItems)
{
if (ReferenceEquals(item.Product, this))
{
item.Product = null;
}
}
}
}
private void FixupPurchaseOrderDetails(object sender, NotifyCollectionChangedEventArgs e)
{
if (e.NewItems != null)
{
foreach (PurchaseOrderDetail item in e.NewItems)
{
item.Product = this;
}
}
if (e.OldItems != null)
{
foreach (PurchaseOrderDetail item in e.OldItems)
{
if (ReferenceEquals(item.Product, this))
{
item.Product = null;
}
}
}
}
private void FixupShoppingCartItems(object sender, NotifyCollectionChangedEventArgs e)
{
if (e.NewItems != null)
{
foreach (ShoppingCartItem item in e.NewItems)
{
item.Product = this;
}
}
if (e.OldItems != null)
{
foreach (ShoppingCartItem item in e.OldItems)
{
if (ReferenceEquals(item.Product, this))
{
item.Product = null;
}
}
}
}
private void FixupSpecialOfferProducts(object sender, NotifyCollectionChangedEventArgs e)
{
if (e.NewItems != null)
{
foreach (SpecialOfferProduct item in e.NewItems)
{
item.Product = this;
}
}
if (e.OldItems != null)
{
foreach (SpecialOfferProduct item in e.OldItems)
{
if (ReferenceEquals(item.Product, this))
{
item.Product = null;
}
}
}
}
private void FixupTransactionHistories(object sender, NotifyCollectionChangedEventArgs e)
{
if (e.NewItems != null)
{
foreach (TransactionHistory item in e.NewItems)
{
item.Product = this;
}
}
if (e.OldItems != null)
{
foreach (TransactionHistory item in e.OldItems)
{
if (ReferenceEquals(item.Product, this))
{
item.Product = null;
}
}
}
}
private void FixupWorkOrders(object sender, NotifyCollectionChangedEventArgs e)
{
if (e.NewItems != null)
{
foreach (WorkOrder item in e.NewItems)
{
item.Product = this;
}
}
if (e.OldItems != null)
{
foreach (WorkOrder item in e.OldItems)
{
if (ReferenceEquals(item.Product, this))
{
item.Product = null;
}
}
}
}
}
}
| 33.458897 | 144 | 0.460378 | [
"MIT"
] | dotnet/ef6tools | test/EntityFramework/FunctionalTests.Transitional/TestModels/StoreModel/Product.cs | 32,154 | C# |
using Microsoft.EntityFrameworkCore.Scaffolding.Metadata;
using NUnit.Framework;
using RevEng.Core;
using RevEng.Shared;
using System.Collections.Generic;
using System.Reflection;
namespace UnitTests.Services
{
[TestFixture]
public class ReplacingCandidateNamingServiceTests
{
[Test]
public void GeneratePascalCaseTableNameWithSchemaName()
{
//Arrange
var expected = "MachineAlertUi";
var exampleOption = new List<Schema>
{
new Schema
{
SchemaName = "machine",
UseSchemaName = true
}
};
var sut = new ReplacingCandidateNamingService(exampleOption);
var exampleDbTable = new DatabaseTable
{
Name = "alert_ui",
Schema = "machine"
};
// Act
var result = sut.GenerateCandidateIdentifier(exampleDbTable);
//Assert
StringAssert.Contains(expected, result);
}
[Test]
public void GeneratePascalCaseTableNameWithSchemaNameWithMoreThanTwoSchemas()
{
//Arrange
var expected = "MachineAlertUi";
var exampleOption = new List<Schema>
{
new Schema
{
SchemaName = "machine",
UseSchemaName = true
},
new Schema
{
SchemaName = "master",
UseSchemaName = true
}
};
var sut = new ReplacingCandidateNamingService(exampleOption);
var exampleDbTable = new DatabaseTable
{
Name = "alert_ui",
Schema = "machine"
};
// Act
var result = sut.GenerateCandidateIdentifier(exampleDbTable);
//Assert
StringAssert.Contains(expected, result);
}
[Test]
public void GeneratePascalCaseTableNameWithSchemaNameWithMoreThanTwoSchemasForTableCollection()
{
//Arrange
var expected = "MachineAlertUi";
var expected2 = "MachineMeasure";
var expected3 = "MasterMeasure";
var expected4 = "DboWorkType";
var exampleOption = new List<Schema>
{
new Schema
{
SchemaName = "machine",
UseSchemaName = true
},
new Schema
{
SchemaName = "master",
UseSchemaName = true
},
new Schema
{
SchemaName = "dbo",
UseSchemaName = true,
Tables = new List<TableRenamer>{ new TableRenamer { Name = "work_type"} }
}
};
var sut = new ReplacingCandidateNamingService(exampleOption);
var exampleDbTables = new List<DatabaseTable>
{
new DatabaseTable {
Name = "alert_ui",
Schema = "machine"
},
new DatabaseTable {
Name = "measure",
Schema = "machine"
},
new DatabaseTable {
Name = "measure",
Schema = "master"
},
new DatabaseTable {
Name = "work_type",
Schema = "dbo"
}
};
// Act
List<string> results = new List<string>();
foreach (var table in exampleDbTables)
{
results.Add(sut.GenerateCandidateIdentifier(table));
}
//Assert
StringAssert.Contains(expected, results[0]);
StringAssert.Contains(expected2, results[1]);
StringAssert.Contains(expected3, results[2]);
StringAssert.Contains(expected4, results[3]);
}
[Test]
public void Issue_354()
{
//Arrange
var exampleOption = new List<Schema>
{
new Schema
{
SchemaName = "stg",
UseSchemaName = false,
Tables = new List<TableRenamer>
{
new TableRenamer
{
Name = "Jobs",
NewName = "stg_Jobs",
Columns = new List<ColumnNamer>
{
new ColumnNamer
{
Name = "JobName",
NewName = "JobRename",
}
}
},
new TableRenamer { Name = "DeliveryAddress", NewName = "stg_DeliveryAddress" }
}
},
};
var sut = new ReplacingCandidateNamingService(exampleOption);
var exampleDbTables = new List<DatabaseTable>
{
new DatabaseTable {
Name = "DeliveryAddress",
Schema = "stg"
},
new DatabaseTable {
Name = "Jobs",
Schema = "stg"
},
};
// Act
var results = new List<string>();
foreach (var table in exampleDbTables)
{
results.Add(sut.GenerateCandidateIdentifier(table));
}
//Assert
StringAssert.AreEqualIgnoringCase("stg_Jobs", results[1]);
StringAssert.AreEqualIgnoringCase("stg_DeliveryAddress", results[0]);
}
[Test]
public void GeneratePascalCaseTableNameWithMoreThanTwoSchemasForTableCollection()
{
//Arrange
var expected = "MachineAlertUi";
var expected2 = "MachineMeasure";
var expected3 = "MasterMeasure";
var expected4 = "WorkCell";
var expected5 = "DifferentTable";
var exampleOption = new List<Schema>
{
new Schema
{
SchemaName = "machine",
UseSchemaName = true
},
new Schema
{
SchemaName = "master",
UseSchemaName = true
},
new Schema
{
SchemaName = "dbo",
UseSchemaName = false
}
};
var sut = new ReplacingCandidateNamingService(exampleOption);
var exampleDbTables = new List<DatabaseTable>
{
new DatabaseTable {
Name = "alert_ui",
Schema = "machine"
},
new DatabaseTable {
Name = "measure",
Schema = "machine"
},
new DatabaseTable {
Name = "measure",
Schema = "master"
},
new DatabaseTable {
Name = "work_cell",
Schema = "dbo"
},
new DatabaseTable {
Name = "different_table",
Schema = "other"
}
};
// Act
List<string> results = new List<string>();
foreach (var table in exampleDbTables)
{
results.Add(sut.GenerateCandidateIdentifier(table));
}
//Assert
StringAssert.Contains(expected, results[0]);
StringAssert.Contains(expected2, results[1]);
StringAssert.Contains(expected3, results[2]);
StringAssert.Contains(expected4, results[3]);
StringAssert.Contains(expected5, results[4]);
}
[Test]
public void GenerateCustomTableNameFromJson()
{
//Arrange
var expected = "new_name_of_the_table";
var exampleOption = new List<Schema>
{
new Schema
{
SchemaName = "machine",
Tables = new List<TableRenamer>
{
new TableRenamer{
NewName = "new_name_of_the_table",
Name = "OldTableName",
}
}
}
};
var sut = new ReplacingCandidateNamingService(exampleOption);
var exampleDbTable = new DatabaseTable
{
Name = "OldTableName",
Schema = "machine"
};
// Act
var result = sut.GenerateCandidateIdentifier(exampleDbTable);
//Assert
StringAssert.Contains(expected, result);
}
[Test]
public void GenerateCustomTableNameFromJsonWithTableCollection()
{
//Arrange
var expected = "new_name_of_the_table";
var expected1 = "AlertUi";
var expected2 = "WorkType";
var exampleOption = new List<Schema>
{
new Schema
{
SchemaName = "machine",
Tables = new List<TableRenamer>
{
new TableRenamer{
NewName = "new_name_of_the_table",
Name = "OldTableName"
}
}
}
};
var sut = new ReplacingCandidateNamingService(exampleOption);
var exampleDbTables = new List<DatabaseTable>
{
new DatabaseTable
{
Name = "OldTableName",
Schema = "machine"
},
new DatabaseTable{
Name = "alert_ui",
Schema = "machine"
},
new DatabaseTable{
Name = "WorkType",
Schema = "dbo"
}
};
var result = new List<string>();
// Act
foreach (var exmapleTable in exampleDbTables)
{
result.Add(sut.GenerateCandidateIdentifier(exmapleTable));
}
//Assert
StringAssert.Contains(expected, result[0]);
StringAssert.Contains(expected1, result[1]);
StringAssert.Contains(expected2, result[2]);
}
[Test]
public void GenerateColumnNameFromJson()
{
//Arrange
var exampleColumn = new DatabaseColumn
{
Name = "OldDummyColumnName",
Table = new DatabaseTable
{
Name = "table_name",
Schema = "machine"
}
};
var expected = "NewDummyColumnName";
var exampleOption = new List<Schema>
{
new Schema
{
SchemaName = "machine",
UseSchemaName = true,
Tables = new List<TableRenamer>
{
new TableRenamer
{
Name = "table_name",
Columns = new List<ColumnNamer>
{
new ColumnNamer
{
Name = "OldDummyColumnName",
NewName = "NewDummyColumnName"
}
}
}
}
}
};
var sut = new ReplacingCandidateNamingService(exampleOption);
//Act
var actResult = sut.GenerateCandidateIdentifier(exampleColumn);
//Assert
StringAssert.Contains(expected, actResult);
}
[Test]
public void GenerateColumnNameInStandarNamingConvention()
{
//Arrange
var exampleColumn = new DatabaseColumn
{
Name = "column_name_to_rename",
Table = new DatabaseTable
{
Name = "table_name",
Schema = "dbo"
}
};
var expected = "ColumnNameToRename";
var exampleOption = new List<Schema>
{
new Schema
{
SchemaName = "machine",
UseSchemaName = true,
Tables = new List<TableRenamer>
{
new TableRenamer
{
Name = "table_name",
Columns = new List<ColumnNamer>
{
new ColumnNamer
{
Name = "OldDummyColumnName",
NewName = "NewDummyColumnName"
}
}
}
}
}
};
var sut = new ReplacingCandidateNamingService(exampleOption);
//Act
var actResult = sut.GenerateCandidateIdentifier(exampleColumn);
//Assert
StringAssert.Contains(expected, actResult);
}
[Test]
public void ChangeColumnNameToCustom()
{
//Arrange
var exampleColumns = new List<DatabaseColumn>
{
new DatabaseColumn{
Name = "column_name_to_rename",
Table = new DatabaseTable
{
Name = "table_name",
Schema = "dbo"
}
},
new DatabaseColumn{
Name = "measure",
Table = new DatabaseTable
{
Name = "table_name",
Schema = "machine"
}
}
};
var expected = "SomethingCustom";
var expected1 = "Measure";
var exampleOption = new List<Schema>
{
new Schema
{
SchemaName = "machine",
UseSchemaName = true,
Tables = new List<TableRenamer>
{
new TableRenamer
{
Name = "table_name",
Columns = new List<ColumnNamer>
{
new ColumnNamer
{
Name = "OldDummyColumnName",
NewName = "NewDummyColumnName"
}
}
}
}
},
new Schema
{
SchemaName = "dbo",
UseSchemaName = false,
Tables = new List<TableRenamer>
{
new TableRenamer
{
Name = "table_name",
Columns = new List<ColumnNamer>
{
new ColumnNamer
{
Name = "column_name_to_rename",
NewName = "SomethingCustom"
}
}
}
}
}
};
var sut = new ReplacingCandidateNamingService(exampleOption);
//Act
var actResult = new List<string>();
foreach (var column in exampleColumns)
{
actResult.Add(sut.GenerateCandidateIdentifier(column));
}
//Assert
StringAssert.Contains(expected, actResult[0]);
StringAssert.Contains(expected1, actResult[1]);
}
/// <summary>
/// Testing the table renaming method using Regex
/// </summary>
[Test]
public void GenerateCustomTableNameFromJsonUsingRegexRenaming()
{
//Arrange
var expected = "NewTableName";
var exampleOption = new List<Schema>
{
new Schema
{
SchemaName = "dbo",
TableRegexPattern = "^Old",
TablePatternReplaceWith = "New"
}
};
var sut = new ReplacingCandidateNamingService(exampleOption);
var exampleDbTable = new DatabaseTable
{
Name = "OldTableName",
Schema = "dbo"
};
// Act
var result = sut.GenerateCandidateIdentifier(exampleDbTable);
//Assert
StringAssert.Contains(expected, result);
}
/// <summary>
/// This is to guarantee that the renaming using regex does not overwrite the current table renaming method
/// </summary>
[Test]
public void GenerateCustomTableNameFromJsonUsingRegexRenamingOverwritten()
{
//Arrange
var expected = "TableNameNotOverwritten";
var exampleOption = new List<Schema>
{
new Schema
{
SchemaName = "dbo",
TableRegexPattern = "^Old",
TablePatternReplaceWith = "New",
Tables = new List<TableRenamer>
{
new TableRenamer{
NewName = "TableNameNotOverwritten",
Name = "OldTableName",
}
}
}
};
var sut = new ReplacingCandidateNamingService(exampleOption);
var exampleDbTable = new DatabaseTable
{
Name = "OldTableName",
Schema = "dbo"
};
// Act
var result = sut.GenerateCandidateIdentifier(exampleDbTable);
//Assert
StringAssert.Contains(expected, result);
}
/// <summary>
/// Testing the column renaming method using Regex
/// </summary>
[Test]
public void GenerateCustomColumnNameFromJsonUsingRegexRenaming()
{
//Arrange
var exampleColumn = new DatabaseColumn
{
Name = "OldColumnName",
Table = new DatabaseTable
{
Name = "table_name",
Schema = "dbo"
}
};
var expected = "NewColumnName";
var exampleOption = new List<Schema>
{
new Schema
{
SchemaName = "dbo",
UseSchemaName = true,
ColumnRegexPattern = "^Old",
ColumnPatternReplaceWith = "New"
}
};
var sut = new ReplacingCandidateNamingService(exampleOption);
//Act
var actResult = sut.GenerateCandidateIdentifier(exampleColumn);
//Assert
StringAssert.Contains(expected, actResult);
}
/// <summary>
/// This is to guarantee that the renaming using regex does not overwrite the current column renaming method
/// </summary>
[Test]
public void GenerateCustomColumnNameFromJsonUsingRegexRenamingOverwritten()
{
//Arrange
var exampleColumn = new DatabaseColumn
{
Name = "OldColumnName",
Table = new DatabaseTable
{
Name = "table_name",
Schema = "dbo"
}
};
var expected = "ColumnNameNotOverwritten";
var exampleOption = new List<Schema>
{
new Schema
{
SchemaName = "dbo",
UseSchemaName = true,
ColumnRegexPattern = "^Old",
ColumnPatternReplaceWith = "New",
Tables = new List<TableRenamer>
{
new TableRenamer
{
Name = "table_name",
Columns = new List<ColumnNamer>
{
new ColumnNamer
{
Name = "OldColumnName",
NewName = "ColumnNameNotOverwritten"
}
}
}
}
}
};
var sut = new ReplacingCandidateNamingService(exampleOption);
//Act
var actResult = sut.GenerateCandidateIdentifier(exampleColumn);
//Assert
StringAssert.Contains(expected, actResult);
}
//[Test]
//public void GenerateIForeignKeyForSelfReferenceTable()
//{
// //Arrange
// var expected = "SelfRef";
// var exampleOption = new List<Schema>
// {
// };
// var sut = new ReplacingCandidateNamingService(exampleOption);
// var fk = CreateSelfRefFK();
// // Act
// var result = sut.GetDependentEndCandidateNavigationPropertyName(fk);
// //Assert
// StringAssert.Contains(expected, result);
// //Assert.AreSame(fk.PrincipalEntityType, fk.ResolveOtherEntityType(fk.DeclaringEntityType));
//}
//[Test]
//public void GenerateIForeignKeyNameWithSchemaName()
//{
// //Arrange
// var expected = "SchemaOneToManyPrincipal";
// var exampleOption = new List<Schema>
// {
// new Schema{ SchemaName = "schema", UseSchemaName = true}
// };
// var sut = new ReplacingCandidateNamingService(exampleOption);
// var fk = CreateOneToManyFK();
// // Act
// var result = sut.GetDependentEndCandidateNavigationPropertyName(fk);
// //Assert
// StringAssert.Contains(expected, result);
//}
//[Test]
//public void GenerateIForeignKeyNameWithoutSchemaName()
//{
// //Arrange
// var expected = "OneToManyPrincipal";
// var exampleOption = new List<Schema>
// {
// new Schema{ SchemaName = "schema", UseSchemaName = false}
// };
// var sut = new ReplacingCandidateNamingService(exampleOption);
// var fk = CreateOneToManyFK();
// // Act
// var result = sut.GetDependentEndCandidateNavigationPropertyName(fk);
// //Assert
// StringAssert.Contains(expected, result);
//}
//private ForeignKey CreateSelfRefFK(bool useAltKey = false)
//{
// var entityType = new Model().AddEntityType(typeof(SelfRef));
// entityType.Scaffolding().Schema = "SchemaName";
// var pk = entityType.GetOrSetPrimaryKey(entityType.AddProperty(SelfRef.IdProperty));
// var fkProp = entityType.AddProperty(SelfRef.SelfRefIdProperty);
// var property = entityType.AddProperty("AltId", typeof(int));
// var principalKey = useAltKey
// ? entityType.GetOrAddKey(property)
// : pk;
// var fk = entityType.AddForeignKey(new[] { fkProp }, principalKey, entityType);
// fk.IsUnique = true;
// fk.HasDependentToPrincipal(SelfRef.SelfRefPrincipalProperty);
// fk.HasPrincipalToDependent(SelfRef.SelfRefDependentProperty);
// return fk;
//}
private class SelfRef
{
public static readonly PropertyInfo IdProperty = typeof(SelfRef).GetProperty(nameof(Id));
public static readonly PropertyInfo SelfRefIdProperty = typeof(SelfRef).GetProperty(nameof(SelfRefId));
public static readonly PropertyInfo SelfRefPrincipalProperty = typeof(SelfRef).GetProperty(nameof(SelfRefPrincipal));
public static readonly PropertyInfo SelfRefDependentProperty = typeof(SelfRef).GetProperty(nameof(SelfRefDependent));
public int Id { get; set; }
public SelfRef SelfRefPrincipal { get; set; }
public SelfRef SelfRefDependent { get; set; }
public int? SelfRefId { get; set; }
}
//private ForeignKey CreateOneToManyFK()
//{
// var model = new Model();
// var principalEntityType = model.AddEntityType(typeof(OneToManyPrincipal));
// var property = principalEntityType.AddProperty(NavigationBase.IdProperty);
// var pk = principalEntityType.GetOrSetPrimaryKey(property);
// var dependentEntityType = model.AddEntityType(typeof(OneToManyDependent));
// var fkProp = dependentEntityType.AddProperty(OneToManyDependent.ForeignKeyProperty);
// var fk = dependentEntityType.AddForeignKey(new[] { fkProp }, pk, principalEntityType);
// principalEntityType.Scaffolding().Schema = "schema";
// fk.HasPrincipalToDependent(NavigationBase.OneToManyDependentsProperty);
// fk.HasDependentToPrincipal(NavigationBase.OneToManyPrincipalProperty);
// return fk;
//}
public abstract class NavigationBase
{
public static readonly PropertyInfo IdProperty = typeof(NavigationBase).GetProperty(nameof(Id));
public static readonly PropertyInfo OneToManyDependentsProperty = typeof(NavigationBase).GetProperty(nameof(OneToManyDependents));
public static readonly PropertyInfo OneToManyPrincipalProperty = typeof(NavigationBase).GetProperty(nameof(OneToManyPrincipal));
public int Id { get; set; }
public IEnumerable<OneToManyDependent> OneToManyDependents { get; set; }
public OneToManyPrincipal OneToManyPrincipal { get; set; }
}
public class OneToManyPrincipal : NavigationBase
{
public IEnumerable<OneToManyDependent> OneToManyDependent { get; set; }
}
public class DerivedOneToManyPrincipal : OneToManyPrincipal
{
}
public class OneToManyDependent : NavigationBase
{
public static readonly PropertyInfo DeceptionProperty = typeof(OneToManyDependent).GetProperty(nameof(Deception));
public static readonly PropertyInfo ForeignKeyProperty = typeof(OneToManyDependent).GetProperty(nameof(OneToManyPrincipalId));
public int OneToManyPrincipalId { get; set; }
public OneToManyPrincipal Deception { get; set; }
}
}
}
| 33.151445 | 142 | 0.443751 | [
"MIT"
] | Manu06D/EFCorePowerTools | src/GUI/NUnitTestCore/ReplacingCandidateNamingServiceTests.cs | 28,678 | C# |
namespace LaptopListingSystem.Web.Areas.Administration.Controllers
{
using LaptopListingSystem.Services.Administration.Contracts;
using LaptopListingSystem.Services.Data.Contracts;
using LaptopListingSystem.Web.Controllers;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
[Authorize(Policy = "Administrator")]
[Route("api/administration/[controller]")]
public class BaseAdministrationController<TEntity> : BaseController
where TEntity : class
{
public BaseAdministrationController(
IUsersDataService usersData,
IAdministrationService<TEntity> administrationService)
: base(usersData)
{
this.AdministrationService = administrationService;
}
protected IAdministrationService<TEntity> AdministrationService { get; set; }
}
}
| 33.846154 | 85 | 0.720455 | [
"MIT"
] | KristianMariyanov/LaptopListingSystem | Web/LaptopListingSystem.Web/Areas/Administration/Controllers/BaseAdministrationController.cs | 882 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace SimpleWorkfloorManagementSuite.Controls {
/// <summary>
/// Class defining a checklist item fot the checklist control.
/// </summary>
public class CheckListItem {
#region -_ Public Properties _-
/// <summary>
/// Gets or sets the checked state for this checklist item.
/// </summary>
public bool Checked { get; set; }
/// <summary>
/// Gets or sets the text for this checklist item.
/// </summary>
public String Text { get; set; }
/// <summary>
/// Gets or sets the tag object for this checklist item.
/// </summary>
public Object Tag { get; set; }
#endregion
#region -_ Construction _-
/// <summary>
/// Initializes a new instance of the <see cref="CheckListItem"/> class.
/// </summary>
/// <param name="text">The text for the new checklist item.</param>
public CheckListItem( String text ) {
this.Text = text;
}
/// <summary>
/// Initializes a new instance of the <see cref="CheckListItem"/> class.
/// </summary>
/// <param name="text">The text for the new checklist item..</param>
/// <param name="tag">The tag object for the new checklist item.</param>
public CheckListItem( String text , Object tag ) {
this.Text = text;
this.Tag = tag;
}
#endregion
}
}
| 23.578947 | 74 | 0.653274 | [
"Unlicense"
] | Djohnnie/SwmSuite-Original | SimpleWorkfloorManagementSuite/Controls/CheckListItem.cs | 1,346 | C# |
using System.Collections.Immutable;
using System.Text;
namespace Biohazrd.Transformation
{
public ref struct TypeTransformationResult
{
public TypeReference TypeReference { get; init; }
public ImmutableArray<TranslationDiagnostic> Diagnostics { get; init; }
public bool IsChange(TypeReference originalTypereference)
=> Diagnostics.Length > 0 || TypeReference != originalTypereference;
public TypeTransformationResult(TypeReference typeReference)
{
TypeReference = typeReference;
Diagnostics = ImmutableArray<TranslationDiagnostic>.Empty;
}
public TypeTransformationResult(TypeReference typeReference, TranslationDiagnostic diagnostic)
{
TypeReference = typeReference;
Diagnostics = ImmutableArray.Create(diagnostic);
}
public TypeTransformationResult(TypeReference typeReference, ImmutableArray<TranslationDiagnostic> diagnostics)
{
TypeReference = typeReference;
Diagnostics = diagnostics;
}
public TypeTransformationResult(TypeReference typeReference, Severity diagnosticSeverity, string diagnosticMessage)
: this(typeReference, new TranslationDiagnostic(diagnosticSeverity, diagnosticMessage))
{ }
public TypeTransformationResult(TypeTransformationResult other)
=> this = other;
public TypeTransformationResult AddDiagnostic(TranslationDiagnostic diagnostic)
=> new TypeTransformationResult(this)
{
Diagnostics = this.Diagnostics.Add(diagnostic)
};
public TypeTransformationResult AddDiagnostic(Severity severity, string diagnosticMessage)
=> AddDiagnostic(new TranslationDiagnostic(severity, diagnosticMessage));
public TypeTransformationResult AddDiagnostics(ImmutableArray<TranslationDiagnostic> diagnostics)
=> new TypeTransformationResult(this)
{
Diagnostics = this.Diagnostics.AddRange(diagnostics)
};
public TypeTransformationResult WithType(TypeReference typeReference)
=> new TypeTransformationResult(this)
{
TypeReference = typeReference
};
public static implicit operator TypeTransformationResult(TypeReference typeReference)
=> new TypeTransformationResult(typeReference);
public override string ToString()
{
if (Diagnostics.Length == 0)
{ return TypeReference.ToString(); }
StringBuilder builder = new();
builder.Append(TypeReference);
if (Diagnostics.Length == 1)
{ builder.Append($" ({Diagnostics[0]})"); }
else
{ builder.Append($" (With {Diagnostics.Length} diagnostics)"); }
return builder.ToString();
}
}
}
| 36.7125 | 123 | 0.659176 | [
"MIT"
] | InfectedLibraries/Biohazrd | Biohazrd.Transformation/TypeTransformationResult.cs | 2,939 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Orleans;
using Orleans.AzureUtils;
using Orleans.Runtime;
using Orleans.Runtime.Configuration;
using UnitTests.StorageTests;
using Xunit;
namespace UnitTests.RemindersTest
{
public abstract class ReminderTableTestsBase : IDisposable, IClassFixture<ConnectionStringFixture>
{
private readonly Logger logger;
private readonly IReminderTable remindersTable;
protected const string testDatabaseName = "OrleansReminderTest";//for relational storage
protected ReminderTableTestsBase(ConnectionStringFixture fixture)
{
LogManager.Initialize(new NodeConfiguration());
logger = LogManager.GetLogger(GetType().Name, LoggerType.Application);
var serviceId = Guid.NewGuid();
var deploymentId = "test-" + serviceId;
logger.Info("DeploymentId={0}", deploymentId);
lock (fixture.SyncRoot)
{
if (fixture.ConnectionString == null)
fixture.ConnectionString = GetConnectionString();
}
var globalConfiguration = new GlobalConfiguration
{
ServiceId = serviceId,
DeploymentId = deploymentId,
AdoInvariantForReminders = GetAdoInvariant(),
DataConnectionStringForReminders = fixture.ConnectionString
};
var rmndr = CreateRemindersTable();
rmndr.Init(globalConfiguration, logger).WithTimeout(TimeSpan.FromMinutes(1)).Wait();
remindersTable = rmndr;
}
public virtual void Dispose()
{
// Reset init timeout after tests
OrleansSiloInstanceManager.initTimeout = AzureTableDefaultPolicies.TableCreationTimeout;
if (remindersTable != null && SiloInstanceTableTestConstants.DeleteEntriesAfterTest)
{
remindersTable.TestOnlyClearTable().Wait();
}
}
protected abstract IReminderTable CreateRemindersTable();
protected abstract string GetConnectionString();
protected virtual string GetAdoInvariant()
{
return null;
}
protected async Task RemindersParallelUpsert()
{
var upserts = await Task.WhenAll(Enumerable.Range(0, 50).Select(i =>
{
var reminder = CreateReminder(MakeTestGrainReference(), i.ToString());
return Task.WhenAll(Enumerable.Range(1, 5).Select(j => remindersTable.UpsertRow(reminder)));
}));
Assert.False(upserts.Any(i => i.Distinct().Count() != 5));
}
protected async Task ReminderSimple()
{
var reminder = CreateReminder(MakeTestGrainReference(), "0");
await remindersTable.UpsertRow(reminder);
var readReminder = await remindersTable.ReadRow(reminder.GrainRef, reminder.ReminderName);
string etagTemp = reminder.ETag = readReminder.ETag;
Assert.Equal(JsonConvert.SerializeObject(readReminder), JsonConvert.SerializeObject(reminder));
Assert.NotNull(etagTemp);
reminder.ETag = await remindersTable.UpsertRow(reminder);
var removeRowRes = await remindersTable.RemoveRow(reminder.GrainRef, reminder.ReminderName, etagTemp);
Assert.False(removeRowRes, "should have failed. Etag is wrong");
removeRowRes = await remindersTable.RemoveRow(reminder.GrainRef, "bla", reminder.ETag);
Assert.False(removeRowRes, "should have failed. reminder name is wrong");
removeRowRes = await remindersTable.RemoveRow(reminder.GrainRef, reminder.ReminderName, reminder.ETag);
Assert.True(removeRowRes, "should have succeeded. Etag is right");
removeRowRes = await remindersTable.RemoveRow(reminder.GrainRef, reminder.ReminderName, reminder.ETag);
Assert.False(removeRowRes, "should have failed. reminder shouldn't exist");
}
protected async Task RemindersRange(int iterations=1000)
{
await Task.WhenAll(Enumerable.Range(1, iterations).Select(async i =>
{
GrainReference grainRef = MakeTestGrainReference();
await remindersTable.UpsertRow(CreateReminder(grainRef, i.ToString()));
}));
var rows = await remindersTable.ReadRows(0, uint.MaxValue);
Assert.Equal(rows.Reminders.Count, iterations);
rows = await remindersTable.ReadRows(0, 0);
Assert.Equal(rows.Reminders.Count, iterations);
var remindersHashes = rows.Reminders.Select(r => r.GrainRef.GetUniformHashCode()).ToArray();
SafeRandom random = new SafeRandom();
await Task.WhenAll(Enumerable.Range(0, iterations).Select(i =>
TestRemindersHashInterval(remindersTable, (uint)random.Next(), (uint)random.Next(),
remindersHashes)));
}
private async Task TestRemindersHashInterval(IReminderTable reminderTable, uint beginHash, uint endHash,
uint[] remindersHashes)
{
var rowsTask = reminderTable.ReadRows(beginHash, endHash);
var expectedHashes = beginHash < endHash
? remindersHashes.Where(r => r > beginHash && r <= endHash)
: remindersHashes.Where(r => r > beginHash || r <= endHash);
HashSet<uint> expectedSet = new HashSet<uint>(expectedHashes);
var returnedHashes = (await rowsTask).Reminders.Select(r => r.GrainRef.GetUniformHashCode());
var returnedSet = new HashSet<uint>(returnedHashes);
Assert.True(returnedSet.SetEquals(expectedSet));
}
private static ReminderEntry CreateReminder(GrainReference grainRef, string reminderName)
{
var now = DateTime.UtcNow;
now = new DateTime(now.Year, now.Month, now.Day, now.Hour, now.Minute, now.Second);
return new ReminderEntry
{
GrainRef = grainRef,
Period = TimeSpan.FromMinutes(1),
StartAt = now,
ReminderName = reminderName
};
}
private static GrainReference MakeTestGrainReference()
{
GrainId regularGrainId = GrainId.GetGrainIdForTesting(Guid.NewGuid());
GrainReference grainRef = GrainReference.FromGrainId(regularGrainId);
return grainRef;
}
}
}
| 39.892216 | 115 | 0.631192 | [
"MIT"
] | Drawaes/orleans | test/TesterInternal/RemindersTest/ReminderTableTestsBase.cs | 6,662 | C# |
using System;
using Nakov.IO; // See http://www.nakov.com/tags/cin
public class CinExample
{
static void Main()
{
Console.Write("Enter your name: ");
string name = Console.ReadLine();
Console.Write("Enter two integers x and y separated by whitespace: ");
// cin >> x >> y;
int x = Cin.NextInt();
double y = Cin.NextDouble();
Console.Write("Enter your age: ");
int age = int.Parse(Console.ReadLine());
Console.WriteLine("Name: {0}, Age: {1}", name, age);
Console.WriteLine("x={0}, y={1}", x, y);
Console.Write("Enter a positive integer number N: ");
// cin >> n;
int n = Cin.NextInt();
Console.Write("Enter N decimal numbers separated by a space: ");
decimal[] numbers = new decimal[n];
for (int i = 0; i < n; i++)
{
// cin >> numbers[i];
numbers[i] = Cin.NextDecimal();
}
Array.Sort(numbers);
Console.WriteLine("The numbers in ascending order: {0}",
string.Join(' ', numbers));
Console.Write("Enter two strings seperated by a space: ");
// cin >> firstStr >> secondStr;
string firstStr = Cin.NextToken();
string secondStr = Cin.NextToken();
Console.WriteLine("First str={0}", firstStr);
Console.WriteLine("Second str={0}", secondStr);
}
} | 31.177778 | 78 | 0.548824 | [
"MIT"
] | nakov/Nakov.io.cin | Examples/CinExample.cs | 1,405 | C# |
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
namespace Genode.Audio
{
/// <summary>
/// Represents a decoder to decode specific audio format.
/// </summary>
public abstract class SoundReader : IDisposable
{
/// <summary>
/// Check if current <see cref="SoundReader"/> object can handle a give data from specified <see cref="Stream"/>.
/// </summary>
/// <param name="stream">The <see cref="Stream"/> to check.</param>
/// <returns><code>true</code> if supported, otherwise false.</returns>
public abstract bool Check(Stream stream);
/// <summary>
/// Open a <see cref="Stream"/> of sound for reading.
/// </summary>
/// <param name="stream">The <see cref="Stream"/> to open.</param>
/// <param name="ownStream">Specify whether the <see cref="SoundReader"/> should close the source <see cref="Stream"/> upon disposing the reader.</param>
/// <returns>A <see cref="SampleInfo"/> containing sample information.</returns>
public abstract SampleInfo Open(Stream stream, bool ownStream = false);
/// <summary>
/// Sets the current read position of the sample offset.
/// </summary>
/// <param name="sampleOffset">The index of the sample to jump to, relative to the beginning.</param>
public abstract void Seek(long sampleOffset);
/// <summary>
/// Reads a block of audio samples from the current stream and writes the data to given sample.
/// </summary>
/// <param name="samples">The sample array to fill.</param>
/// <param name="count">The maximum number of samples to read.</param>
/// <returns>The number of samples actually read.</returns>
public abstract long Read(short[] samples, long count);
/// <summary>
/// Release all resources used by the <see cref="SoundReader"/>.
/// </summary>
public abstract void Dispose();
}
}
| 42.229167 | 161 | 0.619142 | [
"MIT"
] | SirusDoma/Genode | Source/Genode/Audio/Reader/SoundReader.cs | 2,029 | C# |
using DevExpress.Mvvm.UI;
using DevExpress.Mvvm.UI.Interactivity;
using DevExpress.Mvvm.POCO;
using System.Windows.Controls;
using System.Threading;
using System;
using System.Windows;
using System.Linq;
using NUnit.Framework;
using System.Collections.Generic;
using DevExpress.Mvvm.Native;
namespace DevExpress.Mvvm.Tests {
[TestFixture]
public class ServiceContainerTests : BaseWpfFixture {
protected override void TearDownCore() {
base.TearDownCore();
ServiceContainer.Default = null;
}
public interface IService1 { }
public interface IService2 { }
public class TestService1 : IService1 { }
public class TestService2 : IService2 { }
public class TestService1_2 : IService1, IService2 { }
[Test]
public void ContainersLoopTest() {
var child = new TestSupportServices();
var parent = new TestSupportServices();
child.ParentViewModel = parent;
parent.ParentViewModel = child;
var service1 = new TestService1();
child.ServiceContainer.RegisterService(service1, true);
AssertHelper.AssertThrows<Exception>(() => {
child.ServiceContainer.GetService<IService1>();
}, e => {
Assert.AreEqual("A ServiceContainer should not be a direct or indirect parent for itself.", e.Message);
});
}
[Test]
public void AddServicesWithoutKey() {
IServiceContainer container = new ServiceContainer(null);
TestService1 svc1 = new TestService1();
TestService1 svc1_ = new TestService1();
TestService2 svc2 = new TestService2();
container.RegisterService(svc1);
Assert.AreEqual(svc1, container.GetService<IService1>());
container.RegisterService(svc2);
Assert.AreEqual(svc1, container.GetService<IService1>());
Assert.AreEqual(svc2, container.GetService<IService2>());
container.RegisterService("svc1_", svc1_);
Assert.AreEqual(svc1, container.GetService<IService1>());
Assert.AreEqual(svc1_, container.GetService<IService1>("svc1_"));
}
[Test]
public void AddServicesWithoutKey_2() {
IServiceContainer container = new ServiceContainer(null);
TestService1 svc1 = new TestService1();
TestService1 svc1_ = new TestService1();
TestService2 svc2 = new TestService2();
container.RegisterService("svc1_", svc1_);
container.RegisterService(svc1);
container.RegisterService(svc2);
Assert.AreEqual(svc1, container.GetService<IService1>());
Assert.AreEqual(svc2, container.GetService<IService2>());
Assert.AreEqual(svc1_, container.GetService<IService1>("svc1_"));
}
[Test]
public void RemoveServices() {
IServiceContainer container = new ServiceContainer(null);
TestService1 svc1 = new TestService1();
TestService1 svc1_ = new TestService1();
TestService2 svc2 = new TestService2();
container.RegisterService(svc1);
container.RegisterService(svc2);
container.RegisterService("svc1_", svc1_);
Assert.AreEqual(svc1, container.GetService<IService1>());
Assert.AreEqual(svc1_, container.GetService<IService1>("svc1_"));
Assert.AreEqual(svc2, container.GetService<IService2>());
container.UnregisterService(svc1);
Assert.AreEqual(svc1_, container.GetService<IService1>());
Assert.AreEqual(svc1_, container.GetService<IService1>("svc1_"));
Assert.AreEqual(svc2, container.GetService<IService2>());
container.UnregisterService(svc1_);
Assert.AreEqual(null, container.GetService<IService1>());
Assert.AreEqual(null, container.GetService<IService1>("svc1_"));
Assert.AreEqual(svc2, container.GetService<IService2>());
container.UnregisterService(svc2);
Assert.AreEqual(null, container.GetService<IService2>());
}
[Test]
public void GetServiceNotByInterfaceType() {
IServiceContainer container = new ServiceContainer(null);
TestService1 svc1 = new TestService1();
container.RegisterService(svc1);
Assert.Throws<ArgumentException>(() => { container.GetService<TestService1>(); });
}
[Test]
public void GetServiceNotByInterfaceTypeWinKeyName() {
ServiceContainer container = new ServiceContainer(null);
Assert.Throws<ArgumentException>(() => { container.GetService<TestService1>("svc1_"); });
}
[Test]
public void AddServicesWithKey() {
IServiceContainer container = new ServiceContainer(null);
TestService1 svc1 = new TestService1();
TestService1 svc1_ = new TestService1();
container.RegisterService("svc1", svc1);
container.RegisterService("svc1_", svc1_);
Assert.AreEqual(svc1_, container.GetService<IService1>());
Assert.AreEqual(svc1, container.GetService<IService1>("svc1"));
Assert.AreEqual(svc1_, container.GetService<IService1>("svc1_"));
container.RegisterService(svc1_);
Assert.AreEqual(svc1_, container.GetService<IService1>());
container.RegisterService(svc1);
Assert.AreEqual(svc1, container.GetService<IService1>());
}
[Test]
public void GetServiceFromParent() {
var parent = new TestSupportServices();
var child = new TestSupportServices();
var service1 = new TestService1();
child.ServiceContainer.RegisterService(service1);
Assert.AreEqual(service1, child.ServiceContainer.GetService<IService1>());
var service2 = new TestService2();
parent.ServiceContainer.RegisterService(service2);
Assert.AreEqual(null, child.ServiceContainer.GetService<IService2>());
child.ParentViewModel = parent;
Assert.AreEqual(service2, child.ServiceContainer.GetService<IService2>());
Assert.AreEqual(null, child.ServiceContainer.GetService<IService2>(ServiceSearchMode.LocalOnly));
var service2Local = new TestService2();
child.ServiceContainer.RegisterService(service2Local);
Assert.AreEqual(service2Local, child.ServiceContainer.GetService<IService2>(ServiceSearchMode.LocalOnly));
Assert.AreEqual(service2, child.ServiceContainer.GetService<IService2>(ServiceSearchMode.PreferParents));
}
[Test]
public void B235125_GetServiceFromSecondParent() {
var parent1 = new TestSupportServices();
var parent2 = new TestSupportServices();
var child = new TestSupportServices();
var service1 = new TestService1();
var service2 = new TestService1();
parent1.ServiceContainer.RegisterService(service1);
parent2.ServiceContainer.RegisterService(service2);
child.ParentViewModel = parent1;
parent1.ParentViewModel = parent2;
Assert.AreEqual(service1, child.ServiceContainer.GetService<IService1>());
Assert.AreEqual(service2, child.ServiceContainer.GetService<IService1>(ServiceSearchMode.PreferParents));
}
[Test]
public void B235125_GetServiceFromSecondParentByKey() {
var parent1 = new TestSupportServices();
var parent2 = new TestSupportServices();
var child = new TestSupportServices();
var service1 = new TestService1();
var service2 = new TestService1();
parent1.ServiceContainer.RegisterService("key", service1);
parent2.ServiceContainer.RegisterService("key", service2);
child.ParentViewModel = parent1;
parent1.ParentViewModel = parent2;
Assert.AreEqual(service1, child.ServiceContainer.GetService<IService1>("key"));
Assert.AreEqual(service2, child.ServiceContainer.GetService<IService1>("key", ServiceSearchMode.PreferParents));
}
[Test]
public void GetServiceFromParentByKey() {
var parent = new TestSupportServices();
var child = new TestSupportServices();
var service2 = new TestService2();
parent.ServiceContainer.RegisterService("key", service2);
Assert.AreEqual(null, child.ServiceContainer.GetService<IService2>("key"));
child.ParentViewModel = parent;
Assert.AreEqual(service2, child.ServiceContainer.GetService<IService2>("key"));
Assert.AreEqual(null, child.ServiceContainer.GetService<IService2>("key", ServiceSearchMode.LocalOnly));
var service2Local = new TestService2();
child.ServiceContainer.RegisterService("key", service2Local);
Assert.AreEqual(service2Local, child.ServiceContainer.GetService<IService2>("key", ServiceSearchMode.LocalOnly));
Assert.AreEqual(service2, child.ServiceContainer.GetService<IService2>("key", ServiceSearchMode.PreferParents));
Assert.AreEqual(service2Local, child.ServiceContainer.GetService<IService2>("key", ServiceSearchMode.PreferLocal));
}
[Test]
public void YieldToParentTest1() {
var parent = new TestSupportServices();
var child = new TestSupportServices();
var service2 = new TestService2();
parent.ServiceContainer.RegisterService("key", service2);
child.ParentViewModel = parent;
var service2Local = new TestService2();
child.ServiceContainer.RegisterService("key", service2Local, true);
Assert.AreEqual(service2, child.ServiceContainer.GetService<IService2>("key", ServiceSearchMode.PreferParents));
Assert.AreEqual(service2Local, child.ServiceContainer.GetService<IService2>("key", ServiceSearchMode.LocalOnly));
Assert.AreEqual(service2, child.ServiceContainer.GetService<IService2>("key", ServiceSearchMode.PreferLocal));
}
[Test]
public void YieldToParentTest2() {
var parent = new TestSupportServices();
var child = new TestSupportServices();
var service2 = new TestService2();
parent.ServiceContainer.RegisterService(service2);
child.ParentViewModel = parent;
var service2Local = new TestService2();
child.ServiceContainer.RegisterService(service2Local, true);
Assert.AreEqual(service2, child.ServiceContainer.GetService<IService2>(ServiceSearchMode.PreferParents));
Assert.AreEqual(service2Local, child.ServiceContainer.GetService<IService2>(ServiceSearchMode.LocalOnly));
Assert.AreEqual(service2, child.ServiceContainer.GetService<IService2>(ServiceSearchMode.PreferLocal));
}
[Test]
public void YieldToParentTest3() {
var child = new TestSupportServices();
var service2Local = new TestService2();
child.ServiceContainer.RegisterService(service2Local, true);
Assert.AreEqual(service2Local, child.ServiceContainer.GetService<IService2>(ServiceSearchMode.LocalOnly));
Assert.AreEqual(service2Local, child.ServiceContainer.GetService<IService2>(ServiceSearchMode.PreferParents));
Assert.AreEqual(service2Local, child.ServiceContainer.GetService<IService2>(ServiceSearchMode.PreferLocal));
}
[Test]
public void YieldToParentTest4() {
var child = new TestSupportServices();
var service2Local = new TestService2();
child.ServiceContainer.RegisterService("key", service2Local, true);
Assert.AreEqual(service2Local, child.ServiceContainer.GetService<IService2>("key", ServiceSearchMode.LocalOnly));
Assert.AreEqual(service2Local, child.ServiceContainer.GetService<IService2>("key", ServiceSearchMode.PreferParents));
Assert.AreEqual(service2Local, child.ServiceContainer.GetService<IService2>("key", ServiceSearchMode.PreferLocal));
}
[Test]
public void GetService_PreferParent() {
var parent = new TestSupportServices();
var child = new TestSupportServices();
var service2 = new TestService2();
child.ServiceContainer.RegisterService(service2);
child.ParentViewModel = parent;
Assert.AreEqual(service2, child.ServiceContainer.GetService<IService2>(ServiceSearchMode.PreferParents));
}
[Test]
public void GetServiceByKey_PreferParent() {
var parent = new TestSupportServices();
var child = new TestSupportServices();
var service2 = new TestService2();
child.ServiceContainer.RegisterService("key", service2);
child.ParentViewModel = parent;
Assert.AreEqual(service2, child.ServiceContainer.GetService<IService2>("key", ServiceSearchMode.PreferParents));
}
[Test]
public void GetServiceFromParentByKey_InvalidParent() {
var child = new TestSupportServices();
var service2 = new TestService2();
child.ServiceContainer.RegisterService("key", service2);
Assert.AreEqual(service2, child.ServiceContainer.GetService<IService2>("key"));
Assert.AreEqual(null, child.ServiceContainer.GetService<IService1>("key2"));
child.ParentViewModel = child;
Assert.AreEqual(service2, child.ServiceContainer.GetService<IService2>("key"));
Assert.AreEqual(null, child.ServiceContainer.GetService<IService1>("key2"));
}
[Test]
public void GetServiceFromParent_InvalidParent() {
var child = new TestSupportServices();
var service2 = new TestService2();
child.ServiceContainer.RegisterService(service2);
Assert.AreEqual(service2, child.ServiceContainer.GetService<IService2>());
Assert.AreEqual(null, child.ServiceContainer.GetService<IService1>());
child.ParentViewModel = child;
Assert.AreEqual(service2, child.ServiceContainer.GetService<IService2>());
Assert.AreEqual(null, child.ServiceContainer.GetService<IService1>());
var service1 = new TestService1();
ServiceContainer.Default.RegisterService(service1);
try {
Assert.AreEqual(service1, child.ServiceContainer.GetService<IService1>());
} finally {
ServiceContainer.Default.Clear();
}
Assert.AreEqual(null, child.ServiceContainer.GetService<IService1>());
}
[Test]
public void RegisterNull() {
var child = new TestSupportServices();
Assert.Throws<ArgumentNullException>(() => { child.ServiceContainer.RegisterService(null); });
Assert.Throws<ArgumentNullException>(() => { child.ServiceContainer.RegisterService("key", null); });
}
[Test]
public void RegisterByNullKey() {
var child = new TestSupportServices();
var service = new TestService1();
child.ServiceContainer.RegisterService(null, service);
Assert.AreEqual(service, child.ServiceContainer.GetService<IService1>());
}
[Test]
public void Clear() {
var parent = new TestSupportServices();
var child = new TestSupportServices();
var service2 = new TestService2();
child.ServiceContainer.RegisterService(service2);
Assert.AreEqual(service2, child.ServiceContainer.GetService<IService2>());
child.ServiceContainer.Clear();
Assert.AreEqual(null, child.ServiceContainer.GetService<IService2>());
child.ServiceContainer.RegisterService("key", service2);
child.ServiceContainer.Clear();
Assert.AreEqual(null, child.ServiceContainer.GetService<IService2>());
Assert.AreEqual(null, child.ServiceContainer.GetService<IService2>("key"));
}
[Test]
public void RegisterServiceWithoutNameTwice() {
var viewModel = new TestSupportServices();
viewModel.ServiceContainer.RegisterService(new TestService1());
var service1_2 = new TestService1_2();
viewModel.ServiceContainer.RegisterService(service1_2);
Assert.AreEqual(service1_2, viewModel.ServiceContainer.GetService<IService1>());
Assert.AreEqual(service1_2, viewModel.ServiceContainer.GetService<IService2>());
var service2 = new TestService2();
viewModel.ServiceContainer.RegisterService(service2);
Assert.AreEqual(service1_2, viewModel.ServiceContainer.GetService<IService1>());
Assert.AreEqual(service2, viewModel.ServiceContainer.GetService<IService2>());
}
[Test]
public void FindServiceWithoutKeyTest() {
foreach(var useEmptyStringAsParentServiceKey in new bool?[] { null, false, true })
foreach(var useEmptyStringAsLocalServiceKey in new bool?[] { null, false, true }) {
KeylessServiceSearchTestHelper tester = new KeylessServiceSearchTestHelper() { UseEmptyStringAsParentServiceKey = useEmptyStringAsParentServiceKey, UseEmptyStringAsLocalServiceKey = useEmptyStringAsLocalServiceKey };
tester.TestKeylessServiceSearch(29, parentHasKey: false, nestedHasKey: false, yieldToParent: false, preferLocal: false, assertActualIsNested: false);
tester.TestKeylessServiceSearch(30, parentHasKey: false, nestedHasKey: false, yieldToParent: false, preferLocal: true, assertActualIsNested: true);
tester.TestKeylessServiceSearch(31, parentHasKey: false, nestedHasKey: false, yieldToParent: true, preferLocal: false, assertActualIsNested: false);
tester.TestKeylessServiceSearch(32, parentHasKey: false, nestedHasKey: false, yieldToParent: true, preferLocal: true, assertActualIsNested: false);
tester.TestKeylessServiceSearch(33, parentHasKey: false, nestedHasKey: true, yieldToParent: false, preferLocal: false, assertActualIsNested: false);
tester.TestKeylessServiceSearch(34, parentHasKey: false, nestedHasKey: true, yieldToParent: false, preferLocal: true, assertActualIsNested: false);
tester.TestKeylessServiceSearch(35, parentHasKey: false, nestedHasKey: true, yieldToParent: true, preferLocal: false, assertActualIsNested: false);
tester.TestKeylessServiceSearch(36, parentHasKey: false, nestedHasKey: true, yieldToParent: true, preferLocal: true, assertActualIsNested: false);
tester.TestKeylessServiceSearch(37, parentHasKey: true, nestedHasKey: false, yieldToParent: false, preferLocal: false, assertActualIsNested: true);
tester.TestKeylessServiceSearch(38, parentHasKey: true, nestedHasKey: false, yieldToParent: false, preferLocal: true, assertActualIsNested: true);
tester.TestKeylessServiceSearch(39, parentHasKey: true, nestedHasKey: false, yieldToParent: true, preferLocal: false, assertActualIsNested: true);
tester.TestKeylessServiceSearch(40, parentHasKey: true, nestedHasKey: false, yieldToParent: true, preferLocal: true, assertActualIsNested: true);
tester.TestKeylessServiceSearch(41, parentHasKey: true, nestedHasKey: true, yieldToParent: false, preferLocal: false, assertActualIsNested: false);
tester.TestKeylessServiceSearch(42, parentHasKey: true, nestedHasKey: true, yieldToParent: false, preferLocal: true, assertActualIsNested: true);
tester.TestKeylessServiceSearch(43, parentHasKey: true, nestedHasKey: true, yieldToParent: true, preferLocal: false, assertActualIsNested: false);
tester.TestKeylessServiceSearch(44, parentHasKey: true, nestedHasKey: true, yieldToParent: true, preferLocal: true, assertActualIsNested: false);
}
}
[Test]
public void GetApplicationService() {
var defaultServiceContainer = new DefaultServiceContainer2();
var service2InApp = new TestService2();
defaultServiceContainer.Resources.Add("testService2", service2InApp);
var service11 = new TestService1();
var service12 = new TestService1();
defaultServiceContainer.Resources.Add("testService11", service11);
defaultServiceContainer.Resources.Add("testService12", service12);
ServiceContainer.Default = defaultServiceContainer;
var parent = new TestSupportServices();
var child = new TestSupportServices();
var service2 = new TestService2();
child.ServiceContainer.RegisterService(service2);
child.ParentViewModel = parent;
Assert.AreEqual(service2, child.ServiceContainer.GetService<IService2>(ServiceSearchMode.PreferParents));
Assert.AreEqual(service2, child.ServiceContainer.GetService<IService2>());
Assert.IsNotNull(child.ServiceContainer.GetService<IService1>());
Assert.AreEqual(service11, child.ServiceContainer.GetService<IService1>("testService11"));
}
[Test]
public void T711283() {
var defaultServiceContainer = new DefaultServiceContainer2();
defaultServiceContainer.Resources.Add("testService", null);
ServiceContainer.Default = defaultServiceContainer;
var vm = new TestSupportServices();
vm.GetService<IMessageBoxService>();
}
[Test]
public void GetLastParent() {
var root = new TestSupportServices();
var parent = new TestSupportServices();
var child = new TestSupportServices();
parent.ParentViewModel = root;
child.ParentViewModel = parent;
var rootSrv = new TestService1();
var parentSrv = new TestService1();
var childSrv = new TestService1();
root.ServiceContainer.RegisterService(rootSrv);
parent.ServiceContainer.RegisterService(parentSrv);
child.ServiceContainer.RegisterService(childSrv);
Assert.AreEqual(rootSrv, child.ServiceContainer.GetService<IService1>(ServiceSearchMode.PreferParents));
}
[Test]
public void GetApplicationService_DoNotUseServicesInMergedDictionaries() {
var defaultServiceContainer = new DefaultServiceContainer2();
var service1 = new TestService1();
var mergedDictionary = new ResourceDictionary();
mergedDictionary.Add("testService2", service1);
defaultServiceContainer.Resources.MergedDictionaries.Add(mergedDictionary);
Assert.IsNull(defaultServiceContainer.GetService<IService1>());
}
class KeylessServiceSearchTestHelper {
public bool? UseEmptyStringAsParentServiceKey;
public bool? UseEmptyStringAsLocalServiceKey;
public void TestKeylessServiceSearch(int message, bool parentHasKey, bool nestedHasKey, bool yieldToParent, bool preferLocal, bool assertActualIsNested) {
IServiceContainer parentContainer = new ServiceContainer(null);
IServiceContainer nestedContainer = new ServiceContainer(new ParentServiceContainerWrapper(parentContainer));
TestService1 parentService = new TestService1();
RegisterService(parentHasKey, "p", parentService, false, parentContainer, UseEmptyStringAsParentServiceKey);
TestService1 nestedService = new TestService1();
RegisterService(nestedHasKey, "n", nestedService, yieldToParent, nestedContainer, UseEmptyStringAsLocalServiceKey);
string messageString = message.ToString() + " " + ToString(UseEmptyStringAsParentServiceKey) + " " + ToString(UseEmptyStringAsLocalServiceKey);
Assert.AreEqual(assertActualIsNested ? nestedService : parentService, nestedContainer.GetService<IService1>(preferLocal ? ServiceSearchMode.PreferLocal : ServiceSearchMode.PreferParents), messageString);
}
void RegisterService<T>(bool registerWithKey, string key, T service, bool yieldToParent, IServiceContainer serviceContainer, bool? useEmptyStringAsServiceKey) {
if(registerWithKey)
serviceContainer.RegisterService(key, service, yieldToParent);
else if(!useEmptyStringAsServiceKey.HasValue)
serviceContainer.RegisterService(service, yieldToParent);
else if(useEmptyStringAsServiceKey.Value)
serviceContainer.RegisterService(string.Empty, service, yieldToParent);
else
serviceContainer.RegisterService(null, service, yieldToParent);
}
string ToString(bool? v) {
return v == null ? "none" : v.Value ? "empty" : "null";
}
}
}
public class TestSupportServices : ISupportServices, ISupportParentViewModel, ISupportParameter {
readonly ServiceContainer serviceContainer;
public TestSupportServices() {
serviceContainer = new ServiceContainer(this);
}
public IServiceContainer ServiceContainer { get { return serviceContainer; } }
public object ParentViewModel { get; set; }
public object Parameter { get; set; }
public void OnNavigatedTo(object parameter) {
Parameter = parameter;
}
}
public class ParentServiceContainerWrapper : ISupportParentViewModel {
class ParentServiceContainerOwner : ISupportServices {
IServiceContainer parentServiceContainer;
public ParentServiceContainerOwner(IServiceContainer parentServiceContainer) {
this.parentServiceContainer = parentServiceContainer;
}
IServiceContainer ISupportServices.ServiceContainer { get { return parentServiceContainer; } }
}
ParentServiceContainerOwner parentServiceContainerOwner;
public ParentServiceContainerWrapper(IServiceContainer parentServiceContainer) {
this.parentServiceContainerOwner = new ParentServiceContainerOwner(parentServiceContainer);
}
object ISupportParentViewModel.ParentViewModel {
get { return parentServiceContainerOwner; }
set { throw new NotSupportedException(); }
}
}
class DefaultServiceContainer2 : DefaultServiceContainer {
public DefaultServiceContainer2() : base() {
Resources = new ResourceDictionary();
}
public ResourceDictionary Resources { get; private set; }
protected override ResourceDictionary GetApplicationResources() {
return Resources;
}
}
[TestFixture]
public class ServiceBaseTests : BaseWpfFixture {
[Test]
public void UnregisterServiceOnDataContextChanged() {
Button control = new Button();
TestVM vm1 = TestVM.Create();
TestVM vm2 = TestVM.Create();
TestServiceBase service = new TestServiceBase();
Interaction.GetBehaviors(control).Add(service);
control.DataContext = vm1;
Assert.AreEqual(service, vm1.GetService<ITestService>());
control.DataContext = vm2;
Assert.AreEqual(null, vm1.GetService<ITestService>());
Assert.AreEqual(service, vm2.GetService<ITestService>());
}
[Test]
public void UnregisterServiceOnDetaching() {
Button control = new Button();
TestVM vm1 = TestVM.Create();
TestServiceBase service = new TestServiceBase();
Interaction.GetBehaviors(control).Add(service);
control.DataContext = vm1;
Assert.AreEqual(service, vm1.GetService<ITestService>());
Interaction.GetBehaviors(control).Remove(service);
Assert.AreEqual(null, vm1.GetService<ITestService>());
}
[Test]
public void UnregisterServiceOnUnloaded() {
Button control = new Button();
TestVM vm1 = TestVM.Create();
TestServiceBase service = new TestServiceBase() { UnregisterOnUnloaded = true };
Interaction.GetBehaviors(control).Add(service);
control.DataContext = vm1;
Assert.AreEqual(service, vm1.GetService<ITestService>());
Window.Content = control;
Window.Show();
Assert.AreEqual(service, vm1.GetService<ITestService>());
Window.Content = null;
DispatcherHelper.DoEvents();
Assert.AreEqual(null, vm1.GetService<ITestService>());
}
[Test]
public void T250427() {
Grid mainV = new Grid();
TestVM mainVM = TestVM.Create();
TestServiceBase mainService = new TestServiceBase();
Interaction.GetBehaviors(mainV).Add(mainService);
mainV.DataContext = mainVM;
Grid childV = new Grid();
TestVM childVM = TestVM.Create();
TestServiceBase childService = new TestServiceBase();
Interaction.GetBehaviors(childV).Add(childService);
mainV.Children.Add(childV);
Assert.AreEqual(childService, mainVM.GetService<ITestService>());
childV.DataContext = childVM;
Assert.AreEqual(mainService, mainVM.GetService<ITestService>());
Assert.AreEqual(childService, childVM.GetService<ITestService>());
}
public class TestVM {
public static TestVM Create() { return ViewModelSource.Create(() => new TestVM()); }
protected TestVM() { }
}
public interface ITestService { }
public class TestServiceBase : ServiceBase, ITestService { }
}
#if !DXCORE3
[TestFixture]
public class ServiceContainerThreadTest :BaseWpfFixture {
const int iterationCount = 1000;
const int threadCount = 100;
void RunThreads(Action test) {
List<Thread> threads = new List<Thread>();
for(int i = 0; i < threadCount; i++)
threads.Add(new Thread(new ThreadStart(test)));
foreach(var t in threads) t.Start();
foreach(var t in threads) t.Join();
foreach(var t in threads) t.Abort();
}
protected override void SetUpCore() {
base.SetUpCore();
ServiceContainer.Default = null;
}
protected override void TearDownCore() {
ServiceContainer.Default = null;
base.TearDownCore();
}
[Test]
public void DefaultServiceContainerIsThreadSafe() {
Exception ex = null;
Action test = () => {
try {
var key = Guid.NewGuid().ToString();
ServiceContainer.Default.RegisterService(key, new TestServiceBase());
for(int i = 0; i < iterationCount; i++)
ServiceContainer.Default.GetService<ITestService>(key).AddItem(i.ToString());
} catch(Exception e) { ex = e; }
};
RunThreads(test);
Assert.AreEqual(null, ex);
Assert.AreEqual(threadCount, ServiceContainer.Default.GetServices<ITestService>().Count());
foreach(var s in ServiceContainer.Default.GetServices<ITestService>())
Assert.AreEqual(iterationCount, s.Items.Count());
}
public class TestVM : ISupportServices {
public IServiceContainer ServiceContainer { get; set; }
public TestVM(bool isThreadSafe) {
ServiceContainer = new ServiceContainer(isThreadSafe);
}
}
public interface ITestService {
IEnumerable<string> Items { get; }
void AddItem(string value);
}
public class TestServiceBase : ServiceBase, ITestService {
public IEnumerable<string> Items { get { return items; } }
List<string> items = new List<string>();
public void AddItem(string value) {
lock(items) {
items.Add(value);
}
}
}
}
#endif
} | 53.256911 | 236 | 0.652215 | [
"MIT"
] | CentralLaserFacility/DevExpress.Mvvm | DevExpress.Mvvm.Tests/Services/ServiceContainerBaseTests.cs | 32,753 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.