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 UnityEngine;
using System.Collections;
public class DeftRigidBody : MonoBehaviour
{
public enum DeftRigidBodyType { PLAYER, PHYSICSOBJECT };
public DeftRigidBodyType type;
public double m_InterpolationBackTime = 0.1;
public double m_ExtrapolationLimit = 0.5;
public string controllerScript;
internal struct State
{
internal double timestamp;
internal Vector3 pos;
internal Vector3 velocity;
internal Quaternion rot;
internal Vector3 angularVelocity;
}
void OnNetworkInstantiate(NetworkMessageInfo msg)
{
Debug.Log("Instantiating deft rigid body of type " + this.type.ToString());
if (this.type == DeftRigidBodyType.PLAYER)
{
if (networkView.isMine)
{
}
else
{
if (controllerScript != null)
Destroy(gameObject.GetComponent(controllerScript));
// destroy any other controllers or enable/disable them
}
}
if (this.type == DeftRigidBodyType.PHYSICSOBJECT)
{
// todo
}
}
State[] m_BufferedState = new State[20];
int m_TimestampCount;
void Start()
{
foreach (NetworkView n in GetComponents<NetworkView>())
n.observed = this;
}
void OnSerializeNetworkView(BitStream stream, NetworkMessageInfo info)
{
if (stream.isWriting)
{
Vector3 pos = rigidbody.position;
Quaternion rot = rigidbody.rotation;
Vector3 velocity = rigidbody.velocity;
Vector3 angularVelocity = rigidbody.angularVelocity;
stream.Serialize(ref pos);
stream.Serialize(ref velocity);
stream.Serialize(ref rot);
stream.Serialize(ref angularVelocity);
}
else
{
Vector3 pos = Vector3.zero;
Vector3 velocity = Vector3.zero;
Quaternion rot = Quaternion.identity;
Vector3 angularVelocity = Vector3.zero;
stream.Serialize(ref pos);
stream.Serialize(ref velocity);
stream.Serialize(ref rot);
stream.Serialize(ref angularVelocity);
for (int i = m_BufferedState.Length - 1; i >= 1; i--)
{
m_BufferedState[i] = m_BufferedState[i - 1];
}
State state;
state.timestamp = info.timestamp;
state.pos = pos;
state.velocity = velocity;
state.rot = rot;
state.angularVelocity = angularVelocity;
m_BufferedState[0] = state;
m_TimestampCount = Mathf.Min(m_TimestampCount + 1, m_BufferedState.Length);
for (int i = 0; i < m_TimestampCount - 1; i++)
if (m_BufferedState[i].timestamp < m_BufferedState[i + 1].timestamp)
Debug.Log("State inconsistent");
}
}
void Update()
{
// This is the target playback time of the rigid body
double interpolationTime = Network.time - m_InterpolationBackTime;
// Use interpolation if the target playback time is present in the buffer
if (m_BufferedState[0].timestamp > interpolationTime)
{
// Go through buffer and find correct state to play back
for (int i = 0; i < m_TimestampCount; i++)
{
if (m_BufferedState[i].timestamp <= interpolationTime || i == m_TimestampCount - 1)
{
// The state one slot newer (<100ms) than the best playback state
State rhs = m_BufferedState[Mathf.Max(i - 1, 0)];
// The best playback state (closest to 100 ms old (default time))
State lhs = m_BufferedState[i];
// Use the time between the two slots to determine if interpolation is necessary
double length = rhs.timestamp - lhs.timestamp;
float t = 0.0f;
// As the time difference gets closer to 100 ms t gets closer to 1 in
// which case rhs is only used
// Example:
// Time is 10.000, so sampleTime is 9.900
// lhs.time is 9.910 rhs.time is 9.980 length is 0.070
// t is 9.900 - 9.910 / 0.070 = 0.14. So it uses 14% of rhs, 86% of lhs
if (length > 0.0001f)
t = (float)((interpolationTime - lhs.timestamp) / length);
// if t=0 => lhs is used directly
transform.localPosition = Vector3.Lerp(lhs.pos, rhs.pos, t);
transform.localRotation = Quaternion.Slerp(lhs.rot, rhs.rot, t);
return;
}
}
// Use extrapolation
}
else
{
State latest = m_BufferedState[0];
float extrapolationLength = (float)(interpolationTime - latest.timestamp);
// Don't extrapolation for more than 500 ms, you would need to do that carefully
if (extrapolationLength < m_ExtrapolationLimit)
{
float axisLength = extrapolationLength * latest.angularVelocity.magnitude * Mathf.Rad2Deg;
Quaternion angularRotation = Quaternion.AngleAxis(axisLength, latest.angularVelocity);
rigidbody.position = latest.pos + latest.velocity * extrapolationLength;
rigidbody.rotation = angularRotation * latest.rot;
rigidbody.velocity = latest.velocity;
rigidbody.angularVelocity = latest.angularVelocity;
}
}
}
} | 31.783439 | 98 | 0.645691 | [
"MIT"
] | scarlethammergames/showcase | Assets/Scripts/DeftNetwork/DeftRigidBody.cs | 4,992 | C# |
/*
* MemorySharp Library
* http://www.binarysharp.com/
*
* Copyright (C) 2012-2016 Jämes Ménétrey (a.k.a. ZenLulz).
* This library is released under the MIT License.
* See the file LICENSE for more information.
*/
using System;
using System.Collections.Generic;
using Binarysharp.MemoryManagement.Internals;
namespace Binarysharp.MemoryManagement.Assembly
{
/// <summary>
/// Class representing a transaction where the user can insert mnemonics.
/// The code is then executed when the object is disposed.
/// </summary>
public class AssemblyTransaction : IDisposable
{
#region Fields
/// <summary>
/// The reference of the <see cref="MemorySharp"/> object.
/// </summary>
protected readonly MemorySharp MemorySharp;
/// <summary>
/// The builder contains all the instructions inserted by the user.
/// </summary>
public readonly List<string> Instructions;
/// <summary>
/// The exit code of the thread created to execute the assembly code.
/// </summary>
protected IntPtr ExitCode;
#endregion
#region Properties
#region Address
/// <summary>
/// The address where to assembly code is assembled.
/// </summary>
public IntPtr Address { get; private set; }
#endregion
#region IsAutoExecuted
/// <summary>
/// Gets the value indicating whether the assembly code is executed once the object is disposed.
/// </summary>
public bool IsAutoExecuted { get; set; }
#endregion
#endregion
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="AssemblyTransaction"/> class.
/// </summary>
/// <param name="memorySharp">The reference of the <see cref="MemorySharp"/> object.</param>
/// <param name="address">The address where the assembly code is injected.</param>
/// <param name="autoExecute">Indicates whether the assembly code is executed once the object is disposed.</param>
public AssemblyTransaction(MemorySharp memorySharp, IntPtr address, bool autoExecute)
{
// Save the parameters
MemorySharp = memorySharp;
IsAutoExecuted = autoExecute;
Address = address;
// Initialize the string builder
Instructions = new List<string>();
}
/// <summary>
/// Initializes a new instance of the <see cref="AssemblyTransaction"/> class.
/// </summary>
/// <param name="memorySharp">The reference of the <see cref="MemorySharp"/> object.</param>
/// <param name="autoExecute">Indicates whether the assembly code is executed once the object is disposed.</param>
public AssemblyTransaction(MemorySharp memorySharp, bool autoExecute) : this(memorySharp, IntPtr.Zero, autoExecute)
{
}
#endregion
#region Methods
#region Assemble
/// <summary>
/// Assemble the assembly code of this transaction.
/// </summary>
/// <returns>An array of bytes containing the assembly code.</returns>
public byte[] Assemble()
{
return MemorySharp.Assembly.Assembler.Assemble(Instructions);
}
#endregion
#region Dispose (implementation of IDisposable)
/// <summary>
/// Releases all resources used by the <see cref="AssemblyTransaction"/> object.
/// </summary>
public virtual void Dispose()
{
// If a pointer was specified
if (Address != IntPtr.Zero)
{
// If the assembly code must be executed
if (IsAutoExecuted)
{
ExitCode = MemorySharp.Assembly.InjectAndExecute<IntPtr>(Instructions.ToArray(), Address);
}
// Else the assembly code is just injected
else
{
MemorySharp.Assembly.Inject(Instructions.ToArray(), Address);
}
}
// If no pointer was specified and the code assembly code must be executed
if (Address == IntPtr.Zero && IsAutoExecuted)
{
ExitCode = MemorySharp.Assembly.InjectAndExecute<IntPtr>(Instructions.ToArray());
}
}
#endregion
#region GetExitCode
/// <summary>
/// Gets the termination status of the thread.
/// </summary>
public T GetExitCode<T>()
{
return MarshalType<T>.PtrToObject(MemorySharp, ExitCode);
}
#endregion
#endregion
}
}
| 36.813953 | 123 | 0.589387 | [
"MIT"
] | LichProject/MemorySharp | src/MemorySharp/Assembly/AssemblyTransaction.cs | 4,754 | C# |
namespace tomenglertde.ResXManager
{
using System;
using System.Collections.ObjectModel;
using System.ComponentModel.Composition;
using System.Linq;
using System.Windows;
using System.Windows.Input;
using JetBrains.Annotations;
using tomenglertde.ResXManager.Infrastructure;
using TomsToolbox.Core;
using TomsToolbox.Desktop;
using TomsToolbox.Wpf;
using TomsToolbox.Wpf.Composition;
[VisualCompositionExport(RegionId.Content, Sequence = 99)]
[Export(typeof(ITracer))]
public sealed class OutputViewModel : ObservableObject, ITracer
{
[NotNull]
[ItemNotNull]
public ObservableCollection<string> Lines { get; } = new ObservableCollection<string>();
[NotNull]
public ICommand CopyCommand => new DelegateCommand(Copy);
private void Copy()
{
Clipboard.SetText(string.Join(Environment.NewLine, Lines));
}
private void Append([NotNull] string prefix, [NotNull] string value)
{
var lines = value.Split('\n');
Lines.Add(DateTime.Now.ToShortTimeString() + "\t" + prefix + lines[0].Trim('\r'));
Lines.AddRange(lines.Skip(1).Select(l => l.Trim('\r')));
}
void ITracer.TraceError(string value)
{
Append("Error: ", value);
}
void ITracer.TraceWarning(string value)
{
Append("Warning: ", value);
}
void ITracer.WriteLine(string value)
{
Append(string.Empty, value);
}
public override string ToString()
{
return "Output";
}
}
}
| 27.140625 | 97 | 0.581462 | [
"MIT"
] | johnmbaughman/ResXResourceManager | ResXManager/OutputViewModel.cs | 1,739 | C# |
using System;
using System.Collections;
using System.Windows.Forms;
//
// Created by SharpDevelop.
// User: elijah
// Date: 05/20/2011
// Time: 8:45 PM
//
// To change this template use Tools | Options | Coding | Edit Standard Headers.
//
using ICSharpCode.SharpDevelop.Gui.XmlForms;
using System.IO;
using System.Reflection;
namespace SharpLua.SharpDevelop.AddIn
{
public class LuaPad : BaseSharpDevelopUserControl
{
public LuaPad()
{
System.IO.Stream StreamX = System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream("SharpLua.SharpDevelop.AddIn.Pad.xfrm");
SetupFromXmlStream(StreamX);
//AddHandler (Me.Get(Of Button)("test")).Click, AddressOf ButtonClick
SetupWebPage();
}
public void SetupWebPage()
{
WebBrowser WebBrowser = new WebBrowser();
WebBrowser.ScrollBarsEnabled = true;
WebBrowser.ScriptErrorsSuppressed = true;
WebBrowser.Parent = this;
WebBrowser.Location = new System.Drawing.Point(19, 100);
WebBrowser.Size = new System.Drawing.Size(this.Size.Width, this.Size.Height * 3);
WebBrowser.Dock = DockStyle.Fill;
WebBrowser.Navigate("http://www.lua.org/about.html");
}
}
}
| 27.642857 | 146 | 0.738157 | [
"MIT"
] | Stevie-O/SharpLua | OLD.SharpLua/SharpLuaAddIn/Src/MyUserControl.cs | 1,161 | C# |
using System;
using System.Text;
namespace SharpGlyph {
public class GlyphIdOffsetPair {
/// <summary>
/// Glyph ID of glyph present.
/// </summary>
public ushort glyphID;
/// <summary>
/// Location in EBDT.
/// </summary>
public ushort offset;
public static GlyphIdOffsetPair[] ReadArray(BinaryReaderFont reader, int count) {
GlyphIdOffsetPair[] array = new GlyphIdOffsetPair[count];
for (int i = 0; i < count; i++) {
array[i] = Read(reader);
}
return array;
}
public static GlyphIdOffsetPair Read(BinaryReaderFont reader) {
return new GlyphIdOffsetPair {
glyphID = reader.ReadUInt16(),
offset = reader.ReadUInt16()
};
}
public override string ToString() {
StringBuilder builder = new StringBuilder();
builder.AppendLine("{");
builder.AppendFormat("\t\"glyphID\": {0},\n", glyphID);
builder.AppendFormat("\t\"offset\": {0},\n", offset);
builder.Append("}");
return builder.ToString();
}
}
}
| 23.804878 | 83 | 0.656762 | [
"MIT"
] | hikipuro/SharpGlyph | SharpGlyph/SharpGlyph/Tables/EBLC/GlyphIdOffsetPair.cs | 978 | C# |
using System;
using System.Reflection;
namespace GlimpseCore.Agent.Internal.Inspectors.Mvc.Proxies
{
public interface IActionDescriptor
{
string Id { get; }
string DisplayName { get; }
string ActionName { get; }
string ControllerName { get; }
Type ControllerTypeInfo { get; }
MethodInfo MethodInfo { get; }
}
}
| 23.3125 | 59 | 0.63807 | [
"MIT"
] | GlimpseCore/GlimpseCore | src/GlimpseCore.Agent.AspNet/Internal/Inspectors/Mvc/Proxies/IActionDescriptor.cs | 375 | C# |
namespace MuOnline.Core.Commands
{
using Contracts;
using Models.Heroes.HeroContracts;
using Models.Monsters.Contracts;
using Repositories.Contracts;
public class AttackMonsterCommand : ICommand
{
private const string commandMessage = "{0} is the winner!";
private readonly IRepository<IHero> heroRepository;
private readonly IRepository<IMonster> monsterRepository;
public AttackMonsterCommand(IRepository<IHero> heroRepository,
IRepository<IMonster> monsterRepository)
{
this.heroRepository = heroRepository;
this.monsterRepository = monsterRepository;
}
public string Execute(string[] inputArgs)
{
string heroUsername = inputArgs[0];
string monsterUsername = inputArgs[1];
var hero = this.heroRepository.Get(heroUsername);
var monster = this.monsterRepository.Get(monsterUsername);
var heroAttackPoints = hero.TotalAttackPoints;
var monsterAttackPoints = monster.AttackPoints;
while (hero.IsAlive && monster.IsAlive)
{
hero.TakeDamage(monsterAttackPoints);
if (!hero.IsAlive)
{
break;
}
var experience = monster.TakeDamage(heroAttackPoints);
((IProgress)hero).AddExperience(experience);
}
return string.Format(commandMessage,
hero.IsAlive
? hero.GetType().Name
: monster.GetType().Name);
}
}
}
| 30.773585 | 70 | 0.594727 | [
"MIT"
] | MertYumer/C-Fundamentals---January-2019 | C# OOP - February 2019/08. Workshop/MuOnline/Core/Commands/AttackMonsterCommand.cs | 1,633 | C# |
// Copyright (c) Dolittle. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Dolittle.Rules;
using Dolittle.Validation.Rules;
using Machine.Specifications;
using Moq;
using It = Machine.Specifications.It;
namespace Dolittle.Specs.Validation.Rules.for_Required
{
public class when_evaluating_integer_holding_zero
{
static Required rule;
static Mock<IRuleContext> rule_context_mock;
Establish context = () =>
{
rule = new Required(null);
rule_context_mock = new Mock<IRuleContext>();
};
Because of = () => rule.Evaluate(rule_context_mock.Object, 0);
It should_fail_with_value_not_specified_as_reason = () => rule_context_mock.Verify(r => r.Fail(rule, 0, Moq.It.Is<Cause>(_ => _.Reason == Required.ValueNotSpecified)), Moq.Times.Once());
}
}
| 32.714286 | 194 | 0.69214 | [
"MIT"
] | dolittle-fundamentals/DotNET.Fundamentals | Specifications/Validation/Rules/for_Required/when_evaluating_integer_holding_zero.cs | 918 | C# |
using UnityEngine;
using System.Collections;
using HoloToolkit.Unity;
public class tapReact : MonoBehaviour {
[Tooltip("Scale factor to use for tap reaction")]
public float scaleFactor = 0.8f;
[Tooltip("Time in seconds to play the hit and recovery animation")]
public float hitTime = 0.5f;
private Interpolator interp;
private Vector3 origScale;
void Awake()
{
interp = GetComponent<Interpolator>();
}
void Start()
{
origScale = transform.localScale;
}
void OnTap()
{
StartCoroutine(React());
}
IEnumerator React()
{
WaitForSeconds delay = new WaitForSeconds(hitTime);
interp.SetTargetLocalScale(origScale * scaleFactor);
yield return delay;
interp.SetTargetLocalScale(origScale);
}
}
| 21.605263 | 71 | 0.64799 | [
"MIT"
] | Polyrhythm/bud | Assets/Scripts/tapReact.cs | 823 | 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 ec2-2016-11-15.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Net;
using System.Text;
using System.Xml.Serialization;
using Amazon.EC2.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
namespace Amazon.EC2.Model.Internal.MarshallTransformations
{
/// <summary>
/// Response Unmarshaller for ModifyImageAttribute operation
/// </summary>
public class ModifyImageAttributeResponseUnmarshaller : EC2ResponseUnmarshaller
{
/// <summary>
/// Unmarshaller the response from the service to the response class.
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
public override AmazonWebServiceResponse Unmarshall(XmlUnmarshallerContext context)
{
ModifyImageAttributeResponse response = new ModifyImageAttributeResponse();
int originalDepth = context.CurrentDepth;
int targetDepth = originalDepth + 1;
if (context.IsStartOfDocument)
targetDepth = 2;
while (context.ReadAtDepth(originalDepth))
{
if (context.IsStartElement || context.IsAttribute)
{
}
}
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(XmlUnmarshallerContext context, Exception innerException, HttpStatusCode statusCode)
{
ErrorResponse errorResponse = ErrorResponseUnmarshaller.GetInstance().Unmarshall(context);
return new AmazonEC2Exception(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode);
}
private static ModifyImageAttributeResponseUnmarshaller _instance = new ModifyImageAttributeResponseUnmarshaller();
internal static ModifyImageAttributeResponseUnmarshaller GetInstance()
{
return _instance;
}
/// <summary>
/// Gets the singleton.
/// </summary>
public static ModifyImageAttributeResponseUnmarshaller Instance
{
get
{
return _instance;
}
}
}
} | 34.578947 | 158 | 0.657839 | [
"Apache-2.0"
] | ChristopherButtars/aws-sdk-net | sdk/src/Services/EC2/Generated/Model/Internal/MarshallTransformations/ModifyImageAttributeResponseUnmarshaller.cs | 3,285 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// <auto-generated/>
#nullable disable
using System.Collections.Generic;
using System.Text.Json;
using Azure.Core;
namespace Azure.ResourceManager.EventHubs.Models
{
public partial class Encryption : IUtf8JsonSerializable
{
void IUtf8JsonSerializable.Write(Utf8JsonWriter writer)
{
writer.WriteStartObject();
if (KeyVaultProperties != null)
{
writer.WritePropertyName("keyVaultProperties");
writer.WriteStartArray();
foreach (var item in KeyVaultProperties)
{
writer.WriteObjectValue(item);
}
writer.WriteEndArray();
}
if (KeySource != null)
{
writer.WritePropertyName("keySource");
writer.WriteStringValue(KeySource);
}
writer.WriteEndObject();
}
internal static Encryption DeserializeEncryption(JsonElement element)
{
IList<KeyVaultProperties> keyVaultProperties = default;
string keySource = default;
foreach (var property in element.EnumerateObject())
{
if (property.NameEquals("keyVaultProperties"))
{
if (property.Value.ValueKind == JsonValueKind.Null)
{
continue;
}
List<KeyVaultProperties> array = new List<KeyVaultProperties>();
foreach (var item in property.Value.EnumerateArray())
{
if (item.ValueKind == JsonValueKind.Null)
{
array.Add(null);
}
else
{
array.Add(Models.KeyVaultProperties.DeserializeKeyVaultProperties(item));
}
}
keyVaultProperties = array;
continue;
}
if (property.NameEquals("keySource"))
{
if (property.Value.ValueKind == JsonValueKind.Null)
{
continue;
}
keySource = property.Value.GetString();
continue;
}
}
return new Encryption(keyVaultProperties, keySource);
}
}
}
| 33.371795 | 101 | 0.482136 | [
"MIT"
] | AzureDataBox/azure-sdk-for-net | sdk/eventhub/Azure.ResourceManager.EventHubs/src/Generated/Models/Encryption.Serialization.cs | 2,603 | 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.Buffers;
using System.Text;
using System.Diagnostics;
using System.IO;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using System.Security.Cryptography.Asn1;
using System.Security.Cryptography.Pkcs;
using System.Security.Cryptography.Pkcs.Asn1;
using System.Security.Cryptography.X509Certificates;
using X509IssuerSerial = System.Security.Cryptography.Xml.X509IssuerSerial;
namespace Internal.Cryptography
{
internal static partial class PkcsHelpers
{
#if !netcoreapp
// Compatibility API.
internal static void AppendData(this IncrementalHash hasher, ReadOnlySpan<byte> data)
{
hasher.AppendData(data.ToArray());
}
#endif
internal static HashAlgorithmName GetDigestAlgorithm(Oid oid)
{
Debug.Assert(oid != null);
return GetDigestAlgorithm(oid.Value);
}
internal static HashAlgorithmName GetDigestAlgorithm(string oidValue)
{
switch (oidValue)
{
case Oids.Md5:
return HashAlgorithmName.MD5;
case Oids.Sha1:
return HashAlgorithmName.SHA1;
case Oids.Sha256:
return HashAlgorithmName.SHA256;
case Oids.Sha384:
return HashAlgorithmName.SHA384;
case Oids.Sha512:
return HashAlgorithmName.SHA512;
default:
throw new CryptographicException(SR.Cryptography_UnknownHashAlgorithm, oidValue);
}
}
internal static string GetOidFromHashAlgorithm(HashAlgorithmName algName)
{
if (algName == HashAlgorithmName.MD5)
return Oids.Md5;
if (algName == HashAlgorithmName.SHA1)
return Oids.Sha1;
if (algName == HashAlgorithmName.SHA256)
return Oids.Sha256;
if (algName == HashAlgorithmName.SHA384)
return Oids.Sha384;
if (algName == HashAlgorithmName.SHA512)
return Oids.Sha512;
throw new CryptographicException(SR.Cryptography_Cms_UnknownAlgorithm, algName.Name);
}
/// <summary>
/// This is not just a convenience wrapper for Array.Resize(). In DEBUG builds, it forces the array to move in memory even if no resize is needed. This should be used by
/// helper methods that do anything of the form "call a native api once to get the estimated size, call it again to get the data and return the data in a byte[] array."
/// Sometimes, that data consist of a native data structure containing pointers to other parts of the block. Using such a helper to retrieve such a block results in an intermittent
/// AV. By using this helper, you make that AV repro every time.
/// </summary>
public static byte[] Resize(this byte[] a, int size)
{
Array.Resize(ref a, size);
#if DEBUG
a = a.CloneByteArray();
#endif
return a;
}
public static void RemoveAt<T>(ref T[] arr, int idx)
{
Debug.Assert(arr != null);
Debug.Assert(idx >= 0);
Debug.Assert(idx < arr.Length);
if (arr.Length == 1)
{
arr = Array.Empty<T>();
return;
}
T[] tmp = new T[arr.Length - 1];
if (idx != 0)
{
Array.Copy(arr, 0, tmp, 0, idx);
}
if (idx < tmp.Length)
{
Array.Copy(arr, idx + 1, tmp, idx, tmp.Length - idx);
}
arr = tmp;
}
public static T[] NormalizeSet<T>(
T[] setItems,
Action<byte[]> encodedValueProcessor=null)
{
AsnSet<T> set = new AsnSet<T>
{
SetData = setItems,
};
AsnWriter writer = AsnSerializer.Serialize(set, AsnEncodingRules.DER);
byte[] normalizedValue = writer.Encode();
set = AsnSerializer.Deserialize<AsnSet<T>>(normalizedValue, AsnEncodingRules.DER);
if (encodedValueProcessor != null)
{
encodedValueProcessor(normalizedValue);
}
return set.SetData;
}
internal static byte[] EncodeContentInfo<T>(
T value,
string contentType,
AsnEncodingRules ruleSet = AsnEncodingRules.DER)
{
using (AsnWriter innerWriter = AsnSerializer.Serialize(value, ruleSet))
{
ContentInfoAsn content = new ContentInfoAsn
{
ContentType = contentType,
Content = innerWriter.Encode(),
};
using (AsnWriter outerWriter = AsnSerializer.Serialize(content, ruleSet))
{
return outerWriter.Encode();
}
}
}
public static CmsRecipientCollection DeepCopy(this CmsRecipientCollection recipients)
{
CmsRecipientCollection recipientsCopy = new CmsRecipientCollection();
foreach (CmsRecipient recipient in recipients)
{
X509Certificate2 originalCert = recipient.Certificate;
X509Certificate2 certCopy = new X509Certificate2(originalCert.Handle);
CmsRecipient recipientCopy = new CmsRecipient(recipient.RecipientIdentifierType, certCopy);
recipientsCopy.Add(recipientCopy);
GC.KeepAlive(originalCert);
}
return recipientsCopy;
}
public static byte[] UnicodeToOctetString(this string s)
{
byte[] octets = new byte[2 * (s.Length + 1)];
Encoding.Unicode.GetBytes(s, 0, s.Length, octets, 0);
return octets;
}
public static string OctetStringToUnicode(this byte[] octets)
{
if (octets.Length < 2)
return string.Empty; // Desktop compat: 0-length byte array maps to string.empty. 1-length byte array gets passed to Marshal.PtrToStringUni() with who knows what outcome.
string s = Encoding.Unicode.GetString(octets, 0, octets.Length - 2);
return s;
}
public static X509Certificate2Collection GetStoreCertificates(StoreName storeName, StoreLocation storeLocation, bool openExistingOnly)
{
using (X509Store store = new X509Store(storeName, storeLocation))
{
OpenFlags flags = OpenFlags.ReadOnly | OpenFlags.IncludeArchived;
if (openExistingOnly)
flags |= OpenFlags.OpenExistingOnly;
store.Open(flags);
X509Certificate2Collection certificates = store.Certificates;
return certificates;
}
}
/// <summary>
/// Desktop compat: We do not complain about multiple matches. Just take the first one and ignore the rest.
/// </summary>
public static X509Certificate2 TryFindMatchingCertificate(this X509Certificate2Collection certs, SubjectIdentifier recipientIdentifier)
{
//
// Note: SubjectIdentifier has no public constructor so the only one that can construct this type is this assembly.
// Therefore, we trust that the string-ized byte array (serial or ski) in it is correct and canonicalized.
//
SubjectIdentifierType recipientIdentifierType = recipientIdentifier.Type;
switch (recipientIdentifierType)
{
case SubjectIdentifierType.IssuerAndSerialNumber:
{
X509IssuerSerial issuerSerial = (X509IssuerSerial)(recipientIdentifier.Value);
byte[] serialNumber = issuerSerial.SerialNumber.ToSerialBytes();
string issuer = issuerSerial.IssuerName;
foreach (X509Certificate2 candidate in certs)
{
byte[] candidateSerialNumber = candidate.GetSerialNumber();
if (AreByteArraysEqual(candidateSerialNumber, serialNumber) && candidate.Issuer == issuer)
return candidate;
}
}
break;
case SubjectIdentifierType.SubjectKeyIdentifier:
{
string skiString = (string)(recipientIdentifier.Value);
byte[] ski = skiString.ToSkiBytes();
foreach (X509Certificate2 cert in certs)
{
byte[] candidateSki = PkcsPal.Instance.GetSubjectKeyIdentifier(cert);
if (AreByteArraysEqual(ski, candidateSki))
return cert;
}
}
break;
default:
// RecipientInfo's can only be created by this package so if this an invalid type, it's the package's fault.
Debug.Fail($"Invalid recipientIdentifier type: {recipientIdentifierType}");
throw new CryptographicException();
}
return null;
}
internal static bool AreByteArraysEqual(byte[] ba1, byte[] ba2)
{
if (ba1.Length != ba2.Length)
return false;
for (int i = 0; i < ba1.Length; i++)
{
if (ba1[i] != ba2[i])
return false;
}
return true;
}
/// <summary>
/// Asserts on bad or non-canonicalized input. Input must come from trusted sources.
///
/// Subject Key Identifier is string-ized as an upper case hex string. This format is part of the public api behavior and cannot be changed.
/// </summary>
internal static byte[] ToSkiBytes(this string skiString)
{
return skiString.UpperHexStringToByteArray();
}
public static string ToSkiString(this byte[] skiBytes)
{
return ToUpperHexString(skiBytes);
}
public static string ToBigEndianHex(this ReadOnlySpan<byte> bytes)
{
return ToUpperHexString(bytes);
}
/// <summary>
/// Asserts on bad or non-canonicalized input. Input must come from trusted sources.
///
/// Serial number is string-ized as a reversed upper case hex string. This format is part of the public api behavior and cannot be changed.
/// </summary>
internal static byte[] ToSerialBytes(this string serialString)
{
byte[] ba = serialString.UpperHexStringToByteArray();
Array.Reverse(ba);
return ba;
}
public static string ToSerialString(this byte[] serialBytes)
{
serialBytes = serialBytes.CloneByteArray();
Array.Reverse(serialBytes);
return ToUpperHexString(serialBytes);
}
private static string ToUpperHexString(ReadOnlySpan<byte> ba)
{
StringBuilder sb = new StringBuilder(ba.Length * 2);
for (int i = 0; i < ba.Length; i++)
{
sb.Append(ba[i].ToString("X2"));
}
return sb.ToString();
}
/// <summary>
/// Asserts on bad input. Input must come from trusted sources.
/// </summary>
private static byte[] UpperHexStringToByteArray(this string normalizedString)
{
Debug.Assert((normalizedString.Length & 0x1) == 0);
byte[] ba = new byte[normalizedString.Length / 2];
for (int i = 0; i < ba.Length; i++)
{
char c = normalizedString[i * 2];
byte b = (byte)(UpperHexCharToNybble(c) << 4);
c = normalizedString[i * 2 + 1];
b |= UpperHexCharToNybble(c);
ba[i] = b;
}
return ba;
}
/// <summary>
/// Asserts on bad input. Input must come from trusted sources.
/// </summary>
private static byte UpperHexCharToNybble(char c)
{
if (c >= '0' && c <= '9')
return (byte)(c - '0');
if (c >= 'A' && c <= 'F')
return (byte)(c - 'A' + 10);
Debug.Fail($"Invalid hex character: {c}");
throw new CryptographicException(); // This just keeps the compiler happy. We don't expect to reach this.
}
/// <summary>
/// Useful helper for "upgrading" well-known CMS attributes to type-specific objects such as Pkcs9DocumentName, Pkcs9DocumentDescription, etc.
/// </summary>
public static Pkcs9AttributeObject CreateBestPkcs9AttributeObjectAvailable(Oid oid, byte[] encodedAttribute)
{
Pkcs9AttributeObject attributeObject = new Pkcs9AttributeObject(oid, encodedAttribute);
switch (oid.Value)
{
case Oids.DocumentName:
attributeObject = Upgrade<Pkcs9DocumentName>(attributeObject);
break;
case Oids.DocumentDescription:
attributeObject = Upgrade<Pkcs9DocumentDescription>(attributeObject);
break;
case Oids.SigningTime:
attributeObject = Upgrade<Pkcs9SigningTime>(attributeObject);
break;
case Oids.ContentType:
attributeObject = Upgrade<Pkcs9ContentType>(attributeObject);
break;
case Oids.MessageDigest:
attributeObject = Upgrade<Pkcs9MessageDigest>(attributeObject);
break;
#if netcoreapp
case Oids.LocalKeyId:
attributeObject = Upgrade<Pkcs9LocalKeyId>(attributeObject);
break;
#endif
default:
break;
}
return attributeObject;
}
private static T Upgrade<T>(Pkcs9AttributeObject basicAttribute) where T : Pkcs9AttributeObject, new()
{
T enhancedAttribute = new T();
enhancedAttribute.CopyFrom(basicAttribute);
return enhancedAttribute;
}
internal static byte[] OneShot(this ICryptoTransform transform, byte[] data)
{
return OneShot(transform, data, 0, data.Length);
}
internal static byte[] OneShot(this ICryptoTransform transform, byte[] data, int offset, int length)
{
if (transform.CanTransformMultipleBlocks)
{
return transform.TransformFinalBlock(data, offset, length);
}
using (MemoryStream memoryStream = new MemoryStream())
{
using (var cryptoStream = new CryptoStream(memoryStream, transform, CryptoStreamMode.Write))
{
cryptoStream.Write(data, offset, length);
}
return memoryStream.ToArray();
}
}
public static ReadOnlyMemory<byte> DecodeOctetString(ReadOnlyMemory<byte> encodedOctetString)
{
AsnReader reader = new AsnReader(encodedOctetString, AsnEncodingRules.BER);
if (reader.PeekEncodedValue().Length != encodedOctetString.Length)
{
throw new CryptographicException(SR.Cryptography_Der_Invalid_Encoding);
}
if (reader.TryGetPrimitiveOctetStringBytes(out ReadOnlyMemory<byte> primitiveContents))
{
return primitiveContents;
}
byte[] tooBig = new byte[encodedOctetString.Length];
if (reader.TryCopyOctetStringBytes(tooBig, out int bytesWritten))
{
return tooBig.AsMemory(0, bytesWritten);
}
Debug.Fail("TryCopyOctetStringBytes failed with an over-allocated array");
throw new CryptographicException();
}
[StructLayout(LayoutKind.Sequential)]
internal struct AsnSet<T>
{
[SetOf]
public T[] SetData;
}
}
}
| 37.5 | 188 | 0.561614 | [
"MIT"
] | AraHaan/corefx | src/System.Security.Cryptography.Pkcs/src/Internal/Cryptography/PkcsHelpers.cs | 16,725 | 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("TrackableData.Redis.Tests")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("SaladLab")]
[assembly: AssemblyProduct("TrackableData.Redis.Tests")]
[assembly: AssemblyCopyright("Copyright © 2016 SaladLab")]
[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("df1be9ee-c051-4915-b1c0-fe3db423e946")]
// 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.756757 | 84 | 0.752441 | [
"MIT"
] | SaladLab/TrackableData | plugins/TrackableData.Redis.Tests/Properties/AssemblyInfo.cs | 1,437 | C# |
using UnityEngine;
namespace Exanite.Core.Utilities
{
/// <summary>
/// Utility class for miscellaneous Unity methods
/// </summary>
public static class UnityUtility
{
/// <summary>
/// Calls Destroy in Play mode and calls DestroyImmediate in Edit
/// mode
/// </summary>
public static void SafeDestroy(Object obj)
{
if (Application.isPlaying)
{
Object.Destroy(obj);
}
else
{
Object.DestroyImmediate(obj);
}
}
/// <summary>
/// Logs the <paramref name="name" /> and <paramref name="value" />
/// formatted as 'name: value' to the Unity console
/// </summary>
public static void LogVariable(string name, object value)
{
Debug.Log($"{name}: {value}");
}
}
} | 26.571429 | 79 | 0.494624 | [
"MIT"
] | Exanite/Exanite.Core | Utilities/UnityUtility.cs | 932 | C# |
using Microsoft.AspNetCore.Blazor.Hosting;
namespace Blazor.IndexedDB.Framework.Example
{
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IWebAssemblyHostBuilder CreateHostBuilder(string[] args) =>
BlazorWebAssemblyHost.CreateDefaultBuilder()
.UseBlazorStartup<Startup>();
}
}
| 25.588235 | 81 | 0.643678 | [
"MIT"
] | Reshiru/Blazor.IndexedDB.Connector | src/Blazor.IndexedDB.Framework/Blazor.IndexedDB.Framework.Example/Program.cs | 437 | C# |
using System.IO;
namespace mi2cs.Helpers
{
public static class ResourcesHelper
{
public static string ReadResourceContent(string resourceName)
{
var assembly = typeof(ResourcesHelper).Assembly;
using (var stream = assembly.GetManifestResourceStream(resourceName))
{
using (var reader = new StreamReader(stream))
{
return reader.ReadToEnd();
}
}
}
}
}
| 25.25 | 81 | 0.546535 | [
"MIT"
] | matthewrdev/mi2cs | mi2cs/Helpers/ResourcesHelper.cs | 507 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using UnityEngine;
namespace Microsoft.MixedReality.Toolkit.Utilities.Solvers
{
/// <summary>
/// Provides a solver that follows the TrackedObject/TargetTransform in an orbital motion.
/// </summary>
public class Orbital : Solver
{
[SerializeField]
[Tooltip("The desired orientation of this object. Default sets the object to face the TrackedObject/TargetTransform. CameraFacing sets the object to always face the user.")]
private SolverOrientationType orientationType = SolverOrientationType.FollowTrackedObject;
/// <summary>
/// The desired orientation of this object.
/// </summary>
/// <remarks>
/// Default sets the object to face the TrackedObject/TargetTransform. CameraFacing sets the object to always face the user.
/// </remarks>
public SolverOrientationType OrientationType
{
get { return orientationType; }
set { orientationType = value; }
}
[SerializeField]
[Tooltip("XYZ offset for this object in relation to the TrackedObject/TargetTransform. Mixing local and world offsets is not recommended.")]
private Vector3 localOffset = new Vector3(0, -1, 1);
/// <summary>
/// XYZ offset for this object in relation to the TrackedObject/TargetTransform.
/// </summary>
/// <remarks>
/// Mixing local and world offsets is not recommended.
/// </remarks>
public Vector3 LocalOffset
{
get { return localOffset; }
set { localOffset = value; }
}
[SerializeField]
[Tooltip("XYZ offset for this object in worldspace, best used with the YawOnly orientationType. Mixing local and world offsets is not recommended.")]
private Vector3 worldOffset = Vector3.zero;
/// <summary>
/// XYZ offset for this object in worldspace, best used with the YawOnly orientationType.
/// </summary>
/// <remarks>
/// Mixing local and world offsets is not recommended.
/// </remarks>
public Vector3 WorldOffset
{
get { return worldOffset; }
set { worldOffset = value; }
}
[SerializeField]
[Tooltip("Lock the rotation to a specified number of steps around the tracked object.")]
private bool useAngleSteppingForWorldOffset = false;
/// <summary>
/// Lock the rotation to a specified number of steps around the tracked object.
/// </summary>
public bool UseAngleSteppingForWorldOffset
{
get { return useAngleSteppingForWorldOffset; }
set { useAngleSteppingForWorldOffset = value; }
}
[Range(2, 24)]
[SerializeField]
[Tooltip("The division of steps this object can tether to. Higher the number, the more snapple steps.")]
private int tetherAngleSteps = 6;
/// <summary>
/// The division of steps this object can tether to. Higher the number, the more snapple steps.
/// </summary>
public int TetherAngleSteps
{
get { return tetherAngleSteps; }
set
{
tetherAngleSteps = Mathf.Clamp(value, 2, 24);
}
}
public override void SolverUpdate()
{
Vector3 desiredPos = SolverHandler.TransformTarget != null ? SolverHandler.TransformTarget.position : Vector3.zero;
Quaternion targetRot = SolverHandler.TransformTarget != null ? SolverHandler.TransformTarget.rotation : Quaternion.Euler(0, 1, 0);
Quaternion yawOnlyRot = Quaternion.Euler(0, targetRot.eulerAngles.y, 0);
desiredPos = desiredPos + (SnapToTetherAngleSteps(targetRot) * LocalOffset);
desiredPos = desiredPos + (SnapToTetherAngleSteps(yawOnlyRot) * WorldOffset);
Quaternion desiredRot = CalculateDesiredRotation(desiredPos);
GoalPosition = desiredPos;
GoalRotation = desiredRot;
UpdateWorkingPositionToGoal();
UpdateWorkingRotationToGoal();
}
private Quaternion SnapToTetherAngleSteps(Quaternion rotationToSnap)
{
if (!UseAngleSteppingForWorldOffset || SolverHandler.TransformTarget == null)
{
return rotationToSnap;
}
float stepAngle = 360f / tetherAngleSteps;
int numberOfSteps = Mathf.RoundToInt(SolverHandler.TransformTarget.transform.eulerAngles.y / stepAngle);
float newAngle = stepAngle * numberOfSteps;
return Quaternion.Euler(rotationToSnap.eulerAngles.x, newAngle, rotationToSnap.eulerAngles.z);
}
private Quaternion CalculateDesiredRotation(Vector3 desiredPos)
{
Quaternion desiredRot = Quaternion.identity;
switch (orientationType)
{
case SolverOrientationType.YawOnly:
float targetYRotation = SolverHandler.TransformTarget != null ? SolverHandler.TransformTarget.eulerAngles.y : 0.0f;
desiredRot = Quaternion.Euler(0f, targetYRotation, 0f);
break;
case SolverOrientationType.Unmodified:
desiredRot = transform.rotation;
break;
case SolverOrientationType.CameraAligned:
desiredRot = CameraCache.Main.transform.rotation;
break;
case SolverOrientationType.FaceTrackedObject:
desiredRot = SolverHandler.TransformTarget != null ? Quaternion.LookRotation(SolverHandler.TransformTarget.position - desiredPos) : Quaternion.identity;
break;
case SolverOrientationType.CameraFacing:
desiredRot = SolverHandler.TransformTarget != null ? Quaternion.LookRotation(CameraCache.Main.transform.position - desiredPos) : Quaternion.identity;
break;
case SolverOrientationType.FollowTrackedObject:
desiredRot = SolverHandler.TransformTarget != null ? SolverHandler.TransformTarget.rotation : Quaternion.identity;
break;
default:
Debug.LogError($"Invalid OrientationType for Orbital Solver on {gameObject.name}");
break;
}
if (UseAngleSteppingForWorldOffset)
{
desiredRot = SnapToTetherAngleSteps(desiredRot);
}
return desiredRot;
}
}
} | 41.546012 | 181 | 0.620939 | [
"MIT"
] | AdamMitchell-ms/MixedRealityToolkit-Unity | Assets/MixedRealityToolkit.SDK/Features/Utilities/Solvers/Orbital.cs | 6,772 | 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 directconnect-2012-10-25.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using System.Net;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.DirectConnect.Model
{
/// <summary>
/// Information about a virtual interface.
/// </summary>
public partial class AllocatePublicVirtualInterfaceResponse : AmazonWebServiceResponse
{
private AddressFamily _addressFamily;
private string _amazonAddress;
private long? _amazonSideAsn;
private int? _asn;
private string _authKey;
private string _awsDeviceV2;
private List<BGPPeer> _bgpPeers = new List<BGPPeer>();
private string _connectionId;
private string _customerAddress;
private string _customerRouterConfig;
private string _directConnectGatewayId;
private bool? _jumboFrameCapable;
private string _location;
private int? _mtu;
private string _ownerAccount;
private string _region;
private List<RouteFilterPrefix> _routeFilterPrefixes = new List<RouteFilterPrefix>();
private List<Tag> _tags = new List<Tag>();
private string _virtualGatewayId;
private string _virtualInterfaceId;
private string _virtualInterfaceName;
private VirtualInterfaceState _virtualInterfaceState;
private string _virtualInterfaceType;
private int? _vlan;
/// <summary>
/// Gets and sets the property AddressFamily.
/// <para>
/// The address family for the BGP peer.
/// </para>
/// </summary>
public AddressFamily AddressFamily
{
get { return this._addressFamily; }
set { this._addressFamily = value; }
}
// Check to see if AddressFamily property is set
internal bool IsSetAddressFamily()
{
return this._addressFamily != null;
}
/// <summary>
/// Gets and sets the property AmazonAddress.
/// <para>
/// The IP address assigned to the Amazon interface.
/// </para>
/// </summary>
public string AmazonAddress
{
get { return this._amazonAddress; }
set { this._amazonAddress = value; }
}
// Check to see if AmazonAddress property is set
internal bool IsSetAmazonAddress()
{
return this._amazonAddress != null;
}
/// <summary>
/// Gets and sets the property AmazonSideAsn.
/// <para>
/// The autonomous system number (ASN) for the Amazon side of the connection.
/// </para>
/// </summary>
public long AmazonSideAsn
{
get { return this._amazonSideAsn.GetValueOrDefault(); }
set { this._amazonSideAsn = value; }
}
// Check to see if AmazonSideAsn property is set
internal bool IsSetAmazonSideAsn()
{
return this._amazonSideAsn.HasValue;
}
/// <summary>
/// Gets and sets the property Asn.
/// <para>
/// The autonomous system (AS) number for Border Gateway Protocol (BGP) configuration.
/// </para>
///
/// <para>
/// The valid values are 1-2147483647.
/// </para>
/// </summary>
public int Asn
{
get { return this._asn.GetValueOrDefault(); }
set { this._asn = value; }
}
// Check to see if Asn property is set
internal bool IsSetAsn()
{
return this._asn.HasValue;
}
/// <summary>
/// Gets and sets the property AuthKey.
/// <para>
/// The authentication key for BGP configuration. This string has a minimum length of
/// 6 characters and and a maximun lenth of 80 characters.
/// </para>
/// </summary>
public string AuthKey
{
get { return this._authKey; }
set { this._authKey = value; }
}
// Check to see if AuthKey property is set
internal bool IsSetAuthKey()
{
return this._authKey != null;
}
/// <summary>
/// Gets and sets the property AwsDeviceV2.
/// <para>
/// The Direct Connect endpoint on which the virtual interface terminates.
/// </para>
/// </summary>
public string AwsDeviceV2
{
get { return this._awsDeviceV2; }
set { this._awsDeviceV2 = value; }
}
// Check to see if AwsDeviceV2 property is set
internal bool IsSetAwsDeviceV2()
{
return this._awsDeviceV2 != null;
}
/// <summary>
/// Gets and sets the property BgpPeers.
/// <para>
/// The BGP peers configured on this virtual interface.
/// </para>
/// </summary>
public List<BGPPeer> BgpPeers
{
get { return this._bgpPeers; }
set { this._bgpPeers = value; }
}
// Check to see if BgpPeers property is set
internal bool IsSetBgpPeers()
{
return this._bgpPeers != null && this._bgpPeers.Count > 0;
}
/// <summary>
/// Gets and sets the property ConnectionId.
/// <para>
/// The ID of the connection.
/// </para>
/// </summary>
public string ConnectionId
{
get { return this._connectionId; }
set { this._connectionId = value; }
}
// Check to see if ConnectionId property is set
internal bool IsSetConnectionId()
{
return this._connectionId != null;
}
/// <summary>
/// Gets and sets the property CustomerAddress.
/// <para>
/// The IP address assigned to the customer interface.
/// </para>
/// </summary>
public string CustomerAddress
{
get { return this._customerAddress; }
set { this._customerAddress = value; }
}
// Check to see if CustomerAddress property is set
internal bool IsSetCustomerAddress()
{
return this._customerAddress != null;
}
/// <summary>
/// Gets and sets the property CustomerRouterConfig.
/// <para>
/// The customer router configuration.
/// </para>
/// </summary>
public string CustomerRouterConfig
{
get { return this._customerRouterConfig; }
set { this._customerRouterConfig = value; }
}
// Check to see if CustomerRouterConfig property is set
internal bool IsSetCustomerRouterConfig()
{
return this._customerRouterConfig != null;
}
/// <summary>
/// Gets and sets the property DirectConnectGatewayId.
/// <para>
/// The ID of the Direct Connect gateway.
/// </para>
/// </summary>
public string DirectConnectGatewayId
{
get { return this._directConnectGatewayId; }
set { this._directConnectGatewayId = value; }
}
// Check to see if DirectConnectGatewayId property is set
internal bool IsSetDirectConnectGatewayId()
{
return this._directConnectGatewayId != null;
}
/// <summary>
/// Gets and sets the property JumboFrameCapable.
/// <para>
/// Indicates whether jumbo frames (9001 MTU) are supported.
/// </para>
/// </summary>
public bool JumboFrameCapable
{
get { return this._jumboFrameCapable.GetValueOrDefault(); }
set { this._jumboFrameCapable = value; }
}
// Check to see if JumboFrameCapable property is set
internal bool IsSetJumboFrameCapable()
{
return this._jumboFrameCapable.HasValue;
}
/// <summary>
/// Gets and sets the property Location.
/// <para>
/// The location of the connection.
/// </para>
/// </summary>
public string Location
{
get { return this._location; }
set { this._location = value; }
}
// Check to see if Location property is set
internal bool IsSetLocation()
{
return this._location != null;
}
/// <summary>
/// Gets and sets the property Mtu.
/// <para>
/// The maximum transmission unit (MTU), in bytes. The supported values are 1500 and 9001.
/// The default value is 1500.
/// </para>
/// </summary>
public int Mtu
{
get { return this._mtu.GetValueOrDefault(); }
set { this._mtu = value; }
}
// Check to see if Mtu property is set
internal bool IsSetMtu()
{
return this._mtu.HasValue;
}
/// <summary>
/// Gets and sets the property OwnerAccount.
/// <para>
/// The ID of the AWS account that owns the virtual interface.
/// </para>
/// </summary>
public string OwnerAccount
{
get { return this._ownerAccount; }
set { this._ownerAccount = value; }
}
// Check to see if OwnerAccount property is set
internal bool IsSetOwnerAccount()
{
return this._ownerAccount != null;
}
/// <summary>
/// Gets and sets the property Region.
/// <para>
/// The AWS Region where the virtual interface is located.
/// </para>
/// </summary>
public string Region
{
get { return this._region; }
set { this._region = value; }
}
// Check to see if Region property is set
internal bool IsSetRegion()
{
return this._region != null;
}
/// <summary>
/// Gets and sets the property RouteFilterPrefixes.
/// <para>
/// The routes to be advertised to the AWS network in this Region. Applies to public virtual
/// interfaces.
/// </para>
/// </summary>
public List<RouteFilterPrefix> RouteFilterPrefixes
{
get { return this._routeFilterPrefixes; }
set { this._routeFilterPrefixes = value; }
}
// Check to see if RouteFilterPrefixes property is set
internal bool IsSetRouteFilterPrefixes()
{
return this._routeFilterPrefixes != null && this._routeFilterPrefixes.Count > 0;
}
/// <summary>
/// Gets and sets the property Tags.
/// <para>
/// The tags associated with the virtual interface.
/// </para>
/// </summary>
[AWSProperty(Min=1)]
public List<Tag> Tags
{
get { return this._tags; }
set { this._tags = value; }
}
// Check to see if Tags property is set
internal bool IsSetTags()
{
return this._tags != null && this._tags.Count > 0;
}
/// <summary>
/// Gets and sets the property VirtualGatewayId.
/// <para>
/// The ID of the virtual private gateway. Applies only to private virtual interfaces.
/// </para>
/// </summary>
public string VirtualGatewayId
{
get { return this._virtualGatewayId; }
set { this._virtualGatewayId = value; }
}
// Check to see if VirtualGatewayId property is set
internal bool IsSetVirtualGatewayId()
{
return this._virtualGatewayId != null;
}
/// <summary>
/// Gets and sets the property VirtualInterfaceId.
/// <para>
/// The ID of the virtual interface.
/// </para>
/// </summary>
public string VirtualInterfaceId
{
get { return this._virtualInterfaceId; }
set { this._virtualInterfaceId = value; }
}
// Check to see if VirtualInterfaceId property is set
internal bool IsSetVirtualInterfaceId()
{
return this._virtualInterfaceId != null;
}
/// <summary>
/// Gets and sets the property VirtualInterfaceName.
/// <para>
/// The name of the virtual interface assigned by the customer network. The name has a
/// maximum of 100 characters. The following are valid characters: a-z, 0-9 and a hyphen
/// (-).
/// </para>
/// </summary>
public string VirtualInterfaceName
{
get { return this._virtualInterfaceName; }
set { this._virtualInterfaceName = value; }
}
// Check to see if VirtualInterfaceName property is set
internal bool IsSetVirtualInterfaceName()
{
return this._virtualInterfaceName != null;
}
/// <summary>
/// Gets and sets the property VirtualInterfaceState.
/// <para>
/// The state of the virtual interface. The following are the possible values:
/// </para>
/// <ul> <li>
/// <para>
/// <code>confirming</code>: The creation of the virtual interface is pending confirmation
/// from the virtual interface owner. If the owner of the virtual interface is different
/// from the owner of the connection on which it is provisioned, then the virtual interface
/// will remain in this state until it is confirmed by the virtual interface owner.
/// </para>
/// </li> <li>
/// <para>
/// <code>verifying</code>: This state only applies to public virtual interfaces. Each
/// public virtual interface needs validation before the virtual interface can be created.
/// </para>
/// </li> <li>
/// <para>
/// <code>pending</code>: A virtual interface is in this state from the time that it
/// is created until the virtual interface is ready to forward traffic.
/// </para>
/// </li> <li>
/// <para>
/// <code>available</code>: A virtual interface that is able to forward traffic.
/// </para>
/// </li> <li>
/// <para>
/// <code>down</code>: A virtual interface that is BGP down.
/// </para>
/// </li> <li>
/// <para>
/// <code>deleting</code>: A virtual interface is in this state immediately after calling
/// <a>DeleteVirtualInterface</a> until it can no longer forward traffic.
/// </para>
/// </li> <li>
/// <para>
/// <code>deleted</code>: A virtual interface that cannot forward traffic.
/// </para>
/// </li> <li>
/// <para>
/// <code>rejected</code>: The virtual interface owner has declined creation of the virtual
/// interface. If a virtual interface in the <code>Confirming</code> state is deleted
/// by the virtual interface owner, the virtual interface enters the <code>Rejected</code>
/// state.
/// </para>
/// </li> <li>
/// <para>
/// <code>unknown</code>: The state of the virtual interface is not available.
/// </para>
/// </li> </ul>
/// </summary>
public VirtualInterfaceState VirtualInterfaceState
{
get { return this._virtualInterfaceState; }
set { this._virtualInterfaceState = value; }
}
// Check to see if VirtualInterfaceState property is set
internal bool IsSetVirtualInterfaceState()
{
return this._virtualInterfaceState != null;
}
/// <summary>
/// Gets and sets the property VirtualInterfaceType.
/// <para>
/// The type of virtual interface. The possible values are <code>private</code> and <code>public</code>.
/// </para>
/// </summary>
public string VirtualInterfaceType
{
get { return this._virtualInterfaceType; }
set { this._virtualInterfaceType = value; }
}
// Check to see if VirtualInterfaceType property is set
internal bool IsSetVirtualInterfaceType()
{
return this._virtualInterfaceType != null;
}
/// <summary>
/// Gets and sets the property Vlan.
/// <para>
/// The ID of the VLAN.
/// </para>
/// </summary>
public int Vlan
{
get { return this._vlan.GetValueOrDefault(); }
set { this._vlan = value; }
}
// Check to see if Vlan property is set
internal bool IsSetVlan()
{
return this._vlan.HasValue;
}
}
} | 33.181818 | 113 | 0.535452 | [
"Apache-2.0"
] | philasmar/aws-sdk-net | sdk/src/Services/DirectConnect/Generated/Model/AllocatePublicVirtualInterfaceResponse.cs | 18,250 | C# |
namespace SKIT.FlurlHttpClient.Wechat.Work.Models
{
/// <summary>
/// <para>表示 [POST] /cgi-bin/corpgroup/corp/list_app_share_info 接口的响应。</para>
/// </summary>
public class CgibinCorpGroupCropListAppShareInfoResponse : WechatWorkResponse
{
public static class Types
{
public class Agent
{
/// <summary>
/// 获取或设置下级企业 CorpId。
/// </summary>
[Newtonsoft.Json.JsonProperty("corpid")]
[System.Text.Json.Serialization.JsonPropertyName("corpid")]
public string CorpId { get; set; } = default!;
/// <summary>
/// 获取或设置下级企业名称。
/// </summary>
[Newtonsoft.Json.JsonProperty("corp_name")]
[System.Text.Json.Serialization.JsonPropertyName("corp_name")]
public string CorpName { get; set; } = default!;
/// <summary>
/// 获取或设置下级企业应用 ID。
/// </summary>
[Newtonsoft.Json.JsonProperty("agentid")]
[System.Text.Json.Serialization.JsonPropertyName("agentid")]
public int AgentId { get; set; }
}
}
/// <summary>
/// 获取或设置下级企业应用列表。
/// </summary>
[Newtonsoft.Json.JsonProperty("corp_list")]
[System.Text.Json.Serialization.JsonPropertyName("corp_list")]
public Types.Agent[] AgentList { get; set; } = default!;
}
}
| 35.302326 | 81 | 0.523715 | [
"MIT"
] | OrchesAdam/DotNetCore.SKIT.FlurlHttpClient.Wechat | src/SKIT.FlurlHttpClient.Wechat.Work/Models/CgibinCorpGroup/CgibinCorpGroupCropListAppShareInfoResponse.cs | 1,632 | C# |
using Microsoft.EntityFrameworkCore.Migrations;
namespace SolarCoffee.Data.Migrations
{
public partial class Orders : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropForeignKey(
name: "FK_SalesOrderItems_SlSalesOrders_SalesOrderId",
table: "SalesOrderItems");
migrationBuilder.DropForeignKey(
name: "FK_SlSalesOrders_Customers_CustomerId",
table: "SlSalesOrders");
migrationBuilder.DropPrimaryKey(
name: "PK_SlSalesOrders",
table: "SlSalesOrders");
migrationBuilder.RenameTable(
name: "SlSalesOrders",
newName: "SalesOrders");
migrationBuilder.RenameIndex(
name: "IX_SlSalesOrders_CustomerId",
table: "SalesOrders",
newName: "IX_SalesOrders_CustomerId");
migrationBuilder.AddPrimaryKey(
name: "PK_SalesOrders",
table: "SalesOrders",
column: "Id");
migrationBuilder.AddForeignKey(
name: "FK_SalesOrderItems_SalesOrders_SalesOrderId",
table: "SalesOrderItems",
column: "SalesOrderId",
principalTable: "SalesOrders",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_SalesOrders_Customers_CustomerId",
table: "SalesOrders",
column: "CustomerId",
principalTable: "Customers",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropForeignKey(
name: "FK_SalesOrderItems_SalesOrders_SalesOrderId",
table: "SalesOrderItems");
migrationBuilder.DropForeignKey(
name: "FK_SalesOrders_Customers_CustomerId",
table: "SalesOrders");
migrationBuilder.DropPrimaryKey(
name: "PK_SalesOrders",
table: "SalesOrders");
migrationBuilder.RenameTable(
name: "SalesOrders",
newName: "SlSalesOrders");
migrationBuilder.RenameIndex(
name: "IX_SalesOrders_CustomerId",
table: "SlSalesOrders",
newName: "IX_SlSalesOrders_CustomerId");
migrationBuilder.AddPrimaryKey(
name: "PK_SlSalesOrders",
table: "SlSalesOrders",
column: "Id");
migrationBuilder.AddForeignKey(
name: "FK_SalesOrderItems_SlSalesOrders_SalesOrderId",
table: "SalesOrderItems",
column: "SalesOrderId",
principalTable: "SlSalesOrders",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_SlSalesOrders_Customers_CustomerId",
table: "SlSalesOrders",
column: "CustomerId",
principalTable: "Customers",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
}
}
}
| 35.295918 | 71 | 0.560856 | [
"MIT"
] | productive-dev/solar-coffee | SolarCoffee.Data/Migrations/20200209030602_Orders.cs | 3,461 | C# |
using System.Xml.Serialization;
namespace Instagraph.DataProcessor.DtoModels.Export
{
[XmlType("user")]
public class ExportCommentsDto
{
public string Username { get; set; }
public int MostComments { get; set; }
}
} | 20.833333 | 51 | 0.664 | [
"MIT"
] | georgidelchev/CSharp-Databases | 02 - [Entity Framework Core]/[Entity Framework Core - Exams]/08 - [C# DB Advanced Exam - 04 December 2017]/Instagraph.DataProcessor/DtoModels/Export/ExportCommentsDto.cs | 252 | C# |
using Q42.HueApi.Models.Groups;
using Q42.HueApi.Streaming.Models;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace Q42.HueApi.Streaming.Effects.BasEffects
{
public abstract class AngleEffect : BaseEffect
{
/// <summary>
/// Between -1 and 1
/// </summary>
public double X { get; set; }
/// <summary>
/// Between -1 and 1
/// </summary>
public double Y { get; set; }
public double CurrentAngle { get; set; }
/// <summary>
/// Between 0 and 1
/// </summary>
public double Width { get; set; }
/// <summary>
/// Get the multiplier for an effect on a light
/// </summary>
/// <param name="effect"></param>
/// <param name="light"></param>
/// <returns></returns>
public override double? GetEffectStrengthMultiplier(EntertainmentLight light)
{
var angle = Angle(light.LightLocation);
var dif1 = Math.Abs(CurrentAngle - angle);
var dif2 = Math.Abs(CurrentAngle - angle - 360);
var diff = Math.Min(dif1, dif2) / 60;
double? multiplier = this.Width - diff;
multiplier = multiplier > 1 ? 1 : multiplier;
multiplier = multiplier < 0 ? 0 : multiplier;
return multiplier;
}
/// <summary>
/// Calculate the distance between the effect and a light location
/// </summary>
/// <param name="effect"></param>
/// <param name="lightLocation"></param>
/// <returns></returns>
public double Angle(LightLocation lightLocation)
{
return lightLocation.Angle(this.X, this.Y);
}
public Task Rotate(CancellationToken cancellationToken, Func<int> stepSize = null, Func<TimeSpan> waitTime = null)
{
if (stepSize == null)
stepSize = () => 20;
if (waitTime == null)
waitTime = () => TimeSpan.FromMilliseconds(50);
return Task.Run(async () =>
{
while (!cancellationToken.IsCancellationRequested)
{
CurrentAngle += stepSize();
await Task.Delay(waitTime(), cancellationToken).ConfigureAwait(false);
if (CurrentAngle >= 360)
CurrentAngle = 0;
if (CurrentAngle < 0)
CurrentAngle = 360;
}
}, cancellationToken);
}
}
}
| 26.528736 | 118 | 0.605286 | [
"MIT"
] | AngusMcIntyre/Q42.HueApi | src/Q42.HueApi.Streaming/Effects/BasEffects/AngleEffect.cs | 2,308 | C# |
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace Vue2SpaSignalR.Models
{
[Table("Employees")]
public class Employee
{
public int Id { get; set; }
[StringLength(60, MinimumLength = 2)]
public string Name { get; set; }
[DataType(DataType.EmailAddress)]
public string Email { get; set; }
[Display(Name = "Work Items")]
public List<WorkItem> WorkItems { get; set; }
}
}
| 24.272727 | 53 | 0.651685 | [
"MIT"
] | greenec/aspnetcore-Vue-signalR | Models/Employee.cs | 534 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
// Generation date: 10/4/2020 2:55:10 PM
namespace Microsoft.Dynamics.DataEntities
{
/// <summary>
/// There are no comments for InventCountingGroup_BR in the schema.
/// </summary>
public enum InventCountingGroup_BR
{
OwnStockInOtherPower = 2,
OwnStock = 1,
OtherStock = 3
}
}
| 30.166667 | 81 | 0.501381 | [
"MIT"
] | NathanClouseAX/AAXDataEntityPerfTest | Projects/AAXDataEntityPerfTest/ConsoleApp1/Connected Services/D365/InventCountingGroup_BR.cs | 726 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace LogExpert
{
public interface IColumnizedLogLine
{
#region Properties
ILogLine LogLine { get; }
IColumn[] ColumnValues { get; }
#endregion
}
} | 16.052632 | 40 | 0.609836 | [
"MIT"
] | BestFriend83/LogExpert | src/ColumnizerLib/IColumnizedLogLine.cs | 307 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;
using System.Web.Http.Dispatcher;
using WebApiV2.Custom;
namespace WebApiV2
{
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultRoute",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
config.Services.Replace(typeof(IHttpControllerSelector), new CustomControllerSelector(config));
//config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new System.Net.Http.Headers.MediaTypeHeaderValue("Accept: application/mpv.pragimtech.students.v1+json"));
//config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new System.Net.Http.Headers.MediaTypeHeaderValue("Accept: application/mpv.pragimtech.students.v2+json"));
//config.Formatters.XmlFormatter.SupportedMediaTypes.Add(new System.Net.Http.Headers.MediaTypeHeaderValue("Accept: application/mpv.pragimtech.students.v1+xml"));
//config.Formatters.XmlFormatter.SupportedMediaTypes.Add(new System.Net.Http.Headers.MediaTypeHeaderValue("Accept: application/mpv.pragimtech.students.v2+xml"));
//config.Routes.MapHttpRoute(
// name: "StudentV2",
// routeTemplate: "api/v2/students/{id}",
// defaults: new { id = RouteParameter.Optional, controller = "StudentV2" }
//);
}
}
}
| 43.794872 | 175 | 0.665105 | [
"MIT"
] | manuepeva/Angular-asp.netWebApp | WebApiV2/App_Start/WebApiConfig.cs | 1,710 | C# |
namespace MassTransit.PipeConfigurators
{
using System;
using System.Threading;
using Automatonymous;
using Context;
using GreenPipes;
using GreenPipes.Configurators;
using Saga;
using SagaConfigurators;
/// <summary>
/// Configures a message retry for a saga, on the saga configurator, which is constrained to
/// the message types for that saga, and only applies to the saga prior to the saga repository.
/// </summary>
/// <typeparam name="TSaga">The saga type</typeparam>
public class MessageRetrySagaConfigurationObserver<TSaga> :
ISagaConfigurationObserver
where TSaga : class, ISaga
{
readonly CancellationToken _cancellationToken;
readonly ISagaConfigurator<TSaga> _configurator;
readonly Action<IRetryConfigurator> _configure;
public MessageRetrySagaConfigurationObserver(ISagaConfigurator<TSaga> configurator, CancellationToken cancellationToken,
Action<IRetryConfigurator> configure)
{
_configurator = configurator;
_cancellationToken = cancellationToken;
_configure = configure;
}
void ISagaConfigurationObserver.SagaConfigured<T>(ISagaConfigurator<T> configurator)
{
}
public void StateMachineSagaConfigured<TInstance>(ISagaConfigurator<TInstance> configurator, SagaStateMachine<TInstance> stateMachine)
where TInstance : class, ISaga, SagaStateMachineInstance
{
}
void ISagaConfigurationObserver.SagaMessageConfigured<T, TMessage>(ISagaMessageConfigurator<T, TMessage> configurator)
{
var specification = new ConsumeContextRetryPipeSpecification<ConsumeContext<TMessage>, RetryConsumeContext<TMessage>>(Factory, _cancellationToken);
_configure?.Invoke(specification);
_configurator.Message<TMessage>(x => x.AddPipeSpecification(specification));
}
static RetryConsumeContext<TMessage> Factory<TMessage>(ConsumeContext<TMessage> context, IRetryPolicy retryPolicy, RetryContext retryContext)
where TMessage : class
{
return new RetryConsumeContext<TMessage>(context, retryPolicy, retryContext);
}
}
}
| 38.389831 | 159 | 0.705077 | [
"ECL-2.0",
"Apache-2.0"
] | Aerodynamite/MassTrans | src/MassTransit/Configuration/PipeConfigurators/MessageRetrySagaConfigurationObserver.cs | 2,265 | C# |
// Copyright (c) Microsoft. All rights reserved.
namespace Microsoft.Azure.Devices.Edge.Hub.E2E.Test
{
using System;
using System.Collections.Generic;
using System.Diagnostics.Tracing;
using System.IO;
using System.Security.Authentication;
using System.Security.Cryptography.X509Certificates;
using Autofac;
using DotNetty.Common.Internal.Logging;
using Microsoft.Azure.Devices.Client;
using Microsoft.Azure.Devices.Edge.Hub.CloudProxy;
using Microsoft.Azure.Devices.Edge.Hub.Core.Config;
using Microsoft.Azure.Devices.Edge.Hub.Mqtt;
using Microsoft.Azure.Devices.Edge.Hub.Service;
using Microsoft.Azure.Devices.Edge.Hub.Service.Modules;
using Microsoft.Azure.Devices.Edge.Util;
using Microsoft.Azure.Devices.Edge.Util.Logging;
using Microsoft.Azure.Devices.Edge.Util.Metrics;
using Microsoft.Azure.Devices.ProtocolGateway.Instrumentation;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using Moq;
using Newtonsoft.Json;
using EdgeHubConstants = Microsoft.Azure.Devices.Edge.Hub.Service.Constants;
using StorageLogLevel = Microsoft.Azure.Devices.Edge.Storage.StorageLogLevel;
class DependencyManager : IDependencyManager
{
readonly IConfigurationRoot configuration;
readonly X509Certificate2 serverCertificate;
readonly IList<X509Certificate2> trustBundle;
readonly SslProtocols sslProtocols;
readonly IList<string> inboundTemplates = new List<string>()
{
"devices/{deviceId}/messages/events/{params}/",
"devices/{deviceId}/messages/events/",
"devices/{deviceId}/modules/{moduleId}/messages/events/{params}/",
"devices/{deviceId}/modules/{moduleId}/messages/events/",
"$iothub/methods/res/{statusCode}/?$rid={correlationId}",
"$iothub/methods/res/{statusCode}/?$rid={correlationId}&foo={bar}"
};
readonly IDictionary<string, string> outboundTemplates = new Dictionary<string, string>()
{
{ "C2D", "devices/{deviceId}/messages/devicebound" },
{ "TwinEndpoint", "$iothub/twin/res/{statusCode}/?$rid={correlationId}" },
{ "TwinDesiredPropertyUpdate", "$iothub/twin/PATCH/properties/desired/?$version={version}" },
{ "ModuleEndpoint", "devices/{deviceId}/modules/{moduleId}/inputs/{inputName}" }
};
readonly IDictionary<string, string> routes = new Dictionary<string, string>()
{
["r1"] = "FROM /messages/events INTO $upstream",
["r2"] = "FROM /messages/modules/senderA INTO BrokeredEndpoint(\"/modules/receiverA/inputs/input1\")",
["r3"] = "FROM /messages/modules/senderB INTO BrokeredEndpoint(\"/modules/receiverA/inputs/input1\")",
["r4"] = "FROM /messages/modules/sender1 INTO BrokeredEndpoint(\"/modules/receiver1/inputs/input1\")",
["r5"] = "FROM /messages/modules/sender2 INTO BrokeredEndpoint(\"/modules/receiver2/inputs/input1\")",
["r6"] = "FROM /messages/modules/sender3 INTO BrokeredEndpoint(\"/modules/receiver3/inputs/input1\")",
["r7"] = "FROM /messages/modules/sender4 INTO BrokeredEndpoint(\"/modules/receiver4/inputs/input1\")",
["r8"] = "FROM /messages/modules/sender5 INTO BrokeredEndpoint(\"/modules/receiver5/inputs/input1\")",
["r9"] = "FROM /messages/modules/sender6 INTO BrokeredEndpoint(\"/modules/receiver6/inputs/input1\")",
["r10"] = "FROM /messages/modules/sender7 INTO BrokeredEndpoint(\"/modules/receiver7/inputs/input1\")",
["r11"] = "FROM /messages/modules/sender8 INTO BrokeredEndpoint(\"/modules/receiver8/inputs/input1\")",
["r12"] = "FROM /messages/modules/sender9 INTO BrokeredEndpoint(\"/modules/receiver9/inputs/input1\")",
["r13"] = "FROM /messages/modules/sender10 INTO BrokeredEndpoint(\"/modules/receiver10/inputs/input1\")",
["r14"] = "FROM /messages/modules/sender11/outputs/output1 INTO BrokeredEndpoint(\"/modules/receiver11/inputs/input1\")",
["r15"] = "FROM /messages/modules/sender11/outputs/output2 INTO BrokeredEndpoint(\"/modules/receiver11/inputs/input2\")",
};
public DependencyManager(IConfigurationRoot configuration, X509Certificate2 serverCertificate, IList<X509Certificate2> trustBundle, SslProtocols sslProtocols)
{
this.configuration = configuration;
this.serverCertificate = serverCertificate;
this.trustBundle = trustBundle;
this.sslProtocols = sslProtocols;
}
public void Register(ContainerBuilder builder)
{
const int ConnectionPoolSize = 10;
string edgeHubConnectionString = $"{this.configuration[EdgeHubConstants.ConfigKey.IotHubConnectionString]}";
IotHubConnectionStringBuilder iotHubConnectionStringBuilder = IotHubConnectionStringBuilder.Create(edgeHubConnectionString);
var topics = new MessageAddressConversionConfiguration(this.inboundTemplates, this.outboundTemplates);
builder.RegisterModule(new LoggingModule());
var mqttSettingsConfiguration = new Mock<IConfiguration>();
mqttSettingsConfiguration.Setup(c => c.GetSection(It.IsAny<string>())).Returns(Mock.Of<IConfigurationSection>(s => s.Value == null));
var experimentalFeatures = new ExperimentalFeatures(true, false, false, false);
builder.RegisterBuildCallback(
c =>
{
// set up loggers for dotnetty
var loggerFactory = c.Resolve<ILoggerFactory>();
InternalLoggerFactory.DefaultFactory = loggerFactory;
var eventListener = new LoggerEventListener(loggerFactory.CreateLogger("ProtocolGateway"));
eventListener.EnableEvents(CommonEventSource.Log, EventLevel.Informational);
});
var versionInfo = new VersionInfo("v1", "b1", "c1");
var metricsConfig = new MetricsConfig(mqttSettingsConfiguration.Object);
var backupFolder = Option.None<string>();
string storageFolder = string.Empty;
StoreLimits storeLimits = null;
if (!int.TryParse(this.configuration["TimeToLiveSecs"], out int timeToLiveSecs))
{
timeToLiveSecs = -1;
}
if (long.TryParse(this.configuration["MaxStorageBytes"], out long maxStorageBytes))
{
storeLimits = new StoreLimits(maxStorageBytes);
}
var storeAndForwardConfiguration = new StoreAndForwardConfiguration(timeToLiveSecs, storeLimits);
if (bool.TryParse(this.configuration["UsePersistentStorage"], out bool usePersistentStorage) && usePersistentStorage)
{
storageFolder = GetOrCreateDirectoryPath(this.configuration["StorageFolder"], EdgeHubConstants.EdgeHubStorageFolder);
}
if (bool.TryParse(this.configuration["EnableNonPersistentStorageBackup"], out bool enableNonPersistentStorageBackup))
{
backupFolder = Option.Some(this.configuration["BackupFolder"]);
}
var testRoutes = this.routes;
string customRoutes = this.configuration["Routes"];
if (!string.IsNullOrWhiteSpace(customRoutes))
{
testRoutes = JsonConvert.DeserializeObject<IDictionary<string, string>>(customRoutes);
}
if (!bool.TryParse(this.configuration["CheckEntireQueueOnCleanup"], out bool checkEntireQueueOnCleanup))
{
checkEntireQueueOnCleanup = false;
}
if (!int.TryParse(this.configuration["messageCleanupIntervalSecs"], out int messageCleanupIntervalSecs))
{
messageCleanupIntervalSecs = 1800;
}
builder.RegisterModule(
new CommonModule(
string.Empty,
iotHubConnectionStringBuilder.HostName,
Option.None<string>(),
iotHubConnectionStringBuilder.DeviceId,
iotHubConnectionStringBuilder.ModuleId,
string.Empty,
Option.None<string>(),
AuthenticationMode.Scope,
Option.Some(edgeHubConnectionString),
false,
usePersistentStorage,
storageFolder,
Option.None<string>(),
Option.None<string>(),
TimeSpan.FromHours(1),
TimeSpan.FromSeconds(0),
false,
this.trustBundle,
string.Empty,
metricsConfig,
enableNonPersistentStorageBackup,
backupFolder,
Option.None<ulong>(),
Option.None<int>(),
Option.None<StorageLogLevel>(),
false));
builder.RegisterModule(
new RoutingModule(
iotHubConnectionStringBuilder.HostName,
Option.None<string>(),
iotHubConnectionStringBuilder.DeviceId,
iotHubConnectionStringBuilder.ModuleId,
Option.Some(edgeHubConnectionString),
testRoutes,
true,
storeAndForwardConfiguration,
ConnectionPoolSize,
false,
versionInfo,
Option.Some(UpstreamProtocol.Amqp),
TimeSpan.FromSeconds(5),
101,
TimeSpan.FromSeconds(30),
TimeSpan.FromSeconds(3600),
true,
TimeSpan.FromSeconds(20),
false,
Option.None<TimeSpan>(),
Option.None<TimeSpan>(),
false,
10,
10,
true,
TimeSpan.FromHours(1),
checkEntireQueueOnCleanup,
messageCleanupIntervalSecs,
experimentalFeatures,
true,
false,
true,
scopeAuthenticationOnly: true,
trackDeviceState: true));
builder.RegisterModule(new HttpModule("Edge1", iotHubConnectionStringBuilder.DeviceId, "iotedgeApiProxy"));
builder.RegisterModule(new MqttModule(mqttSettingsConfiguration.Object, topics, this.serverCertificate, false, false, false, this.sslProtocols));
builder.RegisterModule(new AmqpModule("amqps", 5671, this.serverCertificate, iotHubConnectionStringBuilder.HostName, true, this.sslProtocols));
}
static string GetOrCreateDirectoryPath(string baseDirectoryPath, string directoryName)
{
if (string.IsNullOrWhiteSpace(baseDirectoryPath) || !Directory.Exists(baseDirectoryPath))
{
baseDirectoryPath = Path.GetTempPath();
}
string directoryPath = Path.Combine(baseDirectoryPath, directoryName);
if (!Directory.Exists(directoryPath))
{
Directory.CreateDirectory(directoryPath);
}
return directoryPath;
}
}
}
| 48.099585 | 166 | 0.610076 | [
"MIT"
] | kiranpradeep/iotedge | edge-hub/core/test/Microsoft.Azure.Devices.Edge.Hub.E2E.Test/DependencyManager.cs | 11,592 | C# |
using UnityEngine;
using System.Collections.Generic;
/// <summary>
/// AudioSource pool.
/// </summary>
/// <remarks>
/// Any AudioSource released will be added to an internal watchlist; the list
/// is periodically checked, and any finished sound will be returned to the
/// pool.
///
/// If activateOnGet is true, the pool will call Play() on any AudioSource it
/// releases; otherwise, you'll need to do that yourself.
/// </remarks>
[AddComponentMenu("ChicoPlugins/Pools/Audio Source")]
public class AudioPool : ComponentPool<AudioSource> {
[SerializeField] float _reclaimRate = 0.5f;
public float reclaimRate {
get { return _reclaimRate; }
}
float timeToReclaim;
List<AudioSource> watchlist = new List<AudioSource>();
public void Reclaim() {
for (int i=watchlist.Count-1; i >= 0; i--) {
AudioSource item = watchlist[i];
if (!item.isPlaying) {
watchlist.RemoveAt(i);
Add(item);
}
}
}
protected override void OnGetNext(AudioSource item) {
watchlist.Add(item);
if (activateOnGet) {
item.Play();
}
enabled = true;
}
protected override void OnAwake() {
timeToReclaim = reclaimRate;
}
protected override void OnUpdate() {
timeToReclaim -= Time.time;
if (timeToReclaim < 0f) {
timeToReclaim = _reclaimRate;
Reclaim();
}
}
}
| 23.160714 | 77 | 0.686199 | [
"MIT"
] | areyoutoo/ChicoPlugins | Project/Assets/Plugins/ChicoPlugins/Pools/AudioPool.cs | 1,299 | C# |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
//------------------------------------------------------------------------------
// <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 AgentService {
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", "4.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class Resource {
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Resource() {
}
/// <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("AgentService.Resource", typeof(Resource).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 string similar to Agent listener exit with retryable error, re-launch agent in 5 seconds..
/// </summary>
internal static string AgentExitWithError {
get {
return ResourceManager.GetString("AgentExitWithError", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Agent listener exit with 0 return code, stop the service, no retry needed..
/// </summary>
internal static string AgentExitWithoutError {
get {
return ResourceManager.GetString("AgentExitWithoutError", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Agent listener exit with terminated error, stop the service, no retry needed..
/// </summary>
internal static string AgentExitWithTerminatedError {
get {
return ResourceManager.GetString("AgentExitWithTerminatedError", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Agent listener exit with undefined return code, re-launch agent in 5 seconds..
/// </summary>
internal static string AgentExitWithUndefinedReturnCode {
get {
return ResourceManager.GetString("AgentExitWithUndefinedReturnCode", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Agent listener update failed, stop the service..
/// </summary>
internal static string AgentUpdateFailed {
get {
return ResourceManager.GetString("AgentUpdateFailed", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Agent listener exit because of updating, re-launch agent in 5 seconds..
/// </summary>
internal static string AgentUpdateInProcess {
get {
return ResourceManager.GetString("AgentUpdateInProcess", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Agent listener has been updated to latest, restart the service to update the servicehost itself..
/// </summary>
internal static string AgentUpdateRestartNeeded {
get {
return ResourceManager.GetString("AgentUpdateRestartNeeded", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Agent listener has been updated to latest, re-launch agent in 5 seconds..
/// </summary>
internal static string AgentUpdateSucceed {
get {
return ResourceManager.GetString("AgentUpdateSucceed", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Crash servicehost to trigger SCM restart the serivce..
/// </summary>
internal static string CrashServiceHost {
get {
return ResourceManager.GetString("CrashServiceHost", resourceCulture);
}
}
}
}
| 41.655405 | 165 | 0.596594 | [
"MIT"
] | 50Wliu/azure-pipelines-agent | src/Agent.Service/Windows/Resource.Designer.cs | 6,165 | C# |
using System;
namespace MCSong
{
public class CmdWhisper : Command
{
public override string name { get { return "whisper"; } }
public override string[] aliases { get { return new string[] { "" }; } }
public override CommandType type { get { return CommandType.Other; } }
public override bool consoleUsable { get { return false; } }
public override bool museumUsable { get { return true; } }
public override LevelPermission defaultRank { get { return LevelPermission.Guest; } }
public CmdWhisper() { }
public override void Use(Player p, string message)
{
if (message == "")
{
p.whisper = !p.whisper; p.whisperTo = "";
if (p.whisper) Player.SendMessage(p, "All messages sent will now auto-whisper");
else Player.SendMessage(p, "Whisper chat turned off");
}
else
{
Player who = Player.Find(message);
if (who == null) { p.whisperTo = ""; p.whisper = false; Player.SendMessage(p, "Could not find player."); return; }
p.whisper = true;
p.whisperTo = who.name;
Player.SendMessage(p, "Auto-whisper enabled. All messages will now be sent to " + who.name + ".");
}
}
public override void Help(Player p)
{
Player.SendMessage(p, "/whisper <name> - Makes all messages act like whispers");
}
}
} | 37.875 | 130 | 0.551815 | [
"ECL-2.0"
] | 727021/MCSong | MCSong/Commands/CmdWhisper.cs | 1,515 | C# |
using System;
using System.Linq;
using System.Data.Entity;
using AMPAExt.Comun;
using System.Collections.Generic;
using AMPA.Modelo;
namespace AMPAExt.Modelo
{
/// <summary>
/// Realiza las llamadas relacionadas con las actividades extraescolares
/// </summary>
public class clsActividad
{
#region Consultas
/// <summary>
/// Obtiene la lista de actividades
/// </summary>
/// <param name="filtro">Campos de búsqueda</param>
/// <returns><see cref="USUARIO_AMPA"/> con los datos de la AMPA</returns>
public List<ACTIVIDAD> GetActividades(FiltroActividad filtro)
{
List<ACTIVIDAD> resultado = new List<ACTIVIDAD>();
try
{
using (AMPAEXTBD db = new AMPAEXTBD())
{
var query = db.ACTIVIDAD
.Include(c => c.ACTIVIDAD_HORARIO)
.Include(c => c.ACTIVIDAD_DESCUENTO)
.Include(c => c.AMPA)
.Include(c => c.EMPRESA);
if (!filtro.Vacio)
{
if (!string.IsNullOrEmpty(filtro.Nombre))
query = query.Where(c => c.NOMBRE.ToUpper().Contains(filtro.Nombre.ToUpper()));
if ((filtro.IdEmpresa) > 0)
query = query.Where(c => c.ID_EMPRESA == filtro.IdEmpresa);
if ((filtro.IdAMPA) > 0)
query = query.Where(c => c.ID_AMPA == filtro.IdAMPA);
if (!string.IsNullOrEmpty(filtro.Activo))
query = query.Where(c => c.ACTIVO == filtro.Activo);
}
query = query.OrderBy(c => c.NOMBRE);
resultado = query.ToList();
}
}
catch (Exception ex)
{
Log.TrazaLog.Error("Error en " + this.GetType().FullName + ".GetActividades()", ex);
}
return resultado;
}
/// <summary>
/// Obtiene una determinada actividad
/// </summary>
/// <param name="idActividad">Identificador de la actividad</param>
/// <returns><see cref="ACTIVIDAD"/> con los datos de la actividad</returns>
public ACTIVIDAD GetActividadById(int idActividad)
{
ACTIVIDAD resultado = new ACTIVIDAD();
try
{
using (AMPAEXTBD db = new AMPAEXTBD())
{
resultado = db.ACTIVIDAD
.Where(c => c.ID_ACTIVIDAD == idActividad)
.Include(c => c.EMPRESA)
.Include(c => c.AMPA)
.Include(c => c.ACTIVIDAD_DESCUENTO)
.Include(c => c.ACTIVIDAD_HORARIO).FirstOrDefault();
List<ACTIVIDAD_DESCUENTO> descuento = db.ACTIVIDAD_DESCUENTO
.Where(c => c.ID_ACTIVIDAD == idActividad)
.Include(c => c.DESCUENTO).ToList();
resultado.ACTIVIDAD_DESCUENTO = descuento;
List<ACTIVIDAD_HORARIO> horario = db.ACTIVIDAD_HORARIO
.Where(c => c.ID_ACTIVIDAD == idActividad)
.Include(c => c.MONITOR).ToList();
resultado.ACTIVIDAD_HORARIO = horario;
}
}
catch (Exception ex)
{
Log.TrazaLog.Error("Error en " + this.GetType().FullName + ".GetActividades()", ex);
}
return resultado;
}
/// <summary>
/// Obtiene la AMPA de un alumno
/// </summary>
/// <param name="idAlumno">Identificador del alumno</param>
/// <returns>Datos de las AMPA <see cref="ALUMNO"/></returns>
public ALUMNO GetAMPAByAlumno(int idAlumno)
{
ALUMNO resultado = new ALUMNO();
try
{
using (AMPAEXTBD db = new AMPAEXTBD())
{
resultado = db.ALUMNO
.Where(c => c.ID_ALUMNO == idAlumno)
.Include (c=>c.TUTOR)
.Include(c=>c.TUTOR.AMPA).FirstOrDefault();
}
}
catch (Exception ex)
{
Log.TrazaLog.Error("Error en " + this.GetType().FullName + ".GetAMPAByAlumno()", ex);
}
return resultado;
}
/// <summary>
/// Obtiene el listado de horarios para una actividad
/// </summary>
/// <param name="idActividad">Identificador de la actividad</param>
/// <returns><see cref="ACTIVIDAD"/> con los datos de la actividad</returns>
public List<ACTIVIDAD_HORARIO> GetHorarioByActividad(int idActividad)
{
List<ACTIVIDAD_HORARIO> resultado = new List<ACTIVIDAD_HORARIO>();
try
{
using (AMPAEXTBD db = new AMPAEXTBD())
{
resultado = db.ACTIVIDAD_HORARIO
.Where(c => c.ID_ACTIVIDAD == idActividad)
.ToList();
}
}
catch (Exception ex)
{
Log.TrazaLog.Error("Error en " + this.GetType().FullName + ".GetHorarioByActividad(). idActividad: " + idActividad.ToString(), ex);
}
return resultado;
}
/// <summary>
/// Obtiene la lista de alumnos para una actividad
/// </summary>
/// <param name="idActividad">Identificador de la actividad/param>
/// <returns>Listado de <see cref="ALUMNO_ACTIVIDAD"/> con los datos de la AMPA</returns>
public List<ALUMNO_ACTIVIDAD> GetAlumnnosByActividad(int idActividad)
{
List<ALUMNO_ACTIVIDAD> resultado = new List<ALUMNO_ACTIVIDAD>();
try
{
using (AMPAEXTBD db = new AMPAEXTBD())
{
resultado = GetAlumnnosByActividad(idActividad, db);
}
}
catch (Exception ex)
{
Log.TrazaLog.Error("Error en " + this.GetType().FullName + ".GetAlumnnosByActividad(). idActividad: " + idActividad.ToString(), ex);
}
return resultado;
}
/// <summary>
/// Obtiene la lista de alumnos para una actividad
/// </summary>
/// <param name="idActividad">Identificador de la actividad/param>
/// <param name="conn">Conexión abierta para realizar la acción</param>
/// <returns>Listado de <see cref="ALUMNO_ACTIVIDAD"/> con los datos de la AMPA</returns>
public List<ALUMNO_ACTIVIDAD> GetAlumnnosByActividad(int idActividad, AMPAEXTBD conn)
{
List<ALUMNO_ACTIVIDAD> resultado = new List<ALUMNO_ACTIVIDAD>();
try
{
resultado = conn.ALUMNO_ACTIVIDAD
.Where(c => c.ACTIVIDAD_HORARIO.ID_ACTIVIDAD == idActividad)
.Include(c => c.ALUMNO)
.Include(c => c.ACTIVIDAD_HORARIO.ACTIVIDAD)
.Include(c => c.ACTIVIDAD_HORARIO).ToList();
}
catch (Exception ex)
{
Log.TrazaLog.Error("Error en " + this.GetType().FullName + ".GetAlumnnosByActividad(). idActividad: " + idActividad.ToString(), ex);
}
return resultado;
}
/// <summary>
/// Obtiene la lista de de alumnos para una actividad y horario
/// </summary>
/// <param name="idActividadHorario">Identificador de la actividad y horario/param>
/// <param name="conn">Conexión abierta para realizar la acción</param>
/// <returns>Listado de <see cref="ALUMNO_ACTIVIDAD"/> apuntados a una actividad y horario</returns>
public List<ALUMNO_ACTIVIDAD> GetAlumnosByActividadHorario(int idActividadHorario, AMPAEXTBD conn)
{
List<ALUMNO_ACTIVIDAD> resultado = new List<ALUMNO_ACTIVIDAD>();
try
{
resultado = conn.ALUMNO_ACTIVIDAD
.Where(c => c.ID_ACT_HORARIO == idActividadHorario)
.ToList();
}
catch (Exception ex)
{
Log.TrazaLog.Error("Error en " + this.GetType().FullName + ".GetAlumnosByActividadHorario(). idActividad: " + idActividadHorario.ToString(), ex);
}
return resultado;
}
/// <summary>
/// Obtiene la lista de alumnos para una actividad
/// </summary>
/// <param name="idActividad">Identificador de la actividad/param>
/// <returns>Listado de <see cref="ALUMNO_ACTIVIDAD"/> con los datos de la AMPA</returns>
public List<ALUMNO_ACTIVIDAD> GetAlumnnosByIdActividad(int idActividad)
{
List<ALUMNO_ACTIVIDAD> resultado = new List<ALUMNO_ACTIVIDAD>();
try
{
using (AMPAEXTBD db = new AMPAEXTBD())
{
resultado = db.ALUMNO_ACTIVIDAD
.Where(c => c.ID_ALUM_ACT == idActividad)
.Include(c => c.ALUMNO)
.Include(c => c.ACTIVIDAD_HORARIO).ToList();
}
}
catch (Exception ex)
{
Log.TrazaLog.Error("Error en " + this.GetType().FullName + ".GetAlumnnosByIdActividad(). idActividad: " + idActividad.ToString(), ex);
}
return resultado;
}
/// <summary>
/// Obtiene los datos del alumno
/// </summary>
/// <param name="idAlumno">Identificador del alumno/param>
/// <returns>Datos del alumno en <see cref="ALUMNO"/></returns>
public ALUMNO GetAlumnnoById(int idAlumno)
{
ALUMNO resultado = new ALUMNO();
try
{
using (AMPAEXTBD db = new AMPAEXTBD())
{
resultado = db.ALUMNO
.Where(c => c.ID_ALUMNO == idAlumno)
.Include(c=> c.TUTOR)
.Include(c => c.CURSO_CLASE.CURSO)
.Include(c => c.CURSO_CLASE.CLASE)
.FirstOrDefault();
}
}
catch (Exception ex)
{
Log.TrazaLog.Error("Error en " + this.GetType().FullName + ".GetAlumnnoById(). idAlumno: " + idAlumno.ToString(), ex);
}
return resultado;
}
/// <summary>
/// Obtiene las actividades de un alumno
/// </summary>
/// <param name="idAlumno">Identificador del alumno/param>
/// <returns>Listado de actividades en <see cref="ALUMNO_ACTIVIDAD"/></returns>
public List<ALUMNO_ACTIVIDAD> GetActividadesByAlumnno(int idAlumno)
{
List<ALUMNO_ACTIVIDAD> resultado = new List<ALUMNO_ACTIVIDAD>();
try
{
using (AMPAEXTBD db = new AMPAEXTBD())
{
resultado = db.ALUMNO_ACTIVIDAD
.Where(c => c.ID_ALUMNO == idAlumno)
.Include(c => c.ACTIVIDAD_HORARIO)
.Include(c => c.ACTIVIDAD_HORARIO.ACTIVIDAD)
.Include(c => c.ACTIVIDAD_HORARIO.ACTIVIDAD.EMPRESA)
.ToList();
}
}
catch (Exception ex)
{
Log.TrazaLog.Error("Error en " + this.GetType().FullName + ".GetActividadesByAlumnno(). idAlumno: " + idAlumno.ToString(), ex);
throw;
}
return resultado;
}
#endregion
#region Altas
/// <summary>
/// Da de alta una actividad extraescolar
/// </summary>
/// <param name="actividad">Datos de la actividad</param>
/// <param name="conn">Conexión abierta para realizar la acción</param>
/// <returns>Identificador de la actividad dada de alta en el sistema.</returns>
public int AltaActividad(ACTIVIDAD actividad, AMPAEXTBD conn)
{
int idActividad;
try
{
conn.ACTIVIDAD.Add(actividad);
conn.SaveChanges();
idActividad = actividad.ID_ACTIVIDAD;
}
catch (Exception ex)
{
Log.TrazaLog.Error("Error al dar de alta la actividad extraescolar. Id_empresa: " + actividad.ID_EMPRESA.ToString(), ex);
throw;
}
return idActividad;
}
/// <summary>
/// Da de alta horarios para la empresa extraescolar
/// </summary>
/// <param name="horario">Datos del horario</param>
/// <param name="conn">Conexión abierta para realizar la acción</param>
/// <returns>Identificador de la actividad dada de alta en el sistema.</returns>
public int AltaHorario(ACTIVIDAD_HORARIO horario, AMPAEXTBD conn)
{
int idHorario;
try
{
conn.ACTIVIDAD_HORARIO.Add(horario);
conn.SaveChanges();
idHorario = horario.ID_ACT_HORARIO;
}
catch (Exception ex)
{
Log.TrazaLog.Error("Error al dar de alta el horario de la actividad extraescolar. Id_actividad: " + horario.ID_ACTIVIDAD.ToString(), ex);
throw;
}
return idHorario;
}
/// <summary>
/// Vincula un horario a un alumno
/// </summary>
/// <param name="horario">Datos del horario</param>
/// <returns>Identificador de la actividad dada de alta en el sistema.</returns>
public int AltaAlumnoHorario(ALUMNO_ACTIVIDAD horario)
{
using (AMPAEXTBD conn = new AMPAEXTBD())
{
return AltaAlumnoHorario(horario, conn);
}
}
/// <summary>
/// Vincula un horario a un alumno
/// </summary>
/// <param name="horario">Datos del horario</param>
/// <param name="conn">Conexión abierta para realizar la acción</param>
/// <returns>Identificador de la actividad dada de alta en el sistema.</returns>
public int AltaAlumnoHorario(ALUMNO_ACTIVIDAD horario, AMPAEXTBD conn)
{
int idHorario;
try
{
conn.ALUMNO_ACTIVIDAD.Add(horario);
conn.SaveChanges();
idHorario = horario.ID_ALUM_ACT;
}
catch (Exception ex)
{
Log.TrazaLog.Error("Error al vincular un horario a un alumno", ex);
throw;
}
return idHorario;
}
/// <summary>
/// Da de alta descuentos para la empresa extraescolar
/// </summary>
/// <param name="horario">Datos del descuento</param>
/// <param name="conn">Conexión abierta para realizar la acción</param>
/// <returns>Identificador de la actividad dada de alta en el sistema.</returns>
public int AltaDescuento(ACTIVIDAD_DESCUENTO descuento, AMPAEXTBD conn)
{
int idDescuento;
try
{
conn.ACTIVIDAD_DESCUENTO.Add(descuento);
conn.SaveChanges();
idDescuento = descuento.ID_ACT_DESCUENTO;
}
catch (Exception ex)
{
Log.TrazaLog.Error("Error al dar de alta el descuento de la actividad extraescolar. Id_actividad: " + descuento.ID_ACTIVIDAD.ToString(), ex);
throw;
}
return idDescuento;
}
#endregion
#region Modificaciones
/// <summary>
/// Modifica una actividad extraescolar
/// </summary>
/// <param name="actividad">Datos de la actividad</param>
/// <param name="conn">Conexión abierta para realizar la acción</param>
/// <returns>Booleano con el resultado: true si ha ido todo bien; false en caso contrario</returns>
public bool ModificarActividad(ACTIVIDAD actividad, AMPAEXTBD conn)
{
bool resultado;
try
{
conn.Entry(actividad).State = EntityState.Modified;
conn.SaveChanges();
resultado = true;
}
catch (Exception ex)
{
Log.TrazaLog.Error("Error al modificar la actividad extraescolar. Id_actividad: " + actividad.ID_EMPRESA.ToString(), ex);
throw;
}
return resultado;
}
/// <summary>
/// Modifica la empresa para una actividad
/// </summary>
/// <param name="actividad">Datos de la actividad</param>
/// <returns>Booleano con el resultado: true si ha ido todo bien; false en caso contrario</returns>
public bool CambiarActividadEmpresa(ACTIVIDAD actividad)
{
bool resultado;
try
{
using (AMPAEXTBD conn = new AMPAEXTBD())
{
conn.Entry(actividad).State = EntityState.Modified;
conn.SaveChanges();
resultado = true;
}
}
catch (Exception ex)
{
Log.TrazaLog.Error("Error al modificar la actividad extraescolar. idActividad: " + actividad.ID_ACTIVIDAD.ToString(), ex);
throw;
}
return resultado;
}
#endregion
#region Bajas
/// <summary>
/// Realiza la eliminación de un horario de actividad
/// </summary>
/// <param name="idHorarioAct">Identificador del horario_actividad</param>
/// <param name="idActividad">Identificador de la actividad</param>
/// <param name="conn">Conexión abierta para realizar la acción</param>
/// <returns>Booleano con el resultado: true si ha ido todo bien; false en caso contrario</returns>
public bool BajaHorario(int idHorarioAct, AMPAEXTBD conn)
{
bool resultado = false;
try
{
ACTIVIDAD_HORARIO horario = conn.ACTIVIDAD_HORARIO
.Where(c => c.ID_ACT_HORARIO == idHorarioAct)
.FirstOrDefault();
if (horario == null)
throw new Exception("El horario " + idHorarioAct.ToString() + " no se encuentra");
conn.ACTIVIDAD_HORARIO.Remove(horario);
conn.SaveChanges();
resultado = true;
}
catch (Exception ex)
{
Log.TrazaLog.Error("Error en " + this.GetType().FullName + ".BajaHorario(). idMonitor: " + idHorarioAct.ToString(), ex);
}
return resultado;
}
/// <summary>
/// Realiza la eliminación de descuentos de una actividad
/// </summary>
/// <param name="idActividad">Identificador de la actividad</param>
/// <param name="conn">Conexión abierta para realizar la acción</param>
/// <returns>Booleano con el resultado: true si ha ido todo bien; false en caso contrario</returns>
public bool BajaDescuentos(int idActividad, AMPAEXTBD conn)
{
bool resultado = false;
try
{
List<ACTIVIDAD_DESCUENTO> descuento = conn.ACTIVIDAD_DESCUENTO
.Where(c => c.ID_ACTIVIDAD == idActividad)
.ToList();
foreach (ACTIVIDAD_DESCUENTO desc in descuento)
{
conn.ACTIVIDAD_DESCUENTO.Remove(desc);
conn.SaveChanges();
}
resultado = true;
}
catch (Exception ex)
{
Log.TrazaLog.Error("Error en " + this.GetType().FullName + ".BajaDescuentos(). idActividad: " + idActividad.ToString(), ex);
}
return resultado;
}
/// <summary>
/// Realiza la eliminación de un alumno de un horario de actividad
/// </summary>
/// <param name="idAlumnoHorario">Identificador del horario de actividad para el alumno</param>
/// <param name="conn">Conexión abierta para realizar la acción</param>
/// <returns>Booleano con el resultado: true si ha ido todo bien; false en caso contrario</returns>
public bool BajaAlumnoHorario(int idAlumnoHorario, AMPAEXTBD conn)
{
bool resultado = false;
try
{
ALUMNO_ACTIVIDAD resultadoAct = conn.ALUMNO_ACTIVIDAD
.Where(c => c.ID_ALUM_ACT == idAlumnoHorario)
.FirstOrDefault();
if (resultadoAct == null)
throw new Exception("El horario para el alumno " + idAlumnoHorario.ToString() + " no se encuentra");
conn.ALUMNO_ACTIVIDAD.Remove(resultadoAct);
conn.SaveChanges();
resultado = true;
}
catch (Exception ex)
{
Log.TrazaLog.Error("Error en " + this.GetType().FullName + ".BajaAlumnoHorario(). idAlumnoHorario: " + idAlumnoHorario.ToString(), ex);
}
return resultado;
}
/// <summary>
/// Da de baja un alumno de una actividad extraescolar
/// </summary>
/// <param name="idAlumno">Identificador del alumno</param>
/// <param name="idActividadHorario">Identificador de la actividad</param>
/// <returns>Booleano con el resultado: true si ha ido todo bien; false en caso contrario</returns>
public bool BajaAlumnoActividad(int idAlumno, int idActividadHorario)
{
bool resultado = false;
try
{
using (AMPAEXTBD conn = new AMPAEXTBD())
{
ALUMNO_ACTIVIDAD alumno = conn.ALUMNO_ACTIVIDAD
.Where(c => c.ID_ALUMNO == idAlumno && c.ID_ACT_HORARIO == idActividadHorario)
.FirstOrDefault();
conn.ALUMNO_ACTIVIDAD.Remove(alumno);
conn.SaveChanges();
resultado = true;
}
}
catch (Exception ex)
{
Log.TrazaLog.Error("Error en " + this.GetType().FullName + ".BajaAlumnoActividad(). idAlumno: " + idAlumno.ToString() + ", idActividadHorario:" + idActividadHorario.ToString(), ex);
throw;
}
return resultado;
}
#endregion
}
}
| 40.132867 | 197 | 0.519603 | [
"MIT"
] | susandiro/UNIR_AMPAExt | AMPA.Modelo/Clases/clsActividad.cs | 22,982 | C# |
using System.Collections.Generic;
using System.Diagnostics;
namespace MvcPerfmon
{
/// <summary>
/// This should be registered as a singleton by your container
/// </summary>
public interface IPerfCounterUtility
{
/// <summary>
/// The named collection of performance counters
/// </summary>
Dictionary<string, PerformanceCounter> PerformanceCounters { get; }
/// <summary>
/// The real implementation will return true
/// The mock implementation will return false
/// </summary>
bool IsMonitoringEnabled { get; }
/// <summary>
/// Initialization method. Usually you want to call this in your global application startup
/// This will ensure all performance counters are properly installed and initialized
/// </summary>
/// <param name="perfCounterSetup">the setup config</param>
void Bootstrap(PerfCounterSetup perfCounterSetup);
/// <summary>
/// Disposal method. Usually you want to call this in your global application end
/// </summary>
void Cleanup();
}
} | 33.588235 | 99 | 0.6331 | [
"MIT"
] | PeteW/MvcPerfmon | MvcPerfmon/IPerfCounterUtility.cs | 1,144 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using Ultraviolet.Core;
namespace Ultraviolet.Graphics.Graphics3D
{
/// <summary>
/// Represents a node in a model hierarchy.
/// </summary>
public class ModelNode : IModelNodeProvider<ModelNode>
{
/// <summary>
/// Initializes a new instance of the <see cref="ModelNode"/> class.
/// </summary>
/// <param name="logicalIndex">The logical index of the node within its parent model.</param>
/// <param name="name">The node's name.</param>
/// <param name="mesh">The node's associated mesh.</param>
/// <param name="children">The node's list of child nodes.</param>
/// <param name="transform">The node's transform matrix.</param>
public ModelNode(Int32 logicalIndex, String name, ModelMesh mesh, IList<ModelNode> children, Matrix transform)
{
this.LogicalIndex = logicalIndex;
this.Name = name;
this.Mesh = mesh;
this.Mesh?.SetParentModelNode(this);
this.Children = new ModelNodeCollection(children);
this.TotalNodeCount = this.Children.Count + (children?.Sum(x => x.TotalNodeCount) ?? 0);
this.Transform.UpdateFromMatrix(transform);
foreach (var child in Children)
child.SetParentModelNode(this);
this.HasGeometry = (Mesh?.Geometries.Count > 0) || this.Children.Any(x => x.HasGeometry);
}
/// <inheritdoc/>
ModelNode IModelNodeProvider<ModelNode>.GetChildNode(Int32 index) => Children[index];
/// <summary>
/// Performs an action on all nodes within this node (including this node).
/// </summary>
/// <param name="action">The action to perform on each node.</param>
/// <param name="state">An arbitrary state object to pass to <paramref name="action"/>.</param>
public void TraverseNodes(Action<ModelNode, Object> action, Object state)
{
Contract.Require(action, nameof(action));
action(this, state);
foreach (var child in Children)
child.TraverseNodes(action, state);
}
/// <summary>
/// Gets the logical index of the node within its parent model.
/// </summary>
public Int32 LogicalIndex { get; }
/// <summary>
/// Gets the node's name.
/// </summary>
public String Name { get; }
/// <inheritdoc/>
ModelNode IModelNodeProvider<ModelNode>.ModelNode => this;
/// <summary>
/// Gets the <see cref="Model"/> that contains this node.
/// </summary>
public Model ParentModel { get; private set; }
/// <summary>
/// Gets the <see cref="ModelScene"/> that contains this node.
/// </summary>
public ModelScene ParentModelScene { get; private set; }
/// <summary>
/// Gets the <see cref="ModelNode"/> that contains this node.
/// </summary>
public ModelNode ParentModelNode { get; private set; }
/// <summary>
/// Gets the node's associated mesh.
/// </summary>
public ModelMesh Mesh { get; }
/// <summary>
/// Gets the node's collection of child nodes.
/// </summary>
public ModelNodeCollection Children { get; }
/// <summary>
/// Gets the node's transform.
/// </summary>
public AffineTransform Transform { get; } = new AffineTransform();
/// <summary>
/// Gets a value indicating whether this node, or any of its descendants, has visible geometry.
/// </summary>
public Boolean HasGeometry { get; }
/// <inheritdoc/>
public Int32 ChildNodeCount => Children.Count;
/// <inheritdoc/>
public Int32 TotalNodeCount { get; }
/// <summary>
/// Sets the node's parent model.
/// </summary>
/// <param name="parent">The scene's parent model.</param>
internal void SetParentModel(Model parent)
{
Contract.Require(parent, nameof(parent));
if (this.ParentModel != null)
throw new InvalidOperationException(UltravioletStrings.ModelParentLinkAlreadyExists);
this.ParentModel = parent;
Mesh?.SetParentModel(parent);
foreach (var child in Children)
child.SetParentModel(parent);
}
/// <summary>
/// Sets the node's parent scene.
/// </summary>
/// <param name="parent">The node's parent scene.</param>
internal void SetParentModelScene(ModelScene parent)
{
Contract.Require(parent, nameof(parent));
if (this.ParentModelScene != null)
throw new InvalidOperationException(UltravioletStrings.ModelParentLinkAlreadyExists);
this.ParentModelScene = parent;
Mesh?.SetParentModelScene(parent);
foreach (var child in Children)
child.SetParentModelScene(parent);
}
/// <summary>
/// Sets the node's parent node.
/// </summary>
/// <param name="parent">The node's parent node.</param>
internal void SetParentModelNode(ModelNode parent)
{
Contract.Require(parent, nameof(parent));
if (this.ParentModelNode != null)
throw new InvalidOperationException(UltravioletStrings.ModelParentLinkAlreadyExists);
this.ParentModelNode = parent;
}
}
} | 34.869565 | 118 | 0.583719 | [
"Apache-2.0",
"MIT"
] | MicroWorldwide/ultraviolet | Source/Ultraviolet/Shared/Graphics/Graphics3D/ModelNode.cs | 5,616 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.AspNetCore.Mvc.Rendering;
using Tutorials_RazorPagesMovie.Models;
using Tutorials_RazorPagesMovie.Services;
namespace Tutorials_RazorPagesMovie.Pages.Movies
{
public class CreateModel : PageModel
{
private readonly Tutorials_RazorPagesMovie.Services.MovieContext _context;
public CreateModel(Tutorials_RazorPagesMovie.Services.MovieContext context)
{
_context = context;
}
public IActionResult OnGet()
{
return Page();
}
[BindProperty]
public Movie Movie { get; set; }
public async Task<IActionResult> OnPostAsync()
{
if (!ModelState.IsValid)
{
return Page();
}
_context.Movie.Add(Movie);
await _context.SaveChangesAsync();
return RedirectToPage("./Index");
}
}
} | 25.069767 | 83 | 0.642857 | [
"Apache-2.0"
] | vincoss/NetCoreSamples | AspNetCore-2.0/src/Tutorials_RazorPagesMovie/Pages/Movies/Create.cshtml.cs | 1,078 | C# |
using System;
using System.Diagnostics.CodeAnalysis;
using Windows.UI.Core;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Template10.Common;
using Template10.Services.NavigationService;
namespace Wicip.Sample.Views
{
public sealed partial class Shell : Page
{
public static Shell Instance { get; set; }
public Shell( NavigationService navigationService )
{
Shell.Instance = this;
this.InitializeComponent();
this.menu.NavigationService = navigationService;
VisualStateManager.GoToState( this, this.NormalVisualState.Name, useTransitions: true );
}
[SuppressMessage( "Microsoft.Design", "CA1026:DefaultParametersShouldNotBeUsed", Justification = "We love default values." )]
public static void SetBusyVisibility( Visibility visible, string text = null )
{
WindowWrapper.Current().Dispatcher.Dispatch( () =>
{
switch( visible )
{
case Visibility.Visible:
Shell.Instance.FindName( nameof( busyScreen ) );
Shell.Instance.tblBusy.Text = text ?? String.Empty;
if( VisualStateManager.GoToState( Shell.Instance, Shell.Instance.BusyVisualState.Name, useTransitions: true ) )
{
SystemNavigationManager.GetForCurrentView().AppViewBackButtonVisibility = AppViewBackButtonVisibility.Collapsed;
}
break;
case Visibility.Collapsed:
if( VisualStateManager.GoToState( Shell.Instance, Shell.Instance.NormalVisualState.Name, useTransitions: true ) )
{
BootStrapper.Current.UpdateShellBackButton();
}
break;
}
} );
}
}
}
| 29.433962 | 127 | 0.725641 | [
"MIT"
] | balassy/wiip | Wicip.Sample/Views/Shell.xaml.cs | 1,562 | C# |
using System.Collections.Generic;
namespace RpgNotes.Desktop.Data.Templates {
public class FactionArticle : IArticleTemplate {
public string TemplateName() => "Faction";
public string TemplateHint() => "groups and factions";
public Image TemplateIcon() => new Image { WebPath="static/images/icons/faction.logo.svg" };
public Article Create(RpgSystem system) {
var article = new Article();
article.Tags = new List<string> {
"faction"
};
return article;
}
}
} | 26.35 | 96 | 0.656546 | [
"MIT"
] | qkmaxware/RpgNotes.Desktop | Data/Templates/FactionArticle.cs | 527 | C# |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
using System.Collections.Generic;
using Aliyun.Acs.Core;
namespace Aliyun.Acs.Config.Model.V20190108
{
public class PutConfigRuleResponse : AcsResponse
{
private string configRuleId;
private string requestId;
public string ConfigRuleId
{
get
{
return configRuleId;
}
set
{
configRuleId = value;
}
}
public string RequestId
{
get
{
return requestId;
}
set
{
requestId = value;
}
}
}
}
| 22.859649 | 63 | 0.693016 | [
"Apache-2.0"
] | AxiosCros/aliyun-openapi-net-sdk | aliyun-net-sdk-config/Config/Model/V20190108/PutConfigRuleResponse.cs | 1,303 | 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 serverlessrepo-2017-09-08.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using System.Net;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.ServerlessApplicationRepository.Model
{
/// <summary>
/// This is the response object from the CreateCloudFormationChangeSet operation.
/// </summary>
public partial class CreateCloudFormationChangeSetResponse : AmazonWebServiceResponse
{
private string _applicationId;
private string _changeSetId;
private string _semanticVersion;
private string _stackId;
/// <summary>
/// Gets and sets the property ApplicationId.
/// <para>
/// The application Amazon Resource Name (ARN).
/// </para>
/// </summary>
public string ApplicationId
{
get { return this._applicationId; }
set { this._applicationId = value; }
}
// Check to see if ApplicationId property is set
internal bool IsSetApplicationId()
{
return this._applicationId != null;
}
/// <summary>
/// Gets and sets the property ChangeSetId.
/// <para>
/// The Amazon Resource Name (ARN) of the change set.
/// </para>
///
/// <para>
/// Length constraints: Minimum length of 1.
/// </para>
///
/// <para>
/// Pattern: ARN:[-a-zA-Z0-9:/]*
/// </para>
/// </summary>
public string ChangeSetId
{
get { return this._changeSetId; }
set { this._changeSetId = value; }
}
// Check to see if ChangeSetId property is set
internal bool IsSetChangeSetId()
{
return this._changeSetId != null;
}
/// <summary>
/// Gets and sets the property SemanticVersion.
/// <para>
/// The semantic version of the application:
/// </para>
///
/// <para>
/// <a href="https://semver.org/">https://semver.org/</a>
/// </para>
/// </summary>
public string SemanticVersion
{
get { return this._semanticVersion; }
set { this._semanticVersion = value; }
}
// Check to see if SemanticVersion property is set
internal bool IsSetSemanticVersion()
{
return this._semanticVersion != null;
}
/// <summary>
/// Gets and sets the property StackId.
/// <para>
/// The unique ID of the stack.
/// </para>
/// </summary>
public string StackId
{
get { return this._stackId; }
set { this._stackId = value; }
}
// Check to see if StackId property is set
internal bool IsSetStackId()
{
return this._stackId != null;
}
}
} | 30.015873 | 113 | 0.553675 | [
"Apache-2.0"
] | philasmar/aws-sdk-net | sdk/src/Services/ServerlessApplicationRepository/Generated/Model/CreateCloudFormationChangeSetResponse.cs | 3,782 | C# |
namespace WindowsFormsApp1
{
partial class Form2
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
this.dataGridView1 = new System.Windows.Forms.DataGridView();
this.deleteCommandDataGridViewTextBoxColumn = new System.Windows.Forms.DataGridViewButtonColumn();
this.EditCollum = new System.Windows.Forms.DataGridViewButtonColumn();
this.idDataGridViewTextBoxColumn = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.nomeDataGridViewTextBoxColumn = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.ativoDataGridViewCheckBoxColumn = new System.Windows.Forms.DataGridViewCheckBoxColumn();
this.usuIncDataGridViewTextBoxColumn = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.usuAltDataGridViewTextBoxColumn = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.datIncDataGridViewTextBoxColumn = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.datAltDataGridViewTextBoxColumn = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.marcasBindingSource = new System.Windows.Forms.BindingSource(this.components);
this.querysInnerJoinDataSet = new WindowsFormsApp1.QuerysInnerJoinDataSet();
this.marcasTableAdapter = new WindowsFormsApp1.QuerysInnerJoinDataSetTableAdapters.MarcasTableAdapter();
this.button1 = new System.Windows.Forms.Button();
((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.marcasBindingSource)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.querysInnerJoinDataSet)).BeginInit();
this.SuspendLayout();
//
// dataGridView1
//
this.dataGridView1.AutoGenerateColumns = false;
this.dataGridView1.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
this.dataGridView1.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] {
this.deleteCommandDataGridViewTextBoxColumn,
this.EditCollum,
this.idDataGridViewTextBoxColumn,
this.nomeDataGridViewTextBoxColumn,
this.ativoDataGridViewCheckBoxColumn,
this.usuIncDataGridViewTextBoxColumn,
this.usuAltDataGridViewTextBoxColumn,
this.datIncDataGridViewTextBoxColumn,
this.datAltDataGridViewTextBoxColumn});
this.dataGridView1.DataSource = this.marcasBindingSource;
this.dataGridView1.Location = new System.Drawing.Point(9, 73);
this.dataGridView1.Name = "dataGridView1";
this.dataGridView1.RowHeadersWidth = 51;
this.dataGridView1.RowTemplate.Height = 24;
this.dataGridView1.Size = new System.Drawing.Size(787, 376);
this.dataGridView1.TabIndex = 0;
this.dataGridView1.CellContentClick += new System.Windows.Forms.DataGridViewCellEventHandler(this.DataGridView1_CellContentClick);
//
// deleteCommandDataGridViewTextBoxColumn
//
this.deleteCommandDataGridViewTextBoxColumn.DataPropertyName = "DeleteCommand";
this.deleteCommandDataGridViewTextBoxColumn.HeaderText = "DeleteCommand";
this.deleteCommandDataGridViewTextBoxColumn.MinimumWidth = 6;
this.deleteCommandDataGridViewTextBoxColumn.Name = "deleteCommandDataGridViewTextBoxColumn";
this.deleteCommandDataGridViewTextBoxColumn.Resizable = System.Windows.Forms.DataGridViewTriState.True;
this.deleteCommandDataGridViewTextBoxColumn.SortMode = System.Windows.Forms.DataGridViewColumnSortMode.Automatic;
this.deleteCommandDataGridViewTextBoxColumn.Width = 125;
//
// EditCollum
//
this.EditCollum.DataPropertyName = "Id";
this.EditCollum.HeaderText = "EditCollum";
this.EditCollum.MinimumWidth = 6;
this.EditCollum.Name = "EditCollum";
this.EditCollum.ReadOnly = true;
this.EditCollum.Text = "Editar";
this.EditCollum.UseColumnTextForButtonValue = true;
this.EditCollum.Width = 125;
//
// idDataGridViewTextBoxColumn
//
this.idDataGridViewTextBoxColumn.DataPropertyName = "Id";
this.idDataGridViewTextBoxColumn.HeaderText = "Id";
this.idDataGridViewTextBoxColumn.MinimumWidth = 6;
this.idDataGridViewTextBoxColumn.Name = "idDataGridViewTextBoxColumn";
this.idDataGridViewTextBoxColumn.ReadOnly = true;
this.idDataGridViewTextBoxColumn.Width = 125;
//
// nomeDataGridViewTextBoxColumn
//
this.nomeDataGridViewTextBoxColumn.DataPropertyName = "Nome";
this.nomeDataGridViewTextBoxColumn.HeaderText = "Nome";
this.nomeDataGridViewTextBoxColumn.MinimumWidth = 6;
this.nomeDataGridViewTextBoxColumn.Name = "nomeDataGridViewTextBoxColumn";
this.nomeDataGridViewTextBoxColumn.Width = 125;
//
// ativoDataGridViewCheckBoxColumn
//
this.ativoDataGridViewCheckBoxColumn.DataPropertyName = "Ativo";
this.ativoDataGridViewCheckBoxColumn.HeaderText = "Ativo";
this.ativoDataGridViewCheckBoxColumn.MinimumWidth = 6;
this.ativoDataGridViewCheckBoxColumn.Name = "ativoDataGridViewCheckBoxColumn";
this.ativoDataGridViewCheckBoxColumn.Width = 125;
//
// usuIncDataGridViewTextBoxColumn
//
this.usuIncDataGridViewTextBoxColumn.DataPropertyName = "UsuInc";
this.usuIncDataGridViewTextBoxColumn.HeaderText = "UsuInc";
this.usuIncDataGridViewTextBoxColumn.MinimumWidth = 6;
this.usuIncDataGridViewTextBoxColumn.Name = "usuIncDataGridViewTextBoxColumn";
this.usuIncDataGridViewTextBoxColumn.Width = 125;
//
// usuAltDataGridViewTextBoxColumn
//
this.usuAltDataGridViewTextBoxColumn.DataPropertyName = "UsuAlt";
this.usuAltDataGridViewTextBoxColumn.HeaderText = "UsuAlt";
this.usuAltDataGridViewTextBoxColumn.MinimumWidth = 6;
this.usuAltDataGridViewTextBoxColumn.Name = "usuAltDataGridViewTextBoxColumn";
this.usuAltDataGridViewTextBoxColumn.Width = 125;
//
// datIncDataGridViewTextBoxColumn
//
this.datIncDataGridViewTextBoxColumn.DataPropertyName = "DatInc";
this.datIncDataGridViewTextBoxColumn.HeaderText = "DatInc";
this.datIncDataGridViewTextBoxColumn.MinimumWidth = 6;
this.datIncDataGridViewTextBoxColumn.Name = "datIncDataGridViewTextBoxColumn";
this.datIncDataGridViewTextBoxColumn.Width = 125;
//
// datAltDataGridViewTextBoxColumn
//
this.datAltDataGridViewTextBoxColumn.DataPropertyName = "DatAlt";
this.datAltDataGridViewTextBoxColumn.HeaderText = "DatAlt";
this.datAltDataGridViewTextBoxColumn.MinimumWidth = 6;
this.datAltDataGridViewTextBoxColumn.Name = "datAltDataGridViewTextBoxColumn";
this.datAltDataGridViewTextBoxColumn.Width = 125;
//
// marcasBindingSource
//
this.marcasBindingSource.DataMember = "Marcas";
this.marcasBindingSource.DataSource = this.querysInnerJoinDataSet;
//
// querysInnerJoinDataSet
//
this.querysInnerJoinDataSet.DataSetName = "QuerysInnerJoinDataSet";
this.querysInnerJoinDataSet.SchemaSerializationMode = System.Data.SchemaSerializationMode.IncludeSchema;
//
// marcasTableAdapter
//
this.marcasTableAdapter.ClearBeforeFill = true;
//
// button1
//
this.button1.Location = new System.Drawing.Point(28, 21);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(148, 39);
this.button1.TabIndex = 1;
this.button1.Text = "Adicionar";
this.button1.UseVisualStyleBackColor = true;
this.button1.Click += new System.EventHandler(this.Button1_Click);
//
// Form2
//
this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 16F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(800, 450);
this.Controls.Add(this.button1);
this.Controls.Add(this.dataGridView1);
this.Name = "Form2";
this.Text = "Form2";
this.Load += new System.EventHandler(this.Form2_Load);
((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.marcasBindingSource)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.querysInnerJoinDataSet)).EndInit();
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.DataGridView dataGridView1;
private QuerysInnerJoinDataSet querysInnerJoinDataSet;
private System.Windows.Forms.BindingSource marcasBindingSource;
private QuerysInnerJoinDataSetTableAdapters.MarcasTableAdapter marcasTableAdapter;
private System.Windows.Forms.DataGridViewButtonColumn deleteCommandDataGridViewTextBoxColumn;
private System.Windows.Forms.DataGridViewButtonColumn EditCollum;
private System.Windows.Forms.DataGridViewTextBoxColumn idDataGridViewTextBoxColumn;
private System.Windows.Forms.DataGridViewTextBoxColumn nomeDataGridViewTextBoxColumn;
private System.Windows.Forms.DataGridViewCheckBoxColumn ativoDataGridViewCheckBoxColumn;
private System.Windows.Forms.DataGridViewTextBoxColumn usuIncDataGridViewTextBoxColumn;
private System.Windows.Forms.DataGridViewTextBoxColumn usuAltDataGridViewTextBoxColumn;
private System.Windows.Forms.DataGridViewTextBoxColumn datIncDataGridViewTextBoxColumn;
private System.Windows.Forms.DataGridViewTextBoxColumn datAltDataGridViewTextBoxColumn;
private System.Windows.Forms.Button button1;
}
} | 54.642857 | 142 | 0.672418 | [
"MIT"
] | hbsishenriquekang/GitC | 05-08-19_09-08-19/WindowsFormsApp1/Form2.Designer.cs | 11,477 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Runtime.InteropServices;
using HeapAllocFlags = Interop.Kernel32.HeapAllocFlags;
namespace Microsoft.Win32.SafeHandles
{
internal sealed class SafeHeapAllocHandle : SafeBuffer, IDisposable
{
public SafeHeapAllocHandle() : base(true) { }
internal static SafeHeapAllocHandle Alloc(int size)
{
SafeHeapAllocHandle result = Interop.Kernel32.HeapAlloc(s_hHeap, HeapAllocFlags.None, size);
if (result.IsInvalid)
{
result.SetHandleAsInvalid();
throw new OutOfMemoryException();
}
#if DEBUG
result._size = size;
unsafe
{
byte* p = (byte*)(result.DangerousGetHandle());
for (int i = 0; i < size; i++)
{
p[i] = 0xcc;
}
}
#endif
return result;
}
protected sealed override bool ReleaseHandle()
{
#if DEBUG
unsafe
{
byte* p = (byte*)handle;
for (int i = 0; i < _size; i++)
{
p[i] = 0xcc;
}
}
#endif
bool success = Interop.Kernel32.HeapFree(s_hHeap, HeapAllocFlags.None, handle);
return success;
}
#if DEBUG
private int _size;
#endif
private static readonly IntPtr s_hHeap = Interop.Kernel32.GetProcessHeap();
}
}
| 27.491525 | 104 | 0.539457 | [
"MIT"
] | 333fred/runtime | src/libraries/System.Security.Cryptography.Pkcs/src/Microsoft/Win32/SafeHandles/SafeHeapAllocHandle.cs | 1,622 | C# |
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Globalization;
using System.Linq;
using DataAccess.Base;
using DataAccess.Common;
using DataAccess.Entity;
using Interface.SCM;
using Application.Common;
using System.Collections;
namespace BusinessProcess.SCM
{
public class BBudgetConfigDetail : ProcessBase, IBudgetConfigDetail
{
public DataSet GetBudgetConfigDetails(int DonorID, int ProgramID, int ProgramStartYear, int CodeID)
{
lock (this)
{
ClsUtility.Init_Hashtable();
ClsObject Lablist = new ClsObject();
ClsUtility.AddParameters("@DonorID", SqlDbType.Int, DonorID.ToString());
ClsUtility.AddParameters("@ProgramID", SqlDbType.Int, ProgramID.ToString());
ClsUtility.AddParameters("@ProgramStartYear", SqlDbType.Int, ProgramStartYear.ToString());
ClsUtility.AddParameters("@CodeID", SqlDbType.Int, CodeID.ToString());
return (DataSet)Lablist.ReturnObject(ClsUtility.theParams, "pr_SCM_GetBudgetConfigDetail", ClsDBUtility.ObjectEnum.DataSet);
}
}
public DataSet GetBudgetConfigTotal(int CodeID)
{
lock (this)
{
ClsUtility.Init_Hashtable();
ClsObject Lablist = new ClsObject();
ClsUtility.AddParameters("@CodeID", SqlDbType.Int, CodeID.ToString());
return (DataSet)Lablist.ReturnObject(ClsUtility.theParams, "Pr_SCM_GETBudgetConfigTotal", ClsDBUtility.ObjectEnum.DataSet);
}
}
public int SaveBudgetConfigDetails(DataTable BudgetConfigDataSet, DataTable CostAllocationDataSet, int UserId, Hashtable SelectedValues)
{
ClsObject ItemList = new ClsObject();
int theRowAffected = 0;
DataRow drBudgetConfig;
string BudgetConfigId = SelectedValues["BudgetConfigureID"].ToString();
foreach (DataRow cadDR in CostAllocationDataSet.Rows)
{
foreach (DataRow theDR in BudgetConfigDataSet.Rows)
{
if (theDR[0].ToString() != "13")
{
for (int i = 2; i <= BudgetConfigDataSet.Columns.Count - 2; i++)
{
ClsUtility.Init_Hashtable();
ClsUtility.AddParameters("@BudgetConfigID", SqlDbType.Int, BudgetConfigId);
ClsUtility.AddParameters("@DonorID", SqlDbType.Int, SelectedValues["DonorID"].ToString());
ClsUtility.AddParameters("@ProgramID", SqlDbType.Int, SelectedValues["ProgramID"].ToString());
ClsUtility.AddParameters("@ProgramStartYear", SqlDbType.Int, SelectedValues["ProgramYear"].ToString());
ClsUtility.AddParameters("@CostAllocationID", SqlDbType.Int, cadDR[i].ToString());
ClsUtility.AddParameters("@BudgetMonthID", SqlDbType.Int, theDR[0].ToString());
ClsUtility.AddParameters("@BudgetAmt", SqlDbType.Float, theDR[i].ToString());
ClsUtility.AddParameters("@DeleteFlag", SqlDbType.Int, "0");
ClsUtility.AddParameters("@UserId", SqlDbType.Int, UserId.ToString());
ClsUtility.AddParameters("@CurrYear", SqlDbType.Int, theDR[1].ToString().Split(' ').Last());
drBudgetConfig = (DataRow)ItemList.ReturnObject(ClsUtility.theParams, "pr_SCM_SaveBudgetConfigDetail", ClsDBUtility.ObjectEnum.DataRow);
BudgetConfigId = drBudgetConfig[0].ToString();
}
}
}
}
return theRowAffected;
}
public int DeleteBudgetConfigDetails(int BudgetConfigID, int DeleteFlag, int UserId)
{
ClsObject ItemList = new ClsObject();
int theRowAffected = 0;
ClsUtility.Init_Hashtable();
ClsUtility.AddParameters("@BudgetConfigID", SqlDbType.Int, BudgetConfigID.ToString());
ClsUtility.AddParameters("@DeleteFlag", SqlDbType.Int, DeleteFlag.ToString());
ClsUtility.AddParameters("@UserId", SqlDbType.Int, UserId.ToString());
theRowAffected = (int)ItemList.ReturnObject(ClsUtility.theParams, "pr_SCM_DeleteBudgetConfigDetail", ClsDBUtility.ObjectEnum.ExecuteNonQuery);
return theRowAffected;
}
public DataSet GetDonorList()
{
lock (this)
{
ClsObject LabLocation = new ClsObject();
ClsUtility.Init_Hashtable();
return (DataSet)LabLocation.ReturnObject(ClsUtility.theParams, "pr_SCM_GetDonorList", ClsDBUtility.ObjectEnum.DataSet);
}
}
public DataSet GetProgramList()
{
lock (this)
{
ClsObject LabLocation = new ClsObject();
ClsUtility.Init_Hashtable();
return (DataSet)LabLocation.ReturnObject(ClsUtility.theParams, "pr_SCM_GetProgramList", ClsDBUtility.ObjectEnum.DataSet);
}
}
public DataSet GetProgramListByDonor(int DonorID)
{
lock (this)
{
ClsObject LabLocation = new ClsObject();
ClsUtility.Init_Hashtable();
ClsUtility.AddParameters("@DonorId", SqlDbType.Int, DonorID.ToString());
return (DataSet)LabLocation.ReturnObject(ClsUtility.theParams, "pr_SCM_GetProgramListByDonor", ClsDBUtility.ObjectEnum.DataSet);
}
}
public DataSet GetCostAllocation(int CodeID)
{
lock (this)
{
ClsObject LabLocation = new ClsObject();
ClsUtility.Init_Hashtable();
ClsUtility.AddParameters("@CodeID", SqlDbType.Int, CodeID.ToString());
return (DataSet)LabLocation.ReturnObject(ClsUtility.theParams, "pr_SCM_GetCostAllocation", ClsDBUtility.ObjectEnum.DataSet);
}
}
public DataSet GetHolisticBudgetView(int CodeID, int ProgramStartYear)
{
lock (this)
{
ClsUtility.Init_Hashtable();
ClsObject Lablist = new ClsObject();
ClsUtility.AddParameters("@CostAllocationID", SqlDbType.Int, CodeID.ToString());
ClsUtility.AddParameters("@ProgramStartYear", SqlDbType.Int, ProgramStartYear.ToString());
return (DataSet)Lablist.ReturnObject(ClsUtility.theParams, "pr_SCM_GetHolisticBudgetView", ClsDBUtility.ObjectEnum.DataSet);
}
}
public DataSet GetHolisticBudgetViewDefaultYear()
{
lock (this)
{
ClsObject LabLocation = new ClsObject();
ClsUtility.Init_Hashtable();
return (DataSet)LabLocation.ReturnObject(ClsUtility.theParams, "pr_SCM_GetHolisticBudgetViewDefaultYear", ClsDBUtility.ObjectEnum.DataSet);
}
}
#region ICosting Members
public DataTable CalcAdminAndConsultFees(int year, int month)
{
throw new NotImplementedException();
}
public DataTable GetPatientVisitConfigForYear(int year, int userId)
{
lock (this)
{
// got get the current visit data for the year/month
ClsUtility.Init_Hashtable();
ClsObject co = new ClsObject();
ClsUtility.AddParameters("@Year", SqlDbType.Int, year.ToString());
var dt = (DataTable)co.ReturnObject(ClsUtility.theParams, "Pr_SCM_GetPatientVisitsPerMonth_Futures", ClsDBUtility.ObjectEnum.DataTable);
// verify all the months exist and add those that don't
bool monthsMissing = false;
var dtNew = new DataTable();
dtNew.Columns.Add("Id", typeof(int));
dtNew.Columns.Add("Year", typeof(int));
dtNew.Columns.Add("Month", typeof(int));
dtNew.Columns.Add("Visits", typeof(int));
for (int i = 1; i <= 12; i++)
{
if (dt.Select("month=" + i).Count() == 0)
{
// row not found = add it
dtNew.Rows.Add(0, year, i, 0);
monthsMissing = true;
}
}
if (monthsMissing) // we'll need to save and re-query to get the data requested.
{
var oldParms = new Hashtable(ClsUtility.theParams); // need to save the parms because the save will reset them.
SavePatientVisitConfigForYear(dtNew, year, userId);
dt = (DataTable)co.ReturnObject(oldParms, "Pr_SCM_GetPatientVisitsPerMonth_Futures", ClsDBUtility.ObjectEnum.DataTable);
}
return dt;
}
}
public int SavePatientVisitConfigForYear(DataTable table, int year, int userId)
{
lock (this)
{
ClsObject co = new ClsObject();
int rows = 0;
foreach (DataRow row in table.Rows)
{
ClsUtility.Init_Hashtable();
ClsUtility.AddParameters("@Id", SqlDbType.Int, row.Field<int>("Id").ToString());
ClsUtility.AddParameters("@Year", SqlDbType.Int, year.ToString());
ClsUtility.AddParameters("@Month", SqlDbType.Int, row.Field<int>("Month").ToString());
ClsUtility.AddParameters("@Visits", SqlDbType.Int, row.Field<int>("Visits").ToString());
ClsUtility.AddParameters("@UserId", SqlDbType.Int, userId.ToString());
int result = (int)co.ReturnObject(ClsUtility.theParams, "Pr_SCM_SavePatientVisitsPerMonth_Futures", ClsDBUtility.ObjectEnum.ExecuteNonQuery);
rows = rows + result;
}
return rows;
}
}
#endregion
}
}
| 45.405286 | 164 | 0.578927 | [
"MIT"
] | uon-crissp/IQCare | SourceBase/DataAccess/BusinessProcess.SCM/BBudgetConfigDetail.cs | 10,309 | C# |
# CS_ARCH_ARM64, 0, None
0x20,0x48,0x28,0x4e = aese v0.16b, v1.16b
0x20,0x58,0x28,0x4e = aesd v0.16b, v1.16b
0x20,0x68,0x28,0x4e = aesmc v0.16b, v1.16b
0x20,0x78,0x28,0x4e = aesimc v0.16b, v1.16b
0x20,0x08,0x28,0x5e = sha1h s0, s1
0x20,0x18,0x28,0x5e = sha1su1 v0.4s, v1.4s
0x20,0x28,0x28,0x5e = sha256su0 v0.4s, v1.4s
0x20,0x00,0x02,0x5e = sha1c q0, s1, v2.4s
0x20,0x10,0x02,0x5e = sha1p q0, s1, v2.4s
0x20,0x20,0x02,0x5e = sha1m q0, s1, v2.4s
0x20,0x30,0x02,0x5e = sha1su0 v0.4s, v1.4s, v2.4s
0x20,0x40,0x02,0x5e = sha256h q0, q1, v2.4s
0x20,0x50,0x02,0x5e = sha256h2 q0, q1, v2.4s
0x20,0x60,0x02,0x5e = sha256su1 v0.4s, v1.4s, v2.4s
| 39.75 | 51 | 0.710692 | [
"BSD-3-Clause"
] | 02107/Lilu | capstone/suite/MC/AArch64/neon-crypto.s.cs | 636 | C# |
using System;
namespace NETStandard.ClassLibrary
{
public class Class1
{
}
}
| 10.111111 | 34 | 0.659341 | [
"MIT"
] | binki/RoslynCodeTaskFactory | Samples/NETStandard.ClassLibrary/Class1.cs | 93 | C# |
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Design;
using Microsoft.Extensions.Configuration;
using Pomelo.EntityFrameworkCore.MySql.Infrastructure;
using System;
using System.IO;
namespace PointOfSale.Persistence.Infrastructure
{
public abstract class DesignTimeDbContextFactoryBase<TContext> :
IDesignTimeDbContextFactory<TContext> where TContext : DbContext
{
private const string ConnectionStringName = "MySQLDatabaseConnection";
private const string AspNetCoreEnvironment = "ASPNETCORE_ENVIRONMENT";
private string DbProvider = "MSSQL";
public TContext CreateDbContext(string[] args)
{
var basePath = Directory.GetCurrentDirectory() + string.Format("{0}..{0}..{0}Presentation{0}PointOfSale.WinFormUI", Path.DirectorySeparatorChar);
return Create(basePath, Environment.GetEnvironmentVariable(AspNetCoreEnvironment));
//return Create(@"Server=.\SQLEXPRESS;Database=Database;Trusted_Connection=True;");
}
protected abstract TContext CreateNewInstance(DbContextOptions<TContext> options);
private TContext Create(string basePath, string environmentName)
{
var configuration = new ConfigurationBuilder()
.SetBasePath(basePath)
.AddJsonFile("appsettings.json")
.AddJsonFile($"appsettings.Local.json", optional: true)
.AddJsonFile($"appsettings.{environmentName}.json", optional: true)
.AddEnvironmentVariables()
.Build();
var connectionString = configuration.GetConnectionString(ConnectionStringName);
DbProvider = configuration.GetSection("AppSettings").GetSection("DbProvider").Value;
return Create(connectionString);
}
private TContext Create(string connectionString)
{
if (string.IsNullOrEmpty(connectionString))
{
throw new ArgumentException($"Connection string '{ConnectionStringName}' is null or empty.", nameof(connectionString));
}
Console.WriteLine($"DesignTimeDbContextFactoryBase.Create(string): Connection string: '{connectionString}'.");
var optionsBuilder = new DbContextOptionsBuilder<TContext>();
switch (DbProvider)
{
case "MSSQL":
optionsBuilder.UseSqlServer(connectionString);
break;
case "MYSQL":
optionsBuilder.UseMySql(connectionString, mySqlOptions => {
mySqlOptions.ServerVersion(new Version(10, 4, 8), ServerType.MariaDb);
});
break;
default:
optionsBuilder.UseInMemoryDatabase($"PointOfSale_{Guid.NewGuid()}");
break;
}
return CreateNewInstance(optionsBuilder.Options);
}
}
}
| 40.876712 | 157 | 0.639745 | [
"MIT"
] | rmnavz/PointOfSale | Src/Infrastructure/PointOfSale.Persistence/Infrastructure/DesignTimeDbContextFactoryBase.cs | 2,986 | C# |
namespace Loupedeck.VoiceMeeterPlugin.Library.Voicemeeter
{
using System;
using System.Collections.Generic;
public sealed class VoicemeeterClient : IDisposable, IObservable<Single>
{
public void Dispose()
{
try
{
RemoteWrapper.Logout();
}
catch (Exception)
{
// ignored
}
}
private readonly List<IObserver<Single>> _observers = new();
public IDisposable Subscribe(IObserver<Single> observer)
{
if (!this._observers.Contains(observer))
{
this._observers.Add(observer);
}
return new Unsubscriber(this._observers, observer);
}
private void Notify(Single value)
{
foreach (var observer in this._observers)
{
observer.OnNext(value);
}
}
private sealed class Unsubscriber : IDisposable
{
private readonly List<IObserver<Single>> _observers;
private readonly IObserver<Single> _observer;
public Unsubscriber(List<IObserver<Single>> observers, IObserver<Single> observer)
{
this._observers = observers;
this._observer = observer;
}
public void Dispose()
{
if (this._observer != null && this._observers.Contains(this._observer))
{
this._observers.Remove(this._observer);
}
}
}
}
} | 27.066667 | 94 | 0.512931 | [
"MIT"
] | XeroxDev/Loupedeck-plugin-VoiceMeeter | VoiceMeeterPlugin/Library/Voicemeeter/VoicemeeterClient.cs | 1,626 | C# |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Threading;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeGeneration;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.Shared.Utilities;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Shared.Extensions
{
internal static class IMethodSymbolExtensions
{
public static bool CompatibleSignatureToDelegate(this IMethodSymbol method, INamedTypeSymbol delegateType)
{
Contract.ThrowIfFalse(delegateType.TypeKind == TypeKind.Delegate);
var invoke = delegateType.DelegateInvokeMethod;
if (invoke == null)
{
// It's possible to get events with no invoke method from metadata. We will assume
// that no method can be an event handler for one.
return false;
}
if (method.Parameters.Length != invoke.Parameters.Length)
{
return false;
}
if (method.ReturnsVoid != invoke.ReturnsVoid)
{
return false;
}
if (!method.ReturnType.InheritsFromOrEquals(invoke.ReturnType))
{
return false;
}
for (int i = 0; i < method.Parameters.Length; i++)
{
if (!invoke.Parameters[i].Type.InheritsFromOrEquals(method.Parameters[i].Type))
{
return false;
}
}
return true;
}
public static IMethodSymbol RenameTypeParameters(this IMethodSymbol method, IList<string> newNames)
{
if (method.TypeParameters.Select(t => t.Name).SequenceEqual(newNames))
{
return method;
}
var typeGenerator = new TypeGenerator();
var updatedTypeParameters = RenameTypeParameters(
method.TypeParameters, newNames, typeGenerator);
var mapping = new Dictionary<ITypeSymbol, ITypeSymbol>();
for (int i = 0; i < method.TypeParameters.Length; i++)
{
mapping[method.TypeParameters[i]] = updatedTypeParameters[i];
}
return CodeGenerationSymbolFactory.CreateMethodSymbol(
method.ContainingType,
method.GetAttributes(),
method.DeclaredAccessibility,
method.GetSymbolModifiers(),
method.ReturnType.SubstituteTypes(mapping, typeGenerator),
method.ExplicitInterfaceImplementations.FirstOrDefault(),
method.Name,
updatedTypeParameters,
method.Parameters.Select(p =>
CodeGenerationSymbolFactory.CreateParameterSymbol(p.GetAttributes(), p.RefKind, p.IsParams, p.Type.SubstituteTypes(mapping, typeGenerator), p.Name, p.IsOptional,
p.HasExplicitDefaultValue, p.HasExplicitDefaultValue ? p.ExplicitDefaultValue : null)).ToList());
}
public static IMethodSymbol RenameParameters(this IMethodSymbol method, IList<string> parameterNames)
{
var parameterList = method.Parameters;
if (parameterList.Select(p => p.Name).SequenceEqual(parameterNames))
{
return method;
}
var parameters = parameterList.RenameParameters(parameterNames);
return CodeGenerationSymbolFactory.CreateMethodSymbol(
method.ContainingType,
method.GetAttributes(),
method.DeclaredAccessibility,
method.GetSymbolModifiers(),
method.ReturnType,
method.ExplicitInterfaceImplementations.FirstOrDefault(),
method.Name,
method.TypeParameters,
parameters);
}
private static IList<ITypeParameterSymbol> RenameTypeParameters(
IList<ITypeParameterSymbol> typeParameters,
IList<string> newNames,
ITypeGenerator typeGenerator)
{
// We generate the type parameter in two passes. The first creates the new type
// parameter. The second updates the constraints to point at this new type parameter.
var newTypeParameters = new List<CodeGenerationTypeParameterSymbol>();
var mapping = new Dictionary<ITypeSymbol, ITypeSymbol>();
for (int i = 0; i < typeParameters.Count; i++)
{
var typeParameter = typeParameters[i];
var newTypeParameter = new CodeGenerationTypeParameterSymbol(
typeParameter.ContainingType,
typeParameter.GetAttributes(),
typeParameter.Variance,
newNames[i],
typeParameter.ConstraintTypes,
typeParameter.HasConstructorConstraint,
typeParameter.HasReferenceTypeConstraint,
typeParameter.HasValueTypeConstraint,
typeParameter.Ordinal);
newTypeParameters.Add(newTypeParameter);
mapping[typeParameter] = newTypeParameter;
}
// Now we update the constraints.
foreach (var newTypeParameter in newTypeParameters)
{
newTypeParameter.ConstraintTypes = ImmutableArray.CreateRange(newTypeParameter.ConstraintTypes, t => t.SubstituteTypes(mapping, typeGenerator));
}
return newTypeParameters.Cast<ITypeParameterSymbol>().ToList();
}
public static IMethodSymbol EnsureNonConflictingNames(
this IMethodSymbol method, INamedTypeSymbol containingType, ISyntaxFactsService syntaxFacts, CancellationToken cancellationToken)
{
// The method's type parameters may conflict with the type parameters in the type
// we're generating into. In that case, rename them.
var parameterNames = NameGenerator.EnsureUniqueness(
method.Parameters.Select(p => p.Name).ToList(), isCaseSensitive: syntaxFacts.IsCaseSensitive);
var outerTypeParameterNames =
containingType.GetAllTypeParameters()
.Select(tp => tp.Name)
.Concat(method.Name)
.Concat(containingType.Name);
var unusableNames = parameterNames.Concat(outerTypeParameterNames).ToSet(
syntaxFacts.IsCaseSensitive ? StringComparer.Ordinal : StringComparer.OrdinalIgnoreCase);
var newTypeParameterNames = NameGenerator.EnsureUniqueness(
method.TypeParameters.Select(tp => tp.Name).ToList(),
n => !unusableNames.Contains(n));
var updatedMethod = method.RenameTypeParameters(newTypeParameterNames);
return updatedMethod.RenameParameters(parameterNames);
}
public static IMethodSymbol RemoveInaccessibleAttributesAndAttributesOfTypes(
this IMethodSymbol method, ISymbol accessibleWithin, params INamedTypeSymbol[] removeAttributeTypes)
{
Func<AttributeData, bool> shouldRemoveAttribute = a =>
removeAttributeTypes.Any(attr => attr != null && attr.Equals(a.AttributeClass)) || !a.AttributeClass.IsAccessibleWithin(accessibleWithin);
return method.RemoveAttributesCore(shouldRemoveAttribute, statements: null, handlesExpressions: null);
}
private static IMethodSymbol RemoveAttributesCore(
this IMethodSymbol method, Func<AttributeData, bool> shouldRemoveAttribute,
IList<SyntaxNode> statements, IList<SyntaxNode> handlesExpressions)
{
var methodHasAttribute = method.GetAttributes().Any(shouldRemoveAttribute);
var someParameterHasAttribute = method.Parameters
.Any(m => m.GetAttributes().Any(shouldRemoveAttribute));
var returnTypeHasAttribute = method.GetReturnTypeAttributes().Any(shouldRemoveAttribute);
if (!methodHasAttribute && !someParameterHasAttribute && !returnTypeHasAttribute)
{
return method;
}
return CodeGenerationSymbolFactory.CreateMethodSymbol(
method.ContainingType,
method.GetAttributes().Where(a => !shouldRemoveAttribute(a)).ToList(),
method.DeclaredAccessibility,
method.GetSymbolModifiers(),
method.ReturnType,
method.ExplicitInterfaceImplementations.FirstOrDefault(),
method.Name,
method.TypeParameters,
method.Parameters.Select(p =>
CodeGenerationSymbolFactory.CreateParameterSymbol(
p.GetAttributes().Where(a => !shouldRemoveAttribute(a)).ToList(),
p.RefKind, p.IsParams, p.Type, p.Name, p.IsOptional,
p.HasExplicitDefaultValue, p.HasExplicitDefaultValue ? p.ExplicitDefaultValue : null)).ToList(),
statements,
handlesExpressions,
method.GetReturnTypeAttributes().Where(a => !shouldRemoveAttribute(a)).ToList());
}
public static bool? IsMoreSpecificThan(this IMethodSymbol method1, IMethodSymbol method2)
{
var p1 = method1.Parameters;
var p2 = method2.Parameters;
// If the methods don't have the same parameter count, then method1 can't be more or
// less specific than method2.
if (p1.Length != p2.Length)
{
return null;
}
// If the methods' parameter types differ, or they have different names, then one can't
// be more specific than the other.
if (!SignatureComparer.Instance.HaveSameSignature(method1.Parameters, method2.Parameters) ||
!method1.Parameters.Select(p => p.Name).SequenceEqual(method2.Parameters.Select(p => p.Name)))
{
return null;
}
// Ok. We have two methods that look extremely similar to each other. However, one might
// be more specific if, for example, it was actually written with concrete types (like 'int')
// versus the other which may have been instantiated from a type parameter. i.e.
//
// class C<T> { void Foo(T t); void Foo(int t); }
//
// THe latter Foo is more specific when comparing "C<int>.Foo(int t)" (method1) vs
// "C<int>.Foo(int t)" (method2).
p1 = method1.OriginalDefinition.Parameters;
p2 = method2.OriginalDefinition.Parameters;
return p1.Select(p => p.Type).ToList().AreMoreSpecificThan(p2.Select(p => p.Type).ToList());
}
public static bool TryGetPredefinedComparisonOperator(this IMethodSymbol symbol, out PredefinedOperator op)
{
if (symbol.MethodKind == MethodKind.BuiltinOperator)
{
op = symbol.GetPredefinedOperator();
switch (op)
{
case PredefinedOperator.Equality:
case PredefinedOperator.Inequality:
case PredefinedOperator.GreaterThanOrEqual:
case PredefinedOperator.LessThanOrEqual:
case PredefinedOperator.GreaterThan:
case PredefinedOperator.LessThan:
return true;
}
}
else
{
op = PredefinedOperator.None;
}
return false;
}
public static PredefinedOperator GetPredefinedOperator(this IMethodSymbol symbol)
{
switch (symbol.Name)
{
case "op_Addition":
case "op_UnaryPlus":
return PredefinedOperator.Addition;
case "op_BitwiseAnd":
return PredefinedOperator.BitwiseAnd;
case "op_BitwiseOr":
return PredefinedOperator.BitwiseOr;
case "op_Concatenate":
return PredefinedOperator.Concatenate;
case "op_Decrement":
return PredefinedOperator.Decrement;
case "op_Division":
return PredefinedOperator.Division;
case "op_Equality":
return PredefinedOperator.Equality;
case "op_ExclusiveOr":
return PredefinedOperator.ExclusiveOr;
case "op_Exponent":
return PredefinedOperator.Exponent;
case "op_GreaterThan":
return PredefinedOperator.GreaterThan;
case "op_GreaterThanOrEqual":
return PredefinedOperator.GreaterThanOrEqual;
case "op_Increment":
return PredefinedOperator.Increment;
case "op_Inequality":
return PredefinedOperator.Inequality;
case "op_IntegerDivision":
return PredefinedOperator.IntegerDivision;
case "op_LeftShift":
return PredefinedOperator.LeftShift;
case "op_LessThan":
return PredefinedOperator.LessThan;
case "op_LessThanOrEqual":
return PredefinedOperator.LessThanOrEqual;
case "op_Like":
return PredefinedOperator.Like;
case "op_LogicalNot":
case "op_OnesComplement":
return PredefinedOperator.Complement;
case "op_Modulus":
return PredefinedOperator.Modulus;
case "op_Multiply":
return PredefinedOperator.Multiplication;
case "op_RightShift":
return PredefinedOperator.RightShift;
case "op_Subtraction":
case "op_UnaryNegation":
return PredefinedOperator.Subtraction;
default:
return PredefinedOperator.None;
}
}
}
}
| 44.123867 | 181 | 0.590003 | [
"Apache-2.0"
] | AArnott/roslyn | src/Workspaces/Core/Portable/Shared/Extensions/IMethodSymbolExtensions.cs | 14,607 | C# |
using System;
public class SquareRoot
{
public static void Main()
{
double number = 12345;
number = Math.Sqrt(number);
Console.WriteLine("{0}", number);
}
} | 18.090909 | 46 | 0.562814 | [
"MIT"
] | emilti/Telerik-Academy-My-Courses | C#-Part1/1.IntroProgrammingHomework/08. Square Root/Square Root.cs | 201 | C# |
using System;
using System.Threading;
using System.Net.Sockets;
using System.Net;
using System.IO;
namespace PubNubMessaging.Core
{
#region "Network Status -- code split required"
internal abstract class ClientNetworkStatus
{
private static bool _status = true;
private static bool _failClientNetworkForTesting = false;
private static bool _machineSuspendMode = false;
private static IJsonPluggableLibrary _jsonPluggableLibrary;
internal static IJsonPluggableLibrary JsonPluggableLibrary {
get {
return _jsonPluggableLibrary;
}
set {
_jsonPluggableLibrary = value;
}
}
#if (SILVERLIGHT || WINDOWS_PHONE)
private static ManualResetEvent mres = new ManualResetEvent(false);
private static ManualResetEvent mreSocketAsync = new ManualResetEvent(false);
#elif(!UNITY_IOS && !UNITY_ANDROID && !MONODROID && !__ANDROID__)
private static ManualResetEventSlim mres = new ManualResetEventSlim (false);
#endif
internal static bool SimulateNetworkFailForTesting {
get {
return _failClientNetworkForTesting;
}
set {
_failClientNetworkForTesting = value;
}
}
internal static bool MachineSuspendMode {
get {
return _machineSuspendMode;
}
set {
_machineSuspendMode = value;
}
}
/*#if(__MonoCS__ && !UNITY_IOS && !UNITY_ANDROID)
static UdpClient udp;
#endif*/
#if(UNITY_IOS || UNITY_ANDROID || __MonoCS__)
static HttpWebRequest request;
static WebResponse response;
internal static int HeartbeatInterval {
get;
set;
}
internal static bool CheckInternetStatusUnity<T> (bool systemActive, Action<PubnubClientError> errorCallback, string[] channels, int heartBeatInterval)
{
HeartbeatInterval = heartBeatInterval;
if (_failClientNetworkForTesting) {
//Only to simulate network fail
return false;
} else {
CheckClientNetworkAvailability<T> (CallbackClientNetworkStatus, errorCallback, channels);
return _status;
}
}
#endif
internal static bool CheckInternetStatus<T> (bool systemActive, Action<PubnubClientError> errorCallback, string[] channels)
{
if (_failClientNetworkForTesting || _machineSuspendMode) {
//Only to simulate network fail
return false;
} else {
CheckClientNetworkAvailability<T> (CallbackClientNetworkStatus, errorCallback, channels);
return _status;
}
}
//#endif
public static bool GetInternetStatus ()
{
return _status;
}
private static void CallbackClientNetworkStatus (bool status)
{
_status = status;
}
private static void CheckClientNetworkAvailability<T> (Action<bool> callback, Action<PubnubClientError> errorCallback, string[] channels)
{
InternetState<T> state = new InternetState<T> ();
state.Callback = callback;
state.ErrorCallback = errorCallback;
state.Channels = channels;
#if (UNITY_ANDROID || UNITY_IOS || MONODROID || __ANDROID__)
CheckSocketConnect<T>(state);
#elif(__MonoCS__)
CheckSocketConnect<T> (state);
#else
ThreadPool.QueueUserWorkItem(CheckSocketConnect<T>, state);
#endif
#if (SILVERLIGHT || WINDOWS_PHONE)
mres.WaitOne();
#elif(!UNITY_ANDROID && !UNITY_IOS && !MONODROID && !__ANDROID__)
mres.Wait ();
#endif
}
private static void CheckSocketConnect<T> (object internetState)
{
InternetState<T> state = internetState as InternetState<T>;
Action<bool> callback = state.Callback;
Action<PubnubClientError> errorCallback = state.ErrorCallback;
string[] channels = state.Channels;
try {
#if (SILVERLIGHT || WINDOWS_PHONE)
using (Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
SocketAsyncEventArgs sae = new SocketAsyncEventArgs();
sae.UserToken = state;
sae.RemoteEndPoint = new DnsEndPoint("pubsub.pubnub.com", 80);
sae.Completed += new EventHandler<SocketAsyncEventArgs>(socketAsync_Completed<T>);
bool test = socket.ConnectAsync(sae);
mreSocketAsync.WaitOne(1000);
sae.Completed -= new EventHandler<SocketAsyncEventArgs>(socketAsync_Completed<T>);
socket.Close();
}
#elif (UNITY_IOS || UNITY_ANDROID || MONODROID || __ANDROID__)
if(request!=null){
request.Abort();
request = null;
}
request = (HttpWebRequest)WebRequest.Create("http://pubsub.pubnub.com");
if(request!= null){
request.Timeout = HeartbeatInterval * 1000;
request.ContentType = "application/json";
if(response!=null){
response.Close();
response = null;
}
response = request.GetResponse ();
if(response != null){
if(((HttpWebResponse)response).ContentLength <= 0){
_status = false;
throw new Exception("Failed to connect");
} else {
using(Stream dataStream = response.GetResponseStream ()){
using(StreamReader reader = new StreamReader (dataStream)){
string responseFromServer = reader.ReadToEnd ();
LoggingMethod.WriteToLog(string.Format("DateTime {0}, Response:{1}", DateTime.Now.ToString(), responseFromServer), LoggingMethod.LevelInfo);
_status = true;
callback(true);
reader.Close();
}
dataStream.Close();
}
}
}
}
#elif(__MonoCS__)
using (UdpClient udp = new UdpClient ("pubsub.pubnub.com", 80)) {
IPAddress localAddress = ((IPEndPoint)udp.Client.LocalEndPoint).Address;
if (udp != null && udp.Client != null && udp.Client.RemoteEndPoint != null) {
udp.Client.SendTimeout = HeartbeatInterval * 1000;
EndPoint remotepoint = udp.Client.RemoteEndPoint;
string remoteAddress = (remotepoint != null) ? remotepoint.ToString () : "";
LoggingMethod.WriteToLog (string.Format ("DateTime {0} checkInternetStatus LocalIP: {1}, RemoteEndPoint:{2}", DateTime.Now.ToString (), localAddress.ToString (), remoteAddress), LoggingMethod.LevelVerbose);
_status = true;
callback (true);
}
}
#else
using (UdpClient udp = new UdpClient("pubsub.pubnub.com", 80))
{
IPAddress localAddress = ((IPEndPoint)udp.Client.LocalEndPoint).Address;
EndPoint remotepoint = udp.Client.RemoteEndPoint;
string remoteAddress = (remotepoint != null) ? remotepoint.ToString() : "";
udp.Close();
LoggingMethod.WriteToLog(string.Format("DateTime {0} checkInternetStatus LocalIP: {1}, RemoteEndPoint:{2}", DateTime.Now.ToString(), localAddress.ToString(), remoteAddress), LoggingMethod.LevelVerbose);
callback(true);
}
#endif
}
#if (UNITY_IOS || UNITY_ANDROID || MONODROID || __ANDROID__)
catch (WebException webEx){
if(webEx.Message.Contains("404")){
_status =true;
callback(true);
} else {
_status =false;
ParseCheckSocketConnectException<T>(webEx, channels, errorCallback, callback);
}
}
#endif
catch (Exception ex) {
#if(__MonoCS__)
_status = false;
#endif
ParseCheckSocketConnectException<T> (ex, channels, errorCallback, callback);
} finally {
#if (UNITY_IOS || UNITY_ANDROID)
if(response!=null){
response.Close();
response = null;
}
if(request!=null){
request = null;
}
#elif(__MonoCS__)
#endif
#if(UNITY_IOS)
GC.Collect();
#endif
}
#if (!UNITY_ANDROID && !UNITY_IOS && !MONODROID && !__ANDROID__)
mres.Set ();
#endif
}
static void ParseCheckSocketConnectException<T> (Exception ex, string[] channels, Action<PubnubClientError> errorCallback, Action<bool> callback)
{
PubnubErrorCode errorType = PubnubErrorCodeHelper.GetErrorType (ex);
int statusCode = (int)errorType;
string errorDescription = PubnubErrorCodeDescription.GetStatusCodeDescription (errorType);
PubnubClientError error = new PubnubClientError (statusCode, PubnubErrorSeverity.Warn, true, ex.ToString (), ex, PubnubMessageSource.Client, null, null, errorDescription, string.Join (",", channels));
GoToCallback (error, errorCallback);
LoggingMethod.WriteToLog (string.Format ("DateTime {0} checkInternetStatus Error. {1}", DateTime.Now.ToString (), ex.ToString ()), LoggingMethod.LevelWarning);
callback (false);
}
private static void GoToCallback<T> (object result, Action<T> Callback)
{
if (Callback != null) {
if (typeof(T) == typeof(string)) {
JsonResponseToCallback (result, Callback);
} else {
Callback ((T)(object)result);
}
}
}
private static void GoToCallback<T> (PubnubClientError result, Action<PubnubClientError> Callback)
{
if (Callback != null) {
//TODO:
//Include custom message related to error/status code for developer
//error.AdditionalMessage = MyCustomErrorMessageRetrieverBasedOnStatusCode(error.StatusCode);
Callback (result);
}
}
private static void JsonResponseToCallback<T> (object result, Action<T> callback)
{
string callbackJson = "";
if (typeof(T) == typeof(string)) {
callbackJson = _jsonPluggableLibrary.SerializeToJsonString (result);
Action<string> castCallback = callback as Action<string>;
castCallback (callbackJson);
}
}
#if (SILVERLIGHT || WINDOWS_PHONE)
static void socketAsync_Completed<T>(object sender, SocketAsyncEventArgs e)
{
if (e.LastOperation == SocketAsyncOperation.Connect)
{
Socket skt = sender as Socket;
InternetState<T> state = e.UserToken as InternetState<T>;
if (state != null)
{
LoggingMethod.WriteToLog(string.Format("DateTime {0} socketAsync_Completed.", DateTime.Now.ToString()), LoggingMethod.LevelInfo);
state.Callback(true);
}
mreSocketAsync.Set();
}
}
#endif
}
#endregion
}
| 41.778523 | 230 | 0.536627 | [
"MIT"
] | samuelcadieux/pubnub-c-sharp | mono-for-android/PubNubMessaging/ClientNetworkStatus.cs | 12,450 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class DestroyIfTooFarLeft : MonoBehaviour
{
void Update()
{
if(transform.position.x < -20f)
{
Destroy(gameObject);
}
}
}
| 16.0625 | 48 | 0.622568 | [
"MIT"
] | danielschneider22/Floopy-Birbs | Assets/Scripts/DestroyIfTooFarLeft.cs | 257 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
namespace NQuery.Authoring.Outlining
{
public abstract class SyntaxTokenOutliner : IOutliner
{
public IEnumerable<OutliningRegionSpan> FindRegions(SyntaxNodeOrToken nodeOrToken)
{
return !nodeOrToken.IsToken
? Enumerable.Empty<OutliningRegionSpan>()
: FindRegions(nodeOrToken.AsToken());
}
protected abstract IEnumerable<OutliningRegionSpan> FindRegions(SyntaxToken token);
}
} | 29.666667 | 91 | 0.694757 | [
"MIT"
] | dallmair/nquery-vnext | src/NQuery.Authoring/Outlining/SyntaxTokenOutliner.cs | 534 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using DM___Server.Models;
namespace DM___Server.Controllers
{
public class ControllerOnGoingGame
{
private Database db;
private Data.OnGoingGamesData onGoingGamesData;
private Data.LobbyRoomData lobbyRoomData;
public ControllerOnGoingGame(Database db, Data.OnGoingGamesData onGoingGamesData, Data.LobbyRoomData lobbyRoomData)
{
this.db = db;
this.onGoingGamesData = onGoingGamesData;
this.lobbyRoomData = lobbyRoomData;
}
public Models.Response processReadyToStart(Models.ClientMessage message, Socket sender)
{
Models.Response response = new Models.Response(sender);
Models.Game game;
game = onGoingGamesData.getGameByID(message.intArguments[0]);
if (game.isPlayer1(sender))
game.isP1Ready = true;
else
game.isP2Ready = true;
if (game.isP1Ready && game.isP2Ready)
{
response.responseCommandToSockets = "READYTOGO";
response.socketsToNotify.Add(game.Player1Socket);
response.socketsToNotify.Add(game.Player2Socket);
}
return response;
}
public Response processFetchDeck(ClientMessage message, Socket sender)
{
Response response = new Response(sender);
Models.Game game;
string deck;
game = onGoingGamesData.getGameByID(Int32.Parse(message.stringArguments[0]));
deck = db.getDeckByID(Int32.Parse(message.stringArguments[1]));
if (game.isPlayer1(sender))
game.loadPlayer1InitialData(deck);
else
game.loadPlayer2InitialData(deck);
response.responseCommandToSender = "DECKSET";
return response;
}
public Response processGetHand(ClientMessage message, Socket sender)
{
Response response = new Response(sender);
Models.Game game;
game = onGoingGamesData.getGameByID(message.intArguments[0]);
if (game.isPlayer1(sender))
response.commandStringArgumentsToSender = game.listPlayer1Hand.Select(x => x.ToString()).ToList<string>();
else
response.commandStringArgumentsToSender = game.listPlayer2Hand.Select(x => x.ToString()).ToList<string>();
response.responseCommandToSender = "HANDRECEIVED";
return response;
}
public Response processGetFirstGameState(ClientMessage message, Socket sender)
{
Response response = new Response(sender);
Models.Game game = onGoingGamesData.getGameByID(Int32.Parse(message.stringArguments[0]));
if (game.isPlayer1(sender))
if (game.isPlayer1First)
response.responseCommandToSender = "YOURTURN";
else
response.responseCommandToSender = "OPPTURN";
else
{
if (game.isPlayer1First)
response.responseCommandToSender = "OPPTURN";
else
response.responseCommandToSender = "YOURTURN";
}
return response;
}
public Response processPlayAsMana(GameMessage message, Socket sender)
{
Response response = new Response(null);
Models.Game game = onGoingGamesData.getGameByID(message.GameID);
if (game.isPlayer1(sender))
{
game.playAsMana(message.intArguments[0], 1);
response.socketsToNotify.Add(game.Player2Socket);
}
else
{
game.playAsMana(message.intArguments[0], 2);
response.socketsToNotify.Add(game.Player1Socket);
}
response.responseCommandToSockets = "PLAYEDASMANA";
response.commandIntArgumentsToSockets = message.intArguments;
return response;
}
public Response processSetPhase(GameMessage message, Socket sender)
{
Response response = new Response();
Models.Game game = onGoingGamesData.getGameByID(message.GameID);
if (game.isPlayer1(sender))
response.socketsToNotify.Add(game.Player2Socket);
else
response.socketsToNotify.Add(game.Player1Socket);
response.responseCommandToSockets = "SETPHASE";
response.commandStringArgumentsToSockets = message.stringArguments;
return response;
}
public Response processInGameChatMessage(GameMessage message, Socket sender)
{
Response response = new Response(sender);
Models.Game game = onGoingGamesData.getGameByID(message.GameID);
if (game.isPlayer1(sender))
response.socketsToNotify.Add(game.Player2Socket);
else
response.socketsToNotify.Add(game.Player1Socket);
response.responseCommandToSender = "NEWINGAMECHATMESSAGE";
response.responseCommandToSockets = "NEWINGAMECHATMESSAGE";
response.commandStringArgumentsToSender = message.stringArguments.ToList<string>();
response.commandStringArgumentsToSockets = message.stringArguments.ToList<string>();
response.commandIntArgumentsToSender.Add(1);
response.commandIntArgumentsToSockets.Add(0);
return response;
}
public Response processEndTurn(GameMessage message, Socket sender)
{
Response response = new Response();
Models.Game game = onGoingGamesData.getGameByID(message.GameID);
if (game.isPlayer1(sender))
{
response.socketsToNotify.Add(game.Player2Socket);
}
else
{
response.socketsToNotify.Add(game.Player1Socket);
}
response.responseCommandToSockets = "YOURTURN";
return response;
}
public Response processStartTurn(GameMessage message, Socket sender)
{
Response response = new Response(sender);
Models.Game game = onGoingGamesData.getGameByID(message.GameID);
if (game.isPlayer1(sender))
{
response.commandIntArgumentsToSender.Add(game.drawCard(1));
}
else
{
response.commandIntArgumentsToSender.Add(game.drawCard(2));
}
response.responseCommandToSender = "ROLLON";
return response;
}
public Response processDrawCard(GameMessage message, Socket sender)
{
Response response = new Response(sender);
Models.Game game = onGoingGamesData.getGameByID(message.GameID);
if (game.isPlayer1(sender))
{
for (int i = 0; i < message.intArguments[0]; i++)
response.commandIntArgumentsToSender.Add(game.drawCard(1));
response.socketsToNotify.Add(game.Player2Socket);
}
else
{
for (int i = 0; i < message.intArguments[0]; i++)
response.commandIntArgumentsToSender.Add(game.drawCard(2));
response.socketsToNotify.Add(game.Player1Socket);
}
response.responseCommandToSender = "YOURECEIVEDCARD";
response.responseCommandToSockets = "OPPRECEIVEDCARD";
response.commandIntArgumentsToSockets = message.intArguments;
return response;
}
public Response processSummon(GameMessage message, Socket sender)
{
Response response = new Response();
Models.Game game = onGoingGamesData.getGameByID(message.GameID);
if (game.isPlayer1(sender))
{
game.summon(message.intArguments[0], 1);
response.socketsToNotify.Add(game.Player2Socket);
}
else
{
game.summon(message.intArguments[0], 2);
response.socketsToNotify.Add(game.Player1Socket);
}
response.responseCommandToSockets = "SUMMON";
response.commandIntArgumentsToSockets = message.intArguments;
return response;
}
public Response processAttackSafeguards(GameMessage message, Socket sender)
{
Response response = new Response();
Models.Game game = onGoingGamesData.getGameByID(message.GameID);
if (game.isPlayer1(sender))
{
response.socketsToNotify.Add(game.Player2Socket);
}
else
{
response.socketsToNotify.Add(game.Player1Socket);
}
response.responseCommandToSockets = "ATTACKSAFEGUARDS";
response.commandIntArgumentsToSockets = message.intArguments;
return response;
}
public Response processBrokenSafeguards(GameMessage message, Socket sender)
{
Response response = new Response(sender);
Models.Game game = onGoingGamesData.getGameByID(message.GameID);
List<int> cardIDs = new List<int>();
message.intArguments.Reverse();
if (game.isPlayer1(sender))
{
foreach (int index in message.intArguments)
cardIDs.Add(game.breakSafeguard(index, 1));
}
else
{
foreach (int index in message.intArguments)
cardIDs.Add(game.breakSafeguard(index, 2));
}
response.responseCommandToSender = "YOURGUARDSBROKE";
response.commandIntArgumentsToSender.Add(cardIDs.Count);
foreach (int index in message.intArguments)
response.commandIntArgumentsToSender.Add(index);
foreach (int cardID in cardIDs)
response.commandIntArgumentsToSender.Add(cardID);
return response;
}
public Response processYouBrokeGuard(GameMessage message, Socket sender)
{
Response response = new Response(sender);
Models.Game game = onGoingGamesData.getGameByID(message.GameID);
message.intArguments.Reverse();
if (game.isPlayer1(sender))
{
response.socketsToNotify.Add(game.Player2Socket);
}
else
{
response.socketsToNotify.Add(game.Player1Socket);
}
response.responseCommandToSockets = "YOUBROKEGUARD";
response.commandIntArgumentsToSockets = message.intArguments.ToList<int>();
return response;
}
public Response processAttackCreature(GameMessage message, Socket sender)
{
Response response = new Response(null);
Models.Game game = onGoingGamesData.getGameByID(message.GameID);
if (game.isPlayer1(sender))
{
response.socketsToNotify.Add(game.Player2Socket);
}
else
{
response.socketsToNotify.Add(game.Player1Socket);
}
response.responseCommandToSockets = "ATTACKCREATURE";
response.commandIntArgumentsToSockets = message.intArguments;
return response;
}
public Response processDoBattle(GameMessage message, Socket sender)
{
Response response = new Response(sender);
Models.Game game = onGoingGamesData.getGameByID(message.GameID);
if (game.isPlayer1(sender))
{
response.socketsToNotify.Add(game.Player2Socket);
}
else
{
response.socketsToNotify.Add(game.Player1Socket);
}
response.responseCommandToSockets = "BATTLE";
response.commandIntArgumentsToSockets = message.intArguments;
return response;
}
public Response processSendTo(GameMessage message, Socket sender)
{
Response response = new Response();
Models.Game game = onGoingGamesData.getGameByID(message.GameID);
if (game.isPlayer1(sender))
{
response.socketsToNotify.Add(game.Player2Socket);
}
else
{
response.socketsToNotify.Add(game.Player1Socket);
}
response.responseCommandToSockets = "SENDTO";
response.commandIntArgumentsToSockets = message.intArguments;
response.commandStringArgumentsToSockets = message.stringArguments;
return response;
}
public Response processAttackOpponent(GameMessage message, Socket sender)
{
Response response = new Response(sender);
Models.Game game = onGoingGamesData.getGameByID(message.GameID);
if (game.isPlayer1(sender))
{
response.socketsToNotify.Add(game.Player2Socket);
}
else
{
response.socketsToNotify.Add(game.Player1Socket);
}
response.responseCommandToSockets = "ATTACKPLAYER";
response.commandIntArgumentsToSockets = message.intArguments;
return response;
}
public Response processISurrender(GameMessage message, Socket sender)
{
Response response = new Response(sender);
Models.Game game = onGoingGamesData.getGameByID(message.GameID);
string victorUsername;
string defeatedUsername;
if (game == null)
return response;
if (game.isPlayer1(sender))
{
victorUsername = lobbyRoomData.getUsernameBySocket(game.Player2Socket);
defeatedUsername = lobbyRoomData.getUsernameBySocket(game.Player1Socket);
response.socketsToNotify.Add(game.Player2Socket);
}
else
{
victorUsername = lobbyRoomData.getUsernameBySocket(game.Player1Socket);
defeatedUsername = lobbyRoomData.getUsernameBySocket(game.Player2Socket);
response.socketsToNotify.Add(game.Player1Socket);
}
db.updateUserData(victorUsername, defeatedUsername);
onGoingGamesData.removeGame(game);
response.responseCommandToSockets = "OPPSURRENDERED";
response.commandIntArgumentsToSockets = message.intArguments;
return response;
}
public Response processDeckToMana(GameMessage message, Socket sender)
{
Response response = new Response(sender);
Models.Game game = onGoingGamesData.getGameByID(message.GameID);
if (game.isPlayer1(sender))
{
for (int i = 0; i < message.intArguments[0]; i++)
response.commandIntArgumentsToSender.Add(game.drawCard(1));
response.socketsToNotify.Add(game.Player2Socket);
}
else
{
for (int i = 0; i < message.intArguments[0]; i++)
response.commandIntArgumentsToSender.Add(game.drawCard(2));
response.socketsToNotify.Add(game.Player1Socket);
}
response.responseCommandToSender = "YOURDECKTOMANA";
response.responseCommandToSockets = "OPPSDECKTOMANA";
response.commandIntArgumentsToSockets = response.commandIntArgumentsToSender.ToList<int>();
return response;
}
}
}
| 35 | 123 | 0.59106 | [
"MIT"
] | Gabriel-Em/Clash-of-the-Elements___Online-2D-TCG | DM - Server/DM - Server/Controllers/ControllerOnGoingGame.cs | 15,997 | C# |
//*********************************************************************
//xCAD
//Copyright(C) 2021 Xarial Pty Limited
//Product URL: https://www.xcad.net
//License: https://xcad.xarial.com/license/
//*********************************************************************
using SolidWorks.Interop.sldworks;
using System;
using System.Collections.Generic;
using System.Text;
using Xarial.XCad.Geometry.Structures;
using Xarial.XCad.Geometry.Surfaces;
using Xarial.XCad.SolidWorks.Documents;
namespace Xarial.XCad.SolidWorks.Geometry.Surfaces
{
public interface ISwCylindricalSurface : ISwSurface, IXCylindricalSurface
{
}
internal class SwCylindricalSurface : SwSurface, ISwCylindricalSurface
{
internal SwCylindricalSurface(ISurface surface, ISwDocument doc, ISwApplication app) : base(surface, doc, app)
{
}
public Point Origin
{
get
{
var cylParams = CylinderParams;
return new Point(cylParams[0], cylParams[1], cylParams[2]);
}
}
public Vector Axis
{
get
{
var cylParams = CylinderParams;
return new Vector(cylParams[3], cylParams[4], cylParams[5]);
}
}
public double Radius => CylinderParams[6];
private double[] CylinderParams
{
get
{
return Surface.CylinderParams as double[];
}
}
}
}
| 25.694915 | 118 | 0.538918 | [
"MIT"
] | EddyAlleman/xcad | src/SolidWorks/Geometry/Surfaces/SwCylindricalSurface.cs | 1,518 | C# |
using Abp.EntityFrameworkCore.Configuration;
using Abp.Modules;
using Abp.Reflection.Extensions;
using Abp.Zero.EntityFrameworkCore;
using Code.Together.EntityFrameworkCore.Seed;
namespace Code.Together.EntityFrameworkCore
{
[DependsOn(
typeof(TogetherCoreModule),
typeof(AbpZeroCoreEntityFrameworkCoreModule))]
public class TogetherEntityFrameworkModule : AbpModule
{
/* Used it tests to skip dbcontext registration, in order to use in-memory database of EF Core */
public bool SkipDbContextRegistration { get; set; }
public bool SkipDbSeed { get; set; }
public override void PreInitialize()
{
if (!SkipDbContextRegistration)
{
Configuration.Modules.AbpEfCore().AddDbContext<TogetherDbContext>(options =>
{
if (options.ExistingConnection != null)
{
TogetherDbContextConfigurer.Configure(options.DbContextOptions, options.ExistingConnection);
}
else
{
TogetherDbContextConfigurer.Configure(options.DbContextOptions, options.ConnectionString);
}
});
}
}
public override void Initialize()
{
IocManager.RegisterAssemblyByConvention(typeof(TogetherEntityFrameworkModule).GetAssembly());
}
public override void PostInitialize()
{
if (!SkipDbSeed)
{
SeedHelper.SeedHostDb(IocManager);
}
}
}
}
| 32.117647 | 116 | 0.591575 | [
"MIT"
] | antonio-mikulic/code.together | aspnet-core/src/Code.Together.EntityFrameworkCore/EntityFrameworkCore/TogetherEntityFrameworkModule.cs | 1,640 | C# |
using System;
using System.Linq;
using System.Reflection;
namespace Regulus.Remote.Client
{
public class MethodStringInvoker
{
private readonly TypeConverterSet _TypeConverterSet ;
public readonly object Target;
public readonly MethodInfo Method;
public MethodStringInvoker(object instance, MethodInfo method, TypeConverterSet set)
{
this.Target = instance;
_TypeConverterSet = set;
this.Method = method;
}
public object Invoke(params string[] in_args)
{
ParameterInfo[] argInfos = Method.GetParameters();
if (in_args.Length != argInfos.Length)
throw new Exception($"Method parameter is {argInfos.Length}, input parameter is {in_args.Length}");
System.Collections.Generic.List<object> argInstances = new System.Collections.Generic.List<object>();
for (int i = 0; i < argInfos.Length; ++i)
{
ParameterInfo argInfo = argInfos[i];
string inArg = in_args[i];
object val;
try
{
_Conversion(inArg, out val, argInfo.ParameterType);
argInstances.Add(val);
}
catch (SystemException se)
{
throw new Exception($"Type mismatch , arg is {inArg}");
}
}
return Method.Invoke(Target, argInstances.ToArray());
}
private void _Conversion(string inArg, out object val, Type parameterType)
{
if (_TypeConverterSet.Convert(inArg, out val, parameterType))
return;
Regulus.Utility.Command.TryConversion(inArg, out val, parameterType);
}
}
} | 29.983607 | 115 | 0.561509 | [
"BSD-2-Clause"
] | jiowchern/Regulus | Regulus.Remote.Client/MethodStringInvoker.cs | 1,831 | C# |
namespace SpineEngine.GlobalManagers.Tweens
{
public enum LoopType
{
None,
RestartFromBeginning,
PingPong
}
} | 14.363636 | 45 | 0.56962 | [
"MIT"
] | ApmeM/SpineEngine | SpineEngine/GlobalManagers/Tweens/LoopType.cs | 160 | C# |
// Copyright (C) 2003-2012 Xtensive LLC.
// All rights reserved.
// For conditions of distribution and use, see license.
// Created by: Denis Krjuchkov
// Created: 2013.01.22
using System;
namespace Xtensive.Tuples.Packed
{
internal abstract class PackedFieldAccessor
{
/// <summary>
/// Getter delegate.
/// </summary>
protected Delegate Getter;
/// <summary>
/// Setter delegate.
/// </summary>
protected Delegate Setter;
/// <summary>
/// Nullable getter delegate.
/// </summary>
protected Delegate NullableGetter;
/// <summary>
/// Nullable setter delegate.
/// </summary>
protected Delegate NullableSetter;
public void SetValue<T>(PackedTuple tuple, PackedFieldDescriptor descriptor, bool isNullable, T value)
{
var setter = (isNullable ? NullableSetter : Setter) as SetValueDelegate<T>;
if (setter!=null)
setter.Invoke(tuple, descriptor, value);
else
SetUntypedValue(tuple, descriptor, value);
}
public T GetValue<T>(PackedTuple tuple, PackedFieldDescriptor descriptor, bool isNullable, out TupleFieldState fieldState)
{
var getter = (isNullable ? NullableGetter : Getter) as GetValueDelegate<T>;
if (getter!=null)
return getter.Invoke(tuple, descriptor, out fieldState);
var targetType = typeof (T);
//Dirty hack of nullable enum reading
if (isNullable)
targetType = Nullable.GetUnderlyingType(targetType) ?? targetType;
if (targetType.IsEnum)
return (T) Enum.ToObject(targetType, GetUntypedValue(tuple, descriptor, out fieldState));
return (T) GetUntypedValue(tuple, descriptor, out fieldState);
}
public abstract object GetUntypedValue(PackedTuple tuple, PackedFieldDescriptor descriptor, out TupleFieldState fieldState);
public abstract void SetUntypedValue(PackedTuple tuple, PackedFieldDescriptor descriptor, object value);
public abstract void CopyValue(PackedTuple source, PackedFieldDescriptor sourceDescriptor,
PackedTuple target, PackedFieldDescriptor targetDescriptor);
public abstract bool ValueEquals(PackedTuple left, PackedFieldDescriptor leftDescriptor,
PackedTuple right, PackedFieldDescriptor rightDescriptor);
public abstract int GetValueHashCode(PackedTuple tuple, PackedFieldDescriptor descriptor);
}
internal sealed class ObjectFieldAccessor : PackedFieldAccessor
{
public override object GetUntypedValue(PackedTuple tuple, PackedFieldDescriptor descriptor, out TupleFieldState fieldState)
{
var state = tuple.GetFieldState(descriptor);
fieldState = state;
return state==TupleFieldState.Available ? tuple.Objects[descriptor.ValueIndex] : null;
}
public override void SetUntypedValue(PackedTuple tuple, PackedFieldDescriptor descriptor, object value)
{
tuple.Objects[descriptor.ValueIndex] = value;
if (value!=null)
tuple.SetFieldState(descriptor, TupleFieldState.Available);
else
tuple.SetFieldState(descriptor, TupleFieldState.Available | TupleFieldState.Null);
}
public override void CopyValue(PackedTuple source, PackedFieldDescriptor sourceDescriptor,
PackedTuple target, PackedFieldDescriptor targetDescriptor)
{
target.Objects[targetDescriptor.ValueIndex] = source.Objects[sourceDescriptor.ValueIndex];
}
public override bool ValueEquals(PackedTuple left, PackedFieldDescriptor leftDescriptor,
PackedTuple right, PackedFieldDescriptor rightDescriptor)
{
var leftValue = left.Objects[leftDescriptor.ValueIndex];
var rightValue = right.Objects[rightDescriptor.ValueIndex];
return leftValue.Equals(rightValue);
}
public override int GetValueHashCode(PackedTuple tuple, PackedFieldDescriptor descriptor)
{
return tuple.Objects[descriptor.ValueIndex].GetHashCode();
}
}
internal abstract class ValueFieldAccessor : PackedFieldAccessor
{
public readonly int BitCount;
public readonly long BitMask;
private static long GetMask(int bits)
{
long result = 0;
for (int i = 0; i < bits; i++) {
result <<= 1;
result |= 1;
}
return result;
}
protected ValueFieldAccessor(int bits)
{
BitCount = bits;
if (bits <= 64)
BitMask = GetMask(bits);
}
}
internal abstract class ValueFieldAccessor<T> : ValueFieldAccessor
where T : struct, IEquatable<T>
{
private static readonly T DefaultValue = default(T);
private static readonly T? NullValue = null;
protected virtual long Encode(T value)
{
throw new NotSupportedException();
}
protected virtual void Encode(T value, long[] values, int offset)
{
throw new NotSupportedException();
}
protected virtual T Decode(long value)
{
throw new NotSupportedException();
}
protected virtual T Decode(long[] values, int offset)
{
throw new NotSupportedException();
}
public override object GetUntypedValue(PackedTuple tuple, PackedFieldDescriptor descriptor, out TupleFieldState fieldState)
{
var state = tuple.GetFieldState(descriptor);
fieldState = state;
return state==TupleFieldState.Available ? (object) Load(tuple, descriptor) : null;
}
public override void SetUntypedValue(PackedTuple tuple, PackedFieldDescriptor descriptor, object value)
{
if (value!=null) {
Store(tuple, descriptor, (T) value);
tuple.SetFieldState(descriptor, TupleFieldState.Available);
}
else
tuple.SetFieldState(descriptor, TupleFieldState.Available | TupleFieldState.Null);
}
public override void CopyValue(PackedTuple source, PackedFieldDescriptor sourceDescriptor,
PackedTuple target, PackedFieldDescriptor targetDescriptor)
{
Store(target, targetDescriptor, Load(source, sourceDescriptor));
}
public override bool ValueEquals(PackedTuple left, PackedFieldDescriptor leftDescriptor,
PackedTuple right, PackedFieldDescriptor rightDescriptor)
{
var leftValue = Load(left, leftDescriptor);
var rightValue = Load(right, rightDescriptor);
return leftValue.Equals(rightValue);
}
public override int GetValueHashCode(PackedTuple tuple, PackedFieldDescriptor descriptor)
{
return Load(tuple, descriptor).GetHashCode();
}
private T GetValue(PackedTuple tuple, PackedFieldDescriptor descriptor, out TupleFieldState fieldState)
{
var state = tuple.GetFieldState(descriptor);
fieldState = state;
return state==TupleFieldState.Available ? Load(tuple, descriptor) : DefaultValue;
}
private T? GetNullableValue(PackedTuple tuple, PackedFieldDescriptor descriptor, out TupleFieldState fieldState)
{
var state = tuple.GetFieldState(descriptor);
fieldState = state;
return state==TupleFieldState.Available ? Load(tuple, descriptor) : NullValue;
}
private void SetValue(PackedTuple tuple, PackedFieldDescriptor descriptor, T value)
{
Store(tuple, descriptor, value);
tuple.SetFieldState(descriptor, TupleFieldState.Available);
}
private void SetNullableValue(PackedTuple tuple, PackedFieldDescriptor descriptor, T? value)
{
if (value!=null) {
Store(tuple, descriptor, value.Value);
tuple.SetFieldState(descriptor, TupleFieldState.Available);
}
else
tuple.SetFieldState(descriptor, TupleFieldState.Available | TupleFieldState.Null);
}
private void Store(PackedTuple tuple, PackedFieldDescriptor d, T value)
{
if (d.ValueBitCount > 64) {
Encode(value, tuple.Values, d.ValueIndex);
return;
}
var encoded = Encode(value);
var block = tuple.Values[d.ValueIndex];
var mask = d.ValueBitMask << d.ValueBitOffset;
tuple.Values[d.ValueIndex] = (block & ~mask) | ((encoded << d.ValueBitOffset) & mask);
}
private T Load(PackedTuple tuple, PackedFieldDescriptor d)
{
if (d.ValueBitCount > 64)
return Decode(tuple.Values, d.ValueIndex);
var encoded = (tuple.Values[d.ValueIndex] >> d.ValueBitOffset) & d.ValueBitMask;
return Decode(encoded);
}
protected ValueFieldAccessor(int bits)
: base(bits)
{
Getter = (GetValueDelegate<T>) GetValue;
Setter = (SetValueDelegate<T>) SetValue;
NullableGetter = (GetValueDelegate<T?>) GetNullableValue;
NullableSetter = (SetValueDelegate<T?>) SetNullableValue;
}
}
internal sealed class BooleanFieldAccessor : ValueFieldAccessor<bool>
{
protected override long Encode(bool value)
{
return value ? 1L : 0L;
}
protected override bool Decode(long value)
{
return value!=0;
}
public BooleanFieldAccessor()
: base(1)
{
}
}
internal sealed class FloatFieldAccessor : ValueFieldAccessor<float>
{
protected override long Encode(float value)
{
unsafe {
return *(int*) &value;
}
}
protected override float Decode(long value)
{
var intValue = unchecked ((int) value);
unsafe {
return *(float*) &intValue;
}
}
public FloatFieldAccessor()
: base(sizeof(float) * 8)
{
}
}
internal sealed class DoubleFieldAccessor : ValueFieldAccessor<double>
{
protected override long Encode(double value)
{
return BitConverter.DoubleToInt64Bits(value);
}
protected override double Decode(long value)
{
return BitConverter.Int64BitsToDouble(value);
}
public DoubleFieldAccessor()
: base(sizeof(double) * 8)
{
}
}
internal sealed class TimeSpanFieldAccessor : ValueFieldAccessor<TimeSpan>
{
protected override long Encode(TimeSpan value)
{
return value.Ticks;
}
protected override TimeSpan Decode(long value)
{
return TimeSpan.FromTicks(value);
}
public TimeSpanFieldAccessor()
: base(sizeof(long) * 8)
{
}
}
internal sealed class DateTimeFieldAccessor : ValueFieldAccessor<DateTime>
{
protected override long Encode(DateTime value)
{
return value.ToBinary();
}
protected override DateTime Decode(long value)
{
return DateTime.FromBinary(value);
}
public DateTimeFieldAccessor()
: base(sizeof(long) * 8)
{
}
}
internal sealed class ByteFieldAccessor : ValueFieldAccessor<byte>
{
protected override long Encode(byte value)
{
return value;
}
protected override byte Decode(long value)
{
return unchecked ((byte) value);
}
public ByteFieldAccessor()
: base(sizeof(byte) * 8)
{
}
}
internal sealed class SByteFieldAccessor : ValueFieldAccessor<sbyte>
{
protected override long Encode(sbyte value)
{
return value;
}
protected override sbyte Decode(long value)
{
return unchecked ((sbyte) value);
}
public SByteFieldAccessor()
: base(sizeof(sbyte) * 8)
{
}
}
internal sealed class ShortFieldAccessor : ValueFieldAccessor<short>
{
protected override long Encode(short value)
{
return value;
}
protected override short Decode(long value)
{
return unchecked ((short) value);
}
public ShortFieldAccessor()
: base(sizeof(short) * 8)
{
}
}
internal sealed class UShortFieldAccessor : ValueFieldAccessor<ushort>
{
protected override long Encode(ushort value)
{
return value;
}
protected override ushort Decode(long value)
{
return unchecked ((ushort) value);
}
public UShortFieldAccessor()
: base(sizeof(ushort) * 8)
{
}
}
internal sealed class IntFieldAccessor : ValueFieldAccessor<int>
{
protected override long Encode(int value)
{
return value;
}
protected override int Decode(long value)
{
return unchecked ((int) value);
}
public IntFieldAccessor()
: base(sizeof(int) * 8)
{
}
}
internal sealed class UIntFieldAccessor : ValueFieldAccessor<uint>
{
protected override long Encode(uint value)
{
return value;
}
protected override uint Decode(long value)
{
return unchecked ((uint) value);
}
public UIntFieldAccessor()
: base(sizeof(uint) * 8)
{
}
}
internal sealed class LongFieldAccessor : ValueFieldAccessor<long>
{
protected override long Encode(long value)
{
return value;
}
protected override long Decode(long value)
{
return value;
}
public LongFieldAccessor()
: base(sizeof(long) * 8)
{
}
}
internal sealed class ULongFieldAccessor : ValueFieldAccessor<ulong>
{
protected override long Encode(ulong value)
{
return unchecked((long) value);
}
protected override ulong Decode(long value)
{
return unchecked((ulong) value);
}
public ULongFieldAccessor()
: base(sizeof(ulong) * 8)
{
}
}
internal sealed class GuidFieldAccessor : ValueFieldAccessor<Guid>
{
protected override Guid Decode(long[] values, int offset)
{
unsafe {
fixed (long* valuePtr = &values[offset])
return *(Guid*) valuePtr;
}
}
protected override void Encode(Guid value, long[] values, int offset)
{
unsafe {
fixed (long* valuePtr = &values[offset])
*(Guid*) valuePtr = value;
}
}
private static unsafe int GetSize()
{
return sizeof (Guid);
}
public GuidFieldAccessor()
: base(GetSize() * 8)
{
}
}
internal sealed class DecimalFieldAccessor : ValueFieldAccessor<decimal>
{
protected override decimal Decode(long[] values, int offset)
{
unsafe {
fixed (long* valuePtr = &values[offset])
return *(decimal*) valuePtr;
}
}
protected override void Encode(decimal value, long[] values, int offset)
{
unsafe {
fixed (long* valuePtr = &values[offset])
*(decimal*) valuePtr = value;
}
}
public DecimalFieldAccessor()
: base(sizeof(decimal) * 8)
{
}
}
}
| 26.967273 | 129 | 0.640912 | [
"MIT"
] | SergeiPavlov/dataobjects-net | DataObjects/Tuples/Packed/PackedFieldAccessor.cs | 14,834 | C# |
using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Threading.Tasks;
using Sanatana.Contents.Objects;
using Sanatana.Contents.Objects.DTOs;
using Sanatana.Contents.Objects.Entities;
using Sanatana.Patterns.Pipelines;
namespace Sanatana.Contents.Selectors.Comments
{
public interface ICommentSelector<TKey, TCategory, TContent, TComment>
where TKey : struct
where TCategory : Category<TKey>
where TContent : Content<TKey>
where TComment : Comment<TKey>
{
Task<Expression<Func<CommentJoinResult<TKey, TComment, TContent>, bool>>> AddCategoryFilter(long permission, TKey? userId, Expression<Func<CommentJoinResult<TKey, TComment, TContent>, bool>> filterConditions, IEnumerable<TKey> categoryIds = null);
Task<Expression<Func<TComment, bool>>> AddCategoryFilter(long permission, TKey? userId, Expression<Func<TComment, bool>> filterConditions, IEnumerable<TKey> categoryIds = null);
List<ParentVM<CommentJoinResult<TKey, TComment, TContent>>> GroupComments(List<CommentJoinResult<TKey, TComment, TContent>> comments, CommentsGroupMethod groupMethod);
List<ParentVM<TComment>> GroupComments(List<TComment> comments, CommentsGroupMethod groupMethod);
Task<PipelineResult<List<ParentVM<TComment>>>> SelectAllForContent(int page, int pageSize, bool orderDescending, TKey contentId, TKey contentCategoryId, long permission, TKey? userId, CommentsGroupMethod groupMethod, Expression<Func<TComment, bool>> filterConditions);
Task<List<ParentVM<CommentJoinResult<TKey, TComment, TContent>>>> SelectPageInCategory(int page, int pageSize, bool orderDescending, DataAmount contentAmount, long permission, TKey? userId, CommentsGroupMethod groupMethod, Expression<Func<CommentJoinResult<TKey, TComment, TContent>, bool>> filterConditions, IEnumerable<TKey> categoryIds = null);
}
} | 76 | 355 | 0.783158 | [
"MIT"
] | RodionKulin/ContentManagementBackend | Sanatana.Contents/Selectors/Comments/ICommentSelector.cs | 1,902 | C# |
using System.Net;
using System.Web.Mvc;
using NinjaDomain.Classes;
using NinjaDomain.DataModel;
namespace MVCApp.Controllers
{
public class NinjaEquipmentsController : Controller
{
private readonly DisconnectedRepository _repo = new DisconnectedRepository();
// GET: NinjaEquipments/Create
public ActionResult Create(int ninjaId, string ninjaName)
{
ViewBag.NinjaId = ninjaId;
ViewBag.NinjaName = ninjaName;
return View();
}
// POST: NinjaEquipments/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(
[Bind(Include = "Id,Name,Type,DateCreated,DateModified,NinjaId")] NinjaEquipment ninjaEquipment)
{
int ninjaId;
if (!int.TryParse(Request.Form["NinjaId"], out ninjaId))
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
_repo.SaveNewEquipment(ninjaEquipment, ninjaId);
return RedirectToAction("Edit", "Ninjas", new {id = ninjaId});
}
// GET: NinjaEquipments/Edit/5
public ActionResult Edit(int? id, int ninjaId, string name)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
ViewBag.NinjaId = ninjaId;
ViewBag.NinjaName = name;
var ninjaEquipment = _repo.GetEquipmentById(id.Value);
if (ninjaEquipment == null)
{
return HttpNotFound();
}
return View(ninjaEquipment);
}
// POST: NinjaEquipments/Edit/5
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "Id,Name,Type,DateCreated,DateModified")] NinjaEquipment ninjaEquipment)
{
int ninjaId;
if (!int.TryParse(Request.Form["NinjaId"], out ninjaId))
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
_repo.SaveUpdatedEquipment(ninjaEquipment, ninjaId);
return RedirectToAction("Edit", "Ninjas", new {id = ninjaId});
}
}
} | 32.263889 | 117 | 0.681877 | [
"MIT"
] | JYang17/SampleCode | Samples/EF6/Distribution/MVCApp Repository/Controllers/NinjaEquipmentsController.cs | 2,325 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
using System;
using System.Collections.Generic;
namespace FASTER.core
{
/// <summary>
/// Interface for users to control creation and retrieval of checkpoint-related data
/// FASTER calls this interface during checkpoint/recovery in this sequence:
///
/// Checkpoint:
/// InitializeIndexCheckpoint (for index checkpoints) ->
/// GetIndexDevice (for index checkpoints) ->
/// InitializeLogCheckpoint (for log checkpoints) ->
/// GetSnapshotLogDevice (for log checkpoints in snapshot mode) ->
/// GetSnapshotObjectLogDevice (for log checkpoints in snapshot mode with objects) ->
/// CommitLogCheckpoint (for log checkpoints) ->
/// CommitIndexCheckpoint (for index checkpoints) ->
///
/// Recovery:
/// GetIndexCommitMetadata ->
/// GetLogCommitMetadata ->
/// GetIndexDevice ->
/// GetSnapshotLogDevice (for recovery in snapshot mode) ->
/// GetSnapshotObjectLogDevice (for recovery in snapshot mode with objects)
///
/// Provided devices will be closed directly by FASTER when done.
/// </summary>
public interface ICheckpointManager : IDisposable
{
/// <summary>
/// Initialize index checkpoint
/// </summary>
/// <param name="indexToken"></param>
void InitializeIndexCheckpoint(Guid indexToken);
/// <summary>
/// Initialize log checkpoint (snapshot and fold-over)
/// </summary>
/// <param name="logToken"></param>
void InitializeLogCheckpoint(Guid logToken);
/// <summary>
/// Commit index checkpoint
/// </summary>
/// <param name="indexToken"></param>
/// <param name="commitMetadata"></param>
/// <returns></returns>
void CommitIndexCheckpoint(Guid indexToken, byte[] commitMetadata);
/// <summary>
/// Commit log checkpoint (snapshot and fold-over)
/// </summary>
/// <param name="logToken"></param>
/// <param name="commitMetadata"></param>
/// <returns></returns>
void CommitLogCheckpoint(Guid logToken, byte[] commitMetadata);
/// <summary>
/// Retrieve commit metadata for specified index checkpoint
/// </summary>
/// <param name="indexToken">Token</param>
/// <returns>Metadata, or null if invalid</returns>
byte[] GetIndexCheckpointMetadata(Guid indexToken);
/// <summary>
/// Retrieve commit metadata for specified log checkpoint
/// </summary>
/// <param name="logToken">Token</param>
/// <returns>Metadata, or null if invalid</returns>
byte[] GetLogCheckpointMetadata(Guid logToken);
/// <summary>
/// Get list of index checkpoint tokens, in order of usage preference
/// </summary>
/// <returns></returns>
IEnumerable<Guid> GetIndexCheckpointTokens();
/// <summary>
/// Get list of log checkpoint tokens, in order of usage preference
/// </summary>
/// <returns></returns>
IEnumerable<Guid> GetLogCheckpointTokens();
/// <summary>
/// Provide device to store index checkpoint (including overflow buckets)
/// </summary>
/// <param name="indexToken"></param>
/// <returns></returns>
IDevice GetIndexDevice(Guid indexToken);
/// <summary>
/// Provide device to store snapshot of log (required only for snapshot checkpoints)
/// </summary>
/// <param name="token"></param>
/// <returns></returns>
IDevice GetSnapshotLogDevice(Guid token);
/// <summary>
/// Provide device to store snapshot of object log (required only for snapshot checkpoints)
/// </summary>
/// <param name="token"></param>
/// <returns></returns>
IDevice GetSnapshotObjectLogDevice(Guid token);
/// <summary>
/// Cleanup all data (subfolder) related to checkpoints by this manager
/// </summary>
void PurgeAll();
}
} | 37.035398 | 99 | 0.604779 | [
"MIT"
] | marius-klimantavicius/mister | Marius.Mister/FASTER.core/Index/Recovery/ICheckpointManager.cs | 4,187 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ManaPotion : MonoBehaviour, ItemOnGUIDoubleClickable {
public float addMana = 100;
public void ItemOnGUIDoubleClick (ItemHandleOnGUI gui)
{
if (GameCentalPr.Instance.PlayerProcessor.AddMana(addMana))
{
gui.Clean();
LEInventory leInventory = GetComponentInParent<LEInventory>();
Item item = GetComponentInChildren<ItemHandleOnObj>().item;
leInventory.RemoveItem(item);
DestroyImmediate(gameObject);
}
}
}
| 24.32 | 74 | 0.667763 | [
"MIT"
] | Visin1991/Role-playing-Game-Framework | FrameWork/Assets/Script/FrameWroks/Entity/ItemSystem/ItemInstance/ManaPotion.cs | 610 | C# |
#nullable enable
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using DotVVM.Framework.Controls;
using DotVVM.Framework.Utils;
using System.Diagnostics;
using DotVVM.Framework.Compilation;
using DotVVM.Framework.Binding.Expressions;
using DotVVM.Framework.Compilation.ControlTree;
using DotVVM.Framework.Compilation.ControlTree.Resolved;
using Newtonsoft.Json;
namespace DotVVM.Framework.Binding
{
/// <summary>
/// Represents a property of DotVVM controls.
/// </summary>
[DebuggerDisplay("{FullName}")]
public class DotvvmProperty : IPropertyDescriptor
{
/// <summary>
/// Gets or sets the name of the property.
/// </summary>
public string Name { get; protected set; }
[JsonIgnore]
ITypeDescriptor IControlAttributeDescriptor.DeclaringType => new ResolvedTypeDescriptor(DeclaringType);
[JsonIgnore]
ITypeDescriptor IControlAttributeDescriptor.PropertyType => new ResolvedTypeDescriptor(PropertyType);
/// <summary>
/// Gets the default value of the property.
/// </summary>
public object? DefaultValue { get; protected set; }
/// <summary>
/// Gets the type of the property.
/// </summary>
public Type PropertyType { get; protected set; }
/// <summary>
/// Gets the type of the class where the property is registered.
/// </summary>
public Type DeclaringType { get; protected set; }
/// <summary>
/// Gets whether the value can be inherited from the parent controls.
/// </summary>
public bool IsValueInherited { get; protected set; }
/// <summary>
/// Gets or sets the Reflection property information.
/// </summary>
[JsonIgnore]
public PropertyInfo? PropertyInfo { get; private set; }
/// <summary>
/// Gets or sets the markup options.
/// </summary>
public MarkupOptionsAttribute MarkupOptions { get; set; }
/// <summary>
/// Virtual DotvvmProperty are not explicitly registered but marked with [MarkupOptions] attribute on DotvvmControl
/// </summary>
public bool IsVirtual { get; set; }
/// <summary>
/// Determines if property type inherits from IBinding
/// </summary>
public bool IsBindingProperty { get; private set; }
/// <summary>
/// Gets the full name of the descriptor.
/// </summary>
public string DescriptorFullName
{
get { return DeclaringType.FullName + "." + Name + "Property"; }
}
/// <summary>
/// Gets the full name of the property.
/// </summary>
public string FullName
{
get { return DeclaringType.Name + "." + Name; }
}
[JsonIgnore]
public DataContextChangeAttribute[] DataContextChangeAttributes { get; private set; }
[JsonIgnore]
public DataContextStackManipulationAttribute? DataContextManipulationAttribute { get; private set; }
/// <summary>
/// Prevents a default instance of the <see cref="DotvvmProperty"/> class from being created.
/// </summary>
#pragma warning disable CS8618 // DotvvmProperty is usually initialized by InitializeProperty
internal DotvvmProperty()
#pragma warning restore CS8618
{
}
/// <summary>
/// Gets the value of the property.
/// </summary>
public virtual object? GetValue(DotvvmBindableObject control, bool inherit = true)
{
if (control.properties.TryGet(this, out var value))
{
return value;
}
if (IsValueInherited && inherit && control.Parent != null)
{
return GetValue(control.Parent);
}
return DefaultValue;
}
/// <summary>
/// Gets whether the value of the property is set
/// </summary>
public virtual bool IsSet(DotvvmBindableObject control, bool inherit = true)
{
if (control.properties.Contains(this))
{
return true;
}
if (IsValueInherited && inherit && control.Parent != null)
{
return IsSet(control.Parent);
}
return false;
}
/// <summary>
/// Sets the value of the property.
/// </summary>
public virtual void SetValue(DotvvmBindableObject control, object? value)
{
control.properties.Set(this, value);
}
/// <summary>
/// Registers the specified DotVVM property.
/// </summary>
public static DotvvmProperty Register<TPropertyType, TDeclaringType>(Expression<Func<DotvvmProperty>> fieldAccessor, TPropertyType defaultValue = default(TPropertyType), bool isValueInherited = false)
{
var field = ReflectionUtils.GetMemberFromExpression(fieldAccessor.Body) as FieldInfo;
if (field == null || !field.IsStatic) throw new ArgumentException("The expression should be simple static field access", nameof(fieldAccessor));
if (!field.Name.EndsWith("Property", StringComparison.Ordinal)) throw new ArgumentException($"DotVVM property backing field's '{field.Name}' name should end with 'Property'");
return Register<TPropertyType, TDeclaringType>(field.Name.Remove(field.Name.Length - "Property".Length), defaultValue, isValueInherited);
}
/// <summary>
/// Registers the specified DotVVM property.
/// </summary>
public static DotvvmProperty Register<TPropertyType, TDeclaringType>(Expression<Func<TDeclaringType, object?>> propertyAccessor, TPropertyType defaultValue = default(TPropertyType), bool isValueInherited = false)
{
var property = ReflectionUtils.GetMemberFromExpression(propertyAccessor.Body) as PropertyInfo;
if (property == null) throw new ArgumentException("The expression should be simple property access", nameof(propertyAccessor));
return Register<TPropertyType, TDeclaringType>(property.Name, defaultValue, isValueInherited);
}
/// <summary>
/// Registers the specified DotVVM property.
/// </summary>
public static DotvvmProperty Register<TPropertyType, TDeclaringType>(string propertyName, TPropertyType defaultValue = default(TPropertyType), bool isValueInherited = false, DotvvmProperty? property = null)
{
var field = typeof(TDeclaringType).GetField(propertyName + "Property", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
if (field == null) throw new ArgumentException($"'{typeof(TDeclaringType).Name}' does not contain static field '{propertyName}Property'.");
return Register(propertyName, typeof(TPropertyType), typeof(TDeclaringType), defaultValue, isValueInherited, property, field);
}
public static DotvvmProperty Register(string propertyName, Type propertyType, Type declaringType, object? defaultValue, bool isValueInherited, DotvvmProperty? property, ICustomAttributeProvider attributeProvider, bool throwOnDuplicitRegistration = true)
{
var fullName = declaringType.FullName + "." + propertyName;
if (property == null) property = new DotvvmProperty();
property.Name = propertyName;
property.IsValueInherited = isValueInherited;
property.DeclaringType = declaringType;
property.PropertyType = propertyType;
property.DefaultValue = defaultValue;
InitializeProperty(property, attributeProvider);
if (!registeredProperties.TryAdd(fullName, property))
{
if (throwOnDuplicitRegistration)
throw new ArgumentException($"Property is already registered: {fullName}");
else
property = registeredProperties[fullName];
}
return property;
}
public static void InitializeProperty(DotvvmProperty property, ICustomAttributeProvider attributeProvider)
{
var propertyInfo = property.DeclaringType.GetProperty(property.Name);
var markupOptions = propertyInfo?.GetCustomAttribute<MarkupOptionsAttribute>()
?? attributeProvider.GetCustomAttribute<MarkupOptionsAttribute>()
?? new MarkupOptionsAttribute() {
AllowBinding = true,
AllowHardCodedValue = true,
MappingMode = MappingMode.Attribute,
Name = property.Name
};
if (string.IsNullOrEmpty(markupOptions.Name)) markupOptions.Name = property.Name;
if (property == null) property = new DotvvmProperty();
property.PropertyInfo = propertyInfo;
property.DataContextChangeAttributes = (propertyInfo != null ?
propertyInfo.GetCustomAttributes<DataContextChangeAttribute>(true) :
attributeProvider.GetCustomAttributes<DataContextChangeAttribute>()).ToArray();
property.DataContextManipulationAttribute = propertyInfo != null ?
propertyInfo.GetCustomAttribute<DataContextStackManipulationAttribute>(true) :
attributeProvider.GetCustomAttribute<DataContextStackManipulationAttribute>();
if (property.DataContextManipulationAttribute != null && property.DataContextChangeAttributes.Any()) throw new ArgumentException($"{nameof(DataContextChangeAttributes)} and {nameof(DataContextManipulationAttribute)} can not be set both at property '{property.FullName}'.");
property.MarkupOptions = markupOptions;
property.IsBindingProperty = typeof(IBinding).IsAssignableFrom(property.PropertyType);
}
public static IEnumerable<DotvvmProperty> GetVirtualProperties(Type controlType)
=> from p in controlType.GetProperties(BindingFlags.Public | BindingFlags.Instance)
where !registeredProperties.ContainsKey(p.DeclaringType!.FullName + "." + p.Name)
let markupOptions = GetVirtualPropertyMarkupOptions(p)
where markupOptions != null
where markupOptions.MappingMode != MappingMode.Exclude
select new DotvvmProperty {
DeclaringType = controlType,
IsValueInherited = false,
MarkupOptions = markupOptions,
Name = p.Name,
PropertyInfo = p,
PropertyType = p.PropertyType,
IsVirtual = true
};
private static MarkupOptionsAttribute? GetVirtualPropertyMarkupOptions(PropertyInfo p)
{
var mo = p.GetCustomAttribute<MarkupOptionsAttribute>();
if (mo == null) return null;
mo.AllowBinding = false;
return mo;
}
private static ConcurrentDictionary<string, DotvvmProperty> registeredProperties = new ConcurrentDictionary<string, DotvvmProperty>();
/// <summary>
/// Resolves the <see cref="DotvvmProperty"/> by the declaring type and name.
/// </summary>
public static DotvvmProperty? ResolveProperty(Type type, string name)
{
var fullName = type.FullName + "." + name;
DotvvmProperty? property;
while (!registeredProperties.TryGetValue(fullName, out property) && type.BaseType != null)
{
type = type.BaseType;
fullName = type.FullName + "." + name;
}
return property;
}
/// <summary>
/// Resolves the <see cref="DotvvmProperty"/> from the full name (DeclaringTypeName.PropertyName).
/// </summary>
public static DotvvmProperty? ResolveProperty(string fullName, bool caseSensitive = true)
{
return registeredProperties.Values.LastOrDefault(p =>
p.FullName.Equals(fullName, caseSensitive ? StringComparison.Ordinal : StringComparison.OrdinalIgnoreCase));
}
/// <summary>
/// Resolves all properties of specified type.
/// </summary>
public static DotvvmProperty[] ResolveProperties(Type type)
{
var types = new HashSet<Type>();
while (type.BaseType != null)
{
types.Add(type);
type = type.BaseType;
}
return registeredProperties.Values.Where(p => types.Contains(p.DeclaringType)).ToArray();
}
public override string ToString()
{
return $"{this.FullName}";
}
}
}
| 41.906149 | 285 | 0.628466 | [
"Apache-2.0"
] | AMBULATUR/dotvvm | src/DotVVM.Framework/Binding/DotvvmProperty.cs | 12,949 | C# |
using AutoHistory;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Sample.Data;
using Sample.Models;
using System.Diagnostics;
namespace Sample.Controllers
{
public class HomeController : Controller
{
private readonly ILogger<HomeController> _logger;
private readonly MyContext _db;
public HomeController(ILogger<HomeController> logger, MyContext db)
{
_logger = logger;
_db = db;
}
public IActionResult Index(int Id)
{
Student st = new Student()
{
Name = "Ali",
Id = Id
};
_db.Students.Add(st);
_db.SaveChangesWithHistory();
return Json(st.Hs_Change);
}
public IActionResult Privacy()
{
return View();
}
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
public IActionResult Error()
{
return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
}
}
}
| 25.422222 | 112 | 0.577797 | [
"MIT"
] | Alibesharat/AutoHistory | Sample/Controllers/HomeController.cs | 1,146 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using System.CodeDom.Compiler;
using Microsoft.CSharp;
using RTSEngine.Interfaces;
using RTSEngine.Controllers;
namespace RTSEngine.Data.Parsers {
public static class ScriptParser {
// Create The Compiler
private static readonly CSharpCodeProvider compiler = new CSharpCodeProvider();
public static Dictionary<string, ReflectedScript> Compile(string[] files, string[] references, out string error) {
// No Error Default
error = null;
// Compile
CompilerParameters compParams = new CompilerParameters(references, null, false);
compParams.CompilerOptions = "/optimize";
compParams.GenerateExecutable = false;
compParams.GenerateInMemory = true;
compParams.TreatWarningsAsErrors = false;
#if DEBUG
compParams.IncludeDebugInformation = true;
#endif
CompilerResults cr = compiler.CompileAssemblyFromFile(compParams, files);
// Check For Errors
if(cr.Errors.Count > 0) {
error = "";
foreach(var e in cr.Errors)
error += e + "\n";
return null;
}
// Dictionaries
var res = new Dictionary<string, ReflectedScript>();
// Loop Through All Visible Types
Assembly a = cr.CompiledAssembly;
Type[] types = a.GetExportedTypes();
foreach(Type t in types) {
ZXPProxy.Add(t);
ZXParser.AddDynamicType(t.FullName, t);
// We Don't Want Abstract Classes Or Interfaces
if(t.IsAbstract || t.IsInterface) continue;
// Check For The Superclass
if(t.IsSubclassOf(typeof(ACScript))) {
var rs = new ReflectedScript(t);
res.Add(rs.TypeName, rs);
}
}
return res;
}
}
} | 33.370968 | 122 | 0.57999 | [
"Apache-2.0"
] | RegrowthStudios/VoxelRTS | RTSGame/RTSEngine/Data/Parsers/ScriptParser.cs | 2,071 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using LanguageExt.Trans;
namespace LanguageExt
{
public static partial class Prelude
{
/// <summary>
/// Use with Try monad in LINQ expressions to auto-clean up disposable items
/// </summary>
public static Try<U> use<T, U>(Try<T> computation, Func<T, U> map) where T : class, IDisposable => () =>
{
var resT = computation.Try();
if (resT.IsFaulted)
{
return new TryResult<U>(resT.Exception);
}
else
{
try
{
var resU = map(resT.Value);
resT.Value?.Dispose();
return new TryResult<U>(resU);
}
catch(Exception e)
{
return new TryResult<U>(e);
}
finally
{
resT.Value?.Dispose();
}
}
};
/// <summary>
/// Use with Try monad in LINQ expressions to auto-clean up disposable items
/// </summary>
public static Try<U> use<T, U>(Try<T> computation, Func<T, Try<U>> bind) where T : class, IDisposable => () =>
{
var resT = computation.Try();
if (resT.IsFaulted)
{
return new TryResult<U>(resT.Exception);
}
else
{
try
{
var resU = bind(resT.Value);
resT.Value?.Dispose();
return resU.Try();
}
catch (Exception e)
{
return new TryResult<U>(e);
}
finally
{
resT.Value?.Dispose();
}
}
};
/// <summary>
/// Use with Task in LINQ expressions to auto-clean up disposable items
/// </summary>
public static async Task<U> use<T, U>(Task<T> computation, Func<T, U> map) where T : class, IDisposable
{
T t = null;
try
{
t = await computation;
return map(t);
}
finally
{
t?.Dispose();
}
}
/// <summary>
/// Use with Task in LINQ expressions to auto-clean up disposable items
/// </summary>
public static async Task<U> use<T, U>(Task<T> computation, Func<T, Task<U>> bind) where T : class, IDisposable
{
T t = null;
try
{
t = await computation;
return await bind(t);
}
finally
{
t?.Dispose();
}
}
/// <summary>
/// Functional implementation of the using(...) { } pattern
/// </summary>
/// <param name="generator">Disposable to use</param>
/// <param name="f">Inner map function that uses the disposable value</param>
/// <returns>Result of f(disposable)</returns>
public static R use<T, R>(Func<T> generator, Func<T, R> f)
where T : class, IDisposable
{
var value = generator();
try
{
return f(value);
}
finally
{
value.Dispose();
}
}
/// <summary>
/// Functional implementation of the using(...) { } pattern
/// </summary>
/// <param name="disposable">Disposable to use</param>
/// <param name="f">Inner map function that uses the disposable value</param>
/// <returns>Result of f(disposable)</returns>
public static R use<T, R>(T disposable, Func<T, R> f)
where T : IDisposable
{
try
{
return f(disposable);
}
finally
{
disposable.Dispose();
}
}
/// <summary>
/// Functional implementation of the using(...) { } pattern
/// </summary>
/// <param name="disposable">Disposable to use</param>
/// <param name="f">Inner map function that uses the disposable value</param>
/// <returns>Result of f(disposable)</returns>
public static Try<R> tryuse<T, R>(Func<T> disposable, Func<T, R> f)
where T : IDisposable =>
Try(disposable)
.Map(v =>
{
try
{
return f(v);
}
finally
{
v.Dispose();
}
});
/// <summary>
/// Functional implementation of the using(...) { } pattern
/// </summary>
/// <param name="disposable">Disposable to use</param>
/// <param name="f">Inner map function that uses the disposable value</param>
/// <returns>Result of f(disposable)</returns>
public static Try<R> tryuse<T, R>(T disposable, Func<T, R> f)
where T : IDisposable => () =>
{
try
{
return f(disposable);
}
finally
{
disposable.Dispose();
}
};
}
}
| 30.032432 | 118 | 0.428366 | [
"MIT"
] | jonny-novikov/language-ext | LanguageExt.Core/Prelude_Use.cs | 5,558 | 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 WebsitePanel.Portal.ProviderControls {
public partial class RDS_Settings {
/// <summary>
/// secCertificateSettings 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 secCertificateSettings;
/// <summary>
/// upPFX 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.FileUpload upPFX;
/// <summary>
/// txtPFXInstallPassword 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 txtPFXInstallPassword;
/// <summary>
/// currentCertificate 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 currentCertificate;
/// <summary>
/// plCertificateInfo 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.Panel plCertificateInfo;
/// <summary>
/// lblIssuedBy 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 lblIssuedBy;
/// <summary>
/// lblSanName 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 lblSanName;
/// <summary>
/// lblExpiryDate 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 lblExpiryDate;
/// <summary>
/// cbCollectionsImport 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 cbCollectionsImport;
/// <summary>
/// lblConnectionBroker 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 lblConnectionBroker;
/// <summary>
/// txtConnectionBroker 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 txtConnectionBroker;
/// <summary>
/// RequiredFieldValidator2 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.RequiredFieldValidator RequiredFieldValidator2;
/// <summary>
/// lblRootOU 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 lblRootOU;
/// <summary>
/// txtRootOU 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 txtRootOU;
/// <summary>
/// RequiredFieldValidator4 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.RequiredFieldValidator RequiredFieldValidator4;
/// <summary>
/// lblComputersRootOU 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 lblComputersRootOU;
/// <summary>
/// txtComputersRootOu 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 txtComputersRootOu;
/// <summary>
/// RequiredFieldValidator1 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.RequiredFieldValidator RequiredFieldValidator1;
/// <summary>
/// lblPrimaryDomainController 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 lblPrimaryDomainController;
/// <summary>
/// txtPrimaryDomainController 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 txtPrimaryDomainController;
/// <summary>
/// RequiredFieldValidator5 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.RequiredFieldValidator RequiredFieldValidator5;
/// <summary>
/// lblUseCentralNPS 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 lblUseCentralNPS;
/// <summary>
/// chkUseCentralNPS 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 chkUseCentralNPS;
/// <summary>
/// lblCentralNPS 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 lblCentralNPS;
/// <summary>
/// txtCentralNPS 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 txtCentralNPS;
/// <summary>
/// locGWServers 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.Localize locGWServers;
/// <summary>
/// txtAddGWServer 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 txtAddGWServer;
/// <summary>
/// btnAddGWServer 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.Button btnAddGWServer;
/// <summary>
/// gvGWServers 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.GridView gvGWServers;
}
}
| 37.920578 | 100 | 0.548363 | [
"BSD-3-Clause"
] | 9192939495969798/Websitepanel | WebsitePanel/Sources/WebsitePanel.WebPortal/DesktopModules/WebsitePanel/ProviderControls/RDS_Settings.ascx.designer.cs | 10,504 | 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("Dedicated Server MQ Client")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("")]
[assembly: AssemblyCopyright("")]
[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("ba1d89e0-9444-41d4-a68e-b818cf502500")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 37.351351 | 84 | 0.743126 | [
"MIT"
] | mmmaxwwwell/space-engineers-dedicated-cluster | DedicatedServerMessageQueuePlugin/DedicatedServerMessageQueuePlugin/Properties/AssemblyInfo.cs | 1,384 | C# |
using Lumia.Application.Interfaces;
using Lumia.Domain.Clientes;
using Lumia.Persistence.Context;
using System;
using System.Collections.Generic;
using System.Text;
namespace Lumia.Persistence.Repositories
{
public class ClienteRepository : Repository<Cliente>, IClienteRepository
{
public ClienteRepository(LumiaDbContext context) : base(context)
{
}
public LumiaDbContext LumiaDbContext
{
get { return Context as LumiaDbContext; }
}
}
}
| 22.391304 | 76 | 0.697087 | [
"MIT"
] | JeannAndrade/Lumia | LumiaSln/src/Lumia.Persistence/Repositories/ClienteRepository.cs | 517 | C# |
namespace DTML.EduBot.UserData
{
using System;
[Serializable]
public class UserData
{
private Gamification.GamerProfile _gamerProfile;
public string UserId { get; set; }
public string NativeLanguageIsoCode { get; set; }
public Gamification.GamerProfile GamerProfile
{
get
{
if (_gamerProfile == null)
{
_gamerProfile = new Gamification.GamerProfile();
}
return _gamerProfile;
}
set
{
_gamerProfile = value;
}
}
}
} | 21.290323 | 68 | 0.484848 | [
"MIT"
] | eklavyamirani/DTML.EduBot | DTML.EduBot/UserData/UserData.cs | 662 | C# |
/*******************************************************************************
* Copyright 2012-2019 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.
* *****************************************************************************
*
* AWS Tools for Windows (TM) PowerShell (TM)
*
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Management.Automation;
using System.Text;
using Amazon.PowerShell.Common;
using Amazon.Runtime;
using Amazon.IoT;
using Amazon.IoT.Model;
namespace Amazon.PowerShell.Cmdlets.IOT
{
/// <summary>
/// List the device certificates signed by the specified CA certificate.<br/><br/>This cmdlet automatically pages all available results to the pipeline - parameters related to iteration are only needed if you want to manually control the paginated output. To disable autopagination, use -NoAutoIteration.
/// </summary>
[Cmdlet("Get", "IOTCertificateListByCA")]
[OutputType("Amazon.IoT.Model.Certificate")]
[AWSCmdlet("Calls the AWS IoT ListCertificatesByCA API operation.", Operation = new[] {"ListCertificatesByCA"}, SelectReturnType = typeof(Amazon.IoT.Model.ListCertificatesByCAResponse))]
[AWSCmdletOutput("Amazon.IoT.Model.Certificate or Amazon.IoT.Model.ListCertificatesByCAResponse",
"This cmdlet returns a collection of Amazon.IoT.Model.Certificate objects.",
"The service call response (type Amazon.IoT.Model.ListCertificatesByCAResponse) can also be referenced from properties attached to the cmdlet entry in the $AWSHistory stack."
)]
public partial class GetIOTCertificateListByCACmdlet : AmazonIoTClientCmdlet, IExecutor
{
#region Parameter AscendingOrder
/// <summary>
/// <para>
/// <para>Specifies the order for results. If True, the results are returned in ascending order,
/// based on the creation date.</para>
/// </para>
/// </summary>
[System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)]
public System.Boolean? AscendingOrder { get; set; }
#endregion
#region Parameter CaCertificateId
/// <summary>
/// <para>
/// <para>The ID of the CA certificate. This operation will list all registered device certificate
/// that were signed by this CA certificate.</para>
/// </para>
/// </summary>
#if !MODULAR
[System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)]
#else
[System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true, Mandatory = true)]
[System.Management.Automation.AllowEmptyString]
[System.Management.Automation.AllowNull]
#endif
[Amazon.PowerShell.Common.AWSRequiredParameter]
public System.String CaCertificateId { get; set; }
#endregion
#region Parameter Marker
/// <summary>
/// <para>
/// <para>The marker for the next set of results.</para>
/// </para>
/// <para>
/// <br/><b>Note:</b> This parameter is only used if you are manually controlling output pagination of the service API call.
/// <br/>In order to manually control output pagination, use '-Marker $null' for the first call and '-Marker $AWSHistory.LastServiceResponse.NextMarker' for subsequent calls.
/// </para>
/// </summary>
[System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)]
[Alias("NextToken")]
public System.String Marker { get; set; }
#endregion
#region Parameter PageSize
/// <summary>
/// <para>
/// <para>The result page size.</para>
/// </para>
/// <para>
/// <br/><b>Note:</b> In AWSPowerShell and AWSPowerShell.NetCore this parameter is used to limit the total number of items returned by the cmdlet.
/// <br/>In AWS.Tools this parameter is simply passed to the service to specify how many items should be returned by each service call.
/// <br/>Pipe the output of this cmdlet into Select-Object -First to terminate retrieving data pages early and control the number of items returned.
/// </para>
/// </summary>
[System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)]
[Alias("MaxItems")]
public int? PageSize { get; set; }
#endregion
#region Parameter Select
/// <summary>
/// Use the -Select parameter to control the cmdlet output. The default value is 'Certificates'.
/// Specifying -Select '*' will result in the cmdlet returning the whole service response (Amazon.IoT.Model.ListCertificatesByCAResponse).
/// Specifying the name of a property of type Amazon.IoT.Model.ListCertificatesByCAResponse will result in that property being returned.
/// Specifying -Select '^ParameterName' will result in the cmdlet returning the selected cmdlet parameter value.
/// </summary>
[System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)]
public string Select { get; set; } = "Certificates";
#endregion
#region Parameter NoAutoIteration
/// <summary>
/// By default the cmdlet will auto-iterate and retrieve all results to the pipeline by performing multiple
/// service calls. If set, the cmdlet will retrieve only the next 'page' of results using the value of Marker
/// as the start point.
/// </summary>
[System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)]
public SwitchParameter NoAutoIteration { get; set; }
#endregion
protected override void ProcessRecord()
{
base.ProcessRecord();
var context = new CmdletContext();
// allow for manipulation of parameters prior to loading into context
PreExecutionContextLoad(context);
if (ParameterWasBound(nameof(this.Select)))
{
context.Select = CreateSelectDelegate<Amazon.IoT.Model.ListCertificatesByCAResponse, GetIOTCertificateListByCACmdlet>(Select) ??
throw new System.ArgumentException("Invalid value for -Select parameter.", nameof(this.Select));
}
context.AscendingOrder = this.AscendingOrder;
context.CaCertificateId = this.CaCertificateId;
#if MODULAR
if (this.CaCertificateId == null && ParameterWasBound(nameof(this.CaCertificateId)))
{
WriteWarning("You are passing $null as a value for parameter CaCertificateId which is marked as required. In case you believe this parameter was incorrectly marked as required, report this by opening an issue at https://github.com/aws/aws-tools-for-powershell/issues.");
}
#endif
context.Marker = this.Marker;
context.PageSize = this.PageSize;
#if !MODULAR
if (ParameterWasBound(nameof(this.PageSize)) && this.PageSize.HasValue)
{
WriteWarning("AWSPowerShell and AWSPowerShell.NetCore use the PageSize parameter to limit the total number of items returned by the cmdlet." +
" This behavior is obsolete and will be removed in a future version of these modules. Pipe the output of this cmdlet into Select-Object -First to terminate" +
" retrieving data pages early and control the number of items returned. AWS.Tools already implements the new behavior of simply passing PageSize" +
" to the service to specify how many items should be returned by each service call.");
}
#endif
// allow further manipulation of loaded context prior to processing
PostExecutionContextLoad(context);
var output = Execute(context) as CmdletOutput;
ProcessOutput(output);
}
#region IExecutor Members
#if MODULAR
public object Execute(ExecutorContext context)
{
var cmdletContext = context as CmdletContext;
var useParameterSelect = this.Select.StartsWith("^");
// create request and set iteration invariants
var request = new Amazon.IoT.Model.ListCertificatesByCARequest();
if (cmdletContext.AscendingOrder != null)
{
request.AscendingOrder = cmdletContext.AscendingOrder.Value;
}
if (cmdletContext.CaCertificateId != null)
{
request.CaCertificateId = cmdletContext.CaCertificateId;
}
if (cmdletContext.PageSize != null)
{
request.PageSize = AutoIterationHelpers.ConvertEmitLimitToServiceTypeInt32(cmdletContext.PageSize.Value);
}
// Initialize loop variant and commence piping
var _nextToken = cmdletContext.Marker;
var _userControllingPaging = this.NoAutoIteration.IsPresent || ParameterWasBound(nameof(this.Marker));
var client = Client ?? CreateClient(_CurrentCredentials, _RegionEndpoint);
do
{
request.Marker = _nextToken;
CmdletOutput output;
try
{
var response = CallAWSServiceOperation(client, request);
object pipelineOutput = null;
if (!useParameterSelect)
{
pipelineOutput = cmdletContext.Select(response, this);
}
output = new CmdletOutput
{
PipelineOutput = pipelineOutput,
ServiceResponse = response
};
_nextToken = response.NextMarker;
}
catch (Exception e)
{
output = new CmdletOutput { ErrorResponse = e };
}
ProcessOutput(output);
} while (!_userControllingPaging && AutoIterationHelpers.HasValue(_nextToken));
if (useParameterSelect)
{
WriteObject(cmdletContext.Select(null, this));
}
return null;
}
#else
public object Execute(ExecutorContext context)
{
var cmdletContext = context as CmdletContext;
var useParameterSelect = this.Select.StartsWith("^");
// create request and set iteration invariants
var request = new Amazon.IoT.Model.ListCertificatesByCARequest();
if (cmdletContext.AscendingOrder != null)
{
request.AscendingOrder = cmdletContext.AscendingOrder.Value;
}
if (cmdletContext.CaCertificateId != null)
{
request.CaCertificateId = cmdletContext.CaCertificateId;
}
// Initialize loop variants and commence piping
System.String _nextToken = null;
int? _emitLimit = null;
int _retrievedSoFar = 0;
if (AutoIterationHelpers.HasValue(cmdletContext.Marker))
{
_nextToken = cmdletContext.Marker;
}
if (AutoIterationHelpers.HasValue(cmdletContext.PageSize))
{
// The service has a maximum page size of 250. If the user has
// asked for more items than page max, and there is no page size
// configured, we rely on the service ignoring the set maximum
// and giving us 250 items back. If a page size is set, that will
// be used to configure the pagination.
// We'll make further calls to satisfy the user's request.
_emitLimit = cmdletContext.PageSize;
}
var _userControllingPaging = this.NoAutoIteration.IsPresent || ParameterWasBound(nameof(this.Marker));
var client = Client ?? CreateClient(_CurrentCredentials, _RegionEndpoint);
do
{
request.Marker = _nextToken;
if (_emitLimit.HasValue)
{
int correctPageSize = AutoIterationHelpers.Min(250, _emitLimit.Value);
request.PageSize = AutoIterationHelpers.ConvertEmitLimitToInt32(correctPageSize);
}
CmdletOutput output;
try
{
var response = CallAWSServiceOperation(client, request);
object pipelineOutput = null;
if (!useParameterSelect)
{
pipelineOutput = cmdletContext.Select(response, this);
}
output = new CmdletOutput
{
PipelineOutput = pipelineOutput,
ServiceResponse = response
};
int _receivedThisCall = response.Certificates.Count;
_nextToken = response.NextMarker;
_retrievedSoFar += _receivedThisCall;
if (_emitLimit.HasValue)
{
_emitLimit -= _receivedThisCall;
}
}
catch (Exception e)
{
if (_retrievedSoFar == 0 || !_emitLimit.HasValue)
{
output = new CmdletOutput { ErrorResponse = e };
}
else
{
break;
}
}
ProcessOutput(output);
} while (!_userControllingPaging && AutoIterationHelpers.HasValue(_nextToken) && (!_emitLimit.HasValue || _emitLimit.Value >= 1));
if (useParameterSelect)
{
WriteObject(cmdletContext.Select(null, this));
}
return null;
}
#endif
public ExecutorContext CreateContext()
{
return new CmdletContext();
}
#endregion
#region AWS Service Operation Call
private Amazon.IoT.Model.ListCertificatesByCAResponse CallAWSServiceOperation(IAmazonIoT client, Amazon.IoT.Model.ListCertificatesByCARequest request)
{
Utils.Common.WriteVerboseEndpointMessage(this, client.Config, "AWS IoT", "ListCertificatesByCA");
try
{
#if DESKTOP
return client.ListCertificatesByCA(request);
#elif CORECLR
return client.ListCertificatesByCAAsync(request).GetAwaiter().GetResult();
#else
#error "Unknown build edition"
#endif
}
catch (AmazonServiceException exc)
{
var webException = exc.InnerException as System.Net.WebException;
if (webException != null)
{
throw new Exception(Utils.Common.FormatNameResolutionFailureMessage(client.Config, webException.Message), webException);
}
throw;
}
}
#endregion
internal partial class CmdletContext : ExecutorContext
{
public System.Boolean? AscendingOrder { get; set; }
public System.String CaCertificateId { get; set; }
public System.String Marker { get; set; }
public int? PageSize { get; set; }
public System.Func<Amazon.IoT.Model.ListCertificatesByCAResponse, GetIOTCertificateListByCACmdlet, object> Select { get; set; } =
(response, cmdlet) => response.Certificates;
}
}
}
| 44.744737 | 308 | 0.574193 | [
"Apache-2.0"
] | 5u5hma/aws-tools-for-powershell | modules/AWSPowerShell/Cmdlets/IoT/Basic/Get-IOTCertificateListByCA-Cmdlet.cs | 17,003 | C# |
//-----------------------------------------------------------------------------
// Copyright (c) 2012 GarageGames, LLC
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//-----------------------------------------------------------------------------
// An implementation of "Practical Morphological Anti-Aliasing" from
// GPU Pro 2 by Jorge Jimenez, Belen Masia, Jose I. Echevarria,
// Fernando Navarro, and Diego Gutierrez.
//
// http://www.iryoku.com/mlaa/
// NOTE: This is currently disabled in favor of FXAA. See
// core\scripts\client\canvas.cs if you want to re-enable it.
singleton GFXStateBlockData( MLAA_EdgeDetectStateBlock : PFX_DefaultStateBlock )
{
// Mark the edge pixels in stencil.
stencilDefined = true;
stencilEnable = true;
stencilPassOp = GFXStencilOpReplace;
stencilFunc = GFXCmpAlways;
stencilRef = 1;
samplersDefined = true;
samplerStates[0] = SamplerClampLinear;
};
singleton ShaderData( MLAA_EdgeDetectionShader )
{
DXVertexShaderFile = $Core::CommonShaderPath @ "/postFX/mlaa/offsetV.hlsl";
DXPixelShaderFile = $Core::CommonShaderPath @ "/postFX/mlaa/edgeDetectionP.hlsl";
OGLVertexShaderFile = $Core::CommonShaderPath @ "/postFX/mlaa/gl/offsetV.glsl";
OGLPixelShaderFile = $Core::CommonShaderPath @ "/postFX/mlaa/gl/edgeDetectionP.glsl";
samplerNames[0] = "$colorMapG";
samplerNames[1] = "$deferredMap";
pixVersion = 3.0;
};
singleton GFXStateBlockData( MLAA_BlendWeightCalculationStateBlock : PFX_DefaultStateBlock )
{
// Here we want to process only marked pixels.
stencilDefined = true;
stencilEnable = true;
stencilPassOp = GFXStencilOpKeep;
stencilFunc = GFXCmpEqual;
stencilRef = 1;
samplersDefined = true;
samplerStates[0] = SamplerClampPoint;
samplerStates[1] = SamplerClampLinear;
samplerStates[2] = SamplerClampPoint;
};
singleton ShaderData( MLAA_BlendWeightCalculationShader )
{
DXVertexShaderFile = $Core::CommonShaderPath @ "/postFX/mlaa/passthruV.hlsl";
DXPixelShaderFile = $Core::CommonShaderPath @ "/postFX/mlaa/blendWeightCalculationP.hlsl";
OGLVertexShaderFile = $Core::CommonShaderPath @ "/postFX/mlaa/gl/passthruV.glsl";
OGLPixelShaderFile = $Core::CommonShaderPath @ "/postFX/mlaa/gl/blendWeightCalculationP.glsl";
samplerNames[0] = "$edgesMap";
samplerNames[1] = "$edgesMapL";
samplerNames[2] = "$areaMap";
pixVersion = 3.0;
};
singleton GFXStateBlockData( MLAA_NeighborhoodBlendingStateBlock : PFX_DefaultStateBlock )
{
// Here we want to process only marked pixels too.
stencilDefined = true;
stencilEnable = true;
stencilPassOp = GFXStencilOpKeep;
stencilFunc = GFXCmpEqual;
stencilRef = 1;
samplersDefined = true;
samplerStates[0] = SamplerClampPoint;
samplerStates[1] = SamplerClampLinear;
samplerStates[2] = SamplerClampPoint;
};
singleton ShaderData( MLAA_NeighborhoodBlendingShader )
{
DXVertexShaderFile = $Core::CommonShaderPath @ "/postFX/mlaa/offsetV.hlsl";
DXPixelShaderFile = $Core::CommonShaderPath @ "/postFX/mlaa/neighborhoodBlendingP.hlsl";
OGLVertexShaderFile = $Core::CommonShaderPath @ "/postFX/mlaa/gl/offsetV.glsl";
OGLPixelShaderFile = $Core::CommonShaderPath @ "/postFX/mlaa/gl/neighborhoodBlendingP.glsl";
samplerNames[0] = "$blendMap";
samplerNames[1] = "$colorMapL";
samplerNames[2] = "$colorMap";
pixVersion = 3.0;
};
singleton PostEffect( MLAAFx )
{
isEnabled = false;
allowReflectPass = false;
renderTime = "PFXAfterDiffuse";
texture[0] = "$backBuffer"; //colorMapG
texture[1] = "#deferred"; // Used for depth detection
target = "$outTex";
targetClear = PFXTargetClear_OnDraw;
targetClearColor = "0 0 0 0";
stateBlock = MLAA_EdgeDetectStateBlock;
shader = MLAA_EdgeDetectionShader;
// The luma calculation weights which can be user adjustable
// per-scene if nessasary. The default value of...
//
// 0.2126 0.7152 0.0722
//
// ... is the HDTV ITU-R Recommendation BT. 709.
lumaCoefficients = "0.2126 0.7152 0.0722";
// The tweakable color threshold used to select
// the range of edge pixels to blend.
threshold = 0.1;
// The depth delta threshold used to select
// the range of edge pixels to blend.
depthThreshold = 0.01;
new PostEffect()
{
internalName = "blendingWeightsCalculation";
target = "$outTex";
targetClear = PFXTargetClear_OnDraw;
shader = MLAA_BlendWeightCalculationShader;
stateBlock = MLAA_BlendWeightCalculationStateBlock;
texture[0] = "$inTex"; // Edges mask
texture[1] = "$inTex"; // Edges mask
texture[2] = "core/postFX/images/AreaMap33.dds";
};
new PostEffect()
{
internalName = "neighborhoodBlending";
shader = MLAA_NeighborhoodBlendingShader;
stateBlock = MLAA_NeighborhoodBlendingStateBlock;
texture[0] = "$inTex"; // Blend weights
texture[1] = "$backBuffer";
texture[2] = "$backBuffer";
};
};
function MLAAFx::setShaderConsts(%this)
{
%this.setShaderConst("$lumaCoefficients", %this.lumaCoefficients);
%this.setShaderConst("$threshold", %this.threshold);
%this.setShaderConst("$depthThreshold", %this.depthThreshold);
} | 34.865591 | 100 | 0.675251 | [
"MIT"
] | Alan-love/Torque3D | Templates/BaseGame/game/core/postFX/scripts/MLAA.cs | 6,300 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using Foundation;
using UIKit;
namespace SingleWordKeyboard
{
public class Application
{
// This is the main entry point of the application.
static void Main (string[] args)
{
// if you want to use a different Application Delegate class from "AppDelegate"
// you can specify it here.
UIApplication.Main (args, null, "AppDelegate");
}
}
}
| 20.380952 | 82 | 0.724299 | [
"MIT"
] | Art-Lav/ios-samples | ios8/SingleWordKeyboard/SingleWordKeyboard/Main.cs | 430 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Globalization;
namespace System
{
public static class DateTimeExtensions
{
public static double CalculateUtcOffset(this DateTime dateTime)
{
return dateTime.Subtract(DateTime.UtcNow).TotalHours;
}
public static int CalculateAge(this DateTime dateOfBirth)
{
return CalculateAge(dateOfBirth, DateTime.Today);
}
public static int CalculateAge(this DateTime dateOfBirth, DateTime referenceDate)
{
var years = referenceDate.Year - dateOfBirth.Year;
if (referenceDate.Month < dateOfBirth.Month || (referenceDate.Month == dateOfBirth.Month && referenceDate.Day < dateOfBirth.Day))
{
--years;
}
return years;
}
public static int GetNumberOfDaysInMonth(this DateTime date)
{
var nextMonth = date.AddMonths(1);
return new DateTime(nextMonth.Year, nextMonth.Month, 1).AddDays(-1).Day;
}
public static DateTime GetFirstDayOfMonth(this DateTime date)
{
return new DateTime(date.Year, date.Month, 1);
}
public static DateTime GetFirstDayOfMonth(this DateTime date, DayOfWeek dayOfWeek)
{
var dt = date.GetFirstDayOfMonth();
while (dt.DayOfWeek != dayOfWeek)
{
dt = dt.AddDays(1);
}
return dt;
}
public static DateTime GetLastDayOfMonth(this DateTime date)
{
return new DateTime(date.Year, date.Month, GetNumberOfDaysInMonth(date));
}
public static DateTime GetLastDayOfMonth(this DateTime date, DayOfWeek dayOfWeek)
{
var dt = date.GetLastDayOfMonth();
while (dt.DayOfWeek != dayOfWeek)
{
dt = dt.AddDays(-1);
}
return dt;
}
public static bool IsToday(this DateTime dt)
{
return dt.Date == DateTime.Today;
}
public static DateTimeOffset ToDateTimeOffset(this DateTime localDateTime)
{
return localDateTime.ToDateTimeOffset(null);
}
public static DateTimeOffset ToDateTimeOffset(this DateTime localDateTime, TimeZoneInfo localTimeZone)
{
localTimeZone = (localTimeZone ?? TimeZoneInfo.Local);
if (localDateTime.Kind != DateTimeKind.Unspecified)
{
localDateTime = new DateTime(localDateTime.Ticks, DateTimeKind.Unspecified);
}
return TimeZoneInfo.ConvertTime(localDateTime, TimeZoneInfo.Utc);
}
public static DateTime GetFirstDayOfWeek(this DateTime date)
{
return date.GetFirstDayOfWeek(null);
}
public static DateTime GetFirstDayOfWeek(this DateTime date, CultureInfo cultureInfo)
{
cultureInfo = (cultureInfo ?? CultureInfo.CurrentCulture);
var firstDayOfWeek = cultureInfo.DateTimeFormat.FirstDayOfWeek;
while (date.DayOfWeek != firstDayOfWeek)
{
date = date.AddDays(-1);
}
return date;
}
public static DateTime GetLastDayOfWeek(this DateTime date)
{
return date.GetLastDayOfWeek(null);
}
public static DateTime GetLastDayOfWeek(this DateTime date, CultureInfo cultureInfo)
{
return date.GetFirstDayOfWeek(cultureInfo).AddDays(6);
}
public static DateTime GetFirstWeekday(this DateTime date, DayOfWeek weekday)
{
return date.GetFirstWeekday(weekday, null);
}
public static DateTime GetFirstWeekday(this DateTime date, DayOfWeek weekday, CultureInfo cultureInfo)
{
var firstDayOfWeek = date.GetFirstDayOfWeek(cultureInfo);
return firstDayOfWeek.GetNextWeekday(weekday);
}
public static DateTime GetNextWeekday(this DateTime date, DayOfWeek weekday)
{
while (date.DayOfWeek != weekday)
{
date = date.AddDays(1);
}
return date;
}
public static DateTime GetPreviousWeekday(this DateTime date, DayOfWeek weekday)
{
while (date.DayOfWeek != weekday)
{
date = date.AddDays(-1);
}
return date;
}
public static bool IsWeekend(this DateTime date)
{
return date.DayOfWeek.EqualsAny(DayOfWeek.Saturday, DayOfWeek.Sunday);
}
public static DateTime AddWeeks(this DateTime date, int value)
{
return date.AddDays(value * 7);
}
public static int GetDaysInYear(this DateTime date)
{
var first = new DateTime(date.Year, 1, 1);
var last = new DateTime(date.Year + 1, 1, 1);
return CalculateDaysBetween(first, last);
}
private static int CalculateDaysBetween(this DateTime fromDate, DateTime toDate)
{
return Convert.ToInt32(toDate.Subtract(fromDate).TotalDays);
}
public static int GetWeekOfYear(this DateTime dateTime)
{
var culture = CultureInfo.CurrentUICulture;
var calendar = culture.Calendar;
var dateTimeFormat = culture.DateTimeFormat;
return calendar.GetWeekOfYear(dateTime, dateTimeFormat.CalendarWeekRule, dateTimeFormat.FirstDayOfWeek);
}
}
}
| 33.431034 | 142 | 0.579852 | [
"MIT"
] | ryanhorath/Rybird.Framework | Core/Framework/Extensions/DateTimeExtensions.cs | 5,819 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using FluentAssertions;
using JsonApiDotNetCore;
using JsonApiDotNetCore.Configuration;
using JsonApiDotNetCore.Serialization.Objects;
using JsonApiDotNetCoreExampleTests.Startups;
using Microsoft.EntityFrameworkCore;
using TestBuildingBlocks;
using Xunit;
namespace JsonApiDotNetCoreExampleTests.IntegrationTests.ReadWrite.Updating.Resources
{
public sealed class ReplaceToManyRelationshipTests : IClassFixture<ExampleIntegrationTestContext<TestableStartup<ReadWriteDbContext>, ReadWriteDbContext>>
{
private readonly ExampleIntegrationTestContext<TestableStartup<ReadWriteDbContext>, ReadWriteDbContext> _testContext;
private readonly ReadWriteFakers _fakers = new();
public ReplaceToManyRelationshipTests(ExampleIntegrationTestContext<TestableStartup<ReadWriteDbContext>, ReadWriteDbContext> testContext)
{
_testContext = testContext;
testContext.UseController<WorkItemsController>();
testContext.ConfigureServicesAfterStartup(services =>
{
services.AddResourceDefinition<ImplicitlyChangingWorkItemDefinition>();
});
}
[Fact]
public async Task Can_clear_OneToMany_relationship()
{
// Arrange
WorkItem existingWorkItem = _fakers.WorkItem.Generate();
existingWorkItem.Subscribers = _fakers.UserAccount.Generate(2).ToHashSet();
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
dbContext.WorkItems.Add(existingWorkItem);
await dbContext.SaveChangesAsync();
});
var requestBody = new
{
data = new
{
type = "workItems",
id = existingWorkItem.StringId,
relationships = new
{
subscribers = new
{
data = Array.Empty<object>()
}
}
}
};
string route = "/workItems/" + existingWorkItem.StringId;
// Act
(HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePatchAsync<Document>(route, requestBody);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.OK);
responseDocument.SingleData.Should().NotBeNull();
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
WorkItem workItemInDatabase = await dbContext.WorkItems.Include(workItem => workItem.Subscribers).FirstWithIdAsync(existingWorkItem.Id);
workItemInDatabase.Subscribers.Should().BeEmpty();
});
}
[Fact]
public async Task Can_clear_ManyToMany_relationship()
{
// Arrange
WorkItem existingWorkItem = _fakers.WorkItem.Generate();
existingWorkItem.Tags = _fakers.WorkTag.Generate(1).ToHashSet();
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
dbContext.WorkItems.Add(existingWorkItem);
await dbContext.SaveChangesAsync();
});
var requestBody = new
{
data = new
{
type = "workItems",
id = existingWorkItem.StringId,
relationships = new
{
tags = new
{
data = Array.Empty<object>()
}
}
}
};
string route = "/workItems/" + existingWorkItem.StringId;
// Act
(HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePatchAsync<Document>(route, requestBody);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.OK);
responseDocument.SingleData.Should().NotBeNull();
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
WorkItem workItemInDatabase = await dbContext.WorkItems.Include(workItem => workItem.Tags).FirstWithIdAsync(existingWorkItem.Id);
workItemInDatabase.Tags.Should().BeEmpty();
});
}
[Fact]
public async Task Can_replace_OneToMany_relationship_with_already_assigned_resources()
{
// Arrange
WorkItem existingWorkItem = _fakers.WorkItem.Generate();
existingWorkItem.Subscribers = _fakers.UserAccount.Generate(2).ToHashSet();
UserAccount existingSubscriber = _fakers.UserAccount.Generate();
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
dbContext.AddInRange(existingWorkItem, existingSubscriber);
await dbContext.SaveChangesAsync();
});
var requestBody = new
{
data = new
{
type = "workItems",
id = existingWorkItem.StringId,
relationships = new
{
subscribers = new
{
data = new[]
{
new
{
type = "userAccounts",
id = existingWorkItem.Subscribers.ElementAt(1).StringId
},
new
{
type = "userAccounts",
id = existingSubscriber.StringId
}
}
}
}
}
};
string route = "/workItems/" + existingWorkItem.StringId;
// Act
(HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePatchAsync<Document>(route, requestBody);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.OK);
responseDocument.SingleData.Should().NotBeNull();
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
WorkItem workItemInDatabase = await dbContext.WorkItems.Include(workItem => workItem.Subscribers).FirstWithIdAsync(existingWorkItem.Id);
workItemInDatabase.Subscribers.Should().HaveCount(2);
workItemInDatabase.Subscribers.Should().ContainSingle(userAccount => userAccount.Id == existingWorkItem.Subscribers.ElementAt(1).Id);
workItemInDatabase.Subscribers.Should().ContainSingle(userAccount => userAccount.Id == existingSubscriber.Id);
});
}
[Fact]
public async Task Can_replace_ManyToMany_relationship_with_already_assigned_resources()
{
// Arrange
WorkItem existingWorkItem = _fakers.WorkItem.Generate();
existingWorkItem.Tags = _fakers.WorkTag.Generate(2).ToHashSet();
List<WorkTag> existingTags = _fakers.WorkTag.Generate(2);
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
dbContext.WorkItems.Add(existingWorkItem);
dbContext.WorkTags.AddRange(existingTags);
await dbContext.SaveChangesAsync();
});
var requestBody = new
{
data = new
{
type = "workItems",
id = existingWorkItem.StringId,
relationships = new
{
tags = new
{
data = new[]
{
new
{
type = "workTags",
id = existingWorkItem.Tags.ElementAt(0).StringId
},
new
{
type = "workTags",
id = existingTags[0].StringId
},
new
{
type = "workTags",
id = existingTags[1].StringId
}
}
}
}
}
};
string route = "/workItems/" + existingWorkItem.StringId;
// Act
(HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePatchAsync<Document>(route, requestBody);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.OK);
responseDocument.SingleData.Should().NotBeNull();
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
WorkItem workItemInDatabase = await dbContext.WorkItems.Include(workItem => workItem.Tags).FirstWithIdAsync(existingWorkItem.Id);
workItemInDatabase.Tags.Should().HaveCount(3);
workItemInDatabase.Tags.Should().ContainSingle(workTag => workTag.Id == existingWorkItem.Tags.ElementAt(0).Id);
workItemInDatabase.Tags.Should().ContainSingle(workTag => workTag.Id == existingTags[0].Id);
workItemInDatabase.Tags.Should().ContainSingle(workTag => workTag.Id == existingTags[1].Id);
});
}
[Fact]
public async Task Can_replace_OneToMany_relationship_with_include()
{
// Arrange
WorkItem existingWorkItem = _fakers.WorkItem.Generate();
UserAccount existingUserAccount = _fakers.UserAccount.Generate();
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
dbContext.AddInRange(existingWorkItem, existingUserAccount);
await dbContext.SaveChangesAsync();
});
var requestBody = new
{
data = new
{
type = "workItems",
id = existingWorkItem.StringId,
relationships = new
{
subscribers = new
{
data = new[]
{
new
{
type = "userAccounts",
id = existingUserAccount.StringId
}
}
}
}
}
};
string route = $"/workItems/{existingWorkItem.StringId}?include=subscribers";
// Act
(HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePatchAsync<Document>(route, requestBody);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.OK);
responseDocument.SingleData.Should().NotBeNull();
responseDocument.SingleData.Type.Should().Be("workItems");
responseDocument.SingleData.Id.Should().Be(existingWorkItem.StringId);
responseDocument.SingleData.Attributes["priority"].Should().Be(existingWorkItem.Priority.ToString("G"));
responseDocument.SingleData.Relationships.Should().NotBeEmpty();
responseDocument.Included.Should().HaveCount(1);
responseDocument.Included[0].Type.Should().Be("userAccounts");
responseDocument.Included[0].Id.Should().Be(existingUserAccount.StringId);
responseDocument.Included[0].Attributes["firstName"].Should().Be(existingUserAccount.FirstName);
responseDocument.Included[0].Attributes["lastName"].Should().Be(existingUserAccount.LastName);
responseDocument.Included[0].Relationships.Should().NotBeEmpty();
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
WorkItem workItemInDatabase = await dbContext.WorkItems.Include(workItem => workItem.Subscribers).FirstWithIdAsync(existingWorkItem.Id);
workItemInDatabase.Subscribers.Should().HaveCount(1);
workItemInDatabase.Subscribers.Single().Id.Should().Be(existingUserAccount.Id);
});
}
[Fact]
public async Task Can_replace_ManyToMany_relationship_with_include_and_fieldsets()
{
// Arrange
WorkItem existingWorkItem = _fakers.WorkItem.Generate();
WorkTag existingTag = _fakers.WorkTag.Generate();
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
dbContext.AddInRange(existingWorkItem, existingTag);
await dbContext.SaveChangesAsync();
});
var requestBody = new
{
data = new
{
type = "workItems",
id = existingWorkItem.StringId,
relationships = new
{
tags = new
{
data = new[]
{
new
{
type = "workTags",
id = existingTag.StringId
}
}
}
}
}
};
string route = $"/workItems/{existingWorkItem.StringId}?fields[workItems]=priority,tags&include=tags&fields[workTags]=text";
// Act
(HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePatchAsync<Document>(route, requestBody);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.OK);
responseDocument.SingleData.Should().NotBeNull();
responseDocument.SingleData.Type.Should().Be("workItems");
responseDocument.SingleData.Id.Should().Be(existingWorkItem.StringId);
responseDocument.SingleData.Attributes.Should().HaveCount(1);
responseDocument.SingleData.Attributes["priority"].Should().Be(existingWorkItem.Priority.ToString("G"));
responseDocument.SingleData.Relationships.Should().HaveCount(1);
responseDocument.SingleData.Relationships["tags"].ManyData.Should().HaveCount(1);
responseDocument.SingleData.Relationships["tags"].ManyData[0].Id.Should().Be(existingTag.StringId);
responseDocument.Included.Should().HaveCount(1);
responseDocument.Included[0].Type.Should().Be("workTags");
responseDocument.Included[0].Id.Should().Be(existingTag.StringId);
responseDocument.Included[0].Attributes.Should().HaveCount(1);
responseDocument.Included[0].Attributes["text"].Should().Be(existingTag.Text);
responseDocument.Included[0].Relationships.Should().BeNull();
int newWorkItemId = int.Parse(responseDocument.SingleData.Id);
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
WorkItem workItemInDatabase = await dbContext.WorkItems.Include(workItem => workItem.Tags).FirstWithIdAsync(newWorkItemId);
workItemInDatabase.Tags.Should().HaveCount(1);
workItemInDatabase.Tags.Single().Id.Should().Be(existingTag.Id);
});
}
[Fact]
public async Task Cannot_replace_for_missing_relationship_type()
{
// Arrange
WorkItem existingWorkItem = _fakers.WorkItem.Generate();
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
dbContext.WorkItems.Add(existingWorkItem);
await dbContext.SaveChangesAsync();
});
var requestBody = new
{
data = new
{
type = "workItems",
id = existingWorkItem.StringId,
relationships = new
{
subscribers = new
{
data = new[]
{
new
{
id = 99999999
}
}
}
}
}
};
string route = "/workItems/" + existingWorkItem.StringId;
// Act
(HttpResponseMessage httpResponse, ErrorDocument responseDocument) = await _testContext.ExecutePatchAsync<ErrorDocument>(route, requestBody);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.UnprocessableEntity);
responseDocument.Errors.Should().HaveCount(1);
Error error = responseDocument.Errors[0];
error.StatusCode.Should().Be(HttpStatusCode.UnprocessableEntity);
error.Title.Should().Be("Failed to deserialize request body: Request body must include 'type' element.");
error.Detail.Should().StartWith("Expected 'type' element in 'subscribers' relationship. - Request body: <<");
}
[Fact]
public async Task Cannot_replace_for_unknown_relationship_type()
{
// Arrange
WorkItem existingWorkItem = _fakers.WorkItem.Generate();
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
dbContext.WorkItems.Add(existingWorkItem);
await dbContext.SaveChangesAsync();
});
var requestBody = new
{
data = new
{
type = "workItems",
id = existingWorkItem.StringId,
relationships = new
{
subscribers = new
{
data = new[]
{
new
{
type = "doesNotExist",
id = 99999999
}
}
}
}
}
};
string route = "/workItems/" + existingWorkItem.StringId;
// Act
(HttpResponseMessage httpResponse, ErrorDocument responseDocument) = await _testContext.ExecutePatchAsync<ErrorDocument>(route, requestBody);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.UnprocessableEntity);
responseDocument.Errors.Should().HaveCount(1);
Error error = responseDocument.Errors[0];
error.StatusCode.Should().Be(HttpStatusCode.UnprocessableEntity);
error.Title.Should().Be("Failed to deserialize request body: Request body includes unknown resource type.");
error.Detail.Should().StartWith("Resource type 'doesNotExist' does not exist. - Request body: <<");
}
[Fact]
public async Task Cannot_replace_for_missing_relationship_ID()
{
// Arrange
WorkItem existingWorkItem = _fakers.WorkItem.Generate();
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
dbContext.WorkItems.Add(existingWorkItem);
await dbContext.SaveChangesAsync();
});
var requestBody = new
{
data = new
{
type = "workItems",
id = existingWorkItem.StringId,
relationships = new
{
subscribers = new
{
data = new[]
{
new
{
type = "userAccounts"
}
}
}
}
}
};
string route = "/workItems/" + existingWorkItem.StringId;
// Act
(HttpResponseMessage httpResponse, ErrorDocument responseDocument) = await _testContext.ExecutePatchAsync<ErrorDocument>(route, requestBody);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.UnprocessableEntity);
responseDocument.Errors.Should().HaveCount(1);
Error error = responseDocument.Errors[0];
error.StatusCode.Should().Be(HttpStatusCode.UnprocessableEntity);
error.Title.Should().Be("Failed to deserialize request body: Request body must include 'id' element.");
error.Detail.Should().StartWith("Expected 'id' element in 'subscribers' relationship. - Request body: <<");
}
[Fact]
public async Task Cannot_replace_with_unknown_relationship_IDs()
{
// Arrange
WorkItem existingWorkItem = _fakers.WorkItem.Generate();
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
dbContext.WorkItems.Add(existingWorkItem);
await dbContext.SaveChangesAsync();
});
var requestBody = new
{
data = new
{
type = "workItems",
id = existingWorkItem.StringId,
relationships = new
{
subscribers = new
{
data = new[]
{
new
{
type = "userAccounts",
id = 88888888
},
new
{
type = "userAccounts",
id = 99999999
}
}
},
tags = new
{
data = new[]
{
new
{
type = "workTags",
id = 88888888
},
new
{
type = "workTags",
id = 99999999
}
}
}
}
}
};
string route = "/workItems/" + existingWorkItem.StringId;
// Act
(HttpResponseMessage httpResponse, ErrorDocument responseDocument) = await _testContext.ExecutePatchAsync<ErrorDocument>(route, requestBody);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.NotFound);
responseDocument.Errors.Should().HaveCount(4);
Error error1 = responseDocument.Errors[0];
error1.StatusCode.Should().Be(HttpStatusCode.NotFound);
error1.Title.Should().Be("A related resource does not exist.");
error1.Detail.Should().Be("Related resource of type 'userAccounts' with ID '88888888' in relationship 'subscribers' does not exist.");
Error error2 = responseDocument.Errors[1];
error2.StatusCode.Should().Be(HttpStatusCode.NotFound);
error2.Title.Should().Be("A related resource does not exist.");
error2.Detail.Should().Be("Related resource of type 'userAccounts' with ID '99999999' in relationship 'subscribers' does not exist.");
Error error3 = responseDocument.Errors[2];
error3.StatusCode.Should().Be(HttpStatusCode.NotFound);
error3.Title.Should().Be("A related resource does not exist.");
error3.Detail.Should().Be("Related resource of type 'workTags' with ID '88888888' in relationship 'tags' does not exist.");
Error error4 = responseDocument.Errors[3];
error4.StatusCode.Should().Be(HttpStatusCode.NotFound);
error4.Title.Should().Be("A related resource does not exist.");
error4.Detail.Should().Be("Related resource of type 'workTags' with ID '99999999' in relationship 'tags' does not exist.");
}
[Fact]
public async Task Cannot_replace_on_relationship_type_mismatch()
{
// Arrange
WorkItem existingWorkItem = _fakers.WorkItem.Generate();
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
dbContext.WorkItems.Add(existingWorkItem);
await dbContext.SaveChangesAsync();
});
var requestBody = new
{
data = new
{
type = "workItems",
id = existingWorkItem.StringId,
relationships = new
{
subscribers = new
{
data = new[]
{
new
{
type = "rgbColors",
id = "0A0B0C"
}
}
}
}
}
};
string route = "/workItems/" + existingWorkItem.StringId;
// Act
(HttpResponseMessage httpResponse, ErrorDocument responseDocument) = await _testContext.ExecutePatchAsync<ErrorDocument>(route, requestBody);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.UnprocessableEntity);
responseDocument.Errors.Should().HaveCount(1);
Error error = responseDocument.Errors[0];
error.StatusCode.Should().Be(HttpStatusCode.UnprocessableEntity);
error.Title.Should().Be("Failed to deserialize request body: Relationship contains incompatible resource type.");
error.Detail.Should().StartWith("Relationship 'subscribers' contains incompatible resource type 'rgbColors'. - Request body: <<");
}
[Fact]
public async Task Can_replace_with_duplicates()
{
// Arrange
WorkItem existingWorkItem = _fakers.WorkItem.Generate();
existingWorkItem.Subscribers = _fakers.UserAccount.Generate(1).ToHashSet();
UserAccount existingSubscriber = _fakers.UserAccount.Generate();
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
dbContext.AddInRange(existingWorkItem, existingSubscriber);
await dbContext.SaveChangesAsync();
});
var requestBody = new
{
data = new
{
type = "workItems",
id = existingWorkItem.StringId,
relationships = new
{
subscribers = new
{
data = new[]
{
new
{
type = "userAccounts",
id = existingSubscriber.StringId
},
new
{
type = "userAccounts",
id = existingSubscriber.StringId
}
}
}
}
}
};
string route = "/workItems/" + existingWorkItem.StringId;
// Act
(HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePatchAsync<Document>(route, requestBody);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.OK);
responseDocument.SingleData.Should().NotBeNull();
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
WorkItem workItemInDatabase = await dbContext.WorkItems.Include(workItem => workItem.Subscribers).FirstWithIdAsync(existingWorkItem.Id);
workItemInDatabase.Subscribers.Should().HaveCount(1);
workItemInDatabase.Subscribers.Single().Id.Should().Be(existingSubscriber.Id);
});
}
[Fact]
public async Task Cannot_replace_with_null_data_in_OneToMany_relationship()
{
// Arrange
WorkItem existingWorkItem = _fakers.WorkItem.Generate();
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
dbContext.WorkItems.Add(existingWorkItem);
await dbContext.SaveChangesAsync();
});
var requestBody = new
{
data = new
{
type = "workItems",
id = existingWorkItem.StringId,
relationships = new
{
subscribers = new
{
data = (object)null
}
}
}
};
string route = "/workItems/" + existingWorkItem.StringId;
// Act
(HttpResponseMessage httpResponse, ErrorDocument responseDocument) = await _testContext.ExecutePatchAsync<ErrorDocument>(route, requestBody);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.UnprocessableEntity);
responseDocument.Errors.Should().HaveCount(1);
Error error = responseDocument.Errors[0];
error.StatusCode.Should().Be(HttpStatusCode.UnprocessableEntity);
error.Title.Should().Be("Failed to deserialize request body: Expected data[] element for to-many relationship.");
error.Detail.Should().StartWith("Expected data[] element for 'subscribers' relationship. - Request body: <<");
}
[Fact]
public async Task Cannot_replace_with_null_data_in_ManyToMany_relationship()
{
// Arrange
WorkItem existingWorkItem = _fakers.WorkItem.Generate();
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
dbContext.WorkItems.Add(existingWorkItem);
await dbContext.SaveChangesAsync();
});
var requestBody = new
{
data = new
{
type = "workItems",
id = existingWorkItem.StringId,
relationships = new
{
tags = new
{
data = (object)null
}
}
}
};
string route = "/workItems/" + existingWorkItem.StringId;
// Act
(HttpResponseMessage httpResponse, ErrorDocument responseDocument) = await _testContext.ExecutePatchAsync<ErrorDocument>(route, requestBody);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.UnprocessableEntity);
responseDocument.Errors.Should().HaveCount(1);
Error error = responseDocument.Errors[0];
error.StatusCode.Should().Be(HttpStatusCode.UnprocessableEntity);
error.Title.Should().Be("Failed to deserialize request body: Expected data[] element for to-many relationship.");
error.Detail.Should().StartWith("Expected data[] element for 'tags' relationship. - Request body: <<");
}
[Fact]
public async Task Can_clear_cyclic_OneToMany_relationship()
{
// Arrange
WorkItem existingWorkItem = _fakers.WorkItem.Generate();
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
dbContext.WorkItems.Add(existingWorkItem);
await dbContext.SaveChangesAsync();
existingWorkItem.Children = existingWorkItem.AsList();
await dbContext.SaveChangesAsync();
});
var requestBody = new
{
data = new
{
type = "workItems",
id = existingWorkItem.StringId,
relationships = new
{
children = new
{
data = Array.Empty<object>()
}
}
}
};
string route = "/workItems/" + existingWorkItem.StringId;
// Act
(HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePatchAsync<Document>(route, requestBody);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.OK);
responseDocument.SingleData.Should().NotBeNull();
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
WorkItem workItemInDatabase = await dbContext.WorkItems.Include(workItem => workItem.Children).FirstWithIdAsync(existingWorkItem.Id);
workItemInDatabase.Children.Should().BeEmpty();
});
}
[Fact]
public async Task Can_clear_cyclic_ManyToMany_relationship()
{
// Arrange
WorkItem existingWorkItem = _fakers.WorkItem.Generate();
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
dbContext.WorkItems.Add(existingWorkItem);
await dbContext.SaveChangesAsync();
existingWorkItem.RelatedFrom = ArrayFactory.Create(existingWorkItem);
await dbContext.SaveChangesAsync();
});
var requestBody = new
{
data = new
{
type = "workItems",
id = existingWorkItem.StringId,
relationships = new
{
relatedFrom = new
{
data = Array.Empty<object>()
}
}
}
};
string route = "/workItems/" + existingWorkItem.StringId;
// Act
(HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePatchAsync<Document>(route, requestBody);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.OK);
responseDocument.SingleData.Should().NotBeNull();
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
// @formatter:wrap_chained_method_calls chop_always
// @formatter:keep_existing_linebreaks true
WorkItem workItemInDatabase = await dbContext.WorkItems
.Include(workItem => workItem.RelatedFrom)
.Include(workItem => workItem.RelatedTo)
.FirstWithIdAsync(existingWorkItem.Id);
// @formatter:keep_existing_linebreaks restore
// @formatter:wrap_chained_method_calls restore
workItemInDatabase.RelatedFrom.Should().BeEmpty();
workItemInDatabase.RelatedTo.Should().BeEmpty();
});
}
[Fact]
public async Task Can_assign_cyclic_OneToMany_relationship()
{
// Arrange
WorkItem existingWorkItem = _fakers.WorkItem.Generate();
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
dbContext.WorkItems.Add(existingWorkItem);
await dbContext.SaveChangesAsync();
});
var requestBody = new
{
data = new
{
type = "workItems",
id = existingWorkItem.StringId,
relationships = new
{
children = new
{
data = new[]
{
new
{
type = "workItems",
id = existingWorkItem.StringId
}
}
}
}
}
};
string route = "/workItems/" + existingWorkItem.StringId;
// Act
(HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePatchAsync<Document>(route, requestBody);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.OK);
responseDocument.SingleData.Should().NotBeNull();
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
WorkItem workItemInDatabase = await dbContext.WorkItems.Include(workItem => workItem.Children).FirstWithIdAsync(existingWorkItem.Id);
workItemInDatabase.Children.Should().HaveCount(1);
workItemInDatabase.Children[0].Id.Should().Be(existingWorkItem.Id);
});
}
[Fact]
public async Task Can_assign_cyclic_ManyToMany_relationship()
{
// Arrange
WorkItem existingWorkItem = _fakers.WorkItem.Generate();
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
dbContext.WorkItems.Add(existingWorkItem);
await dbContext.SaveChangesAsync();
});
var requestBody = new
{
data = new
{
type = "workItems",
id = existingWorkItem.StringId,
relationships = new
{
relatedTo = new
{
data = new[]
{
new
{
type = "workItems",
id = existingWorkItem.StringId
}
}
}
}
}
};
string route = "/workItems/" + existingWorkItem.StringId;
// Act
(HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePatchAsync<Document>(route, requestBody);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.OK);
responseDocument.SingleData.Should().NotBeNull();
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
// @formatter:wrap_chained_method_calls chop_always
// @formatter:keep_existing_linebreaks true
WorkItem workItemInDatabase = await dbContext.WorkItems
.Include(workItem => workItem.RelatedFrom)
.Include(workItem => workItem.RelatedTo)
.FirstWithIdAsync(existingWorkItem.Id);
// @formatter:keep_existing_linebreaks restore
// @formatter:wrap_chained_method_calls restore
workItemInDatabase.RelatedFrom.Should().HaveCount(1);
workItemInDatabase.RelatedFrom[0].Id.Should().Be(existingWorkItem.Id);
workItemInDatabase.RelatedTo.Should().HaveCount(1);
workItemInDatabase.RelatedTo[0].Id.Should().Be(existingWorkItem.Id);
});
}
}
}
| 38.71134 | 158 | 0.502869 | [
"MIT"
] | sgryphon/JsonApiDotNetCore | test/JsonApiDotNetCoreExampleTests/IntegrationTests/ReadWrite/Updating/Resources/ReplaceToManyRelationshipTests.cs | 41,305 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace LionFire.Execution
{
public interface IHasProgressMessage
{
string ProgressMessage { get; }
}
}
| 17.307692 | 40 | 0.728889 | [
"MIT"
] | LionFire/Core | src/LionFire.Execution.Abstractions/Execution/Progress/IHasProgressMessage.cs | 227 | 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.
// Template Source: Templates\CSharp\Requests\EntityCollectionResponse.cs.tt
namespace Microsoft.Graph
{
using System.Collections.Generic;
using System.Runtime.Serialization;
using Newtonsoft.Json;
/// <summary>
/// The type EducationRootClassesCollectionResponse.
/// </summary>
[JsonObject(MemberSerialization = MemberSerialization.OptIn)]
public class EducationRootClassesCollectionResponse
{
/// <summary>
/// Gets or sets the <see cref="IEducationRootClassesCollectionPage"/> value.
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName ="value", Required = Newtonsoft.Json.Required.Default)]
public IEducationRootClassesCollectionPage Value { get; set; }
/// <summary>
/// Gets or sets additional data.
/// </summary>
[JsonExtensionData(ReadData = true)]
public IDictionary<string, object> AdditionalData { get; set; }
}
}
| 41.878788 | 153 | 0.620116 | [
"MIT"
] | AzureMentor/msgraph-sdk-dotnet | src/Microsoft.Graph/Requests/Generated/EducationRootClassesCollectionResponse.cs | 1,382 | C# |
/*
* Copyright (c) 2018 THL A29 Limited, a Tencent company. 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.
*/
namespace TencentCloud.Vpc.V20170312.Models
{
using Newtonsoft.Json;
using System.Collections.Generic;
using TencentCloud.Common;
public class ModifyAddressesBandwidthRequest : AbstractModel
{
/// <summary>
/// EIP唯一标识ID,形如'eip-xxxx'
/// </summary>
[JsonProperty("AddressIds")]
public string[] AddressIds{ get; set; }
/// <summary>
/// 调整带宽目标值
/// </summary>
[JsonProperty("InternetMaxBandwidthOut")]
public long? InternetMaxBandwidthOut{ get; set; }
/// <summary>
/// 包月带宽起始时间(已废弃,输入无效)
/// </summary>
[JsonProperty("StartTime")]
public string StartTime{ get; set; }
/// <summary>
/// 包月带宽结束时间(已废弃,输入无效)
/// </summary>
[JsonProperty("EndTime")]
public string EndTime{ get; set; }
/// <summary>
/// For internal usage only. DO NOT USE IT.
/// </summary>
internal override void ToMap(Dictionary<string, string> map, string prefix)
{
this.SetParamArraySimple(map, prefix + "AddressIds.", this.AddressIds);
this.SetParamSimple(map, prefix + "InternetMaxBandwidthOut", this.InternetMaxBandwidthOut);
this.SetParamSimple(map, prefix + "StartTime", this.StartTime);
this.SetParamSimple(map, prefix + "EndTime", this.EndTime);
}
}
}
| 31.861538 | 103 | 0.627716 | [
"Apache-2.0"
] | ImEdisonJiang/tencentcloud-sdk-dotnet | TencentCloud/Vpc/V20170312/Models/ModifyAddressesBandwidthRequest.cs | 2,163 | C# |
using System;
using MikhailKhalizev.Processor.x86.BinToCSharp;
namespace MikhailKhalizev.Max.Program
{
public partial class RawProgram
{
[MethodInfo("0x1011_7635-e1d2a3e1")]
public void Method_1011_7635()
{
ii(0x1011_7635, 5); push(0x2c); /* push 0x2c */
ii(0x1011_763a, 5); call(Definitions.sys_check_available_stack_size, 0x4_e713);/* call 0x10165d52 */
ii(0x1011_763f, 1); push(ecx); /* push ecx */
ii(0x1011_7640, 1); push(esi); /* push esi */
ii(0x1011_7641, 1); push(edi); /* push edi */
ii(0x1011_7642, 1); push(ebp); /* push ebp */
ii(0x1011_7643, 2); mov(ebp, esp); /* mov ebp, esp */
ii(0x1011_7645, 6); sub(esp, 0x18); /* sub esp, 0x18 */
ii(0x1011_764b, 3); mov(memd[ss, ebp - 12], eax); /* mov [ebp-0xc], eax */
ii(0x1011_764e, 3); mov(memd[ss, ebp - 8], edx); /* mov [ebp-0x8], edx */
ii(0x1011_7651, 3); mov(memd[ss, ebp - 4], ebx); /* mov [ebp-0x4], ebx */
ii(0x1011_7654, 3); mov(eax, memd[ss, ebp - 12]); /* mov eax, [ebp-0xc] */
ii(0x1011_7657, 5); call(0x1013_aaa8, 0x2_344c); /* call 0x1013aaa8 */
ii(0x1011_765c, 3); mov(memd[ss, ebp - 12], eax); /* mov [ebp-0xc], eax */
ii(0x1011_765f, 3); lea(eax, memd[ss, ebp - 12]); /* lea eax, [ebp-0xc] */
ii(0x1011_7662, 3); mov(memd[ss, ebp - 16], eax); /* mov [ebp-0x10], eax */
ii(0x1011_7665, 3); mov(eax, memd[ss, ebp - 12]); /* mov eax, [ebp-0xc] */
ii(0x1011_7668, 3); add(eax, 0xc); /* add eax, 0xc */
ii(0x1011_766b, 5); call(Definitions.my_ctor_0x101b_38f8, -0xa_0f80);/* call 0x100766f0 */
ii(0x1011_7670, 3); sub(eax, 0xc); /* sub eax, 0xc */
ii(0x1011_7673, 3); mov(memd[ss, ebp - 12], eax); /* mov [ebp-0xc], eax */
ii(0x1011_7676, 3); lea(eax, memd[ss, ebp - 12]); /* lea eax, [ebp-0xc] */
ii(0x1011_7679, 3); mov(memd[ss, ebp - 20], eax); /* mov [ebp-0x14], eax */
ii(0x1011_767c, 3); mov(eax, memd[ss, ebp - 12]); /* mov eax, [ebp-0xc] */
ii(0x1011_767f, 3); add(eax, 0x10); /* add eax, 0x10 */
ii(0x1011_7682, 5); call(Definitions.my_ctor_0x101b_4184, -0xa_0b97);/* call 0x10076af0 */
ii(0x1011_7687, 3); sub(eax, 0x10); /* sub eax, 0x10 */
ii(0x1011_768a, 3); mov(memd[ss, ebp - 12], eax); /* mov [ebp-0xc], eax */
ii(0x1011_768d, 3); mov(eax, memd[ss, ebp - 12]); /* mov eax, [ebp-0xc] */
ii(0x1011_7690, 7); mov(memd[ds, eax + 2], 0x101b_6730); /* mov dword [eax+0x2], 0x101b6730 */
ii(0x1011_7697, 3); mov(eax, memd[ss, ebp - 4]); /* mov eax, [ebp-0x4] */
ii(0x1011_769a, 3); mov(edx, memd[ss, ebp - 12]); /* mov edx, [ebp-0xc] */
ii(0x1011_769d, 4); mov(memw[ds, edx + 6], ax); /* mov [edx+0x6], ax */
ii(0x1011_76a1, 3); mov(eax, memd[ss, ebp - 8]); /* mov eax, [ebp-0x8] */
ii(0x1011_76a4, 5); call(/* sys */ 0x1017_cee0, 0x6_5837);/* call 0x1017cee0 */
ii(0x1011_76a9, 2); mov(edx, eax); /* mov edx, eax */
ii(0x1011_76ab, 3); mov(eax, memd[ss, ebp - 12]); /* mov eax, [ebp-0xc] */
ii(0x1011_76ae, 3); mov(memd[ds, eax + 8], edx); /* mov [eax+0x8], edx */
ii(0x1011_76b1, 3); mov(eax, memd[ss, ebp - 12]); /* mov eax, [ebp-0xc] */
ii(0x1011_76b4, 4); mov(memb[ds, eax + 20], 0); /* mov byte [eax+0x14], 0x0 */
ii(0x1011_76b8, 3); mov(eax, memd[ss, ebp - 12]); /* mov eax, [ebp-0xc] */
ii(0x1011_76bb, 3); mov(memd[ss, ebp - 24], eax); /* mov [ebp-0x18], eax */
ii(0x1011_76be, 3); mov(eax, memd[ss, ebp - 24]); /* mov eax, [ebp-0x18] */
ii(0x1011_76c1, 2); mov(esp, ebp); /* mov esp, ebp */
ii(0x1011_76c3, 1); pop(ebp); /* pop ebp */
ii(0x1011_76c4, 1); pop(edi); /* pop edi */
ii(0x1011_76c5, 1); pop(esi); /* pop esi */
ii(0x1011_76c6, 1); pop(ecx); /* pop ecx */
ii(0x1011_76c7, 1); ret(); /* ret */
}
}
}
| 78.111111 | 114 | 0.439138 | [
"Apache-2.0"
] | mikhail-khalizev/max | source/MikhailKhalizev.Max/source/Program/Auto/z-1011-7635.cs | 4,921 | C# |
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.
namespace System.Data.Entity.Core.Common.CommandTrees.Internal
{
using System.Collections.Generic;
using System.Data.Entity.Core.Metadata.Edm;
using System.Data.Entity.Resources;
using System.Data.Entity.Utilities;
using System.Diagnostics;
using System.Linq;
internal sealed class DbExpressionValidator : DbExpressionRebinder
{
private readonly DataSpace requiredSpace;
private readonly DataSpace[] allowedMetadataSpaces;
private readonly DataSpace[] allowedFunctionSpaces;
private readonly Dictionary<string, DbParameterReferenceExpression> paramMappings =
new Dictionary<string, DbParameterReferenceExpression>();
private readonly Stack<Dictionary<string, TypeUsage>> variableScopes = new Stack<Dictionary<string, TypeUsage>>();
private string expressionArgumentName;
internal DbExpressionValidator(MetadataWorkspace metadata, DataSpace expectedDataSpace)
: base(metadata)
{
requiredSpace = expectedDataSpace;
allowedFunctionSpaces = new[] { DataSpace.CSpace, DataSpace.SSpace };
if (expectedDataSpace == DataSpace.SSpace)
{
allowedMetadataSpaces = new[] { DataSpace.SSpace, DataSpace.CSpace };
}
else
{
allowedMetadataSpaces = new[] { DataSpace.CSpace };
}
}
internal Dictionary<string, DbParameterReferenceExpression> Parameters
{
get { return paramMappings; }
}
internal void ValidateExpression(DbExpression expression, string argumentName)
{
DebugCheck.NotNull(expression);
expressionArgumentName = argumentName;
VisitExpression(expression);
expressionArgumentName = null;
Debug.Assert(variableScopes.Count == 0, "Variable scope stack left in inconsistent state");
}
protected override EntitySetBase VisitEntitySet(EntitySetBase entitySet)
{
return ValidateMetadata(entitySet, base.VisitEntitySet, es => es.EntityContainer.DataSpace, allowedMetadataSpaces);
}
protected override EdmFunction VisitFunction(EdmFunction function)
{
// Functions from the current space and S-Space are allowed
return ValidateMetadata(function, base.VisitFunction, func => func.DataSpace, allowedFunctionSpaces);
}
protected override EdmType VisitType(EdmType type)
{
return ValidateMetadata(type, base.VisitType, et => et.DataSpace, allowedMetadataSpaces);
}
protected override TypeUsage VisitTypeUsage(TypeUsage type)
{
return ValidateMetadata(type, base.VisitTypeUsage, tu => tu.EdmType.DataSpace, allowedMetadataSpaces);
}
protected override void OnEnterScope(IEnumerable<DbVariableReferenceExpression> scopeVariables)
{
var newScope = scopeVariables.ToDictionary(var => var.VariableName, var => var.ResultType, StringComparer.Ordinal);
variableScopes.Push(newScope);
}
protected override void OnExitScope()
{
variableScopes.Pop();
}
public override DbExpression Visit(DbVariableReferenceExpression expression)
{
Check.NotNull(expression, "expression");
var result = base.Visit(expression);
if (result.ExpressionKind
== DbExpressionKind.VariableReference)
{
var varRef = (DbVariableReferenceExpression)result;
TypeUsage foundType = null;
foreach (var scope in variableScopes)
{
if (scope.TryGetValue(varRef.VariableName, out foundType))
{
break;
}
}
if (foundType == null)
{
ThrowInvalid(Strings.Cqt_Validator_VarRefInvalid(varRef.VariableName));
}
// SQLBUDT#545720: Equivalence is not a sufficient check (consider row types) - equality is required.
if (!TypeSemantics.IsEqual(varRef.ResultType, foundType))
{
ThrowInvalid(Strings.Cqt_Validator_VarRefTypeMismatch(varRef.VariableName));
}
}
return result;
}
public override DbExpression Visit(DbParameterReferenceExpression expression)
{
Check.NotNull(expression, "expression");
var result = base.Visit(expression);
if (result.ExpressionKind
== DbExpressionKind.ParameterReference)
{
var paramRef = result as DbParameterReferenceExpression;
DbParameterReferenceExpression foundParam;
if (paramMappings.TryGetValue(paramRef.ParameterName, out foundParam))
{
// SQLBUDT#545720: Equivalence is not a sufficient check (consider row types for TVPs) - equality is required.
if (!TypeSemantics.IsEqual(paramRef.ResultType, foundParam.ResultType))
{
ThrowInvalid(Strings.Cqt_Validator_InvalidIncompatibleParameterReferences(paramRef.ParameterName));
}
}
else
{
paramMappings.Add(paramRef.ParameterName, paramRef);
}
}
return result;
}
private TMetadata ValidateMetadata<TMetadata>(
TMetadata metadata, Func<TMetadata, TMetadata> map, Func<TMetadata, DataSpace> getDataSpace, DataSpace[] allowedSpaces)
{
var result = map(metadata);
if (!ReferenceEquals(metadata, result))
{
ThrowInvalidMetadata<TMetadata>();
}
var resultSpace = getDataSpace(result);
if (!allowedSpaces.Any(ds => ds == resultSpace))
{
ThrowInvalidSpace<TMetadata>();
}
return result;
}
private void ThrowInvalidMetadata<TMetadata>()
{
ThrowInvalid(Strings.Cqt_Validator_InvalidOtherWorkspaceMetadata(typeof(TMetadata).Name));
}
private void ThrowInvalidSpace<TMetadata>()
{
ThrowInvalid(
Strings.Cqt_Validator_InvalidIncorrectDataSpaceMetadata(
typeof(TMetadata).Name, Enum.GetName(typeof(DataSpace), requiredSpace)));
}
private void ThrowInvalid(string message)
{
throw new ArgumentException(message, expressionArgumentName);
}
}
}
| 39.248619 | 133 | 0.594172 | [
"Apache-2.0"
] | TerraVenil/entityframework | src/EntityFramework/Core/Common/CommandTrees/Internal/Validator.cs | 7,104 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DotVVM.Framework.ViewModel;
namespace OldWebApp.ViewModels
{
public class AboutViewModel : SiteViewModel
{
public override string Title => "About";
}
}
| 17.733333 | 48 | 0.733083 | [
"Apache-2.0"
] | riganti/dotvvm-samples-webforms-migration | src/OldWebApp/OldWebApp.NetCore/ViewModels/AboutViewModel.cs | 266 | C# |
using Eventuous.Subscriptions.Context;
using Eventuous.Subscriptions.Filters.Partitioning;
using static Eventuous.Subscriptions.Diagnostics.SubscriptionsEventSource;
namespace Eventuous.Subscriptions.Filters;
public sealed class PartitioningFilter : ConsumeFilter<DelayedAckConsumeContext>, IAsyncDisposable {
readonly int _partitionCount;
readonly Partitioner.GetPartitionHash _partitioner;
readonly ConcurrentFilter[] _filters;
public PartitioningFilter(uint partitionCount, Partitioner.GetPartitionHash? partitioner = null) {
_partitionCount = (int)partitionCount;
_partitioner = partitioner ?? (ctx => MurmurHash3.Hash(ctx.Stream));
_filters = Enumerable.Range(0, _partitionCount).Select(_ => new ConcurrentFilter(1)).ToArray();
}
public PartitioningFilter(uint partitionCount, Partitioner.GetPartitionKey getPartitionKey)
: this(partitionCount, ctx => MurmurHash3.Hash(getPartitionKey(ctx))) { }
public override ValueTask Send(DelayedAckConsumeContext context, Func<DelayedAckConsumeContext, ValueTask>? next) {
var hash = _partitioner(context);
var partition = hash % _partitionCount;
return _filters[partition].Send(context.WithItem(ContextKeys.PartitionId, partition), next);
}
public async ValueTask DisposeAsync() {
Log.Stopping(nameof(PartitioningFilter), "concurrent filters", "");
await Task.WhenAll(_filters.Select(async x => await x.DisposeAsync()));
}
} | 49.580645 | 119 | 0.732596 | [
"MIT"
] | Eventuous/eventuous | src/Core/src/Eventuous.Subscriptions/Filters/PartitioningFilter.cs | 1,537 | C# |
namespace DWGitsh.Extensions.Models
{
public class GitConfigUser
{
public string Name { get; set; }
public string Mailbox { get; set; }
public string Email { get; set; }
public override string ToString()
{
if (Name == null && Email == null) return string.Empty;
return $"{{Name=\"{Name}\", Email=\"{Email}\"}}";
}
}
} | 25.25 | 67 | 0.529703 | [
"MIT"
] | DavidWise/DWGitSH | DWGitsh.Extensions/Models/GitConfigUser.cs | 406 | C# |
using UnityEngine;
using System.Collections;
public class Cat : MonoBehaviour {
private enum State {
Idle,
Fight,
Shoot,
Exploding,
};
public Animator anim;
public BoxCollider2D box;
public BoxCollider2D playerBox;
public GameObject player;
public Rigidbody2D bullet;
public GameObject explode;
public GameObject healthGlobe;
private Vector3 initPos;
private int health;
private State state;
private uint shootCtr;
void Start () {
initPos = transform.position;
health = 12;
state = State.Idle;
shootCtr = 30;
}
void FixedUpdate() {
switch (state) {
case State.Fight:
if (++shootCtr >= 70) {
anim.SetTrigger("shuffle");
shootCtr = 0;
state = State.Shoot;
}
break;
case State.Shoot:
StartCoroutine(GenBullets(Random.Range(4, 9)));
state = State.Fight;
break;
}
}
void LateUpdate() {
if (box.bounds.Intersects (playerBox.bounds)) {
player.SendMessage("ApplyDamage", 12);
}
}
IEnumerator GenBullets(int amt) {
for (int i = 0; i < amt; i++) {
yield return new WaitForSeconds(0.03125f);
var rb = Instantiate(bullet, transform.position, transform.rotation) as Rigidbody2D;
Physics2D.IgnoreCollision(rb.GetComponent<BoxCollider2D>(), box);
rb.AddForce(new Vector2(-256.0f, -256.0f), ForceMode2D.Impulse);
}
}
void Activate() {
if (state.Equals (State.Idle)) {
state = State.Fight;
}
}
void ApplyDamage(int dmg) {
health = Mathf.Max (0, health - Mathf.Abs(dmg));
if (health <= 0) {
state = State.Exploding;
StartCoroutine(Exploder());
}
}
void Reset() {
Debug.Log("HERE");
transform.position = initPos;
health = 12;
state = State.Idle;
shootCtr = 30;
}
IEnumerator Exploder() {
for (int i = 0; i < 10; i++) {
var v = new Vector3(Random.Range(-16.0f, 32.0f), Random.Range(-16.0f, 16.0f), 0.0f);
Instantiate(explode, transform.position + v, transform.rotation);
yield return new WaitForSeconds(0.0625f);
}
if (Random.Range(0, 100) >= 90) {
Instantiate(healthGlobe, transform.position, transform.rotation);
}
Destroy(gameObject);
}
}
| 20.417476 | 87 | 0.664765 | [
"MIT"
] | djoyahoy/uniman2 | Assets/Scripts/Cat.cs | 2,105 | C# |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using Microsoft.VisualStudio.Shell;
namespace Microsoft.Sarif.Viewer
{
/// <summary>
/// Handles management and dispatching of EventHandlers in a weak way.
/// </summary>
public static class WeakEventHandlerManager
{
///<summary>
/// Invokes the handlers
///</summary>
///<param name="sender"></param>
///<param name="handlers"></param>
public static void CallWeakReferenceHandlers(object sender, List<WeakReference> handlers)
{
if (handlers != null)
{
// Take a snapshot of the handlers before we call out to them since the handlers
// could cause the array to me modified while we are reading it.
EventHandler[] callees = new EventHandler[handlers.Count];
int count = 0;
//Clean up handlers
count = CleanupOldHandlers(handlers, callees, count);
// Call the handlers that we snapshotted
for (int i = 0; i < count; i++)
{
CallHandler(sender, callees[i]);
}
}
}
private static void CallHandler(object sender, EventHandler eventHandler)
{
if (eventHandler != null)
{
ThreadHelper.JoinableTaskFactory.Run(async delegate
{
await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();
eventHandler(sender, EventArgs.Empty);
});
}
}
private static int CleanupOldHandlers(List<WeakReference> handlers, EventHandler[] callees, int count)
{
for (int i = handlers.Count - 1; i >= 0; i--)
{
WeakReference reference = handlers[i];
EventHandler handler = reference.Target as EventHandler;
if (handler == null)
{
// Clean up old handlers that have been collected
handlers.RemoveAt(i);
}
else
{
callees[count] = handler;
count++;
}
}
return count;
}
///<summary>
/// Adds a handler to the supplied list in a weak way.
///</summary>
///<param name="handlers">Existing handler list. It will be created if null.</param>
///<param name="handler">Handler to add.</param>
///<param name="defaultListSize">Default list size.</param>
public static void AddWeakReferenceHandler(ref List<WeakReference> handlers, EventHandler handler, int defaultListSize)
{
if (handlers == null)
{
handlers = (defaultListSize > 0 ? new List<WeakReference>(defaultListSize) : new List<WeakReference>());
}
handlers.Add(new WeakReference(handler));
}
///<summary>
/// Removes an event handler from the reference list.
///</summary>
///<param name="handlers">Handler list to remove reference from.</param>
///<param name="handler">Handler to remove.</param>
public static void RemoveWeakReferenceHandler(List<WeakReference> handlers, EventHandler handler)
{
if (handlers != null)
{
for (int i = handlers.Count - 1; i >= 0; i--)
{
WeakReference reference = handlers[i];
EventHandler existingHandler = reference.Target as EventHandler;
if ((existingHandler == null) || (existingHandler == handler))
{
// Clean up old handlers that have been collected
// in addition to the handler that is to be removed.
handlers.RemoveAt(i);
}
}
}
}
}
}
| 37.482143 | 127 | 0.530014 | [
"MIT"
] | Bhaskers-Blu-Org2/sarif-visualstudio-extension | src/Sarif.Viewer.VisualStudio/WeakEventHandlerManager.cs | 4,200 | C# |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Collections.Immutable;
using Microsoft.CodeAnalysis.Common;
namespace Microsoft.CodeAnalysis.Editor
{
internal class TodoItemsUpdatedArgs : UpdatedEventArgs
{
/// <summary>
/// Solution this task items are associated with
/// </summary>
public Solution Solution { get; }
/// <summary>
/// The task items associated with the ID.
/// </summary>
public ImmutableArray<TodoItem> TodoItems { get; }
public TodoItemsUpdatedArgs(
object id, Workspace workspace, Solution solution, ProjectId projectId, DocumentId documentId, ImmutableArray<TodoItem> todoItems) :
base(id, workspace, projectId, documentId)
{
this.Solution = solution;
this.TodoItems = todoItems;
}
}
}
| 34.068966 | 161 | 0.654858 | [
"Apache-2.0"
] | 0x53A/roslyn | src/EditorFeatures/Core/Implementation/TodoComment/TodoItemsUpdatedArgs.cs | 990 | C# |
using System.Runtime.Serialization;
using System.Xml;
using Newtonsoft.Json;
namespace Iviz.Urdf
{
[DataContract]
public sealed class Texture
{
[DataMember] public string Filename { get; }
internal Texture(XmlNode node)
{
Filename = Utils.ParseString(node.Attributes?["filename"]);
}
public override string ToString() => JsonConvert.SerializeObject(this);
}
} | 23.052632 | 79 | 0.639269 | [
"MIT"
] | KIT-ISAS/iviz | iviz_urdf/Urdf/Texture.cs | 438 | C# |
/*
http://www.cgsoso.com/forum-211-1.html
CG搜搜 Unity3d 每日Unity3d插件免费更新 更有VIP资源!
CGSOSO 主打游戏开发,影视设计等CG资源素材。
插件如若商用,请务必官网购买!
daily assets update for try.
U should buy the asset from home store if u use it in your project!
*/
#if !BESTHTTP_DISABLE_SERVERSENT_EVENTS
using System;
using System.Collections.Generic;
using BestHTTP.Extensions;
#if UNITY_WEBGL && !UNITY_EDITOR
using System.Runtime.InteropServices;
#endif
namespace BestHTTP.ServerSentEvents
{
/// <summary>
/// Possible states of an EventSource object.
/// </summary>
public enum States
{
Initial,
Connecting,
Open,
Retrying,
Closing,
Closed
}
public delegate void OnGeneralEventDelegate(EventSource eventSource);
public delegate void OnMessageDelegate(EventSource eventSource, BestHTTP.ServerSentEvents.Message message);
public delegate void OnErrorDelegate(EventSource eventSource, string error);
public delegate bool OnRetryDelegate(EventSource eventSource);
public delegate void OnEventDelegate(EventSource eventSource, BestHTTP.ServerSentEvents.Message message);
public delegate void OnStateChangedDelegate(EventSource eventSource, States oldState, States newState);
#if UNITY_WEBGL && !UNITY_EDITOR
delegate void OnWebGLEventSourceOpenDelegate(uint id);
delegate void OnWebGLEventSourceMessageDelegate(uint id, string eventStr, string data, string eventId, int retry);
delegate void OnWebGLEventSourceErrorDelegate(uint id, string reason);
#endif
/// <summary>
/// http://www.w3.org/TR/eventsource/
/// </summary>
public class EventSource
#if !UNITY_WEBGL || UNITY_EDITOR
: IHeartbeat
#endif
{
#region Public Properties
/// <summary>
/// Uri of the remote endpoint.
/// </summary>
public Uri Uri { get; private set; }
/// <summary>
/// Current state of the EventSource object.
/// </summary>
public States State
{
get
{
return _state;
}
private set
{
States oldState = _state;
_state = value;
if (OnStateChanged != null)
{
try
{
OnStateChanged(this, oldState, _state);
}
catch(Exception ex)
{
HTTPManager.Logger.Exception("EventSource", "OnStateChanged", ex);
}
}
}
}
private States _state;
/// <summary>
/// Time to wait to do a reconnect attempt. Default to 2 sec. The server can overwrite this setting.
/// </summary>
public TimeSpan ReconnectionTime { get; set; }
/// <summary>
/// The last successfully received event's id.
/// </summary>
public string LastEventId { get; private set; }
#if !UNITY_WEBGL || UNITY_EDITOR
/// <summary>
/// The internal request object of the EventSource.
/// </summary>
public HTTPRequest InternalRequest { get; private set; }
#endif
#endregion
#region Public Events
/// <summary>
/// Called when successfully connected to the server.
/// </summary>
public event OnGeneralEventDelegate OnOpen;
/// <summary>
/// Called on every message received from the server.
/// </summary>
public event OnMessageDelegate OnMessage;
/// <summary>
/// Called when an error occures.
/// </summary>
public event OnErrorDelegate OnError;
#if !UNITY_WEBGL || UNITY_EDITOR
/// <summary>
/// Called when the EventSource will try to do a retry attempt. If this function returns with false, it will cancel the attempt.
/// </summary>
public event OnRetryDelegate OnRetry;
#endif
/// <summary>
/// Called when the EventSource object closed.
/// </summary>
public event OnGeneralEventDelegate OnClosed;
/// <summary>
/// Called every time when the State property changed.
/// </summary>
public event OnStateChangedDelegate OnStateChanged;
#endregion
#region Privates
/// <summary>
/// A dictionary to store eventName => delegate mapping.
/// </summary>
private Dictionary<string, OnEventDelegate> EventTable;
#if !UNITY_WEBGL || UNITY_EDITOR
/// <summary>
/// Number of retry attempts made.
/// </summary>
private byte RetryCount;
/// <summary>
/// When we called the Retry function. We will delay the Open call from here.
/// </summary>
private DateTime RetryCalled;
#else
private static Dictionary<uint, EventSource> EventSources = new Dictionary<uint, EventSource>();
private uint Id;
#endif
#endregion
public EventSource(Uri uri)
{
this.Uri = uri;
this.ReconnectionTime = TimeSpan.FromMilliseconds(2000);
#if !UNITY_WEBGL || UNITY_EDITOR
this.InternalRequest = new HTTPRequest(Uri, HTTPMethods.Get, true, true, OnRequestFinished);
// Set headers
this.InternalRequest.SetHeader("Accept", "text/event-stream");
this.InternalRequest.SetHeader("Cache-Control", "no-cache");
this.InternalRequest.SetHeader("Accept-Encoding", "identity");
// Set protocol stuff
this.InternalRequest.ProtocolHandler = SupportedProtocols.ServerSentEvents;
this.InternalRequest.OnUpgraded = OnUpgraded;
// Disable internal retry
this.InternalRequest.DisableRetry = true;
#endif
}
#region Public Functions
/// <summary>
/// Start to connect to the remote servr.
/// </summary>
public void Open()
{
if (this.State != States.Initial &&
this.State != States.Retrying &&
this.State != States.Closed)
return;
this.State = States.Connecting;
#if !UNITY_WEBGL || UNITY_EDITOR
if (!string.IsNullOrEmpty(this.LastEventId))
this.InternalRequest.SetHeader("Last-Event-ID", this.LastEventId);
this.InternalRequest.Send();
#else
this.Id = ES_Create(this.Uri.ToString(), true, OnOpenCallback, OnMessageCallback, OnErrorCallback);
EventSources.Add(this.Id, this);
#endif
}
/// <summary>
/// Start to close the connection.
/// </summary>
public void Close()
{
if (this.State == States.Closing ||
this.State == States.Closed)
return;
this.State = States.Closing;
#if !UNITY_WEBGL || UNITY_EDITOR
if (this.InternalRequest != null)
this.InternalRequest.Abort();
else
this.State = States.Closed;
#else
ES_Close(this.Id);
SetClosed("Close");
EventSources.Remove(this.Id);
ES_Release(this.Id);
#endif
}
/// <summary>
/// With this function an event handler can be subscribed for an event name.
/// </summary>
public void On(string eventName, OnEventDelegate action)
{
if (EventTable == null)
EventTable = new Dictionary<string, OnEventDelegate>();
EventTable[eventName] = action;
}
/// <summary>
/// With this function the event handler can be removed for the given event name.
/// </summary>
/// <param name="eventName"></param>
public void Off(string eventName)
{
if (eventName == null)
return;
EventTable.Remove(eventName);
}
#endregion
#region Private Helper Functions
private void CallOnError(string error, string msg)
{
if (OnError != null)
{
try
{
OnError(this, error);
}
catch (Exception ex)
{
HTTPManager.Logger.Exception("EventSource", msg + " - OnError", ex);
}
}
}
#if !UNITY_WEBGL || UNITY_EDITOR
private bool CallOnRetry()
{
if (OnRetry != null)
{
try
{
return OnRetry(this);
}
catch(Exception ex)
{
HTTPManager.Logger.Exception("EventSource", "CallOnRetry", ex);
}
}
return true;
}
#endif
private void SetClosed(string msg)
{
this.State = States.Closed;
if (OnClosed != null)
{
try
{
OnClosed(this);
}
catch (Exception ex)
{
HTTPManager.Logger.Exception("EventSource", msg + " - OnClosed", ex);
}
}
}
#if !UNITY_WEBGL || UNITY_EDITOR
private void Retry()
{
if (RetryCount > 0 ||
!CallOnRetry())
{
SetClosed("Retry");
return;
}
RetryCount++;
RetryCalled = DateTime.UtcNow;
HTTPManager.Heartbeats.Subscribe(this);
this.State = States.Retrying;
}
#endif
#endregion
#region HTTP Request Implementation
#if !UNITY_WEBGL || UNITY_EDITOR
/// <summary>
/// We are successfully upgraded to the EventSource protocol, we can start to receive and parse the incoming data.
/// </summary>
private void OnUpgraded(HTTPRequest originalRequest, HTTPResponse response)
{
EventSourceResponse esResponse = response as EventSourceResponse;
if (esResponse == null)
{
CallOnError("Not an EventSourceResponse!", "OnUpgraded");
return;
}
if (OnOpen != null)
{
try
{
OnOpen(this);
}
catch (Exception ex)
{
HTTPManager.Logger.Exception("EventSource", "OnOpen", ex);
}
}
esResponse.OnMessage += OnMessageReceived;
esResponse.StartReceive();
this.RetryCount = 0;
this.State = States.Open;
}
private void OnRequestFinished(HTTPRequest req, HTTPResponse resp)
{
if (this.State == States.Closed)
return;
if (this.State == States.Closing ||
req.State == HTTPRequestStates.Aborted)
{
SetClosed("OnRequestFinished");
return;
}
string reason = string.Empty;
// In some cases retry is prohibited
bool canRetry = true;
switch (req.State)
{
// The server sent all the data it's wanted.
case HTTPRequestStates.Processing:
canRetry = !resp.HasHeader("content-length");
break;
// The request finished without any problem.
case HTTPRequestStates.Finished:
// HTTP 200 OK responses that have a Content-Type specifying an unsupported type, or that have no Content-Type at all, must cause the user agent to fail the connection.
if (resp.StatusCode == 200 && !resp.HasHeaderWithValue("content-type", "text/event-stream"))
{
reason = "No Content-Type header with value 'text/event-stream' present.";
canRetry = false;
}
// HTTP 500 Internal Server Error, 502 Bad Gateway, 503 Service Unavailable, and 504 Gateway Timeout responses, and any network error that prevents the connection
// from being established in the first place (e.g. DNS errors), must cause the user agent to asynchronously reestablish the connection.
// Any other HTTP response code not listed here must cause the user agent to fail the connection.
if (canRetry &&
resp.StatusCode != 500 &&
resp.StatusCode != 502 &&
resp.StatusCode != 503 &&
resp.StatusCode != 504)
{
canRetry = false;
reason = string.Format("Request Finished Successfully, but the server sent an error. Status Code: {0}-{1} Message: {2}",
resp.StatusCode,
resp.Message,
resp.DataAsText);
}
break;
// The request finished with an unexpected error. The request's Exception property may contain more info about the error.
case HTTPRequestStates.Error:
reason = "Request Finished with Error! " + (req.Exception != null ? (req.Exception.Message + "\n" + req.Exception.StackTrace) : "No Exception");
break;
// The request aborted, initiated by the user.
case HTTPRequestStates.Aborted:
// If the state is Closing, then it's a normal behaviour, and we close the EventSource
reason = "OnRequestFinished - Aborted without request. EventSource's State: " + this.State;
break;
// Ceonnecting to the server is timed out.
case HTTPRequestStates.ConnectionTimedOut:
reason = "Connection Timed Out!";
break;
// The request didn't finished in the given time.
case HTTPRequestStates.TimedOut:
reason = "Processing the request Timed Out!";
break;
}
// If we are not closing the EventSource, then we will try to reconnect.
if (this.State < States.Closing)
{
if (!string.IsNullOrEmpty(reason))
CallOnError(reason, "OnRequestFinished");
if (canRetry)
Retry();
else
SetClosed("OnRequestFinished");
}
else
SetClosed("OnRequestFinished");
}
#endif
#endregion
#region EventStreamResponse Event Handlers
private void OnMessageReceived(
#if !UNITY_WEBGL || UNITY_EDITOR
EventSourceResponse resp,
#endif
BestHTTP.ServerSentEvents.Message message)
{
if (this.State >= States.Closing)
return;
// 1.) Set the last event ID string of the event source to value of the last event ID buffer.
// The buffer does not get reset, so the last event ID string of the event source remains set to this value until the next time it is set by the server.
// We check here only for null, because it can be a non-null but empty string.
if (message.Id != null)
this.LastEventId = message.Id;
if (message.Retry.TotalMilliseconds > 0)
this.ReconnectionTime = message.Retry;
// 2.) If the data buffer is an empty string, set the data buffer and the event type buffer to the empty string and abort these steps.
if (string.IsNullOrEmpty(message.Data))
return;
// 3.) If the data buffer's last character is a U+000A LINE FEED (LF) character, then remove the last character from the data buffer.
// This step can be ignored. We constructed the string to be able to skip this step.
if (OnMessage != null)
{
try
{
OnMessage(this, message);
}
catch (Exception ex)
{
HTTPManager.Logger.Exception("EventSource", "OnMessageReceived - OnMessage", ex);
}
}
if (!string.IsNullOrEmpty(message.Event))
{
OnEventDelegate action;
if (EventTable.TryGetValue(message.Event, out action))
{
if (action != null)
{
try
{
action(this, message);
}
catch(Exception ex)
{
HTTPManager.Logger.Exception("EventSource", "OnMessageReceived - action", ex);
}
}
}
}
}
#endregion
#region IHeartbeat Implementation
#if !UNITY_WEBGL || UNITY_EDITOR
void IHeartbeat.OnHeartbeatUpdate(TimeSpan dif)
{
if (this.State != States.Retrying)
{
HTTPManager.Heartbeats.Unsubscribe(this);
return;
}
if (DateTime.UtcNow - RetryCalled >= ReconnectionTime)
{
Open();
if (this.State != States.Connecting)
SetClosed("OnHeartbeatUpdate");
HTTPManager.Heartbeats.Unsubscribe(this);
}
}
#endif
#endregion
#region WebGL Static Callbacks
#if UNITY_WEBGL && !UNITY_EDITOR
[AOT.MonoPInvokeCallback(typeof(OnWebGLEventSourceOpenDelegate))]
static void OnOpenCallback(uint id)
{
EventSource es;
if (EventSources.TryGetValue(id, out es))
{
if (es.OnOpen != null)
{
try
{
es.OnOpen(es);
}
catch(Exception ex)
{
HTTPManager.Logger.Exception("EventSource", "OnOpen", ex);
}
}
es.State = States.Open;
}
else
HTTPManager.Logger.Warning("EventSource", "OnOpenCallback - No EventSource found for id: " + id.ToString());
}
[AOT.MonoPInvokeCallback(typeof(OnWebGLEventSourceMessageDelegate))]
static void OnMessageCallback(uint id, string eventStr, string data, string eventId, int retry)
{
EventSource es;
if (EventSources.TryGetValue(id, out es))
{
var msg = new BestHTTP.ServerSentEvents.Message();
msg.Id = eventId;
msg.Data = data;
msg.Event = eventStr;
msg.Retry = TimeSpan.FromSeconds(retry);
es.OnMessageReceived(msg);
}
}
[AOT.MonoPInvokeCallback(typeof(OnWebGLEventSourceErrorDelegate))]
static void OnErrorCallback(uint id, string reason)
{
EventSource es;
if (EventSources.TryGetValue(id, out es))
{
es.CallOnError(reason, "OnErrorCallback");
es.SetClosed("OnError");
EventSources.Remove(id);
}
try
{
ES_Release(id);
}
catch (Exception ex)
{
HTTPManager.Logger.Exception("EventSource", "ES_Release", ex);
}
}
#endif
#endregion
#region WebGL Interface
#if UNITY_WEBGL && !UNITY_EDITOR
[DllImport("__Internal")]
static extern uint ES_Create(string url, bool withCred, OnWebGLEventSourceOpenDelegate onOpen, OnWebGLEventSourceMessageDelegate onMessage, OnWebGLEventSourceErrorDelegate onError);
[DllImport("__Internal")]
static extern void ES_Close(uint id);
[DllImport("__Internal")]
static extern void ES_Release(uint id);
#endif
#endregion
}
}
#endif
| 31.412308 | 189 | 0.52919 | [
"MIT"
] | zhoumingliang/test-git-subtree | Assets/RotateMe/Scripts/Best HTTP (Pro)/BestHTTP/ServerSentEvents/EventSource.cs | 20,512 | C# |
#region Copyright & License
// Copyright © 2012 - 2020 François Chabot
//
// 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.
#endregion
using System.Reflection;
using Be.Stateless.BizTalk.Stream;
using Be.Stateless.BizTalk.Unit.MicroComponent;
using Be.Stateless.Resources;
using FluentAssertions;
using Microsoft.BizTalk.Message.Interop;
using Moq;
using Xunit;
namespace Be.Stateless.BizTalk.MicroComponent
{
public class ZipDecoderFixture : MicroComponentFixture<ZipDecoder>
{
[Fact]
public void WrapsMessageStreamInZipInputStream()
{
var bodyPart = new Mock<IBaseMessagePart>();
bodyPart.Setup(p => p.GetOriginalDataStream()).Returns(ResourceManager.Load(Assembly.GetExecutingAssembly(), "Be.Stateless.BizTalk.Resources.Zip.message.zip"));
bodyPart.SetupProperty(p => p.Data);
MessageMock.Setup(m => m.BodyPart).Returns(bodyPart.Object);
var sut = new ZipDecoder();
sut.Execute(PipelineContextMock.Object, MessageMock.Object);
MessageMock.Object.BodyPart.Data.Should().BeOfType<ZipInputStream>();
}
}
}
| 32.957447 | 163 | 0.763073 | [
"Apache-2.0"
] | FrancoisHub/Be.Stateless.BizTalk.Pipeline.MicroComponents | src/Be.Stateless.BizTalk.Pipeline.MicroComponents.Tests/MicroComponent/ZipDecoderFixture.cs | 1,553 | C# |
namespace SadConsole.Themes
{
using System;
using System.Collections.Generic;
using System.Runtime.Serialization;
using SadConsole.Controls;
/// <summary>
/// The library of themes. Holds the themes of all controls.
/// </summary>
[DataContract]
public class Library
{
private static Library _libraryInstance;
private Colors _colors;
private Dictionary<System.Type, ThemeBase> _controlThemes;
/// <summary>
/// If a control does not specify its own theme, the theme from this property will be used.
/// </summary>
public static Library Default
{
get
{
if (_libraryInstance != null) return _libraryInstance;
_libraryInstance = new Library();
_libraryInstance.ApplyDefaults();
return _libraryInstance;
}
set
{
if (null == value)
{
_libraryInstance = new Library();
_libraryInstance.ApplyDefaults();
}
else
_libraryInstance = value;
}
}
/// <summary>
/// Colors for the theme library.
/// </summary>
[DataMember]
public Colors Colors
{
get => _colors;
set
{
if (_colors == null) throw new System.NullReferenceException("Colors cannot be set to null");
_colors = value;
}
}
/// <summary>
/// Theme for <see cref="ControlsConsole"/>.
/// </summary>
[DataMember]
public ControlsConsoleTheme ControlsConsoleTheme { get; set; }
/// <summary>
/// Theme for the <see cref="Window"/> control.
/// </summary>
[DataMember]
public WindowTheme WindowTheme { get; set; }
static Library()
{
if (Default == null)
{
Default = new Library(false);
Default.ApplyDefaults();
}
}
/// <summary>
/// Seeds the library with the default themes.
/// </summary>
public void ApplyDefaults()
{
ControlsConsoleTheme = new ControlsConsoleTheme();
WindowTheme = new WindowTheme();
SetControlTheme(typeof(ScrollBar), new ScrollBarTheme());
SetControlTheme(typeof(SelectionButton), new ButtonTheme());
SetControlTheme(typeof(Button), new ButtonTheme());
SetControlTheme(typeof(CheckBox), new CheckBoxTheme());
SetControlTheme(typeof(ListBox), new ListBoxTheme(new ScrollBarTheme()));
SetControlTheme(typeof(ProgressBar), new ProgressBarTheme());
SetControlTheme(typeof(RadioButton), new RadioButtonTheme());
SetControlTheme(typeof(TextBox), new TextBoxTheme());
SetControlTheme(typeof(DrawingSurface), new DrawingSurfaceTheme());
SetControlTheme(typeof(Label), new LabelTheme());
}
/// <summary>
/// Creates a new instance of the theme library with default themes.
/// </summary>
public Library()
{
_colors = new Colors();
_controlThemes = new Dictionary<Type, ThemeBase>(15);
}
/// <summary>
/// Create the instance for the singleton.
/// </summary>
/// <param name="_">Not used.</param>
private Library(bool _) => _colors = new Colors();
/// <summary>
/// Creates and returns a theme based on the type of control provided.
/// </summary>
/// <param name="control">The control instance</param>
/// <returns>A theme that is associated with the control.</returns>
public ThemeBase GetControlTheme(Type control)
{
if (_controlThemes.ContainsKey(control))
return _controlThemes[control].Clone();
throw new System.Exception("Control does not have an associated theme.");
}
/// <summary>
/// Sets a control theme based on the control type.
/// </summary>
/// <param name="control">The control type to register a theme.</param>
/// <param name="theme">The theme to associate with the control.</param>
/// <returns>A theme that is associated with the control.</returns>
public void SetControlTheme(Type control, ThemeBase theme)
{
if (null == control) throw new ArgumentNullException(nameof(control), "Cannot use a null control type");
_controlThemes[control] = theme ?? throw new ArgumentNullException(nameof(theme), "Cannot set the theme of a control to null");
}
/// <summary>
/// Clones this library.
/// </summary>
/// <returns>A new instance of a library.</returns>
public Library Clone()
{
var library = new Library();
foreach (var item in _controlThemes)
library.SetControlTheme(item.Key, item.Value);
library._colors = _colors.Clone();
return library;
}
}
}
| 33.246835 | 139 | 0.552065 | [
"MIT"
] | SoRRiSoJa/SadConsole | src/SadConsole/Themes/Library.cs | 5,255 | C# |
// Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved.
// Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.
namespace PInvoke
{
using System;
using System.Runtime.InteropServices;
/// <content>
/// Contains the <see cref="DeviceContextValues"/> nested type.
/// </content>
public partial class User32
{
/// <summary>
/// Values to pass to the <see cref="GetDCEx"/> method describing how to create the DC.
/// </summary>
[Flags]
public enum DeviceContextValues : uint
{
/// <summary>
/// Returns a DC that corresponds to the window rectangle rather than the client rectangle.
/// </summary>
DCX_WINDOW = 0x00000001,
/// <summary>
/// Returns a DC from the cache, rather than the OWNDC or CLASSDC window.
/// Essentially overrides CS_OWNDC and CS_CLASSDC.
/// </summary>
DCX_CACHE = 0x00000002,
/// <summary>
/// Does not reset the attributes of this DC to the default attributes when this DC is released.
/// </summary>
DCX_NORESETATTRS = 0x00000004,
/// <summary>
/// Excludes the visible regions of all child windows below the window identified by hWnd.
/// </summary>
DCX_CLIPCHILDREN = 0x00000008,
/// <summary>
/// Excludes the visible regions of all sibling windows above the window identified by hWnd.
/// </summary>
DCX_CLIPSIBLINGS = 0x00000010,
/// <summary>
/// Uses the visible region of the parent window. The parent's WS_CLIPCHILDREN and CS_PARENTDC style bits are ignored.
/// The origin is set to the upper-left corner of the window identified by hWnd.
/// </summary>
DCX_PARENTCLIP = 0x00000020,
/// <summary>
/// The clipping region identified by hrgnClip is excluded from the visible region of the returned DC.
/// </summary>
DCX_EXCLUDERGN = 0x00000040,
/// <summary>
/// The clipping region identified by hrgnClip is intersected with the visible region of the returned DC.
/// </summary>
DCX_INTERSECTRGN = 0x00000080,
/// <summary>
/// Undocumented
/// </summary>
/// <remarks>Reserved; do not use.</remarks>
DCX_EXCLUDEUPDATE = 0x00000100,
/// <summary>
/// Returns a region that includes the window's update region.
/// </summary>
/// <remarks>Reserved; do not use (it is documented on Windows CE GetDCEx function on MSDN).</remarks>
DCX_INTERSECTUPDATE = 0x00000200,
/// <summary>
/// Allows drawing even if there is a LockWindowUpdate call in effect
/// that would otherwise exclude this window. Used for drawing during tracking.
/// </summary>
DCX_LOCKWINDOWUPDATE = 0x00000400,
/// <summary>
/// Undocumented, something internal related to WM_NCPAINT message and not using <see cref="DCX_CACHE"/> on updates.
/// </summary>
/// <remarks>Internal; do not use</remarks>
DCX_USESTYLE = 0x00010000,
/// <summary>
/// When specified with <see cref="DCX_INTERSECTUPDATE"/>, causes the DC to be completely validated.
/// Using this function with both <see cref="DCX_INTERSECTUPDATE"/> and <see cref="DCX_VALIDATE"/> is identical to using the <see cref="BeginPaint(IntPtr, PAINTSTRUCT*)"/> function.
/// </summary>
/// <remarks>Reserved; do not use (it is documented on Windows CE GetDCEx function on MSDN).</remarks>
DCX_VALIDATE = 0x00200000,
}
}
} | 42.638298 | 193 | 0.58508 | [
"MIT"
] | jmelosegui/pinvoke | src/User32.Desktop/User32+DeviceContextValues.cs | 4,010 | C# |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Runtime.InteropServices;
internal static partial class Interop
{
internal static partial class mincore
{
/// <summary>
/// Make sure to keep in sync with EventProvider.EventData.
/// </summary>
public struct EventData
{
internal unsafe ulong Ptr;
internal uint Size;
internal uint Reserved;
}
[DllImport(Interop.Libraries.Eventing)]
internal unsafe static extern int EventWriteTransfer(
ulong registrationHandle,
void* eventDescriptor,
Guid* activityId,
Guid* relatedActivityId,
int userDataCount,
EventData* userData
);
}
}
| 29.0625 | 101 | 0.597849 | [
"MIT"
] | 690486439/corefx | src/Common/src/Interop/Windows/mincore/Interop.EventWriteTransfer.cs | 930 | C# |
using Markdraw.Delta;
namespace Markdraw.Tree
{
public class ImageLeaf : Leaf
{
private ImageInsert _correspondingInsert;
public override ImageInsert CorrespondingInsert { get => _correspondingInsert; }
public ImageLeaf(ImageInsert imageInsert) : this(imageInsert, null, 0) { }
public ImageLeaf(ImageInsert imageInsert, DeltaTree deltaTree, int i) : base(deltaTree, i)
{
_correspondingInsert = imageInsert;
}
public override string ToString()
{
if (ParentTree is not null && ParentTree.HasI)
{
return $@"<img src=""{CorrespondingInsert.Url}"" alt=""{CorrespondingInsert.Alt}"" i=""{I}"" contenteditable=""false"" />"; ;
}
return $@"<img src=""{CorrespondingInsert.Url}"" alt=""{CorrespondingInsert.Alt}"" />";
}
}
}
| 29.62963 | 133 | 0.665 | [
"MIT"
] | jonathanjameswatson/markdraw | Markdraw.Tree/ImageLeaf.cs | 800 | C# |
using System;
using System.Collections.Generic;
using Xamarin.Forms;
using AudioCore.Common;
using AudioCore.Input;
using AudioCore.Output;
namespace AudioCore.Demo
{
public partial class TestTonePage : DemoPage
{
#region Private Fields
/// <summary>
/// The test tone input.
/// </summary>
private TestToneInput _testToneInput;
/// <summary>
/// The platform default audio output.
/// </summary>
private PlatformOutput _output;
/// <summary>
/// The current playback status, <c>true</c> if currently playing, otherwise <c>false</c>.
/// </summary>
private bool _playing;
/// <summary>
/// The type of test tone.
/// </summary>
private TestToneInput.ToneType _toneType = TestToneInput.ToneType.SineWave;
/// <summary>
/// The test tone frequency.
/// </summary>
private int _frequency = 1000;
/// <summary>
/// The test tone volume.
/// </summary>
private int _volume;
/// <summary>
/// If the phase should be reversed every other channel.
/// </summary>
private bool _reversePhase;
#endregion
#region Constructor and Page Lifecycle Events
/// <summary>
/// Initializes a new instance of the <see cref="T:AudioCore.Demo.TestTonePage"/> class.
/// </summary>
public TestTonePage()
{
InitializeComponent();
// Populate the output device list and select the default device
List<AudioDevice> devices = PlatformOutput.GetDevices();
outputPicker.ItemsSource = devices;
outputPicker.ItemDisplayBinding = new Binding("Name");
outputPicker.SelectedItem = devices.Find(x => x.Default == true);
}
/// <summary>
/// Disposes all resources held by the page, stopping audio playback.
/// </summary>
public override void Dispose()
{
if (_output != null)
{
_output.Dispose();
}
}
#endregion
#region UI Methods
/// <summary>
/// Handles the test tone type being changed.
/// </summary>
/// <param name="sender">The sending object.</param>
/// <param name="e">The event arguments.</param>
private void ToneChanged(object sender, EventArgs e)
{
switch (typePicker.Items[typePicker.SelectedIndex])
{
default:
_toneType = TestToneInput.ToneType.SineWave;
break;
case "Square Wave":
_toneType = TestToneInput.ToneType.SquareWave;
break;
case "Sawtooth Wave":
_toneType = TestToneInput.ToneType.SawtoothWave;
break;
case "Triangle Wave":
_toneType = TestToneInput.ToneType.TriangleWave;
break;
}
if (_playing)
{
_testToneInput.Type = _toneType;
}
}
/// <summary>
/// Handles the frequency slider value being changed.
/// </summary>
/// <param name="sender">The sending object.</param>
/// <param name="e">The event arguments.</param>
private void FrequencyChanged(object sender, EventArgs e)
{
_frequency = (int)frequencySlider.Value;
if (_playing)
{
_testToneInput.Frequency = _frequency;
}
}
/// <summary>
/// Handles the volume slider value being changed.
/// </summary>
/// <param name="sender">The sending object.</param>
/// <param name="e">The event arguments.</param>
private void VolumeChanged(object sender, EventArgs e)
{
_volume = (int)(Math.Log10(volumeSlider.Value) * 20);
if (_playing)
{
_testToneInput.Volume = _volume;
}
}
/// <summary>
/// Handles the reverse phase check box being checked and unchecked.
/// </summary>
/// <param name="sender">The sending object.</param>
/// <param name="e">The event arguments.</param>
private void ReversePhaseChanged(object sender, CheckedChangedEventArgs e)
{
_reversePhase = phaseCheckBox.IsChecked;
if (_playing)
{
_testToneInput.ReversePhase = _reversePhase;
}
}
/// <summary>
/// Handles the play/stop button being clicked or tapped.
/// </summary>
/// <param name="sender">The sending object.</param>
/// <param name="e">The event arguments.</param>
private void PlaybackButtonClicked(object sender, EventArgs e)
{
// Start playback if not currently playing, otherwise stop it
if (!_playing)
{
StartPlayback();
}
else
{
StopPlayback();
}
}
#endregion
#region Playback Methods
/// <summary>
/// Starts the playback of the test tone input.
/// </summary>
private void StartPlayback()
{
// Try to start playback, catching any errors
try
{
// Create the platform audio output
_output = new PlatformOutput(((AudioDevice)outputPicker.SelectedItem).ID);
// Create the test tone input using the specified frequency and volume, using the output sample rate and channel count
_testToneInput = new TestToneInput(_output.Channels, _output.SampleRate)
{
Frequency = _frequency,
Type = _toneType,
Volume = _volume,
ReversePhase = _reversePhase
};
// Add the test tone input to the output
_output.AddInput(_testToneInput);
// Start playback
_output.Start();
// Set to currently playing, changing the button text
_playing = true;
playbackButton.Text = "Stop";
// Disable the device picker
outputPicker.IsEnabled = false;
}
catch (Exception e) // If an error occurs
{
// Release test tone input and audio output, disposing it first if required
_testToneInput = null;
if (_output != null)
{
_output.Dispose();
_output = null;
}
// Display error message
DisplayAlert("Unable to start playback", e.Message, "OK");
}
}
/// <summary>
/// Stops playback.
/// </summary>
private void StopPlayback()
{
// Stop playback
_output.Stop();
// Dispose the output
_output.Dispose();
// Release the output and test tone input
_output = null;
_testToneInput = null;
// Set to stopped, changing the button text
_playing = false;
playbackButton.Text = "Play";
// Eable the device picker
outputPicker.IsEnabled = true;
}
#endregion
}
} | 33.377193 | 134 | 0.515243 | [
"Apache-2.0"
] | orryverducci/AudioCore | AudioCore.Demo/TestTonePage.xaml.cs | 7,612 | C# |
using System;
using System.Collections.Generic;
using System.Text;
namespace Section1Video4
{
public enum SecurityLevel
{
Trace = 0,
Info = 1,
Warning = 2,
Error = 3,
Critical = 4
}
public interface IReporter
{
void Report(Exception ex, string description, SecurityLevel level);
}
}
| 17.047619 | 75 | 0.600559 | [
"MIT"
] | PacktMrunal/Modern-App-Development-with-C-8-and-.NET-Core-3.0 | Section 1/Section1Video4/Section1Video4/IReporter.cs | 360 | C# |
using System;
using System.Linq;
using Gdk;
using NLog;
namespace QS.Project.Search.GtkUI
{
[System.ComponentModel.ToolboxItem(true)]
public partial class OneEntrySearchView : Gtk.Bin
{
private static Logger logger = LogManager.GetCurrentClassLogger();
#region Настройка
/// <summary>
/// Задержка в передачи запроса на поиск во view model.
/// Измеряется в милсекундах.
/// </summary>
public static uint QueryDelay = 0;
#endregion
SearchViewModel viewModel;
uint timerId;
public OneEntrySearchView(SearchViewModel viewModel)
{
this.Build();
this.viewModel = viewModel;
entrySearch.Changed += EntSearchText_Changed;
}
void EntSearchText_Changed(object sender, EventArgs e)
{
if(QueryDelay != 0) {
GLib.Source.Remove(timerId);
timerId = GLib.Timeout.Add(QueryDelay, new GLib.TimeoutHandler(RunSearch));
} else
RunSearch();
}
bool RunSearch()
{
var allFields = entrySearch.Text.Split(new char[] {' '}, StringSplitOptions.RemoveEmptyEntries);
viewModel.SearchValues = allFields;
timerId = 0;
return false;
}
protected void OnButtonSearchClearClicked(object sender, EventArgs e)
{
viewModel.SearchValues = new string[0];
entrySearch.Text = string.Empty;
}
public override void Destroy()
{
GLib.Source.Remove(timerId);
base.Destroy();
}
protected void OnEntrySearchWidgetEvent(object o, Gtk.WidgetEventArgs args)
{
if(args.Event.Type == EventType.KeyPress) {
EventKey eventKey = args.Args.OfType<EventKey>().FirstOrDefault();
if(eventKey != null && (eventKey.Key == Gdk.Key.Return || eventKey.Key == Gdk.Key.KP_Enter)) {
GLib.Source.Remove(timerId);
RunSearch();
}
}
}
}
} | 24.169014 | 99 | 0.700466 | [
"Apache-2.0"
] | opopve/QSProjects | QS.Project.Gtk/Project.Search.GtkUI/OneEntrySearchView.cs | 1,782 | C# |
using System;
// https://docs.microsoft.com/en-us/windows/win32/cimwin32prov/win32-videocontroller
namespace Hardware.Info.Net6
{
/// <summary>
/// WMI class: Win32_VideoController
/// </summary>
public class VideoController
{
/// <summary>
/// Memory size of the video adapter.
/// </summary>
public UInt32 AdapterRAM { get; set; }
/// <summary>
/// Short description of the object.
/// </summary>
public string Caption { get; set; } = string.Empty;
/// <summary>
/// Number of bits used to display each pixel.
/// </summary>
public UInt32 CurrentBitsPerPixel { get; set; }
/// <summary>
/// Current number of horizontal pixels.
/// </summary>
public UInt32 CurrentHorizontalResolution { get; set; }
/// <summary>
/// Number of colors supported at the current resolution.
/// </summary>
public UInt64 CurrentNumberOfColors { get; set; }
/// <summary>
/// Frequency at which the video controller refreshes the image for the monitor.
/// A value of 0 (zero) indicates the default rate is being used, while 0xFFFFFFFF indicates the optimal rate is being used.
/// </summary>
public UInt32 CurrentRefreshRate { get; set; }
/// <summary>
/// Current number of vertical pixels.
/// </summary>
public UInt32 CurrentVerticalResolution { get; set; }
/// <summary>
/// Description of the object.
/// </summary>
public string Description { get; set; } = string.Empty;
/// <summary>
/// Last modification date and time of the currently installed video driver.
/// </summary>
public string DriverDate { get; set; } = string.Empty;
/// <summary>
/// Version number of the video driver.
/// </summary>
public string DriverVersion { get; set; } = string.Empty;
/// <summary>
/// Manufacturer of the video controller.
/// </summary>
public string Manufacturer { get; set; } = string.Empty;
/// <summary>
/// Maximum refresh rate of the video controller in hertz.
/// </summary>
public UInt32 MaxRefreshRate { get; set; }
/// <summary>
/// Minimum refresh rate of the video controller in hertz.
/// </summary>
public UInt32 MinRefreshRate { get; set; }
/// <summary>
/// Label by which the object is known.
/// </summary>
public string Name { get; set; } = string.Empty;
/// <summary>
/// Current resolution, color, and scan mode settings of the video controller.
/// </summary>
public string VideoModeDescription { get; set; } = string.Empty;
/// <summary>
/// Free-form string describing the video processor.
/// </summary>
public string VideoProcessor { get; set; } = string.Empty;
public override string ToString() =>
$"Caption: {Caption}{Environment.NewLine}" +
$"Description: {Description}{Environment.NewLine}" +
$"Name: {Name}{Environment.NewLine}" +
$"Manufacturer: {Manufacturer}{Environment.NewLine}" +
$"AdapterRAM: {AdapterRAM}{Environment.NewLine}" +
$"CurrentBitsPerPixel: {CurrentBitsPerPixel}{Environment.NewLine}" +
$"CurrentHorizontalResolution: {CurrentHorizontalResolution}{Environment.NewLine}" +
$"CurrentNumberOfColors: {CurrentNumberOfColors}{Environment.NewLine}" +
$"CurrentRefreshRate: {CurrentRefreshRate}{Environment.NewLine}" +
$"CurrentVerticalResolution: {CurrentVerticalResolution}{Environment.NewLine}" +
$"DriverDate: {DriverDate}{Environment.NewLine}" +
$"DriverVersion: {DriverVersion}{Environment.NewLine}" +
$"MaxRefreshRate: {MaxRefreshRate}{Environment.NewLine}" +
$"MinRefreshRate: {MinRefreshRate}{Environment.NewLine}" +
$"VideoModeDescription: {VideoModeDescription}{Environment.NewLine}" +
$"VideoProcessor: {VideoProcessor}{Environment.NewLine}";
}
}
| 37.910714 | 132 | 0.594442 | [
"MIT"
] | tjdskaqks/Hardware.Info | Hardware.Info.Net6/Components/VideoController.cs | 4,248 | C# |
/* ====================================================================
Copyright (C) 2004-2008 fyiReporting Software, LLC
This file is part of the fyiReporting RDL project.
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.
For additional information, email info@fyireporting.com or visit
the website www.fyiReporting.com.
*/
using System;
using System.Collections;
using System.IO;
using System.Reflection;
using fyiReporting.RDL;
namespace fyiReporting.RDL
{
/// <summary>
/// IsMissing attribute
/// </summary>
[Serializable]
internal class FunctionFieldIsMissing : FunctionField
{
/// <summary>
/// Determine if value of Field is available
/// </summary>
public FunctionFieldIsMissing(Field fld) : base(fld)
{
}
public FunctionFieldIsMissing(string method) : base(method)
{
}
public override TypeCode GetTypeCode()
{
return TypeCode.Boolean;
}
public override bool IsConstant()
{
return false;
}
public override IExpr ConstantOptimization()
{
return this; // not a constant
}
//
public override object Evaluate(Report rpt, Row row)
{
return EvaluateBoolean(rpt, row);
}
public override double EvaluateDouble(Report rpt, Row row)
{
return EvaluateBoolean(rpt, row)? 1: 0;
}
public override decimal EvaluateDecimal(Report rpt, Row row)
{
return EvaluateBoolean(rpt, row)? 1m: 0m;
}
public override string EvaluateString(Report rpt, Row row)
{
return EvaluateBoolean(rpt, row)? "True": "False";
}
public override DateTime EvaluateDateTime(Report rpt, Row row)
{
return DateTime.MinValue;
}
public override bool EvaluateBoolean(Report rpt, Row row)
{
object o = base.Evaluate(rpt, row);
return o == null? true: false;
}
}
}
| 23.43299 | 75 | 0.687198 | [
"Apache-2.0"
] | gregberns/ZipRdlProjectDev410 | src/RdlEngine/Functions/FunctionFieldIsMissing.cs | 2,273 | C# |
using System.Linq;
using Model = Discord.API.AuditLog;
using EntryModel = Discord.API.AuditLogEntry;
namespace Discord.Rest
{
public class ChannelUpdateAuditLogData : IAuditLogData
{
private ChannelUpdateAuditLogData(ulong id, ChannelInfo before, ChannelInfo after)
{
ChannelId = id;
Before = before;
After = after;
}
internal static ChannelUpdateAuditLogData Create(BaseDiscordClient discord, Model log, EntryModel entry)
{
var changes = entry.Changes;
var nameModel = changes.FirstOrDefault(x => x.ChangedProperty == "name");
var topicModel = changes.FirstOrDefault(x => x.ChangedProperty == "topic");
var bitrateModel = changes.FirstOrDefault(x => x.ChangedProperty == "bitrate");
var userLimitModel = changes.FirstOrDefault(x => x.ChangedProperty == "user_limit");
string oldName = nameModel?.OldValue?.ToObject<string>(),
newName = nameModel?.NewValue?.ToObject<string>();
string oldTopic = topicModel?.OldValue?.ToObject<string>(),
newTopic = topicModel?.NewValue?.ToObject<string>();
int? oldBitrate = bitrateModel?.OldValue?.ToObject<int>(),
newBitrate = bitrateModel?.NewValue?.ToObject<int>();
int? oldLimit = userLimitModel?.OldValue?.ToObject<int>(),
newLimit = userLimitModel?.NewValue?.ToObject<int>();
var before = new ChannelInfo(oldName, oldTopic, oldBitrate, oldLimit);
var after = new ChannelInfo(newName, newTopic, newBitrate, newLimit);
return new ChannelUpdateAuditLogData(entry.TargetId.Value, before, after);
}
public ulong ChannelId { get; }
public ChannelInfo Before { get; }
public ChannelInfo After { get; }
}
}
| 40.804348 | 112 | 0.63399 | [
"MIT"
] | CasinoBoyale/Discord.Net | src/Discord.Net.Rest/Entities/AuditLogs/DataTypes/ChannelUpdateAuditLogData.cs | 1,879 | C# |
// System
using System;
using System.Collections;
using System.Collections.Generic;
// Unity Engine
using UnityEditor;
using UnityEngine;
#if UNITY_EDITOR
[InitializeOnLoad]
public class PrettyDebug : ILogHandler {
public PrettyDebug() {
Debug.unityLogger.logHandler = this;
}
#region Instance Methods
public void LogException(Exception exception, UnityEngine.Object context) {
Debug.LogException(exception, context);
}
public void LogFormat(LogType logType, UnityEngine.Object context, string format, params object[] args) {
string s = "[" + context.name + "] " + format;
switch (logType) {
case LogType.Assert:
Debug.LogAssertionFormat(context, s, args);
return;
case LogType.Error:
Debug.LogErrorFormat(context, s, args);
return;
case LogType.Exception:
Debug.LogErrorFormat(context, s, args);
return;
case LogType.Log:
Debug.LogFormat(context, s, args);
return;
case LogType.Warning:
Debug.LogWarningFormat(context, s, args);
return;
default:
Debug.LogWarning("[Pretty Debug] Could not find handler for LogType!");
return;
}
}
#endregion
}
#endif | 25 | 109 | 0.581429 | [
"MIT"
] | oliviasculley/nervv | Assets/Scripts/Debug/PrettyDebug.cs | 1,402 | C# |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics.ContractsLight;
using System.IO;
using System.Threading.Tasks;
using BuildXL.Cache.ContentStore.Hashing;
using BuildXL.Native.IO;
using BuildXL.Storage;
using BuildXL.Utilities;
using BuildXL.Utilities.Collections;
using BuildXL.Utilities.Tasks;
using static BuildXL.Utilities.FormattableStringEx;
namespace BuildXL.Engine.Cache.Artifacts
{
/// <summary>
/// Trivial artifact content cache implementation which is initially empty, and stores content only in memory.
/// Since all content is stored in memory, this implementation is only suitable for testing.
/// </summary>
/// <remarks>
/// This implementation, despite having a simple map of hash -> bytes in memory, models a distinct 'local' vs. 'remote'
/// cache. This is used for some testing scenarios aroung e.g. zig-zag, in which the indication of which content was brought local
/// (from somewhere remote) is significant.
/// - After a store operation, a hash is then available locally and remotely (regardless of where it was before).
/// - After a 'load-available' operation, a hash is marked as local if it was only remote.
/// - Materialize operations require content to be local (note that this is stricter than the BuildCache behavior, but the strictness is very nice for testing).
/// </remarks>
public sealed class InMemoryArtifactContentCache : IArtifactContentCacheForTest
{
private readonly PipExecutionContext m_context;
private readonly object m_lock;
private readonly Dictionary<ContentHash, CacheEntry> m_content;
private ConcurrentDictionary<string, FileRealizationMode> m_pathRealizationModes;
private sealed class CacheEntry
{
public readonly byte[] Content;
/// <remarks>
/// We only need to model local vs. remote storage for testing scenarios in which 'bytes transferred' / 'files transferred' metrics
/// need to be authentic.
/// </remarks>
public CacheSites Sites;
public CacheEntry(byte[] content, CacheSites sites)
{
Content = content;
Sites = sites;
}
}
/// <nodoc />
public InMemoryArtifactContentCache(PipExecutionContext context)
: this(context, new object(), new Dictionary<ContentHash, CacheEntry>())
{
Contract.Requires(context != null);
}
/// <inheritdoc />
public FileRealizationMode GetRealizationMode(string path)
{
return m_pathRealizationModes[path];
}
/// <inheritdoc />
public void ReinitializeRealizationModeTracking()
{
m_pathRealizationModes = new ConcurrentDictionary<string, FileRealizationMode>(StringComparer.OrdinalIgnoreCase);
}
/// <nodoc />
private InMemoryArtifactContentCache(
PipExecutionContext context,
object syncLock,
Dictionary<ContentHash, CacheEntry> content)
{
Contract.Requires(context != null);
Contract.Requires(syncLock != null);
Contract.Requires(content != null);
m_context = context;
m_lock = syncLock;
m_content = content;
Analysis.IgnoreArgument(m_context);
}
/// <summary>
/// Wraps the content cache's content for use with another execution context
/// </summary>
public InMemoryArtifactContentCache WrapForContext(PipExecutionContext context)
{
return new InMemoryArtifactContentCache(context, m_lock, m_content);
}
/// <inheritdoc />
public void Clear()
{
m_content.Clear();
m_pathRealizationModes?.Clear();
}
/// <inheritdoc />
public void DiscardContentIfPresent(ContentHash content, CacheSites sitesToDiscardFrom)
{
lock (m_lock)
{
CacheEntry entry;
if (m_content.TryGetValue(content, out entry))
{
CacheSites newSites = entry.Sites & ~sitesToDiscardFrom;
if (newSites == CacheSites.None)
{
m_content.Remove(content);
}
else
{
entry.Sites = newSites;
}
}
}
}
/// <inheritdoc />
public CacheSites FindContainingSites(ContentHash hash)
{
lock (m_lock)
{
CacheEntry entry;
bool available = m_content.TryGetValue(hash, out entry);
if (available)
{
return entry.Sites;
}
else
{
return CacheSites.None;
}
}
}
/// <inheritdoc />
public Task<Possible<ContentAvailabilityBatchResult, Failure>> TryLoadAvailableContentAsync(IReadOnlyList<ContentHash> hashes)
{
return Task.Run<Possible<ContentAvailabilityBatchResult, Failure>>(
() =>
{
lock (m_lock)
{
bool allAvailable = true;
var results = new ContentAvailabilityResult[hashes.Count];
for (int i = 0; i < hashes.Count; i++)
{
CacheEntry entry;
bool available = m_content.TryGetValue(hashes[i], out entry);
long bytesTransferredRemotely;
// The content is now in the local site, if it wasn't already.
if (available)
{
bytesTransferredRemotely = (entry.Sites & CacheSites.Local) == 0
? entry.Content.Length
: 0;
entry.Sites |= CacheSites.Local;
}
else
{
bytesTransferredRemotely = 0;
}
results[i] = new ContentAvailabilityResult(hashes[i], isAvailable: available, bytesTransferred: bytesTransferredRemotely, sourceCache: "InMemoryCache");
allAvailable &= available;
}
return new ContentAvailabilityBatchResult(
ReadOnlyArray<ContentAvailabilityResult>.FromWithoutCopy(results),
allContentAvailable: allAvailable);
}
});
}
/// <inheritdoc />
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2000:DisposeObjectsBeforeLosingScope")]
public Task<Possible<Stream, Failure>> TryOpenContentStreamAsync(ContentHash contentHash)
{
return Task.Run<Possible<Stream, Failure>>(
() =>
{
lock (m_lock)
{
CacheEntry entry;
if (m_content.TryGetValue(contentHash, out entry))
{
if ((entry.Sites & CacheSites.Local) == 0)
{
return new Failure<string>("Content is available in 'remote' cache but is not local. Load it locally first with TryLoadAvailableContentAsync.");
}
return new MemoryStream(entry.Content, writable: false);
}
else
{
return new Failure<string>("Content not found (locally or remotely). Store it first with TryStoreAsync.");
}
}
});
}
/// <inheritdoc />
public Task<Possible<Unit, Failure>> TryMaterializeAsync(
FileRealizationMode fileRealizationModes,
ExpandedAbsolutePath path,
ContentHash contentHash)
{
return Task.Run<Possible<Unit, Failure>>(
() =>
{
lock (m_lock)
{
CacheEntry entry;
if (m_content.TryGetValue(contentHash, out entry))
{
if ((entry.Sites & CacheSites.Local) == 0)
{
return new Failure<string>("Content is available in 'remote' cache but is not local. Load it locally first with TryLoadAvailableContentAsync.");
}
string expandedPath = path.ExpandedPath;
// IArtifactContentCache prescribes that materialization always produces a 'new' file.
var mayBeDelete = FileUtilities.TryDeletePathIfExists(expandedPath);
if (!mayBeDelete.Succeeded)
{
return mayBeDelete.Failure;
}
try
{
if (m_pathRealizationModes != null)
{
m_pathRealizationModes[expandedPath] = fileRealizationModes;
}
ExceptionUtilities.HandleRecoverableIOException(
() =>
{
Directory.CreateDirectory(Path.GetDirectoryName(expandedPath));
File.WriteAllBytes(expandedPath, entry.Content);
},
ex => { throw new BuildXLException("Failed to materialize content (content found, but couldn't write it)", ex); });
return Unit.Void;
}
catch (BuildXLException ex)
{
return new RecoverableExceptionFailure(ex);
}
}
else
{
return new Failure<string>("Content not found (locally or remotely). Store it first with TryStoreAsync.");
}
}
});
}
/// <inheritdoc />
public async Task<Possible<Unit, Failure>> TryStoreAsync(
FileRealizationMode fileRealizationModes,
ExpandedAbsolutePath path,
ContentHash contentHash)
{
Possible<ContentHash, Failure> maybeStored = await TryStoreInternalAsync(
path,
fileRealizationModes,
knownContentHash: contentHash);
return maybeStored.Then(hash => Unit.Void);
}
/// <inheritdoc />
public Task<Possible<ContentHash, Failure>> TryStoreAsync(
FileRealizationMode fileRealizationModes,
ExpandedAbsolutePath path)
{
return TryStoreInternalAsync(
path,
fileRealizationModes,
knownContentHash: null);
}
private Task<Possible<ContentHash, Failure>> TryStoreInternalAsync(
ExpandedAbsolutePath path,
FileRealizationMode fileRealizationModes,
ContentHash? knownContentHash)
{
return Task.Run<Possible<ContentHash, Failure>>(
() =>
{
lock (m_lock)
{
byte[] contentBytes = ExceptionUtilities.HandleRecoverableIOException(
() => { return File.ReadAllBytes(path.ExpandedPath); },
ex => { throw new BuildXLException("Failed to store content (couldn't read new content from disk)", ex); });
ContentHash contentHash = ContentHashingUtilities.HashBytes(contentBytes);
if (knownContentHash.HasValue && contentHash != knownContentHash.Value)
{
return new Failure<string>(I($"Stored content had an unexpected hash. (expected: {knownContentHash.Value}; actual: {contentHash})"));
}
CacheEntry entry;
if (m_content.TryGetValue(contentHash, out entry))
{
// We assume that stores of content already present somewhere still cause replication
// to both the local and remote sites. See class remarks.
entry.Sites |= CacheSites.LocalAndRemote;
return contentHash;
}
else
{
try
{
if (m_pathRealizationModes != null)
{
m_pathRealizationModes[path.ExpandedPath] = fileRealizationModes;
}
// We assume that stored content is instantly and magically replicated to some remote place.
// See class remarks.
m_content[contentHash] = new CacheEntry(contentBytes, CacheSites.LocalAndRemote);
return contentHash;
}
catch (BuildXLException ex)
{
return new RecoverableExceptionFailure(ex);
}
}
}
});
}
/// <inheritdoc />
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2000:DisposeObjectsBeforeLosingScope")]
public async Task<Possible<Unit, Failure>> TryStoreAsync(Stream content, ContentHash contentHash)
{
Possible<ContentHash, Failure> maybeStored = await TryStoreInternalAsync(content, knownContentHash: null);
return maybeStored.Then(hash => Unit.Void);
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2000:DisposeObjectsBeforeLosingScope")]
private Task<Possible<ContentHash, Failure>> TryStoreInternalAsync(Stream content, ContentHash? knownContentHash)
{
return Task.Run<Possible<ContentHash, Failure>>(
() =>
{
lock (m_lock)
{
CacheEntry entry;
if (knownContentHash.HasValue && m_content.TryGetValue(knownContentHash.Value, out entry))
{
// We assume that stores of content already present somewhere still cause replication
// to both the local and remote sites. See class remarks.
entry.Sites |= CacheSites.LocalAndRemote;
return knownContentHash.Value;
}
else
{
try
{
byte[] contentBytes = ExceptionUtilities.HandleRecoverableIOException(
() =>
{
MemoryStream memoryStream;
Stream streamToRead;
if (!content.CanSeek)
{
memoryStream = new MemoryStream();
streamToRead = memoryStream;
}
else
{
memoryStream = null;
streamToRead = content;
}
using (memoryStream)
{
if (memoryStream != null)
{
content.CopyTo(memoryStream);
memoryStream.Position = 0;
}
Contract.Assert(streamToRead.CanSeek);
Contract.Assume(streamToRead.Length <= int.MaxValue);
var length = (int)streamToRead.Length;
var contentBytesLocal = new byte[length];
int read = 0;
while (read < length)
{
int readThisIteration = streamToRead.Read(contentBytesLocal, read, length - read);
if (readThisIteration == 0)
{
throw new BuildXLException("Unexpected end of stream");
}
read += readThisIteration;
}
return contentBytesLocal;
}
},
ex => { throw new BuildXLException("Failed to read content from the provided stream in order to store it", ex); });
ContentHash contentHash = knownContentHash ?? ContentHashingUtilities.HashBytes(contentBytes);
// We assume that stored content is instantly and magically replicated to some remote place.
// See class remarks.
m_content[contentHash] = new CacheEntry(contentBytes, CacheSites.LocalAndRemote);
return contentHash;
}
catch (BuildXLException ex)
{
return new RecoverableExceptionFailure(ex);
}
}
}
});
}
}
}
| 45.138009 | 181 | 0.455767 | [
"MIT"
] | AzureMentor/BuildXL | Public/Src/Engine/Cache/Artifacts/InMemoryArtifactContentCache.cs | 19,951 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.