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
sequence | repository_name
stringlengths 7
92
| path
stringlengths 3
249
| size
int64 5
1.04M
| lang
stringclasses 2
values |
---|---|---|---|---|---|---|---|---|
using Microsoft.EntityFrameworkCore;
using TestingControllersSample.Core.Model;
namespace TestingControllersSample.Infrastructure
{
public class AppDbContext : DbContext
{
public AppDbContext(DbContextOptions<AppDbContext> dbContextOptions) :
base(dbContextOptions)
{
}
public DbSet<BrainstormSession> BrainstormSessions { get; set; }
}
}
| 24.875 | 78 | 0.713568 | [
"MIT"
] | yangzuo0621/AspNetCore.Tutorial | src/test/unit-tests/mvc-test/TestingControllersSample/Infrastructure/AppDbContext.cs | 400 | C# |
using System;
using System.Threading.Tasks;
using Acquaint.Data;
using Acquaint.Models;
using Acquaint.Util;
using CoreGraphics;
using Foundation;
using UIKit;
namespace Acquaint.Native.iOS
{
/// <summary>
/// Acquaintance table view controller. The layout for this view controller is defined almost entirely in Main.storyboard.
/// </summary>
public partial class AcquaintanceTableViewController : UITableViewController, IUIViewControllerPreviewingDelegate
{
/// <summary>
/// The acquaintance table view source.
/// </summary>
readonly AcquaintanceTableViewSource _AcquaintanceTableViewSource;
// This constructor signature is required, for marshalling between the managed and native instances of this class.
public AcquaintanceTableViewController(IntPtr handle) : base(handle)
{
_AcquaintanceTableViewSource = new AcquaintanceTableViewSource();
RefreshControl = new UIRefreshControl();
}
// The ViewDidLoad() method is called when the view is first requested by the application.
// The "async" keyword is added here to the override in order to allow other awaited async method calls inside the override to be called ascynchronously.
public override void ViewDidLoad()
{
base.ViewDidLoad();
SetTableViewProperties();
// override the back button text for AcquaintanceDetailViewController (the navigated-to view controller)
NavigationItem.BackBarButtonItem = new UIBarButtonItem("List", UIBarButtonItemStyle.Plain, null);
RefreshControl.ValueChanged += async (sender, e) => await RefreshAcquaintances();
TableView.AddSubview(RefreshControl);
}
// The ViewDidAppear() override is called after the view has appeared on the screen.
public override async void ViewDidAppear(bool animated)
{
base.ViewDidAppear(animated);
if (string.IsNullOrWhiteSpace(Settings.DataPartitionPhrase))
{
PerformSegue("PresentSetupViewControllerSegue", this);
return;
}
await RefreshAcquaintances();
}
async Task RefreshAcquaintances()
{
// ! flag to indicate how this refresh command was instantiated.
bool triggeredByPullToRefresh = false;
// Store the original offset of the TableView.
var originalOffset = new CGPoint(TableView.ContentOffset.X, TableView.ContentOffset.Y);
// If
if (RefreshControl.Refreshing)
triggeredByPullToRefresh = true;
try
{
// If this refresh has not been started by a pull-to-refresh UI action, then we need to manually set the tableview offset to SHOW the refresh indicator.
if (!triggeredByPullToRefresh)
TableView.SetContentOffset(new CGPoint(originalOffset.X, originalOffset.Y - RefreshControl.Frame.Size.Height), true);
// Starts animating the refreshing indicator, and sets its Refreshing property to true.
RefreshControl.BeginRefreshing();
// request the TableViewSource to load acquaintances
await _AcquaintanceTableViewSource.LoadAcquaintances();
// Tell the TableView to update its UI (reload the cells) because the TableViewSource has updated.
TableView.ReloadData();
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine($"Error getting acquaintances: {ex.Message}");
// present an alert about the failure
using (var alert = new UIAlertView("Error getting acquaintances", "Ensure you have a network connection, and that a valid backend service URL is present in the app settings.", null, "OK"))
{
alert.Show();
}
}
finally
{
// Starts animating the refreshing indicator, and sets its Refreshing property to false.
RefreshControl.EndRefreshing();
// If this refresh has not been started by a pull-to-refresh UI action, then we need to manually set the tableview offset to HIDE the refresh indicator.
if (!triggeredByPullToRefresh)
TableView.SetContentOffset(originalOffset, true);
}
}
/// <summary>
/// Sets some table view properties.
/// </summary>
void SetTableViewProperties()
{
TableView.Source = _AcquaintanceTableViewSource;
TableView.AllowsSelection = true;
TableView.RowHeight = 60;
}
// The PrepareForSegue() override is called when a segue has been activated, but before it executes.
public override void PrepareForSegue(UIStoryboardSegue segue, NSObject sender)
{
// Determine segue action by segue identifier.
// Note that these segues are defined in Main.storyboard.
switch (segue.Identifier)
{
case "NewAcquaintanceSegue":
// get the destination viewcontroller from the segue
var acquaintanceEditViewController = segue.DestinationViewController as AcquaintanceEditViewController;
// instantiate new Acquaintance and assign to viewcontroller
acquaintanceEditViewController.Acquaintance = null;
break;
case "AcquaintanceDetailSegue":
// the selected index path
var indexPath = TableView.IndexPathForSelectedRow;
// the index of the item in the collection that corresponds to the selected cell
var itemIndex = indexPath.Row;
// get the destination viewcontroller from the segue
var acquaintanceDetailViewController = segue.DestinationViewController as AcquaintanceDetailViewController;
// if the detaination viewcontrolller is not null
if (acquaintanceDetailViewController != null && TableView.Source != null)
{
// set the acquaintance on the view controller
acquaintanceDetailViewController.Acquaintance = ((AcquaintanceTableViewSource)TableView.Source).Acquaintances[itemIndex];
}
break;
}
}
/// <summary>
/// Called when the iOS interface environment changes. We're using it here to detect whether or not 3D Touch capabiliies are available on the device.
/// </summary>
/// <param name="previousTraitCollection">Previous trait collection.</param>
public override void TraitCollectionDidChange(UITraitCollection previousTraitCollection)
{
base.TraitCollectionDidChange(previousTraitCollection);
// If 3D Touch (ForceTouch) is available, then register a IUIViewControllerPreviewingDelegate, which in this case is this very class because we're implementing IUIViewControllerPreviewingDelegate.
// You could put the IUIViewControllerPreviewingDelegate implementation in another class if you wanted to. Then you'd pass an instance of it, instead of "this".
if (TraitCollection.ForceTouchCapability == UIForceTouchCapability.Available)
{
RegisterForPreviewingWithDelegate(this, View);
}
}
/// <summary>
/// Gets the view controller that will be displayed for a 3D Touch preview "peek".
/// </summary>
/// <returns>The view controller for preview.</returns>
/// <param name="previewingContext">Previewing context.</param>
/// <param name="location">Location.</param>
public UIViewController GetViewControllerForPreview(IUIViewControllerPreviewing previewingContext, CoreGraphics.CGPoint location)
{
// Obtain the index path and the cell that was pressed.
var indexPath = TableView.IndexPathForRowAtPoint(location);
if (indexPath == null)
return null;
// get the cell that is being pressed for preview "peeking"
var cell = TableView.CellAt(indexPath);
if (cell == null)
return null;
// Create a detail view controller and set its properties.
var detailViewController = Storyboard.InstantiateViewController("AcquaintanceDetailViewController") as AcquaintanceDetailViewController;
if (detailViewController == null)
return null;
// set the acquaintance on the view controller
detailViewController.Acquaintance = _AcquaintanceTableViewSource.Acquaintances[indexPath.Row];
// set the frame on the screen that will NOT be blurred out during the preview "peek"
previewingContext.SourceRect = cell.Frame;
return detailViewController;
}
/// <summary>
/// Commits the view controller that will displayed when a 3D Touch gesture is fully depressed, beyond just the preview.
/// </summary>
/// <param name="previewingContext">Previewing context.</param>
/// <param name="viewControllerToCommit">View controller to commit.</param>
public void CommitViewController(IUIViewControllerPreviewing previewingContext, UIViewController viewControllerToCommit)
{
// Show the view controller that is being preview "peeked".
// Instead, you could do whatever you want here, such as commit some other view controller than the one that is being "peeked".
ShowViewController(viewControllerToCommit, this);
}
}
}
| 39.223256 | 199 | 0.754891 | [
"MIT"
] | aoffpo/com.munxie.imtest | App/Acquaint.Native/Acquaint.Native.iOS/AcquaintanceTableViewController.cs | 8,433 | 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 appflow-2020-08-23.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
using System.Xml.Serialization;
using Amazon.Appflow.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using ThirdParty.Json.LitJson;
namespace Amazon.Appflow.Model.Internal.MarshallTransformations
{
/// <summary>
/// UpsolverS3OutputFormatConfig Marshaller
/// </summary>
public class UpsolverS3OutputFormatConfigMarshaller : IRequestMarshaller<UpsolverS3OutputFormatConfig, JsonMarshallerContext>
{
/// <summary>
/// Unmarshaller the response from the service to the response class.
/// </summary>
/// <param name="requestObject"></param>
/// <param name="context"></param>
/// <returns></returns>
public void Marshall(UpsolverS3OutputFormatConfig requestObject, JsonMarshallerContext context)
{
if(requestObject.IsSetAggregationConfig())
{
context.Writer.WritePropertyName("aggregationConfig");
context.Writer.WriteObjectStart();
var marshaller = AggregationConfigMarshaller.Instance;
marshaller.Marshall(requestObject.AggregationConfig, context);
context.Writer.WriteObjectEnd();
}
if(requestObject.IsSetFileType())
{
context.Writer.WritePropertyName("fileType");
context.Writer.Write(requestObject.FileType);
}
if(requestObject.IsSetPrefixConfig())
{
context.Writer.WritePropertyName("prefixConfig");
context.Writer.WriteObjectStart();
var marshaller = PrefixConfigMarshaller.Instance;
marshaller.Marshall(requestObject.PrefixConfig, context);
context.Writer.WriteObjectEnd();
}
}
/// <summary>
/// Singleton Marshaller.
/// </summary>
public readonly static UpsolverS3OutputFormatConfigMarshaller Instance = new UpsolverS3OutputFormatConfigMarshaller();
}
} | 35.571429 | 131 | 0.64759 | [
"Apache-2.0"
] | philasmar/aws-sdk-net | sdk/src/Services/Appflow/Generated/Model/Internal/MarshallTransformations/UpsolverS3OutputFormatConfigMarshaller.cs | 2,988 | C# |
//======= Copyright (c) Valve Corporation, All rights reserved. ===============
//
// Purpose: Utility functions used in several places
//
//=============================================================================
using UnityEngine;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
namespace Valve.VR.InteractionSystem
{
//-------------------------------------------------------------------------
public static class Util
{
public const float FeetToMeters = 0.3048f;
public const float FeetToCentimeters = 30.48f;
public const float InchesToMeters = 0.0254f;
public const float InchesToCentimeters = 2.54f;
public const float MetersToFeet = 3.28084f;
public const float MetersToInches = 39.3701f;
public const float CentimetersToFeet = 0.0328084f;
public const float CentimetersToInches = 0.393701f;
public const float KilometersToMiles = 0.621371f;
public const float MilesToKilometers = 1.60934f;
//-------------------------------------------------
// Remap num from range 1 to range 2
//-------------------------------------------------
public static float RemapNumber( float num, float low1, float high1, float low2, float high2 )
{
return low2 + ( num - low1 ) * ( high2 - low2 ) / ( high1 - low1 );
}
//-------------------------------------------------
public static float RemapNumberClamped( float num, float low1, float high1, float low2, float high2 )
{
return Mathf.Clamp( RemapNumber( num, low1, high1, low2, high2 ), Mathf.Min( low2, high2 ), Mathf.Max( low2, high2 ) );
}
//-------------------------------------------------
public static float Approach( float target, float value, float speed )
{
float delta = target - value;
if ( delta > speed )
value += speed;
else if ( delta < -speed )
value -= speed;
else
value = target;
return value;
}
//-------------------------------------------------
public static Vector3 BezierInterpolate3( Vector3 p0, Vector3 c0, Vector3 p1, float t )
{
Vector3 p0c0 = Vector3.Lerp( p0, c0, t );
Vector3 c0p1 = Vector3.Lerp( c0, p1, t );
return Vector3.Lerp( p0c0, c0p1, t );
}
//-------------------------------------------------
public static Vector3 BezierInterpolate4( Vector3 p0, Vector3 c0, Vector3 c1, Vector3 p1, float t )
{
Vector3 p0c0 = Vector3.Lerp( p0, c0, t );
Vector3 c0c1 = Vector3.Lerp( c0, c1, t );
Vector3 c1p1 = Vector3.Lerp( c1, p1, t );
Vector3 x = Vector3.Lerp( p0c0, c0c1, t );
Vector3 y = Vector3.Lerp( c0c1, c1p1, t );
//Debug.DrawRay(p0, Vector3.forward);
//Debug.DrawRay(c0, Vector3.forward);
//Debug.DrawRay(c1, Vector3.forward);
//Debug.DrawRay(p1, Vector3.forward);
//Gizmos.DrawSphere(p0c0, 0.5F);
//Gizmos.DrawSphere(c0c1, 0.5F);
//Gizmos.DrawSphere(c1p1, 0.5F);
//Gizmos.DrawSphere(x, 0.5F);
//Gizmos.DrawSphere(y, 0.5F);
return Vector3.Lerp( x, y, t );
}
//-------------------------------------------------
public static Vector3 Vector3FromString( string szString )
{
string[] szParseString = szString.Substring( 1, szString.Length - 1 ).Split( ',' );
float x = float.Parse( szParseString[0] );
float y = float.Parse( szParseString[1] );
float z = float.Parse( szParseString[2] );
Vector3 vReturn = new Vector3( x, y, z );
return vReturn;
}
//-------------------------------------------------
public static Vector2 Vector2FromString( string szString )
{
string[] szParseString = szString.Substring( 1, szString.Length - 1 ).Split( ',' );
float x = float.Parse( szParseString[0] );
float y = float.Parse( szParseString[1] );
Vector3 vReturn = new Vector2( x, y );
return vReturn;
}
//-------------------------------------------------
public static float Normalize( float value, float min, float max )
{
float normalizedValue = ( value - min ) / ( max - min );
return normalizedValue;
}
//-------------------------------------------------
public static Vector3 Vector2AsVector3( Vector2 v )
{
return new Vector3( v.x, 0.0f, v.y );
}
//-------------------------------------------------
public static Vector2 Vector3AsVector2( Vector3 v )
{
return new Vector2( v.x, v.z );
}
//-------------------------------------------------
public static float AngleOf( Vector2 v )
{
float fDist = v.magnitude;
if ( v.y >= 0.0f )
{
return Mathf.Acos( v.x / fDist );
}
else
{
return Mathf.Acos( -v.x / fDist ) + Mathf.PI;
}
}
//-------------------------------------------------
public static float YawOf( Vector3 v )
{
float fDist = v.magnitude;
if ( v.z >= 0.0f )
{
return Mathf.Acos( v.x / fDist );
}
else
{
return Mathf.Acos( -v.x / fDist ) + Mathf.PI;
}
}
//-------------------------------------------------
public static void Swap<T>( ref T lhs, ref T rhs )
{
T temp = lhs;
lhs = rhs;
rhs = temp;
}
//-------------------------------------------------
public static void Shuffle<T>( T[] array )
{
for ( int i = array.Length - 1; i > 0; i-- )
{
int r = UnityEngine.Random.Range( 0, i );
Swap( ref array[i], ref array[r] );
}
}
//-------------------------------------------------
public static void Shuffle<T>( List<T> list )
{
for ( int i = list.Count - 1; i > 0; i-- )
{
int r = UnityEngine.Random.Range( 0, i );
T temp = list[i];
list[i] = list[r];
list[r] = temp;
}
}
//-------------------------------------------------
public static int RandomWithLookback( int min, int max, List<int> history, int historyCount )
{
int index = UnityEngine.Random.Range( min, max - history.Count );
for ( int i = 0; i < history.Count; i++ )
{
if ( index >= history[i] )
{
index++;
}
}
history.Add( index );
if ( history.Count > historyCount )
{
history.RemoveRange( 0, history.Count - historyCount );
}
return index;
}
//-------------------------------------------------
public static Transform FindChild( Transform parent, string name )
{
if ( parent.name == name )
return parent;
foreach ( Transform child in parent )
{
var found = FindChild( child, name );
if ( found != null )
return found;
}
return null;
}
//-------------------------------------------------
public static bool IsNullOrEmpty<T>( T[] array )
{
if ( array == null )
return true;
if ( array.Length == 0 )
return true;
return false;
}
//-------------------------------------------------
public static bool IsValidIndex<T>( T[] array, int i )
{
if ( array == null )
return false;
return ( i >= 0 ) && ( i < array.Length );
}
//-------------------------------------------------
public static bool IsValidIndex<T>( List<T> list, int i )
{
if ( list == null || list.Count == 0 )
return false;
return ( i >= 0 ) && ( i < list.Count );
}
//-------------------------------------------------
public static int FindOrAdd<T>( List<T> list, T item )
{
int index = list.IndexOf( item );
if ( index == -1 )
{
list.Add( item );
index = list.Count - 1;
}
return index;
}
//-------------------------------------------------
public static List<T> FindAndRemove<T>( List<T> list, System.Predicate<T> match )
{
List<T> retVal = list.FindAll( match );
list.RemoveAll( match );
return retVal;
}
//-------------------------------------------------
public static T FindOrAddComponent<T>( GameObject gameObject ) where T : Component
{
T component = gameObject.GetComponent<T>();
if ( component )
return component;
return gameObject.AddComponent<T>();
}
//-------------------------------------------------
public static void FastRemove<T>( List<T> list, int index )
{
list[index] = list[list.Count - 1];
list.RemoveAt( list.Count - 1 );
}
//-------------------------------------------------
public static void ReplaceGameObject<T, U>( T replace, U replaceWith )
where T : MonoBehaviour
where U : MonoBehaviour
{
replace.gameObject.SetActive( false );
replaceWith.gameObject.SetActive( true );
}
//-------------------------------------------------
public static void SwitchLayerRecursively( Transform transform, int fromLayer, int toLayer )
{
if ( transform.gameObject.layer == fromLayer )
transform.gameObject.layer = toLayer;
int childCount = transform.childCount;
for ( int i = 0; i < childCount; i++ )
{
SwitchLayerRecursively( transform.GetChild( i ), fromLayer, toLayer );
}
}
//-------------------------------------------------
public static void DrawCross( Vector3 origin, Color crossColor, float size )
{
Vector3 line1Start = origin + ( Vector3.right * size );
Vector3 line1End = origin - ( Vector3.right * size );
Debug.DrawLine( line1Start, line1End, crossColor );
Vector3 line2Start = origin + ( Vector3.up * size );
Vector3 line2End = origin - ( Vector3.up * size );
Debug.DrawLine( line2Start, line2End, crossColor );
Vector3 line3Start = origin + ( Vector3.forward * size );
Vector3 line3End = origin - ( Vector3.forward * size );
Debug.DrawLine( line3Start, line3End, crossColor );
}
//-------------------------------------------------
public static void ResetTransform( Transform t, bool resetScale = true )
{
t.localPosition = Vector3.zero;
t.localRotation = Quaternion.identity;
if ( resetScale )
{
t.localScale = new Vector3( 1f, 1f, 1f );
}
}
//-------------------------------------------------
public static Vector3 ClosestPointOnLine( Vector3 vA, Vector3 vB, Vector3 vPoint )
{
var vVector1 = vPoint - vA;
var vVector2 = ( vB - vA ).normalized;
var d = Vector3.Distance( vA, vB );
var t = Vector3.Dot( vVector2, vVector1 );
if ( t <= 0 )
return vA;
if ( t >= d )
return vB;
var vVector3 = vVector2 * t;
var vClosestPoint = vA + vVector3;
return vClosestPoint;
}
//-------------------------------------------------
public static void AfterTimer( GameObject go, float _time, System.Action callback, bool trigger_if_destroyed_early = false )
{
AfterTimer_Component afterTimer_component = go.AddComponent<AfterTimer_Component>();
afterTimer_component.Init( _time, callback, trigger_if_destroyed_early );
}
//-------------------------------------------------
public static void SendPhysicsMessage( Collider collider, string message, SendMessageOptions sendMessageOptions )
{
Rigidbody rb = collider.attachedRigidbody;
if ( rb && rb.gameObject != collider.gameObject )
{
rb.SendMessage( message, sendMessageOptions );
}
collider.SendMessage( message, sendMessageOptions );
}
//-------------------------------------------------
public static void SendPhysicsMessage( Collider collider, string message, object arg, SendMessageOptions sendMessageOptions )
{
Rigidbody rb = collider.attachedRigidbody;
if ( rb && rb.gameObject != collider.gameObject )
{
rb.SendMessage( message, arg, sendMessageOptions );
}
collider.SendMessage( message, arg, sendMessageOptions );
}
//-------------------------------------------------
public static void IgnoreCollisions( GameObject goA, GameObject goB )
{
Collider[] goA_colliders = goA.GetComponentsInChildren<Collider>();
Collider[] goB_colliders = goB.GetComponentsInChildren<Collider>();
if ( goA_colliders.Length == 0 || goB_colliders.Length == 0 )
{
return;
}
foreach ( Collider cA in goA_colliders )
{
foreach ( Collider cB in goB_colliders )
{
if ( cA.enabled && cB.enabled )
{
Physics.IgnoreCollision( cA, cB, true );
}
}
}
}
//-------------------------------------------------
public static IEnumerator WrapCoroutine( IEnumerator coroutine, System.Action onCoroutineFinished )
{
while ( coroutine.MoveNext() )
{
yield return coroutine.Current;
}
onCoroutineFinished();
}
//-------------------------------------------------
public static Color ColorWithAlpha( this Color color, float alpha )
{
color.a = alpha;
return color;
}
//-------------------------------------------------
// Exits the application if running standalone, or stops playback if running in the editor.
//-------------------------------------------------
public static void Quit()
{
#if UNITY_EDITOR
UnityEditor.EditorApplication.isPlaying = false;
#else
// NOTE: The recommended call for exiting a Unity app is UnityEngine.Application.Quit(), but as
// of 5.1.0f3 this was causing the application to crash. The following works without crashing:
System.Diagnostics.Process.GetCurrentProcess().Kill();
#endif
}
//-------------------------------------------------
// Truncate floats to the specified # of decimal places when you want easier-to-read numbers without clamping to an int
//-------------------------------------------------
public static decimal FloatToDecimal( float value, int decimalPlaces = 2 )
{
return Math.Round( (decimal)value, decimalPlaces );
}
//-------------------------------------------------
public static T Median<T>( this IEnumerable<T> source )
{
if ( source == null )
{
throw new ArgumentException( "Argument cannot be null.", "source" );
}
int count = source.Count();
if ( count == 0 )
{
throw new InvalidOperationException( "Enumerable must contain at least one element." );
}
return source.OrderBy( x => x ).ElementAt( count / 2 );
}
//-------------------------------------------------
public static void ForEach<T>( this IEnumerable<T> source, Action<T> action )
{
if ( source == null )
{
throw new ArgumentException( "Argument cannot be null.", "source" );
}
foreach ( T value in source )
{
action( value );
}
}
//-------------------------------------------------
// In some cases Unity/C# don't correctly interpret the newline control character (\n).
// This function replaces every instance of "\\n" with the actual newline control character.
//-------------------------------------------------
public static string FixupNewlines( string text )
{
bool newLinesRemaining = true;
while ( newLinesRemaining )
{
int CIndex = text.IndexOf( "\\n" );
if ( CIndex == -1 )
{
newLinesRemaining = false;
}
else
{
text = text.Remove( CIndex - 1, 3 );
text = text.Insert( CIndex - 1, "\n" );
}
}
return text;
}
//-------------------------------------------------
#if (UNITY_5_5 || UNITY_5_4)
public static float PathLength( UnityEngine.AI.NavMeshPath path )
#else
public static float PathLength( UnityEngine.AI.NavMeshPath path )
#endif
{
if ( path.corners.Length < 2 )
return 0;
Vector3 previousCorner = path.corners[0];
float lengthSoFar = 0.0f;
int i = 1;
while ( i < path.corners.Length )
{
Vector3 currentCorner = path.corners[i];
lengthSoFar += Vector3.Distance( previousCorner, currentCorner );
previousCorner = currentCorner;
i++;
}
return lengthSoFar;
}
//-------------------------------------------------
public static bool HasCommandLineArgument( string argumentName )
{
string[] args = System.Environment.GetCommandLineArgs();
for ( int i = 0; i < args.Length; i++ )
{
if ( args[i].Equals( argumentName ) )
{
return true;
}
}
return false;
}
//-------------------------------------------------
public static int GetCommandLineArgValue( string argumentName, int nDefaultValue )
{
string[] args = System.Environment.GetCommandLineArgs();
for ( int i = 0; i < args.Length; i++ )
{
if ( args[i].Equals( argumentName ) )
{
if ( i == ( args.Length - 1 ) ) // Last arg, return default
{
return nDefaultValue;
}
return System.Int32.Parse( args[i + 1] );
}
}
return nDefaultValue;
}
//-------------------------------------------------
public static float GetCommandLineArgValue( string argumentName, float flDefaultValue )
{
string[] args = System.Environment.GetCommandLineArgs();
for ( int i = 0; i < args.Length; i++ )
{
if ( args[i].Equals( argumentName ) )
{
if ( i == ( args.Length - 1 ) ) // Last arg, return default
{
return flDefaultValue;
}
return (float)Double.Parse( args[i + 1] );
}
}
return flDefaultValue;
}
//-------------------------------------------------
public static void SetActive( GameObject gameObject, bool active )
{
if ( gameObject != null )
{
gameObject.SetActive( active );
}
}
//-------------------------------------------------
// The version of Path.Combine() included with Unity can only combine two paths.
// This version mimics the modern .NET version, which allows for any number of
// paths to be combined.
//-------------------------------------------------
public static string CombinePaths( params string[] paths )
{
if ( paths.Length == 0 )
{
return "";
}
else
{
string combinedPath = paths[0];
for ( int i = 1; i < paths.Length; i++ )
{
combinedPath = Path.Combine( combinedPath, paths[i] );
}
return combinedPath;
}
}
}
//-------------------------------------------------------------------------
//Component used by the static AfterTimer function
//-------------------------------------------------------------------------
[System.Serializable]
public class AfterTimer_Component : MonoBehaviour
{
private GameObject go;
private System.Action callback;
private float triggerTime;
private float timer;
private bool timerActive = false;
private bool triggerOnEarlyDestroy = false;
//-------------------------------------------------
public void Init( float _time, System.Action _callback, bool earlydestroy )
{
triggerTime = _time;
callback = _callback;
triggerOnEarlyDestroy = earlydestroy;
timerActive = true;
StartCoroutine( Wait() );
}
//-------------------------------------------------
private IEnumerator Wait()
{
yield return new WaitForSeconds( triggerTime );
timerActive = false;
callback.Invoke();
Destroy( this );
}
//-------------------------------------------------
void OnDestroy()
{
if ( timerActive )
{
//If the component or its GameObject get destroyed before the timer is complete, clean up
StopCoroutine( Wait() );
timerActive = false;
if ( triggerOnEarlyDestroy )
{
callback.Invoke();
}
}
}
}
}
| 25.46748 | 127 | 0.532642 | [
"MIT"
] | 13rac1/Roll-a-Ball-VR | Assets/SteamVR/InteractionSystem/Core/Scripts/Util.cs | 18,797 | C# |
using System;
using System.Collections.Generic;
namespace ObjectFactories.Example
{
public static class Program
{
public static void Main(string[] args)
{
EmailSender emailer1 = new EmailSender();
emailer1.TellEveryone("Hello, World!");
emailer1.TellEveryone("Bye, World");
EmailSender emailer2 = new EmailSender();
emailer2.TellEveryone("Hello, World!");
IHasStuff stuff = new HasStuff();
for (int i = 0; i < 1000000; ++i)
{
foreach (string value in stuff.Values)
{
if (value == null)
{
throw new ArgumentException();
}
}
}
}
}
public interface IHasStuff
{
IEnumerable<string> Values
{
get;
}
}
public class HasStuff : IHasStuff
{
#region Member Data
private readonly List<string> _values = new List<string>();
#endregion
#region IHasStuff Members
public IEnumerable<string> Values
{
get { return _values; }
}
#endregion
#region HasStuff()
public HasStuff()
{
_values.Add("Jacob");
_values.Add("Andy");
}
#endregion
}
}
| 20.728814 | 64 | 0.554374 | [
"MIT"
] | abombss/machine | Experiments/ObjectFactories/ObjectFactories.Example/Program.cs | 1,225 | C# |
namespace RelaxAndSport.Infrastructure.Common.Persistence
{
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using RelaxAndSport.Domain.Booking.Models.Client;
using RelaxAndSport.Domain.Booking.Models.Massages;
using RelaxAndSport.Domain.Booking.Models.MassagesAppointments;
using RelaxAndSport.Domain.Booking.Models.MassagesSchedule;
using RelaxAndSport.Domain.Booking.Models.TrainifngsAppointments;
using RelaxAndSport.Domain.Booking.Models.Trainings;
using RelaxAndSport.Domain.Booking.Models.TrainingsSchedule;
using RelaxAndSport.Domain.Common.Models;
using RelaxAndSport.Domain.Statistics.Models;
using RelaxAndSport.Infrastructure.Booking;
using RelaxAndSport.Infrastructure.Common.Events;
using RelaxAndSport.Infrastructure.Identity;
using RelaxAndSport.Infrastructure.Statistics;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
internal class RelaxAndSportDbContext : IdentityDbContext<User>,
IBookingDbContext,
IStatisticsDbContext
{
private readonly IEventDispatcher eventDispatcher;
private readonly Stack<object> savesChangesTracker;
public RelaxAndSportDbContext(
DbContextOptions<RelaxAndSportDbContext> options,
IEventDispatcher eventDispatcher)
: base(options)
{
this.eventDispatcher = eventDispatcher;
this.savesChangesTracker = new Stack<object>();
}
public DbSet<Client> Clients { get; set; } = default!;
public DbSet<Massage> Massages { get; set; } = default!;
public DbSet<MassageAppointment> MassageAppointments { get; set; } = default!;
public DbSet<MassagesSchedule> MassagesSchedules { get; set; } = default!;
public DbSet<Training> Trainings { get; set; } = default!;
public DbSet<Trainer> Trainers { get; set; } = default!;
public DbSet<TrainingAppointment> TrainingAppointments { get; set; } = default!;
public DbSet<TrainingsSchedule> TrainingsSchedules { get; set; } = default!;
public DbSet<Statistics> Statistics { get; set; } = default!;
public override async Task<int> SaveChangesAsync(CancellationToken cancellationToken = new CancellationToken())
{
this.savesChangesTracker.Push(new object());
var entities = this.ChangeTracker
.Entries<IEntity>()
.Select(e => e.Entity)
.Where(e => e.Events.Any())
.ToArray();
foreach (var entity in entities)
{
var events = entity.Events.ToArray();
entity.ClearEvents();
foreach (var domainEvent in events)
{
await this.eventDispatcher.Dispatch(domainEvent);
}
}
this.savesChangesTracker.Pop();
if (!this.savesChangesTracker.Any())
{
return await base.SaveChangesAsync(cancellationToken);
}
return 0;
}
protected override void OnModelCreating(ModelBuilder builder)
{
builder.ApplyConfigurationsFromAssembly(Assembly.GetExecutingAssembly());
base.OnModelCreating(builder);
}
}
}
| 35.244898 | 119 | 0.655761 | [
"MIT"
] | kriskok95/RelaxAndSport | src/Server/RelaxAndSport.Infrastructure/Common/Persistence/RelaxAndSportDbContext.cs | 3,456 | C# |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
//
// This class represents the Default COM+ binder.
//
//
namespace System {
using System;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Diagnostics.Contracts;
using CultureInfo = System.Globalization.CultureInfo;
//Marked serializable even though it has no state.
[Serializable]
internal class DefaultBinder : Binder
{
// This method is passed a set of methods and must choose the best
// fit. The methods all have the same number of arguments and the object
// array args. On exit, this method will choice the best fit method
// and coerce the args to match that method. By match, we mean all primitive
// arguments are exact matchs and all object arguments are exact or subclasses
// of the target. If the target OR is an interface, the object must implement
// that interface. There are a couple of exceptions
// thrown when a method cannot be returned. If no method matchs the args and
// ArgumentException is thrown. If multiple methods match the args then
// an AmbiguousMatchException is thrown.
//
// The most specific match will be selected.
//
[System.Security.SecuritySafeCritical] // auto-generated
public override MethodBase BindToMethod(
BindingFlags bindingAttr, MethodBase[] match, ref Object[] args,
ParameterModifier[] modifiers, CultureInfo cultureInfo, String[] names, out Object state)
{
if (match == null || match.Length == 0)
throw new ArgumentException(Environment.GetResourceString("Arg_EmptyArray"), "match");
Contract.EndContractBlock();
MethodBase[] candidates = (MethodBase[]) match.Clone();
int i;
int j;
state = null;
#region Map named parameters to candidate parameter postions
// We are creating an paramOrder array to act as a mapping
// between the order of the args and the actual order of the
// parameters in the method. This order may differ because
// named parameters (names) may change the order. If names
// is not provided, then we assume the default mapping (0,1,...)
int[][] paramOrder = new int[candidates.Length][];
for (i = 0; i < candidates.Length; i++)
{
ParameterInfo[] par = candidates[i].GetParametersNoCopy();
// args.Length + 1 takes into account the possibility of a last paramArray that can be omitted
paramOrder[i] = new int[(par.Length > args.Length) ? par.Length : args.Length];
if (names == null)
{
// Default mapping
for (j = 0; j < args.Length; j++)
paramOrder[i][j] = j;
}
else
{
// Named parameters, reorder the mapping. If CreateParamOrder fails, it means that the method
// doesn't have a name that matchs one of the named parameters so we don't consider it any further.
if (!CreateParamOrder(paramOrder[i], par, names))
candidates[i] = null;
}
}
#endregion
Type[] paramArrayTypes = new Type[candidates.Length];
Type[] argTypes = new Type[args.Length];
#region Cache the type of the provided arguments
// object that contain a null are treated as if they were typeless (but match either object
// references or value classes). We mark this condition by placing a null in the argTypes array.
for (i = 0; i < args.Length; i++)
{
if (args[i] != null)
{
argTypes[i] = args[i].GetType();
}
}
#endregion
// Find the method that matches...
int CurIdx = 0;
bool defaultValueBinding = ((bindingAttr & BindingFlags.OptionalParamBinding) != 0);
Type paramArrayType = null;
#region Filter methods by parameter count and type
for (i = 0; i < candidates.Length; i++)
{
paramArrayType = null;
// If we have named parameters then we may have a hole in the candidates array.
if (candidates[i] == null)
continue;
// Validate the parameters.
ParameterInfo[] par = candidates[i].GetParametersNoCopy();
#region Match method by parameter count
if (par.Length == 0)
{
#region No formal parameters
if (args.Length != 0)
{
if ((candidates[i].CallingConvention & CallingConventions.VarArgs) == 0)
continue;
}
// This is a valid routine so we move it up the candidates list.
paramOrder[CurIdx] = paramOrder[i];
candidates[CurIdx++] = candidates[i];
continue;
#endregion
}
else if (par.Length > args.Length)
{
#region Shortage of provided parameters
// If the number of parameters is greater than the number of args then
// we are in the situation were we may be using default values.
for (j = args.Length; j < par.Length - 1; j++)
{
if (par[j].DefaultValue == System.DBNull.Value)
break;
}
if (j != par.Length - 1)
continue;
if (par[j].DefaultValue == System.DBNull.Value)
{
if (!par[j].ParameterType.IsArray)
continue;
if (!par[j].IsDefined(typeof(ParamArrayAttribute), true))
continue;
paramArrayType = par[j].ParameterType.GetElementType();
}
#endregion
}
else if (par.Length < args.Length)
{
#region Excess provided parameters
// test for the ParamArray case
int lastArgPos = par.Length - 1;
if (!par[lastArgPos].ParameterType.IsArray)
continue;
if (!par[lastArgPos].IsDefined(typeof(ParamArrayAttribute), true))
continue;
if (paramOrder[i][lastArgPos] != lastArgPos)
continue;
paramArrayType = par[lastArgPos].ParameterType.GetElementType();
#endregion
}
else
{
#region Test for paramArray, save paramArray type
int lastArgPos = par.Length - 1;
if (par[lastArgPos].ParameterType.IsArray
&& par[lastArgPos].IsDefined(typeof(ParamArrayAttribute), true)
&& paramOrder[i][lastArgPos] == lastArgPos)
{
if (!par[lastArgPos].ParameterType.IsAssignableFrom(argTypes[lastArgPos]))
paramArrayType = par[lastArgPos].ParameterType.GetElementType();
}
#endregion
}
#endregion
Type pCls = null;
int argsToCheck = (paramArrayType != null) ? par.Length - 1 : args.Length;
#region Match method by parameter type
for (j = 0; j < argsToCheck; j++)
{
#region Classic argument coersion checks
// get the formal type
pCls = par[j].ParameterType;
if (pCls.IsByRef)
pCls = pCls.GetElementType();
// the type is the same
if (pCls == argTypes[paramOrder[i][j]])
continue;
// a default value is available
if (defaultValueBinding && args[paramOrder[i][j]] == Type.Missing)
continue;
// the argument was null, so it matches with everything
if (args[paramOrder[i][j]] == null)
continue;
// the type is Object, so it will match everything
if (pCls == typeof(Object))
continue;
// now do a "classic" type check
if (pCls.IsPrimitive)
{
if (argTypes[paramOrder[i][j]] == null || !CanConvertPrimitiveObjectToType(args[paramOrder[i][j]],(RuntimeType)pCls))
{
break;
}
}
else
{
if (argTypes[paramOrder[i][j]] == null)
continue;
if (!pCls.IsAssignableFrom(argTypes[paramOrder[i][j]]))
{
if (argTypes[paramOrder[i][j]].IsCOMObject)
{
if (pCls.IsInstanceOfType(args[paramOrder[i][j]]))
continue;
}
break;
}
}
#endregion
}
if (paramArrayType != null && j == par.Length - 1)
{
#region Check that excess arguments can be placed in the param array
for (; j < args.Length; j++)
{
if (paramArrayType.IsPrimitive)
{
if (argTypes[j] == null || !CanConvertPrimitiveObjectToType(args[j], (RuntimeType)paramArrayType))
break;
}
else
{
if (argTypes[j] == null)
continue;
if (!paramArrayType.IsAssignableFrom(argTypes[j]))
{
if (argTypes[j].IsCOMObject)
{
if (paramArrayType.IsInstanceOfType(args[j]))
continue;
}
break;
}
}
}
#endregion
}
#endregion
if (j == args.Length)
{
#region This is a valid routine so we move it up the candidates list
paramOrder[CurIdx] = paramOrder[i];
paramArrayTypes[CurIdx] = paramArrayType;
candidates[CurIdx++] = candidates[i];
#endregion
}
}
#endregion
// If we didn't find a method
if (CurIdx == 0)
throw new MissingMethodException(Environment.GetResourceString("MissingMember"));
if (CurIdx == 1)
{
#region Found only one method
if (names != null)
{
state = new BinderState((int[])paramOrder[0].Clone(), args.Length, paramArrayTypes[0] != null);
ReorderParams(paramOrder[0],args);
}
// If the parameters and the args are not the same length or there is a paramArray
// then we need to create a argument array.
ParameterInfo[] parms = candidates[0].GetParametersNoCopy();
if (parms.Length == args.Length)
{
if (paramArrayTypes[0] != null)
{
Object[] objs = new Object[parms.Length];
int lastPos = parms.Length - 1;
Array.Copy(args, 0, objs, 0, lastPos);
objs[lastPos] = Array.UnsafeCreateInstance(paramArrayTypes[0], 1);
((Array)objs[lastPos]).SetValue(args[lastPos], 0);
args = objs;
}
}
else if (parms.Length > args.Length)
{
Object[] objs = new Object[parms.Length];
for (i=0;i<args.Length;i++)
objs[i] = args[i];
for (;i<parms.Length - 1;i++)
objs[i] = parms[i].DefaultValue;
if (paramArrayTypes[0] != null)
objs[i] = Array.UnsafeCreateInstance(paramArrayTypes[0], 0); // create an empty array for the
else
objs[i] = parms[i].DefaultValue;
args = objs;
}
else
{
if ((candidates[0].CallingConvention & CallingConventions.VarArgs) == 0)
{
Object[] objs = new Object[parms.Length];
int paramArrayPos = parms.Length - 1;
Array.Copy(args, 0, objs, 0, paramArrayPos);
objs[paramArrayPos] = Array.UnsafeCreateInstance(paramArrayTypes[0], args.Length - paramArrayPos);
Array.Copy(args, paramArrayPos, (System.Array)objs[paramArrayPos], 0, args.Length - paramArrayPos);
args = objs;
}
}
#endregion
return candidates[0];
}
int currentMin = 0;
bool ambig = false;
for (i = 1; i < CurIdx; i++)
{
#region Walk all of the methods looking the most specific method to invoke
int newMin = FindMostSpecificMethod(candidates[currentMin], paramOrder[currentMin], paramArrayTypes[currentMin],
candidates[i], paramOrder[i], paramArrayTypes[i], argTypes, args);
if (newMin == 0)
{
ambig = true;
}
else if (newMin == 2)
{
currentMin = i;
ambig = false;
}
#endregion
}
if (ambig)
throw new AmbiguousMatchException(Environment.GetResourceString("Arg_AmbiguousMatchException"));
// Reorder (if needed)
if (names != null) {
state = new BinderState((int[])paramOrder[currentMin].Clone(), args.Length, paramArrayTypes[currentMin] != null);
ReorderParams(paramOrder[currentMin], args);
}
// If the parameters and the args are not the same length or there is a paramArray
// then we need to create a argument array.
ParameterInfo[] parameters = candidates[currentMin].GetParametersNoCopy();
if (parameters.Length == args.Length)
{
if (paramArrayTypes[currentMin] != null)
{
Object[] objs = new Object[parameters.Length];
int lastPos = parameters.Length - 1;
Array.Copy(args, 0, objs, 0, lastPos);
objs[lastPos] = Array.UnsafeCreateInstance(paramArrayTypes[currentMin], 1);
((Array)objs[lastPos]).SetValue(args[lastPos], 0);
args = objs;
}
}
else if (parameters.Length > args.Length)
{
Object[] objs = new Object[parameters.Length];
for (i=0;i<args.Length;i++)
objs[i] = args[i];
for (;i<parameters.Length - 1;i++)
objs[i] = parameters[i].DefaultValue;
if (paramArrayTypes[currentMin] != null)
{
objs[i] = Array.UnsafeCreateInstance(paramArrayTypes[currentMin], 0);
}
else
{
objs[i] = parameters[i].DefaultValue;
}
args = objs;
}
else
{
if ((candidates[currentMin].CallingConvention & CallingConventions.VarArgs) == 0)
{
Object[] objs = new Object[parameters.Length];
int paramArrayPos = parameters.Length - 1;
Array.Copy(args, 0, objs, 0, paramArrayPos);
objs[paramArrayPos] = Array.UnsafeCreateInstance(paramArrayTypes[currentMin], args.Length - paramArrayPos);
Array.Copy(args, paramArrayPos, (System.Array)objs[paramArrayPos], 0, args.Length - paramArrayPos);
args = objs;
}
}
return candidates[currentMin];
}
// Given a set of fields that match the base criteria, select a field.
// if value is null then we have no way to select a field
[System.Security.SecuritySafeCritical] // auto-generated
public override FieldInfo BindToField(BindingFlags bindingAttr,FieldInfo[] match, Object value,CultureInfo cultureInfo)
{
if (match == null) {
throw new ArgumentNullException("match");
}
int i;
// Find the method that match...
int CurIdx = 0;
Type valueType = null;
FieldInfo[] candidates = (FieldInfo[]) match.Clone();
// If we are a FieldSet, then use the value's type to disambiguate
if ((bindingAttr & BindingFlags.SetField) != 0) {
valueType = value.GetType();
for (i=0;i<candidates.Length;i++) {
Type pCls = candidates[i].FieldType;
if (pCls == valueType) {
candidates[CurIdx++] = candidates[i];
continue;
}
if (value == Empty.Value) {
// the object passed in was null which would match any non primitive non value type
if (pCls.IsClass) {
candidates[CurIdx++] = candidates[i];
continue;
}
}
if (pCls == typeof(Object)) {
candidates[CurIdx++] = candidates[i];
continue;
}
if (pCls.IsPrimitive) {
if (CanConvertPrimitiveObjectToType(value,(RuntimeType)pCls)) {
candidates[CurIdx++] = candidates[i];
continue;
}
}
else {
if (pCls.IsAssignableFrom(valueType)) {
candidates[CurIdx++] = candidates[i];
continue;
}
}
}
if (CurIdx == 0)
throw new MissingFieldException(Environment.GetResourceString("MissingField"));
if (CurIdx == 1)
return candidates[0];
}
// Walk all of the methods looking the most specific method to invoke
int currentMin = 0;
bool ambig = false;
for (i=1;i<CurIdx;i++) {
int newMin = FindMostSpecificField(candidates[currentMin], candidates[i]);
if (newMin == 0)
ambig = true;
else {
if (newMin == 2) {
currentMin = i;
ambig = false;
}
}
}
if (ambig)
throw new AmbiguousMatchException(Environment.GetResourceString("Arg_AmbiguousMatchException"));
return candidates[currentMin];
}
// Given a set of methods that match the base criteria, select a method based
// upon an array of types. This method should return null if no method matchs
// the criteria.
[System.Security.SecuritySafeCritical] // auto-generated
public override MethodBase SelectMethod(BindingFlags bindingAttr,MethodBase[] match,Type[] types,ParameterModifier[] modifiers)
{
int i;
int j;
Type[] realTypes = new Type[types.Length];
for (i=0;i<types.Length;i++) {
realTypes[i] = types[i].UnderlyingSystemType;
if (!(realTypes[i] is RuntimeType))
throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"),"types");
}
types = realTypes;
// We don't automatically jump out on exact match.
if (match == null || match.Length == 0)
throw new ArgumentException(Environment.GetResourceString("Arg_EmptyArray"), "match");
MethodBase[] candidates = (MethodBase[]) match.Clone();
// Find all the methods that can be described by the types parameter.
// Remove all of them that cannot.
int CurIdx = 0;
for (i=0;i<candidates.Length;i++) {
ParameterInfo[] par = candidates[i].GetParametersNoCopy();
if (par.Length != types.Length)
continue;
for (j=0;j<types.Length;j++) {
Type pCls = par[j].ParameterType;
if (pCls == types[j])
continue;
if (pCls == typeof(Object))
continue;
if (pCls.IsPrimitive) {
if (!(types[j].UnderlyingSystemType is RuntimeType) ||
!CanConvertPrimitive((RuntimeType)types[j].UnderlyingSystemType,(RuntimeType)pCls.UnderlyingSystemType))
break;
}
else {
if (!pCls.IsAssignableFrom(types[j]))
break;
}
}
if (j == types.Length)
candidates[CurIdx++] = candidates[i];
}
if (CurIdx == 0)
return null;
if (CurIdx == 1)
return candidates[0];
// Walk all of the methods looking the most specific method to invoke
int currentMin = 0;
bool ambig = false;
int[] paramOrder = new int[types.Length];
for (i=0;i<types.Length;i++)
paramOrder[i] = i;
for (i=1;i<CurIdx;i++) {
int newMin = FindMostSpecificMethod(candidates[currentMin], paramOrder, null, candidates[i], paramOrder, null, types, null);
if (newMin == 0)
ambig = true;
else {
if (newMin == 2) {
currentMin = i;
ambig = false;
currentMin = i;
}
}
}
if (ambig)
throw new AmbiguousMatchException(Environment.GetResourceString("Arg_AmbiguousMatchException"));
return candidates[currentMin];
}
// Given a set of properties that match the base criteria, select one.
[System.Security.SecuritySafeCritical] // auto-generated
public override PropertyInfo SelectProperty(BindingFlags bindingAttr,PropertyInfo[] match,Type returnType,
Type[] indexes,ParameterModifier[] modifiers)
{
// Allow a null indexes array. But if it is not null, every element must be non-null as well.
if (indexes != null && !Contract.ForAll(indexes, delegate(Type t) { return t != null; }))
{
Exception e; // Written this way to pass the Code Contracts style requirements.
#if FEATURE_LEGACYNETCF
if (CompatibilitySwitches.IsAppEarlierThanWindowsPhone8)
e = new NullReferenceException();
else
#endif
e = new ArgumentNullException("indexes");
throw e;
}
if (match == null || match.Length == 0)
throw new ArgumentException(Environment.GetResourceString("Arg_EmptyArray"), "match");
Contract.EndContractBlock();
PropertyInfo[] candidates = (PropertyInfo[]) match.Clone();
int i,j = 0;
// Find all the properties that can be described by type indexes parameter
int CurIdx = 0;
int indexesLength = (indexes != null) ? indexes.Length : 0;
for (i=0;i<candidates.Length;i++) {
if (indexes != null)
{
ParameterInfo[] par = candidates[i].GetIndexParameters();
if (par.Length != indexesLength)
continue;
for (j=0;j<indexesLength;j++) {
Type pCls = par[j]. ParameterType;
// If the classes exactly match continue
if (pCls == indexes[j])
continue;
if (pCls == typeof(Object))
continue;
if (pCls.IsPrimitive) {
if (!(indexes[j].UnderlyingSystemType is RuntimeType) ||
!CanConvertPrimitive((RuntimeType)indexes[j].UnderlyingSystemType,(RuntimeType)pCls.UnderlyingSystemType))
break;
}
else {
if (!pCls.IsAssignableFrom(indexes[j]))
break;
}
}
}
if (j == indexesLength) {
if (returnType != null) {
if (candidates[i].PropertyType.IsPrimitive) {
if (!(returnType.UnderlyingSystemType is RuntimeType) ||
!CanConvertPrimitive((RuntimeType)returnType.UnderlyingSystemType,(RuntimeType)candidates[i].PropertyType.UnderlyingSystemType))
continue;
}
else {
if (!candidates[i].PropertyType.IsAssignableFrom(returnType))
continue;
}
}
candidates[CurIdx++] = candidates[i];
}
}
if (CurIdx == 0)
return null;
if (CurIdx == 1)
return candidates[0];
// Walk all of the properties looking the most specific method to invoke
int currentMin = 0;
bool ambig = false;
int[] paramOrder = new int[indexesLength];
for (i=0;i<indexesLength;i++)
paramOrder[i] = i;
for (i=1;i<CurIdx;i++) {
int newMin = FindMostSpecificType(candidates[currentMin].PropertyType, candidates[i].PropertyType,returnType);
if (newMin == 0 && indexes != null)
newMin = FindMostSpecific(candidates[currentMin].GetIndexParameters(),
paramOrder,
null,
candidates[i].GetIndexParameters(),
paramOrder,
null,
indexes,
null);
if (newMin == 0)
{
newMin = FindMostSpecificProperty(candidates[currentMin], candidates[i]);
if (newMin == 0)
ambig = true;
}
if (newMin == 2) {
ambig = false;
currentMin = i;
}
}
if (ambig)
throw new AmbiguousMatchException(Environment.GetResourceString("Arg_AmbiguousMatchException"));
return candidates[currentMin];
}
// ChangeType
// The default binder doesn't support any change type functionality.
// This is because the default is built into the low level invoke code.
public override Object ChangeType(Object value,Type type,CultureInfo cultureInfo)
{
throw new NotSupportedException(Environment.GetResourceString("NotSupported_ChangeType"));
}
public override void ReorderArgumentArray(ref Object[] args, Object state)
{
BinderState binderState = (BinderState)state;
ReorderParams(binderState.m_argsMap, args);
if (binderState.m_isParamArray) {
int paramArrayPos = args.Length - 1;
if (args.Length == binderState.m_originalSize)
args[paramArrayPos] = ((Object[])args[paramArrayPos])[0];
else {
// must be args.Length < state.originalSize
Object[] newArgs = new Object[args.Length];
Array.Copy(args, 0, newArgs, 0, paramArrayPos);
for (int i = paramArrayPos, j = 0; i < newArgs.Length; i++, j++) {
newArgs[i] = ((Object[])args[paramArrayPos])[j];
}
args = newArgs;
}
}
else {
if (args.Length > binderState.m_originalSize) {
Object[] newArgs = new Object[binderState.m_originalSize];
Array.Copy(args, 0, newArgs, 0, binderState.m_originalSize);
args = newArgs;
}
}
}
// Return any exact bindings that may exist. (This method is not defined on the
// Binder and is used by RuntimeType.)
public static MethodBase ExactBinding(MethodBase[] match,Type[] types,ParameterModifier[] modifiers)
{
if (match==null)
throw new ArgumentNullException("match");
Contract.EndContractBlock();
MethodBase[] aExactMatches = new MethodBase[match.Length];
int cExactMatches = 0;
for (int i=0;i<match.Length;i++) {
ParameterInfo[] par = match[i].GetParametersNoCopy();
if (par.Length == 0) {
continue;
}
int j;
for (j=0;j<types.Length;j++) {
Type pCls = par[j]. ParameterType;
// If the classes exactly match continue
if (!pCls.Equals(types[j]))
break;
}
if (j < types.Length)
continue;
// Add the exact match to the array of exact matches.
aExactMatches[cExactMatches] = match[i];
cExactMatches++;
}
if (cExactMatches == 0)
return null;
if (cExactMatches == 1)
return aExactMatches[0];
return FindMostDerivedNewSlotMeth(aExactMatches, cExactMatches);
}
// Return any exact bindings that may exist. (This method is not defined on the
// Binder and is used by RuntimeType.)
public static PropertyInfo ExactPropertyBinding(PropertyInfo[] match,Type returnType,Type[] types,ParameterModifier[] modifiers)
{
if (match==null)
throw new ArgumentNullException("match");
Contract.EndContractBlock();
PropertyInfo bestMatch = null;
int typesLength = (types != null) ? types.Length : 0;
for (int i=0;i<match.Length;i++) {
ParameterInfo[] par = match[i].GetIndexParameters();
int j;
for (j=0;j<typesLength;j++) {
Type pCls = par[j].ParameterType;
// If the classes exactly match continue
if (pCls != types[j])
break;
}
if (j < typesLength)
continue;
if (returnType != null && returnType != match[i].PropertyType)
continue;
if (bestMatch != null)
throw new AmbiguousMatchException(Environment.GetResourceString("Arg_AmbiguousMatchException"));
bestMatch = match[i];
}
return bestMatch;
}
private static int FindMostSpecific(ParameterInfo[] p1, int[] paramOrder1, Type paramArrayType1,
ParameterInfo[] p2, int[] paramOrder2, Type paramArrayType2,
Type[] types, Object[] args)
{
// A method using params is always less specific than one not using params
if (paramArrayType1 != null && paramArrayType2 == null) return 2;
if (paramArrayType2 != null && paramArrayType1 == null) return 1;
// now either p1 and p2 both use params or neither does.
bool p1Less = false;
bool p2Less = false;
for (int i = 0; i < types.Length; i++)
{
if (args != null && args[i] == Type.Missing)
continue;
Type c1, c2;
// If a param array is present, then either
// the user re-ordered the parameters in which case
// the argument to the param array is either an array
// in which case the params is conceptually ignored and so paramArrayType1 == null
// or the argument to the param array is a single element
// in which case paramOrder[i] == p1.Length - 1 for that element
// or the user did not re-order the parameters in which case
// the paramOrder array could contain indexes larger than p.Length - 1 (see VSW 577286)
// so any index >= p.Length - 1 is being put in the param array
if (paramArrayType1 != null && paramOrder1[i] >= p1.Length - 1)
c1 = paramArrayType1;
else
c1 = p1[paramOrder1[i]].ParameterType;
if (paramArrayType2 != null && paramOrder2[i] >= p2.Length - 1)
c2 = paramArrayType2;
else
c2 = p2[paramOrder2[i]].ParameterType;
if (c1 == c2) continue;
switch (FindMostSpecificType(c1, c2, types[i])) {
case 0: return 0;
case 1: p1Less = true; break;
case 2: p2Less = true; break;
}
}
// Two way p1Less and p2Less can be equal. All the arguments are the
// same they both equal false, otherwise there were things that both
// were the most specific type on....
if (p1Less == p2Less)
{
// if we cannot tell which is a better match based on parameter types (p1Less == p2Less),
// let's see which one has the most matches without using the params array (the longer one wins).
if (!p1Less && args != null)
{
if (p1.Length > p2.Length)
{
return 1;
}
else if (p2.Length > p1.Length)
{
return 2;
}
}
return 0;
}
else
{
return (p1Less == true) ? 1 : 2;
}
}
[System.Security.SecuritySafeCritical] // auto-generated
private static int FindMostSpecificType(Type c1, Type c2, Type t)
{
// If the two types are exact move on...
if (c1 == c2)
return 0;
if (c1 == t)
return 1;
if (c2 == t)
return 2;
bool c1FromC2;
bool c2FromC1;
if (c1.IsByRef || c2.IsByRef)
{
if (c1.IsByRef && c2.IsByRef)
{
c1 = c1.GetElementType();
c2 = c2.GetElementType();
}
else if (c1.IsByRef)
{
if (c1.GetElementType() == c2)
return 2;
c1 = c1.GetElementType();
}
else
{
if (c2.GetElementType() == c1)
return 1;
c2 = c2.GetElementType();
}
}
if (c1.IsPrimitive && c2.IsPrimitive)
{
c1FromC2 = CanConvertPrimitive((RuntimeType)c2, (RuntimeType)c1);
c2FromC1 = CanConvertPrimitive((RuntimeType)c1, (RuntimeType)c2);
}
else
{
c1FromC2 = c1.IsAssignableFrom(c2);
c2FromC1 = c2.IsAssignableFrom(c1);
}
if (c1FromC2 == c2FromC1)
return 0;
if (c1FromC2)
{
return 2;
}
else
{
return 1;
}
}
private static int FindMostSpecificMethod(MethodBase m1, int[] paramOrder1, Type paramArrayType1,
MethodBase m2, int[] paramOrder2, Type paramArrayType2,
Type[] types, Object[] args)
{
// Find the most specific method based on the parameters.
int res = FindMostSpecific(m1.GetParametersNoCopy(), paramOrder1, paramArrayType1,
m2.GetParametersNoCopy(), paramOrder2, paramArrayType2, types, args);
// If the match was not ambigous then return the result.
if (res != 0)
return res;
// Check to see if the methods have the exact same name and signature.
if (CompareMethodSigAndName(m1, m2))
{
// Determine the depth of the declaring types for both methods.
int hierarchyDepth1 = GetHierarchyDepth(m1.DeclaringType);
int hierarchyDepth2 = GetHierarchyDepth(m2.DeclaringType);
// The most derived method is the most specific one.
if (hierarchyDepth1 == hierarchyDepth2)
{
return 0;
}
else if (hierarchyDepth1 < hierarchyDepth2)
{
return 2;
}
else
{
return 1;
}
}
// The match is ambigous.
return 0;
}
private static int FindMostSpecificField(FieldInfo cur1,FieldInfo cur2)
{
// Check to see if the fields have the same name.
if (cur1.Name == cur2.Name)
{
int hierarchyDepth1 = GetHierarchyDepth(cur1.DeclaringType);
int hierarchyDepth2 = GetHierarchyDepth(cur2.DeclaringType);
if (hierarchyDepth1 == hierarchyDepth2) {
Contract.Assert(cur1.IsStatic != cur2.IsStatic, "hierarchyDepth1 == hierarchyDepth2");
return 0;
}
else if (hierarchyDepth1 < hierarchyDepth2)
return 2;
else
return 1;
}
// The match is ambigous.
return 0;
}
private static int FindMostSpecificProperty(PropertyInfo cur1,PropertyInfo cur2)
{
// Check to see if the fields have the same name.
if (cur1.Name == cur2.Name)
{
int hierarchyDepth1 = GetHierarchyDepth(cur1.DeclaringType);
int hierarchyDepth2 = GetHierarchyDepth(cur2.DeclaringType);
if (hierarchyDepth1 == hierarchyDepth2) {
return 0;
}
else if (hierarchyDepth1 < hierarchyDepth2)
return 2;
else
return 1;
}
// The match is ambigous.
return 0;
}
internal static bool CompareMethodSigAndName(MethodBase m1, MethodBase m2)
{
ParameterInfo[] params1 = m1.GetParametersNoCopy();
ParameterInfo[] params2 = m2.GetParametersNoCopy();
if (params1.Length != params2.Length)
return false;
int numParams = params1.Length;
for (int i = 0; i < numParams; i++)
{
if (params1[i].ParameterType != params2[i].ParameterType)
return false;
}
return true;
}
internal static int GetHierarchyDepth(Type t)
{
int depth = 0;
Type currentType = t;
do
{
depth++;
currentType = currentType.BaseType;
} while (currentType != null);
return depth;
}
internal static MethodBase FindMostDerivedNewSlotMeth(MethodBase[] match, int cMatches)
{
int deepestHierarchy = 0;
MethodBase methWithDeepestHierarchy = null;
for (int i = 0; i < cMatches; i++)
{
// Calculate the depth of the hierarchy of the declaring type of the
// current method.
int currentHierarchyDepth = GetHierarchyDepth(match[i].DeclaringType);
// The two methods have the same name, signature, and hierarchy depth.
// This can only happen if at least one is vararg or generic.
if (currentHierarchyDepth == deepestHierarchy)
{
throw new AmbiguousMatchException(Environment.GetResourceString("Arg_AmbiguousMatchException"));
}
// Check to see if this method is on the most derived class.
if (currentHierarchyDepth > deepestHierarchy)
{
deepestHierarchy = currentHierarchyDepth;
methWithDeepestHierarchy = match[i];
}
}
return methWithDeepestHierarchy;
}
// CanConvertPrimitive
// This will determine if the source can be converted to the target type
[System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern bool CanConvertPrimitive(RuntimeType source,RuntimeType target);
// CanConvertPrimitiveObjectToType
// This method will determine if the primitive object can be converted
// to a type.
[System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
static internal extern bool CanConvertPrimitiveObjectToType(Object source,RuntimeType type);
// This method will sort the vars array into the mapping order stored
// in the paramOrder array.
private static void ReorderParams(int[] paramOrder,Object[] vars)
{
object[] varsCopy = new object[vars.Length];
for (int i = 0; i < vars.Length; i ++)
varsCopy[i] = vars[i];
for (int i = 0; i < vars.Length; i ++)
vars[i] = varsCopy[paramOrder[i]];
}
// This method will create the mapping between the Parameters and the underlying
// data based upon the names array. The names array is stored in the same order
// as the values and maps to the parameters of the method. We store the mapping
// from the parameters to the names in the paramOrder array. All parameters that
// don't have matching names are then stored in the array in order.
private static bool CreateParamOrder(int[] paramOrder,ParameterInfo[] pars,String[] names)
{
bool[] used = new bool[pars.Length];
// Mark which parameters have not been found in the names list
for (int i=0;i<pars.Length;i++)
paramOrder[i] = -1;
// Find the parameters with names.
for (int i=0;i<names.Length;i++) {
int j;
for (j=0;j<pars.Length;j++) {
if (names[i].Equals(pars[j].Name)) {
paramOrder[j] = i;
used[i] = true;
break;
}
}
// This is an error condition. The name was not found. This
// method must not match what we sent.
if (j == pars.Length)
return false;
}
// Now we fill in the holes with the parameters that are unused.
int pos = 0;
for (int i=0;i<pars.Length;i++) {
if (paramOrder[i] == -1) {
for (;pos<pars.Length;pos++) {
if (!used[pos]) {
paramOrder[i] = pos;
pos++;
break;
}
}
}
}
return true;
}
internal class BinderState {
internal int[] m_argsMap;
internal int m_originalSize;
internal bool m_isParamArray;
internal BinderState(int[] argsMap, int originalSize, bool isParamArray) {
m_argsMap = argsMap;
m_originalSize = originalSize;
m_isParamArray = isParamArray;
}
}
}
}
| 40.972766 | 160 | 0.46715 | [
"MIT"
] | 1Crazymoney/cs2cpp | CoreLib/System/DefaultBinder.cs | 48,143 | C# |
namespace NWN.FinalFantasy.Service
{
public static class Random
{
private static readonly System.Random _random = new System.Random();
/// <summary>
/// Retrieves the next random integer value.
/// </summary>
/// <returns>The next random integer value.</returns>
public static int Next()
{
return _random.Next();
}
/// <summary>
/// Retrieves the next random integer value, not to exceed the max value.
/// </summary>
/// <param name="max">The max value to randomly get.</param>
/// <returns>The next random integer value.</returns>
public static int Next(int max)
{
return _random.Next(max);
}
/// <summary>
/// Retrieves the next random integer value, not to fall outside of the min and max range.
/// </summary>
/// <param name="min">The minimum value</param>
/// <param name="max">The maximum value</param>
/// <returns>The next random integer value</returns>
public static int Next(int min, int max)
{
return _random.Next(min, max);
}
/// <summary>
/// Retrieves the next random float value
/// </summary>
/// <returns>The next random float value</returns>
public static float NextFloat()
{
return (float)_random.NextDouble();
}
/// <summary>
/// Retrieves the next random float value, not to fall outside of the min and max range.
/// </summary>
/// <param name="min">The minimum value</param>
/// <param name="max">The maximum value</param>
/// <returns>The next random float value</returns>
public static float NextFloat(float min, float max)
{
return (float)(_random.NextDouble() * (max - min) + min);
}
/// <summary>
/// Retrieves a random index out of the provided weight values.
/// </summary>
/// <param name="weights">The array of weights to randomly select from</param>
/// <returns>The index of the selected value</returns>
public static int GetRandomWeightedIndex(int[] weights)
{
int totalWeight = 0;
foreach (int weight in weights)
{
totalWeight += weight;
}
int randomIndex = -1;
double random = NextFloat() * totalWeight;
for (int i = 0; i < weights.Length; ++i)
{
random -= weights[i];
if (random <= 0.0d)
{
randomIndex = i;
break;
}
}
return randomIndex;
}
/// <summary>
/// Rolls a certain number of dice.
/// </summary>
/// <param name="numberOfDice">The number of dice to roll. Minimum is 1</param>
/// <param name="min">The minimum number on each die. Minimum is 1</param>
/// <param name="max">The maximum number on each die. Minimum is 1</param>
/// <returns>A random value selected based on the configured parameters</returns>
private static int RollDice(int numberOfDice, int min, int max)
{
if (numberOfDice < 1) numberOfDice = 1;
if (min < 1) min = 1;
if (min > max) min = max;
int result = 0;
for (int x = 1; x <= numberOfDice; x++)
{
result += _random.Next(min, max);
}
return result;
}
/// <summary>
/// Rolls dice with 2 sides.
/// </summary>
/// <param name="numberOfDice">The number of dice to roll</param>
/// <param name="minimum">The minimum value.</param>
/// <returns>A random value selected base on the parameters.</returns>
public static int D2(int numberOfDice, int minimum = 1)
{
return RollDice(numberOfDice, minimum, 2);
}
/// <summary>
/// Rolls dice with 3 sides.
/// </summary>
/// <param name="numberOfDice">The number of dice to roll</param>
/// <param name="minimum">The minimum value.</param>
/// <returns>A random value selected base on the parameters.</returns>
public static int D3(int numberOfDice, int minimum = 1)
{
return RollDice(numberOfDice, minimum, 3);
}
/// <summary>
/// Rolls dice with 4 sides.
/// </summary>
/// <param name="numberOfDice">The number of dice to roll</param>
/// <param name="minimum">The minimum value.</param>
/// <returns>A random value selected base on the parameters.</returns>
public static int D4(int numberOfDice, int minimum = 1)
{
return RollDice(numberOfDice, minimum, 4);
}
/// <summary>
/// Rolls dice with 6 sides.
/// </summary>
/// <param name="numberOfDice">The number of dice to roll</param>
/// <param name="minimum">The minimum value.</param>
/// <returns>A random value selected base on the parameters.</returns>
public static int D6(int numberOfDice, int minimum = 1)
{
return RollDice(numberOfDice, minimum, 6);
}
/// <summary>
/// Rolls dice with 8 sides.
/// </summary>
/// <param name="numberOfDice">The number of dice to roll</param>
/// <param name="minimum">The minimum value.</param>
/// <returns>A random value selected base on the parameters.</returns>
public static int D8(int numberOfDice, int minimum = 1)
{
return RollDice(numberOfDice, minimum, 8);
}
/// <summary>
/// Rolls dice with 10 sides.
/// </summary>
/// <param name="numberOfDice">The number of dice to roll</param>
/// <param name="minimum">The minimum value.</param>
/// <returns>A random value selected base on the parameters.</returns>
public static int D10(int numberOfDice, int minimum = 1)
{
return RollDice(numberOfDice, minimum, 10);
}
/// <summary>
/// Rolls dice with 12 sides.
/// </summary>
/// <param name="numberOfDice">The number of dice to roll</param>
/// <param name="minimum">The minimum value.</param>
/// <returns>A random value selected base on the parameters.</returns>
public static int D12(int numberOfDice, int minimum = 1)
{
return RollDice(numberOfDice, minimum, 12);
}
/// <summary>
/// Rolls dice with 20 sides.
/// </summary>
/// <param name="numberOfDice">The number of dice to roll</param>
/// <param name="minimum">The minimum value.</param>
/// <returns>A random value selected base on the parameters.</returns>
public static int D20(int numberOfDice, int minimum = 1)
{
return RollDice(numberOfDice, minimum, 20);
}
/// <summary>
/// Rolls dice with 100 sides.
/// </summary>
/// <param name="numberOfDice">The number of dice to roll</param>
/// <param name="minimum">The minimum value.</param>
/// <returns>A random value selected base on the parameters.</returns>
public static int D100(int numberOfDice, int minimum = 1)
{
return RollDice(numberOfDice, minimum, 100);
}
}
}
| 36.584541 | 98 | 0.544302 | [
"MIT"
] | Martinus-1453/NWN.FinalFantasy | NWN.FinalFantasy/Service/Random.cs | 7,575 | C# |
/******************************************************************************
* Spine Runtimes License Agreement
* Last updated January 1, 2020. Replaces all prior versions.
*
* Copyright (c) 2013-2020, Esoteric Software LLC
*
* Integration of the Spine Runtimes into software or otherwise creating
* derivative works of the Spine Runtimes is permitted under the terms and
* conditions of Section 2 of the Spine Editor License Agreement:
* http://esotericsoftware.com/spine-editor-license
*
* Otherwise, it is permitted to integrate the Spine Runtimes into software
* or otherwise create derivative works of the Spine Runtimes (collectively,
* "Products"), provided that each user of the Products must obtain their own
* Spine Editor license and redistribution of the Products in any form must
* include this license and copyright notice.
*
* THE SPINE RUNTIMES ARE PROVIDED BY ESOTERIC SOFTWARE LLC "AS IS" AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL ESOTERIC SOFTWARE LLC BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES,
* BUSINESS INTERRUPTION, OR LOSS OF USE, DATA, OR PROFITS) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THE SPINE RUNTIMES, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*****************************************************************************/
using UnityEngine;
using System.Collections;
using Spine.Unity;
namespace Spine.Unity.Examples {
public class RaggedySpineboy : MonoBehaviour {
public LayerMask groundMask;
public float restoreDuration = 0.5f;
public Vector2 launchVelocity = new Vector2(50,100);
Spine.Unity.Examples.SkeletonRagdoll2D ragdoll;
Collider2D naturalCollider;
void Start () {
ragdoll = GetComponent<Spine.Unity.Examples.SkeletonRagdoll2D>();
naturalCollider = GetComponent<Collider2D>();
}
void AddRigidbody () {
var rb = gameObject.AddComponent<Rigidbody2D>();
rb.freezeRotation = true;
naturalCollider.enabled = true;
}
void RemoveRigidbody () {
Destroy(GetComponent<Rigidbody2D>());
naturalCollider.enabled = false;
}
void OnMouseUp () {
if (naturalCollider.enabled)
Launch();
}
void Launch () {
RemoveRigidbody();
ragdoll.Apply();
ragdoll.RootRigidbody.velocity = new Vector2(Random.Range(-launchVelocity.x, launchVelocity.x), launchVelocity.y);
StartCoroutine(WaitUntilStopped());
}
IEnumerator Restore () {
Vector3 estimatedPos = ragdoll.EstimatedSkeletonPosition;
Vector3 rbPosition = ragdoll.RootRigidbody.position;
Vector3 skeletonPoint = estimatedPos;
RaycastHit2D hit = Physics2D.Raycast((Vector2)rbPosition, (Vector2)(estimatedPos - rbPosition), Vector3.Distance(estimatedPos, rbPosition), groundMask);
if (hit.collider != null)
skeletonPoint = hit.point;
ragdoll.RootRigidbody.isKinematic = true;
ragdoll.SetSkeletonPosition(skeletonPoint);
yield return ragdoll.SmoothMix(0, restoreDuration);
ragdoll.Remove();
AddRigidbody();
}
IEnumerator WaitUntilStopped () {
yield return new WaitForSeconds(0.5f);
float t = 0;
while (t < 0.5f) {
t = (ragdoll.RootRigidbody.velocity.magnitude > 0.09f) ? 0 : t + Time.deltaTime;
yield return null;
}
StartCoroutine(Restore());
}
}
}
| 36.126214 | 156 | 0.693093 | [
"Apache-2.0"
] | bob-ben-star/dameforcode | Assets/Spine Examples/Scripts/RaggedySpineboy.cs | 3,721 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using Microsoft.AspNet.Identity.Owin;
using Microsoft.Owin.Security;
using Owin;
using BookstoreWebForms.Models;
namespace BookstoreWebForms.Account
{
public partial class Manage : System.Web.UI.Page
{
protected string SuccessMessage
{
get;
private set;
}
private bool HasPassword(ApplicationUserManager manager)
{
return manager.HasPassword(User.Identity.GetUserId());
}
public bool HasPhoneNumber { get; private set; }
public bool TwoFactorEnabled { get; private set; }
public bool TwoFactorBrowserRemembered { get; private set; }
public int LoginsCount { get; set; }
protected void Page_Load()
{
var manager = Context.GetOwinContext().GetUserManager<ApplicationUserManager>();
HasPhoneNumber = String.IsNullOrEmpty(manager.GetPhoneNumber(User.Identity.GetUserId()));
// Enable this after setting up two-factor authentientication
//PhoneNumber.Text = manager.GetPhoneNumber(User.Identity.GetUserId()) ?? String.Empty;
TwoFactorEnabled = manager.GetTwoFactorEnabled(User.Identity.GetUserId());
LoginsCount = manager.GetLogins(User.Identity.GetUserId()).Count;
var authenticationManager = HttpContext.Current.GetOwinContext().Authentication;
if (!IsPostBack)
{
// Determine the sections to render
if (HasPassword(manager))
{
ChangePassword.Visible = true;
}
else
{
CreatePassword.Visible = true;
ChangePassword.Visible = false;
}
// Render success message
var message = Request.QueryString["m"];
if (message != null)
{
// Strip the query string from action
Form.Action = ResolveUrl("~/Account/Manage");
SuccessMessage =
message == "ChangePwdSuccess" ? "Your password has been changed."
: message == "SetPwdSuccess" ? "Your password has been set."
: message == "RemoveLoginSuccess" ? "The account was removed."
: message == "AddPhoneNumberSuccess" ? "Phone number has been added"
: message == "RemovePhoneNumberSuccess" ? "Phone number was removed"
: String.Empty;
successMessage.Visible = !String.IsNullOrEmpty(SuccessMessage);
}
}
}
private void AddErrors(IdentityResult result)
{
foreach (var error in result.Errors)
{
ModelState.AddModelError("", error);
}
}
// Remove phonenumber from user
protected void RemovePhone_Click(object sender, EventArgs e)
{
var manager = Context.GetOwinContext().GetUserManager<ApplicationUserManager>();
var signInManager = Context.GetOwinContext().Get<ApplicationSignInManager>();
var result = manager.SetPhoneNumber(User.Identity.GetUserId(), null);
if (!result.Succeeded)
{
return;
}
var user = manager.FindById(User.Identity.GetUserId());
if (user != null)
{
signInManager.SignIn(user, isPersistent: false, rememberBrowser: false);
Response.Redirect("/Account/Manage?m=RemovePhoneNumberSuccess");
}
}
// DisableTwoFactorAuthentication
protected void TwoFactorDisable_Click(object sender, EventArgs e)
{
var manager = Context.GetOwinContext().GetUserManager<ApplicationUserManager>();
manager.SetTwoFactorEnabled(User.Identity.GetUserId(), false);
Response.Redirect("/Account/Manage");
}
//EnableTwoFactorAuthentication
protected void TwoFactorEnable_Click(object sender, EventArgs e)
{
var manager = Context.GetOwinContext().GetUserManager<ApplicationUserManager>();
manager.SetTwoFactorEnabled(User.Identity.GetUserId(), true);
Response.Redirect("/Account/Manage");
}
}
} | 35.867188 | 101 | 0.585711 | [
"MIT"
] | PhilipYordanov/BookstoreService | BookstoreService/BookstoreWebForms/Account/Manage.aspx.cs | 4,593 | C# |
using System;
using System.Collections.Generic;
using System.Text;
namespace MilitaryElite.Exceptions
{
public class InvalidMissionStateException : Exception
{
private const string DEF_EXC_MSG = "Invalid mission state!";
public InvalidMissionStateException()
: base(DEF_EXC_MSG)
{
}
public InvalidMissionStateException(string message)
: base(message)
{
}
}
}
| 21.619048 | 68 | 0.638767 | [
"MIT"
] | StelaKaneva/Csharp-OOP | InterfacesAndAbstraction/Exercise/MilitaryElite/MilitaryElite/MilitaryElite/Exceptions/InvalidMissionStateException.cs | 456 | C# |
// Copyright (c) 2016 Jon P Smith, GitHub: JonPSmith, web: http://www.thereformedprogrammer.net/
// Licensed under MIT license. See License.txt in the project root for license information.
using System;
namespace ServiceLayer.BookServices
{
public class BookListDto
{
public int BookId { get; set; }
public string Title { get; set; }
public DateTime PublishedOn { get; set; }
public decimal OrgPrice { get; set; }
public decimal ActualPrice { get; set; }
public string PromotionalText { get; set; }
public string AuthorsOrdered { get; set; }
public int ReviewsCount { get; set; }
public double? ReviewsAverageVotes { get; set; }
}
} | 34 | 97 | 0.603581 | [
"MIT"
] | JonPSmith/EfCore.GenericBizRunner | ServiceLayer/BookServices/BookListDto.cs | 784 | C# |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the MIT license. See License.txt in the project root for license information.
using DslResources = Microsoft.Data.Entity.Design.EntityDesigner.Properties.Resources;
using Model = Microsoft.Data.Entity.Design.Model.Entity;
namespace Microsoft.Data.Entity.Design.EntityDesigner.ViewModel
{
using System;
using System.Collections.Generic;
using System.Globalization;
using Microsoft.Data.Entity.Design.Model.Entity;
abstract partial class EntityTypeBase
{
public string EntitySetName
{
get
{
if (EntityDesignerViewModel != null)
{
var modelEntityType = EntityDesignerViewModel.ModelXRef.GetExisting(this) as Model.Entity.EntityType;
if (modelEntityType != null)
{
var entitySet = modelEntityType.EntitySet;
if (entitySet != null)
{
return entitySet.DisplayName;
}
}
}
return "";
}
}
public string GetBaseTypeNameValue()
{
// optimistic fix for https://entityframework.codeplex.com/workitem/1143
var modelXRef = EntityDesignerViewModel.ModelXRef;
if (modelXRef == null)
{
return string.Empty;
}
// We need to look at the model to get the base-type name; the view-model might not have it.
// In multiple diagram scenario, the base entity-type might not exist in the current diagram.
var modelEntityType = modelXRef.GetExisting(this) as ConceptualEntityType;
if (modelEntityType != null
&& modelEntityType.BaseType != null
&& modelEntityType.BaseType.Target != null)
{
return modelEntityType.BaseType.Target.DisplayName.Trim();
}
return String.Empty;
}
public bool GetHasBaseTypeValue()
{
return (String.IsNullOrEmpty(GetBaseTypeNameValue()) == false);
}
/// <summary>
/// Walks entity properties and returns a comma-separated string with key property names
/// </summary>
/// <param name="separator"></param>
/// <returns></returns>
public string GetKeyNamesSeparatedBy(string separator)
{
var separatedKeys = String.Empty;
try
{
var keyList = new List<String>();
foreach (var property in GetKeyProperties())
{
keyList.Add(property.Name);
}
separatedKeys = String.Join(separator, keyList.ToArray());
}
catch (InvalidOperationException)
{
// Detected circular inheritance, nothing to do!
}
return separatedKeys;
}
/// <summary>
/// Recursively walks the base type hierarchy and returns properties that are keys.
/// Also checks for circular inheritance and throws an InvalidOperationException if found.
/// </summary>
/// <returns></returns>
internal List<Property> GetKeyProperties()
{
var circularPath = String.Empty;
if (HasCircularInheritance(out circularPath))
{
throw new InvalidOperationException(
String.Format(
CultureInfo.CurrentCulture,
DslResources.Error_CircularEntityInheritanceFound,
Name, circularPath));
}
var keyProperties = new List<Property>();
if (BaseType != null)
{
keyProperties.AddRange(BaseType.GetKeyProperties());
}
else
{
keyProperties.AddRange(GetLocalKeyProperties());
}
return keyProperties;
}
/// <summary>
/// Returns a list of key properties that are defined locally in this Entity.
/// </summary>
/// <returns></returns>
internal List<Property> GetLocalKeyProperties()
{
var keyProperties = new List<Property>();
foreach (var property in Properties)
{
var scalarProperty = property as ScalarProperty;
if (scalarProperty != null
&& scalarProperty.EntityKey)
{
keyProperties.Add(property);
}
}
return keyProperties;
}
/// <summary>
/// Detects if this entity has a circular inheritance
/// </summary>
/// <param name="circularPathFound"></param>
/// <returns></returns>
internal bool HasCircularInheritance(out string circularPathFound)
{
var hasCircularInheritance = false;
var visited = new Dictionary<EntityTypeBase, int>();
visited.Add(this, 0);
var circularPath = Name;
circularPathFound = circularPath;
var baseType = BaseType;
while (baseType != null)
{
circularPath += " -> " + baseType.Name;
if (visited.ContainsKey(baseType))
{
circularPathFound = circularPath;
hasCircularInheritance = true;
break;
}
visited.Add(baseType, 0);
baseType = baseType.BaseType;
}
return hasCircularInheritance;
}
public override string ToString()
{
return Name;
}
/// <summary>
/// Returns all properties and navigation properties names (recursively including baseType properties)
/// </summary>
/// <returns></returns>
internal List<string> GetPropertiesNames()
{
List<string> names = null;
if (BaseType != null)
{
names = BaseType.GetPropertiesNames();
}
else
{
names = new List<string>();
}
foreach (var property in Properties)
{
names.Add(property.Name);
}
foreach (var navProp in NavigationProperties)
{
names.Add(navProp.Name);
}
return names;
}
}
}
| 33.108374 | 145 | 0.517334 | [
"MIT"
] | dotnet/ef6tools | src/EFTools/EntityDesignEntityDesigner/CustomCode/DomainClasses/EntityTypeBase.cs | 6,723 | C# |
using System;
using System.IO;
namespace SharpPhysFS
{
public class PhysFSStream : Stream
{
IntPtr handle;
bool readOnly = false;
PhysFS physFS;
internal PhysFSStream(PhysFS pfs, IntPtr ptr, bool readOnly)
{
handle = ptr;
this.readOnly = readOnly;
physFS = pfs;
}
public override bool CanRead
{
get
{
return true;
}
}
public override bool CanSeek
{
get
{
return true;
}
}
public override bool CanWrite
{
get
{
return !readOnly;
}
}
public override void Flush()
{
PhysFS.LowLevel.Flush(handle, physFS);
}
public override long Length
{
get
{
return PhysFS.LowLevel.FileLength(handle);
}
}
public override long Position
{
get
{
return PhysFS.LowLevel.Tell(handle);
}
set
{
PhysFS.LowLevel.Seek(handle, (ulong)value, physFS);
}
}
public long Read(byte[] buffer, int offset, uint count)
{
return PhysFS.LowLevel.Read(handle, buffer, 1, count, offset);
}
public override int Read(byte[] buffer, int offset, int count)
{
return (int)Read(buffer, offset, (uint)count);
}
public override long Seek(long offset, SeekOrigin origin)
{
long pos = 0;
if (origin == SeekOrigin.Begin)
pos = 0;
else if (origin == SeekOrigin.Current)
pos = PhysFS.LowLevel.Tell(handle);
else
pos = PhysFS.LowLevel.FileLength(handle);
PhysFS.LowLevel.Seek(handle, (ulong)(pos + offset), physFS);
return pos + offset;
}
public long Write(byte[] buffer, uint offset, uint count)
{
return PhysFS.LowLevel.Write(handle, buffer, 1, count);
}
public override void Write(byte[] buffer, int offset, int count)
{
Write(buffer, (uint)offset, (uint)count);
}
public override void SetLength(long value)
{
throw new NotImplementedException();
}
protected override void Dispose(bool disposing)
{
if(disposing)
{
if (handle != IntPtr.Zero)
{
PhysFS.LowLevel.Close(handle, physFS);
handle = IntPtr.Zero;
}
}
base.Dispose(disposing);
}
}
}
| 19.247934 | 68 | 0.565908 | [
"MIT"
] | etinquis/SharpPhysFS | SharpPhysFS/PhysFSStream.cs | 2,331 | C# |
// $Id$
//
// Copyright 2008 The AnkhSVN 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.
#region Copyright And Revision History
/*---------------------------------------------------------------------------
DiagonalVector.cs
Copyright (c) 2002 Bill Menees. All rights reserved.
[email protected]
Who When What
------- ---------- -----------------------------------------------------
BMenees 10.20.2002 Created.
-----------------------------------------------------------------------------*/
#endregion
using System;
using System.Diagnostics;
namespace Ankh.Diff.DiffUtils
{
/// <summary>
/// Implements a vector from -MAX to MAX
/// </summary>
internal sealed class DiagonalVector
{
int m_iMax;
int[] m_arData;
public DiagonalVector(int N, int M)
{
int iDelta = N - M;
//We have to add Delta to support reverse vectors, which are
//centered around the Delta diagonal instead of the 0 diagonal.
m_iMax = N + M + Math.Abs(iDelta);
//Create an array of size 2*MAX+1 to hold -MAX..+MAX.
m_arData = new int[2 * m_iMax + 1];
}
public int this[int iUserIndex]
{
get
{
return m_arData[GetActualIndex(iUserIndex)];
}
set
{
m_arData[GetActualIndex(iUserIndex)] = value;
}
}
private int GetActualIndex(int iUserIndex)
{
int iIndex = iUserIndex + m_iMax;
Debug.Assert(iIndex >= 0 && iIndex < m_arData.Length);
return iIndex;
}
}
}
| 28.038462 | 79 | 0.540924 | [
"Apache-2.0"
] | AnkhSVN/AnkhSVN | src/Ankh.Diff/DiffUtils/Classes/DiagonalVector.cs | 2,187 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the Apache 2.0 License.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Globalization;
using System.Linq.Expressions;
using System.Reflection;
namespace System.Linq
{
/// <summary>
/// Rewrites an expression tree representation using AsyncQueryable methods to the corresponding AsyncEnumerable equivalents.
/// </summary>
internal class AsyncEnumerableRewriter : ExpressionVisitor
{
private static volatile ILookup<string, MethodInfo> _methods;
protected override Expression VisitConstant(ConstantExpression node)
{
//
// Not an expression representation obtained from the async enumerable query provider,
// so just a plain constant that can be returned as-is.
//
if (!(node.Value is AsyncEnumerableQuery enumerableQuery))
{
return node;
}
//
// Expression representation obtained from the async enumerable query provider, so first
// check whether it wraps an enumerable sequence that has been evaluated already.
//
if (enumerableQuery.Enumerable != null)
{
var publicType = GetPublicType(enumerableQuery.Enumerable.GetType());
return Expression.Constant(enumerableQuery.Enumerable, publicType);
}
//
// If not evaluated yet, inline the expression representation.
//
return Visit(enumerableQuery.Expression);
}
protected override Expression VisitMethodCall(MethodCallExpression node)
{
var obj = Visit(node.Object);
var args = Visit(node.Arguments);
//
// Nothing changed during the visit; just some unrelated method call that can
// be returned as-is.
//
if (obj == node.Object && args == node.Arguments)
{
return node;
}
var typeArgs = node.Method.IsGenericMethod ? node.Method.GetGenericArguments() : null;
//
// Check whether the method is compatible with the recursively rewritten instance
// and arguments expressions. If so, create a new call expression.
//
if ((node.Method.IsStatic || node.Method.DeclaringType.IsAssignableFrom(obj.Type)) && ArgsMatch(node.Method, args, typeArgs))
{
return Expression.Call(obj, node.Method, args);
}
MethodInfo method;
//
// Find a corresponding method in the non-expression world, e.g. rewriting from
// the AsyncQueryable methods to the ones on AsyncEnumerable.
//
if (node.Method.DeclaringType == typeof(AsyncQueryable))
{
method = FindEnumerableMethod(node.Method.Name, args, typeArgs);
args = FixupQuotedArgs(method, args);
return Expression.Call(obj, method, args);
}
else
{
method = FindMethod(node.Method.DeclaringType, node.Method.Name, args, typeArgs, BindingFlags.Static | (node.Method.IsPublic ? BindingFlags.Public : BindingFlags.NonPublic));
args = FixupQuotedArgs(method, args);
}
return Expression.Call(obj, method, args);
}
protected override Expression VisitLambda<T>(Expression<T> node)
{
//
// Don't recurse into lambdas; all the ones returning IAsyncQueryable<T>
// are compatible with their IAsyncEnumerable<T> counterparts due to the
// covariant return type.
//
return node;
}
protected override Expression VisitParameter(ParameterExpression node)
{
//
// See remark on VisitLambda.
//
return node;
}
private static Type GetPublicType(Type type)
{
if (!type.GetTypeInfo().IsNestedPrivate)
{
return type;
}
foreach (var ifType in type.GetInterfaces())
{
if (ifType.GetTypeInfo().IsGenericType)
{
var def = ifType.GetGenericTypeDefinition();
if (def == typeof(IAsyncEnumerable<>) || def == typeof(IAsyncGrouping<,>))
{
return ifType;
}
}
}
//
// NB: Add if we ever decide to add the non-generic interface.
//
//if (typeof(IAsyncEnumerable).IsAssignableFrom(type))
//{
// return typeof(IAsyncEnumerable);
//}
return type;
}
private static bool ArgsMatch(MethodInfo method, ReadOnlyCollection<Expression> args, Type[]? typeArgs)
{
//
// Number of parameters should match the number of arguments to bind.
//
var parameters = method.GetParameters();
if (parameters.Length != args.Count)
{
return false;
}
//
// Both should be generic or non-generic.
//
if (!method.IsGenericMethod && typeArgs != null && typeArgs.Length != 0)
{
return false;
}
//
// Closed generic methods need to get converted to their open generic counterpart.
//
if (!method.IsGenericMethodDefinition && method.IsGenericMethod && method.ContainsGenericParameters)
{
method = method.GetGenericMethodDefinition();
}
//
// For generic methods, close the candidate using the specified type arguments.
//
if (method.IsGenericMethodDefinition)
{
//
// We should have at least 1 type argument.
//
if (typeArgs == null || typeArgs.Length == 0)
{
return false;
}
//
// The number of type arguments needed should match the specified type argument count.
//
if (method.GetGenericArguments().Length != typeArgs.Length)
{
return false;
}
//
// Close the generic method and re-obtain the parameters.
//
method = method.MakeGenericMethod(typeArgs);
parameters = method.GetParameters();
}
//
// Check for contravariant assignability of each parameter.
//
for (var i = 0; i < args.Count; i++)
{
var type = parameters[i].ParameterType;
//
// Hardening against reflection quirks.
//
if (type == null)
{
return false;
}
//
// Deal with ref or out parameters by using the element type which can
// match the corresponding expression type (ref passing is not encoded
// in the type of expression trees).
//
if (type.IsByRef)
{
type = type.GetElementType();
}
var expression = args[i];
//
// If the expression is assignable to the parameter, all is good. If not,
// it's possible there's a match because we're dealing with a quote that
// needs to be unpacked.
//
if (!type.IsAssignableFrom(expression.Type))
{
//
// Unpack the quote, if any. See AsyncQueryable for examples of operators
// that hit this case.
//
if (expression.NodeType == ExpressionType.Quote)
{
expression = ((UnaryExpression)expression).Operand;
}
//
// Try assigning the raw expression type or the quote-free expression type
// to the parameter. If none of these work, there's no match.
//
if (!type.IsAssignableFrom(expression.Type) && !type.IsAssignableFrom(StripExpression(expression.Type)))
{
return false;
}
}
}
return true;
}
private static ReadOnlyCollection<Expression> FixupQuotedArgs(MethodInfo method, ReadOnlyCollection<Expression> argList)
{
//
// Get all of the method parameters. No fix-up needed if empty.
//
var parameters = method.GetParameters();
if (parameters.Length != 0)
{
var list = default(List<Expression>);
//
// Process all parameters. If any fixup is needed, the list will
// get assigned.
//
for (var i = 0; i < parameters.Length; i++)
{
var expression = argList[i];
var parameterInfo = parameters[i];
//
// Perform the fix-up if needed and check the outcome. If a
// change was made, the list is lazily allocated.
//
expression = FixupQuotedExpression(parameterInfo.ParameterType, expression);
if (list == null && expression != argList[i])
{
list = new List<Expression>(argList.Count);
for (var j = 0; j < i; j++)
{
list.Add(argList[j]);
}
}
if (list != null)
{
list.Add(expression);
}
}
//
// If any argument was fixed up, return a new argument list.
//
if (list != null)
{
argList = new ReadOnlyCollection<Expression>(list);
}
}
return argList;
}
private static Expression FixupQuotedExpression(Type type, Expression expression)
{
var res = expression;
//
// Keep unquoting until assignability checks pass.
//
while (!type.IsAssignableFrom(res.Type))
{
//
// In case this is not a quote, bail out early.
//
if (res.NodeType != ExpressionType.Quote)
{
//
// Array initialization expressions need special care by unquoting the elements.
//
if (!type.IsAssignableFrom(res.Type) && type.IsArray && res.NodeType == ExpressionType.NewArrayInit)
{
var unquotedType = StripExpression(res.Type);
if (type.IsAssignableFrom(unquotedType))
{
var newArrayExpression = (NewArrayExpression)res;
var count = newArrayExpression.Expressions.Count;
var elementType = type.GetElementType();
var list = new List<Expression>(count);
for (var i = 0; i < count; i++)
{
list.Add(FixupQuotedExpression(elementType, newArrayExpression.Expressions[i]));
}
expression = Expression.NewArrayInit(elementType, list);
}
}
return expression;
}
//
// Unquote and try again; at most two passes should be needed.
//
res = ((UnaryExpression)res).Operand;
}
return res;
}
private static Type StripExpression(Type type)
{
//
// Array of quotes need to be stripped, so extract the element type.
//
var elemType = type.IsArray ? type.GetElementType() : type;
//
// Try to find Expression<T> and obtain T.
//
var genType = FindGenericType(typeof(Expression<>), elemType);
if (genType != null)
{
elemType = genType.GetGenericArguments()[0];
}
//
// Not an array, nothing to do here.
//
if (!type.IsArray)
{
return type;
}
//
// Reconstruct the array type from the stripped element type.
//
var arrayRank = type.GetArrayRank();
if (arrayRank != 1)
{
return elemType.MakeArrayType(arrayRank);
}
return elemType.MakeArrayType();
}
private static MethodInfo FindEnumerableMethod(string name, ReadOnlyCollection<Expression> args, params Type[]? typeArgs)
{
//
// Ensure the cached lookup table for AsyncEnumerable methods is initialized.
//
if (_methods == null)
{
_methods = typeof(AsyncEnumerable).GetMethods(BindingFlags.Static | BindingFlags.Public).ToLookup(m => m.Name);
}
//
// Find a match based on the method name and the argument types.
//
var method = _methods[name].FirstOrDefault(m => ArgsMatch(m, args, typeArgs));
if (method == null)
{
throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, "Could not find method with name '{0}' on type '{1}'.", name, typeof(Enumerable)));
}
//
// Close the generic method if needed.
//
if (typeArgs != null)
{
return method.MakeGenericMethod(typeArgs);
}
return method;
}
private static MethodInfo FindMethod(Type type, string name, ReadOnlyCollection<Expression> args, Type[]? typeArgs, BindingFlags flags)
{
//
// Support the enumerable methods to be defined on another type.
//
var targetType = type.GetTypeInfo().GetCustomAttribute<LocalQueryMethodImplementationTypeAttribute>()?.TargetType ?? type;
//
// Get all the candidates based on name and fail if none are found.
//
var methods = targetType.GetMethods(flags).Where(m => m.Name == name).ToArray();
if (methods.Length == 0)
{
throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, "Could not find method with name '{0}' on type '{1}'.", name, type));
}
//
// Find a match based on arguments and fail if no match is found.
//
var method = methods.FirstOrDefault(m => ArgsMatch(m, args, typeArgs));
if (method == null)
{
throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, "Could not find a matching method with name '{0}' on type '{1}'.", name, type));
}
//
// Close the generic method if needed.
//
if (typeArgs != null)
{
return method.MakeGenericMethod(typeArgs);
}
return method;
}
private static Type? FindGenericType(Type definition, Type type)
{
while (type != null && type != typeof(object))
{
//
// If the current type matches the specified definition, return.
//
if (type.GetTypeInfo().IsGenericType && type.GetGenericTypeDefinition() == definition)
{
return type;
}
//
// Probe all interfaces implemented by the current type.
//
if (definition.GetTypeInfo().IsInterface)
{
foreach (var ifType in type.GetInterfaces())
{
var res = FindGenericType(definition, ifType);
if (res != null)
{
return res;
}
}
}
//
// Continue up the type hierarchy.
//
type = type.GetTypeInfo().BaseType;
}
return null;
}
}
}
| 35.51417 | 190 | 0.486434 | [
"Apache-2.0"
] | giusepe/reactive | Ix.NET/Source/System.Linq.Async.Queryable/System/Linq/AsyncEnumerableRewriter.cs | 17,546 | C# |
using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("AWSSDK.SQS")]
[assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (3.5) - Amazon Simple Queue Service. Amazon Simple Queue Service (SQS) is a fast, reliable, scalable, fully managed message queuing service. SQS makes it simple and cost-effective to decouple the components of a cloud application.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyProduct("Amazon Web Services SDK for .NET")]
[assembly: AssemblyCompany("Amazon.com, Inc")]
[assembly: AssemblyCopyright("Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("3.3")]
[assembly: AssemblyFileVersion("3.7.2.5")] | 48.6875 | 302 | 0.751605 | [
"Apache-2.0"
] | jamieromanowski/aws-sdk-net | sdk/code-analysis/ServiceAnalysis/SQS/Properties/AssemblyInfo.cs | 1,558 | C# |
using System.Collections.Generic;
using System.Threading;
using GraphQL.Conversion;
using GraphQL.Execution;
using GraphQL.Instrumentation;
using GraphQL.Introspection;
using GraphQL.Language.AST;
using GraphQL.Types;
using GraphQL.Validation;
using GraphQL.Validation.Complexity;
namespace GraphQL
{
public class ExecutionOptions
{
public ISchema Schema { get; set; }
public object Root { get; set; }
public string Query { get; set; }
public string OperationName { get; set; }
public Document Document { get; set; }
public Inputs Inputs { get; set; }
public CancellationToken CancellationToken { get; set; } = default;
public IEnumerable<IValidationRule> ValidationRules { get; set; }
public IDictionary<string, object> UserContext { get; set; } = new Dictionary<string, object>();
public IFieldMiddlewareBuilder FieldMiddleware { get; set; } = new FieldMiddlewareBuilder();
public ComplexityConfiguration ComplexityConfiguration { get; set; } = null;
public IList<IDocumentExecutionListener> Listeners { get; } = new List<IDocumentExecutionListener>();
public IFieldNameConverter FieldNameConverter { get; set; } = CamelCaseFieldNameConverter.Instance;
public bool ExposeExceptions { get; set; } = false;
//Note disabling will increase performance
public bool EnableMetrics { get; set; } = true;
//Note disabling will increase performance. When true all nodes will have the middleware injected for resolving fields.
public bool SetFieldMiddleware { get; set; } = true;
public bool ThrowOnUnhandledException { get; set; } = false;
/// <summary>
/// Provides the ability to filter the schema upon introspection to hide types.
/// </summary>
public ISchemaFilter SchemaFilter { get; set; } = new DefaultSchemaFilter();
}
}
| 40.125 | 127 | 0.695223 | [
"MIT"
] | chrisandflora/financial-Blessings | src/GraphQL/Execution/ExecutionOptions.cs | 1,926 | C# |
using System;
namespace Genbox.WolframAlpha.Objects
{
public class Source
{
public Uri Url { get; set; }
public string Text { get; set; }
}
} | 17.1 | 40 | 0.596491 | [
"MIT"
] | Genbox/WolframAlpha | src/WolframAlpha/Objects/Source.cs | 173 | C# |
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Acme.Biz;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Acme.Biz.Tests
{
[TestClass()]
public class ProductTests
{
[TestMethod()]
public void CalculateSuggestedPriceTest()
{
//Arrange
var currentProduct = new Product(1, "Saw", "");
currentProduct.Cost = 50m;
var expected = 55m;
//Act
var actual = currentProduct.CalculateSuggestedPrice(10m);
//Assert
Assert.AreEqual(expected,actual);
}
}
}
namespace Acme.Biz
{
/// <summary>
/// Summary description for ProductTests
/// </summary>
[TestClass]
public class ProductTests
{
[TestMethod()]
public void SayHelloTest()
{
//Arrange
var currentProduct = new Product();
currentProduct.ProductName = "saw";
currentProduct.ProductId = 1;
currentProduct.ProductVendor.CompanyName = "ABC Corp";
currentProduct.Description = "15-inch steel blade hand saw";
var expected = "Hello saw (1): 15-inch steel blade hand saw" + " Available on: ";
//Act
var actual = currentProduct.SayHello();
//Assert
Assert.AreEqual(expected, actual);
}
[TestMethod()]
public void SayHello_ParameterisedConstructor()
{
//Arrange
var currentProduct = new Product
{
ProductId = 1,
ProductName = "saw",
Description = "15-inch steel blade hand saw"
};
var expected = "Hello saw (1): 15-inch steel blade hand saw" + " Available on: ";
//Act
var actual = currentProduct.SayHello();
//Assert
Assert.AreEqual(expected, actual);
}
[TestMethod]
public void Product_Null()
{
//Arrange
Product currentProduct = null;
var companyName = currentProduct?.ProductVendor?.CompanyName;
string expected = null;
//Act
string actual= companyName;
//Assert
Assert.AreEqual(expected, actual);
}
[TestMethod]
public void ConvertMetersToInchesTest()
{
//Arrange
var expected = 78.74;
//Act
var actual = 2 * Product.InchesPerMeter;
//Assert
Assert.AreEqual(expected, actual);
}
[TestMethod]
public void MinimumPriceTest_Default()
{
//Arrange
var currentProduct = new Product();
var expected = .96m;
//Act
var actual = currentProduct.MinimumPrice;
//Assert
Assert.AreEqual(expected, actual);
}
[TestMethod]
public void MinimumPriceTest_Bulk()
{
//Arrange
var currentProduct = new Product(1, "Bulk Tools", "");
var expected = 9.99m;
//Act
var actual = currentProduct.MinimumPrice;
//Assert
Assert.AreEqual(expected, actual);
}
[TestMethod]
public void ProductName_Formate()
{
//Arrange
var currentProduct = new Product();
currentProduct.ProductName = " Steel Hammer ";
var expected = "Steel Hammer";
//Act
var actual = currentProduct.ProductName;
//Assert
Assert.AreEqual(expected, actual);
}
[TestMethod]
public void ProductName_TooShort()
{
//Arrange
var currentProduct = new Product();
currentProduct.ProductName = "aw";
string expected = null;
string expectedMessage = "Product Name must be at least 3 characters";
//Act
var actual = currentProduct.ProductName;
var actualMessage = currentProduct.ValidationMessage;
//Assert
Assert.AreEqual(expected, actual);
Assert.AreEqual(expectedMessage, actualMessage);
}
[TestMethod]
public void ProductName_TooLong()
{
//Arrange
var currentProduct = new Product();
currentProduct.ProductName = "Steel Bladed Hand Saw";
string expected = null;
string expectedMessage = "Product Name cannot be more than 20 characters";
//Act
var actual = currentProduct.ProductName;
var actualMessage = currentProduct.ValidationMessage;
//Assert
Assert.AreEqual(expected, actual);
Assert.AreEqual(expectedMessage, actualMessage);
}
[TestMethod]
public void ProductName_JustRight()
{
//Arrange
var currentProduct = new Product();
currentProduct.ProductName = "Saw";
string expected = "Saw";
string expectedMessage = null;
//Act
var actual = currentProduct.ProductName;
var actualMessage = currentProduct.ValidationMessage;
//Assert
Assert.AreEqual(expected, actual);
Assert.AreEqual(expectedMessage, actualMessage);
}
[TestMethod]
public void Category_DefaultValue()
{
//Arrange
var currentProduct = new Product();
var expected = "Tools";
//Act
var actual = currentProduct.Category;
//Assert
Assert.AreEqual(expected, actual);
}
[TestMethod]
public void Category_NewValue()
{
//Arrange
var currentProduct = new Product();
currentProduct.Category = "Garden";
var expected = "Garden";
//Act
var actual = currentProduct.Category;
//Assert
Assert.AreEqual(expected, actual);
}
[TestMethod]
public void Sequencce_DefaultValue()
{
//Arrange
var currentProduct = new Product();
var expected = 1;
//Act
var actual = currentProduct.SequenceNumber;
//Assert
Assert.AreEqual(expected, actual);
}
[TestMethod]
public void Sequencce_NewValue()
{
//Arrange
var currentProduct = new Product();
currentProduct.SequenceNumber = 5;
var expected = 5;
//Act
var actual = currentProduct.SequenceNumber;
//Assert
Assert.AreEqual(expected, actual);
}
[TestMethod]
public void ProductCode_DefaultValue()
{
//Arrange
var currentProduct = new Product();
var expected = "Tools-1";
//Act
var actual = currentProduct.ProductCode;
//Assert
Assert.AreEqual(expected, actual);
}
}
}
| 26.263538 | 93 | 0.525911 | [
"MIT"
] | Farhan-Info/Csharp-Best-Practices | AcmeApp/Tests/Acme.BizTests/ProductTests.cs | 7,277 | C# |
using System;
using System.Collections.Generic;
namespace Com.GitHub.ZachDeibert.CssComputers.Generator {
class ComputerModel {
public string Name;
public List<Pin> Pins = new List<Pin>();
public List<TruthTable> TruthTables = new List<TruthTable>();
}
}
| 26.181818 | 69 | 0.690972 | [
"MIT"
] | zachdeibert/css-computers | generator/ComputerModel.cs | 288 | C# |
namespace Example.WindowsApp.Views
{
using System.Windows;
public static class ShellProperty
{
public static readonly DependencyProperty TitleProperty = DependencyProperty.RegisterAttached(
"Title",
typeof(string),
typeof(ShellProperty),
new PropertyMetadata(string.Empty, PropertyChanged));
public static string GetTitle(DependencyObject obj)
{
return (string)obj.GetValue(TitleProperty);
}
public static void SetTitle(DependencyObject obj, string value)
{
obj.SetValue(TitleProperty, value);
}
private static void PropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
if (((FrameworkElement)d).Parent is FrameworkElement { DataContext: IShellControl shell })
{
UpdateShellControl(shell, d);
}
}
public static void UpdateShellControl(IShellControl shell, DependencyObject? d)
{
shell.Title.Value = d is null ? string.Empty : GetTitle(d);
}
}
}
| 30.486486 | 102 | 0.620567 | [
"MIT"
] | usausa/Smart-Net-Navigation | Example.WindowsApp/Views/ShellProperty.cs | 1,128 | C# |
using UnityEngine;
using System.Linq;
public class WeaponPartBehaviour : MonoBehaviour
{
[HideInInspector]
public WeaponPartSlot[] slots;
[HideInInspector]
public ModularWeapon weapon;
protected virtual void Awake ()
{
weapon = GetComponentInParent<ModularWeapon>();
slots = gameObject.GetComponentsInChildren<WeaponPartSlot>().Where(s => s.transform.parent = transform).ToArray();
if (transform.parent != null)
{
var slot = transform.parent.GetComponent<WeaponPartSlot>();
if (slot != null)
SetPart(slot.part);
}
}
public virtual void SetPart(WeaponPart part)
{
}
} | 23.793103 | 122 | 0.637681 | [
"Unlicense"
] | Voldakk/Unity-FPS | Assets/Scripts/Weapons/WeaponParts/WeaponPartBehaviour.cs | 692 | C# |
using System.Threading.Tasks;
using commercetools.Common;
using commercetools.Project;
using NUnit.Framework;
namespace commercetools.Tests
{
/// <summary>
/// Test the API methods in the ProjectManager class.
/// </summary>
[TestFixture]
public class ProjectManagerTest
{
private Client _client;
/// <summary>
/// Test setup
/// </summary>
[OneTimeSetUp]
public void Init()
{
_client = Helper.GetClient();
}
/// <summary>
/// Test teardown
/// </summary>
[OneTimeTearDown]
public void Dispose()
{
}
/// <summary>
/// Tests the ProjectManager.GetProjectAsync method.
/// </summary>
/// <see cref="ProjectManager.GetProjectAsync"/>
[Test]
public async Task ShouldGetProjectAsync()
{
Response<Project.Project> response = await _client.Project().GetProjectAsync();
Assert.IsTrue(response.Success);
Project.Project project = response.Result;
Assert.NotNull(project.Key);
Assert.NotNull(project.Name);
Assert.NotNull(project.CreatedAt);
}
}
}
| 23.884615 | 91 | 0.562802 | [
"MIT"
] | DavidDeVries/commercetools-dotnet-sdk | commercetools.NET.Tests/ProjectManagerTest.cs | 1,244 | C# |
// Description: Entity Framework Bulk Operations & Utilities (EF Bulk SaveChanges, Insert, Update, Delete, Merge | LINQ Query Cache, Deferred, Filter, IncludeFilter, IncludeOptimize | Audit)
// Website & Documentation: https://github.com/zzzprojects/Entity-Framework-Plus
// Forum & Issues: https://github.com/zzzprojects/EntityFramework-Plus/issues
// License: https://github.com/zzzprojects/EntityFramework-Plus/blob/master/LICENSE
// More projects: http://www.zzzprojects.com/
// Copyright © ZZZ Projects Inc. 2014 - 2016. All rights reserved.
#if FULL || QUERY_CACHE
using System;
namespace Z.EntityFramework.Plus
{
internal static partial class InternalExtensions
{
/// <summary>An object extension method that return null if the value is DBNull.Value.</summary>
/// <param name="item">The item to act on.</param>
/// <returns>Null if the value is DBNull.Value.</returns>
public static object IfDbNullThenNull(this object item)
{
if (item == DBNull.Value)
{
item = null;
}
return item;
}
}
}
#endif | 37.733333 | 191 | 0.671378 | [
"MIT"
] | Ahmed-Abdelhameed/EntityFramework-Plus | src/shared/Z.EF.Plus._Core.Shared/EF/Object/Object.NullIfDbNull.cs | 1,135 | C# |
using System;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Xml.Linq;
using BurnSystems.Logging;
using DatenMeister.Core;
using DatenMeister.Core.EMOF.Implementation;
using DatenMeister.Core.EMOF.Implementation.DotNet;
using DatenMeister.Core.EMOF.Interface.Reflection;
using DatenMeister.Core.Provider.Xmi;
namespace DatenMeister.BootStrap.PublicSettings
{
/// <summary>
/// This is helper class being used to load and understand the public setting
/// </summary>
public class PublicSettingHandler
{
/// <summary>
/// Defines the XmiFileName
/// </summary>
public static string XmiFileName = "DatenMeister.Settings.xmi";
/// <summary>
/// Defines the class logger
/// </summary>
private static readonly ILogger Logger = new ClassLogger(typeof(PublicSettingHandler));
/// <summary>
/// Loads the public settings for the DatenMeister
/// </summary>
/// <param name="directoryPath">Path to the directory</param>
/// <returns>The found public integrations settings</returns>
public static PublicIntegrationSettings? LoadSettingsFromDirectory(string directoryPath)
{
var path = Path.Combine(directoryPath, XmiFileName);
var result = LoadSettingsFromFile(path);
if (result == null)
{
Logger.Info($"No Configuration file found in {directoryPath}");
}
return result;
}
/// <summary>
/// Loads the settings from
/// </summary>
/// <param name="path"></param>
/// <returns></returns>
/// <exception cref="InvalidOperationException"></exception>
private static PublicIntegrationSettings? LoadSettingsFromFile(string path)
{
PublicIntegrationSettings? settings = null;
if (File.Exists(path))
{
try
{
Logger.Info($"Loading public integration from {path}");
var extent = ConfigurationLoader.LoadSetting(path);
// Goes through all elements
foreach (var element in extent.elements().OfType<IElement>())
{
settings = DotNetConverter.ConvertToDotNetObject<PublicIntegrationSettings>(element);
settings.settingsFilePath = path;
settings.databasePath = settings.databasePath != null
? Environment.ExpandEnvironmentVariables(settings.databasePath)
: null;
foreach (var variable in settings.environmentVariable
.Where(variable => variable.key != null && variable.value != null))
{
Environment.SetEnvironmentVariable(variable.key!, variable.value);
Logger.Info($"Setting Environmental Variable: {variable.key} = {variable.value}");
}
}
}
catch (Exception exc)
{
Logger.Error($"Exception occured during Loading of Xmi: {exc.Message}");
}
}
// Now starts to set the set the environment according the public settings
if (!string.IsNullOrEmpty(settings?.databasePath))
{
Environment.SetEnvironmentVariable("dm_DatabasePath", settings?.databasePath);
}
// Now set the default paths, if they are not set
SetEnvironmentVariableToDesktopFolderIfNotExisting(
"dm_ImportPath", "import");
SetEnvironmentVariableToDesktopFolderIfNotExisting(
"dm_ReportPath", "report");
SetEnvironmentVariableToDesktopFolderIfNotExisting(
"dm_ExportPath", "export");
Environment.SetEnvironmentVariable(
"dm_ApplicationPath",
Path.GetDirectoryName(Assembly.GetEntryAssembly()?.Location));
Logger.Info($"No Xmi-File for external configuration found in: {path}");
return settings;
void SetEnvironmentVariableToDesktopFolderIfNotExisting(string dmImportPath, string folderName)
{
var importPath = Environment.GetEnvironmentVariable(dmImportPath);
if (string.IsNullOrEmpty(importPath))
{
Environment.SetEnvironmentVariable(
dmImportPath,
Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.Desktop),
folderName));
}
}
}
}
} | 40.483607 | 110 | 0.560437 | [
"MIT"
] | mbrenn/datenmeister-new | src/DatenMeister.BootStrap/PublicSettings/PublicSettingHandler.cs | 4,939 | C# |
using Newtonsoft.Json;
using PayNL.Enums;
namespace PayNL.Objects
{
/// <summary>
/// Merchant information
/// </summary>
public class Merchant
{
/// <summary>
/// Merchant ID
/// </summary>
[JsonProperty("id")]
public string ID { get; set; }
/// <summary>
/// Merchant Name
/// </summary>
[JsonProperty("name")]
public string Name { get; set; }
/// <summary>
/// Merchant Public Name
/// </summary>
[JsonProperty("publicName")]
public string PublicName { get; set; }
/// <summary>
/// Active State of the merchant
/// </summary>
[JsonProperty("state")]
public ActiveState State { get; set; }
}
}
| 21.833333 | 46 | 0.501272 | [
"MIT"
] | I-Synergy/Pay.nl | src/PayNL/Objects/Merchant.cs | 788 | C# |
using UnityEngine;
public class TerrainTrees : TerrainGridPopulator
{
// the tree templates game object
public GameObject[] m_treeTemplates;
// the maximum number of trees we can place (based on 100% bio density)
public int m_maxNumTrees;
// populate this planet with trees
public void Initialize( PlanetGenerator planetGenerator, float elevationScale, int randomSeed )
{
// get to this planet
var planet = planetGenerator.GetPlanet();
// calculate the number of trees to place
var numTrees = ( planet.m_bioDensity * m_maxNumTrees ) / 100;
// place them
Initialize( elevationScale, m_treeTemplates, numTrees, randomSeed, false, 0.67f, 1.0f );
}
}
| 26.96 | 96 | 0.746291 | [
"Unlicense"
] | Blakeley00/starflight | Starflight/Assets/Scripts/Spaceflight/Components/TerrainTrees.cs | 676 | C# |
using UnityEngine;
using System.Collections;
using UnityEngine.SceneManagement;
using UnityEngine.EventSystems;
using System.Collections.Generic;
using System;
public class EditorUIController : MonoBehaviour {
public static EditorUIController singleton;
void Awake(){
singleton = this;
}
void Start(){
PlayerSettingsController.singleton.GetPlayerSettings ();
}
public void LoadTesteScene(){
SaveButton ();
SceneManager.LoadScene (1);
}
public void CarouselItemEnter(int id){
GearType type = StoreController.singleton.gearDb.GetGearTypeById (id);
InfoPanelController.singleton.ShowPanel (type.gearName, type.price.ToString(), type.description);
}
public void CarouselItemOut(){
InfoPanelController.singleton.HidePanel ();
}
public void SaveButton(){
GearControllerEditor.singleton.SaveGear ();
PlayerSettingsController.singleton.SetPlayerSettings ();
}
public void LoadButton(){
GearControllerEditor.singleton.LoadGearSet ();
PlayerSettingsController.singleton.ResetPlayerSettings ();
}
public void ItemCarouselClick(int id){
EditorController.singleton.IntantiateDragger (id);
}
public bool InUIClick(){
return EventSystem.current.IsPointerOverGameObject ();
}
public void UpdateCarousel(){
List<CarouselCollection> collections = GetCollections ();
collections = SetItems (collections);
CarouselCollectionController.singleton.SetCollections (collections.ToArray());
CarouselController.singleton.AddClickItemMethod (ItemCarouselClick);
}
List<CarouselCollection> SetItems(List<CarouselCollection> collections){
foreach(CarouselCollection collection in collections){
List<GearType> types = StoreController.singleton.gearDb.GetGearTypeByCollection (collection.collectionName);
foreach(GearType type in types){
collection.items.Add (new CarouselItem(){id = type.id, image = type.icon});
}
}
return collections;
}
List<CarouselCollection> GetCollections(){
List<CarouselCollection> collections = new List<CarouselCollection> ();
foreach (var collectionName in Enum.GetValues(typeof(GearCollection))){
collections.Add (new CarouselCollection (){ collectionName = collectionName.ToString() });
}
return collections;
}
} | 27.75 | 111 | 0.777027 | [
"MIT"
] | ccadori/mecha | Assets/Scripts/Controller/UI/EditorUIController.cs | 2,222 | C# |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.IO;
using System.Runtime.Serialization;
using System.Text;
using System.Text.RegularExpressions;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Linq;
using System.ComponentModel.DataAnnotations;
using OpenAPIDateConverter = Cloud.Governance.Client.Client.OpenAPIDateConverter;
namespace Cloud.Governance.Client.Model
{
/// <summary>
/// PersonalSettings
/// </summary>
[DataContract(Name = "PersonalSettings")]
public partial class PersonalSettings : IEquatable<PersonalSettings>, IValidatableObject
{
/// <summary>
/// Initializes a new instance of the <see cref="PersonalSettings" /> class.
/// </summary>
/// <param name="id">id.</param>
/// <param name="userID">userID (default to 0).</param>
/// <param name="languageID">languageID (default to 0).</param>
/// <param name="timeZoneID">timeZoneID (default to 0).</param>
/// <param name="isAdjustDaylight">isAdjustDaylight (default to false).</param>
/// <param name="properties">properties.</param>
public PersonalSettings(Guid id = default(Guid), int userID = 0, int languageID = 0, int timeZoneID = 0, bool isAdjustDaylight = false, PersonalSettingsPropertyInfo properties = default(PersonalSettingsPropertyInfo))
{
this.Id = id;
this.UserID = userID;
this.LanguageID = languageID;
this.TimeZoneID = timeZoneID;
this.IsAdjustDaylight = isAdjustDaylight;
this.Properties = properties;
}
/// <summary>
/// Gets or Sets Id
/// </summary>
[DataMember(Name = "id", EmitDefaultValue = false)]
public Guid Id { get; set; }
/// <summary>
/// Gets or Sets UserID
/// </summary>
[DataMember(Name = "userID", EmitDefaultValue = false)]
public int UserID { get; set; }
/// <summary>
/// Gets or Sets LanguageID
/// </summary>
[DataMember(Name = "languageID", EmitDefaultValue = false)]
public int LanguageID { get; set; }
/// <summary>
/// Gets or Sets TimeZoneID
/// </summary>
[DataMember(Name = "timeZoneID", EmitDefaultValue = false)]
public int TimeZoneID { get; set; }
/// <summary>
/// Gets or Sets IsAdjustDaylight
/// </summary>
[DataMember(Name = "isAdjustDaylight", EmitDefaultValue = false)]
public bool IsAdjustDaylight { get; set; }
/// <summary>
/// Gets or Sets Properties
/// </summary>
[DataMember(Name = "properties", EmitDefaultValue = true)]
public PersonalSettingsPropertyInfo Properties { get; set; }
/// <summary>
/// Returns the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("class PersonalSettings {\n");
sb.Append(" Id: ").Append(Id).Append("\n");
sb.Append(" UserID: ").Append(UserID).Append("\n");
sb.Append(" LanguageID: ").Append(LanguageID).Append("\n");
sb.Append(" TimeZoneID: ").Append(TimeZoneID).Append("\n");
sb.Append(" IsAdjustDaylight: ").Append(IsAdjustDaylight).Append("\n");
sb.Append(" Properties: ").Append(Properties).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public virtual string ToJson()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="input">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object input)
{
return this.Equals(input as PersonalSettings);
}
/// <summary>
/// Returns true if PersonalSettings instances are equal
/// </summary>
/// <param name="input">Instance of PersonalSettings to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(PersonalSettings input)
{
if (input == null)
return false;
return
(
this.Id == input.Id ||
(this.Id != null &&
this.Id.Equals(input.Id))
) &&
(
this.UserID == input.UserID ||
this.UserID.Equals(input.UserID)
) &&
(
this.LanguageID == input.LanguageID ||
this.LanguageID.Equals(input.LanguageID)
) &&
(
this.TimeZoneID == input.TimeZoneID ||
this.TimeZoneID.Equals(input.TimeZoneID)
) &&
(
this.IsAdjustDaylight == input.IsAdjustDaylight ||
this.IsAdjustDaylight.Equals(input.IsAdjustDaylight)
) &&
(
this.Properties == input.Properties ||
(this.Properties != null &&
this.Properties.Equals(input.Properties))
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
unchecked // Overflow is fine, just wrap
{
int hashCode = 41;
if (this.Id != null)
hashCode = hashCode * 59 + this.Id.GetHashCode();
hashCode = hashCode * 59 + this.UserID.GetHashCode();
hashCode = hashCode * 59 + this.LanguageID.GetHashCode();
hashCode = hashCode * 59 + this.TimeZoneID.GetHashCode();
hashCode = hashCode * 59 + this.IsAdjustDaylight.GetHashCode();
if (this.Properties != null)
hashCode = hashCode * 59 + this.Properties.GetHashCode();
return hashCode;
}
}
/// <summary>
/// To validate all properties of the instance
/// </summary>
/// <param name="validationContext">Validation context</param>
/// <returns>Validation Result</returns>
IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> IValidatableObject.Validate(ValidationContext validationContext)
{
yield break;
}
}
}
| 36.947368 | 224 | 0.550997 | [
"Apache-2.0"
] | AvePoint/cloud-governance-client | csharp-netstandard/src/Cloud.Governance.Client/Model/PersonalSettings.cs | 7,020 | C# |
using MemBus;
using PersistentPlanet.Controls.Controls;
using PersistentPlanet.Primitives.Platform;
namespace PersistentPlanet.Controls
{
public class KeyboardManager
{
private readonly IPublisher _publisher;
private readonly IKeyboardAxisManager _xAxisManager;
private readonly IKeyboardAxisManager _zAxisManager;
public KeyboardManager(IPublisher publisher)
: this(new KeyboardAxisManager<XAxisUpdatedEvent>(publisher, Key.W, Key.S, Key.A, Key.D),
new KeyboardAxisManager<ZAxisUpdatedEvent>(publisher, Key.Up, Key.Down, Key.Left, Key.Right))
{
_publisher = publisher;
}
public KeyboardManager(IKeyboardAxisManager xAxisManager, IKeyboardAxisManager zAxisManager)
{
_xAxisManager = xAxisManager;
_zAxisManager = zAxisManager;
}
public void KeyUp(Key key)
{
_xAxisManager.KeyUp(key);
_zAxisManager.KeyUp(key);
}
public void KeyDown(Key key)
{
if (key == Key.Escape)
{
_publisher.Publish(new EscapePressedEvent());
}
_xAxisManager.KeyDown(key);
_zAxisManager.KeyDown(key);
}
}
}
| 29.159091 | 111 | 0.62198 | [
"MIT"
] | James226/persistent-planet | PersistentPlanet.Controls/KeyboardManager.cs | 1,285 | C# |
// ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------------------------------------------------------------
namespace Microsoft.WindowsAzure.Commands.Storage
{
using Commands.Common.Storage.ResourceModel;
using Microsoft.WindowsAzure.Commands.Common.Storage;
using Microsoft.WindowsAzure.Commands.Storage.Common;
using Microsoft.WindowsAzure.Commands.Storage.Model.Contract;
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Blob;
using System;
using System.Collections.Generic;
using System.Globalization;
/// <summary>
/// Base cmdlet for storage blob/container cmdlet
/// </summary>
public class StorageCloudBlobCmdletBase : StorageCloudCmdletBase<IStorageBlobManagement>
{
/// <summary>
/// Initializes a new instance of the StorageCloudBlobCmdletBase class.
/// </summary>
public StorageCloudBlobCmdletBase()
: this(null)
{
}
/// <summary>
/// Initializes a new instance of the StorageCloudBlobCmdletBase class.
/// </summary>
/// <param name="channel">IStorageBlobManagement channel</param>
public StorageCloudBlobCmdletBase(IStorageBlobManagement channel)
{
Channel = channel;
}
/// <summary>
/// Blob request options
/// </summary>
public BlobRequestOptions RequestOptions
{
get
{
return (BlobRequestOptions)GetRequestOptions(StorageServiceType.Blob);
}
}
protected static CloudBlob GetBlobReferenceFromServerWithContainer(
IStorageBlobManagement localChannel,
CloudBlobContainer container,
string blobName,
AccessCondition accessCondition = null,
BlobRequestOptions requestOptions = null,
OperationContext operationContext = null,
DateTimeOffset? snapshotTime = null)
{
return GetBlobReferenceWrapper(() =>
{
try
{
return localChannel.GetBlobReferenceFromServer(container, blobName, accessCondition, requestOptions, operationContext, snapshotTime);
}
catch (InvalidOperationException)
{
return null;
}
},
blobName,
container.Name);
}
protected static CloudBlob GetBlobSnapshotReferenceFromServerWithContainer(
IStorageBlobManagement localChannel,
CloudBlobContainer container,
string blobName,
DateTime SrcBlobSnapshotTime,
AccessCondition accessCondition = null,
BlobRequestOptions requestOptions = null,
OperationContext operationContext = null)
{
return GetBlobReferenceWrapper(() =>
{
try
{
return localChannel.GetBlobReferenceFromServer(container, blobName, accessCondition, requestOptions, operationContext);
}
catch (InvalidOperationException)
{
return null;
}
},
blobName,
container.Name);
}
protected static CloudBlob GetBlobReferenceWrapper(Func<CloudBlob> getBlobReference, string blobName, string containerName)
{
CloudBlob blob = getBlobReference();
if (null == blob)
{
throw new ResourceNotFoundException(String.Format(Resources.BlobNotFound, blobName, containerName));
}
return blob;
}
/// <summary>
/// Make sure the pipeline blob is valid and already existing
/// </summary>
/// <param name="blob">CloudBlob object</param>
internal void ValidatePipelineCloudBlob(CloudBlob blob)
{
if (null == blob)
{
throw new ArgumentException(String.Format(Resources.ObjectCannotBeNull, typeof(CloudBlob).Name));
}
if (!NameUtil.IsValidBlobName(blob.Name))
{
throw new ArgumentException(String.Format(Resources.InvalidBlobName, blob.Name));
}
ValidatePipelineCloudBlobContainer(blob.Container);
//BlobRequestOptions requestOptions = RequestOptions;
//if (!Channel.DoesBlobExist(blob, requestOptions, OperationContext))
//{
// throw new ResourceNotFoundException(String.Format(Resources.BlobNotFound, blob.Name, blob.Container.Name));
//}
}
/// <summary>
/// Make sure the container is valid and already existing
/// </summary>
/// <param name="container">A CloudBlobContainer object</param>
internal void ValidatePipelineCloudBlobContainer(CloudBlobContainer container)
{
if (null == container)
{
throw new ArgumentException(String.Format(Resources.ObjectCannotBeNull, typeof(CloudBlobContainer).Name));
}
if (!NameUtil.IsValidContainerName(container.Name))
{
throw new ArgumentException(String.Format(Resources.InvalidContainerName, container.Name));
}
//BlobRequestOptions requestOptions = RequestOptions;
//if (container.ServiceClient.Credentials.IsSharedKey
// && !Channel.DoesContainerExist(container, requestOptions, OperationContext))
//{
// throw new ResourceNotFoundException(String.Format(Resources.ContainerNotFound, container.Name));
//}
}
/// <summary>
/// Create blob client and storage service management channel if need to.
/// </summary>
/// <returns>IStorageManagement object</returns>
protected override IStorageBlobManagement CreateChannel()
{
//Init storage blob management channel
if (Channel == null || !ShareChannel)
{
Channel = new StorageBlobManagement(GetCmdletStorageContext());
}
return Channel;
}
/// <summary>
/// Get a service channel object using specified storage account
/// </summary>
/// <param name="account">Cloud storage account object</param>
/// <returns>IStorageBlobManagement channel object</returns>
protected IStorageBlobManagement CreateChannel(AzureStorageContext context)
{
return new StorageBlobManagement(context);
}
/// <summary>
/// whether the specified blob is a snapshot
/// </summary>
/// <param name="blob">CloudBlob object</param>
/// <returns>true if the specified blob is snapshot, otherwise false</returns>
internal bool IsSnapshot(CloudBlob blob)
{
return !string.IsNullOrEmpty(blob.Name) && blob.SnapshotTime != null;
}
/// <summary>
/// Write CloudBlob to output using specified service channel
/// </summary>
/// <param name="blob">The output CloudBlob object</param>
/// <param name="channel">IStorageBlobManagement channel object</param>
internal void WriteCloudBlobObject(long taskId, IStorageBlobManagement channel, CloudBlob blob, BlobContinuationToken continuationToken = null)
{
AzureStorageBlob azureBlob = new AzureStorageBlob(blob);
azureBlob.Context = channel.StorageContext;
azureBlob.ContinuationToken = continuationToken;
OutputStream.WriteObject(taskId, azureBlob);
}
/// <summary>
/// Write CloudBlob to output using specified service channel
/// </summary>
/// <param name="blob">The output CloudBlob object</param>
/// <param name="channel">IStorageBlobManagement channel object</param>
internal void WriteCloudContainerObject(long taskId, IStorageBlobManagement channel,
CloudBlobContainer container, BlobContainerPermissions permissions, BlobContinuationToken continuationToken = null)
{
AzureStorageContainer azureContainer = new AzureStorageContainer(container, permissions);
azureContainer.Context = channel.StorageContext;
azureContainer.ContinuationToken = continuationToken;
OutputStream.WriteObject(taskId, azureContainer);
}
protected void ValidateBlobType(CloudBlob blob)
{
if ((BlobType.BlockBlob != blob.BlobType)
&& (BlobType.PageBlob != blob.BlobType)
&& (BlobType.AppendBlob != blob.BlobType))
{
throw new InvalidOperationException(string.Format(
CultureInfo.CurrentCulture,
Resources.InvalidBlobType,
blob.BlobType,
blob.Name));
}
}
protected void ValidateBlobTier(BlobType type, PremiumPageBlobTier? pageBlobTier)
{
if ((pageBlobTier != null)
&& (type != BlobType.PageBlob))
{
throw new ArgumentOutOfRangeException("BlobType, PageBlobTier", String.Format("PremiumPageBlobTier can only be set to Page Blob. The Current BlobType is: {0}", type));
}
}
protected bool ContainerIsEmpty(CloudBlobContainer container)
{
try
{
BlobContinuationToken blobToken = new BlobContinuationToken();
using (IEnumerator<IListBlobItem> listedBlobs = container
.ListBlobsSegmentedAsync("", true, BlobListingDetails.None, 1, blobToken, RequestOptions,
OperationContext).Result.Results.GetEnumerator())
{
return !(listedBlobs.MoveNext() && listedBlobs.Current != null);
}
}
catch(Exception)
{
return false;
}
}
}
} | 40.675182 | 184 | 0.579363 | [
"MIT"
] | Acidburn0zzz/azure-powershell | src/ResourceManager/Storage/Commands.Storage/Blob/StorageCloudBlobCmdletBase.cs | 10,874 | C# |
using UnityEngine;
/// <summary>
/// Encapsulates the settings which the player can update
/// </summary>
public class SettableSettings
{
/// <summary>
/// Number of pixels needed to move the cursor across the entire screen
/// </summary>
public Vector2 Sensitivity { get; set; }
} | 25.833333 | 76 | 0.654839 | [
"MIT"
] | MatthewCalligaro/TheNoseArcade | faceRacer/FaceRacer/Assets/Scripts/NonMonoBehaviour/SettableSettings.cs | 312 | C# |
using System;
using TrueMyth;
namespace Samples
{
public class User
{
public int Id { get; set; }
public string Name { get; set; }
public string Email { get; set; }
public bool Deactivated { get; set; }
}
public enum UserRepositoryErrorCategory
{
NotFound,
Deactivated
}
public class UserRepositoryError
{
public string Message { get; set; }
public Maybe<Exception> Exception { get; set; }
public Maybe<UserRepositoryErrorCategory> ErrorCategory { get; set; }
}
public class UserRepository
{
private readonly Random _rand = new Random(unchecked((int)DateTime.Now.Ticks));
public Result<User, UserRepositoryError> GetActiveUser(int id)
{
var user = FindUser(id);
if (user == null) {
return new UserRepositoryError {
Message = "User not found.",
ErrorCategory = Maybe.Of(UserRepositoryErrorCategory.NotFound)
};
}
if (user.Deactivated) {
return new UserRepositoryError {
Message = "User was deactivated.",
ErrorCategory = Maybe.Of(UserRepositoryErrorCategory.Deactivated)
};
}
return user;
}
private User FindUser(int id)
{
//mmmmmmmmagic
return _rand.RandBool()
? new User {
Id = _rand.RandBool() ? id : _rand.Next(),
Name = "SampleUser",
Email = "[email protected]",
Deactivated = _rand.RandBool()
}
: null;
}
}
} | 27.65625 | 87 | 0.512429 | [
"MIT"
] | chriskrycho/true-myth-cs-port | test/TrueMyth.Samples/UserRepository.cs | 1,770 | C# |
using UnityEngine;
using System.Collections;
namespace LuxWater.Demo {
public class LuxWater_ExtendedFlycam : MonoBehaviour
{
// slightly changed....
/*
EXTENDED FLYCAM
Desi Quintans (CowfaceGames.com), 17 August 2012.
Based on FlyThrough.js by Slin (http://wiki.unity3d.com/index.php/FlyThrough), 17 May 2011.
LICENSE
Free as in speech, and free as in beer.
FEATURES
WASD/Arrows: Movement
Q: Dropp
E: Climb
Shift: Move faster
Control: Move slower
End: Toggle cursor locking to screen (you can also press Ctrl+P to toggle play mode on and off).
*/
public float cameraSensitivity = 90;
public float climbSpeed = 4;
public float normalMoveSpeed = 10;
public float slowMoveFactor = 0.25f;
public float fastMoveFactor = 3;
private float rotationX = 0.0f;
private float rotationY = 0.0f;
private bool isOrtho = false;
private Camera cam;
void Start () {
rotationX = transform.eulerAngles.y;
cam = GetComponent<Camera>();
if (cam != null) {
isOrtho = cam.orthographic;
}
}
void Update ()
{
// Cache deltaTime!
var deltaTime = Time.deltaTime;
rotationX += Input.GetAxis("Mouse X") * cameraSensitivity * deltaTime;
rotationY += Input.GetAxis("Mouse Y") * cameraSensitivity * deltaTime;
rotationY = Mathf.Clamp (rotationY, -90, 90);
var tempRotation = Quaternion.AngleAxis(rotationX, Vector3.up);
tempRotation *= Quaternion.AngleAxis(rotationY, Vector3.left);
transform.localRotation = Quaternion.Slerp(transform.localRotation, tempRotation, deltaTime * 6.0f);
if (Input.GetKey (KeyCode.LeftShift) || Input.GetKey (KeyCode.RightShift))
{
transform.position += transform.forward * (normalMoveSpeed * fastMoveFactor) * Input.GetAxis("Vertical") * deltaTime;
transform.position += transform.right * (normalMoveSpeed * fastMoveFactor) * Input.GetAxis("Horizontal") * deltaTime;
}
else if (Input.GetKey (KeyCode.LeftControl) || Input.GetKey (KeyCode.RightControl))
{
transform.position += transform.forward * (normalMoveSpeed * slowMoveFactor) * Input.GetAxis("Vertical") * deltaTime;
transform.position += transform.right * (normalMoveSpeed * slowMoveFactor) * Input.GetAxis("Horizontal") * deltaTime;
}
else
{
if(isOrtho) {
cam.orthographicSize *= (1.0f - Input.GetAxis("Vertical") * deltaTime);
}
else {
transform.position += transform.forward * normalMoveSpeed * Input.GetAxis("Vertical") * deltaTime;
}
transform.position += transform.right * normalMoveSpeed * Input.GetAxis("Horizontal") * deltaTime;
}
if (Input.GetKey (KeyCode.Q)) {transform.position -= transform.up * climbSpeed * deltaTime;}
if (Input.GetKey (KeyCode.E)) {transform.position += transform.up * climbSpeed * deltaTime;}
}
}
} | 32.5 | 124 | 0.668034 | [
"Apache-2.0"
] | ctalamonti/Not-Earth | Not Earth/Assets/Imported/LuxWater/Demos/Scripts/LuxWater_ExtendedFlycam.cs | 2,927 | C# |
using System.Collections.Generic;
using System.Drawing;
using Entities;
using System;
namespace DotWayTest
{
class MilkyMan : EntityCircle, IEntity
{
public float Speed { get; set; }
public double Angle { get; set; }
public float DX
{
get
{
return (float)Math.Cos(this.Angle);
}
}
public float DY
{
get
{
return (float)Math.Sin(this.Angle);
}
}
public Brush Brush = Brushes.Red;
public void onManagedDraw(Graphics graphics)
{
if (this.IsDrawWay)
{
this.DrawWay(graphics);
}
graphics.FillEllipse(this.Brush, this.X, this.Y, 2 * this.Radius, 2 * this.Radius);
}
public void onManagedUpdate(float pSecondsElapsed)
{
if (this.dotsIndex < this.dotsStack.Count - 1)
{
int currIndex = this.dotsStack[this.dotsIndex];
int nextIndex = this.dotsStack[this.dotsIndex + 1];
this.CenterX += this.Speed * pSecondsElapsed * this.DX;
this.CenterY += this.Speed * pSecondsElapsed * this.DY;
float x, y;
x = this.map.Dots[nextIndex].X - this.map.Dots[currIndex].X;
y = this.map.Dots[nextIndex].Y - this.map.Dots[currIndex].Y;
double p2p1 = Math.Sqrt(x * x + y * y);
x = this.CenterX - this.map.Dots[currIndex].X;
y = this.CenterY - this.map.Dots[currIndex].Y;
double pp1 = Math.Sqrt(x * x + y * y);
while (pp1 > p2p1 && this.dotsIndex < this.dotsStack.Count - 1)
{
double d = pp1 - p2p1;
this.dotsIndex++;
currIndex = this.dotsStack[this.dotsIndex];
this.CenterX = this.map.Dots[currIndex].X;
this.CenterY = this.map.Dots[currIndex].Y;
if (this.dotsIndex < this.dotsStack.Count - 1)
{
nextIndex = this.dotsStack[this.dotsIndex + 1];
this.Angle = Math.Atan2(this.map.Dots[nextIndex].Y - this.map.Dots[currIndex].Y, this.map.Dots[nextIndex].X - this.map.Dots[currIndex].X);
this.CenterX += (float)d * this.DX;
this.CenterY += (float)d * this.DY;
x = this.map.Dots[nextIndex].X - this.map.Dots[currIndex].X;
y = this.map.Dots[nextIndex].Y - this.map.Dots[currIndex].Y;
p2p1 = Math.Sqrt(x * x + y * y);
x = this.CenterX - this.map.Dots[currIndex].X;
y = this.CenterY - this.map.Dots[currIndex].Y;
pp1 = Math.Sqrt(x * x + y * y);
}
}
}
}
public bool IsDrawWay = false;
private void DrawWay(Graphics graphics)
{
for (int i = 0; i < this.dotsStack.Count - 1; ++i)
{
// TODO: Correct view.
PointF p1 = this.map.Dots[this.dotsStack[i]];
PointF p2 = this.map.Dots[this.dotsStack[i + 1]];
graphics.DrawLine(Pens.Yellow, p1, p2);
}
}
public Map map = null;
public int dotsIndex = 0;
public readonly List<int> dotsStack = new List<int>();
private readonly List<int> dotsChecker = new List<int>();
public void Init()
{
if (this.map.Dots != null)
{
this.dotsIndex = 0;
this.dotsStack.Clear();
this.dotsStack.Add(0);
this.dotsChecker.Clear();
for (int i = this.map.Dots.Length - 1; i >= 0; --i)
{
this.dotsChecker.Add(0);
}
this.dotsChecker[0] = 1;
}
}
public void AddDotNear(Point point)
{
int indexMin = 0;
double distanceMin = float.PositiveInfinity;
for (int i = 0; i < this.map.Dots.Length; ++i)
{
PointF dot = this.map.Dots[i];
float x = point.X - dot.X;
float y = point.Y - dot.Y;
double d = x * x + y * y;
if (distanceMin > d)
{
distanceMin = d;
indexMin = i;
}
}
if (distanceMin < Options.DotsRadius * Options.DotsRadius)
{
this.dotsIndex = indexMin;
this.dotsStack.Add(this.dotsIndex);
this.dotsChecker[this.dotsIndex]++;
}
}
public void FinishDotsStack() // TODO: Write FinishDotsStackAnother(), FinishDotsStackRandom().
{
for (int i = 0; i < this.dotsStack.Count; ++i)
{
this.dotsChecker[this.dotsStack[i]] = 1;
}
for (int i = 0; i < this.map.Dots.Length - 2; ++i)
{
int k = 0;
double md = float.PositiveInfinity;
for (int j = 1; j < this.map.Dots.Length - 1; ++j)
{
if (this.dotsChecker[j] == 0)
{
float x = this.map.Dots[this.dotsStack[this.dotsStack.Count - 1]].X - this.map.Dots[j].X;
float y = this.map.Dots[this.dotsStack[this.dotsStack.Count - 1]].Y - this.map.Dots[j].Y;
double d = Math.Sqrt(x * x + y * y);
if (md > d)
{
md = d;
k = j;
}
}
}
this.dotsStack.Add(k);
this.dotsChecker[k]++;
}
this.dotsStack.Add(this.map.Dots.Length - 1);
}
public void FinishDotsStackRandom()
{
for (int i = 0; i < this.dotsStack.Count; ++i)
{
this.dotsChecker[this.dotsStack[i]] = 1;
}
int[] randArray = new int[this.map.Dots.Length];
for (int i = 0; i < this.map.Dots.Length; ++i)
{
randArray[i] = i;
}
for (int i = 0; i < this.map.Dots.Length; ++i)
{
int j = Options.random.Next(1, this.map.Dots.Length - 1);
int k = Options.random.Next(1, this.map.Dots.Length - 1);
int r = randArray[j];
randArray[j] = randArray[k];
randArray[k] = r;
}
for (int i = 0; i < this.map.Dots.Length; ++i)
{
if (this.dotsChecker[randArray[i]] == 0)
{
this.dotsStack.Add(randArray[i]);
this.dotsChecker[randArray[i]]++;
}
}
if (this.dotsStack[this.dotsStack.Count - 1] != this.map.Dots.Length - 1)
{
this.dotsStack.Add(Options.DotsCount - 1);
}
}
public bool IsFull
{
get
{
bool isFinish = this.dotsStack[this.dotsStack.Count - 1] == this.map.Dots.Length - 1;
for (int i = this.dotsChecker.Count - 1; i >= 0 && isFinish; --i)
{
isFinish = isFinish && this.dotsChecker[i] > 0;
}
return isFinish;
}
}
}
}
| 34.302222 | 162 | 0.43703 | [
"CC0-1.0"
] | Ring-r/sandbox | DotWayTest/DotWayTest/Entities/MilkyMan.cs | 7,720 | C# |
using Handelabra.Sentinels.Engine.Controller;
using Handelabra.Sentinels.Engine.Model;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
namespace Cauldron.Malichae
{
public class HighEzaelCardController : DjinnOngoingController
{
public HighEzaelCardController(Card card, TurnTakerController turnTakerController)
: base(card, turnTakerController, "Ezael", "Ezael")
{
}
public override void AddTriggers()
{
base.AddEndOfTurnTrigger(tt => tt == base.TurnTaker, EndOfTurnReponse, TriggerType.GainHP);
base.AddTriggers();
}
private IEnumerator EndOfTurnReponse(PhaseChangeAction pca)
{
var coroutine = GameController.GainHP(this.DecisionMaker, c => c.IsTarget && IsDjinn(c), 1, cardSource: GetCardSource());
if (base.UseUnityCoroutines)
{
yield return base.GameController.StartCoroutine(coroutine);
}
else
{
base.GameController.ExhaustCoroutine(coroutine);
}
yield break;
}
public override IEnumerator UsePower(int index = 0)
{
int djinnHP = GetPowerNumeral(0, 2);
int otherHP = GetPowerNumeral(1, 1);
var card = GetCardThisCardIsNextTo();
var coroutine = base.GameController.GainHP(DecisionMaker, c => c.IsTarget && (c.IsHero || IsDjinn(c)), c => IsDjinn(c) ? djinnHP : otherHP, cardSource: GetCardSource());
if (base.UseUnityCoroutines)
{
yield return base.GameController.StartCoroutine(coroutine);
}
else
{
base.GameController.ExhaustCoroutine(coroutine);
}
coroutine = DestroySelf();
if (base.UseUnityCoroutines)
{
yield return base.GameController.StartCoroutine(coroutine);
}
else
{
base.GameController.ExhaustCoroutine(coroutine);
}
yield break;
}
}
}
| 33.46875 | 181 | 0.584034 | [
"MIT"
] | LNBertolini/CauldronMods | Controller/Heroes/Malichae/Cards/HighEzaelCardController.cs | 2,144 | 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.
[assembly:System.Reflection.AssemblyVersionAttribute("4.0.10.0")]
[assembly:System.Diagnostics.DebuggableAttribute((System.Diagnostics.DebuggableAttribute.DebuggingModes)(2))]
[assembly:System.Reflection.AssemblyCompanyAttribute("Xamarin, Inc.")]
[assembly:System.Reflection.AssemblyCopyrightAttribute("Copyright (c) 2013 Xamarin Inc. (http://www.xamarin.com)")]
[assembly:System.Reflection.AssemblyDefaultAliasAttribute("System.Net.Primitives.dll")]
[assembly:System.Reflection.AssemblyDescriptionAttribute("System.Net.Primitives.dll")]
[assembly:System.Reflection.AssemblyFileVersionAttribute("4.0.0.0")]
[assembly:System.Reflection.AssemblyInformationalVersionAttribute("4.0.0.0")]
[assembly:System.Reflection.AssemblyProductAttribute("Mono Common Language Infrastructure")]
[assembly:System.Reflection.AssemblyTitleAttribute("System.Net.Primitives.dll")]
[assembly:System.Runtime.CompilerServices.CompilationRelaxationsAttribute(8)]
[assembly:System.Runtime.CompilerServices.ReferenceAssemblyAttribute]
[assembly:System.Runtime.CompilerServices.RuntimeCompatibilityAttribute(WrapNonExceptionThrows=true)]
[assembly:System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Net.AuthenticationSchemes))]
[assembly:System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Net.Cookie))]
[assembly:System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Net.CookieCollection))]
[assembly:System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Net.CookieContainer))]
[assembly:System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Net.CookieException))]
[assembly:System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Net.CredentialCache))]
[assembly:System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Net.DecompressionMethods))]
[assembly:System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Net.DnsEndPoint))]
[assembly:System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Net.EndPoint))]
[assembly:System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Net.HttpStatusCode))]
[assembly:System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Net.ICredentials))]
[assembly:System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Net.ICredentialsByHost))]
[assembly:System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Net.IPAddress))]
[assembly:System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Net.IPEndPoint))]
[assembly:System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Net.IWebProxy))]
[assembly:System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Net.NetworkCredential))]
[assembly:System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Net.NetworkInformation.IPAddressCollection))]
[assembly:System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Net.Security.AuthenticationLevel))]
[assembly:System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Net.Security.SslPolicyErrors))]
[assembly:System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Net.SocketAddress))]
[assembly:System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Net.Sockets.AddressFamily))]
[assembly:System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Net.Sockets.SocketError))]
[assembly:System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Net.Sockets.SocketException))]
[assembly:System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Net.TransportContext))]
[assembly:System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Security.Authentication.CipherAlgorithmType))]
[assembly:System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Security.Authentication.ExchangeAlgorithmType))]
[assembly:System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Security.Authentication.ExtendedProtection.ChannelBinding))]
[assembly:System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Security.Authentication.ExtendedProtection.ChannelBindingKind))]
[assembly:System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Security.Authentication.HashAlgorithmType))]
[assembly:System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Security.Authentication.SslProtocols))]
| 96.666667 | 145 | 0.865948 | [
"MIT"
] | marek-safar/reference-assemblies | src/v4.6.1/Facades/System.Net.Primitives.cs | 4,640 | C# |
//
// Copyright (c) 2004-2020 Jaroslaw Kowalski <[email protected]>, Kim Christensen, Julian Verdurmen
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Reflection;
using JetBrains.Annotations;
using NLog.Common;
using NLog.Filters;
using NLog.Internal;
using NLog.Layouts;
using NLog.Targets;
using NLog.Targets.Wrappers;
using NLog.Time;
namespace NLog.Config
{
/// <summary>
/// Loads NLog configuration from <see cref="ILoggingConfigurationElement"/>
/// </summary>
public abstract class LoggingConfigurationParser : LoggingConfiguration
{
private readonly ServiceRepository _serviceRepository;
/// <summary>
/// Constructor
/// </summary>
/// <param name="logFactory"></param>
protected LoggingConfigurationParser(LogFactory logFactory)
: base(logFactory)
{
_serviceRepository = logFactory.ServiceRepository;
}
/// <summary>
/// Loads NLog configuration from provided config section
/// </summary>
/// <param name="nlogConfig"></param>
/// <param name="basePath"></param>
protected void LoadConfig(ILoggingConfigurationElement nlogConfig, string basePath)
{
InternalLogger.Trace("ParseNLogConfig");
nlogConfig.AssertName("nlog");
SetNLogElementSettings(nlogConfig);
var validatedConfig = ValidatedConfigurationElement.Create(nlogConfig, LogFactory); // Validate after having loaded initial settings
//first load the extensions, as the can be used in other elements (targets etc)
foreach (var extensionsChild in validatedConfig.ValidChildren)
{
if (extensionsChild.MatchesName("extensions"))
{
ParseExtensionsElement(extensionsChild, basePath);
}
}
var rulesList = new List<ValidatedConfigurationElement>();
//parse all other direct elements
foreach (var child in validatedConfig.ValidChildren)
{
if (child.MatchesName("rules"))
{
//postpone parsing <rules> to the end
rulesList.Add(child);
}
else if (child.MatchesName("extensions"))
{
//already parsed
}
else if (!ParseNLogSection(child))
{
InternalLogger.Warn("Skipping unknown 'NLog' child node: {0}", child.Name);
}
}
foreach (var ruleChild in rulesList)
{
ParseRulesElement(ruleChild, LoggingRules);
}
}
private void SetNLogElementSettings(ILoggingConfigurationElement nlogConfig)
{
var sortedList = CreateUniqueSortedListFromConfig(nlogConfig);
bool? parseMessageTemplates = null;
bool internalLoggerEnabled = false;
foreach (var configItem in sortedList)
{
switch (configItem.Key.ToUpperInvariant())
{
case "THROWEXCEPTIONS":
LogFactory.ThrowExceptions = ParseBooleanValue(configItem.Key, configItem.Value, LogFactory.ThrowExceptions);
break;
case "THROWCONFIGEXCEPTIONS":
LogFactory.ThrowConfigExceptions = ParseNullableBooleanValue(configItem.Key, configItem.Value, false);
break;
case "INTERNALLOGLEVEL":
InternalLogger.LogLevel = ParseLogLevelSafe(configItem.Key, configItem.Value, InternalLogger.LogLevel);
internalLoggerEnabled = InternalLogger.LogLevel != LogLevel.Off;
break;
case "USEINVARIANTCULTURE":
if (ParseBooleanValue(configItem.Key, configItem.Value, false))
DefaultCultureInfo = CultureInfo.InvariantCulture;
break;
case "KEEPVARIABLESONRELOAD":
LogFactory.KeepVariablesOnReload = ParseBooleanValue(configItem.Key, configItem.Value, LogFactory.KeepVariablesOnReload);
break;
case "INTERNALLOGTOCONSOLE":
InternalLogger.LogToConsole = ParseBooleanValue(configItem.Key, configItem.Value, InternalLogger.LogToConsole);
break;
case "INTERNALLOGTOCONSOLEERROR":
InternalLogger.LogToConsoleError = ParseBooleanValue(configItem.Key, configItem.Value, InternalLogger.LogToConsoleError);
break;
case "INTERNALLOGFILE":
var internalLogFile = configItem.Value?.Trim();
if (!string.IsNullOrEmpty(internalLogFile))
{
internalLogFile = ExpandFilePathVariables(internalLogFile);
InternalLogger.LogFile = internalLogFile;
}
break;
case "INTERNALLOGTOTRACE":
InternalLogger.LogToTrace = ParseBooleanValue(configItem.Key, configItem.Value, InternalLogger.LogToTrace);
break;
case "INTERNALLOGINCLUDETIMESTAMP":
InternalLogger.IncludeTimestamp = ParseBooleanValue(configItem.Key, configItem.Value, InternalLogger.IncludeTimestamp);
break;
case "GLOBALTHRESHOLD":
LogFactory.GlobalThreshold = ParseLogLevelSafe(configItem.Key, configItem.Value, LogFactory.GlobalThreshold);
break; // expanding variables not possible here, they are created later
case "PARSEMESSAGETEMPLATES":
parseMessageTemplates = ParseNullableBooleanValue(configItem.Key, configItem.Value, true);
break;
case "AUTOSHUTDOWN":
LogFactory.AutoShutdown = ParseBooleanValue(configItem.Key, configItem.Value, true);
break;
case "AUTORELOAD":
break; // Ignore here, used by other logic
default:
InternalLogger.Debug("Skipping unknown 'NLog' property {0}={1}", configItem.Key, configItem.Value);
break;
}
}
if (!internalLoggerEnabled && !InternalLogger.HasActiveLoggers())
{
InternalLogger.LogLevel = LogLevel.Off; // Reduce overhead of the InternalLogger when not configured
}
_serviceRepository.ConfigurationItemFactory.ParseMessageTemplates = parseMessageTemplates;
}
/// <summary>
/// Builds list with unique keys, using last value of duplicates. High priority keys placed first.
/// </summary>
/// <param name="nlogConfig"></param>
/// <returns></returns>
private static IList<KeyValuePair<string, string>> CreateUniqueSortedListFromConfig(ILoggingConfigurationElement nlogConfig)
{
var dict = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
foreach (var configItem in nlogConfig.Values)
{
if (!string.IsNullOrEmpty(configItem.Key))
{
string key = configItem.Key.Trim();
if (!dict.ContainsKey(key))
{
dict[key] = configItem.Value;
}
else
{
InternalLogger.Debug("Skipping duplicate value for 'NLog'. PropertyName={0}. Skips Value={1}. Existing Value={2}", configItem.Key, configItem.Value, dict[key]);
}
}
}
var sortedList = new List<KeyValuePair<string, string>>(dict.Count);
var highPriorityList = new[]
{
"ThrowExceptions",
"ThrowConfigExceptions",
"InternalLogLevel",
"InternalLogFile",
"InternalLogToConsole",
};
foreach (var highPrioritySetting in highPriorityList)
{
if (dict.TryGetValue(highPrioritySetting, out var settingValue))
{
sortedList.Add(new KeyValuePair<string, string>(highPrioritySetting, settingValue));
dict.Remove(highPrioritySetting);
}
}
foreach (var configItem in dict)
{
sortedList.Add(configItem);
}
return sortedList;
}
private string ExpandFilePathVariables(string internalLogFile)
{
try
{
if (ContainsSubStringIgnoreCase(internalLogFile, "${currentdir}", out string currentDirToken))
internalLogFile = internalLogFile.Replace(currentDirToken, System.IO.Directory.GetCurrentDirectory() + System.IO.Path.DirectorySeparatorChar.ToString());
if (ContainsSubStringIgnoreCase(internalLogFile, "${basedir}", out string baseDirToken))
internalLogFile = internalLogFile.Replace(baseDirToken, LogFactory.CurrentAppEnvironment.AppDomainBaseDirectory + System.IO.Path.DirectorySeparatorChar.ToString());
if (ContainsSubStringIgnoreCase(internalLogFile, "${tempdir}", out string tempDirToken))
internalLogFile = internalLogFile.Replace(tempDirToken, LogFactory.CurrentAppEnvironment.UserTempFilePath + System.IO.Path.DirectorySeparatorChar.ToString());
#if !NETSTANDARD1_3
if (ContainsSubStringIgnoreCase(internalLogFile, "${processdir}", out string processDirToken))
internalLogFile = internalLogFile.Replace(processDirToken, System.IO.Path.GetDirectoryName(LogFactory.CurrentAppEnvironment.CurrentProcessFilePath) + System.IO.Path.DirectorySeparatorChar.ToString());
#endif
if (internalLogFile.IndexOf("%", StringComparison.OrdinalIgnoreCase) >= 0)
internalLogFile = Environment.ExpandEnvironmentVariables(internalLogFile);
return internalLogFile;
}
catch
{
return internalLogFile;
}
}
private static bool ContainsSubStringIgnoreCase(string haystack, string needle, out string result)
{
int needlePos = haystack.IndexOf(needle, StringComparison.OrdinalIgnoreCase);
result = needlePos >= 0 ? haystack.Substring(needlePos, needle.Length) : null;
return result != null;
}
/// <summary>
/// Parse loglevel, but don't throw if exception throwing is disabled
/// </summary>
/// <param name="attributeName">Name of attribute for logging.</param>
/// <param name="attributeValue">Value of parse.</param>
/// <param name="default">Used if there is an exception</param>
/// <returns></returns>
private LogLevel ParseLogLevelSafe(string attributeName, string attributeValue, LogLevel @default)
{
try
{
var internalLogLevel = LogLevel.FromString(attributeValue?.Trim());
return internalLogLevel;
}
catch (Exception exception)
{
if (exception.MustBeRethrownImmediately())
throw;
const string message = "attribute '{0}': '{1}' isn't valid LogLevel. {2} will be used.";
var configException =
new NLogConfigurationException(exception, message, attributeName, attributeValue, @default);
if (MustThrowConfigException(configException))
throw configException;
return @default;
}
}
/// <summary>
/// Parses a single config section within the NLog-config
/// </summary>
/// <param name="configSection"></param>
/// <returns>Section was recognized</returns>
protected virtual bool ParseNLogSection(ILoggingConfigurationElement configSection)
{
switch (configSection.Name?.Trim().ToUpperInvariant())
{
case "TIME":
ParseTimeElement(ValidatedConfigurationElement.Create(configSection, LogFactory));
return true;
case "VARIABLE":
ParseVariableElement(ValidatedConfigurationElement.Create(configSection, LogFactory));
return true;
case "VARIABLES":
ParseVariablesElement(ValidatedConfigurationElement.Create(configSection, LogFactory));
return true;
case "APPENDERS":
case "TARGETS":
ParseTargetsElement(ValidatedConfigurationElement.Create(configSection, LogFactory));
return true;
}
return false;
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability",
"CA2001:AvoidCallingProblematicMethods", MessageId = "System.Reflection.Assembly.LoadFrom",
Justification = "Need to load external assembly.")]
private void ParseExtensionsElement(ValidatedConfigurationElement extensionsElement, string baseDirectory)
{
extensionsElement.AssertName("extensions");
foreach (var childItem in extensionsElement.ValidChildren)
{
string prefix = null;
string type = null;
string assemblyFile = null;
string assemblyName = null;
foreach (var childProperty in childItem.Values)
{
if (MatchesName(childProperty.Key, "prefix"))
{
prefix = childProperty.Value + ".";
}
else if (MatchesName(childProperty.Key, "type"))
{
type = childProperty.Value;
}
else if (MatchesName(childProperty.Key, "assemblyFile"))
{
assemblyFile = childProperty.Value;
}
else if (MatchesName(childProperty.Key, "assembly"))
{
assemblyName = childProperty.Value;
}
else
{
InternalLogger.Debug("Skipping unknown property {0} for element {1} in section {2}",
childProperty.Key, childItem.Name, extensionsElement.Name);
}
}
if (!StringHelpers.IsNullOrWhiteSpace(type))
{
RegisterExtension(type, prefix);
}
#if !NETSTANDARD1_3
if (!StringHelpers.IsNullOrWhiteSpace(assemblyFile))
{
ParseExtensionWithAssemblyFile(baseDirectory, assemblyFile, prefix);
continue;
}
#endif
if (!StringHelpers.IsNullOrWhiteSpace(assemblyName))
{
ParseExtensionWithAssembly(assemblyName, prefix);
}
}
}
private void RegisterExtension(string type, string itemNamePrefix)
{
try
{
_serviceRepository.ConfigurationItemFactory.RegisterType(Type.GetType(type, true), itemNamePrefix);
}
catch (Exception exception)
{
if (exception.MustBeRethrownImmediately())
throw;
var configException =
new NLogConfigurationException("Error loading extensions: " + type, exception);
if (MustThrowConfigException(configException))
throw configException;
}
}
#if !NETSTANDARD1_3
private void ParseExtensionWithAssemblyFile(string baseDirectory, string assemblyFile, string prefix)
{
try
{
Assembly asm = AssemblyHelpers.LoadFromPath(assemblyFile, baseDirectory);
_serviceRepository.ConfigurationItemFactory.RegisterItemsFromAssembly(asm, prefix);
}
catch (Exception exception)
{
if (exception.MustBeRethrownImmediately())
throw;
var configException =
new NLogConfigurationException("Error loading extensions: " + assemblyFile, exception);
if (MustThrowConfigException(configException))
throw configException;
}
}
#endif
private void ParseExtensionWithAssembly(string assemblyName, string prefix)
{
try
{
Assembly asm = AssemblyHelpers.LoadFromName(assemblyName);
_serviceRepository.ConfigurationItemFactory.RegisterItemsFromAssembly(asm, prefix);
}
catch (Exception exception)
{
if (exception.MustBeRethrownImmediately())
throw;
var configException =
new NLogConfigurationException("Error loading extensions: " + assemblyName, exception);
if (MustThrowConfigException(configException))
throw configException;
}
}
private void ParseVariableElement(ValidatedConfigurationElement variableElement)
{
string variableName = null;
string variableValue = null;
foreach (var childProperty in variableElement.Values)
{
if (MatchesName(childProperty.Key, "name"))
variableName = childProperty.Value;
else if (MatchesName(childProperty.Key, "value") || MatchesName(childProperty.Key, "layout"))
variableValue = childProperty.Value;
else
InternalLogger.Debug("Skipping unknown property {0} for element {1} in section {2}",
childProperty.Key, variableElement.Name, "variables");
}
if (!AssertNonEmptyValue(variableName, "name", variableElement.Name, "variables"))
return;
Layout variableLayout = variableValue != null ? (Layout)ExpandSimpleVariables(variableValue) : null;
if (variableLayout == null)
{
var child = variableElement.ValidChildren.FirstOrDefault();
if (child != null)
{
variableLayout = TryCreateLayoutInstance(child, typeof(Layout));
if (variableLayout != null)
{
ConfigureFromAttributesAndElements(child, variableLayout);
}
}
}
if (!AssertNotNullValue(variableLayout, "value or text", variableElement.Name, "variables"))
return;
Variables[variableName] = variableLayout;
}
private void ParseVariablesElement(ValidatedConfigurationElement variableElement)
{
variableElement.AssertName("variables");
foreach (var childItem in variableElement.ValidChildren)
{
ParseVariableElement(childItem);
}
}
private void ParseTimeElement(ValidatedConfigurationElement timeElement)
{
timeElement.AssertName("time");
string timeSourceType = null;
foreach (var childProperty in timeElement.Values)
{
if (MatchesName(childProperty.Key, "type"))
timeSourceType = childProperty.Value;
else
InternalLogger.Debug("Skipping unknown property {0} for element {1} in section {2}",
childProperty.Key, timeElement.Name, timeElement.Name);
}
if (!AssertNonEmptyValue(timeSourceType, "type", timeElement.Name, string.Empty))
return;
TimeSource newTimeSource = _serviceRepository.ConfigurationItemFactory.TimeSources.CreateInstance(timeSourceType);
ConfigureObjectFromAttributes(newTimeSource, timeElement, true);
InternalLogger.Info("Selecting time source {0}", newTimeSource);
TimeSource.Current = newTimeSource;
}
[ContractAnnotation("value:notnull => true")]
private static bool AssertNotNullValue(object value, string propertyName, string elementName, string sectionName)
{
if (value != null)
return true;
return AssertNonEmptyValue(string.Empty, propertyName, elementName, sectionName);
}
[ContractAnnotation("value:null => false")]
private static bool AssertNonEmptyValue(string value, string propertyName, string elementName, string sectionName)
{
if (!StringHelpers.IsNullOrWhiteSpace(value))
return true;
if (LogManager.ThrowConfigExceptions ?? LogManager.ThrowExceptions)
throw new NLogConfigurationException(
$"Expected property {propertyName} on element name: {elementName} in section: {sectionName}");
InternalLogger.Warn("Skipping element name: {0} in section: {1} because property {2} is blank", elementName,
sectionName, propertyName);
return false;
}
/// <summary>
/// Parse {Rules} xml element
/// </summary>
/// <param name="rulesElement"></param>
/// <param name="rulesCollection">Rules are added to this parameter.</param>
private void ParseRulesElement(ValidatedConfigurationElement rulesElement, IList<LoggingRule> rulesCollection)
{
InternalLogger.Trace("ParseRulesElement");
rulesElement.AssertName("rules");
foreach (var childItem in rulesElement.ValidChildren)
{
LoggingRule loggingRule = ParseRuleElement(childItem);
if (loggingRule != null)
{
lock (rulesCollection)
{
rulesCollection.Add(loggingRule);
}
}
}
}
private LogLevel LogLevelFromString(string text)
{
return LogLevel.FromString(ExpandSimpleVariables(text).Trim());
}
/// <summary>
/// Parse {Logger} xml element
/// </summary>
/// <param name="loggerElement"></param>
private LoggingRule ParseRuleElement(ValidatedConfigurationElement loggerElement)
{
string minLevel = null;
string maxLevel = null;
string enableLevels = null;
string ruleName = null;
string namePattern = null;
bool enabled = true;
bool final = false;
string writeTargets = null;
foreach (var childProperty in loggerElement.Values)
{
switch (childProperty.Key?.Trim().ToUpperInvariant())
{
case "NAME":
if (loggerElement.MatchesName("logger"))
namePattern = childProperty.Value; // Legacy Style
else
ruleName = childProperty.Value;
break;
case "RULENAME":
ruleName = childProperty.Value; // Legacy Style
break;
case "LOGGER":
namePattern = childProperty.Value;
break;
case "ENABLED":
enabled = ParseBooleanValue(childProperty.Key, childProperty.Value, true);
break;
case "APPENDTO":
writeTargets = childProperty.Value;
break;
case "WRITETO":
writeTargets = childProperty.Value;
break;
case "FINAL":
final = ParseBooleanValue(childProperty.Key, childProperty.Value, false);
break;
case "LEVEL":
case "LEVELS":
enableLevels = childProperty.Value;
break;
case "MINLEVEL":
minLevel = childProperty.Value;
break;
case "MAXLEVEL":
maxLevel = childProperty.Value;
break;
default:
InternalLogger.Debug("Skipping unknown property {0} for element {1} in section {2}",
childProperty.Key, loggerElement.Name, "rules");
break;
}
}
if (string.IsNullOrEmpty(ruleName) && string.IsNullOrEmpty(namePattern) &&
string.IsNullOrEmpty(writeTargets) && !final)
{
InternalLogger.Debug("Logging rule without name or filter or targets is ignored");
return null;
}
namePattern = namePattern ?? "*";
if (!enabled)
{
InternalLogger.Debug("Logging rule {0} with filter `{1}` is disabled", ruleName, namePattern);
return null;
}
var rule = new LoggingRule(ruleName)
{
LoggerNamePattern = namePattern,
Final = final,
};
EnableLevelsForRule(rule, enableLevels, minLevel, maxLevel);
ParseLoggingRuleTargets(writeTargets, rule);
ParseLoggingRuleChildren(loggerElement, rule);
return rule;
}
private void EnableLevelsForRule(LoggingRule rule, string enableLevels, string minLevel, string maxLevel)
{
if (enableLevels != null)
{
enableLevels = ExpandSimpleVariables(enableLevels);
if (enableLevels.IndexOf('{') >= 0)
{
SimpleLayout simpleLayout = ParseLevelLayout(enableLevels);
rule.EnableLoggingForLevels(simpleLayout);
}
else
{
foreach (var logLevel in enableLevels.SplitAndTrimTokens(','))
{
rule.EnableLoggingForLevel(LogLevelFromString(logLevel));
}
}
}
else
{
minLevel = minLevel != null ? ExpandSimpleVariables(minLevel) : minLevel;
maxLevel = maxLevel != null ? ExpandSimpleVariables(maxLevel) : maxLevel;
if (minLevel?.IndexOf('{') >= 0 || maxLevel?.IndexOf('{') >= 0)
{
SimpleLayout minLevelLayout = ParseLevelLayout(minLevel);
SimpleLayout maxLevelLayout = ParseLevelLayout(maxLevel);
rule.EnableLoggingForRange(minLevelLayout, maxLevelLayout);
}
else
{
LogLevel minLogLevel = minLevel != null ? LogLevelFromString(minLevel) : LogLevel.MinLevel;
LogLevel maxLogLevel = maxLevel != null ? LogLevelFromString(maxLevel) : LogLevel.MaxLevel;
rule.SetLoggingLevels(minLogLevel, maxLogLevel);
}
}
}
private SimpleLayout ParseLevelLayout(string levelLayout)
{
SimpleLayout simpleLayout = !StringHelpers.IsNullOrWhiteSpace(levelLayout) ? new SimpleLayout(levelLayout, _serviceRepository.ConfigurationItemFactory) : null;
simpleLayout?.Initialize(this);
return simpleLayout;
}
private void ParseLoggingRuleTargets(string writeTargets, LoggingRule rule)
{
if (string.IsNullOrEmpty(writeTargets))
return;
foreach (string targetName in writeTargets.SplitAndTrimTokens(','))
{
Target target = FindTargetByName(targetName);
if (target != null)
{
rule.Targets.Add(target);
}
else
{
var configException =
new NLogConfigurationException($"Target '{targetName}' not found for logging rule: {(string.IsNullOrEmpty(rule.RuleName) ? rule.LoggerNamePattern : rule.RuleName)}.");
if (MustThrowConfigException(configException))
throw configException;
}
}
}
private void ParseLoggingRuleChildren(ValidatedConfigurationElement loggerElement, LoggingRule rule)
{
foreach (var child in loggerElement.ValidChildren)
{
LoggingRule childRule = null;
if (child.MatchesName("filters"))
{
ParseFilters(rule, child);
}
else if (child.MatchesName("logger") && loggerElement.MatchesName("logger"))
{
childRule = ParseRuleElement(child);
}
else if (child.MatchesName("rule") && loggerElement.MatchesName("rule"))
{
childRule = ParseRuleElement(child);
}
else
{
InternalLogger.Debug("Skipping unknown child {0} for element {1} in section {2}", child.Name,
loggerElement.Name, "rules");
}
if (childRule != null)
{
lock (rule.ChildRules)
{
rule.ChildRules.Add(childRule);
}
}
}
}
private void ParseFilters(LoggingRule rule, ValidatedConfigurationElement filtersElement)
{
filtersElement.AssertName("filters");
var defaultActionResult = filtersElement.GetOptionalValue("defaultAction", null);
if (defaultActionResult != null)
{
PropertyHelper.SetPropertyFromString(rule, nameof(rule.DefaultFilterResult), defaultActionResult,
_serviceRepository.ConfigurationItemFactory);
}
foreach (var filterElement in filtersElement.ValidChildren)
{
string name = filterElement.Name;
Filter filter = _serviceRepository.ConfigurationItemFactory.Filters.CreateInstance(name);
ConfigureObjectFromAttributes(filter, filterElement, false);
rule.Filters.Add(filter);
}
}
private void ParseTargetsElement(ValidatedConfigurationElement targetsElement)
{
targetsElement.AssertName("targets", "appenders");
bool asyncWrap = ParseBooleanValue("async", targetsElement.GetOptionalValue("async", "false"), false);
ValidatedConfigurationElement defaultWrapperElement = null;
var typeNameToDefaultTargetParameters =
new Dictionary<string, ValidatedConfigurationElement>(StringComparer.OrdinalIgnoreCase);
foreach (var targetElement in targetsElement.ValidChildren)
{
string targetTypeName = targetElement.GetConfigItemTypeAttribute();
string targetValueName = targetElement.GetOptionalValue("name", null);
Target newTarget = null;
if (!string.IsNullOrEmpty(targetValueName))
targetValueName = $"{targetElement.Name}(Name={targetValueName})";
else
targetValueName = targetElement.Name;
switch (targetElement.Name?.Trim().ToUpperInvariant())
{
case "DEFAULT-WRAPPER":
if (AssertNonEmptyValue(targetTypeName, "type", targetValueName, targetsElement.Name))
{
defaultWrapperElement = targetElement;
}
break;
case "DEFAULT-TARGET-PARAMETERS":
if (AssertNonEmptyValue(targetTypeName, "type", targetValueName, targetsElement.Name))
{
typeNameToDefaultTargetParameters[targetTypeName.Trim()] = targetElement;
}
break;
case "TARGET":
case "APPENDER":
case "WRAPPER":
case "WRAPPER-TARGET":
case "COMPOUND-TARGET":
if (AssertNonEmptyValue(targetTypeName, "type", targetValueName, targetsElement.Name))
{
newTarget = CreateTargetType(targetTypeName);
if (newTarget != null)
{
ParseTargetElement(newTarget, targetElement, typeNameToDefaultTargetParameters);
}
}
break;
default:
InternalLogger.Debug("Skipping unknown element {0} in section {1}", targetValueName,
targetsElement.Name);
break;
}
if (newTarget != null)
{
if (asyncWrap)
{
newTarget = WrapWithAsyncTargetWrapper(newTarget);
}
if (defaultWrapperElement != null)
{
newTarget = WrapWithDefaultWrapper(newTarget, defaultWrapperElement);
}
InternalLogger.Info("Adding target {0}(Name={1})", newTarget.GetType().Name, newTarget.Name);
AddTarget(newTarget.Name, newTarget);
}
}
}
private Target CreateTargetType(string targetTypeName)
{
Target newTarget = null;
try
{
newTarget = _serviceRepository.ConfigurationItemFactory.Targets.CreateInstance(targetTypeName);
if (newTarget == null)
throw new NLogConfigurationException($"Factory returned null for target type: {targetTypeName}");
}
catch (Exception ex)
{
if (ex.MustBeRethrownImmediately())
throw;
var configException = new NLogConfigurationException($"Failed to create target type: {targetTypeName}", ex);
if (MustThrowConfigException(configException))
throw configException;
}
return newTarget;
}
private void ParseTargetElement(Target target, ValidatedConfigurationElement targetElement,
Dictionary<string, ValidatedConfigurationElement> typeNameToDefaultTargetParameters = null)
{
string targetTypeName = targetElement.GetConfigItemTypeAttribute("targets");
if (typeNameToDefaultTargetParameters != null &&
typeNameToDefaultTargetParameters.TryGetValue(targetTypeName, out var defaults))
{
ParseTargetElement(target, defaults, null);
}
var compound = target as CompoundTargetBase;
var wrapper = target as WrapperTargetBase;
ConfigureObjectFromAttributes(target, targetElement, true);
foreach (var childElement in targetElement.ValidChildren)
{
if (compound != null &&
ParseCompoundTarget(compound, childElement, typeNameToDefaultTargetParameters, null))
{
continue;
}
if (wrapper != null &&
ParseTargetWrapper(wrapper, childElement, typeNameToDefaultTargetParameters))
{
continue;
}
SetPropertyFromElement(target, childElement, targetElement);
}
}
private bool ParseTargetWrapper(
WrapperTargetBase wrapper,
ValidatedConfigurationElement childElement,
Dictionary<string, ValidatedConfigurationElement> typeNameToDefaultTargetParameters)
{
if (IsTargetRefElement(childElement.Name))
{
var targetName = childElement.GetRequiredValue("name", GetName(wrapper));
Target newTarget = FindTargetByName(targetName);
if (newTarget == null)
{
var configException = new NLogConfigurationException($"Referenced target '{targetName}' not found.");
if (MustThrowConfigException(configException))
throw configException;
}
wrapper.WrappedTarget = newTarget;
return true;
}
if (IsTargetElement(childElement.Name))
{
string targetTypeName = childElement.GetConfigItemTypeAttribute(GetName(wrapper));
Target newTarget = CreateTargetType(targetTypeName);
if (newTarget != null)
{
ParseTargetElement(newTarget, childElement, typeNameToDefaultTargetParameters);
if (newTarget.Name != null)
{
// if the new target has name, register it
AddTarget(newTarget.Name, newTarget);
}
if (wrapper.WrappedTarget != null)
{
var configException = new NLogConfigurationException($"Failed to assign wrapped target {targetTypeName}, because target {wrapper.Name} already has one.");
if (MustThrowConfigException(configException))
throw configException;
}
}
wrapper.WrappedTarget = newTarget;
return true;
}
return false;
}
private bool ParseCompoundTarget(
CompoundTargetBase compound,
ValidatedConfigurationElement childElement,
Dictionary<string, ValidatedConfigurationElement> typeNameToDefaultTargetParameters,
string targetName)
{
if (MatchesName(childElement.Name, "targets") || MatchesName(childElement.Name, "appenders"))
{
foreach (var child in childElement.ValidChildren)
{
ParseCompoundTarget(compound, child, typeNameToDefaultTargetParameters, null);
}
return true;
}
if (IsTargetRefElement(childElement.Name))
{
targetName = childElement.GetRequiredValue("name", GetName(compound));
Target newTarget = FindTargetByName(targetName);
if (newTarget == null)
{
throw new NLogConfigurationException("Referenced target '" + targetName + "' not found.");
}
compound.Targets.Add(newTarget);
return true;
}
if (IsTargetElement(childElement.Name))
{
string targetTypeName = childElement.GetConfigItemTypeAttribute(GetName(compound));
Target newTarget = CreateTargetType(targetTypeName);
if (newTarget != null)
{
if (targetName != null)
newTarget.Name = targetName;
ParseTargetElement(newTarget, childElement, typeNameToDefaultTargetParameters);
if (newTarget.Name != null)
{
// if the new target has name, register it
AddTarget(newTarget.Name, newTarget);
}
compound.Targets.Add(newTarget);
}
return true;
}
return false;
}
private void ConfigureObjectFromAttributes(object targetObject, ValidatedConfigurationElement element, bool ignoreType)
{
foreach (var kvp in element.ValueLookup)
{
string childName = kvp.Key;
string childValue = kvp.Value;
if (ignoreType && MatchesName(childName, "type"))
{
continue;
}
try
{
PropertyHelper.SetPropertyFromString(targetObject, childName, ExpandSimpleVariables(childValue),
_serviceRepository.ConfigurationItemFactory);
}
catch (Exception ex)
{
InternalLogger.Warn(ex, "Error when setting '{0}' on attibute '{1}'", childValue, childName);
throw;
}
}
}
private void SetPropertyFromElement(object o, ValidatedConfigurationElement childElement, ILoggingConfigurationElement parentElement)
{
if (!PropertyHelper.TryGetPropertyInfo(o, childElement.Name, out var propInfo))
{
InternalLogger.Debug("Skipping unknown element {0} in section {1}. Not matching any property on {2} - {3}", childElement.Name, parentElement.Name, o, o?.GetType());
return;
}
if (AddArrayItemFromElement(o, propInfo, childElement))
{
return;
}
if (SetLayoutFromElement(o, propInfo, childElement))
{
return;
}
if (SetFilterFromElement(o, propInfo, childElement))
{
return;
}
SetItemFromElement(o, propInfo, childElement);
}
private bool AddArrayItemFromElement(object o, PropertyInfo propInfo, ValidatedConfigurationElement element)
{
Type elementType = PropertyHelper.GetArrayItemType(propInfo);
if (elementType != null)
{
IList propertyValue = (IList)propInfo.GetValue(o, null);
if (string.Equals(propInfo.Name, element.Name, StringComparison.OrdinalIgnoreCase))
{
bool foundChild = false;
foreach (var child in element.ValidChildren)
{
foundChild = true;
propertyValue.Add(ParseArrayItemFromElement(elementType, child));
}
if (foundChild)
return true;
}
object arrayItem = ParseArrayItemFromElement(elementType, element);
propertyValue.Add(arrayItem);
return true;
}
return false;
}
private object ParseArrayItemFromElement(Type elementType, ValidatedConfigurationElement element)
{
object arrayItem = TryCreateLayoutInstance(element, elementType);
// arrayItem is not a layout
if (arrayItem == null)
arrayItem = _serviceRepository.GetService(elementType);
ConfigureObjectFromAttributes(arrayItem, element, true);
ConfigureObjectFromElement(arrayItem, element);
return arrayItem;
}
private bool SetLayoutFromElement(object o, PropertyInfo propInfo, ValidatedConfigurationElement element)
{
var layout = TryCreateLayoutInstance(element, propInfo.PropertyType);
// and is a Layout and 'type' attribute has been specified
if (layout != null)
{
SetItemOnProperty(o, propInfo, element, layout);
return true;
}
return false;
}
private bool SetFilterFromElement(object o, PropertyInfo propInfo, ValidatedConfigurationElement element)
{
var type = propInfo.PropertyType;
Filter filter = TryCreateFilterInstance(element, type);
// and is a Filter and 'type' attribute has been specified
if (filter != null)
{
SetItemOnProperty(o, propInfo, element, filter);
return true;
}
return false;
}
private Layout TryCreateLayoutInstance(ValidatedConfigurationElement element, Type type)
{
return TryCreateInstance(element, type, _serviceRepository.ConfigurationItemFactory.Layouts);
}
private Filter TryCreateFilterInstance(ValidatedConfigurationElement element, Type type)
{
return TryCreateInstance(element, type, _serviceRepository.ConfigurationItemFactory.Filters);
}
private T TryCreateInstance<T>(ValidatedConfigurationElement element, Type type, INamedItemFactory<T, Type> factory)
where T : class
{
// Check if correct type
if (!IsAssignableFrom<T>(type))
return null;
// Check if the 'type' attribute has been specified
string layoutTypeName = element.GetConfigItemTypeAttribute();
if (layoutTypeName == null)
return null;
return factory.CreateInstance(ExpandSimpleVariables(layoutTypeName));
}
private static bool IsAssignableFrom<T>(Type type)
{
return typeof(T).IsAssignableFrom(type);
}
private void SetItemOnProperty(object o, PropertyInfo propInfo, ValidatedConfigurationElement element, object properyValue)
{
ConfigureFromAttributesAndElements(element, properyValue);
propInfo.SetValue(o, properyValue, null);
}
private void SetItemFromElement(object o, PropertyInfo propInfo, ValidatedConfigurationElement element)
{
object item = propInfo.GetValue(o, null);
ConfigureFromAttributesAndElements(element, item);
}
private void ConfigureFromAttributesAndElements(ValidatedConfigurationElement element, object item)
{
ConfigureObjectFromAttributes(item, element, true);
ConfigureObjectFromElement(item, element);
}
private void ConfigureObjectFromElement(object targetObject, ValidatedConfigurationElement element)
{
foreach (var child in element.ValidChildren)
{
SetPropertyFromElement(targetObject, child, element);
}
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability",
"CA2000:Dispose objects before losing scope", Justification = "Target is disposed elsewhere.")]
private static Target WrapWithAsyncTargetWrapper(Target target)
{
#if !NET3_5
if (target is AsyncTaskTarget)
{
InternalLogger.Debug("Skip wrapping target '{0}' with AsyncTargetWrapper", target.Name);
return target;
}
#endif
var asyncTargetWrapper = new AsyncTargetWrapper();
asyncTargetWrapper.WrappedTarget = target;
asyncTargetWrapper.Name = target.Name;
target.Name = target.Name + "_wrapped";
InternalLogger.Debug("Wrapping target '{0}' with AsyncTargetWrapper and renaming to '{1}",
asyncTargetWrapper.Name, target.Name);
target = asyncTargetWrapper;
return target;
}
private Target WrapWithDefaultWrapper(Target target, ValidatedConfigurationElement defaultWrapperElement)
{
string wrapperTypeName = defaultWrapperElement.GetConfigItemTypeAttribute("targets");
Target wrapperTargetInstance = CreateTargetType(wrapperTypeName);
WrapperTargetBase wtb = wrapperTargetInstance as WrapperTargetBase;
if (wtb == null)
{
throw new NLogConfigurationException("Target type specified on <default-wrapper /> is not a wrapper.");
}
ParseTargetElement(wrapperTargetInstance, defaultWrapperElement);
while (wtb.WrappedTarget != null)
{
wtb = wtb.WrappedTarget as WrapperTargetBase;
if (wtb == null)
{
throw new NLogConfigurationException(
"Child target type specified on <default-wrapper /> is not a wrapper.");
}
}
#if !NET3_5
if (target is AsyncTaskTarget && wrapperTargetInstance is AsyncTargetWrapper && ReferenceEquals(wrapperTargetInstance, wtb))
{
InternalLogger.Debug("Skip wrapping target '{0}' with AsyncTargetWrapper", target.Name);
return target;
}
#endif
wtb.WrappedTarget = target;
wrapperTargetInstance.Name = target.Name;
target.Name = target.Name + "_wrapped";
InternalLogger.Debug("Wrapping target '{0}' with '{1}' and renaming to '{2}", wrapperTargetInstance.Name,
wrapperTargetInstance.GetType().Name, target.Name);
return wrapperTargetInstance;
}
/// <summary>
/// Parse boolean
/// </summary>
/// <param name="propertyName">Name of the property for logging.</param>
/// <param name="value">value to parse</param>
/// <param name="defaultValue">Default value to return if the parse failed</param>
/// <returns>Boolean attribute value or default.</returns>
private bool ParseBooleanValue(string propertyName, string value, bool defaultValue)
{
try
{
return Convert.ToBoolean(value?.Trim(), CultureInfo.InvariantCulture);
}
catch (Exception exception)
{
if (exception.MustBeRethrownImmediately())
throw;
var configException = new NLogConfigurationException(exception, $"'{propertyName}' hasn't a valid boolean value '{value}'. {defaultValue} will be used");
if (MustThrowConfigException(configException))
throw configException;
return defaultValue;
}
}
private bool? ParseNullableBooleanValue(string propertyName, string value, bool defaultValue)
{
return StringHelpers.IsNullOrWhiteSpace(value)
? (bool?)null
: ParseBooleanValue(propertyName, value, defaultValue);
}
private bool MustThrowConfigException(NLogConfigurationException configException)
{
if (configException.MustBeRethrown())
return true; // Global LogManager says throw
if (LogFactory.ThrowConfigExceptions ?? LogFactory.ThrowExceptions)
return true; // Local LogFactory says throw
return false;
}
private static bool MatchesName(string key, string expectedKey)
{
return string.Equals(key?.Trim(), expectedKey, StringComparison.OrdinalIgnoreCase);
}
private static bool IsTargetElement(string name)
{
return name.Equals("target", StringComparison.OrdinalIgnoreCase)
|| name.Equals("wrapper", StringComparison.OrdinalIgnoreCase)
|| name.Equals("wrapper-target", StringComparison.OrdinalIgnoreCase)
|| name.Equals("compound-target", StringComparison.OrdinalIgnoreCase);
}
private static bool IsTargetRefElement(string name)
{
return name.Equals("target-ref", StringComparison.OrdinalIgnoreCase)
|| name.Equals("wrapper-target-ref", StringComparison.OrdinalIgnoreCase)
|| name.Equals("compound-target-ref", StringComparison.OrdinalIgnoreCase);
}
private static string GetName(Target target)
{
return string.IsNullOrEmpty(target.Name) ? target.GetType().Name : target.Name;
}
/// <summary>
/// Config element that's validated and having extra context
/// </summary>
private class ValidatedConfigurationElement : ILoggingConfigurationElement
{
private static readonly IDictionary<string, string> EmptyDefaultDictionary = new SortHelpers.ReadOnlySingleBucketDictionary<string, string>();
private readonly ILoggingConfigurationElement _element;
private readonly bool _throwConfigExceptions;
private IList<ValidatedConfigurationElement> _validChildren;
public static ValidatedConfigurationElement Create(ILoggingConfigurationElement element, LogFactory logFactory)
{
if (element is ValidatedConfigurationElement validConfig)
return validConfig;
else
return new ValidatedConfigurationElement(element, logFactory.ThrowConfigExceptions ?? logFactory.ThrowExceptions);
}
public ValidatedConfigurationElement(ILoggingConfigurationElement element, bool throwConfigExceptions)
{
_throwConfigExceptions = throwConfigExceptions;
Name = element.Name.Trim();
ValueLookup = CreateValueLookup(element, throwConfigExceptions);
_element = element;
}
public string Name { get; }
public IDictionary<string, string> ValueLookup { get; }
public IEnumerable<ValidatedConfigurationElement> ValidChildren
{
get
{
if (_validChildren != null)
return _validChildren;
else
return YieldAndCacheValidChildren();
}
}
IEnumerable<ValidatedConfigurationElement> YieldAndCacheValidChildren()
{
foreach (var child in _element.Children)
{
_validChildren = _validChildren ?? new List<ValidatedConfigurationElement>();
var validChild = new ValidatedConfigurationElement(child, _throwConfigExceptions);
_validChildren.Add(validChild);
yield return validChild;
}
_validChildren = _validChildren ?? ArrayHelper.Empty<ValidatedConfigurationElement>();
}
public IEnumerable<KeyValuePair<string, string>> Values => ValueLookup;
/// <remarks>
/// Explicit cast because net3_5 doesn't support covariance.
/// </remarks>
IEnumerable<ILoggingConfigurationElement> ILoggingConfigurationElement.Children => ValidChildren.Cast<ILoggingConfigurationElement>();
public string GetRequiredValue(string attributeName, string section)
{
string value = GetOptionalValue(attributeName, null);
if (value == null)
{
throw new NLogConfigurationException($"Expected {attributeName} on {Name} in {section}");
}
if (StringHelpers.IsNullOrWhiteSpace(value))
{
throw new NLogConfigurationException(
$"Expected non-empty {attributeName} on {Name} in {section}");
}
return value;
}
public string GetOptionalValue(string attributeName, string defaultValue)
{
ValueLookup.TryGetValue(attributeName, out string value);
return value ?? defaultValue;
}
private static IDictionary<string, string> CreateValueLookup(ILoggingConfigurationElement element, bool throwConfigExceptions)
{
IDictionary<string, string> valueLookup = null;
List<string> warnings = null;
foreach (var attribute in element.Values)
{
var attributeKey = attribute.Key?.Trim() ?? string.Empty;
valueLookup = valueLookup ?? new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
if (!string.IsNullOrEmpty(attributeKey) && !valueLookup.ContainsKey(attributeKey))
{
valueLookup[attributeKey] = attribute.Value;
}
else
{
string validationError = string.IsNullOrEmpty(attributeKey) ? $"Invalid property for '{element.Name}' without name. Value={attribute.Value}"
: $"Duplicate value for '{element.Name}'. PropertyName={attributeKey}. Skips Value={attribute.Value}. Existing Value={valueLookup[attributeKey]}";
InternalLogger.Debug("Skipping {0}", validationError);
if (throwConfigExceptions)
{
warnings = warnings ?? new List<string>();
warnings.Add(validationError);
}
}
}
if (throwConfigExceptions && warnings?.Count > 0)
{
throw new NLogConfigurationException(StringHelpers.Join(Environment.NewLine, warnings));
}
return valueLookup ?? EmptyDefaultDictionary;
}
}
}
} | 41.979065 | 220 | 0.561739 | [
"BSD-3-Clause"
] | ErickJeffries/NLog | src/NLog/Config/LoggingConfigurationParser.cs | 60,156 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace BudgetAnalyser.Properties {
using System;
/// <summary>
/// A strongly-typed resource class, for looking up localized strings, etc.
/// </summary>
// This class was auto-generated by the StronglyTypedResourceBuilder
// class via a tool like ResGen or Visual Studio.
// To add or remove a member, edit your .ResX file then rerun ResGen
// with the /str option, or rebuild your VS project.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class Resources {
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Resources() {
}
/// <summary>
/// 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("BudgetAnalyser.Properties.Resources", typeof(Resources).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// Overrides the current thread's CurrentUICulture property for all
/// resource lookups using this strongly typed resource class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture {
get {
return resourceCulture;
}
set {
resourceCulture = value;
}
}
}
}
| 44.59375 | 181 | 0.600561 | [
"MIT"
] | Benrnz/BudgetAnalyser | BudgetAnalyser/Properties/Resources.Designer.cs | 2,856 | C# |
using System.IO;
namespace SeqCli.Util
{
static class Content
{
public static string GetPath(string relativePath)
{
var thisDir = Path.GetDirectoryName(Path.GetFullPath(typeof(Content).Assembly.Location)) ?? ".";
return Path.Combine(thisDir, relativePath);
}
}
} | 24.923077 | 108 | 0.626543 | [
"Apache-2.0"
] | KodrAus/seqcli | src/SeqCli/Util/Content.cs | 326 | C# |
namespace _06.Birthday_Celebrations.Models
{
using Interfaces;
public abstract class LivingBeing : IBirthable
{
public LivingBeing(string birthDate, string name)
{
this.BirthDate = birthDate;
this.Name = name;
}
public string BirthDate { get; private set; }
public string Name { get; private set; }
}
}
| 21.5 | 57 | 0.602067 | [
"MIT"
] | RAstardzhiev/SoftUni-C- | C# OOP Advanced/Interfaces and Abstraction - Exercises/06. Birthday Celebrations/Models/LivingBeing.cs | 389 | C# |
using EdsLibrary.Extensions;
using System;
using Console = Colorful.Console;
using System.Drawing;
using Ann;
using Ann.Examples.Demonstration;
namespace Ann.Examples.Inertion
{
public class DemoInertion : Demo<DynamicEntity>
{
public DemoInertion(int steps, AnnParameters parameters)
: base(DynamicEntity.NumberOfInputs, DynamicEntity.NumberOfOutputs, steps, parameters)
{
this.consoleMenu.AddItem(ConsoleKey.G, "goal", MenuSetGoal);
}
private void MenuSetGoal()
{
Console.Write("Enter Goal value: ");
string input = Console.ReadLine();
if (string.IsNullOrEmpty(input))
{
float goal = AnnParameters.random.Next(-10000.0f, 10000.0f);
SetGoal(goal);
Console.WriteLine("Goal set.", Color.LightGreen);
}
else if (int.TryParse(input, out int goal))
{
SetGoal(goal);
Console.WriteLine("Goal set.", Color.LightGreen);
}
else
{
Console.WriteLine("Unable to parse integer.", Color.Red);
}
}
private void SetGoal(float goal)
{
foreach (var entity in dynamicEntities)
{
entity.positionGoal = goal;
}
}
}
}
| 29.916667 | 99 | 0.531337 | [
"MIT"
] | ERGeorgiev/ann | Ann.Examples/Inertion/DemoInertion.cs | 1,438 | C# |
/*
* This filePath is part of AceQL C# Client SDK.
* AceQL C# Client SDK: Remote SQL access over HTTP with AceQL HTTP.
* Copyright (C) 2020, KawanSoft SAS
* (http://www.kawansoft.com). All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this filePath 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 AceQL.Client.Api.Http;
using System;
using System.Threading.Tasks;
namespace AceQL.Client.Api
{
/// <summary>
/// Class <see cref="AceQLTransaction"/>. Allows to define a Transaction in order to execute remote commit or rollback.
/// </summary>
public class AceQLTransaction : IDisposable
{
/// <summary>
/// The AceQL connection
/// </summary>
private readonly AceQLConnection connection;
/// <summary>
/// The instance that does all http stuff
/// </summary>
private readonly AceQLHttpApi aceQLHttpApi;
/// <summary>
/// The isolation level
/// </summary>
private readonly IsolationLevel isolationLevel = IsolationLevel.Unspecified;
/// <summary>
/// Initializes a new instance of the <see cref="AceQLTransaction"/> class.
/// </summary>
/// <param name="connection">The AceQL connection.</param>
internal AceQLTransaction(AceQLConnection connection)
{
this.aceQLHttpApi = connection.aceQLHttpApi;
this.connection = connection;
}
/// <summary>
/// Initializes a new instance of the <see cref="AceQLTransaction"/> class.
/// </summary>
/// <param name="connection">The AceQL connection.</param>
/// <param name="isolationLevel">The isolation level.</param>
internal AceQLTransaction(AceQLConnection connection, IsolationLevel isolationLevel) : this(connection)
{
this.isolationLevel = isolationLevel;
}
/// <summary>
/// Gets the transaction isolation as string.
/// </summary>
/// <param name="transactionIsolationLevel">The transaction isolation level.</param>
/// <returns>The transaction isolation as string.</returns>
internal static String GetTransactionIsolationAsString(IsolationLevel transactionIsolationLevel)
{
if (transactionIsolationLevel == IsolationLevel.Unspecified)
{
return "NONE";
}
else if (transactionIsolationLevel == IsolationLevel.ReadCommitted)
{
return "READ_COMMITTED";
}
else if (transactionIsolationLevel == IsolationLevel.ReadUncommitted)
{
return "READ_UNCOMMITTED";
}
else if (transactionIsolationLevel == IsolationLevel.RepeatableRead)
{
return "REPEATABLE_READ";
}
else if (transactionIsolationLevel == IsolationLevel.Serializable)
{
return "SERIALIZABLE";
}
else {
return "UNKNOWN";
}
}
/// <summary>
/// Specifies the isolation level for this transaction.
/// </summary>
/// <value>The isolation level.</value>
public IsolationLevel IsolationLevel
{
get
{
return isolationLevel;
}
}
/// <summary>
/// Gets the connection to remote database.
/// </summary>
/// <value>the connection to remote database.</value>
public AceQLConnection AceQLConnection
{
get
{
return connection;
}
}
/// <summary>
/// Commits the remote database transaction.
/// <para/>Note that this call will put the remote connection in auto commit mode on after Commit.
/// </summary>
/// <exception cref="AceQL.Client.Api.AceQLException">If any Exception occurs.</exception>
public async Task CommitAsync()
{
await aceQLHttpApi.CallApiNoResultAsync("set_auto_commit", "true").ConfigureAwait(false);
}
/// <summary>
/// Rolls back a transaction from a pending state.
/// <para/>Note that this call will put the remote connection in auto commit mode on after Rollback.
/// </summary>
/// <exception cref="AceQL.Client.Api.AceQLException">If any Exception occurs.</exception>
public async Task RollbackAsync()
{
await aceQLHttpApi.CallApiNoResultAsync("rollback", null).ConfigureAwait(false);
await aceQLHttpApi.CallApiNoResultAsync("set_auto_commit", "true").ConfigureAwait(false);
}
/// <summary>
/// Optional call, does nothing.
/// The opened <see cref="AceQLTransaction"/> must be closed by an <see cref="AceQLTransaction.CommitAsync"/>
/// or an <see cref="AceQLTransaction.RollbackAsync"/>
///
/// <para/>Method is provided for consistency as a DbTransaction (as a SQL Server SqlTransaction) is <see cref="IDisposable"/>.
/// </summary>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// Releases unmanaged and - optionally - managed resources.
/// </summary>
/// <param name="v"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
protected virtual void Dispose(bool v)
{
}
}
}
| 36.611765 | 146 | 0.585154 | [
"Apache-2.0"
] | GuillaumeR77/AceQL.Client2 | AceQLClient/src/Api/AceQLTransaction.cs | 6,226 | C# |
/*
* MIT License
*
* Copyright (c) 2018 Clark Yang
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
* of the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
using System;
using System.Reflection;
using Loxodon.Log;
#if !UNITY_IOS && !ENABLE_IL2CPP && !NET_STANDARD_2_0
using System.Reflection.Emit;
#endif
#if !UNITY_IOS && !ENABLE_IL2CPP
using System.Linq.Expressions;
#endif
namespace BindKit.Binding.Reflection
{
#pragma warning disable 0414
public class ProxyFieldInfo : IProxyFieldInfo
{
private static readonly ILog log = LogManager.GetLogger(typeof(ProxyFieldInfo));
private readonly bool isValueType;
protected FieldInfo fieldInfo;
public ProxyFieldInfo(FieldInfo fieldInfo)
{
if (fieldInfo == null)
throw new ArgumentNullException("fieldInfo");
this.fieldInfo = fieldInfo;
#if NETFX_CORE
this.isValueType = this.fieldInfo.DeclaringType.GetTypeInfo().IsValueType;
#else
this.isValueType = this.fieldInfo.DeclaringType.IsValueType;
#endif
}
public virtual bool IsValueType { get { return isValueType; } }
public virtual Type ValueType { get { return fieldInfo.FieldType; } }
public virtual Type DeclaringType { get { return this.fieldInfo.DeclaringType; } }
public virtual string Name { get { return this.fieldInfo.Name; } }
public virtual bool IsStatic { get { return this.fieldInfo.IsStatic(); } }
public virtual object GetValue(object target)
{
return this.fieldInfo.GetValue(target);
}
public virtual void SetValue(object target, object value)
{
if (fieldInfo.IsInitOnly)
throw new MemberAccessException("The value is read-only.");
if (IsValueType)
throw new NotSupportedException("Assignments of Value type are not supported.");
this.fieldInfo.SetValue(target, value);
}
}
#pragma warning disable 0414
public class ProxyFieldInfo<T, TValue> : ProxyFieldInfo, IProxyFieldInfo<T, TValue>
{
private static readonly ILog log = LogManager.GetLogger(typeof(ProxyFieldInfo<T, TValue>));
private Func<T, TValue> getter;
private Action<T, TValue> setter;
public ProxyFieldInfo(string fieldName) : this(typeof(T).GetField(fieldName))
{
}
public ProxyFieldInfo(FieldInfo fieldInfo) : base(fieldInfo)
{
if (!typeof(TValue).Equals(this.fieldInfo.FieldType) || !this.DeclaringType.IsAssignableFrom(typeof(T)))
throw new ArgumentException("The field types do not match!");
this.getter = this.MakeGetter(fieldInfo);
this.setter = this.MakeSetter(fieldInfo);
}
public ProxyFieldInfo(string fieldName, Func<T, TValue> getter, Action<T, TValue> setter) : this(typeof(T).GetField(fieldName), getter, setter)
{
}
public ProxyFieldInfo(FieldInfo fieldInfo, Func<T, TValue> getter, Action<T, TValue> setter) : base(fieldInfo)
{
if (!typeof(TValue).Equals(this.fieldInfo.FieldType) || !this.DeclaringType.IsAssignableFrom(typeof(T)))
throw new ArgumentException("The field types do not match!");
this.getter = getter;
this.setter = setter;
}
private Action<T, TValue> MakeSetter(FieldInfo fieldInfo)
{
if (this.IsValueType)
return null;
if (fieldInfo.IsInitOnly)
return null;
#if !UNITY_IOS && !ENABLE_IL2CPP
#if NETFX_CORE || NET_STANDARD_2_0
try
{
var targetExp = Expression.Parameter(typeof(T), "target");
var paramExp = Expression.Parameter(typeof(TValue), "value");
var fieldExp = Expression.Field(fieldInfo.IsStatic ? null : targetExp, fieldInfo);
var assignExp = Expression.Assign(fieldExp, paramExp);
var lambda = Expression.Lambda<Action<T, TValue>>(assignExp, targetExp, paramExp);
return lambda.Compile();
}
catch (Exception e)
{
if (log.IsWarnEnabled)
log.WarnFormat("{0}", e);
}
#else
try
{
DynamicMethod m = new DynamicMethod("Setter", typeof(void), new Type[] { typeof(T), typeof(TValue) }, typeof(T));
ILGenerator cg = m.GetILGenerator();
if (fieldInfo.IsStatic)
{
cg.Emit(OpCodes.Ldarg_1);
cg.Emit(OpCodes.Stsfld, fieldInfo);
cg.Emit(OpCodes.Ret);
}
else
{
cg.Emit(OpCodes.Ldarg_0);
cg.Emit(OpCodes.Ldarg_1);
cg.Emit(OpCodes.Stfld, fieldInfo);
cg.Emit(OpCodes.Ret);
}
return (Action<T, TValue>)m.CreateDelegate(typeof(Action<T, TValue>));
}
catch (Exception e)
{
if (log.IsWarnEnabled)
log.WarnFormat("{0}", e);
}
#endif
#endif
return null;
}
private Func<T, TValue> MakeGetter(FieldInfo fieldInfo)
{
#if !UNITY_IOS && !ENABLE_IL2CPP
try
{
var targetExp = Expression.Parameter(typeof(T), "target");
var fieldExp = Expression.Field(fieldInfo.IsStatic ? null : targetExp, fieldInfo);
var lambda = Expression.Lambda<Func<T, TValue>>(fieldExp, targetExp);
return lambda.Compile();
}
catch (Exception e)
{
if (log.IsWarnEnabled)
log.WarnFormat("{0}", e);
}
#endif
return null;
}
public override Type DeclaringType { get { return typeof(T); } }
public TValue GetValue(T target)
{
if (this.getter != null)
return this.getter(target);
return (TValue)this.fieldInfo.GetValue(target);
}
public override object GetValue(object target)
{
if (this.getter != null)
return this.getter((T)target);
return this.fieldInfo.GetValue(target);
}
TValue IProxyFieldInfo<TValue>.GetValue(object target)
{
return this.GetValue((T)target);
}
public void SetValue(T target, TValue value)
{
if (fieldInfo.IsInitOnly)
throw new MemberAccessException("The value is read-only.");
if (IsValueType)
throw new NotSupportedException("Assignments of Value type are not supported.");
if (this.setter != null)
{
this.setter(target, value);
return;
}
this.fieldInfo.SetValue(target, value);
}
public override void SetValue(object target, object value)
{
if (fieldInfo.IsInitOnly)
throw new MemberAccessException("The value is read-only.");
if (IsValueType)
throw new NotSupportedException("Assignments of Value type are not supported.");
if (this.setter != null)
{
this.setter((T)target, (TValue)value);
return;
}
this.fieldInfo.SetValue(target, value);
}
public void SetValue(object target, TValue value)
{
this.SetValue((T)target, value);
}
}
}
| 33.713178 | 151 | 0.587032 | [
"MIT"
] | 84KaliPleXon3/QFramework | Assets/QFramework/Framework/0.PackageKit/BindKit/Framework/Binding/Reflection/ProxyFieldInfo.cs | 8,700 | C# |
namespace Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210
{
using Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.PowerShell;
/// <summary>Provider specific switch protection input.</summary>
[System.ComponentModel.TypeConverter(typeof(SwitchProtectionProviderSpecificInputTypeConverter))]
public partial class SwitchProtectionProviderSpecificInput
{
/// <summary>
/// <c>AfterDeserializeDictionary</c> will be called after the deserialization has finished, allowing customization of the
/// object before it is returned. Implement this method in a partial class to enable this behavior
/// </summary>
/// <param name="content">The global::System.Collections.IDictionary content that should be used.</param>
partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content);
/// <summary>
/// <c>AfterDeserializePSObject</c> will be called after the deserialization has finished, allowing customization of the object
/// before it is returned. Implement this method in a partial class to enable this behavior
/// </summary>
/// <param name="content">The global::System.Management.Automation.PSObject content that should be used.</param>
partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content);
/// <summary>
/// <c>BeforeDeserializeDictionary</c> will be called before the deserialization has commenced, allowing complete customization
/// of the object before it is deserialized.
/// If you wish to disable the default deserialization entirely, return <c>true</c> in the <see "returnNow" /> output parameter.
/// Implement this method in a partial class to enable this behavior.
/// </summary>
/// <param name="content">The global::System.Collections.IDictionary content that should be used.</param>
/// <param name="returnNow">Determines if the rest of the serialization should be processed, or if the method should return
/// instantly.</param>
partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow);
/// <summary>
/// <c>BeforeDeserializePSObject</c> will be called before the deserialization has commenced, allowing complete customization
/// of the object before it is deserialized.
/// If you wish to disable the default deserialization entirely, return <c>true</c> in the <see "returnNow" /> output parameter.
/// Implement this method in a partial class to enable this behavior.
/// </summary>
/// <param name="content">The global::System.Management.Automation.PSObject content that should be used.</param>
/// <param name="returnNow">Determines if the rest of the serialization should be processed, or if the method should return
/// instantly.</param>
partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow);
/// <summary>
/// Deserializes a <see cref="global::System.Collections.IDictionary" /> into an instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.SwitchProtectionProviderSpecificInput"
/// />.
/// </summary>
/// <param name="content">The global::System.Collections.IDictionary content that should be used.</param>
/// <returns>
/// an instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.ISwitchProtectionProviderSpecificInput"
/// />.
/// </returns>
public static Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.ISwitchProtectionProviderSpecificInput DeserializeFromDictionary(global::System.Collections.IDictionary content)
{
return new SwitchProtectionProviderSpecificInput(content);
}
/// <summary>
/// Deserializes a <see cref="global::System.Management.Automation.PSObject" /> into an instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.SwitchProtectionProviderSpecificInput"
/// />.
/// </summary>
/// <param name="content">The global::System.Management.Automation.PSObject content that should be used.</param>
/// <returns>
/// an instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.ISwitchProtectionProviderSpecificInput"
/// />.
/// </returns>
public static Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.ISwitchProtectionProviderSpecificInput DeserializeFromPSObject(global::System.Management.Automation.PSObject content)
{
return new SwitchProtectionProviderSpecificInput(content);
}
/// <summary>
/// Creates a new instance of <see cref="SwitchProtectionProviderSpecificInput" />, deserializing the content from a json
/// string.
/// </summary>
/// <param name="jsonText">a string containing a JSON serialized instance of this model.</param>
/// <returns>an instance of the <see cref="className" /> model class.</returns>
public static Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.ISwitchProtectionProviderSpecificInput FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonNode.Parse(jsonText));
/// <summary>
/// Deserializes a <see cref="global::System.Collections.IDictionary" /> into a new instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.SwitchProtectionProviderSpecificInput"
/// />.
/// </summary>
/// <param name="content">The global::System.Collections.IDictionary content that should be used.</param>
internal SwitchProtectionProviderSpecificInput(global::System.Collections.IDictionary content)
{
bool returnNow = false;
BeforeDeserializeDictionary(content, ref returnNow);
if (returnNow)
{
return;
}
// actually deserialize
((Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.ISwitchProtectionProviderSpecificInputInternal)this).InstanceType = (string) content.GetValueForProperty("InstanceType",((Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.ISwitchProtectionProviderSpecificInputInternal)this).InstanceType, global::System.Convert.ToString);
AfterDeserializeDictionary(content);
}
/// <summary>
/// Deserializes a <see cref="global::System.Management.Automation.PSObject" /> into a new instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.SwitchProtectionProviderSpecificInput"
/// />.
/// </summary>
/// <param name="content">The global::System.Management.Automation.PSObject content that should be used.</param>
internal SwitchProtectionProviderSpecificInput(global::System.Management.Automation.PSObject content)
{
bool returnNow = false;
BeforeDeserializePSObject(content, ref returnNow);
if (returnNow)
{
return;
}
// actually deserialize
((Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.ISwitchProtectionProviderSpecificInputInternal)this).InstanceType = (string) content.GetValueForProperty("InstanceType",((Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.ISwitchProtectionProviderSpecificInputInternal)this).InstanceType, global::System.Convert.ToString);
AfterDeserializePSObject(content);
}
/// <summary>Serializes this instance to a json string.</summary>
/// <returns>a <see cref="System.String" /> containing this model serialized to JSON text.</returns>
public string ToJsonString() => ToJson(null, Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.SerializationMode.IncludeAll)?.ToString();
}
/// Provider specific switch protection input.
[System.ComponentModel.TypeConverter(typeof(SwitchProtectionProviderSpecificInputTypeConverter))]
public partial interface ISwitchProtectionProviderSpecificInput
{
}
} | 63.529851 | 361 | 0.696699 | [
"MIT"
] | AverageDesigner/azure-powershell | src/Migrate/generated/api/Models/Api20210210/SwitchProtectionProviderSpecificInput.PowerShell.cs | 8,380 | C# |
// Copyright 2017 the original author or authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Steeltoe.Management.Endpoint.Middleware;
using Steeltoe.Management.EndpointCore.ContentNegotiation;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace Steeltoe.Management.Endpoint.ThreadDump
{
public class ThreadDumpEndpointMiddleware : EndpointMiddleware<List<ThreadInfo>>
{
private readonly RequestDelegate _next;
public ThreadDumpEndpointMiddleware(RequestDelegate next, ThreadDumpEndpoint endpoint, IEnumerable<IManagementOptions> mgmtOptions, ILogger<ThreadDumpEndpointMiddleware> logger = null)
: base(endpoint, mgmtOptions, logger: logger)
{
_next = next;
}
public async Task Invoke(HttpContext context)
{
if (RequestVerbAndPathMatch(context.Request.Method, context.Request.Path.Value))
{
await HandleThreadDumpRequestAsync(context).ConfigureAwait(false);
}
else
{
await _next(context).ConfigureAwait(false);
}
}
protected internal async Task HandleThreadDumpRequestAsync(HttpContext context)
{
var serialInfo = HandleRequest();
_logger?.LogDebug("Returning: {0}", serialInfo);
context.HandleContentNegotiation(_logger);
await context.Response.WriteAsync(serialInfo).ConfigureAwait(false);
}
}
}
| 37.142857 | 192 | 0.700962 | [
"Apache-2.0"
] | FrancisChung/steeltoe | src/Management/src/EndpointCore/ThreadDump/ThreadDumpEndpointMiddleware.cs | 2,082 | C# |
using System;
using Microsoft.EntityFrameworkCore.Migrations;
namespace Angular.Server.Data.Migrations
{
public partial class AuditableFields : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<DateTime>(
name: "CreatedOn",
table: "AspNetUsers",
nullable: true);
migrationBuilder.AddColumn<string>(
name: "DeletedBy",
table: "AspNetUsers",
nullable: true);
migrationBuilder.AddColumn<DateTime>(
name: "DeletedOn",
table: "AspNetUsers",
nullable: true);
migrationBuilder.AddColumn<bool>(
name: "IsDeleted",
table: "AspNetUsers",
nullable: false,
defaultValue: false);
migrationBuilder.AddColumn<DateTime>(
name: "LastUpdatedOn",
table: "AspNetUsers",
nullable: true);
migrationBuilder.AddColumn<DateTime>(
name: "CreatedOn",
table: "Persons",
nullable: true);
migrationBuilder.AddColumn<string>(
name: "DeletedBy",
table: "Persons",
nullable: true);
migrationBuilder.AddColumn<DateTime>(
name: "DeletedOn",
table: "Persons",
nullable: true);
migrationBuilder.AddColumn<bool>(
name: "IsDeleted",
table: "Persons",
nullable: false,
defaultValue: false);
migrationBuilder.AddColumn<DateTime>(
name: "LastUpdatedOn",
table: "Persons",
nullable: true);
migrationBuilder.AlterColumn<DateTime>(
name: "LastUpdatedOn",
table: "Units",
nullable: true,
oldClrType: typeof(DateTime));
migrationBuilder.AddColumn<DateTime>(
name: "CreatedOn",
table: "Units",
nullable: true);
migrationBuilder.AddColumn<string>(
name: "DeletedBy",
table: "Units",
nullable: true);
migrationBuilder.AddColumn<DateTime>(
name: "DeletedOn",
table: "Units",
nullable: true);
migrationBuilder.AddColumn<bool>(
name: "IsDeleted",
table: "Units",
nullable: false,
defaultValue: false);
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "CreatedOn",
table: "AspNetUsers");
migrationBuilder.DropColumn(
name: "DeletedBy",
table: "AspNetUsers");
migrationBuilder.DropColumn(
name: "DeletedOn",
table: "AspNetUsers");
migrationBuilder.DropColumn(
name: "IsDeleted",
table: "AspNetUsers");
migrationBuilder.DropColumn(
name: "LastUpdatedOn",
table: "AspNetUsers");
migrationBuilder.DropColumn(
name: "CreatedOn",
table: "Persons");
migrationBuilder.DropColumn(
name: "DeletedBy",
table: "Persons");
migrationBuilder.DropColumn(
name: "DeletedOn",
table: "Persons");
migrationBuilder.DropColumn(
name: "IsDeleted",
table: "Persons");
migrationBuilder.DropColumn(
name: "LastUpdatedOn",
table: "Persons");
migrationBuilder.DropColumn(
name: "CreatedOn",
table: "Units");
migrationBuilder.DropColumn(
name: "DeletedBy",
table: "Units");
migrationBuilder.DropColumn(
name: "DeletedOn",
table: "Units");
migrationBuilder.DropColumn(
name: "IsDeleted",
table: "Units");
migrationBuilder.AlterColumn<DateTime>(
name: "LastUpdatedOn",
table: "Units",
nullable: false,
oldClrType: typeof(DateTime),
oldNullable: true);
}
}
}
| 30.566879 | 72 | 0.463847 | [
"MIT"
] | JediKnights/TelerikAcademy-Angular-Course-Server | src/Angular.Server.Data/Migrations/20170101150809_AuditableFields.cs | 4,801 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated from a template.
//
// Manual changes to this file may cause unexpected behavior in your application.
// Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace LinQ.Katas.DataRepository
{
using System;
using System.Collections.Generic;
public partial class Employee
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public Employee()
{
this.EmployeeDepartmentHistories = new HashSet<EmployeeDepartmentHistory>();
this.EmployeePayHistories = new HashSet<EmployeePayHistory>();
this.JobCandidates = new HashSet<JobCandidate>();
this.PurchaseOrderHeaders = new HashSet<PurchaseOrderHeader>();
}
public int BusinessEntityID { get; set; }
public string NationalIDNumber { get; set; }
public string LoginID { get; set; }
public Nullable<short> OrganizationLevel { get; set; }
public string JobTitle { get; set; }
public System.DateTime BirthDate { get; set; }
public string MaritalStatus { get; set; }
public string Gender { get; set; }
public System.DateTime HireDate { get; set; }
public bool SalariedFlag { get; set; }
public short VacationHours { get; set; }
public short SickLeaveHours { get; set; }
public bool CurrentFlag { get; set; }
public System.Guid rowguid { get; set; }
public System.DateTime ModifiedDate { get; set; }
public virtual Person Person { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<EmployeeDepartmentHistory> EmployeeDepartmentHistories { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<EmployeePayHistory> EmployeePayHistories { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<JobCandidate> JobCandidates { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<PurchaseOrderHeader> PurchaseOrderHeaders { get; set; }
public virtual SalesPerson SalesPerson { get; set; }
}
}
| 51.555556 | 128 | 0.655532 | [
"MIT"
] | cybk/LinQ.Katas | LinQ.Katas/LinQ.Katas.DataRepository/Employee.cs | 2,784 | C# |
namespace SentryApi.Client
{
public class IssuesRequest : SentryRequest
{
public IssuesRequest(string organizationSlug, string projectSlug)
: this(organizationSlug, projectSlug, null, Period.All)
{
}
public IssuesRequest(string organizationSlug, string projectSlug, string queryString)
: this(organizationSlug, projectSlug, queryString, Period.All)
{
}
public IssuesRequest(string organizationSlug, string projectSlug, string queryString, Period period)
: base(organizationSlug, projectSlug)
{
Period = period;
QueryString = queryString;
}
public Period Period { get; }
public string QueryString { get; }
}
}
| 28.666667 | 108 | 0.630491 | [
"MIT"
] | olsh/sentry-api-client | src/SentryApi.Client/Models/IssuesRequest.cs | 776 | C# |
using System;
using NetRuntimeSystem = System;
using System.ComponentModel;
using NetOffice.Attributes;
namespace NetOffice.MSHTMLApi
{
/// <summary>
/// DispatchInterface IHTMLStyleSheet3
/// SupportByVersion MSHTML, 4
/// </summary>
[SupportByVersion("MSHTML", 4)]
[EntityType(EntityType.IsDispatchInterface)]
[TypeId("30510496-98B5-11CF-BB82-00AA00BDCE0B")]
public interface IHTMLStyleSheet3 : IHTMLStyleSheet2
{
}
}
| 22.789474 | 53 | 0.764434 | [
"MIT"
] | igoreksiz/NetOffice | Source/MSHTML/DispatchInterfaces/IHTMLStyleSheet3.cs | 435 | C# |
using Bitsmith.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Bitsmith.ViewModels
{
public class ListItemViewModel : ViewModel<ListItem>
{
private bool _IsSelected;
public bool IsSelected
{
get { return _IsSelected; }
set
{
_IsSelected = value;
OnPropertyChanged("IsSelected");
}
}
public string DatastoreId
{
get
{
return Model.Id;
}
set
{
Model.Id = value;
OnPropertyChanged("DatastoreId");
}
}
public string Id
{
get
{
return Model.Identifier.Id;
}
set
{
Model.Identifier.Id = value;
OnPropertyChanged("Id");
}
}
public string Display
{
get
{
return Model.Identifier.Display;
}
set
{
Model.Identifier.Display = value;
OnPropertyChanged("Display");
}
}
public string Token
{
get
{
return Model.Identifier.Token;
}
set
{
Model.Identifier.Token = value;
OnPropertyChanged("Token");
}
}
public string MasterId
{
get
{
return Model.Identifier.MasterId;
}
set
{
Model.Identifier.MasterId = value;
OnPropertyChanged("MasterId");
}
}
public string Group
{
get
{
return Model.Group;
}
set
{
Model.Group = value;
OnPropertyChanged("Group");
}
}
public string Key
{
get
{
return Model.Key;
}
set
{
Model.Key = value;
OnPropertyChanged("Key");
}
}
private string _Value;
public string Value
{
get
{
return _Value;
}
set
{
_Value = value;
OnPropertyChanged("Value");
}
}
public int Sort
{
get
{
return Model.Sort;
}
set
{
Model.Sort = value;
OnPropertyChanged("Sort");
}
}
public ListItemViewModel(ListItem model)
{
Model = model;
}
}
}
| 19.10828 | 56 | 0.371333 | [
"MIT"
] | eXtensoft/eXtensoft-snippet | src/Bitsmith/modules/.common/view.models/shared/lists/ListItemViewModel.cs | 3,002 | C# |
using System.Linq;
using System.Reflection;
using UnityEditor;
using UnityEngine;
using UnityWeld.Binding;
using UnityWeld.Binding.Internal;
namespace UnityWeld_Editor
{
[CustomEditor(typeof(EventBinding))]
public class EventBindingEditor : BaseBindingEditor
{
private EventBinding targetScript;
// Whether or not the values on our target match its prefab.
private bool viewEventPrefabModified;
private bool viewModelMethodPrefabModified;
private void OnEnable()
{
targetScript = (EventBinding)target;
}
public override void OnInspectorGUI()
{
if (CannotModifyInPlayMode())
{
GUI.enabled = false;
}
UpdatePrefabModifiedProperties();
var defaultLabelStyle = EditorStyles.label.fontStyle;
EditorStyles.label.fontStyle = viewEventPrefabModified
? FontStyle.Bold
: defaultLabelStyle;
ShowEventMenu(
UnityEventWatcher.GetBindableEvents(targetScript.gameObject)
.OrderBy(evt => evt.Name)
.ToArray(),
updatedValue => targetScript.ViewEventName = updatedValue,
targetScript.ViewEventName
);
EditorStyles.label.fontStyle = viewModelMethodPrefabModified
? FontStyle.Bold
: defaultLabelStyle;
ShowMethodMenu(targetScript, TypeResolver.FindBindableMethods(targetScript));
EditorStyles.label.fontStyle = defaultLabelStyle;
}
/// <summary>
/// Draws the dropdown for selecting a method from bindableViewModelMethods
/// </summary>
private void ShowMethodMenu(
EventBinding targetScript,
BindableMember<MethodInfo>[] bindableMethods
)
{
var tooltip = "Method on the view-model to bind to.";
InspectorUtils.DoPopup(
new GUIContent(targetScript.ViewModelMethodName),
new GUIContent("View-model method", tooltip),
m => m.ViewModelType + "/" + m.MemberName,
m => true,
m => m.ToString() == targetScript.ViewModelMethodName,
m => UpdateProperty(
updatedValue => targetScript.ViewModelMethodName = updatedValue,
targetScript.ViewModelMethodName,
m.ToString(),
"Set bound view-model method"
),
bindableMethods
.OrderBy(m => m.ViewModelTypeName)
.ThenBy(m => m.MemberName)
.ToArray()
);
}
/// <summary>
/// Check whether each of the properties on the object have been changed
/// from the value in the prefab.
/// </summary>
private void UpdatePrefabModifiedProperties()
{
var property = serializedObject.GetIterator();
// Need to call Next(true) to get the first child. Once we have it,
// Next(false) will iterate through the properties.
property.Next(true);
do
{
switch (property.name)
{
case "viewEventName":
viewEventPrefabModified = property.prefabOverride;
break;
case "viewModelMethodName":
viewModelMethodPrefabModified = property.prefabOverride;
break;
}
}
while (property.Next(false));
}
}
}
| 34.585586 | 90 | 0.533472 | [
"MIT"
] | MonarchSolutions/Unity-Weld | UnityWeld_Editor/EventBindingEditor.cs | 3,839 | C# |
using Microsoft.SqlServer.XEvent.Linq;
using NLog;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace XESmartTarget.Core
{
public class Target
{
private static Logger logger = LogManager.GetCurrentClassLogger();
public Target()
{
}
public List<Response> Responses { get; set; } = new List<Response>();
public string ServerName { get; set; }
public string SessionName { get; set; }
public string UserName { get; set; }
public string Password { get; set; }
public string DatabaseName { get; set; }
public bool FailOnProcessingError { get; set; } = false;
private bool stopped = false;
public void Start()
{
string connectionString = "Data Source=" + ServerName + ";";
if (String.IsNullOrEmpty(DatabaseName))
{
connectionString += "Initial Catalog = master; ";
}
else
{
connectionString += "Initial Catalog = " + DatabaseName + "; ";
}
if (String.IsNullOrEmpty(UserName))
{
connectionString += "Integrated Security = SSPI; ";
}
else
{
connectionString += "User Id = " + UserName + "; ";
connectionString += "Password = " + Password + "; ";
}
logger.Info(String.Format("Connecting to XE session '{0}' on server '{1}'", SessionName,ServerName));
QueryableXEventData eventStream = new QueryableXEventData(
connectionString,
SessionName,
EventStreamSourceOptions.EventStream,
EventStreamCacheOptions.DoNotCache);
logger.Info("Connected.");
try
{
foreach (PublishedEvent xevent in eventStream)
{
if (stopped)
{
break;
}
// Pass events to the responses
foreach (Response r in Responses)
{
// filter out unwanted events
// if no events are specified, will process all
if (r.Events.Count > 0)
{
if (!r.Events.Contains(xevent.Name))
{
continue;
}
}
try
{
r.Process(xevent);
}
catch(Exception e)
{
if (FailOnProcessingError)
{
throw;
}
else
{
logger.Error(e);
}
}
}
}
}
catch (Exception e)
{
logger.Error(e);
throw;
}
logger.Info("Quitting");
}
public void Stop()
{
stopped = true;
}
}
}
| 29.904348 | 113 | 0.410875 | [
"MIT"
] | denissukhotin/XESmartTarget | XESmartTarget.Core/Target.cs | 3,441 | C# |
// <auto-generated />
using System;
using Dalmatian.Data;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
namespace Dalmatian.Data.Migrations
{
[DbContext(typeof(ApplicationDbContext))]
[Migration("20200415174707_EditTableDogAndPerson")]
partial class EditTableDogAndPerson
{
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "3.1.2")
.HasAnnotation("Relational:MaxIdentifierLength", 128)
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
modelBuilder.Entity("Dalmatian.Data.Models.ApplicationRole", b =>
{
b.Property<string>("Id")
.HasColumnType("nvarchar(450)");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken()
.HasColumnType("nvarchar(max)");
b.Property<DateTime>("CreatedOn")
.HasColumnType("datetime2");
b.Property<DateTime?>("DeletedOn")
.HasColumnType("datetime2");
b.Property<bool>("IsDeleted")
.HasColumnType("bit");
b.Property<DateTime?>("ModifiedOn")
.HasColumnType("datetime2");
b.Property<string>("Name")
.HasColumnType("nvarchar(256)")
.HasMaxLength(256);
b.Property<string>("NormalizedName")
.HasColumnType("nvarchar(256)")
.HasMaxLength(256);
b.HasKey("Id");
b.HasIndex("IsDeleted");
b.HasIndex("NormalizedName")
.IsUnique()
.HasName("RoleNameIndex")
.HasFilter("[NormalizedName] IS NOT NULL");
b.ToTable("AspNetRoles");
});
modelBuilder.Entity("Dalmatian.Data.Models.ApplicationUser", b =>
{
b.Property<string>("Id")
.HasColumnType("nvarchar(450)");
b.Property<int>("AccessFailedCount")
.HasColumnType("int");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken()
.HasColumnType("nvarchar(max)");
b.Property<DateTime>("CreatedOn")
.HasColumnType("datetime2");
b.Property<DateTime?>("DeletedOn")
.HasColumnType("datetime2");
b.Property<string>("Email")
.HasColumnType("nvarchar(256)")
.HasMaxLength(256);
b.Property<bool>("EmailConfirmed")
.HasColumnType("bit");
b.Property<bool>("IsDeleted")
.HasColumnType("bit");
b.Property<bool>("LockoutEnabled")
.HasColumnType("bit");
b.Property<DateTimeOffset?>("LockoutEnd")
.HasColumnType("datetimeoffset");
b.Property<DateTime?>("ModifiedOn")
.HasColumnType("datetime2");
b.Property<string>("NormalizedEmail")
.HasColumnType("nvarchar(256)")
.HasMaxLength(256);
b.Property<string>("NormalizedUserName")
.HasColumnType("nvarchar(256)")
.HasMaxLength(256);
b.Property<string>("PasswordHash")
.HasColumnType("nvarchar(max)");
b.Property<string>("PhoneNumber")
.HasColumnType("nvarchar(max)");
b.Property<bool>("PhoneNumberConfirmed")
.HasColumnType("bit");
b.Property<string>("SecurityStamp")
.HasColumnType("nvarchar(max)");
b.Property<bool>("TwoFactorEnabled")
.HasColumnType("bit");
b.Property<string>("UserName")
.HasColumnType("nvarchar(256)")
.HasMaxLength(256);
b.HasKey("Id");
b.HasIndex("IsDeleted");
b.HasIndex("NormalizedEmail")
.HasName("EmailIndex");
b.HasIndex("NormalizedUserName")
.IsUnique()
.HasName("UserNameIndex")
.HasFilter("[NormalizedUserName] IS NOT NULL");
b.ToTable("AspNetUsers");
});
modelBuilder.Entity("Dalmatian.Data.Models.BirthCertificate", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<int>("ConfirmationOfMatingId")
.HasColumnType("int");
b.Property<DateTime>("CreatedOn")
.HasColumnType("datetime2");
b.Property<DateTime>("DateOfBirth")
.HasColumnType("datetime2");
b.Property<DateTime?>("DeletedOn")
.HasColumnType("datetime2");
b.Property<bool>("IsDeleted")
.HasColumnType("bit");
b.Property<int>("KennelId")
.HasColumnType("int");
b.Property<int>("LetterOfLitter")
.HasColumnType("int");
b.Property<DateTime?>("ModifiedOn")
.HasColumnType("datetime2");
b.Property<int>("NumberOfFemales")
.HasColumnType("int");
b.Property<int>("NumberOfMales")
.HasColumnType("int");
b.Property<int>("NumberOfPuppies")
.HasColumnType("int");
b.Property<int>("PersonId")
.HasColumnType("int");
b.Property<string>("RegistrationNumber")
.HasColumnType("nvarchar(max)");
b.HasKey("Id");
b.HasIndex("ConfirmationOfMatingId");
b.HasIndex("IsDeleted");
b.HasIndex("KennelId");
b.HasIndex("PersonId");
b.ToTable("BirthCertificates");
});
modelBuilder.Entity("Dalmatian.Data.Models.BreedingInformation", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<int>("BreedingStatus")
.HasColumnType("int");
b.Property<int>("CountryOfOrigin")
.HasColumnType("int");
b.Property<int>("CountryOfResidence")
.HasColumnType("int");
b.Property<DateTime>("CreatedOn")
.HasColumnType("datetime2");
b.Property<DateTime?>("DeletedOn")
.HasColumnType("datetime2");
b.Property<int>("DogId")
.HasColumnType("int");
b.Property<double>("Height")
.HasColumnType("float");
b.Property<int>("HeightUnits")
.HasColumnType("int");
b.Property<bool>("IsDeleted")
.HasColumnType("bit");
b.Property<DateTime?>("ModifiedOn")
.HasColumnType("datetime2");
b.Property<double>("Weight")
.HasColumnType("float");
b.Property<int>("WeightUnits")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("DogId");
b.HasIndex("IsDeleted");
b.ToTable("BreedingInformations");
});
modelBuilder.Entity("Dalmatian.Data.Models.ClubRegisterNumber", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<string>("ClubNumber")
.HasColumnType("nvarchar(max)");
b.Property<DateTime>("CreatedOn")
.HasColumnType("datetime2");
b.Property<DateTime?>("DateOfClubRegister")
.HasColumnType("datetime2");
b.Property<DateTime?>("DeletedOn")
.HasColumnType("datetime2");
b.Property<int>("DogId")
.HasColumnType("int");
b.Property<bool>("IsDeleted")
.HasColumnType("bit");
b.Property<DateTime?>("ModifiedOn")
.HasColumnType("datetime2");
b.HasKey("Id");
b.HasIndex("DogId");
b.HasIndex("IsDeleted");
b.ToTable("ClubRegisterNumbers");
});
modelBuilder.Entity("Dalmatian.Data.Models.ConfirmationOfMating", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<DateTime>("CreatedOn")
.HasColumnType("datetime2");
b.Property<DateTime>("DateOfMating")
.HasColumnType("datetime2");
b.Property<DateTime?>("DeletedOn")
.HasColumnType("datetime2");
b.Property<int>("DogFatherId")
.HasColumnType("int");
b.Property<int>("DogMotherId")
.HasColumnType("int");
b.Property<DateTime>("EstimatedDateOfBirth")
.HasColumnType("datetime2");
b.Property<bool>("IsDeleted")
.HasColumnType("bit");
b.Property<DateTime?>("ModifiedOn")
.HasColumnType("datetime2");
b.Property<string>("OwnerFemaleDog")
.HasColumnType("nvarchar(max)");
b.Property<string>("OwnerMaleDog")
.HasColumnType("nvarchar(max)");
b.Property<string>("RegistrationNumber")
.HasColumnType("nvarchar(max)");
b.Property<int>("TypeOfMating")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("DogFatherId");
b.HasIndex("DogMotherId");
b.HasIndex("IsDeleted");
b.ToTable("ConfirmationOfMatings");
});
modelBuilder.Entity("Dalmatian.Data.Models.Dog", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<int>("Breed")
.HasColumnType("int");
b.Property<int>("Color")
.HasColumnType("int");
b.Property<DateTime>("CreatedOn")
.HasColumnType("datetime2");
b.Property<DateTime?>("DateOfBirth")
.HasColumnType("datetime2");
b.Property<DateTime?>("DateOfDeath")
.HasColumnType("datetime2");
b.Property<DateTime?>("DeletedOn")
.HasColumnType("datetime2");
b.Property<int?>("FatherDogId")
.HasColumnType("int");
b.Property<string>("ImagesUrl")
.HasColumnType("nvarchar(max)");
b.Property<bool>("IsDeleted")
.HasColumnType("bit");
b.Property<DateTime?>("ModifiedOn")
.HasColumnType("datetime2");
b.Property<int?>("MotherDogId")
.HasColumnType("int");
b.Property<string>("PedigreeName")
.HasColumnType("nvarchar(max)");
b.Property<int?>("PersonBreederId")
.HasColumnType("int");
b.Property<int?>("PersonOwnerId")
.HasColumnType("int");
b.Property<int>("SexDog")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("FatherDogId");
b.HasIndex("IsDeleted");
b.HasIndex("MotherDogId");
b.HasIndex("PersonBreederId");
b.HasIndex("PersonOwnerId");
b.ToTable("Dogs");
});
modelBuilder.Entity("Dalmatian.Data.Models.HealthInformation", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<int>("Baer")
.HasColumnType("int");
b.Property<DateTime>("CreatedOn")
.HasColumnType("datetime2");
b.Property<DateTime?>("DateOfBaer")
.HasColumnType("datetime2");
b.Property<DateTime?>("DateOfElbowRating")
.HasColumnType("datetime2");
b.Property<DateTime?>("DateOfHipRating")
.HasColumnType("datetime2");
b.Property<DateTime?>("DeletedOn")
.HasColumnType("datetime2");
b.Property<int>("DogId")
.HasColumnType("int");
b.Property<int>("ElbowRating")
.HasColumnType("int");
b.Property<int>("HipRating")
.HasColumnType("int");
b.Property<bool>("IsDeleted")
.HasColumnType("bit");
b.Property<DateTime?>("ModifiedOn")
.HasColumnType("datetime2");
b.Property<string>("OtherHealthTest")
.HasColumnType("nvarchar(max)");
b.HasKey("Id");
b.HasIndex("DogId");
b.HasIndex("IsDeleted");
b.ToTable("HealthInformations");
});
modelBuilder.Entity("Dalmatian.Data.Models.Kennel", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<string>("Address")
.HasColumnType("nvarchar(max)");
b.Property<string>("City")
.HasColumnType("nvarchar(max)");
b.Property<int>("Country")
.HasColumnType("int");
b.Property<DateTime>("CreatedOn")
.HasColumnType("datetime2");
b.Property<DateTime>("DateOfRegistration")
.HasColumnType("datetime2");
b.Property<DateTime?>("DeletedOn")
.HasColumnType("datetime2");
b.Property<bool>("IsDeleted")
.HasColumnType("bit");
b.Property<DateTime?>("ModifiedOn")
.HasColumnType("datetime2");
b.Property<string>("Name")
.HasColumnType("nvarchar(max)");
b.Property<int?>("PersonCoOwnerId")
.HasColumnType("int");
b.Property<int>("PersonOwnerId")
.HasColumnType("int");
b.Property<string>("RegistrationNumber")
.HasColumnType("nvarchar(max)");
b.HasKey("Id");
b.HasIndex("IsDeleted");
b.HasIndex("PersonCoOwnerId");
b.HasIndex("PersonOwnerId");
b.ToTable("Kennels");
});
modelBuilder.Entity("Dalmatian.Data.Models.Litter", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<DateTime>("CreatedOn")
.HasColumnType("datetime2");
b.Property<DateTime?>("DeletedOn")
.HasColumnType("datetime2");
b.Property<bool>("IsDeleted")
.HasColumnType("bit");
b.Property<DateTime?>("ModifiedOn")
.HasColumnType("datetime2");
b.HasKey("Id");
b.HasIndex("IsDeleted");
b.ToTable("Litters");
});
modelBuilder.Entity("Dalmatian.Data.Models.Parent", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<DateTime>("CreatedOn")
.HasColumnType("datetime2");
b.Property<DateTime?>("DeletedOn")
.HasColumnType("datetime2");
b.Property<bool>("IsDeleted")
.HasColumnType("bit");
b.Property<DateTime?>("ModifiedOn")
.HasColumnType("datetime2");
b.HasKey("Id");
b.HasIndex("IsDeleted");
b.ToTable("Parents");
});
modelBuilder.Entity("Dalmatian.Data.Models.Person", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<string>("Address")
.HasColumnType("nvarchar(max)");
b.Property<string>("City")
.HasColumnType("nvarchar(max)");
b.Property<int>("Country")
.HasColumnType("int");
b.Property<DateTime>("CreatedOn")
.HasColumnType("datetime2");
b.Property<DateTime?>("DeletedOn")
.HasColumnType("datetime2");
b.Property<string>("Email")
.HasColumnType("nvarchar(max)");
b.Property<string>("Facebook")
.HasColumnType("nvarchar(max)");
b.Property<string>("Firstname")
.HasColumnType("nvarchar(max)");
b.Property<string>("Instagram")
.HasColumnType("nvarchar(max)");
b.Property<bool>("IsDeleted")
.HasColumnType("bit");
b.Property<string>("Lastname")
.HasColumnType("nvarchar(max)");
b.Property<string>("Linkedin")
.HasColumnType("nvarchar(max)");
b.Property<string>("Middlename")
.HasColumnType("nvarchar(max)");
b.Property<DateTime?>("ModifiedOn")
.HasColumnType("datetime2");
b.Property<string>("Phone")
.HasColumnType("nvarchar(max)");
b.Property<string>("Twitter")
.HasColumnType("nvarchar(max)");
b.Property<string>("UserId")
.HasColumnType("nvarchar(450)");
b.Property<string>("Website")
.HasColumnType("nvarchar(max)");
b.HasKey("Id");
b.HasIndex("IsDeleted");
b.HasIndex("UserId");
b.ToTable("Persons");
});
modelBuilder.Entity("Dalmatian.Data.Models.RegistrationDogNumber", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<DateTime>("CreatedOn")
.HasColumnType("datetime2");
b.Property<DateTime?>("DateOfRegistrationNumber")
.HasColumnType("datetime2");
b.Property<DateTime?>("DeletedOn")
.HasColumnType("datetime2");
b.Property<int>("DogId")
.HasColumnType("int");
b.Property<bool>("IsDeleted")
.HasColumnType("bit");
b.Property<DateTime?>("ModifiedOn")
.HasColumnType("datetime2");
b.Property<string>("RegistrationNumber")
.HasColumnType("nvarchar(max)");
b.HasKey("Id");
b.HasIndex("DogId");
b.HasIndex("IsDeleted");
b.ToTable("RegistrationDogNumbers");
});
modelBuilder.Entity("Dalmatian.Data.Models.ReportOfLitter", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<string>("BreederInCharge")
.HasColumnType("nvarchar(max)");
b.Property<DateTime>("CreatedOn")
.HasColumnType("datetime2");
b.Property<DateTime>("DateOfExamination")
.HasColumnType("datetime2");
b.Property<DateTime?>("DeletedOn")
.HasColumnType("datetime2");
b.Property<int>("DogId")
.HasColumnType("int");
b.Property<bool>("IsDeleted")
.HasColumnType("bit");
b.Property<int>("LitterId")
.HasColumnType("int");
b.Property<DateTime?>("ModifiedOn")
.HasColumnType("datetime2");
b.HasKey("Id");
b.HasIndex("DogId");
b.HasIndex("IsDeleted");
b.HasIndex("LitterId");
b.ToTable("ReportOfLitters");
});
modelBuilder.Entity("Dalmatian.Data.Models.Setting", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<DateTime>("CreatedOn")
.HasColumnType("datetime2");
b.Property<DateTime?>("DeletedOn")
.HasColumnType("datetime2");
b.Property<bool>("IsDeleted")
.HasColumnType("bit");
b.Property<DateTime?>("ModifiedOn")
.HasColumnType("datetime2");
b.Property<string>("Name")
.HasColumnType("nvarchar(max)");
b.Property<string>("Value")
.HasColumnType("nvarchar(max)");
b.HasKey("Id");
b.HasIndex("IsDeleted");
b.ToTable("Settings");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<string>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<string>("ClaimType")
.HasColumnType("nvarchar(max)");
b.Property<string>("ClaimValue")
.HasColumnType("nvarchar(max)");
b.Property<string>("RoleId")
.IsRequired()
.HasColumnType("nvarchar(450)");
b.HasKey("Id");
b.HasIndex("RoleId");
b.ToTable("AspNetRoleClaims");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<string>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<string>("ClaimType")
.HasColumnType("nvarchar(max)");
b.Property<string>("ClaimValue")
.HasColumnType("nvarchar(max)");
b.Property<string>("UserId")
.IsRequired()
.HasColumnType("nvarchar(450)");
b.HasKey("Id");
b.HasIndex("UserId");
b.ToTable("AspNetUserClaims");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<string>", b =>
{
b.Property<string>("LoginProvider")
.HasColumnType("nvarchar(450)");
b.Property<string>("ProviderKey")
.HasColumnType("nvarchar(450)");
b.Property<string>("ProviderDisplayName")
.HasColumnType("nvarchar(max)");
b.Property<string>("UserId")
.IsRequired()
.HasColumnType("nvarchar(450)");
b.HasKey("LoginProvider", "ProviderKey");
b.HasIndex("UserId");
b.ToTable("AspNetUserLogins");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<string>", b =>
{
b.Property<string>("UserId")
.HasColumnType("nvarchar(450)");
b.Property<string>("RoleId")
.HasColumnType("nvarchar(450)");
b.HasKey("UserId", "RoleId");
b.HasIndex("RoleId");
b.ToTable("AspNetUserRoles");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<string>", b =>
{
b.Property<string>("UserId")
.HasColumnType("nvarchar(450)");
b.Property<string>("LoginProvider")
.HasColumnType("nvarchar(450)");
b.Property<string>("Name")
.HasColumnType("nvarchar(450)");
b.Property<string>("Value")
.HasColumnType("nvarchar(max)");
b.HasKey("UserId", "LoginProvider", "Name");
b.ToTable("AspNetUserTokens");
});
modelBuilder.Entity("Dalmatian.Data.Models.BirthCertificate", b =>
{
b.HasOne("Dalmatian.Data.Models.ConfirmationOfMating", "ConfirmationOfMating")
.WithMany()
.HasForeignKey("ConfirmationOfMatingId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
b.HasOne("Dalmatian.Data.Models.Kennel", "Kennel")
.WithMany()
.HasForeignKey("KennelId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
b.HasOne("Dalmatian.Data.Models.Person", "Person")
.WithMany()
.HasForeignKey("PersonId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
});
modelBuilder.Entity("Dalmatian.Data.Models.BreedingInformation", b =>
{
b.HasOne("Dalmatian.Data.Models.Dog", "Dog")
.WithMany("BreedingInformations")
.HasForeignKey("DogId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
});
modelBuilder.Entity("Dalmatian.Data.Models.ClubRegisterNumber", b =>
{
b.HasOne("Dalmatian.Data.Models.Dog", "Dog")
.WithMany("ClubRegisterNumbers")
.HasForeignKey("DogId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
});
modelBuilder.Entity("Dalmatian.Data.Models.ConfirmationOfMating", b =>
{
b.HasOne("Dalmatian.Data.Models.Dog", "DogFather")
.WithMany()
.HasForeignKey("DogFatherId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
b.HasOne("Dalmatian.Data.Models.Dog", "DogMother")
.WithMany()
.HasForeignKey("DogMotherId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
});
modelBuilder.Entity("Dalmatian.Data.Models.Dog", b =>
{
b.HasOne("Dalmatian.Data.Models.Dog", "Father")
.WithMany("SubFathers")
.HasForeignKey("FatherDogId");
b.HasOne("Dalmatian.Data.Models.Dog", "Mother")
.WithMany("SubMothers")
.HasForeignKey("MotherDogId");
b.HasOne("Dalmatian.Data.Models.Person", "PersonBreeder")
.WithMany()
.HasForeignKey("PersonBreederId");
b.HasOne("Dalmatian.Data.Models.Person", "PersonOwner")
.WithMany()
.HasForeignKey("PersonOwnerId");
});
modelBuilder.Entity("Dalmatian.Data.Models.HealthInformation", b =>
{
b.HasOne("Dalmatian.Data.Models.Dog", "Dog")
.WithMany("HealthInformations")
.HasForeignKey("DogId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
});
modelBuilder.Entity("Dalmatian.Data.Models.Kennel", b =>
{
b.HasOne("Dalmatian.Data.Models.Person", "PersonCoOwner")
.WithMany()
.HasForeignKey("PersonCoOwnerId");
b.HasOne("Dalmatian.Data.Models.Person", "PersonOwner")
.WithMany()
.HasForeignKey("PersonOwnerId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
});
modelBuilder.Entity("Dalmatian.Data.Models.Person", b =>
{
b.HasOne("Dalmatian.Data.Models.ApplicationUser", "User")
.WithMany()
.HasForeignKey("UserId");
});
modelBuilder.Entity("Dalmatian.Data.Models.RegistrationDogNumber", b =>
{
b.HasOne("Dalmatian.Data.Models.Dog", "Dog")
.WithMany("RegistrationDogNumbers")
.HasForeignKey("DogId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
});
modelBuilder.Entity("Dalmatian.Data.Models.ReportOfLitter", b =>
{
b.HasOne("Dalmatian.Data.Models.Dog", "Dog")
.WithMany()
.HasForeignKey("DogId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
b.HasOne("Dalmatian.Data.Models.Litter", "Litter")
.WithMany()
.HasForeignKey("LitterId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<string>", b =>
{
b.HasOne("Dalmatian.Data.Models.ApplicationRole", null)
.WithMany()
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<string>", b =>
{
b.HasOne("Dalmatian.Data.Models.ApplicationUser", null)
.WithMany("Claims")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<string>", b =>
{
b.HasOne("Dalmatian.Data.Models.ApplicationUser", null)
.WithMany("Logins")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<string>", b =>
{
b.HasOne("Dalmatian.Data.Models.ApplicationRole", null)
.WithMany()
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
b.HasOne("Dalmatian.Data.Models.ApplicationUser", null)
.WithMany("Roles")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<string>", b =>
{
b.HasOne("Dalmatian.Data.Models.ApplicationUser", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
});
#pragma warning restore 612, 618
}
}
}
| 36.474903 | 125 | 0.447655 | [
"MIT"
] | angelneychev/Dalmatian | src/Data/Dalmatian.Data/Migrations/20200415174707_EditTableDogAndPerson.Designer.cs | 37,790 | C# |
// ------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version: 16.0.0.0
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
// ------------------------------------------------------------------------------
namespace Microsoft.StreamProcessing
{
using System.Linq;
using System;
/// <summary>
/// Class to produce the template output
/// </summary>
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.TextTemplating", "16.0.0.0")]
internal partial class SelectManyTemplate : CommonUnaryTemplate
{
/// <summary>
/// Create the template output
/// </summary>
public override string TransformText()
{
this.Write(@"// *********************************************************************
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License
// *********************************************************************
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
using System.Reflection;
using System.Runtime.Serialization;
using Microsoft.StreamProcessing;
using Microsoft.StreamProcessing.Internal;
using Microsoft.StreamProcessing.Internal.Collections;
");
if (this.keyType.Namespace != null)
{
this.Write("using ");
this.Write(this.ToStringHelper.ToStringWithCulture(this.keyType.Namespace));
this.Write(";\r\n");
}
if (this.payloadType.Namespace != null)
{
this.Write("using ");
this.Write(this.ToStringHelper.ToStringWithCulture(this.payloadType.Namespace));
this.Write(";\r\n");
}
if (this.resultType.Namespace != null)
{
this.Write("using ");
this.Write(this.ToStringHelper.ToStringWithCulture(this.resultType.Namespace));
this.Write(";\r\n");
}
this.Write("\r\n// TKey: ");
this.Write(this.ToStringHelper.ToStringWithCulture(TKey));
this.Write("\r\n// TPayload: ");
this.Write(this.ToStringHelper.ToStringWithCulture(TPayload));
this.Write("\r\n// TResult: ");
this.Write(this.ToStringHelper.ToStringWithCulture(TResult));
this.Write("\r\n// Source Fields: ");
this.Write(this.ToStringHelper.ToStringWithCulture(String.Join(",", this.fields.Select(f => f.OriginalName))));
this.Write("\r\n// Destination Fields: ");
this.Write(this.ToStringHelper.ToStringWithCulture(String.Join(",", this.resultFields.Select(f => f.OriginalName))));
this.Write("\r\n// Computed Fields: ");
this.Write(this.ToStringHelper.ToStringWithCulture(String.Join(",", this.computedFields.Keys.Select(f => f.OriginalName))));
this.Write("\r\n// ProjectionReturningResultInstance: ");
this.Write(this.ToStringHelper.ToStringWithCulture(this.projectionReturningResultInstance.ExpressionToCSharp()));
this.Write("\r\n\r\n[DataContract]\r\ninternal sealed class ");
this.Write(this.ToStringHelper.ToStringWithCulture(className));
this.Write(this.ToStringHelper.ToStringWithCulture(genericParameters));
this.Write(" : UnaryPipe<");
this.Write(this.ToStringHelper.ToStringWithCulture(TKey));
this.Write(", ");
this.Write(this.ToStringHelper.ToStringWithCulture(TPayload));
this.Write(", ");
this.Write(this.ToStringHelper.ToStringWithCulture(TResult));
this.Write(">\r\n{\r\n private ");
this.Write(this.ToStringHelper.ToStringWithCulture(Transformer.GetMemoryPoolClassName(this.keyType, this.resultType)));
this.Write(this.ToStringHelper.ToStringWithCulture(MemoryPoolGenericParameters));
this.Write(" pool;\r\n private readonly Func<PlanNode, IQueryObject, PlanNode> queryPlanGene" +
"rator;\r\n\r\n [DataMember]\r\n private int iter;\r\n\r\n private StreamMessage<");
this.Write(this.ToStringHelper.ToStringWithCulture(TKey));
this.Write(", ");
this.Write(this.ToStringHelper.ToStringWithCulture(TResult));
this.Write("> genericBatch;\r\n [DataMember]\r\n private ");
this.Write(this.ToStringHelper.ToStringWithCulture(Transformer.GetBatchClassName(keyType, resultType)));
this.Write(this.ToStringHelper.ToStringWithCulture(TKeyTResultGenericParameters));
this.Write(" batch;\r\n\r\n // Fields used to point directly to the arrays within the result b" +
"atch\r\n private long[] dest_vsync;\r\n private long[] dest_vother;\r\n priva" +
"te ");
this.Write(this.ToStringHelper.ToStringWithCulture(TKey));
this.Write("[] destkey;\r\n private int[] dest_hash;\r\n\r\n ");
this.Write(this.ToStringHelper.ToStringWithCulture(staticCtor));
this.Write("\r\n\r\n public ");
this.Write(this.ToStringHelper.ToStringWithCulture(className));
this.Write("() { }\r\n\r\n public ");
this.Write(this.ToStringHelper.ToStringWithCulture(className));
this.Write("(\r\n IStreamable<");
this.Write(this.ToStringHelper.ToStringWithCulture(TKey));
this.Write(", ");
this.Write(this.ToStringHelper.ToStringWithCulture(TResult));
this.Write("> stream,\r\n IStreamObserver<");
this.Write(this.ToStringHelper.ToStringWithCulture(TKey));
this.Write(", ");
this.Write(this.ToStringHelper.ToStringWithCulture(TResult));
this.Write("> observer,\r\n Func<PlanNode, IQueryObject, PlanNode> queryPlanGenerator)\r\n" +
" : base(stream, observer)\r\n {\r\n pool = MemoryManager.GetMemoryP" +
"ool<");
this.Write(this.ToStringHelper.ToStringWithCulture(TKey));
this.Write(", ");
this.Write(this.ToStringHelper.ToStringWithCulture(TResult));
this.Write(">() as ");
this.Write(this.ToStringHelper.ToStringWithCulture(Transformer.GetMemoryPoolClassName(this.keyType, this.resultType)));
this.Write(this.ToStringHelper.ToStringWithCulture(MemoryPoolGenericParameters));
this.Write(@";
this.queryPlanGenerator = queryPlanGenerator;
MyAllocate();
}
public override void ProduceQueryPlan(PlanNode previous)
{
Observer.ProduceQueryPlan(queryPlanGenerator(previous, this));
}
private void MyAllocate()
{
pool.Get(out genericBatch);
genericBatch.Allocate();
this.batch = genericBatch as ");
this.Write(this.ToStringHelper.ToStringWithCulture(Transformer.GetBatchClassName(keyType, resultType)));
this.Write(this.ToStringHelper.ToStringWithCulture(TKeyTResultGenericParameters));
this.Write(@";
this.UpdatePointers();
}
protected override void UpdatePointers()
{
// Assign pointers to bookkeeping arrays
dest_vsync = this.batch.vsync.col;
dest_vother = this.batch.vother.col;
destkey = this.batch.key.col;
dest_hash = this.batch.hash.col;
}
protected override void DisposeState() => this.batch.Free();
public override unsafe void OnNext(StreamMessage<");
this.Write(this.ToStringHelper.ToStringWithCulture(TKey));
this.Write(", ");
this.Write(this.ToStringHelper.ToStringWithCulture(TPayload));
this.Write("> _inBatch)\r\n {\r\n var batch = _inBatch as ");
this.Write(this.ToStringHelper.ToStringWithCulture(BatchGeneratedFrom_TKey_TPayload));
this.Write(this.ToStringHelper.ToStringWithCulture(TKeyTPayloadGenericParameters));
this.Write(";\r\n\r\n var count = batch.Count;\r\n this.batch.iter = batch.iter;\r\n\r\n " +
" // Create locals that point directly to the arrays within the columns in " +
"the destination batch.\r\n");
foreach (var f in this.computedFields.Keys)
{
if (f.OptimizeString())
{
this.Write(" var dest_");
this.Write(this.ToStringHelper.ToStringWithCulture(f.Name));
this.Write(" = this.batch.");
this.Write(this.ToStringHelper.ToStringWithCulture(f.Name));
this.Write(";\r\n");
}
else
{
this.Write(" var dest_");
this.Write(this.ToStringHelper.ToStringWithCulture(f.Name));
this.Write(" = this.batch.");
this.Write(this.ToStringHelper.ToStringWithCulture(f.Name));
this.Write(".col;\r\n");
}
}
this.Write("\r\n // Create locals that point directly to the arrays within the columns i" +
"n the source batch.\r\n");
foreach (var f in this.fields)
{
if (f.canBeFixed)
{
this.Write(" fixed (");
this.Write(this.ToStringHelper.ToStringWithCulture(f.TypeName));
this.Write("* ");
this.Write(this.ToStringHelper.ToStringWithCulture(f.Name));
this.Write("_col = batch.");
this.Write(this.ToStringHelper.ToStringWithCulture(f.Name));
this.Write(".col)\r\n {\r\n");
}
else
{
this.Write(" var ");
this.Write(this.ToStringHelper.ToStringWithCulture(f.Name));
this.Write("_col = batch.");
this.Write(this.ToStringHelper.ToStringWithCulture(f.Name));
this.Write(".col;\r\n");
}
}
this.Write("\r\n var srckey = batch.key.col;\r\n");
if (this.hasKey)
{
this.Write(" var key_col = srckey; // hack until MakeColumnOriented is fixed\r\n");
}
this.Write(@"
fixed (long* src_bv = batch.bitvector.col, src_vsync = batch.vsync.col, src_vother = batch.vother.col)
fixed (int* src_hash = batch.hash.col)
{
for (int i = 0; i < count; i++)
{
if ((src_bv[i >> 6] & (1L << (i & 0x3f))) == 0)
{
");
if (this.StartEdgeParameterName != null)
{
this.Write(" var ");
this.Write(this.ToStringHelper.ToStringWithCulture(this.StartEdgeParameterName));
this.Write(" = src_vsync[i] < src_vother[i] ? src_vsync[i] : src_vother[i];\r\n");
}
if (this.useEnumerator)
{
this.Write(" var enumerator = ");
this.Write(this.ToStringHelper.ToStringWithCulture(transformedSelectorAsSource));
this.Write(".GetEnumerator();\r\n while (enumerator.MoveNext())\r\n");
}
else
{
if (!this.enumerableRepeatSelector)
{
this.Write("\r\n var e_prime = ");
this.Write(this.ToStringHelper.ToStringWithCulture(transformedSelectorAsSource));
this.Write(";\r\n");
}
this.Write("\r\n");
if (this.keyParameterName != null)
{
this.Write(" var ");
this.Write(this.ToStringHelper.ToStringWithCulture(this.keyParameterName));
this.Write(" = srckey[i];\r\n");
}
this.Write(" for (int _x = 0; _x < ");
this.Write(this.ToStringHelper.ToStringWithCulture(this.loopCounter));
this.Write("; _x++)\r\n");
}
this.Write("\r\n {\r\n dest_vsync[iter] = src_vsync[i];" +
"\r\n dest_vother[iter] = src_vother[i];\r\n");
if (this.useEnumerator)
{
this.Write(" this.batch[iter] = enumerator.Current;\r\n");
}
else if (this.enumerableRepeatSelector)
{
if (this.projectionReturningResultInstance != null)
{
this.Write(" this.batch[iter] = ");
this.Write(this.ToStringHelper.ToStringWithCulture(this.projectionReturningResultInstance.ExpressionToCSharp()));
this.Write(";\r\n");
}
else
{
foreach (var kv in this.computedFields)
{
var f = kv.Key;
var v = kv.Value.ExpressionToCSharp();
if (f.OptimizeString())
{
this.Write(" dest_");
this.Write(this.ToStringHelper.ToStringWithCulture(f.Name));
this.Write(".AddString(");
this.Write(this.ToStringHelper.ToStringWithCulture(v));
this.Write(");\r\n");
}
else
{
this.Write(" dest_");
this.Write(this.ToStringHelper.ToStringWithCulture(f.Name));
this.Write("[iter] = ");
this.Write(this.ToStringHelper.ToStringWithCulture(v));
this.Write(";\r\n");
}
}
}
}
else
{
this.Write(" this.batch[iter] = e_prime;\r\n");
}
this.Write(@"
destkey[iter] = srckey[i];
dest_hash[iter] = src_hash[i];
iter++;
if (iter == Config.DataBatchSize)
{
FlushContents();
// Create locals that point directly to the arrays within the columns in the destination batch.
");
foreach (var f in this.computedFields.Keys)
{
if (f.OptimizeString())
{
this.Write(" dest_");
this.Write(this.ToStringHelper.ToStringWithCulture(f.Name));
this.Write(" = this.batch.");
this.Write(this.ToStringHelper.ToStringWithCulture(f.Name));
this.Write(";\r\n");
}
else
{
this.Write(" dest_");
this.Write(this.ToStringHelper.ToStringWithCulture(f.Name));
this.Write(" = this.batch.");
this.Write(this.ToStringHelper.ToStringWithCulture(f.Name));
this.Write(".col;\r\n");
}
}
this.Write("\r\n this.batch.iter = batch.iter;\r\n " +
" }\r\n }\r\n");
if (this.useEnumerator)
{
this.Write("\r\n enumerator.Dispose();\r\n");
}
this.Write(@" }
else if (src_vother[i] < 0)
{
dest_vsync[iter] = src_vsync[i];
dest_vother[iter] = src_vother[i];
destkey[iter] = default;
this.batch[iter] = default;
dest_hash[iter] = src_hash[i];
this.batch.bitvector.col[(iter) >> 6] |= (1L << ((iter) & 0x3f));
iter++;
if (iter == Config.DataBatchSize)
{
FlushContents();
// Create locals that point directly to the arrays within the columns in the destination batch.
");
foreach (var f in this.computedFields.Keys)
{
if (f.OptimizeString())
{
this.Write(" dest_");
this.Write(this.ToStringHelper.ToStringWithCulture(f.Name));
this.Write(" = this.batch.");
this.Write(this.ToStringHelper.ToStringWithCulture(f.Name));
this.Write(";\r\n");
}
else
{
this.Write(" dest_");
this.Write(this.ToStringHelper.ToStringWithCulture(f.Name));
this.Write(" = this.batch.");
this.Write(this.ToStringHelper.ToStringWithCulture(f.Name));
this.Write(".col;\r\n");
}
}
this.Write(" this.batch.iter = batch.iter;\r\n }\r\n " +
" }\r\n }\r\n\r\n } // end src_hash, src_bv, src_vsync, s" +
"rc_vother\r\n\r\n");
foreach (var f in this.fields.Where(fld => fld.canBeFixed))
{
this.Write(" }\r\n");
}
this.Write(@"
batch.Free();
}
protected override void FlushContents()
{
if (iter == 0) return;
this.batch.Count = iter;
this.batch.Seal();
this.Observer.OnNext(this.batch);
iter = 0;
MyAllocate();
}
public override int CurrentlyBufferedOutputCount => iter;
public override int CurrentlyBufferedInputCount => 0;
}
");
return this.GenerationEnvironment.ToString();
}
}
}
| 43.468672 | 136 | 0.541571 | [
"MIT"
] | AlgorithmsAreCool/Trill | Sources/Core/Microsoft.StreamProcessing/Operators/SelectMany/SelectManyTemplate.cs | 17,346 | C# |
using System;
using System.Collections.Generic;
using System.Text;
namespace Core.Utilities.Results
{
public class ErrorDataResult<T> : DataResult<T>
{
public ErrorDataResult(T data, string message) : base(data, false, message)
{
}
public ErrorDataResult(T data) : base(data, false)
{
}
public ErrorDataResult(string message) : base(default, false, message)
{
}
public ErrorDataResult() : base(default, false)
{
}
}
}
| 20.423077 | 83 | 0.591337 | [
"MIT"
] | msarigul20/BootcampBackendCode | BootcampFinalProject/Core/Utilities/Results/ErrorDataResult.cs | 533 | C# |
#region << 版 本 注 释 >>
/*----------------------------------------------------------------
* Copyright (C) 2018 天下商机(txooo.com)版权所有
*
* 文 件 名:PlatformType
* 所属项目:Iwenli.Mobile
* 创建用户:iwenli(HouWeiya)
* 创建时间:2018/5/21 16:55:04
*
* 功能描述:
* 1、
*
* 修改标识:
* 修改描述:
* 修改时间:
* 待 完 善:
* 1、
----------------------------------------------------------------*/
#endregion
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Iwenli.Mobile
{
/// <summary>
/// 公众平台类型
/// </summary>
public enum PlatformType : int
{
/// <summary>
/// Wap
/// </summary>
Default = 0,
/// <summary>
/// 微信
/// </summary>
Weixin = 1,
/// <summary>
/// 易信
/// </summary>
Yixin = 2,
/// <summary>
/// 来往
/// </summary>
Laiwan = 3,
/// <summary>
/// 飞信
/// </summary>
Feixin = 4,
/// <summary>
/// 支付宝
/// </summary>
Alipay = 5,
/// <summary>
/// 新浪微博
/// </summary>
Weibo = 6,
/// <summary>
/// 腾讯微博
/// </summary>
TQQ = 7,
/// <summary>
/// 微信小程序
/// </summary>
MiniProgram = 100,
/// <summary>
/// 支付宝生活号
/// </summary>
AliLive = 101
}
}
| 19.355263 | 66 | 0.371176 | [
"Apache-2.0"
] | iwenli/ILI | Iwenli.Mobile/PlatformType.cs | 1,663 | C# |
namespace Zinc.WebServices.Rest
{
internal class ZnHeaders
{
internal const string ActivityId = "Zn-ActivityId";
internal const string AccessToken = "Zn-AccessToken";
internal const string ExecutionId = "Zn-ExecutionId";
internal const string MomentStart = "Zn-MomentStart";
internal const string MomentEnd = "Zn-MomentEnd";
}
}
| 31.833333 | 61 | 0.67801 | [
"BSD-3-Clause"
] | filipetoscano/Zinc | src/Zinc.WebServices/Rest/ZnHeaders.cs | 384 | 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 devicefarm-2015-06-23.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.DeviceFarm.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using ThirdParty.Json.LitJson;
namespace Amazon.DeviceFarm.Model.Internal.MarshallTransformations
{
/// <summary>
/// Response Unmarshaller for UpdateInstanceProfile operation
/// </summary>
public class UpdateInstanceProfileResponseUnmarshaller : JsonResponseUnmarshaller
{
/// <summary>
/// Unmarshaller the response from the service to the response class.
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
public override AmazonWebServiceResponse Unmarshall(JsonUnmarshallerContext context)
{
UpdateInstanceProfileResponse response = new UpdateInstanceProfileResponse();
context.Read();
int targetDepth = context.CurrentDepth;
while (context.ReadAtDepth(targetDepth))
{
if (context.TestExpression("instanceProfile", targetDepth))
{
var unmarshaller = InstanceProfileUnmarshaller.Instance;
response.InstanceProfile = unmarshaller.Unmarshall(context);
continue;
}
}
return response;
}
/// <summary>
/// Unmarshaller error response to exception.
/// </summary>
/// <param name="context"></param>
/// <param name="innerException"></param>
/// <param name="statusCode"></param>
/// <returns></returns>
public override AmazonServiceException UnmarshallException(JsonUnmarshallerContext context, Exception innerException, HttpStatusCode statusCode)
{
var errorResponse = JsonErrorResponseUnmarshaller.GetInstance().Unmarshall(context);
errorResponse.InnerException = innerException;
errorResponse.StatusCode = statusCode;
var responseBodyBytes = context.GetResponseBodyBytes();
using (var streamCopy = new MemoryStream(responseBodyBytes))
using (var contextCopy = new JsonUnmarshallerContext(streamCopy, false, null))
{
if (errorResponse.Code != null && errorResponse.Code.Equals("ArgumentException"))
{
return ArgumentExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("LimitExceededException"))
{
return LimitExceededExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("NotFoundException"))
{
return NotFoundExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("ServiceAccountException"))
{
return ServiceAccountExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse);
}
}
return new AmazonDeviceFarmException(errorResponse.Message, errorResponse.InnerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, errorResponse.StatusCode);
}
private static UpdateInstanceProfileResponseUnmarshaller _instance = new UpdateInstanceProfileResponseUnmarshaller();
internal static UpdateInstanceProfileResponseUnmarshaller GetInstance()
{
return _instance;
}
/// <summary>
/// Gets the singleton.
/// </summary>
public static UpdateInstanceProfileResponseUnmarshaller Instance
{
get
{
return _instance;
}
}
}
} | 40.565574 | 194 | 0.630835 | [
"Apache-2.0"
] | philasmar/aws-sdk-net | sdk/src/Services/DeviceFarm/Generated/Model/Internal/MarshallTransformations/UpdateInstanceProfileResponseUnmarshaller.cs | 4,949 | C# |
using NBitcoin.RPC;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using NBitcoin;
using NTumbleBit.Logging;
namespace NTumbleBit.Services.RPC
{
public class RPCBroadcastService : IBroadcastService
{
public class Record
{
public int Expiration
{
get; set;
}
public Transaction Transaction
{
get; set;
}
}
RPCWalletCache _Cache;
public RPCBroadcastService(RPCClient rpc, RPCWalletCache cache, IRepository repository)
{
_RPCClient = rpc ?? throw new ArgumentNullException(nameof(rpc));
_Repository = repository ?? throw new ArgumentNullException(nameof(repository));
_Cache = cache;
_BlockExplorerService = new RPCBlockExplorerService(rpc, cache, repository);
_RPCBatch = new RPCBatch<bool>(_RPCClient);
}
public TimeSpan BatchInterval
{
get
{
return _RPCBatch.BatchInterval;
}
set
{
_RPCBatch.BatchInterval = value;
}
}
private readonly RPCBlockExplorerService _BlockExplorerService;
private readonly RPCBatch<bool> _RPCBatch;
public RPCBlockExplorerService BlockExplorerService
{
get
{
return _BlockExplorerService;
}
}
private readonly IRepository _Repository;
public IRepository Repository
{
get
{
return _Repository;
}
}
private readonly RPCClient _RPCClient;
public RPCClient RPCClient
{
get
{
return _RPCClient;
}
}
public Record[] GetTransactions()
{
var transactions = Repository.List<Record>("Broadcasts");
foreach(var tx in transactions)
tx.Transaction.PrecomputeHash(true, true);
var txByTxId = transactions.ToDictionary(t => t.Transaction.GetHash());
var dependsOn = transactions.Select(t => new
{
Tx = t,
Depends = t.Transaction.Inputs.Select(i => i.PrevOut)
.Where(o => txByTxId.ContainsKey(o.Hash))
.Select(o => txByTxId[o.Hash])
})
.ToDictionary(o => o.Tx, o => o.Depends.ToArray());
return transactions.TopologicalSort(tx => dependsOn[tx]).ToArray();
}
public Transaction[] TryBroadcast()
{
uint256[] r = null;
return TryBroadcast(ref r);
}
public Transaction[] TryBroadcast(ref uint256[] knownBroadcasted)
{
var startTime = DateTimeOffset.UtcNow;
int totalEntries = 0;
List<Transaction> broadcasted = new List<Transaction>();
var broadcasting = new List<Tuple<Transaction, Task<bool>>>();
HashSet<uint256> knownBroadcastedSet = new HashSet<uint256>(knownBroadcasted ?? new uint256[0]);
int height = _Cache.BlockCount;
foreach(var obj in _Cache.GetEntries())
{
if(obj.Confirmations > 0)
knownBroadcastedSet.Add(obj.TransactionId);
}
foreach(var tx in GetTransactions())
{
totalEntries++;
if(!knownBroadcastedSet.Contains(tx.Transaction.GetHash()))
{
broadcasting.Add(Tuple.Create(tx.Transaction, TryBroadcastCoreAsync(tx, height)));
}
knownBroadcastedSet.Add(tx.Transaction.GetHash());
}
knownBroadcasted = knownBroadcastedSet.ToArray();
foreach(var broadcast in broadcasting)
{
if(broadcast.Item2.GetAwaiter().GetResult())
broadcasted.Add(broadcast.Item1);
}
Logs.Broadcasters.LogInformation($"Broadcasted {broadcasted.Count} transaction(s), monitoring {totalEntries} entries in {(long)(DateTimeOffset.UtcNow - startTime).TotalSeconds} seconds");
return broadcasted.ToArray();
}
private async Task<bool> TryBroadcastCoreAsync(Record tx, int currentHeight)
{
bool remove = false;
try
{
remove = currentHeight >= tx.Expiration;
//Happens when the caller does not know the previous input yet
if(tx.Transaction.Inputs.Count == 0 || tx.Transaction.Inputs[0].PrevOut.Hash == uint256.Zero)
return false;
bool isFinal = tx.Transaction.IsFinal(DateTimeOffset.UtcNow, currentHeight + 1);
if(!isFinal || IsDoubleSpend(tx.Transaction))
return false;
try
{
await _RPCBatch.WaitTransactionAsync(async batch =>
{
await batch.SendRawTransactionAsync(tx.Transaction).ConfigureAwait(false);
return true;
}).ConfigureAwait(false);
_Cache.ImportTransaction(tx.Transaction, 0);
Logs.Broadcasters.LogInformation($"Broadcasted {tx.Transaction.GetHash()}");
return true;
}
catch(RPCException ex)
{
if(ex.RPCResult == null || ex.RPCResult.Error == null)
{
return false;
}
var error = ex.RPCResult.Error.Message;
if(ex.RPCResult.Error.Code != RPCErrorCode.RPC_TRANSACTION_ALREADY_IN_CHAIN &&
!error.EndsWith("bad-txns-inputs-spent", StringComparison.OrdinalIgnoreCase) &&
!error.EndsWith("txn-mempool-conflict", StringComparison.OrdinalIgnoreCase) &&
!error.EndsWith("Missing inputs", StringComparison.OrdinalIgnoreCase))
{
remove = false;
}
}
return false;
}
finally
{
if(remove)
RemoveRecord(tx);
}
}
private bool IsDoubleSpend(Transaction tx)
{
var spentInputs = new HashSet<OutPoint>(tx.Inputs.Select(txin => txin.PrevOut));
foreach(var entry in _Cache.GetEntries())
{
if(entry.Confirmations > 0)
{
var walletTransaction = _Cache.GetTransaction(entry.TransactionId);
if(walletTransaction != null)
{
foreach(var input in walletTransaction.Inputs)
{
if(spentInputs.Contains(input.PrevOut))
{
return true;
}
}
}
}
}
return false;
}
private void RemoveRecord(Record tx)
{
Repository.Delete<Record>("Broadcasts", tx.Transaction.GetHash().ToString());
Repository.UpdateOrInsert<Transaction>("CachedTransactions", tx.Transaction.GetHash().ToString(), tx.Transaction, (a, b) => a);
}
public Task<bool> BroadcastAsync(Transaction transaction)
{
var record = new Record();
record.Transaction = transaction;
var height = _Cache.BlockCount;
//3 days expiration
record.Expiration = height + (int)(TimeSpan.FromDays(3).Ticks / Network.Main.Consensus.PowTargetSpacing.Ticks);
Repository.UpdateOrInsert<Record>("Broadcasts", transaction.GetHash().ToString(), record, (o, n) => o);
return TryBroadcastCoreAsync(record, height);
}
public Transaction GetKnownTransaction(uint256 txId)
{
return Repository.Get<Record>("Broadcasts", txId.ToString())?.Transaction ??
Repository.Get<Transaction>("CachedTransactions", txId.ToString());
}
}
}
| 27.491453 | 190 | 0.690191 | [
"MIT"
] | D3m0nKingx/NTumbleBit | NTumbleBit/Services/RPC/RPCBroadcastService.cs | 6,435 | C# |
// ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------------------------------------------------------------
namespace Microsoft.WindowsAzure.Commands.ServiceManagement.Test.FunctionalTests.IaasCmdletInfo
{
using PowershellCore;
public class GetAzureStorageAccountCmdletInfo : CmdletsInfo
{
public GetAzureStorageAccountCmdletInfo(string accountName)
{
cmdletName = Utilities.GetAzureStorageAccountCmdletName;
if (accountName != null)
{
this.cmdletParams.Add(new CmdletParam("StorageAccountName", accountName));
}
}
}
}
| 40.8125 | 96 | 0.605666 | [
"MIT"
] | Milstein/azure-sdk-tools | WindowsAzurePowershell/src/Commands.ServiceManagement.Test/FunctionalTests/IaasCmdletInfo/GetAzureStorageAccountCmdletInfo.cs | 1,275 | C# |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/datastore/v1/datastore.proto
#pragma warning disable 1591, 0612, 3021
#region Designer generated code
using pb = global::Google.Protobuf;
using pbc = global::Google.Protobuf.Collections;
using pbr = global::Google.Protobuf.Reflection;
using scg = global::System.Collections.Generic;
namespace Google.Cloud.Datastore.V1 {
/// <summary>Holder for reflection information generated from google/datastore/v1/datastore.proto</summary>
public static partial class DatastoreReflection {
#region Descriptor
/// <summary>File descriptor for google/datastore/v1/datastore.proto</summary>
public static pbr::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbr::FileDescriptor descriptor;
static DatastoreReflection() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"CiNnb29nbGUvZGF0YXN0b3JlL3YxL2RhdGFzdG9yZS5wcm90bxITZ29vZ2xl",
"LmRhdGFzdG9yZS52MRocZ29vZ2xlL2FwaS9hbm5vdGF0aW9ucy5wcm90bxog",
"Z29vZ2xlL2RhdGFzdG9yZS92MS9lbnRpdHkucHJvdG8aH2dvb2dsZS9kYXRh",
"c3RvcmUvdjEvcXVlcnkucHJvdG8igwEKDUxvb2t1cFJlcXVlc3QSEgoKcHJv",
"amVjdF9pZBgIIAEoCRI2CgxyZWFkX29wdGlvbnMYASABKAsyIC5nb29nbGUu",
"ZGF0YXN0b3JlLnYxLlJlYWRPcHRpb25zEiYKBGtleXMYAyADKAsyGC5nb29n",
"bGUuZGF0YXN0b3JlLnYxLktleSKiAQoOTG9va3VwUmVzcG9uc2USMAoFZm91",
"bmQYASADKAsyIS5nb29nbGUuZGF0YXN0b3JlLnYxLkVudGl0eVJlc3VsdBIy",
"CgdtaXNzaW5nGAIgAygLMiEuZ29vZ2xlLmRhdGFzdG9yZS52MS5FbnRpdHlS",
"ZXN1bHQSKgoIZGVmZXJyZWQYAyADKAsyGC5nb29nbGUuZGF0YXN0b3JlLnYx",
"LktleSKEAgoPUnVuUXVlcnlSZXF1ZXN0EhIKCnByb2plY3RfaWQYCCABKAkS",
"NgoMcGFydGl0aW9uX2lkGAIgASgLMiAuZ29vZ2xlLmRhdGFzdG9yZS52MS5Q",
"YXJ0aXRpb25JZBI2CgxyZWFkX29wdGlvbnMYASABKAsyIC5nb29nbGUuZGF0",
"YXN0b3JlLnYxLlJlYWRPcHRpb25zEisKBXF1ZXJ5GAMgASgLMhouZ29vZ2xl",
"LmRhdGFzdG9yZS52MS5RdWVyeUgAEjIKCWdxbF9xdWVyeRgHIAEoCzIdLmdv",
"b2dsZS5kYXRhc3RvcmUudjEuR3FsUXVlcnlIAEIMCgpxdWVyeV90eXBlInMK",
"EFJ1blF1ZXJ5UmVzcG9uc2USNAoFYmF0Y2gYASABKAsyJS5nb29nbGUuZGF0",
"YXN0b3JlLnYxLlF1ZXJ5UmVzdWx0QmF0Y2gSKQoFcXVlcnkYAiABKAsyGi5n",
"b29nbGUuZGF0YXN0b3JlLnYxLlF1ZXJ5Ii0KF0JlZ2luVHJhbnNhY3Rpb25S",
"ZXF1ZXN0EhIKCnByb2plY3RfaWQYCCABKAkiLwoYQmVnaW5UcmFuc2FjdGlv",
"blJlc3BvbnNlEhMKC3RyYW5zYWN0aW9uGAEgASgMIjoKD1JvbGxiYWNrUmVx",
"dWVzdBISCgpwcm9qZWN0X2lkGAggASgJEhMKC3RyYW5zYWN0aW9uGAEgASgM",
"IhIKEFJvbGxiYWNrUmVzcG9uc2UigwIKDUNvbW1pdFJlcXVlc3QSEgoKcHJv",
"amVjdF9pZBgIIAEoCRI1CgRtb2RlGAUgASgOMicuZ29vZ2xlLmRhdGFzdG9y",
"ZS52MS5Db21taXRSZXF1ZXN0Lk1vZGUSFQoLdHJhbnNhY3Rpb24YASABKAxI",
"ABIwCgltdXRhdGlvbnMYBiADKAsyHS5nb29nbGUuZGF0YXN0b3JlLnYxLk11",
"dGF0aW9uIkYKBE1vZGUSFAoQTU9ERV9VTlNQRUNJRklFRBAAEhEKDVRSQU5T",
"QUNUSU9OQUwQARIVChFOT05fVFJBTlNBQ1RJT05BTBACQhYKFHRyYW5zYWN0",
"aW9uX3NlbGVjdG9yImYKDkNvbW1pdFJlc3BvbnNlEj0KEG11dGF0aW9uX3Jl",
"c3VsdHMYAyADKAsyIy5nb29nbGUuZGF0YXN0b3JlLnYxLk11dGF0aW9uUmVz",
"dWx0EhUKDWluZGV4X3VwZGF0ZXMYBCABKAUiUAoSQWxsb2NhdGVJZHNSZXF1",
"ZXN0EhIKCnByb2plY3RfaWQYCCABKAkSJgoEa2V5cxgBIAMoCzIYLmdvb2ds",
"ZS5kYXRhc3RvcmUudjEuS2V5Ij0KE0FsbG9jYXRlSWRzUmVzcG9uc2USJgoE",
"a2V5cxgBIAMoCzIYLmdvb2dsZS5kYXRhc3RvcmUudjEuS2V5IocCCghNdXRh",
"dGlvbhItCgZpbnNlcnQYBCABKAsyGy5nb29nbGUuZGF0YXN0b3JlLnYxLkVu",
"dGl0eUgAEi0KBnVwZGF0ZRgFIAEoCzIbLmdvb2dsZS5kYXRhc3RvcmUudjEu",
"RW50aXR5SAASLQoGdXBzZXJ0GAYgASgLMhsuZ29vZ2xlLmRhdGFzdG9yZS52",
"MS5FbnRpdHlIABIqCgZkZWxldGUYByABKAsyGC5nb29nbGUuZGF0YXN0b3Jl",
"LnYxLktleUgAEhYKDGJhc2VfdmVyc2lvbhgIIAEoA0gBQgsKCW9wZXJhdGlv",
"bkIdChtjb25mbGljdF9kZXRlY3Rpb25fc3RyYXRlZ3kiYwoOTXV0YXRpb25S",
"ZXN1bHQSJQoDa2V5GAMgASgLMhguZ29vZ2xlLmRhdGFzdG9yZS52MS5LZXkS",
"DwoHdmVyc2lvbhgEIAEoAxIZChFjb25mbGljdF9kZXRlY3RlZBgFIAEoCCLV",
"AQoLUmVhZE9wdGlvbnMSTAoQcmVhZF9jb25zaXN0ZW5jeRgBIAEoDjIwLmdv",
"b2dsZS5kYXRhc3RvcmUudjEuUmVhZE9wdGlvbnMuUmVhZENvbnNpc3RlbmN5",
"SAASFQoLdHJhbnNhY3Rpb24YAiABKAxIACJNCg9SZWFkQ29uc2lzdGVuY3kS",
"IAocUkVBRF9DT05TSVNURU5DWV9VTlNQRUNJRklFRBAAEgoKBlNUUk9ORxAB",
"EgwKCEVWRU5UVUFMEAJCEgoQY29uc2lzdGVuY3lfdHlwZTLbBgoJRGF0YXN0",
"b3JlEn4KBkxvb2t1cBIiLmdvb2dsZS5kYXRhc3RvcmUudjEuTG9va3VwUmVx",
"dWVzdBojLmdvb2dsZS5kYXRhc3RvcmUudjEuTG9va3VwUmVzcG9uc2UiK4LT",
"5JMCJSIgL3YxL3Byb2plY3RzL3twcm9qZWN0X2lkfTpsb29rdXA6ASoShgEK",
"CFJ1blF1ZXJ5EiQuZ29vZ2xlLmRhdGFzdG9yZS52MS5SdW5RdWVyeVJlcXVl",
"c3QaJS5nb29nbGUuZGF0YXN0b3JlLnYxLlJ1blF1ZXJ5UmVzcG9uc2UiLYLT",
"5JMCJyIiL3YxL3Byb2plY3RzL3twcm9qZWN0X2lkfTpydW5RdWVyeToBKhKm",
"AQoQQmVnaW5UcmFuc2FjdGlvbhIsLmdvb2dsZS5kYXRhc3RvcmUudjEuQmVn",
"aW5UcmFuc2FjdGlvblJlcXVlc3QaLS5nb29nbGUuZGF0YXN0b3JlLnYxLkJl",
"Z2luVHJhbnNhY3Rpb25SZXNwb25zZSI1gtPkkwIvIiovdjEvcHJvamVjdHMv",
"e3Byb2plY3RfaWR9OmJlZ2luVHJhbnNhY3Rpb246ASoSfgoGQ29tbWl0EiIu",
"Z29vZ2xlLmRhdGFzdG9yZS52MS5Db21taXRSZXF1ZXN0GiMuZ29vZ2xlLmRh",
"dGFzdG9yZS52MS5Db21taXRSZXNwb25zZSIrgtPkkwIlIiAvdjEvcHJvamVj",
"dHMve3Byb2plY3RfaWR9OmNvbW1pdDoBKhKGAQoIUm9sbGJhY2sSJC5nb29n",
"bGUuZGF0YXN0b3JlLnYxLlJvbGxiYWNrUmVxdWVzdBolLmdvb2dsZS5kYXRh",
"c3RvcmUudjEuUm9sbGJhY2tSZXNwb25zZSItgtPkkwInIiIvdjEvcHJvamVj",
"dHMve3Byb2plY3RfaWR9OnJvbGxiYWNrOgEqEpIBCgtBbGxvY2F0ZUlkcxIn",
"Lmdvb2dsZS5kYXRhc3RvcmUudjEuQWxsb2NhdGVJZHNSZXF1ZXN0GiguZ29v",
"Z2xlLmRhdGFzdG9yZS52MS5BbGxvY2F0ZUlkc1Jlc3BvbnNlIjCC0+STAioi",
"JS92MS9wcm9qZWN0cy97cHJvamVjdF9pZH06YWxsb2NhdGVJZHM6ASpChQEK",
"F2NvbS5nb29nbGUuZGF0YXN0b3JlLnYxQg5EYXRhc3RvcmVQcm90b1ABWjxn",
"b29nbGUuZ29sYW5nLm9yZy9nZW5wcm90by9nb29nbGVhcGlzL2RhdGFzdG9y",
"ZS92MTtkYXRhc3RvcmWqAhlHb29nbGUuQ2xvdWQuRGF0YXN0b3JlLlYxYgZw",
"cm90bzM="));
descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
new pbr::FileDescriptor[] { global::Google.Api.AnnotationsReflection.Descriptor, global::Google.Cloud.Datastore.V1.EntityReflection.Descriptor, global::Google.Cloud.Datastore.V1.QueryReflection.Descriptor, },
new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] {
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.Datastore.V1.LookupRequest), global::Google.Cloud.Datastore.V1.LookupRequest.Parser, new[]{ "ProjectId", "ReadOptions", "Keys" }, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.Datastore.V1.LookupResponse), global::Google.Cloud.Datastore.V1.LookupResponse.Parser, new[]{ "Found", "Missing", "Deferred" }, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.Datastore.V1.RunQueryRequest), global::Google.Cloud.Datastore.V1.RunQueryRequest.Parser, new[]{ "ProjectId", "PartitionId", "ReadOptions", "Query", "GqlQuery" }, new[]{ "QueryType" }, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.Datastore.V1.RunQueryResponse), global::Google.Cloud.Datastore.V1.RunQueryResponse.Parser, new[]{ "Batch", "Query" }, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.Datastore.V1.BeginTransactionRequest), global::Google.Cloud.Datastore.V1.BeginTransactionRequest.Parser, new[]{ "ProjectId" }, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.Datastore.V1.BeginTransactionResponse), global::Google.Cloud.Datastore.V1.BeginTransactionResponse.Parser, new[]{ "Transaction" }, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.Datastore.V1.RollbackRequest), global::Google.Cloud.Datastore.V1.RollbackRequest.Parser, new[]{ "ProjectId", "Transaction" }, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.Datastore.V1.RollbackResponse), global::Google.Cloud.Datastore.V1.RollbackResponse.Parser, null, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.Datastore.V1.CommitRequest), global::Google.Cloud.Datastore.V1.CommitRequest.Parser, new[]{ "ProjectId", "Mode", "Transaction", "Mutations" }, new[]{ "TransactionSelector" }, new[]{ typeof(global::Google.Cloud.Datastore.V1.CommitRequest.Types.Mode) }, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.Datastore.V1.CommitResponse), global::Google.Cloud.Datastore.V1.CommitResponse.Parser, new[]{ "MutationResults", "IndexUpdates" }, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.Datastore.V1.AllocateIdsRequest), global::Google.Cloud.Datastore.V1.AllocateIdsRequest.Parser, new[]{ "ProjectId", "Keys" }, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.Datastore.V1.AllocateIdsResponse), global::Google.Cloud.Datastore.V1.AllocateIdsResponse.Parser, new[]{ "Keys" }, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.Datastore.V1.Mutation), global::Google.Cloud.Datastore.V1.Mutation.Parser, new[]{ "Insert", "Update", "Upsert", "Delete", "BaseVersion" }, new[]{ "Operation", "ConflictDetectionStrategy" }, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.Datastore.V1.MutationResult), global::Google.Cloud.Datastore.V1.MutationResult.Parser, new[]{ "Key", "Version", "ConflictDetected" }, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.Datastore.V1.ReadOptions), global::Google.Cloud.Datastore.V1.ReadOptions.Parser, new[]{ "ReadConsistency", "Transaction" }, new[]{ "ConsistencyType" }, new[]{ typeof(global::Google.Cloud.Datastore.V1.ReadOptions.Types.ReadConsistency) }, null)
}));
}
#endregion
}
#region Messages
/// <summary>
/// The request for [Datastore.Lookup][google.datastore.v1.Datastore.Lookup].
/// </summary>
public sealed partial class LookupRequest : pb::IMessage<LookupRequest> {
private static readonly pb::MessageParser<LookupRequest> _parser = new pb::MessageParser<LookupRequest>(() => new LookupRequest());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<LookupRequest> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Cloud.Datastore.V1.DatastoreReflection.Descriptor.MessageTypes[0]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public LookupRequest() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public LookupRequest(LookupRequest other) : this() {
projectId_ = other.projectId_;
ReadOptions = other.readOptions_ != null ? other.ReadOptions.Clone() : null;
keys_ = other.keys_.Clone();
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public LookupRequest Clone() {
return new LookupRequest(this);
}
/// <summary>Field number for the "project_id" field.</summary>
public const int ProjectIdFieldNumber = 8;
private string projectId_ = "";
/// <summary>
/// The ID of the project against which to make the request.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string ProjectId {
get { return projectId_; }
set {
projectId_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "read_options" field.</summary>
public const int ReadOptionsFieldNumber = 1;
private global::Google.Cloud.Datastore.V1.ReadOptions readOptions_;
/// <summary>
/// The options for this lookup request.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::Google.Cloud.Datastore.V1.ReadOptions ReadOptions {
get { return readOptions_; }
set {
readOptions_ = value;
}
}
/// <summary>Field number for the "keys" field.</summary>
public const int KeysFieldNumber = 3;
private static readonly pb::FieldCodec<global::Google.Cloud.Datastore.V1.Key> _repeated_keys_codec
= pb::FieldCodec.ForMessage(26, global::Google.Cloud.Datastore.V1.Key.Parser);
private readonly pbc::RepeatedField<global::Google.Cloud.Datastore.V1.Key> keys_ = new pbc::RepeatedField<global::Google.Cloud.Datastore.V1.Key>();
/// <summary>
/// Keys of entities to look up.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public pbc::RepeatedField<global::Google.Cloud.Datastore.V1.Key> Keys {
get { return keys_; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as LookupRequest);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(LookupRequest other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (ProjectId != other.ProjectId) return false;
if (!object.Equals(ReadOptions, other.ReadOptions)) return false;
if(!keys_.Equals(other.keys_)) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (ProjectId.Length != 0) hash ^= ProjectId.GetHashCode();
if (readOptions_ != null) hash ^= ReadOptions.GetHashCode();
hash ^= keys_.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (readOptions_ != null) {
output.WriteRawTag(10);
output.WriteMessage(ReadOptions);
}
keys_.WriteTo(output, _repeated_keys_codec);
if (ProjectId.Length != 0) {
output.WriteRawTag(66);
output.WriteString(ProjectId);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (ProjectId.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(ProjectId);
}
if (readOptions_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(ReadOptions);
}
size += keys_.CalculateSize(_repeated_keys_codec);
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(LookupRequest other) {
if (other == null) {
return;
}
if (other.ProjectId.Length != 0) {
ProjectId = other.ProjectId;
}
if (other.readOptions_ != null) {
if (readOptions_ == null) {
readOptions_ = new global::Google.Cloud.Datastore.V1.ReadOptions();
}
ReadOptions.MergeFrom(other.ReadOptions);
}
keys_.Add(other.keys_);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 10: {
if (readOptions_ == null) {
readOptions_ = new global::Google.Cloud.Datastore.V1.ReadOptions();
}
input.ReadMessage(readOptions_);
break;
}
case 26: {
keys_.AddEntriesFrom(input, _repeated_keys_codec);
break;
}
case 66: {
ProjectId = input.ReadString();
break;
}
}
}
}
}
/// <summary>
/// The response for [Datastore.Lookup][google.datastore.v1.Datastore.Lookup].
/// </summary>
public sealed partial class LookupResponse : pb::IMessage<LookupResponse> {
private static readonly pb::MessageParser<LookupResponse> _parser = new pb::MessageParser<LookupResponse>(() => new LookupResponse());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<LookupResponse> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Cloud.Datastore.V1.DatastoreReflection.Descriptor.MessageTypes[1]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public LookupResponse() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public LookupResponse(LookupResponse other) : this() {
found_ = other.found_.Clone();
missing_ = other.missing_.Clone();
deferred_ = other.deferred_.Clone();
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public LookupResponse Clone() {
return new LookupResponse(this);
}
/// <summary>Field number for the "found" field.</summary>
public const int FoundFieldNumber = 1;
private static readonly pb::FieldCodec<global::Google.Cloud.Datastore.V1.EntityResult> _repeated_found_codec
= pb::FieldCodec.ForMessage(10, global::Google.Cloud.Datastore.V1.EntityResult.Parser);
private readonly pbc::RepeatedField<global::Google.Cloud.Datastore.V1.EntityResult> found_ = new pbc::RepeatedField<global::Google.Cloud.Datastore.V1.EntityResult>();
/// <summary>
/// Entities found as `ResultType.FULL` entities. The order of results in this
/// field is undefined and has no relation to the order of the keys in the
/// input.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public pbc::RepeatedField<global::Google.Cloud.Datastore.V1.EntityResult> Found {
get { return found_; }
}
/// <summary>Field number for the "missing" field.</summary>
public const int MissingFieldNumber = 2;
private static readonly pb::FieldCodec<global::Google.Cloud.Datastore.V1.EntityResult> _repeated_missing_codec
= pb::FieldCodec.ForMessage(18, global::Google.Cloud.Datastore.V1.EntityResult.Parser);
private readonly pbc::RepeatedField<global::Google.Cloud.Datastore.V1.EntityResult> missing_ = new pbc::RepeatedField<global::Google.Cloud.Datastore.V1.EntityResult>();
/// <summary>
/// Entities not found as `ResultType.KEY_ONLY` entities. The order of results
/// in this field is undefined and has no relation to the order of the keys
/// in the input.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public pbc::RepeatedField<global::Google.Cloud.Datastore.V1.EntityResult> Missing {
get { return missing_; }
}
/// <summary>Field number for the "deferred" field.</summary>
public const int DeferredFieldNumber = 3;
private static readonly pb::FieldCodec<global::Google.Cloud.Datastore.V1.Key> _repeated_deferred_codec
= pb::FieldCodec.ForMessage(26, global::Google.Cloud.Datastore.V1.Key.Parser);
private readonly pbc::RepeatedField<global::Google.Cloud.Datastore.V1.Key> deferred_ = new pbc::RepeatedField<global::Google.Cloud.Datastore.V1.Key>();
/// <summary>
/// A list of keys that were not looked up due to resource constraints. The
/// order of results in this field is undefined and has no relation to the
/// order of the keys in the input.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public pbc::RepeatedField<global::Google.Cloud.Datastore.V1.Key> Deferred {
get { return deferred_; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as LookupResponse);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(LookupResponse other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if(!found_.Equals(other.found_)) return false;
if(!missing_.Equals(other.missing_)) return false;
if(!deferred_.Equals(other.deferred_)) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
hash ^= found_.GetHashCode();
hash ^= missing_.GetHashCode();
hash ^= deferred_.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
found_.WriteTo(output, _repeated_found_codec);
missing_.WriteTo(output, _repeated_missing_codec);
deferred_.WriteTo(output, _repeated_deferred_codec);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
size += found_.CalculateSize(_repeated_found_codec);
size += missing_.CalculateSize(_repeated_missing_codec);
size += deferred_.CalculateSize(_repeated_deferred_codec);
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(LookupResponse other) {
if (other == null) {
return;
}
found_.Add(other.found_);
missing_.Add(other.missing_);
deferred_.Add(other.deferred_);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 10: {
found_.AddEntriesFrom(input, _repeated_found_codec);
break;
}
case 18: {
missing_.AddEntriesFrom(input, _repeated_missing_codec);
break;
}
case 26: {
deferred_.AddEntriesFrom(input, _repeated_deferred_codec);
break;
}
}
}
}
}
/// <summary>
/// The request for [Datastore.RunQuery][google.datastore.v1.Datastore.RunQuery].
/// </summary>
public sealed partial class RunQueryRequest : pb::IMessage<RunQueryRequest> {
private static readonly pb::MessageParser<RunQueryRequest> _parser = new pb::MessageParser<RunQueryRequest>(() => new RunQueryRequest());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<RunQueryRequest> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Cloud.Datastore.V1.DatastoreReflection.Descriptor.MessageTypes[2]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public RunQueryRequest() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public RunQueryRequest(RunQueryRequest other) : this() {
projectId_ = other.projectId_;
PartitionId = other.partitionId_ != null ? other.PartitionId.Clone() : null;
ReadOptions = other.readOptions_ != null ? other.ReadOptions.Clone() : null;
switch (other.QueryTypeCase) {
case QueryTypeOneofCase.Query:
Query = other.Query.Clone();
break;
case QueryTypeOneofCase.GqlQuery:
GqlQuery = other.GqlQuery.Clone();
break;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public RunQueryRequest Clone() {
return new RunQueryRequest(this);
}
/// <summary>Field number for the "project_id" field.</summary>
public const int ProjectIdFieldNumber = 8;
private string projectId_ = "";
/// <summary>
/// The ID of the project against which to make the request.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string ProjectId {
get { return projectId_; }
set {
projectId_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "partition_id" field.</summary>
public const int PartitionIdFieldNumber = 2;
private global::Google.Cloud.Datastore.V1.PartitionId partitionId_;
/// <summary>
/// Entities are partitioned into subsets, identified by a partition ID.
/// Queries are scoped to a single partition.
/// This partition ID is normalized with the standard default context
/// partition ID.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::Google.Cloud.Datastore.V1.PartitionId PartitionId {
get { return partitionId_; }
set {
partitionId_ = value;
}
}
/// <summary>Field number for the "read_options" field.</summary>
public const int ReadOptionsFieldNumber = 1;
private global::Google.Cloud.Datastore.V1.ReadOptions readOptions_;
/// <summary>
/// The options for this query.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::Google.Cloud.Datastore.V1.ReadOptions ReadOptions {
get { return readOptions_; }
set {
readOptions_ = value;
}
}
/// <summary>Field number for the "query" field.</summary>
public const int QueryFieldNumber = 3;
/// <summary>
/// The query to run.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::Google.Cloud.Datastore.V1.Query Query {
get { return queryTypeCase_ == QueryTypeOneofCase.Query ? (global::Google.Cloud.Datastore.V1.Query) queryType_ : null; }
set {
queryType_ = value;
queryTypeCase_ = value == null ? QueryTypeOneofCase.None : QueryTypeOneofCase.Query;
}
}
/// <summary>Field number for the "gql_query" field.</summary>
public const int GqlQueryFieldNumber = 7;
/// <summary>
/// The GQL query to run.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::Google.Cloud.Datastore.V1.GqlQuery GqlQuery {
get { return queryTypeCase_ == QueryTypeOneofCase.GqlQuery ? (global::Google.Cloud.Datastore.V1.GqlQuery) queryType_ : null; }
set {
queryType_ = value;
queryTypeCase_ = value == null ? QueryTypeOneofCase.None : QueryTypeOneofCase.GqlQuery;
}
}
private object queryType_;
/// <summary>Enum of possible cases for the "query_type" oneof.</summary>
public enum QueryTypeOneofCase {
None = 0,
Query = 3,
GqlQuery = 7,
}
private QueryTypeOneofCase queryTypeCase_ = QueryTypeOneofCase.None;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public QueryTypeOneofCase QueryTypeCase {
get { return queryTypeCase_; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void ClearQueryType() {
queryTypeCase_ = QueryTypeOneofCase.None;
queryType_ = null;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as RunQueryRequest);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(RunQueryRequest other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (ProjectId != other.ProjectId) return false;
if (!object.Equals(PartitionId, other.PartitionId)) return false;
if (!object.Equals(ReadOptions, other.ReadOptions)) return false;
if (!object.Equals(Query, other.Query)) return false;
if (!object.Equals(GqlQuery, other.GqlQuery)) return false;
if (QueryTypeCase != other.QueryTypeCase) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (ProjectId.Length != 0) hash ^= ProjectId.GetHashCode();
if (partitionId_ != null) hash ^= PartitionId.GetHashCode();
if (readOptions_ != null) hash ^= ReadOptions.GetHashCode();
if (queryTypeCase_ == QueryTypeOneofCase.Query) hash ^= Query.GetHashCode();
if (queryTypeCase_ == QueryTypeOneofCase.GqlQuery) hash ^= GqlQuery.GetHashCode();
hash ^= (int) queryTypeCase_;
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (readOptions_ != null) {
output.WriteRawTag(10);
output.WriteMessage(ReadOptions);
}
if (partitionId_ != null) {
output.WriteRawTag(18);
output.WriteMessage(PartitionId);
}
if (queryTypeCase_ == QueryTypeOneofCase.Query) {
output.WriteRawTag(26);
output.WriteMessage(Query);
}
if (queryTypeCase_ == QueryTypeOneofCase.GqlQuery) {
output.WriteRawTag(58);
output.WriteMessage(GqlQuery);
}
if (ProjectId.Length != 0) {
output.WriteRawTag(66);
output.WriteString(ProjectId);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (ProjectId.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(ProjectId);
}
if (partitionId_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(PartitionId);
}
if (readOptions_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(ReadOptions);
}
if (queryTypeCase_ == QueryTypeOneofCase.Query) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(Query);
}
if (queryTypeCase_ == QueryTypeOneofCase.GqlQuery) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(GqlQuery);
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(RunQueryRequest other) {
if (other == null) {
return;
}
if (other.ProjectId.Length != 0) {
ProjectId = other.ProjectId;
}
if (other.partitionId_ != null) {
if (partitionId_ == null) {
partitionId_ = new global::Google.Cloud.Datastore.V1.PartitionId();
}
PartitionId.MergeFrom(other.PartitionId);
}
if (other.readOptions_ != null) {
if (readOptions_ == null) {
readOptions_ = new global::Google.Cloud.Datastore.V1.ReadOptions();
}
ReadOptions.MergeFrom(other.ReadOptions);
}
switch (other.QueryTypeCase) {
case QueryTypeOneofCase.Query:
Query = other.Query;
break;
case QueryTypeOneofCase.GqlQuery:
GqlQuery = other.GqlQuery;
break;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 10: {
if (readOptions_ == null) {
readOptions_ = new global::Google.Cloud.Datastore.V1.ReadOptions();
}
input.ReadMessage(readOptions_);
break;
}
case 18: {
if (partitionId_ == null) {
partitionId_ = new global::Google.Cloud.Datastore.V1.PartitionId();
}
input.ReadMessage(partitionId_);
break;
}
case 26: {
global::Google.Cloud.Datastore.V1.Query subBuilder = new global::Google.Cloud.Datastore.V1.Query();
if (queryTypeCase_ == QueryTypeOneofCase.Query) {
subBuilder.MergeFrom(Query);
}
input.ReadMessage(subBuilder);
Query = subBuilder;
break;
}
case 58: {
global::Google.Cloud.Datastore.V1.GqlQuery subBuilder = new global::Google.Cloud.Datastore.V1.GqlQuery();
if (queryTypeCase_ == QueryTypeOneofCase.GqlQuery) {
subBuilder.MergeFrom(GqlQuery);
}
input.ReadMessage(subBuilder);
GqlQuery = subBuilder;
break;
}
case 66: {
ProjectId = input.ReadString();
break;
}
}
}
}
}
/// <summary>
/// The response for [Datastore.RunQuery][google.datastore.v1.Datastore.RunQuery].
/// </summary>
public sealed partial class RunQueryResponse : pb::IMessage<RunQueryResponse> {
private static readonly pb::MessageParser<RunQueryResponse> _parser = new pb::MessageParser<RunQueryResponse>(() => new RunQueryResponse());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<RunQueryResponse> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Cloud.Datastore.V1.DatastoreReflection.Descriptor.MessageTypes[3]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public RunQueryResponse() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public RunQueryResponse(RunQueryResponse other) : this() {
Batch = other.batch_ != null ? other.Batch.Clone() : null;
Query = other.query_ != null ? other.Query.Clone() : null;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public RunQueryResponse Clone() {
return new RunQueryResponse(this);
}
/// <summary>Field number for the "batch" field.</summary>
public const int BatchFieldNumber = 1;
private global::Google.Cloud.Datastore.V1.QueryResultBatch batch_;
/// <summary>
/// A batch of query results (always present).
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::Google.Cloud.Datastore.V1.QueryResultBatch Batch {
get { return batch_; }
set {
batch_ = value;
}
}
/// <summary>Field number for the "query" field.</summary>
public const int QueryFieldNumber = 2;
private global::Google.Cloud.Datastore.V1.Query query_;
/// <summary>
/// The parsed form of the `GqlQuery` from the request, if it was set.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::Google.Cloud.Datastore.V1.Query Query {
get { return query_; }
set {
query_ = value;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as RunQueryResponse);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(RunQueryResponse other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (!object.Equals(Batch, other.Batch)) return false;
if (!object.Equals(Query, other.Query)) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (batch_ != null) hash ^= Batch.GetHashCode();
if (query_ != null) hash ^= Query.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (batch_ != null) {
output.WriteRawTag(10);
output.WriteMessage(Batch);
}
if (query_ != null) {
output.WriteRawTag(18);
output.WriteMessage(Query);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (batch_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(Batch);
}
if (query_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(Query);
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(RunQueryResponse other) {
if (other == null) {
return;
}
if (other.batch_ != null) {
if (batch_ == null) {
batch_ = new global::Google.Cloud.Datastore.V1.QueryResultBatch();
}
Batch.MergeFrom(other.Batch);
}
if (other.query_ != null) {
if (query_ == null) {
query_ = new global::Google.Cloud.Datastore.V1.Query();
}
Query.MergeFrom(other.Query);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 10: {
if (batch_ == null) {
batch_ = new global::Google.Cloud.Datastore.V1.QueryResultBatch();
}
input.ReadMessage(batch_);
break;
}
case 18: {
if (query_ == null) {
query_ = new global::Google.Cloud.Datastore.V1.Query();
}
input.ReadMessage(query_);
break;
}
}
}
}
}
/// <summary>
/// The request for [Datastore.BeginTransaction][google.datastore.v1.Datastore.BeginTransaction].
/// </summary>
public sealed partial class BeginTransactionRequest : pb::IMessage<BeginTransactionRequest> {
private static readonly pb::MessageParser<BeginTransactionRequest> _parser = new pb::MessageParser<BeginTransactionRequest>(() => new BeginTransactionRequest());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<BeginTransactionRequest> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Cloud.Datastore.V1.DatastoreReflection.Descriptor.MessageTypes[4]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public BeginTransactionRequest() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public BeginTransactionRequest(BeginTransactionRequest other) : this() {
projectId_ = other.projectId_;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public BeginTransactionRequest Clone() {
return new BeginTransactionRequest(this);
}
/// <summary>Field number for the "project_id" field.</summary>
public const int ProjectIdFieldNumber = 8;
private string projectId_ = "";
/// <summary>
/// The ID of the project against which to make the request.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string ProjectId {
get { return projectId_; }
set {
projectId_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as BeginTransactionRequest);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(BeginTransactionRequest other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (ProjectId != other.ProjectId) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (ProjectId.Length != 0) hash ^= ProjectId.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (ProjectId.Length != 0) {
output.WriteRawTag(66);
output.WriteString(ProjectId);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (ProjectId.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(ProjectId);
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(BeginTransactionRequest other) {
if (other == null) {
return;
}
if (other.ProjectId.Length != 0) {
ProjectId = other.ProjectId;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 66: {
ProjectId = input.ReadString();
break;
}
}
}
}
}
/// <summary>
/// The response for [Datastore.BeginTransaction][google.datastore.v1.Datastore.BeginTransaction].
/// </summary>
public sealed partial class BeginTransactionResponse : pb::IMessage<BeginTransactionResponse> {
private static readonly pb::MessageParser<BeginTransactionResponse> _parser = new pb::MessageParser<BeginTransactionResponse>(() => new BeginTransactionResponse());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<BeginTransactionResponse> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Cloud.Datastore.V1.DatastoreReflection.Descriptor.MessageTypes[5]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public BeginTransactionResponse() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public BeginTransactionResponse(BeginTransactionResponse other) : this() {
transaction_ = other.transaction_;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public BeginTransactionResponse Clone() {
return new BeginTransactionResponse(this);
}
/// <summary>Field number for the "transaction" field.</summary>
public const int TransactionFieldNumber = 1;
private pb::ByteString transaction_ = pb::ByteString.Empty;
/// <summary>
/// The transaction identifier (always present).
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public pb::ByteString Transaction {
get { return transaction_; }
set {
transaction_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as BeginTransactionResponse);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(BeginTransactionResponse other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (Transaction != other.Transaction) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (Transaction.Length != 0) hash ^= Transaction.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (Transaction.Length != 0) {
output.WriteRawTag(10);
output.WriteBytes(Transaction);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (Transaction.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeBytesSize(Transaction);
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(BeginTransactionResponse other) {
if (other == null) {
return;
}
if (other.Transaction.Length != 0) {
Transaction = other.Transaction;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 10: {
Transaction = input.ReadBytes();
break;
}
}
}
}
}
/// <summary>
/// The request for [Datastore.Rollback][google.datastore.v1.Datastore.Rollback].
/// </summary>
public sealed partial class RollbackRequest : pb::IMessage<RollbackRequest> {
private static readonly pb::MessageParser<RollbackRequest> _parser = new pb::MessageParser<RollbackRequest>(() => new RollbackRequest());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<RollbackRequest> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Cloud.Datastore.V1.DatastoreReflection.Descriptor.MessageTypes[6]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public RollbackRequest() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public RollbackRequest(RollbackRequest other) : this() {
projectId_ = other.projectId_;
transaction_ = other.transaction_;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public RollbackRequest Clone() {
return new RollbackRequest(this);
}
/// <summary>Field number for the "project_id" field.</summary>
public const int ProjectIdFieldNumber = 8;
private string projectId_ = "";
/// <summary>
/// The ID of the project against which to make the request.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string ProjectId {
get { return projectId_; }
set {
projectId_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "transaction" field.</summary>
public const int TransactionFieldNumber = 1;
private pb::ByteString transaction_ = pb::ByteString.Empty;
/// <summary>
/// The transaction identifier, returned by a call to
/// [Datastore.BeginTransaction][google.datastore.v1.Datastore.BeginTransaction].
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public pb::ByteString Transaction {
get { return transaction_; }
set {
transaction_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as RollbackRequest);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(RollbackRequest other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (ProjectId != other.ProjectId) return false;
if (Transaction != other.Transaction) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (ProjectId.Length != 0) hash ^= ProjectId.GetHashCode();
if (Transaction.Length != 0) hash ^= Transaction.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (Transaction.Length != 0) {
output.WriteRawTag(10);
output.WriteBytes(Transaction);
}
if (ProjectId.Length != 0) {
output.WriteRawTag(66);
output.WriteString(ProjectId);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (ProjectId.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(ProjectId);
}
if (Transaction.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeBytesSize(Transaction);
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(RollbackRequest other) {
if (other == null) {
return;
}
if (other.ProjectId.Length != 0) {
ProjectId = other.ProjectId;
}
if (other.Transaction.Length != 0) {
Transaction = other.Transaction;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 10: {
Transaction = input.ReadBytes();
break;
}
case 66: {
ProjectId = input.ReadString();
break;
}
}
}
}
}
/// <summary>
/// The response for [Datastore.Rollback][google.datastore.v1.Datastore.Rollback].
/// (an empty message).
/// </summary>
public sealed partial class RollbackResponse : pb::IMessage<RollbackResponse> {
private static readonly pb::MessageParser<RollbackResponse> _parser = new pb::MessageParser<RollbackResponse>(() => new RollbackResponse());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<RollbackResponse> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Cloud.Datastore.V1.DatastoreReflection.Descriptor.MessageTypes[7]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public RollbackResponse() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public RollbackResponse(RollbackResponse other) : this() {
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public RollbackResponse Clone() {
return new RollbackResponse(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as RollbackResponse);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(RollbackResponse other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(RollbackResponse other) {
if (other == null) {
return;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
}
}
}
}
/// <summary>
/// The request for [Datastore.Commit][google.datastore.v1.Datastore.Commit].
/// </summary>
public sealed partial class CommitRequest : pb::IMessage<CommitRequest> {
private static readonly pb::MessageParser<CommitRequest> _parser = new pb::MessageParser<CommitRequest>(() => new CommitRequest());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<CommitRequest> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Cloud.Datastore.V1.DatastoreReflection.Descriptor.MessageTypes[8]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public CommitRequest() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public CommitRequest(CommitRequest other) : this() {
projectId_ = other.projectId_;
mode_ = other.mode_;
mutations_ = other.mutations_.Clone();
switch (other.TransactionSelectorCase) {
case TransactionSelectorOneofCase.Transaction:
Transaction = other.Transaction;
break;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public CommitRequest Clone() {
return new CommitRequest(this);
}
/// <summary>Field number for the "project_id" field.</summary>
public const int ProjectIdFieldNumber = 8;
private string projectId_ = "";
/// <summary>
/// The ID of the project against which to make the request.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string ProjectId {
get { return projectId_; }
set {
projectId_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "mode" field.</summary>
public const int ModeFieldNumber = 5;
private global::Google.Cloud.Datastore.V1.CommitRequest.Types.Mode mode_ = 0;
/// <summary>
/// The type of commit to perform. Defaults to `TRANSACTIONAL`.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::Google.Cloud.Datastore.V1.CommitRequest.Types.Mode Mode {
get { return mode_; }
set {
mode_ = value;
}
}
/// <summary>Field number for the "transaction" field.</summary>
public const int TransactionFieldNumber = 1;
/// <summary>
/// The identifier of the transaction associated with the commit. A
/// transaction identifier is returned by a call to
/// [Datastore.BeginTransaction][google.datastore.v1.Datastore.BeginTransaction].
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public pb::ByteString Transaction {
get { return transactionSelectorCase_ == TransactionSelectorOneofCase.Transaction ? (pb::ByteString) transactionSelector_ : pb::ByteString.Empty; }
set {
transactionSelector_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
transactionSelectorCase_ = TransactionSelectorOneofCase.Transaction;
}
}
/// <summary>Field number for the "mutations" field.</summary>
public const int MutationsFieldNumber = 6;
private static readonly pb::FieldCodec<global::Google.Cloud.Datastore.V1.Mutation> _repeated_mutations_codec
= pb::FieldCodec.ForMessage(50, global::Google.Cloud.Datastore.V1.Mutation.Parser);
private readonly pbc::RepeatedField<global::Google.Cloud.Datastore.V1.Mutation> mutations_ = new pbc::RepeatedField<global::Google.Cloud.Datastore.V1.Mutation>();
/// <summary>
/// The mutations to perform.
///
/// When mode is `TRANSACTIONAL`, mutations affecting a single entity are
/// applied in order. The following sequences of mutations affecting a single
/// entity are not permitted in a single `Commit` request:
///
/// - `insert` followed by `insert`
/// - `update` followed by `insert`
/// - `upsert` followed by `insert`
/// - `delete` followed by `update`
///
/// When mode is `NON_TRANSACTIONAL`, no two mutations may affect a single
/// entity.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public pbc::RepeatedField<global::Google.Cloud.Datastore.V1.Mutation> Mutations {
get { return mutations_; }
}
private object transactionSelector_;
/// <summary>Enum of possible cases for the "transaction_selector" oneof.</summary>
public enum TransactionSelectorOneofCase {
None = 0,
Transaction = 1,
}
private TransactionSelectorOneofCase transactionSelectorCase_ = TransactionSelectorOneofCase.None;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public TransactionSelectorOneofCase TransactionSelectorCase {
get { return transactionSelectorCase_; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void ClearTransactionSelector() {
transactionSelectorCase_ = TransactionSelectorOneofCase.None;
transactionSelector_ = null;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as CommitRequest);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(CommitRequest other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (ProjectId != other.ProjectId) return false;
if (Mode != other.Mode) return false;
if (Transaction != other.Transaction) return false;
if(!mutations_.Equals(other.mutations_)) return false;
if (TransactionSelectorCase != other.TransactionSelectorCase) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (ProjectId.Length != 0) hash ^= ProjectId.GetHashCode();
if (Mode != 0) hash ^= Mode.GetHashCode();
if (transactionSelectorCase_ == TransactionSelectorOneofCase.Transaction) hash ^= Transaction.GetHashCode();
hash ^= mutations_.GetHashCode();
hash ^= (int) transactionSelectorCase_;
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (transactionSelectorCase_ == TransactionSelectorOneofCase.Transaction) {
output.WriteRawTag(10);
output.WriteBytes(Transaction);
}
if (Mode != 0) {
output.WriteRawTag(40);
output.WriteEnum((int) Mode);
}
mutations_.WriteTo(output, _repeated_mutations_codec);
if (ProjectId.Length != 0) {
output.WriteRawTag(66);
output.WriteString(ProjectId);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (ProjectId.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(ProjectId);
}
if (Mode != 0) {
size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) Mode);
}
if (transactionSelectorCase_ == TransactionSelectorOneofCase.Transaction) {
size += 1 + pb::CodedOutputStream.ComputeBytesSize(Transaction);
}
size += mutations_.CalculateSize(_repeated_mutations_codec);
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(CommitRequest other) {
if (other == null) {
return;
}
if (other.ProjectId.Length != 0) {
ProjectId = other.ProjectId;
}
if (other.Mode != 0) {
Mode = other.Mode;
}
mutations_.Add(other.mutations_);
switch (other.TransactionSelectorCase) {
case TransactionSelectorOneofCase.Transaction:
Transaction = other.Transaction;
break;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 10: {
Transaction = input.ReadBytes();
break;
}
case 40: {
mode_ = (global::Google.Cloud.Datastore.V1.CommitRequest.Types.Mode) input.ReadEnum();
break;
}
case 50: {
mutations_.AddEntriesFrom(input, _repeated_mutations_codec);
break;
}
case 66: {
ProjectId = input.ReadString();
break;
}
}
}
}
#region Nested types
/// <summary>Container for nested types declared in the CommitRequest message type.</summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static partial class Types {
/// <summary>
/// The modes available for commits.
/// </summary>
public enum Mode {
/// <summary>
/// Unspecified. This value must not be used.
/// </summary>
[pbr::OriginalName("MODE_UNSPECIFIED")] Unspecified = 0,
/// <summary>
/// Transactional: The mutations are either all applied, or none are applied.
/// Learn about transactions [here](https://cloud.google.com/datastore/docs/concepts/transactions).
/// </summary>
[pbr::OriginalName("TRANSACTIONAL")] Transactional = 1,
/// <summary>
/// Non-transactional: The mutations may not apply as all or none.
/// </summary>
[pbr::OriginalName("NON_TRANSACTIONAL")] NonTransactional = 2,
}
}
#endregion
}
/// <summary>
/// The response for [Datastore.Commit][google.datastore.v1.Datastore.Commit].
/// </summary>
public sealed partial class CommitResponse : pb::IMessage<CommitResponse> {
private static readonly pb::MessageParser<CommitResponse> _parser = new pb::MessageParser<CommitResponse>(() => new CommitResponse());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<CommitResponse> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Cloud.Datastore.V1.DatastoreReflection.Descriptor.MessageTypes[9]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public CommitResponse() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public CommitResponse(CommitResponse other) : this() {
mutationResults_ = other.mutationResults_.Clone();
indexUpdates_ = other.indexUpdates_;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public CommitResponse Clone() {
return new CommitResponse(this);
}
/// <summary>Field number for the "mutation_results" field.</summary>
public const int MutationResultsFieldNumber = 3;
private static readonly pb::FieldCodec<global::Google.Cloud.Datastore.V1.MutationResult> _repeated_mutationResults_codec
= pb::FieldCodec.ForMessage(26, global::Google.Cloud.Datastore.V1.MutationResult.Parser);
private readonly pbc::RepeatedField<global::Google.Cloud.Datastore.V1.MutationResult> mutationResults_ = new pbc::RepeatedField<global::Google.Cloud.Datastore.V1.MutationResult>();
/// <summary>
/// The result of performing the mutations.
/// The i-th mutation result corresponds to the i-th mutation in the request.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public pbc::RepeatedField<global::Google.Cloud.Datastore.V1.MutationResult> MutationResults {
get { return mutationResults_; }
}
/// <summary>Field number for the "index_updates" field.</summary>
public const int IndexUpdatesFieldNumber = 4;
private int indexUpdates_;
/// <summary>
/// The number of index entries updated during the commit, or zero if none were
/// updated.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int IndexUpdates {
get { return indexUpdates_; }
set {
indexUpdates_ = value;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as CommitResponse);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(CommitResponse other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if(!mutationResults_.Equals(other.mutationResults_)) return false;
if (IndexUpdates != other.IndexUpdates) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
hash ^= mutationResults_.GetHashCode();
if (IndexUpdates != 0) hash ^= IndexUpdates.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
mutationResults_.WriteTo(output, _repeated_mutationResults_codec);
if (IndexUpdates != 0) {
output.WriteRawTag(32);
output.WriteInt32(IndexUpdates);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
size += mutationResults_.CalculateSize(_repeated_mutationResults_codec);
if (IndexUpdates != 0) {
size += 1 + pb::CodedOutputStream.ComputeInt32Size(IndexUpdates);
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(CommitResponse other) {
if (other == null) {
return;
}
mutationResults_.Add(other.mutationResults_);
if (other.IndexUpdates != 0) {
IndexUpdates = other.IndexUpdates;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 26: {
mutationResults_.AddEntriesFrom(input, _repeated_mutationResults_codec);
break;
}
case 32: {
IndexUpdates = input.ReadInt32();
break;
}
}
}
}
}
/// <summary>
/// The request for [Datastore.AllocateIds][google.datastore.v1.Datastore.AllocateIds].
/// </summary>
public sealed partial class AllocateIdsRequest : pb::IMessage<AllocateIdsRequest> {
private static readonly pb::MessageParser<AllocateIdsRequest> _parser = new pb::MessageParser<AllocateIdsRequest>(() => new AllocateIdsRequest());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<AllocateIdsRequest> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Cloud.Datastore.V1.DatastoreReflection.Descriptor.MessageTypes[10]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public AllocateIdsRequest() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public AllocateIdsRequest(AllocateIdsRequest other) : this() {
projectId_ = other.projectId_;
keys_ = other.keys_.Clone();
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public AllocateIdsRequest Clone() {
return new AllocateIdsRequest(this);
}
/// <summary>Field number for the "project_id" field.</summary>
public const int ProjectIdFieldNumber = 8;
private string projectId_ = "";
/// <summary>
/// The ID of the project against which to make the request.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string ProjectId {
get { return projectId_; }
set {
projectId_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "keys" field.</summary>
public const int KeysFieldNumber = 1;
private static readonly pb::FieldCodec<global::Google.Cloud.Datastore.V1.Key> _repeated_keys_codec
= pb::FieldCodec.ForMessage(10, global::Google.Cloud.Datastore.V1.Key.Parser);
private readonly pbc::RepeatedField<global::Google.Cloud.Datastore.V1.Key> keys_ = new pbc::RepeatedField<global::Google.Cloud.Datastore.V1.Key>();
/// <summary>
/// A list of keys with incomplete key paths for which to allocate IDs.
/// No key may be reserved/read-only.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public pbc::RepeatedField<global::Google.Cloud.Datastore.V1.Key> Keys {
get { return keys_; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as AllocateIdsRequest);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(AllocateIdsRequest other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (ProjectId != other.ProjectId) return false;
if(!keys_.Equals(other.keys_)) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (ProjectId.Length != 0) hash ^= ProjectId.GetHashCode();
hash ^= keys_.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
keys_.WriteTo(output, _repeated_keys_codec);
if (ProjectId.Length != 0) {
output.WriteRawTag(66);
output.WriteString(ProjectId);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (ProjectId.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(ProjectId);
}
size += keys_.CalculateSize(_repeated_keys_codec);
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(AllocateIdsRequest other) {
if (other == null) {
return;
}
if (other.ProjectId.Length != 0) {
ProjectId = other.ProjectId;
}
keys_.Add(other.keys_);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 10: {
keys_.AddEntriesFrom(input, _repeated_keys_codec);
break;
}
case 66: {
ProjectId = input.ReadString();
break;
}
}
}
}
}
/// <summary>
/// The response for [Datastore.AllocateIds][google.datastore.v1.Datastore.AllocateIds].
/// </summary>
public sealed partial class AllocateIdsResponse : pb::IMessage<AllocateIdsResponse> {
private static readonly pb::MessageParser<AllocateIdsResponse> _parser = new pb::MessageParser<AllocateIdsResponse>(() => new AllocateIdsResponse());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<AllocateIdsResponse> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Cloud.Datastore.V1.DatastoreReflection.Descriptor.MessageTypes[11]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public AllocateIdsResponse() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public AllocateIdsResponse(AllocateIdsResponse other) : this() {
keys_ = other.keys_.Clone();
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public AllocateIdsResponse Clone() {
return new AllocateIdsResponse(this);
}
/// <summary>Field number for the "keys" field.</summary>
public const int KeysFieldNumber = 1;
private static readonly pb::FieldCodec<global::Google.Cloud.Datastore.V1.Key> _repeated_keys_codec
= pb::FieldCodec.ForMessage(10, global::Google.Cloud.Datastore.V1.Key.Parser);
private readonly pbc::RepeatedField<global::Google.Cloud.Datastore.V1.Key> keys_ = new pbc::RepeatedField<global::Google.Cloud.Datastore.V1.Key>();
/// <summary>
/// The keys specified in the request (in the same order), each with
/// its key path completed with a newly allocated ID.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public pbc::RepeatedField<global::Google.Cloud.Datastore.V1.Key> Keys {
get { return keys_; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as AllocateIdsResponse);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(AllocateIdsResponse other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if(!keys_.Equals(other.keys_)) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
hash ^= keys_.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
keys_.WriteTo(output, _repeated_keys_codec);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
size += keys_.CalculateSize(_repeated_keys_codec);
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(AllocateIdsResponse other) {
if (other == null) {
return;
}
keys_.Add(other.keys_);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 10: {
keys_.AddEntriesFrom(input, _repeated_keys_codec);
break;
}
}
}
}
}
/// <summary>
/// A mutation to apply to an entity.
/// </summary>
public sealed partial class Mutation : pb::IMessage<Mutation> {
private static readonly pb::MessageParser<Mutation> _parser = new pb::MessageParser<Mutation>(() => new Mutation());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<Mutation> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Cloud.Datastore.V1.DatastoreReflection.Descriptor.MessageTypes[12]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public Mutation() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public Mutation(Mutation other) : this() {
switch (other.OperationCase) {
case OperationOneofCase.Insert:
Insert = other.Insert.Clone();
break;
case OperationOneofCase.Update:
Update = other.Update.Clone();
break;
case OperationOneofCase.Upsert:
Upsert = other.Upsert.Clone();
break;
case OperationOneofCase.Delete:
Delete = other.Delete.Clone();
break;
}
switch (other.ConflictDetectionStrategyCase) {
case ConflictDetectionStrategyOneofCase.BaseVersion:
BaseVersion = other.BaseVersion;
break;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public Mutation Clone() {
return new Mutation(this);
}
/// <summary>Field number for the "insert" field.</summary>
public const int InsertFieldNumber = 4;
/// <summary>
/// The entity to insert. The entity must not already exist.
/// The entity key's final path element may be incomplete.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::Google.Cloud.Datastore.V1.Entity Insert {
get { return operationCase_ == OperationOneofCase.Insert ? (global::Google.Cloud.Datastore.V1.Entity) operation_ : null; }
set {
operation_ = value;
operationCase_ = value == null ? OperationOneofCase.None : OperationOneofCase.Insert;
}
}
/// <summary>Field number for the "update" field.</summary>
public const int UpdateFieldNumber = 5;
/// <summary>
/// The entity to update. The entity must already exist.
/// Must have a complete key path.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::Google.Cloud.Datastore.V1.Entity Update {
get { return operationCase_ == OperationOneofCase.Update ? (global::Google.Cloud.Datastore.V1.Entity) operation_ : null; }
set {
operation_ = value;
operationCase_ = value == null ? OperationOneofCase.None : OperationOneofCase.Update;
}
}
/// <summary>Field number for the "upsert" field.</summary>
public const int UpsertFieldNumber = 6;
/// <summary>
/// The entity to upsert. The entity may or may not already exist.
/// The entity key's final path element may be incomplete.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::Google.Cloud.Datastore.V1.Entity Upsert {
get { return operationCase_ == OperationOneofCase.Upsert ? (global::Google.Cloud.Datastore.V1.Entity) operation_ : null; }
set {
operation_ = value;
operationCase_ = value == null ? OperationOneofCase.None : OperationOneofCase.Upsert;
}
}
/// <summary>Field number for the "delete" field.</summary>
public const int DeleteFieldNumber = 7;
/// <summary>
/// The key of the entity to delete. The entity may or may not already exist.
/// Must have a complete key path and must not be reserved/read-only.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::Google.Cloud.Datastore.V1.Key Delete {
get { return operationCase_ == OperationOneofCase.Delete ? (global::Google.Cloud.Datastore.V1.Key) operation_ : null; }
set {
operation_ = value;
operationCase_ = value == null ? OperationOneofCase.None : OperationOneofCase.Delete;
}
}
/// <summary>Field number for the "base_version" field.</summary>
public const int BaseVersionFieldNumber = 8;
/// <summary>
/// The version of the entity that this mutation is being applied to. If this
/// does not match the current version on the server, the mutation conflicts.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public long BaseVersion {
get { return conflictDetectionStrategyCase_ == ConflictDetectionStrategyOneofCase.BaseVersion ? (long) conflictDetectionStrategy_ : 0L; }
set {
conflictDetectionStrategy_ = value;
conflictDetectionStrategyCase_ = ConflictDetectionStrategyOneofCase.BaseVersion;
}
}
private object operation_;
/// <summary>Enum of possible cases for the "operation" oneof.</summary>
public enum OperationOneofCase {
None = 0,
Insert = 4,
Update = 5,
Upsert = 6,
Delete = 7,
}
private OperationOneofCase operationCase_ = OperationOneofCase.None;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public OperationOneofCase OperationCase {
get { return operationCase_; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void ClearOperation() {
operationCase_ = OperationOneofCase.None;
operation_ = null;
}
private object conflictDetectionStrategy_;
/// <summary>Enum of possible cases for the "conflict_detection_strategy" oneof.</summary>
public enum ConflictDetectionStrategyOneofCase {
None = 0,
BaseVersion = 8,
}
private ConflictDetectionStrategyOneofCase conflictDetectionStrategyCase_ = ConflictDetectionStrategyOneofCase.None;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ConflictDetectionStrategyOneofCase ConflictDetectionStrategyCase {
get { return conflictDetectionStrategyCase_; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void ClearConflictDetectionStrategy() {
conflictDetectionStrategyCase_ = ConflictDetectionStrategyOneofCase.None;
conflictDetectionStrategy_ = null;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as Mutation);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(Mutation other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (!object.Equals(Insert, other.Insert)) return false;
if (!object.Equals(Update, other.Update)) return false;
if (!object.Equals(Upsert, other.Upsert)) return false;
if (!object.Equals(Delete, other.Delete)) return false;
if (BaseVersion != other.BaseVersion) return false;
if (OperationCase != other.OperationCase) return false;
if (ConflictDetectionStrategyCase != other.ConflictDetectionStrategyCase) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (operationCase_ == OperationOneofCase.Insert) hash ^= Insert.GetHashCode();
if (operationCase_ == OperationOneofCase.Update) hash ^= Update.GetHashCode();
if (operationCase_ == OperationOneofCase.Upsert) hash ^= Upsert.GetHashCode();
if (operationCase_ == OperationOneofCase.Delete) hash ^= Delete.GetHashCode();
if (conflictDetectionStrategyCase_ == ConflictDetectionStrategyOneofCase.BaseVersion) hash ^= BaseVersion.GetHashCode();
hash ^= (int) operationCase_;
hash ^= (int) conflictDetectionStrategyCase_;
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (operationCase_ == OperationOneofCase.Insert) {
output.WriteRawTag(34);
output.WriteMessage(Insert);
}
if (operationCase_ == OperationOneofCase.Update) {
output.WriteRawTag(42);
output.WriteMessage(Update);
}
if (operationCase_ == OperationOneofCase.Upsert) {
output.WriteRawTag(50);
output.WriteMessage(Upsert);
}
if (operationCase_ == OperationOneofCase.Delete) {
output.WriteRawTag(58);
output.WriteMessage(Delete);
}
if (conflictDetectionStrategyCase_ == ConflictDetectionStrategyOneofCase.BaseVersion) {
output.WriteRawTag(64);
output.WriteInt64(BaseVersion);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (operationCase_ == OperationOneofCase.Insert) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(Insert);
}
if (operationCase_ == OperationOneofCase.Update) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(Update);
}
if (operationCase_ == OperationOneofCase.Upsert) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(Upsert);
}
if (operationCase_ == OperationOneofCase.Delete) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(Delete);
}
if (conflictDetectionStrategyCase_ == ConflictDetectionStrategyOneofCase.BaseVersion) {
size += 1 + pb::CodedOutputStream.ComputeInt64Size(BaseVersion);
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(Mutation other) {
if (other == null) {
return;
}
switch (other.OperationCase) {
case OperationOneofCase.Insert:
Insert = other.Insert;
break;
case OperationOneofCase.Update:
Update = other.Update;
break;
case OperationOneofCase.Upsert:
Upsert = other.Upsert;
break;
case OperationOneofCase.Delete:
Delete = other.Delete;
break;
}
switch (other.ConflictDetectionStrategyCase) {
case ConflictDetectionStrategyOneofCase.BaseVersion:
BaseVersion = other.BaseVersion;
break;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 34: {
global::Google.Cloud.Datastore.V1.Entity subBuilder = new global::Google.Cloud.Datastore.V1.Entity();
if (operationCase_ == OperationOneofCase.Insert) {
subBuilder.MergeFrom(Insert);
}
input.ReadMessage(subBuilder);
Insert = subBuilder;
break;
}
case 42: {
global::Google.Cloud.Datastore.V1.Entity subBuilder = new global::Google.Cloud.Datastore.V1.Entity();
if (operationCase_ == OperationOneofCase.Update) {
subBuilder.MergeFrom(Update);
}
input.ReadMessage(subBuilder);
Update = subBuilder;
break;
}
case 50: {
global::Google.Cloud.Datastore.V1.Entity subBuilder = new global::Google.Cloud.Datastore.V1.Entity();
if (operationCase_ == OperationOneofCase.Upsert) {
subBuilder.MergeFrom(Upsert);
}
input.ReadMessage(subBuilder);
Upsert = subBuilder;
break;
}
case 58: {
global::Google.Cloud.Datastore.V1.Key subBuilder = new global::Google.Cloud.Datastore.V1.Key();
if (operationCase_ == OperationOneofCase.Delete) {
subBuilder.MergeFrom(Delete);
}
input.ReadMessage(subBuilder);
Delete = subBuilder;
break;
}
case 64: {
BaseVersion = input.ReadInt64();
break;
}
}
}
}
}
/// <summary>
/// The result of applying a mutation.
/// </summary>
public sealed partial class MutationResult : pb::IMessage<MutationResult> {
private static readonly pb::MessageParser<MutationResult> _parser = new pb::MessageParser<MutationResult>(() => new MutationResult());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<MutationResult> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Cloud.Datastore.V1.DatastoreReflection.Descriptor.MessageTypes[13]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public MutationResult() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public MutationResult(MutationResult other) : this() {
Key = other.key_ != null ? other.Key.Clone() : null;
version_ = other.version_;
conflictDetected_ = other.conflictDetected_;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public MutationResult Clone() {
return new MutationResult(this);
}
/// <summary>Field number for the "key" field.</summary>
public const int KeyFieldNumber = 3;
private global::Google.Cloud.Datastore.V1.Key key_;
/// <summary>
/// The automatically allocated key.
/// Set only when the mutation allocated a key.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::Google.Cloud.Datastore.V1.Key Key {
get { return key_; }
set {
key_ = value;
}
}
/// <summary>Field number for the "version" field.</summary>
public const int VersionFieldNumber = 4;
private long version_;
/// <summary>
/// The version of the entity on the server after processing the mutation. If
/// the mutation doesn't change anything on the server, then the version will
/// be the version of the current entity or, if no entity is present, a version
/// that is strictly greater than the version of any previous entity and less
/// than the version of any possible future entity.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public long Version {
get { return version_; }
set {
version_ = value;
}
}
/// <summary>Field number for the "conflict_detected" field.</summary>
public const int ConflictDetectedFieldNumber = 5;
private bool conflictDetected_;
/// <summary>
/// Whether a conflict was detected for this mutation. Always false when a
/// conflict detection strategy field is not set in the mutation.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool ConflictDetected {
get { return conflictDetected_; }
set {
conflictDetected_ = value;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as MutationResult);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(MutationResult other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (!object.Equals(Key, other.Key)) return false;
if (Version != other.Version) return false;
if (ConflictDetected != other.ConflictDetected) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (key_ != null) hash ^= Key.GetHashCode();
if (Version != 0L) hash ^= Version.GetHashCode();
if (ConflictDetected != false) hash ^= ConflictDetected.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (key_ != null) {
output.WriteRawTag(26);
output.WriteMessage(Key);
}
if (Version != 0L) {
output.WriteRawTag(32);
output.WriteInt64(Version);
}
if (ConflictDetected != false) {
output.WriteRawTag(40);
output.WriteBool(ConflictDetected);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (key_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(Key);
}
if (Version != 0L) {
size += 1 + pb::CodedOutputStream.ComputeInt64Size(Version);
}
if (ConflictDetected != false) {
size += 1 + 1;
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(MutationResult other) {
if (other == null) {
return;
}
if (other.key_ != null) {
if (key_ == null) {
key_ = new global::Google.Cloud.Datastore.V1.Key();
}
Key.MergeFrom(other.Key);
}
if (other.Version != 0L) {
Version = other.Version;
}
if (other.ConflictDetected != false) {
ConflictDetected = other.ConflictDetected;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 26: {
if (key_ == null) {
key_ = new global::Google.Cloud.Datastore.V1.Key();
}
input.ReadMessage(key_);
break;
}
case 32: {
Version = input.ReadInt64();
break;
}
case 40: {
ConflictDetected = input.ReadBool();
break;
}
}
}
}
}
/// <summary>
/// The options shared by read requests.
/// </summary>
public sealed partial class ReadOptions : pb::IMessage<ReadOptions> {
private static readonly pb::MessageParser<ReadOptions> _parser = new pb::MessageParser<ReadOptions>(() => new ReadOptions());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<ReadOptions> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Cloud.Datastore.V1.DatastoreReflection.Descriptor.MessageTypes[14]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ReadOptions() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ReadOptions(ReadOptions other) : this() {
switch (other.ConsistencyTypeCase) {
case ConsistencyTypeOneofCase.ReadConsistency:
ReadConsistency = other.ReadConsistency;
break;
case ConsistencyTypeOneofCase.Transaction:
Transaction = other.Transaction;
break;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ReadOptions Clone() {
return new ReadOptions(this);
}
/// <summary>Field number for the "read_consistency" field.</summary>
public const int ReadConsistencyFieldNumber = 1;
/// <summary>
/// The non-transactional read consistency to use.
/// Cannot be set to `STRONG` for global queries.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::Google.Cloud.Datastore.V1.ReadOptions.Types.ReadConsistency ReadConsistency {
get { return consistencyTypeCase_ == ConsistencyTypeOneofCase.ReadConsistency ? (global::Google.Cloud.Datastore.V1.ReadOptions.Types.ReadConsistency) consistencyType_ : 0; }
set {
consistencyType_ = value;
consistencyTypeCase_ = ConsistencyTypeOneofCase.ReadConsistency;
}
}
/// <summary>Field number for the "transaction" field.</summary>
public const int TransactionFieldNumber = 2;
/// <summary>
/// The identifier of the transaction in which to read. A
/// transaction identifier is returned by a call to
/// [Datastore.BeginTransaction][google.datastore.v1.Datastore.BeginTransaction].
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public pb::ByteString Transaction {
get { return consistencyTypeCase_ == ConsistencyTypeOneofCase.Transaction ? (pb::ByteString) consistencyType_ : pb::ByteString.Empty; }
set {
consistencyType_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
consistencyTypeCase_ = ConsistencyTypeOneofCase.Transaction;
}
}
private object consistencyType_;
/// <summary>Enum of possible cases for the "consistency_type" oneof.</summary>
public enum ConsistencyTypeOneofCase {
None = 0,
ReadConsistency = 1,
Transaction = 2,
}
private ConsistencyTypeOneofCase consistencyTypeCase_ = ConsistencyTypeOneofCase.None;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ConsistencyTypeOneofCase ConsistencyTypeCase {
get { return consistencyTypeCase_; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void ClearConsistencyType() {
consistencyTypeCase_ = ConsistencyTypeOneofCase.None;
consistencyType_ = null;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as ReadOptions);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(ReadOptions other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (ReadConsistency != other.ReadConsistency) return false;
if (Transaction != other.Transaction) return false;
if (ConsistencyTypeCase != other.ConsistencyTypeCase) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (consistencyTypeCase_ == ConsistencyTypeOneofCase.ReadConsistency) hash ^= ReadConsistency.GetHashCode();
if (consistencyTypeCase_ == ConsistencyTypeOneofCase.Transaction) hash ^= Transaction.GetHashCode();
hash ^= (int) consistencyTypeCase_;
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (consistencyTypeCase_ == ConsistencyTypeOneofCase.ReadConsistency) {
output.WriteRawTag(8);
output.WriteEnum((int) ReadConsistency);
}
if (consistencyTypeCase_ == ConsistencyTypeOneofCase.Transaction) {
output.WriteRawTag(18);
output.WriteBytes(Transaction);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (consistencyTypeCase_ == ConsistencyTypeOneofCase.ReadConsistency) {
size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) ReadConsistency);
}
if (consistencyTypeCase_ == ConsistencyTypeOneofCase.Transaction) {
size += 1 + pb::CodedOutputStream.ComputeBytesSize(Transaction);
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(ReadOptions other) {
if (other == null) {
return;
}
switch (other.ConsistencyTypeCase) {
case ConsistencyTypeOneofCase.ReadConsistency:
ReadConsistency = other.ReadConsistency;
break;
case ConsistencyTypeOneofCase.Transaction:
Transaction = other.Transaction;
break;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 8: {
consistencyType_ = input.ReadEnum();
consistencyTypeCase_ = ConsistencyTypeOneofCase.ReadConsistency;
break;
}
case 18: {
Transaction = input.ReadBytes();
break;
}
}
}
}
#region Nested types
/// <summary>Container for nested types declared in the ReadOptions message type.</summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static partial class Types {
/// <summary>
/// The possible values for read consistencies.
/// </summary>
public enum ReadConsistency {
/// <summary>
/// Unspecified. This value must not be used.
/// </summary>
[pbr::OriginalName("READ_CONSISTENCY_UNSPECIFIED")] Unspecified = 0,
/// <summary>
/// Strong consistency.
/// </summary>
[pbr::OriginalName("STRONG")] Strong = 1,
/// <summary>
/// Eventual consistency.
/// </summary>
[pbr::OriginalName("EVENTUAL")] Eventual = 2,
}
}
#endregion
}
#endregion
}
#endregion Designer generated code
| 37.094011 | 328 | 0.671279 | [
"Apache-2.0"
] | Acidburn0zzz/google-cloud-dotnet | apis/Google.Cloud.Datastore.V1/Google.Cloud.Datastore.V1/Datastore.cs | 106,534 | C# |
using MediatR;
using WebAppClientes.Infra.CrossCutting.Dtos;
namespace WebAppClientes.Domain.Commands
{
public class CreateClienteCommand : IRequest<CommandReturnDto>
{
public string Nome { get; private set; }
public string Cpf { get; private set; }
public string Rua { get; private set; }
public string Bairro { get; private set; }
public string Cidade { get; private set; }
public string Observacoes { get; private set; }
public CreateClienteCommand(string nome, string cpf, string rua, string bairro, string cidade, string obs)
{
Nome = nome;
Cpf = cpf;
Rua = rua;
Bairro = bairro;
Cidade = cidade;
Observacoes = obs;
}
}
} | 31.4 | 114 | 0.601274 | [
"MIT"
] | rafaeldalsenter/web-app-clientes | WebAppClientes.Domain/Commands/CreateClienteCommand.cs | 787 | C# |
using System;
using System.Collections.Generic;
using Merchello.Core.Models;
using Merchello.Core.Models.TypeFields;
using Umbraco.Core.Persistence.Repositories;
namespace Merchello.Core.Persistence.Repositories
{
/// <summary>
/// Marker interface for the customer registry repository
/// </summary>
internal interface IItemCacheRepository : IRepositoryQueryable<Guid, IItemCache>
{
}
}
| 24.411765 | 84 | 0.756627 | [
"MIT"
] | bowserm/Merchello | src/Merchello.Core/Persistence/Repositories/Interfaces/IItemCacheRepository.cs | 417 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using Unity.MARS.Authoring;
using Unity.MARS.Conditions;
using Unity.MARS.Simulation;
using Unity.XRTools.ModuleLoader;
using UnityEditor;
using UnityEditor.MARS;
using UnityEditor.MARS.Authoring;
using UnityEditor.MARS.Simulation;
using UnityEngine;
namespace Unity.MARS
{
/// <summary>
/// Custom editor for all MARSEntity components
/// </summary>
[CanEditMultipleObjects]
[CustomEditor(typeof(MARSEntity), true)]
class MarsEntityEditor : Editor
{
static readonly string[] k_PropertiesToIgnore =
{
"m_PrefabParentObject",
"m_PrefabInternal",
"m_GameObject",
"m_ObjectHideFlags",
"m_EditorHideFlags",
"m_Script",
"m_EditorClassIdentifier",
"m_PrefabInstance",
"m_PrefabAsset"
};
const string k_MultiEditingWarning = "Multi-entity editing not supported in the inspector.\nYou can still use handles in the scene view.";
const string k_NoConditionsAssignedWarning = "No conditions have been assigned to this entity, so it won't match any world data.\n" +
"Use 'Add MARS Component -> Condition' below, or click the button to add a PlaneSize condition to make this Entity match a surface with a minimum size.";
const string k_NoRelationWarning = "No relations have been assigned to this set.\n" +
"Use 'Add MARS Component -> Relation' below, or click the button to add an Elevation relation.";
const string k_SelectObjectLabel = "Select Object";
const string k_SelectSimObject = "In Simulation";
const string k_SelectSceneObject = "In Scene View";
const string k_WizardAddElevation = "Add Elevation Relation";
const string k_WizardAddPlaneSize = "Add PlaneSize Condition";
const string k_EntityWizardAnalyticEventBase = "EntityWizard / ";
const string k_NoConditions = k_EntityWizardAnalyticEventBase + "No Conditions";
const string k_AddPlaneSizeCondition = k_EntityWizardAnalyticEventBase + "Add PlaneSizeCondition";
const string k_NoRelation = k_EntityWizardAnalyticEventBase + "No Relation";
const string k_AddElevationRelation = k_EntityWizardAnalyticEventBase + "Add Elevation Relation";
const string k_ColorUndoLabel = "Modify Color";
const float k_ColorOptionsButtonWidth = 24f;
[SerializeField]
public MonoBehaviourComponentList monoBehaviourComponent;
[SerializeField]
// ReSharper disable once NotAccessedField.Local
#pragma warning disable 0414
SerializedObject m_SerializedComponents;
#pragma warning restore 0414
static readonly GUIContent k_StopShowingEntityHints = new GUIContent("X", "Stop showing MARSEntity hints");
static readonly GUIContent k_LearnMoreSetsButton = new GUIContent("?", "Learn more about MARS Sets");
static readonly GUIContent k_LearnMoreConditionsButton = new GUIContent("?", "Learn more about MARS Conditions");
static readonly GUIContent k_SetNewColorContent = new GUIContent("Set new color");
static readonly GUIContent k_SetSimilarToParentContent = new GUIContent("Set similar to parent");
static readonly GUIContent k_ApplySimilarToChildrenContent = new GUIContent("Apply similar to children");
static readonly GUIContent k_ResetToDefaultContent = new GUIContent("Reset to default");
GUIContent m_ColorOptionsButtonContent;
MarsComponentListEditor m_ListEditor;
MARSEntity m_SelectedEntity;
Transform m_SelectedTransform;
List<Condition> m_Conditions = new List<Condition>();
List<Relation> m_Relations = new List<Relation>();
SerializedProperty m_ColorProperty;
GenericMenu m_ColorOptionMenu;
List<MultiConditionBase> m_MultiConditions = new List<MultiConditionBase>();
List<MultiRelationBase> m_MultiRelations = new List<MultiRelationBase>();
public void OnEnable()
{
m_SelectedEntity = (MARSEntity)target;
m_ColorProperty = serializedObject.FindProperty("m_Color");
if (m_ColorProperty != null)
{
SetupColorOptionMenu();
m_ColorOptionsButtonContent = new GUIContent(MarsUIResources.instance.Ellipisis, "Color options");
}
// HACK: This should not be null but it is when entering play mode with a simulation object selected
if (!m_SelectedEntity)
return;
m_SelectedTransform = m_SelectedEntity.transform;
RefreshComponentList();
Undo.undoRedoPerformed += OnUndoRedoPerformed;
}
void OnDisable()
{
Undo.undoRedoPerformed -= OnUndoRedoPerformed;
if (m_ListEditor != null)
m_ListEditor.Clear();
// Catches conditions being added since OnDisable is called when undo/redo is called
// and when adding/removing/copying a condition component, even when inspector is closed.
// May be null if Modules have not reloaded before code on inspector is called.
ModuleLoaderCore.instance.GetModule<MarsEntityEditorModule>()?.UpdateConditionData();
}
void SetupColorOptionMenu()
{
m_ColorOptionMenu = new GenericMenu();
m_ColorOptionMenu.AddItem(k_SetNewColorContent, false, SetNewColor);
m_ColorOptionMenu.AddItem(k_SetSimilarToParentContent, false, SetSimilarToParent);
m_ColorOptionMenu.AddItem(k_ApplySimilarToChildrenContent, false, ApplyHueToChildren);
m_ColorOptionMenu.AddItem(k_ResetToDefaultContent, false, ResetColorToDefault);
}
void RefreshComponentList()
{
m_ListEditor = new MarsComponentListEditor(this);
m_ListEditor.OnComponentPasted += ListEditorOnOnComponentPasted;
monoBehaviourComponent = CreateInstance<MonoBehaviourComponentList>();
foreach (var editorTarget in targets)
{
var entity = editorTarget as MARSEntity;
if (entity == null)
continue;
var components = entity.GetComponents<MonoBehaviour>()
.Where(w => w != null && MarsComponentListEditor.SupportsType(w.GetType())).ToList();
monoBehaviourComponent.components.AddRange(components);
}
m_ListEditor.Init(monoBehaviourComponent, m_SerializedComponents = new SerializedObject(monoBehaviourComponent));
m_SelectedEntity.GetComponents(m_Relations);
m_SelectedEntity.GetComponents(m_MultiRelations);
m_SelectedEntity.GetComponents(m_Conditions);
m_SelectedEntity.GetComponents(m_MultiConditions);
// Don't try to copy simulatables if in play mode or in main scene
var simSceneModule = SimulationSceneModule.instance;
if (EditorApplication.isPlayingOrWillChangePlaymode || simSceneModule == null
|| m_SelectedEntity.gameObject.scene != simSceneModule.ContentScene)
return;
// Copy any new components
var simulatedObjectsManager = ModuleLoaderCore.instance.GetModule<SimulatedObjectsManager>();
if (simulatedObjectsManager == null)
return;
foreach (var mb in monoBehaviourComponent.components)
{
var simulated = mb as ISimulatable;
if (simulated == null)
continue;
var original = simulatedObjectsManager.GetOriginalSimulatable(simulated);
if (original == null)
{
var originalEntity = (MARSEntity)simulatedObjectsManager.GetOriginalSimulatable(mb.GetComponent<MARSEntity>());
if (originalEntity != null)
{
var newComp = originalEntity.gameObject.AddComponent(simulated.GetType()) as ISimulatable;
simulatedObjectsManager.AddSimulatedCopy(simulated, newComp);
ApplySimulatedChangesToOriginal();
}
}
}
}
void ListEditorOnOnComponentPasted()
{
ApplySimulatedChangesToOriginal();
}
public override void OnInspectorGUI()
{
serializedObject.Update();
DrawColorEditor();
if (serializedObject.isEditingMultipleObjects)
{
EditorGUILayout.HelpBox(k_MultiEditingWarning, MessageType.Info);
}
else
{
DrawSelectObjectButtons();
MarsCompareTool.DrawControls(this);
if (MarsHints.ShowEntitySetupHints)
DrawEntitySetupWizard();
using (var check = new EditorGUI.ChangeCheckScope())
{
m_ListEditor.OnGUI();
if (check.changed)
{
serializedObject.ApplyModifiedProperties();
ApplySimulatedChangesToOriginal();
m_SelectedEntity.GetComponents(m_Relations);
m_SelectedEntity.GetComponents(m_MultiRelations);
m_SelectedEntity.GetComponents(m_Conditions);
m_SelectedEntity.GetComponents(m_MultiConditions);
}
}
}
}
void DrawColorEditor()
{
if (m_ColorProperty == null)
return;
using (new EditorGUILayout.HorizontalScope())
{
using (var check = new EditorGUI.ChangeCheckScope())
{
EditorGUILayout.PropertyField(m_ColorProperty, GUILayout.ExpandWidth(false));
if (check.changed)
{
serializedObject.ApplyModifiedProperties();
foreach (var selected in targets)
{
var editorColor = target as IHasEditorColor;
if (editorColor != null)
{
editorColor.colorIndex =
-1; // Clear color index because it is now using a custom color.
EntityVisualsModule.instance.UpdateColor((MARSEntity) selected);
}
}
}
}
if (GUILayout.Button(m_ColorOptionsButtonContent, MarsEditorGUI.InternalEditorStyles.ButtonIcon, GUILayout.Width(k_ColorOptionsButtonWidth), GUILayout.Height(EditorGUIUtility.singleLineHeight)))
{
m_ColorOptionMenu.ShowAsContext();
}
}
}
void SetNewColor()
{
Undo.RecordObjects(targets, k_ColorUndoLabel);
foreach (var selected in targets)
{
var editorColor = selected as IHasEditorColor;
if (editorColor != null)
{
editorColor.SetNewColor(false, true);
EntityVisualsModule.instance.UpdateColor((MARSEntity) selected);
}
}
serializedObject.ApplyModifiedProperties();
}
void ResetColorToDefault()
{
Undo.RecordObjects(targets, k_ColorUndoLabel);
foreach (var selected in targets)
{
var editorColor = selected as IHasEditorColor;
if (editorColor != null)
{
editorColor.SetNewColor(false);
EntityVisualsModule.instance.UpdateColor((MARSEntity) selected);
}
}
serializedObject.ApplyModifiedProperties();
}
void SetSimilarToParent()
{
Undo.RecordObjects(targets, k_ColorUndoLabel);
foreach (var selected in targets)
{
var entity = (MARSEntity)selected;
if (entity.transform.parent == null)
continue;
var editorColor = selected as IHasEditorColor;
if (editorColor != null)
{
editorColor.SetNewColor(true);
EntityVisualsModule.instance.UpdateColor(entity);
}
}
serializedObject.ApplyModifiedProperties();
}
void ApplyHueToChildren()
{
Undo.RecordObjects(targets, k_ColorUndoLabel);
foreach (var selected in targets)
{
var editorColor = selected as IHasEditorColor;
if (editorColor == null)
continue;
var component = (Component)editorColor;
foreach (var childEditorColor in component.GetComponentsInChildren<IHasEditorColor>())
{
if (childEditorColor == editorColor)
continue;
Undo.RecordObject((Component)childEditorColor, k_ColorUndoLabel);
childEditorColor.SetNewColor(true);
var childEntity = childEditorColor as MARSEntity;
if (childEntity != null)
EntityVisualsModule.instance.UpdateColor(childEntity);
}
}
serializedObject.ApplyModifiedProperties();
}
void OnUndoRedoPerformed()
{
foreach (var selected in targets)
{
var entity = selected as MARSEntity;
foreach (var childEntity in entity.GetComponentsInChildren<MARSEntity>())
{
if (childEntity is IHasEditorColor)
{
EntityVisualsModule.instance.UpdateColor(childEntity);
}
}
}
}
void DrawSelectObjectButtons()
{
if (EditorApplication.isPlayingOrWillChangePlaymode)
return;
var simulatedObjectsManager = ModuleLoaderCore.instance.GetModule<SimulatedObjectsManager>();
if (simulatedObjectsManager == null)
return;
var simObject = simulatedObjectsManager.GetCopiedTransform(m_SelectedTransform);
var sceneObject = simulatedObjectsManager.GetOriginalTransform(m_SelectedTransform);
if (simObject != null || sceneObject != null)
{
using (new EditorGUILayout.HorizontalScope())
{
EditorGUILayout.PrefixLabel(k_SelectObjectLabel);
using (new EditorGUI.DisabledScope(simObject == null))
{
if (GUILayout.Button(k_SelectSimObject, MarsEditorGUI.Styles.MiniFontButton, GUILayout.ExpandWidth(true)))
Selection.activeTransform = simObject;
}
using (new EditorGUI.DisabledScope(sceneObject == null))
{
if (GUILayout.Button(k_SelectSceneObject, MarsEditorGUI.Styles.MiniFontButton, GUILayout.ExpandWidth(true)))
Selection.activeTransform = sceneObject;
}
}
}
}
void DrawEntitySetupWizard()
{
var drewWizard = true;
if ((m_SelectedEntity as Replicator) != null)
{
drewWizard = false;
}
else if ((m_SelectedEntity as ProxyGroup) != null)
{
if (m_Relations.Count < 1 && m_MultiRelations.Count < 1)
{
MarsEditorUtils.HintBox(true, k_NoRelationWarning, k_NoRelation,
k_LearnMoreSetsButton, MarsHelpURLs.ProxyGroupHelpURL, k_StopShowingEntityHints,
() => {
MarsHints.ShowEntitySetupHints = false;
});
if (GUILayout.Button(k_WizardAddElevation))
{
Undo.AddComponent<ElevationRelation>(m_SelectedEntity.gameObject);
EditorEvents.UiComponentUsed.Send(new UiComponentArgs { label = k_AddElevationRelation });
}
}
}
else if (m_Conditions.Count < 1 && m_MultiConditions.Count < 1)
{
MarsEditorUtils.HintBox(true, k_NoConditionsAssignedWarning, k_NoConditions,
k_LearnMoreConditionsButton, MarsHelpURLs.ProxyConditionsHelpURL, k_StopShowingEntityHints, () =>
{
MarsHints.ShowEntitySetupHints = false;
});
if (GUILayout.Button(k_WizardAddPlaneSize))
{
Undo.AddComponent<PlaneSizeCondition>(m_SelectedTransform.gameObject);
EditorEvents.UiComponentUsed.Send(new UiComponentArgs { label = k_AddPlaneSizeCondition });
EntityVisualsModule.instance.InvalidateVisual(m_SelectedEntity);
}
}
else
{
drewWizard = false;
}
if (drewWizard)
EditorGUILayout.Separator();
}
public void EditorOnSceneGUI(SceneView sceneView)
{
using (var check = new EditorGUI.ChangeCheckScope())
{
if (sceneView == SceneView.lastActiveSceneView)
{
m_ListEditor.OnSceneGUI();
if (check.changed)
{
ApplySimulatedChangesToOriginal();
}
}
}
}
void ApplySimulatedChangesToOriginal()
{
// Don't apply changes to original if already in the editor scene
var simSceneModule = SimulationSceneModule.instance;
if (simSceneModule == null || m_SelectedEntity.gameObject.scene != simSceneModule.ContentScene)
return;
// Copy serialized properties from all the MonoBehaviours that this editor is editing
var simulatedObjectsManager = ModuleLoaderCore.instance.GetModule<SimulatedObjectsManager>();
if (simulatedObjectsManager == null)
return;
foreach (var mb in monoBehaviourComponent.components)
{
var simulated = mb as ISimulatable;
if (simulated == null)
continue;
var original = simulatedObjectsManager.GetOriginalSimulatable(simulated);
if (original == null)
continue;
// Check if the object is destroyed
var originalMono = original as MonoBehaviour;
if (originalMono == null)
{
simulatedObjectsManager.DirtySimulatableScene();
continue;
}
var originalSerialized = new SerializedObject(originalMono);
var simulatableSerialized = new SerializedObject(simulated as MonoBehaviour);
var propertyIterator = simulatableSerialized.GetIterator();
var enterChildren = true;
while (NextUserProperty(propertyIterator, enterChildren))
{
enterChildren = true;
// If the property is referencing a simulation object, want to get the reference to the original version.
if (propertyIterator.propertyType == SerializedPropertyType.ObjectReference &&
propertyIterator.objectReferenceValue != null)
{
var referenceInstanceId = propertyIterator.objectReferenceInstanceIDValue;
var reference = EditorUtility.InstanceIDToObject(referenceInstanceId);
var originalRef = simulatedObjectsManager.GetOriginalObject(reference);
if (originalRef != null)
{
originalSerialized.FindProperty(propertyIterator.propertyPath).objectReferenceInstanceIDValue = originalRef.GetInstanceID();
enterChildren = false; //Don't copy the file id and path id
continue; // Don't copy this property because it is a reference and not a prefab
}
}
// For all other serialized properties copy them if they are different
originalSerialized.CopyFromSerializedPropertyIfDifferent(propertyIterator);
}
originalSerialized.ApplyModifiedProperties();
originalSerialized.Dispose();
simulatableSerialized.Dispose();
}
}
static bool NextUserProperty(SerializedProperty propertyIterator, bool enterChildren)
{
if (!propertyIterator.Next(enterChildren))
return false;
var userProperty = true;
do
{
userProperty = true;
foreach (var ignoreString in k_PropertiesToIgnore)
{
if (propertyIterator.propertyPath.Contains(ignoreString))
{
userProperty = false;
if (!propertyIterator.Next(false)) // Skip children of ignored property
return false; // Return false if there is no next property
break;
}
}
}
while (!userProperty);
return true;
}
/// <summary>
/// Invalidates the visuals for the entity and re-syncs the values in the editor.
/// </summary>
public void Invalidate()
{
EntityVisualsModule.instance.InvalidateVisual(m_SelectedEntity);
OnDisable();
var simulatedObjectsManager = ModuleLoaderCore.instance.GetModule<SimulatedObjectsManager>();
foreach (var mb in monoBehaviourComponent.components)
{
if (simulatedObjectsManager == null)
continue;
// Early out if object was destroyed
if (mb == null)
{
simulatedObjectsManager.DirtySimulatableScene();
break;
}
var simulatable = mb as ISimulatable;
if (simulatable == null)
continue;
if (SimulatedObjectsManager.IsSimulatedObject(mb.gameObject))
{
// If object is simulated we need to check the original version still exists.
var original = simulatedObjectsManager.GetOriginalSimulatable(simulatable);
if (original != null)
{
// Check if the object is destroyed
var originalMono = original as MonoBehaviour;
if (originalMono == null)
{
simulatedObjectsManager.DirtySimulatableScene();
break;
}
}
}
else
{
// If object is original(scene) we need to check the simulated version still exists.
var simulated = simulatedObjectsManager.GetCopiedSimulatable(simulatable);
if (simulated != null)
{
// Check if the object is destroyed
var simulatedMono = simulated as MonoBehaviour;
if (simulatedMono == null)
{
simulatedObjectsManager.DirtySimulatableScene();
break;
}
}
}
}
OnEnable();
Repaint();
}
}
}
| 41.277311 | 210 | 0.562378 | [
"Apache-2.0"
] | bsides44/MARSGeofencing | MARS geofencing/Library/PackageCache/[email protected]/Editor/Scripts/Entities/MarsEntityEditor.cs | 24,562 | C# |
using AutoMapper;
using MiCake.DDD.Domain;
using MiCake.DDD.Extensions.Store;
using MiCake.DDD.Extensions.Store.Mapping;
using System;
using System.Linq.Expressions;
namespace MiCake.AutoMapper
{
/// <summary>
/// <see cref="IPersistentObjectMapConfig{TKey,TDomainEntity, TPersistentObject}"/> implement for AutoMapper.
/// </summary>
internal class AutoMapperPersistentObjectMapConfig<TKey, TDomainEntity, TPersistentObject> : IPersistentObjectMapConfig<TKey, TDomainEntity, TPersistentObject>
where TDomainEntity : IAggregateRoot<TKey>
where TPersistentObject : IPersistentObject<TKey, TDomainEntity>
{
private IMappingExpression<TDomainEntity, TPersistentObject> _autoMapperExpression;
public AutoMapperPersistentObjectMapConfig(IMappingExpression<TDomainEntity, TPersistentObject> autoMapperExpression)
=> _autoMapperExpression = autoMapperExpression;
public void Build()
{
_autoMapperExpression
.AfterMap((s, d) => d.AddDomainEvents(s.GetDomainEvents())) //Give DomainEvents to persistent object.
.ReverseMap();
}
public IPersistentObjectMapConfig<TKey, TDomainEntity, TPersistentObject> MapProperty<TEntityProperty, TPersistentObjectProperty>(
Expression<Func<TDomainEntity, TEntityProperty>> domainEntiyProperty,
Expression<Func<TPersistentObject, TPersistentObjectProperty>> persistentObjectProperty)
{
_autoMapperExpression.ForMember(persistentObjectProperty, opt => opt.MapFrom(domainEntiyProperty));
return this;
}
}
}
| 44.594595 | 163 | 0.727879 | [
"MIT"
] | wrsxinlang/MiCake | src/framework/MiCake.AutoMapper/AutoMapperPersistentObjectMapConfig.cs | 1,652 | C# |
using System.Windows.Forms;
namespace AnyChatCSharpDemo
{
partial class frmHall : Form
{
/// <summary>
/// 必需的设计器变量。
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// 清理所有正在使用的资源。
/// </summary>
/// <param name="disposing">如果应释放托管资源,为 true;否则为 false。</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows 窗体设计器生成的代码
/// <summary>
/// 设计器支持所需的方法 - 不要
/// 使用代码编辑器修改此方法的内容。
/// </summary>
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(frmHall));
this.panel1 = new System.Windows.Forms.Panel();
this.richTextBox1 = new AnyChatCSharpDemo.TransparentRichTextBox();
this.dataGridView1 = new AnyChatCSharpDemo.MyDataGrid();
this.Column1 = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.Column2 = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.Column3 = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.Column4 = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.panel1.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).BeginInit();
this.SuspendLayout();
//
// panel1
//
this.panel1.Controls.Add(this.richTextBox1);
this.panel1.Location = new System.Drawing.Point(213, 110);
this.panel1.Name = "panel1";
this.panel1.Size = new System.Drawing.Size(388, 280);
this.panel1.TabIndex = 2;
//
// richTextBox1
//
this.richTextBox1.BackColor = System.Drawing.Color.White;
this.richTextBox1.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.richTextBox1.Location = new System.Drawing.Point(112, 37);
this.richTextBox1.Name = "richTextBox1";
this.richTextBox1.ScrollBars = System.Windows.Forms.RichTextBoxScrollBars.None;
this.richTextBox1.Size = new System.Drawing.Size(222, 199);
this.richTextBox1.TabIndex = 0;
this.richTextBox1.Text = "";
//
// dataGridView1
//
this.dataGridView1.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
this.dataGridView1.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] {
this.Column1,
this.Column2,
this.Column3,
this.Column4});
this.dataGridView1.Location = new System.Drawing.Point(12, 12);
this.dataGridView1.Name = "dataGridView1";
this.dataGridView1.RowTemplate.Height = 23;
this.dataGridView1.Size = new System.Drawing.Size(87, 160);
this.dataGridView1.TabIndex = 1;
//
// Column1
//
this.Column1.HeaderText = "Column1";
this.Column1.Name = "Column1";
//
// Column2
//
this.Column2.HeaderText = "Column2";
this.Column2.Name = "Column2";
//
// Column3
//
this.Column3.HeaderText = "Column3";
this.Column3.Name = "Column3";
//
// Column4
//
this.Column4.HeaderText = "Column4";
this.Column4.Name = "Column4";
//
// frmHall
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.BackColor = System.Drawing.Color.ForestGreen;
this.BackgroundImage = global::AnyChatCSharpDemo.Properties.Resources.桌面11;
this.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch;
this.ClientSize = new System.Drawing.Size(775, 468);
this.Controls.Add(this.panel1);
this.Controls.Add(this.dataGridView1);
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.Name = "frmHall";
this.Text = "frmHall";
this.panel1.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).EndInit();
this.ResumeLayout(false);
}
#endregion
private TransparentRichTextBox richTextBox1;
private MyDataGrid dataGridView1;
private System.Windows.Forms.DataGridViewTextBoxColumn Column1;
private System.Windows.Forms.DataGridViewTextBoxColumn Column2;
private System.Windows.Forms.DataGridViewTextBoxColumn Column3;
private System.Windows.Forms.DataGridViewTextBoxColumn Column4;
private System.Windows.Forms.Panel panel1;
}
} | 40.666667 | 139 | 0.590736 | [
"Apache-2.0"
] | alucard263096/AMKRemoteClass | Documents/AnyChat/AnyChatCoreSDK_Win32_r4840/src/client/c#/AnyChatCSharpDemo/frmHall.Designer.cs | 5,402 | C# |
// ==========================================================================
// Squidex Headless CMS
// ==========================================================================
// Copyright (c) Squidex UG (haftungsbeschränkt)
// All rights reserved. Licensed under the MIT license.
// ==========================================================================
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Squidex.Domain.Apps.Core.Rules;
using Squidex.Domain.Apps.Core.Rules.EnrichedEvents;
using Squidex.Domain.Apps.Events;
using Squidex.Infrastructure.EventSourcing;
namespace Squidex.Domain.Apps.Core.HandleRules
{
public interface IRuleTriggerHandler
{
Type TriggerType { get; }
Task<List<EnrichedEvent>> CreateEnrichedEventsAsync(Envelope<AppEvent> @event);
bool Trigger(EnrichedEvent @event, RuleTrigger trigger);
bool Trigger(AppEvent @event, RuleTrigger trigger, Guid ruleId);
}
}
| 33.896552 | 87 | 0.574771 | [
"MIT"
] | IainCoSource/squidex | backend/src/Squidex.Domain.Apps.Core.Operations/HandleRules/IRuleTriggerHandler.cs | 986 | C# |
using System;
using System.Collections.Generic;
namespace Paradigm.ORM.Data.StoredProcedures
{
/// <summary>
/// Provides an interface to execute data reader stored procedures returning only 6 result sets.
/// </summary>
/// <remarks>
/// Instead of sending individual parameters to the procedure, the orm expects a <see cref="TParameters"/> type
/// containing or referencing the mapping information, where individual parameters will be mapped to properties.
/// </remarks>
/// <typeparam name="TParameters">The type of the parameters.</typeparam>
/// <typeparam name="TResult1">The type of the first result.</typeparam>
/// <typeparam name="TResult2">The type of the second result.</typeparam>
/// <typeparam name="TResult3">The type of the third result.</typeparam>
/// <typeparam name="TResult4">The type of the fourth result.</typeparam>
/// <typeparam name="TResult5">The type of the fifth result.</typeparam>
/// <typeparam name="TResult6">The type of the sixth result.</typeparam>
/// <seealso cref="Paradigm.ORM.Data.StoredProcedures.IRoutine" />
public partial interface IReaderStoredProcedure<in TParameters, TResult1, TResult2, TResult3, TResult4, TResult5, TResult6> : IRoutine
{
/// <summary>
/// Executes the stored procedure and return a list of tuples.
/// </summary>
/// <param name="parameters">The parameters.</param>
/// <returns>List of tuples.</returns>
Tuple<List<TResult1>, List<TResult2>, List<TResult3>, List<TResult4>, List<TResult5>, List<TResult6>> Execute(TParameters parameters);
}
} | 54.566667 | 142 | 0.69212 | [
"MIT"
] | MiracleDevs/Paradigm.ORM | src/Paradigm.ORM.Data/StoredProcedures/IReaderStoredProcedure.6.cs | 1,637 | C# |
// <auto-generated>
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// </auto-generated>
namespace Microsoft.Azure.Management.CosmosDB
{
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// CollectionPartitionOperations operations.
/// </summary>
internal partial class CollectionPartitionOperations : IServiceOperations<CosmosDBManagementClient>, ICollectionPartitionOperations
{
/// <summary>
/// Initializes a new instance of the CollectionPartitionOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal CollectionPartitionOperations(CosmosDBManagementClient client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
Client = client;
}
/// <summary>
/// Gets a reference to the CosmosDBManagementClient
/// </summary>
public CosmosDBManagementClient Client { get; private set; }
/// <summary>
/// Retrieves the metrics determined by the given filter for the given
/// collection, split by partition.
/// </summary>
/// <param name='resourceGroupName'>
/// Name of an Azure resource group.
/// </param>
/// <param name='accountName'>
/// Cosmos DB database account name.
/// </param>
/// <param name='databaseRid'>
/// Cosmos DB database rid.
/// </param>
/// <param name='collectionRid'>
/// Cosmos DB collection rid.
/// </param>
/// <param name='filter'>
/// An OData filter expression that describes a subset of metrics to return.
/// The parameters that can be filtered are name.value (name of the metric, can
/// have an or of multiple names), startTime, endTime, and timeGrain. The
/// supported operator is eq.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IEnumerable<PartitionMetric>>> ListMetricsWithHttpMessagesAsync(string resourceGroupName, string accountName, string databaseRid, string collectionRid, string filter, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (resourceGroupName != null)
{
if (resourceGroupName.Length > 90)
{
throw new ValidationException(ValidationRules.MaxLength, "resourceGroupName", 90);
}
if (resourceGroupName.Length < 1)
{
throw new ValidationException(ValidationRules.MinLength, "resourceGroupName", 1);
}
if (!System.Text.RegularExpressions.Regex.IsMatch(resourceGroupName, "^[-\\w\\._\\(\\)]+$"))
{
throw new ValidationException(ValidationRules.Pattern, "resourceGroupName", "^[-\\w\\._\\(\\)]+$");
}
}
if (accountName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "accountName");
}
if (accountName != null)
{
if (accountName.Length > 50)
{
throw new ValidationException(ValidationRules.MaxLength, "accountName", 50);
}
if (accountName.Length < 3)
{
throw new ValidationException(ValidationRules.MinLength, "accountName", 3);
}
if (!System.Text.RegularExpressions.Regex.IsMatch(accountName, "^[a-z0-9]+(-[a-z0-9]+)*"))
{
throw new ValidationException(ValidationRules.Pattern, "accountName", "^[a-z0-9]+(-[a-z0-9]+)*");
}
}
if (databaseRid == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "databaseRid");
}
if (collectionRid == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "collectionRid");
}
if (filter == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "filter");
}
string apiVersion = "2020-03-01";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("accountName", accountName);
tracingParameters.Add("databaseRid", databaseRid);
tracingParameters.Add("collectionRid", collectionRid);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("filter", filter);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "ListMetrics", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/databases/{databaseRid}/collections/{collectionRid}/partitions/metrics").ToString();
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{accountName}", System.Uri.EscapeDataString(accountName));
_url = _url.Replace("{databaseRid}", System.Uri.EscapeDataString(databaseRid));
_url = _url.Replace("{collectionRid}", System.Uri.EscapeDataString(collectionRid));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (filter != null)
{
_queryParameters.Add(string.Format("$filter={0}", System.Uri.EscapeDataString(filter)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IEnumerable<PartitionMetric>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<PartitionMetric>>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Retrieves the usages (most recent storage data) for the given collection,
/// split by partition.
/// </summary>
/// <param name='resourceGroupName'>
/// Name of an Azure resource group.
/// </param>
/// <param name='accountName'>
/// Cosmos DB database account name.
/// </param>
/// <param name='databaseRid'>
/// Cosmos DB database rid.
/// </param>
/// <param name='collectionRid'>
/// Cosmos DB collection rid.
/// </param>
/// <param name='filter'>
/// An OData filter expression that describes a subset of usages to return. The
/// supported parameter is name.value (name of the metric, can have an or of
/// multiple names).
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IEnumerable<PartitionUsage>>> ListUsagesWithHttpMessagesAsync(string resourceGroupName, string accountName, string databaseRid, string collectionRid, string filter = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (resourceGroupName != null)
{
if (resourceGroupName.Length > 90)
{
throw new ValidationException(ValidationRules.MaxLength, "resourceGroupName", 90);
}
if (resourceGroupName.Length < 1)
{
throw new ValidationException(ValidationRules.MinLength, "resourceGroupName", 1);
}
if (!System.Text.RegularExpressions.Regex.IsMatch(resourceGroupName, "^[-\\w\\._\\(\\)]+$"))
{
throw new ValidationException(ValidationRules.Pattern, "resourceGroupName", "^[-\\w\\._\\(\\)]+$");
}
}
if (accountName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "accountName");
}
if (accountName != null)
{
if (accountName.Length > 50)
{
throw new ValidationException(ValidationRules.MaxLength, "accountName", 50);
}
if (accountName.Length < 3)
{
throw new ValidationException(ValidationRules.MinLength, "accountName", 3);
}
if (!System.Text.RegularExpressions.Regex.IsMatch(accountName, "^[a-z0-9]+(-[a-z0-9]+)*"))
{
throw new ValidationException(ValidationRules.Pattern, "accountName", "^[a-z0-9]+(-[a-z0-9]+)*");
}
}
if (databaseRid == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "databaseRid");
}
if (collectionRid == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "collectionRid");
}
string apiVersion = "2020-03-01";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("accountName", accountName);
tracingParameters.Add("databaseRid", databaseRid);
tracingParameters.Add("collectionRid", collectionRid);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("filter", filter);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "ListUsages", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/databases/{databaseRid}/collections/{collectionRid}/partitions/usages").ToString();
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{accountName}", System.Uri.EscapeDataString(accountName));
_url = _url.Replace("{databaseRid}", System.Uri.EscapeDataString(databaseRid));
_url = _url.Replace("{collectionRid}", System.Uri.EscapeDataString(collectionRid));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (filter != null)
{
_queryParameters.Add(string.Format("$filter={0}", System.Uri.EscapeDataString(filter)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IEnumerable<PartitionUsage>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<PartitionUsage>>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| 46.061837 | 352 | 0.560508 | [
"MIT"
] | HeidiSteen/azure-sdk-for-net | sdk/cosmosdb/Microsoft.Azure.Management.CosmosDB/src/Generated/CollectionPartitionOperations.cs | 26,071 | 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.Collections.Generic;
using System.Collections;
using System.ComponentModel;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Net;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
using System.Threading;
namespace System.Net.Sockets
{
internal static partial class SocketPal
{
// The API that uses this information is not supported on *nix, and will throw
// PlatformNotSupportedException instead.
public const int ProtocolInformationSize = 0;
public readonly static bool SupportsMultipleConnectAttempts = GetPlatformSupportsMultipleConnectAttempts();
private readonly static bool SupportsDualModeIPv4PacketInfo = GetPlatformSupportsDualModeIPv4PacketInfo();
private static bool GetPlatformSupportsMultipleConnectAttempts()
{
return Interop.Sys.PlatformSupportsMultipleConnectAttempts();
}
private static bool GetPlatformSupportsDualModeIPv4PacketInfo()
{
return Interop.Sys.PlatformSupportsDualModeIPv4PacketInfo();
}
public static SocketError GetSocketErrorForErrorCode(Interop.Error errorCode)
{
// NOTE: SocketError values with no direct mapping have been omitted for now.
//
// These values are:
// - SocketError.SocketNotSupported
// - SocketError.OperationNotSupported
// - SocketError.ProtocolFamilyNotSupported
// - SocketError.NoBufferSpaceAvailable
// - SocketError.Shutdown
// - SocketError.HostDown
// - SocketError.ProcessLimit
//
// Although they are not present in this mapping, SocketError.IOPending and
// SocketError.OperationAborted are returned directly methods on
// SocketAsyncContext (these errors are only relevant for async I/O).
switch (errorCode)
{
case Interop.Error.SUCCESS:
return SocketError.Success;
case Interop.Error.EINTR:
return SocketError.Interrupted;
case Interop.Error.EACCES:
return SocketError.AccessDenied;
case Interop.Error.EFAULT:
return SocketError.Fault;
case Interop.Error.EINVAL:
return SocketError.InvalidArgument;
case Interop.Error.EMFILE:
case Interop.Error.ENFILE:
return SocketError.TooManyOpenSockets;
case Interop.Error.EAGAIN:
return SocketError.WouldBlock;
case Interop.Error.EINPROGRESS:
return SocketError.InProgress;
case Interop.Error.EALREADY:
return SocketError.AlreadyInProgress;
case Interop.Error.ENOTSOCK:
return SocketError.NotSocket;
case Interop.Error.EDESTADDRREQ:
return SocketError.DestinationAddressRequired;
case Interop.Error.EMSGSIZE:
return SocketError.MessageSize;
case Interop.Error.EPROTOTYPE:
return SocketError.ProtocolType;
case Interop.Error.ENOPROTOOPT:
case Interop.Error.ENOTSUP:
return SocketError.ProtocolOption;
case Interop.Error.EPROTONOSUPPORT:
return SocketError.ProtocolNotSupported;
case Interop.Error.EAFNOSUPPORT:
return SocketError.AddressFamilyNotSupported;
case Interop.Error.EADDRINUSE:
return SocketError.AddressAlreadyInUse;
case Interop.Error.EADDRNOTAVAIL:
return SocketError.AddressNotAvailable;
case Interop.Error.ENETDOWN:
return SocketError.NetworkDown;
case Interop.Error.ENETUNREACH:
return SocketError.NetworkUnreachable;
case Interop.Error.ENETRESET:
return SocketError.NetworkReset;
case Interop.Error.ECONNABORTED:
return SocketError.ConnectionAborted;
case Interop.Error.ECONNRESET:
return SocketError.ConnectionReset;
case Interop.Error.EISCONN:
return SocketError.IsConnected;
case Interop.Error.ENOTCONN:
return SocketError.NotConnected;
case Interop.Error.ETIMEDOUT:
return SocketError.TimedOut;
case Interop.Error.ECONNREFUSED:
return SocketError.ConnectionRefused;
case Interop.Error.EHOSTUNREACH:
return SocketError.HostUnreachable;
default:
return SocketError.SocketError;
}
}
private static unsafe IPPacketInformation GetIPPacketInformation(Interop.Sys.MessageHeader* messageHeader, bool isIPv4, bool isIPv6)
{
if (!isIPv4 && !isIPv6)
{
return default(IPPacketInformation);
}
Interop.Sys.IPPacketInformation nativePacketInfo;
if (!Interop.Sys.TryGetIPPacketInformation(messageHeader, isIPv4, &nativePacketInfo))
{
return default(IPPacketInformation);
}
return new IPPacketInformation(nativePacketInfo.Address.GetIPAddress(), nativePacketInfo.InterfaceIndex);
}
public static SocketError CreateSocket(AddressFamily addressFamily, SocketType socketType, ProtocolType protocolType, out SafeCloseSocket socket)
{
return SafeCloseSocket.CreateSocket(addressFamily, socketType, protocolType, out socket);
}
private static unsafe int Receive(int fd, SocketFlags flags, int available, byte[] buffer, int offset, int count, byte[] socketAddress, ref int socketAddressLen, out SocketFlags receivedFlags, out Interop.Error errno)
{
Debug.Assert(socketAddress != null || socketAddressLen == 0);
var pinnedSocketAddress = default(GCHandle);
byte* sockAddr = null;
int sockAddrLen = 0;
long received;
try
{
if (socketAddress != null)
{
pinnedSocketAddress = GCHandle.Alloc(socketAddress, GCHandleType.Pinned);
sockAddr = (byte*)pinnedSocketAddress.AddrOfPinnedObject();
sockAddrLen = socketAddressLen;
}
fixed (byte* b = buffer)
{
var iov = new Interop.Sys.IOVector {
Base = &b[offset],
Count = (UIntPtr)count
};
var messageHeader = new Interop.Sys.MessageHeader {
SocketAddress = sockAddr,
SocketAddressLen = sockAddrLen,
IOVectors = &iov,
IOVectorCount = 1
};
errno = Interop.Sys.ReceiveMessage(fd, &messageHeader, flags, &received);
receivedFlags = messageHeader.Flags;
sockAddrLen = messageHeader.SocketAddressLen;
}
}
finally
{
if (pinnedSocketAddress.IsAllocated)
{
pinnedSocketAddress.Free();
}
}
if (errno != Interop.Error.SUCCESS)
{
return -1;
}
socketAddressLen = sockAddrLen;
return checked((int)received);
}
private static unsafe int Send(int fd, SocketFlags flags, byte[] buffer, ref int offset, ref int count, byte[] socketAddress, int socketAddressLen, out Interop.Error errno)
{
var pinnedSocketAddress = default(GCHandle);
byte* sockAddr = null;
int sockAddrLen = 0;
int sent;
try
{
if (socketAddress != null)
{
pinnedSocketAddress = GCHandle.Alloc(socketAddress, GCHandleType.Pinned);
sockAddr = (byte*)pinnedSocketAddress.AddrOfPinnedObject();
sockAddrLen = socketAddressLen;
}
fixed (byte* b = buffer)
{
var iov = new Interop.Sys.IOVector {
Base = &b[offset],
Count = (UIntPtr)count
};
var messageHeader = new Interop.Sys.MessageHeader {
SocketAddress = sockAddr,
SocketAddressLen = sockAddrLen,
IOVectors = &iov,
IOVectorCount = 1
};
long bytesSent;
errno = Interop.Sys.SendMessage(fd, &messageHeader, flags, &bytesSent);
sent = checked((int)bytesSent);
}
}
finally
{
if (pinnedSocketAddress.IsAllocated)
{
pinnedSocketAddress.Free();
}
}
if (errno != Interop.Error.SUCCESS)
{
return -1;
}
offset += sent;
count -= sent;
return sent;
}
private static unsafe int Send(int fd, SocketFlags flags, IList<ArraySegment<byte>> buffers, ref int bufferIndex, ref int offset, byte[] socketAddress, int socketAddressLen, out Interop.Error errno)
{
// Pin buffers and set up iovecs.
int startIndex = bufferIndex, startOffset = offset;
var pinnedSocketAddress = default(GCHandle);
byte* sockAddr = null;
int sockAddrLen = 0;
int maxBuffers = buffers.Count - startIndex;
var handles = new GCHandle[maxBuffers];
var iovecs = new Interop.Sys.IOVector[maxBuffers];
int sent;
int toSend = 0, iovCount = maxBuffers;
try
{
for (int i = 0; i < maxBuffers; i++, startOffset = 0)
{
ArraySegment<byte> buffer = buffers[startIndex + i];
Debug.Assert(buffer.Offset + startOffset < buffer.Array.Length);
handles[i] = GCHandle.Alloc(buffer.Array, GCHandleType.Pinned);
iovecs[i].Base = &((byte*)handles[i].AddrOfPinnedObject())[buffer.Offset + startOffset];
toSend += (buffer.Count - startOffset);
iovecs[i].Count = (UIntPtr)(buffer.Count - startOffset);
}
if (socketAddress != null)
{
pinnedSocketAddress = GCHandle.Alloc(socketAddress, GCHandleType.Pinned);
sockAddr = (byte*)pinnedSocketAddress.AddrOfPinnedObject();
sockAddrLen = socketAddressLen;
}
// Make the call
fixed (Interop.Sys.IOVector* iov = iovecs)
{
var messageHeader = new Interop.Sys.MessageHeader {
SocketAddress = sockAddr,
SocketAddressLen = sockAddrLen,
IOVectors = iov,
IOVectorCount = iovCount
};
long bytesSent;
errno = Interop.Sys.SendMessage(fd, &messageHeader, flags, &bytesSent);
sent = checked((int)bytesSent);
}
}
finally
{
// Free GC handles.
for (int i = 0; i < iovCount; i++)
{
if (handles[i].IsAllocated)
{
handles[i].Free();
}
}
if (pinnedSocketAddress.IsAllocated)
{
pinnedSocketAddress.Free();
}
}
if (errno != Interop.Error.SUCCESS)
{
return -1;
}
// Update position.
int endIndex = bufferIndex, endOffset = offset, unconsumed = sent;
for (; endIndex < buffers.Count && unconsumed > 0; endIndex++, endOffset = 0)
{
int space = buffers[endIndex].Count - endOffset;
if (space > unconsumed)
{
endOffset += unconsumed;
break;
}
unconsumed -= space;
}
bufferIndex = endIndex;
offset = endOffset;
return sent;
}
private static unsafe int Receive(int fd, SocketFlags flags, int available, IList<ArraySegment<byte>> buffers, byte[] socketAddress, ref int socketAddressLen, out SocketFlags receivedFlags, out Interop.Error errno)
{
// Pin buffers and set up iovecs.
int maxBuffers = buffers.Count;
var handles = new GCHandle[maxBuffers];
var iovecs = new Interop.Sys.IOVector[maxBuffers];
var pinnedSocketAddress = default(GCHandle);
byte* sockAddr = null;
int sockAddrLen = 0;
long received = 0;
int toReceive = 0, iovCount = maxBuffers;
try
{
for (int i = 0; i < maxBuffers; i++)
{
ArraySegment<byte> buffer = buffers[i];
handles[i] = GCHandle.Alloc(buffer.Array, GCHandleType.Pinned);
iovecs[i].Base = &((byte*)handles[i].AddrOfPinnedObject())[buffer.Offset];
int space = buffer.Count;
toReceive += space;
if (toReceive >= available)
{
iovecs[i].Count = (UIntPtr)(space - (toReceive - available));
toReceive = available;
iovCount = i + 1;
break;
}
iovecs[i].Count = (UIntPtr)space;
}
if (socketAddress != null)
{
pinnedSocketAddress = GCHandle.Alloc(socketAddress, GCHandleType.Pinned);
sockAddr = (byte*)pinnedSocketAddress.AddrOfPinnedObject();
sockAddrLen = socketAddressLen;
}
// Make the call.
fixed (Interop.Sys.IOVector* iov = iovecs)
{
var messageHeader = new Interop.Sys.MessageHeader {
SocketAddress = sockAddr,
SocketAddressLen = sockAddrLen,
IOVectors = iov,
IOVectorCount = iovCount
};
errno = Interop.Sys.ReceiveMessage(fd, &messageHeader, flags, &received);
receivedFlags = messageHeader.Flags;
sockAddrLen = messageHeader.SocketAddressLen;
}
}
finally
{
// Free GC handles.
for (int i = 0; i < iovCount; i++)
{
if (handles[i].IsAllocated)
{
handles[i].Free();
}
}
if (pinnedSocketAddress.IsAllocated)
{
pinnedSocketAddress.Free();
}
}
if (errno != Interop.Error.SUCCESS)
{
return -1;
}
socketAddressLen = sockAddrLen;
return checked((int)received);
}
private static unsafe int ReceiveMessageFrom(int fd, SocketFlags flags, int available, byte[] buffer, int offset, int count, byte[] socketAddress, ref int socketAddressLen, bool isIPv4, bool isIPv6, out SocketFlags receivedFlags, out IPPacketInformation ipPacketInformation, out Interop.Error errno)
{
Debug.Assert(socketAddress != null);
int cmsgBufferLen = Interop.Sys.GetControlMessageBufferSize(isIPv4, isIPv6);
var cmsgBuffer = stackalloc byte[cmsgBufferLen];
int sockAddrLen = socketAddressLen;
Interop.Sys.MessageHeader messageHeader;
long received;
fixed (byte* rawSocketAddress = socketAddress)
fixed (byte* b = buffer)
{
var sockAddr = (byte*)rawSocketAddress;
var iov = new Interop.Sys.IOVector {
Base = &b[offset],
Count = (UIntPtr)count
};
messageHeader = new Interop.Sys.MessageHeader {
SocketAddress = sockAddr,
SocketAddressLen = sockAddrLen,
IOVectors = &iov,
IOVectorCount = 1,
ControlBuffer = cmsgBuffer,
ControlBufferLen = cmsgBufferLen
};
errno = Interop.Sys.ReceiveMessage(fd, &messageHeader, flags, &received);
receivedFlags = messageHeader.Flags;
sockAddrLen = messageHeader.SocketAddressLen;
}
ipPacketInformation = GetIPPacketInformation(&messageHeader, isIPv4, isIPv6);
if (errno != Interop.Error.SUCCESS)
{
return -1;
}
socketAddressLen = sockAddrLen;
return checked((int)received);
}
public static unsafe bool TryCompleteAccept(int fileDescriptor, byte[] socketAddress, ref int socketAddressLen, out int acceptedFd, out SocketError errorCode)
{
int fd;
Interop.Error errno;
int sockAddrLen = socketAddressLen;
fixed (byte* rawSocketAddress = socketAddress)
{
errno = Interop.Sys.Accept(fileDescriptor, rawSocketAddress, &sockAddrLen, &fd);
}
if (errno == Interop.Error.SUCCESS)
{
Debug.Assert(fd != -1);
// If the accept completed successfully, ensure that the accepted socket is non-blocking.
int err = Interop.Sys.Fcntl.SetIsNonBlocking((IntPtr)fd, 1);
if (err == 0)
{
socketAddressLen = sockAddrLen;
errorCode = SocketError.Success;
acceptedFd = fd;
}
else
{
errorCode = GetSocketErrorForErrorCode(Interop.Sys.GetLastError());
acceptedFd = -1;
Interop.Sys.Close((IntPtr)fd);
}
return true;
}
acceptedFd = -1;
if (errno != Interop.Error.EAGAIN && errno != Interop.Error.EWOULDBLOCK)
{
errorCode = GetSocketErrorForErrorCode(errno);
return true;
}
errorCode = SocketError.Success;
return false;
}
public static unsafe bool TryStartConnect(int fileDescriptor, byte[] socketAddress, int socketAddressLen, out SocketError errorCode)
{
Debug.Assert(socketAddress != null);
Debug.Assert(socketAddressLen > 0);
Interop.Error err;
fixed (byte* rawSocketAddress = socketAddress)
{
err = Interop.Sys.Connect(fileDescriptor, rawSocketAddress, socketAddressLen);
}
if (err == Interop.Error.SUCCESS)
{
errorCode = SocketError.Success;
return true;
}
if (err != Interop.Error.EINPROGRESS)
{
errorCode = GetSocketErrorForErrorCode(err);
return true;
}
errorCode = SocketError.Success;
return false;
}
private static unsafe void PrimeForNextConnectAttempt(int fileDescriptor, int socketAddressLen)
{
Debug.Assert(SupportsMultipleConnectAttempts);
// On some platforms (e.g. Linux), a non-blocking socket that fails a connect() attempt
// needs to be kicked with another connect to AF_UNSPEC before further connect() attempts
// will return valid errors. Otherwise, further connect() attempts will return ECONNABORTED.
var sockAddr = stackalloc byte[socketAddressLen];
Interop.Error afErr = Interop.Sys.SetAddressFamily(sockAddr, socketAddressLen, (int)AddressFamily.Unspecified);
Debug.Assert(afErr == Interop.Error.SUCCESS, "PrimeForNextConnectAttempt: failed to set address family");
Interop.Error err = Interop.Sys.Connect(fileDescriptor, sockAddr, socketAddressLen);
Debug.Assert(err == Interop.Error.SUCCESS, "PrimeForNextConnectAttempt: failed to disassociate socket after failed connect()");
}
public static unsafe bool TryCompleteConnect(int fileDescriptor, int socketAddressLen, out SocketError errorCode)
{
Interop.Error socketError;
Interop.Error err = Interop.Sys.GetSocketErrorOption(fileDescriptor, &socketError);
if (err != Interop.Error.SUCCESS)
{
Debug.Assert(err == Interop.Error.EBADF);
errorCode = SocketError.SocketError;
return true;
}
if (socketError == Interop.Error.SUCCESS)
{
errorCode = SocketError.Success;
return true;
}
else if (socketError == Interop.Error.EINPROGRESS)
{
errorCode = SocketError.Success;
return false;
}
errorCode = GetSocketErrorForErrorCode(socketError);
if (SupportsMultipleConnectAttempts)
{
PrimeForNextConnectAttempt(fileDescriptor, socketAddressLen);
}
return true;
}
public static bool TryCompleteReceiveFrom(int fileDescriptor, byte[] buffer, int offset, int count, SocketFlags flags, byte[] socketAddress, ref int socketAddressLen, out int bytesReceived, out SocketFlags receivedFlags, out SocketError errorCode)
{
return TryCompleteReceiveFrom(fileDescriptor, buffer, null, offset, count, flags, socketAddress, ref socketAddressLen, out bytesReceived, out receivedFlags, out errorCode);
}
public static bool TryCompleteReceiveFrom(int fileDescriptor, IList<ArraySegment<byte>> buffers, SocketFlags flags, byte[] socketAddress, ref int socketAddressLen, out int bytesReceived, out SocketFlags receivedFlags, out SocketError errorCode)
{
return TryCompleteReceiveFrom(fileDescriptor, null, buffers, 0, 0, flags, socketAddress, ref socketAddressLen, out bytesReceived, out receivedFlags, out errorCode);
}
public static unsafe bool TryCompleteReceiveFrom(int fileDescriptor, byte[] buffer, IList<ArraySegment<byte>> buffers, int offset, int count, SocketFlags flags, byte[] socketAddress, ref int socketAddressLen, out int bytesReceived, out SocketFlags receivedFlags, out SocketError errorCode)
{
int available;
Interop.Error errno = Interop.Sys.GetBytesAvailable(fileDescriptor, &available);
if (errno != Interop.Error.SUCCESS)
{
bytesReceived = 0;
receivedFlags = 0;
errorCode = GetSocketErrorForErrorCode(errno);
return true;
}
if (available == 0)
{
// Always request at least one byte.
available = 1;
}
int received;
if (buffer != null)
{
received = Receive(fileDescriptor, flags, available, buffer, offset, count, socketAddress, ref socketAddressLen, out receivedFlags, out errno);
}
else
{
received = Receive(fileDescriptor, flags, available, buffers, socketAddress, ref socketAddressLen, out receivedFlags, out errno);
}
if (received != -1)
{
bytesReceived = received;
errorCode = SocketError.Success;
return true;
}
bytesReceived = 0;
if (errno != Interop.Error.EAGAIN && errno != Interop.Error.EWOULDBLOCK)
{
errorCode = GetSocketErrorForErrorCode(errno);
return true;
}
errorCode = SocketError.Success;
return false;
}
public static unsafe bool TryCompleteReceiveMessageFrom(int fileDescriptor, byte[] buffer, int offset, int count, SocketFlags flags, byte[] socketAddress, ref int socketAddressLen, bool isIPv4, bool isIPv6, out int bytesReceived, out SocketFlags receivedFlags, out IPPacketInformation ipPacketInformation, out SocketError errorCode)
{
int available;
Interop.Error errno = Interop.Sys.GetBytesAvailable(fileDescriptor, &available);
if (errno != Interop.Error.SUCCESS)
{
bytesReceived = 0;
receivedFlags = 0;
ipPacketInformation = default(IPPacketInformation);
errorCode = GetSocketErrorForErrorCode(errno);
return true;
}
if (available == 0)
{
// Always request at least one byte.
available = 1;
}
int received = ReceiveMessageFrom(fileDescriptor, flags, available, buffer, offset, count, socketAddress, ref socketAddressLen, isIPv4, isIPv6, out receivedFlags, out ipPacketInformation, out errno);
if (received != -1)
{
bytesReceived = received;
errorCode = SocketError.Success;
return true;
}
bytesReceived = 0;
if (errno != Interop.Error.EAGAIN && errno != Interop.Error.EWOULDBLOCK)
{
errorCode = GetSocketErrorForErrorCode(errno);
return true;
}
errorCode = SocketError.Success;
return false;
}
public static bool TryCompleteSendTo(int fileDescriptor, byte[] buffer, ref int offset, ref int count, SocketFlags flags, byte[] socketAddress, int socketAddressLen, ref int bytesSent, out SocketError errorCode)
{
int bufferIndex = 0;
return TryCompleteSendTo(fileDescriptor, buffer, null, ref bufferIndex, ref offset, ref count, flags, socketAddress, socketAddressLen, ref bytesSent, out errorCode);
}
public static bool TryCompleteSendTo(int fileDescriptor, IList<ArraySegment<byte>> buffers, ref int bufferIndex, ref int offset, SocketFlags flags, byte[] socketAddress, int socketAddressLen, ref int bytesSent, out SocketError errorCode)
{
int count = 0;
return TryCompleteSendTo(fileDescriptor, null, buffers, ref bufferIndex, ref offset, ref count, flags, socketAddress, socketAddressLen, ref bytesSent, out errorCode);
}
public static bool TryCompleteSendTo(int fileDescriptor, byte[] buffer, IList<ArraySegment<byte>> buffers, ref int bufferIndex, ref int offset, ref int count, SocketFlags flags, byte[] socketAddress, int socketAddressLen, ref int bytesSent, out SocketError errorCode)
{
for (;;)
{
int sent;
Interop.Error errno;
if (buffer != null)
{
sent = Send(fileDescriptor, flags, buffer, ref offset, ref count, socketAddress, socketAddressLen, out errno);
}
else
{
sent = Send(fileDescriptor, flags, buffers, ref bufferIndex, ref offset, socketAddress, socketAddressLen, out errno);
}
if (sent == -1)
{
if (errno != Interop.Error.EAGAIN && errno != Interop.Error.EWOULDBLOCK)
{
errorCode = GetSocketErrorForErrorCode(errno);
return true;
}
errorCode = SocketError.Success;
return false;
}
bytesSent += sent;
bool isComplete = sent == 0 ||
(buffer != null && count == 0) ||
(buffers != null && bufferIndex == buffers.Count);
if (isComplete)
{
errorCode = SocketError.Success;
return true;
}
}
}
public static SocketError SetBlocking(SafeCloseSocket handle, bool shouldBlock, out bool willBlock)
{
// NOTE: since we need to emulate blocking I/O on *nix (!), this does NOT change the blocking
// mode of the socket. Instead, it toggles a bit on the handle to indicate whether or not
// the PAL methods with blocking semantics should retry in the case of an operation that
// cannot be completed synchronously.
handle.IsNonBlocking = !shouldBlock;
willBlock = shouldBlock;
return SocketError.Success;
}
public static unsafe SocketError GetSockName(SafeCloseSocket handle, byte[] buffer, ref int nameLen)
{
Interop.Error err;
int addrLen = nameLen;
fixed (byte* rawBuffer = buffer)
{
err = Interop.Sys.GetSockName(handle.FileDescriptor, rawBuffer, &addrLen);
}
nameLen = addrLen;
return err == Interop.Error.SUCCESS ? SocketError.Success : GetSocketErrorForErrorCode(err);
}
public static unsafe SocketError GetAvailable(SafeCloseSocket handle, out int available)
{
int value = 0;
Interop.Error err = Interop.Sys.GetBytesAvailable(handle.FileDescriptor, &value);
available = value;
return err == Interop.Error.SUCCESS ? SocketError.Success : GetSocketErrorForErrorCode(err);
}
public static unsafe SocketError GetPeerName(SafeCloseSocket handle, byte[] buffer, ref int nameLen)
{
Interop.Error err;
int addrLen = nameLen;
fixed (byte* rawBuffer = buffer)
{
err = Interop.Sys.GetPeerName(handle.FileDescriptor, rawBuffer, &addrLen);
}
nameLen = addrLen;
return err == Interop.Error.SUCCESS ? SocketError.Success : GetSocketErrorForErrorCode(err);
}
public static unsafe SocketError Bind(SafeCloseSocket handle, byte[] buffer, int nameLen)
{
Interop.Error err;
fixed (byte* rawBuffer = buffer)
{
err = Interop.Sys.Bind(handle.FileDescriptor, rawBuffer, nameLen);
}
return err == Interop.Error.SUCCESS ? SocketError.Success : GetSocketErrorForErrorCode(err);
}
public static SocketError Listen(SafeCloseSocket handle, int backlog)
{
Interop.Error err = Interop.Sys.Listen(handle.FileDescriptor, backlog);
return err == Interop.Error.SUCCESS ? SocketError.Success : GetSocketErrorForErrorCode(err);
}
public static SocketError Accept(SafeCloseSocket handle, byte[] buffer, ref int nameLen, out SafeCloseSocket socket)
{
return SafeCloseSocket.Accept(handle, buffer, ref nameLen, out socket);
}
public static SocketError Connect(SafeCloseSocket handle, byte[] socketAddress, int socketAddressLen)
{
if (!handle.IsNonBlocking)
{
return handle.AsyncContext.Connect(socketAddress, socketAddressLen, -1);
}
SocketError errorCode;
bool completed = TryStartConnect(handle.FileDescriptor, socketAddress, socketAddressLen, out errorCode);
return completed ? errorCode : SocketError.WouldBlock;
}
public static SocketError Disconnect(Socket socket, SafeCloseSocket handle, bool reuseSocket)
{
throw new PlatformNotSupportedException();
}
public static SocketError Send(SafeCloseSocket handle, IList<ArraySegment<byte>> buffers, SocketFlags socketFlags, out int bytesTransferred)
{
var bufferList = buffers;
if (!handle.IsNonBlocking)
{
return handle.AsyncContext.Send(bufferList, socketFlags, handle.SendTimeout, out bytesTransferred);
}
bytesTransferred = 0;
int bufferIndex = 0;
int offset = 0;
SocketError errorCode;
bool completed = TryCompleteSendTo(handle.FileDescriptor, bufferList, ref bufferIndex, ref offset, socketFlags, null, 0, ref bytesTransferred, out errorCode);
return completed ? errorCode : SocketError.WouldBlock;
}
public static SocketError Send(SafeCloseSocket handle, byte[] buffer, int offset, int count, SocketFlags socketFlags, out int bytesTransferred)
{
if (!handle.IsNonBlocking)
{
return handle.AsyncContext.Send(buffer, offset, count, socketFlags, handle.SendTimeout, out bytesTransferred);
}
bytesTransferred = 0;
SocketError errorCode;
bool completed = TryCompleteSendTo(handle.FileDescriptor, buffer, ref offset, ref count, socketFlags, null, 0, ref bytesTransferred, out errorCode);
return completed ? errorCode : SocketError.WouldBlock;
}
public static SocketError SendTo(SafeCloseSocket handle, byte[] buffer, int offset, int count, SocketFlags socketFlags, byte[] socketAddress, int socketAddressLen, out int bytesTransferred)
{
if (!handle.IsNonBlocking)
{
return handle.AsyncContext.SendTo(buffer, offset, count, socketFlags, socketAddress, socketAddressLen, handle.SendTimeout, out bytesTransferred);
}
bytesTransferred = 0;
SocketError errorCode;
bool completed = TryCompleteSendTo(handle.FileDescriptor, buffer, ref offset, ref count, socketFlags, socketAddress, socketAddressLen, ref bytesTransferred, out errorCode);
return completed ? errorCode : SocketError.WouldBlock;
}
public static SocketError Receive(SafeCloseSocket handle, IList<ArraySegment<byte>> buffers, ref SocketFlags socketFlags, out int bytesTransferred)
{
SocketError errorCode;
if (!handle.IsNonBlocking)
{
errorCode = handle.AsyncContext.Receive(buffers, ref socketFlags, handle.ReceiveTimeout, out bytesTransferred);
}
else
{
int socketAddressLen = 0;
if (!TryCompleteReceiveFrom(handle.FileDescriptor, buffers, socketFlags, null, ref socketAddressLen, out bytesTransferred, out socketFlags, out errorCode))
{
errorCode = SocketError.WouldBlock;
}
}
return errorCode;
}
public static SocketError Receive(SafeCloseSocket handle, byte[] buffer, int offset, int count, SocketFlags socketFlags, out int bytesTransferred)
{
if (!handle.IsNonBlocking)
{
return handle.AsyncContext.Receive(buffer, offset, count, ref socketFlags, handle.ReceiveTimeout, out bytesTransferred);
}
int socketAddressLen = 0;
SocketError errorCode;
bool completed = TryCompleteReceiveFrom(handle.FileDescriptor, buffer, offset, count, socketFlags, null, ref socketAddressLen, out bytesTransferred, out socketFlags, out errorCode);
return completed ? errorCode : SocketError.WouldBlock;
}
public static SocketError ReceiveMessageFrom(Socket socket, SafeCloseSocket handle, byte[] buffer, int offset, int count, ref SocketFlags socketFlags, Internals.SocketAddress socketAddress, out Internals.SocketAddress receiveAddress, out IPPacketInformation ipPacketInformation, out int bytesTransferred)
{
byte[] socketAddressBuffer = socketAddress.Buffer;
int socketAddressLen = socketAddress.Size;
bool isIPv4, isIPv6;
Socket.GetIPProtocolInformation(socket.AddressFamily, socketAddress, out isIPv4, out isIPv6);
SocketError errorCode;
if (!handle.IsNonBlocking)
{
errorCode = handle.AsyncContext.ReceiveMessageFrom(buffer, offset, count, ref socketFlags, socketAddressBuffer, ref socketAddressLen, isIPv4, isIPv6, handle.ReceiveTimeout, out ipPacketInformation, out bytesTransferred);
}
else
{
if (!TryCompleteReceiveMessageFrom(handle.FileDescriptor, buffer, offset, count, socketFlags, socketAddressBuffer, ref socketAddressLen, isIPv4, isIPv6, out bytesTransferred, out socketFlags, out ipPacketInformation, out errorCode))
{
errorCode = SocketError.WouldBlock;
}
}
socketAddress.InternalSize = socketAddressLen;
receiveAddress = socketAddress;
return errorCode;
}
public static SocketError ReceiveFrom(SafeCloseSocket handle, byte[] buffer, int offset, int count, SocketFlags socketFlags, byte[] socketAddress, ref int socketAddressLen, out int bytesTransferred)
{
if (!handle.IsNonBlocking)
{
return handle.AsyncContext.ReceiveFrom(buffer, offset, count, ref socketFlags, socketAddress, ref socketAddressLen, handle.ReceiveTimeout, out bytesTransferred);
}
SocketError errorCode;
bool completed = TryCompleteReceiveFrom(handle.FileDescriptor, buffer, offset, count, socketFlags, socketAddress, ref socketAddressLen, out bytesTransferred, out socketFlags, out errorCode);
return completed ? errorCode : SocketError.WouldBlock;
}
public static SocketError Ioctl(SafeCloseSocket handle, int ioControlCode, byte[] optionInValue, byte[] optionOutValue, out int optionLength)
{
// TODO: can this be supported in some reasonable fashion?
throw new PlatformNotSupportedException();
}
public static SocketError IoctlInternal(SafeCloseSocket handle, IOControlCode ioControlCode, IntPtr optionInValue, int inValueLength, IntPtr optionOutValue, int outValueLength, out int optionLength)
{
// TODO: can this be supported in some reasonable fashion?
throw new PlatformNotSupportedException();
}
public static unsafe SocketError SetSockOpt(SafeCloseSocket handle, SocketOptionLevel optionLevel, SocketOptionName optionName, int optionValue)
{
if (optionLevel == SocketOptionLevel.Socket)
{
if (optionName == SocketOptionName.ReceiveTimeout)
{
handle.ReceiveTimeout = optionValue == 0 ? -1 : optionValue;
return SocketError.Success;
}
else if (optionName == SocketOptionName.SendTimeout)
{
handle.SendTimeout = optionValue == 0 ? -1 : optionValue;
return SocketError.Success;
}
}
Interop.Error err = Interop.Sys.SetSockOpt(handle.FileDescriptor, optionLevel, optionName, (byte*)&optionValue, sizeof(int));
return err == Interop.Error.SUCCESS ? SocketError.Success : GetSocketErrorForErrorCode(err);
}
public static unsafe SocketError SetSockOpt(SafeCloseSocket handle, SocketOptionLevel optionLevel, SocketOptionName optionName, byte[] optionValue)
{
Interop.Error err;
if (optionValue == null || optionValue.Length == 0)
{
err = Interop.Sys.SetSockOpt(handle.FileDescriptor, optionLevel, optionName, null, 0);
}
else
{
fixed (byte* pinnedValue = optionValue)
{
err = Interop.Sys.SetSockOpt(handle.FileDescriptor, optionLevel, optionName, pinnedValue, optionValue.Length);
}
}
return err == Interop.Error.SUCCESS ? SocketError.Success : GetSocketErrorForErrorCode(err);
}
public static unsafe SocketError SetMulticastOption(SafeCloseSocket handle, SocketOptionName optionName, MulticastOption optionValue)
{
Debug.Assert(optionName == SocketOptionName.AddMembership || optionName == SocketOptionName.DropMembership);
Interop.Sys.MulticastOption optName = optionName == SocketOptionName.AddMembership ?
Interop.Sys.MulticastOption.MULTICAST_ADD :
Interop.Sys.MulticastOption.MULTICAST_DROP;
var opt = new Interop.Sys.IPv4MulticastOption {
MulticastAddress = unchecked((uint)optionValue.Group.GetAddress()),
LocalAddress = unchecked((uint)optionValue.LocalAddress.GetAddress()),
InterfaceIndex = optionValue.InterfaceIndex
};
Interop.Error err = Interop.Sys.SetIPv4MulticastOption(handle.FileDescriptor, optName, &opt);
return err == Interop.Error.SUCCESS ? SocketError.Success : GetSocketErrorForErrorCode(err);
}
public static unsafe SocketError SetIPv6MulticastOption(SafeCloseSocket handle, SocketOptionName optionName, IPv6MulticastOption optionValue)
{
Debug.Assert(optionName == SocketOptionName.AddMembership || optionName == SocketOptionName.DropMembership);
Interop.Sys.MulticastOption optName = optionName == SocketOptionName.AddMembership ?
Interop.Sys.MulticastOption.MULTICAST_ADD :
Interop.Sys.MulticastOption.MULTICAST_DROP;
var opt = new Interop.Sys.IPv6MulticastOption {
Address = optionValue.Group.GetNativeIPAddress(),
InterfaceIndex = (int)optionValue.InterfaceIndex
};
Interop.Error err = Interop.Sys.SetIPv6MulticastOption(handle.FileDescriptor, optName, &opt);
return err == Interop.Error.SUCCESS ? SocketError.Success : GetSocketErrorForErrorCode(err);
}
public static unsafe SocketError SetLingerOption(SafeCloseSocket handle, LingerOption optionValue)
{
var opt = new Interop.Sys.LingerOption {
OnOff = optionValue.Enabled ? 1 : 0,
Seconds = optionValue.LingerTime
};
Interop.Error err = Interop.Sys.SetLingerOption(handle.FileDescriptor, &opt);
return err == Interop.Error.SUCCESS ? SocketError.Success : GetSocketErrorForErrorCode(err);
}
public static void SetReceivingDualModeIPv4PacketInformation(Socket socket)
{
// NOTE: some platforms (e.g. OS X) do not support receiving IPv4 packet information for packets received
// on dual-mode sockets. On these platforms, this call is a no-op.
if (SupportsDualModeIPv4PacketInfo)
{
socket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.PacketInformation, true);
}
}
public static unsafe SocketError GetSockOpt(SafeCloseSocket handle, SocketOptionLevel optionLevel, SocketOptionName optionName, out int optionValue)
{
if (optionLevel == SocketOptionLevel.Socket)
{
if (optionName == SocketOptionName.ReceiveTimeout)
{
optionValue = handle.ReceiveTimeout == -1 ? 0 : handle.ReceiveTimeout;
return SocketError.Success;
}
else if (optionName == SocketOptionName.SendTimeout)
{
optionValue = handle.SendTimeout == -1 ? 0 : handle.SendTimeout;
return SocketError.Success;
}
}
int value = 0;
int optLen = sizeof(int);
Interop.Error err = Interop.Sys.GetSockOpt(handle.FileDescriptor, optionLevel, optionName, (byte*)&value, &optLen);
optionValue = value;
return err == Interop.Error.SUCCESS ? SocketError.Success : GetSocketErrorForErrorCode(err);
}
public static unsafe SocketError GetSockOpt(SafeCloseSocket handle, SocketOptionLevel optionLevel, SocketOptionName optionName, byte[] optionValue, ref int optionLength)
{
int optLen = optionLength;
Interop.Error err;
if (optionValue == null || optionValue.Length == 0)
{
optLen = 0;
err = Interop.Sys.GetSockOpt(handle.FileDescriptor, optionLevel, optionName, null, &optLen);
}
else
{
fixed (byte* pinnedValue = optionValue)
{
err = Interop.Sys.GetSockOpt(handle.FileDescriptor, optionLevel, optionName, pinnedValue, &optLen);
}
}
if (err == Interop.Error.SUCCESS)
{
optionLength = optLen;
return SocketError.Success;
}
return GetSocketErrorForErrorCode(err);
}
public static unsafe SocketError GetMulticastOption(SafeCloseSocket handle, SocketOptionName optionName, out MulticastOption optionValue)
{
Debug.Assert(optionName == SocketOptionName.AddMembership || optionName == SocketOptionName.DropMembership);
Interop.Sys.MulticastOption optName = optionName == SocketOptionName.AddMembership ?
Interop.Sys.MulticastOption.MULTICAST_ADD :
Interop.Sys.MulticastOption.MULTICAST_DROP;
Interop.Sys.IPv4MulticastOption opt;
Interop.Error err = Interop.Sys.GetIPv4MulticastOption(handle.FileDescriptor, optName, &opt);
if (err != Interop.Error.SUCCESS)
{
optionValue = default(MulticastOption);
return GetSocketErrorForErrorCode(err);
}
var multicastAddress = new IPAddress((long)opt.MulticastAddress);
var localAddress = new IPAddress((long)opt.LocalAddress);
optionValue = new MulticastOption(multicastAddress, localAddress) {
InterfaceIndex = opt.InterfaceIndex
};
return SocketError.Success;
}
public static unsafe SocketError GetIPv6MulticastOption(SafeCloseSocket handle, SocketOptionName optionName, out IPv6MulticastOption optionValue)
{
Debug.Assert(optionName == SocketOptionName.AddMembership || optionName == SocketOptionName.DropMembership);
Interop.Sys.MulticastOption optName = optionName == SocketOptionName.AddMembership ?
Interop.Sys.MulticastOption.MULTICAST_ADD :
Interop.Sys.MulticastOption.MULTICAST_DROP;
Interop.Sys.IPv6MulticastOption opt;
Interop.Error err = Interop.Sys.GetIPv6MulticastOption(handle.FileDescriptor, optName, &opt);
if (err != Interop.Error.SUCCESS)
{
optionValue = default(IPv6MulticastOption);
return GetSocketErrorForErrorCode(err);
}
optionValue = new IPv6MulticastOption(opt.Address.GetIPAddress(), opt.InterfaceIndex);
return SocketError.Success;
}
public static unsafe SocketError GetLingerOption(SafeCloseSocket handle, out LingerOption optionValue)
{
var opt = new Interop.Sys.LingerOption();
Interop.Error err = Interop.Sys.GetLingerOption(handle.FileDescriptor, &opt);
if (err != Interop.Error.SUCCESS)
{
optionValue = default(LingerOption);
return GetSocketErrorForErrorCode(err);
}
optionValue = new LingerOption(opt.OnOff != 0, opt.Seconds);
return SocketError.Success;
}
public static unsafe SocketError Poll(SafeCloseSocket handle, int microseconds, SelectMode mode, out bool status)
{
uint* fdSet = stackalloc uint[Interop.Sys.FD_SETSIZE_UINTS];
Interop.Sys.FD_ZERO(fdSet);
Interop.Sys.FD_SET(handle.FileDescriptor, fdSet);
int fdCount = 0;
uint* readFds = null;
uint* writeFds = null;
uint* errorFds = null;
switch (mode)
{
case SelectMode.SelectRead:
readFds = fdSet;
fdCount = handle.FileDescriptor + 1;
break;
case SelectMode.SelectWrite:
writeFds = fdSet;
fdCount = handle.FileDescriptor + 1;
break;
case SelectMode.SelectError:
errorFds = fdSet;
fdCount = handle.FileDescriptor + 1;
break;
}
int socketCount = 0;
Interop.Error err = Interop.Sys.Select(fdCount, readFds, writeFds, errorFds, microseconds, &socketCount);
if (err != Interop.Error.SUCCESS)
{
status = false;
return GetSocketErrorForErrorCode(err);
}
status = Interop.Sys.FD_ISSET(handle.FileDescriptor, fdSet);
return SocketError.Success;
}
public static unsafe SocketError Select(IList checkRead, IList checkWrite, IList checkError, int microseconds)
{
uint* readSet = stackalloc uint[Interop.Sys.FD_SETSIZE_UINTS];
int maxReadFd = Socket.FillFdSetFromSocketList(readSet, checkRead);
uint* writeSet = stackalloc uint[Interop.Sys.FD_SETSIZE_UINTS];
int maxWriteFd = Socket.FillFdSetFromSocketList(writeSet, checkWrite);
uint* errorSet = stackalloc uint[Interop.Sys.FD_SETSIZE_UINTS];
int maxErrorFd = Socket.FillFdSetFromSocketList(errorSet, checkError);
int fdCount = 0;
uint* readFds = null;
uint* writeFds = null;
uint* errorFds = null;
if (maxReadFd != 0)
{
readFds = readSet;
fdCount = maxReadFd;
}
if (maxWriteFd != 0)
{
writeFds = writeSet;
if (maxWriteFd > fdCount)
{
fdCount = maxWriteFd;
}
}
if (maxErrorFd != 0)
{
errorFds = errorSet;
if (maxErrorFd > fdCount)
{
fdCount = maxErrorFd;
}
}
int socketCount;
Interop.Error err = Interop.Sys.Select(fdCount, readFds, writeFds, errorFds, microseconds, &socketCount);
if (GlobalLog.IsEnabled)
{
GlobalLog.Print("Socket::Select() Interop.Sys.Select returns socketCount:" + socketCount);
}
if (err != Interop.Error.SUCCESS)
{
return GetSocketErrorForErrorCode(err);
}
Socket.FilterSocketListUsingFdSet(readSet, checkRead);
Socket.FilterSocketListUsingFdSet(writeSet, checkWrite);
Socket.FilterSocketListUsingFdSet(errorSet, checkError);
return SocketError.Success;
}
public static SocketError Shutdown(SafeCloseSocket handle, bool isConnected, bool isDisconnected, SocketShutdown how)
{
Interop.Error err = Interop.Sys.Shutdown(handle.FileDescriptor, how);
if (err == Interop.Error.SUCCESS)
{
return SocketError.Success;
}
// If shutdown returns ENOTCONN and we think that this socket has ever been connected,
// ignore the error. This can happen for TCP connections if the underlying connection
// has reached the CLOSE state. Ignoring the error matches Winsock behavior.
if (err == Interop.Error.ENOTCONN && (isConnected || isDisconnected))
{
return SocketError.Success;
}
return GetSocketErrorForErrorCode(err);
}
public static SocketError ConnectAsync(Socket socket, SafeCloseSocket handle, byte[] socketAddress, int socketAddressLen, ConnectOverlappedAsyncResult asyncResult)
{
return handle.AsyncContext.ConnectAsync(socketAddress, socketAddressLen, asyncResult.CompletionCallback);
}
public static SocketError SendAsync(SafeCloseSocket handle, byte[] buffer, int offset, int count, SocketFlags socketFlags, OverlappedAsyncResult asyncResult)
{
return handle.AsyncContext.SendAsync(buffer, offset, count, socketFlags, asyncResult.CompletionCallback);
}
public static SocketError SendAsync(SafeCloseSocket handle, IList<ArraySegment<byte>> buffers, SocketFlags socketFlags, OverlappedAsyncResult asyncResult)
{
return handle.AsyncContext.SendAsync(buffers, socketFlags, asyncResult.CompletionCallback);
}
public static SocketError SendToAsync(SafeCloseSocket handle, byte[] buffer, int offset, int count, SocketFlags socketFlags, Internals.SocketAddress socketAddress, OverlappedAsyncResult asyncResult)
{
asyncResult.SocketAddress = socketAddress;
return handle.AsyncContext.SendToAsync(buffer, offset, count, socketFlags, socketAddress.Buffer, socketAddress.Size, asyncResult.CompletionCallback);
}
public static SocketError ReceiveAsync(SafeCloseSocket handle, byte[] buffer, int offset, int count, SocketFlags socketFlags, OverlappedAsyncResult asyncResult)
{
return handle.AsyncContext.ReceiveAsync(buffer, offset, count, socketFlags, asyncResult.CompletionCallback);
}
public static SocketError ReceiveAsync(SafeCloseSocket handle, IList<ArraySegment<byte>> buffers, SocketFlags socketFlags, OverlappedAsyncResult asyncResult)
{
return handle.AsyncContext.ReceiveAsync(buffers, socketFlags, asyncResult.CompletionCallback);
}
public static SocketError ReceiveFromAsync(SafeCloseSocket handle, byte[] buffer, int offset, int count, SocketFlags socketFlags, Internals.SocketAddress socketAddress, OverlappedAsyncResult asyncResult)
{
asyncResult.SocketAddress = socketAddress;
return handle.AsyncContext.ReceiveFromAsync(buffer, offset, count, socketFlags, socketAddress.Buffer, socketAddress.InternalSize, asyncResult.CompletionCallback);
}
public static SocketError ReceiveMessageFromAsync(Socket socket, SafeCloseSocket handle, byte[] buffer, int offset, int count, SocketFlags socketFlags, Internals.SocketAddress socketAddress, ReceiveMessageOverlappedAsyncResult asyncResult)
{
asyncResult.SocketAddress = socketAddress;
bool isIPv4, isIPv6;
Socket.GetIPProtocolInformation(((Socket)asyncResult.AsyncObject).AddressFamily, socketAddress, out isIPv4, out isIPv6);
return handle.AsyncContext.ReceiveMessageFromAsync(buffer, offset, count, socketFlags, socketAddress.Buffer, socketAddress.InternalSize, isIPv4, isIPv6, asyncResult.CompletionCallback);
}
public static SocketError AcceptAsync(Socket socket, SafeCloseSocket handle, SafeCloseSocket acceptHandle, int receiveSize, int socketAddressSize, AcceptOverlappedAsyncResult asyncResult)
{
Debug.Assert(acceptHandle == null);
byte[] socketAddressBuffer = new byte[socketAddressSize];
return handle.AsyncContext.AcceptAsync(socketAddressBuffer, socketAddressSize, asyncResult.CompletionCallback);
}
}
}
| 42.156573 | 340 | 0.585827 | [
"MIT"
] | mellinoe/corefx | src/System.Net.Sockets/src/System/Net/Sockets/SocketPal.Unix.cs | 57,080 | C# |
// ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See License.txt in the repo root for license information.
// ------------------------------------------------------------
namespace LoadDriverLib
{
/// <summary>
/// The load test goes through the states in the enum below
/// </summary>
internal enum TestExecutorState : int
{
Uninitialized,
Initializing,
Initialized,
RunningWritePhase,
WritePhaseCompleted,
RunningReadPhase,
ReadPhaseCompleted
}
} | 30.952381 | 99 | 0.526154 | [
"MIT"
] | Azure-Samples/service-fabric-dotnet-performance | ServiceLoadTest/Framework/LoadDriverLib/TestExecutorState.cs | 652 | C# |
// *** WARNING: this file was generated by pulumigen. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.Kubernetes.Types.Inputs.Apps.V1Beta2
{
/// <summary>
/// DeploymentSpec is the specification of the desired behavior of the Deployment.
/// </summary>
public class DeploymentSpecArgs : Pulumi.ResourceArgs
{
/// <summary>
/// Minimum number of seconds for which a newly created pod should be ready without any of its container crashing, for it to be considered available. Defaults to 0 (pod will be considered available as soon as it is ready)
/// </summary>
[Input("minReadySeconds")]
public Input<int>? MinReadySeconds { get; set; }
/// <summary>
/// Indicates that the deployment is paused.
/// </summary>
[Input("paused")]
public Input<bool>? Paused { get; set; }
/// <summary>
/// The maximum time in seconds for a deployment to make progress before it is considered to be failed. The deployment controller will continue to process failed deployments and a condition with a ProgressDeadlineExceeded reason will be surfaced in the deployment status. Note that progress will not be estimated during the time a deployment is paused. Defaults to 600s.
/// </summary>
[Input("progressDeadlineSeconds")]
public Input<int>? ProgressDeadlineSeconds { get; set; }
/// <summary>
/// Number of desired pods. This is a pointer to distinguish between explicit zero and not specified. Defaults to 1.
/// </summary>
[Input("replicas")]
public Input<int>? Replicas { get; set; }
/// <summary>
/// The number of old ReplicaSets to retain to allow rollback. This is a pointer to distinguish between explicit zero and not specified. Defaults to 10.
/// </summary>
[Input("revisionHistoryLimit")]
public Input<int>? RevisionHistoryLimit { get; set; }
/// <summary>
/// Label selector for pods. Existing ReplicaSets whose pods are selected by this will be the ones affected by this deployment. It must match the pod template's labels.
/// </summary>
[Input("selector", required: true)]
public Input<Pulumi.Kubernetes.Types.Inputs.Meta.V1.LabelSelectorArgs> Selector { get; set; } = null!;
/// <summary>
/// The deployment strategy to use to replace existing pods with new ones.
/// </summary>
[Input("strategy")]
public Input<Pulumi.Kubernetes.Types.Inputs.Apps.V1Beta2.DeploymentStrategyArgs>? Strategy { get; set; }
/// <summary>
/// Template describes the pods that will be created.
/// </summary>
[Input("template", required: true)]
public Input<Pulumi.Kubernetes.Types.Inputs.Core.V1.PodTemplateSpecArgs> Template { get; set; } = null!;
public DeploymentSpecArgs()
{
}
}
}
| 44.211268 | 378 | 0.656579 | [
"Apache-2.0"
] | AaronFriel/pulumi-kubernetes | sdk/dotnet/Apps/V1Beta2/Inputs/DeploymentSpecArgs.cs | 3,139 | C# |
using Bogus.DataSets;
using Bogus.Extensions.Brazil;
using Bogus.Extensions.UnitedStates;
using FluentAssertions;
using Xunit;
namespace Bogus.Tests.DataSetTests
{
public class CompanyTest : SeededTest
{
public CompanyTest()
{
company = new Company();
}
private readonly Company company;
[Fact]
public void can_get_a_catch_phrase()
{
company.CatchPhrase().Should().Be("Phased background protocol");
}
[Fact]
public void can_get_a_company_name_with_custom_format()
{
company.CompanyName(0).Should().Be("Mitchell Inc");
}
[Fact]
public void can_get_company_bs_phrase()
{
company.Bs().Should().Be("maximize leading-edge schemas"); //lol
}
[Fact]
public void can_get_company_name()
{
company.CompanyName().Should().Be("Brown - Schultz");
}
[Fact]
public void can_get_company_suffix_array()
{
var arr = company.Suffexes();
arr.Length.Should().NotBe(0);
}
[Fact]
public void can_generate_cnpj_for_brazil()
{
company.Cnpj().Should().Be("61.860.606/0001-91");
}
[Fact]
public void can_generate_an_EIN()
{
company.Ein().Should().Be("61-8606064");
}
}
} | 21.532258 | 73 | 0.590262 | [
"MIT"
] | esteban1991/TestAsp | Source/Bogus.Tests/DataSetTests/CompanyTest.cs | 1,335 | C# |
/*
Copyright (c) 2019, John Lewin
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
The views and conclusions contained in the software and documentation are those
of the authors and should not be interpreted as representing official policies,
either expressed or implied, of the FreeBSD Project.
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using MatterHackers.Agg;
using MatterHackers.DataConverters3D;
using MatterHackers.MatterControl.SlicerConfiguration;
using MatterHackers.VectorMath;
namespace MatterHackers.gsBundle
{
public class SlaSlicer : IObjectSlicer
{
public async Task<bool> Slice(IEnumerable<IObject3D> printableItems, PrinterSettings printerSettings, string filePath, IProgress<ProgressStatus> progressReporter, CancellationToken cancellationToken)
{
using (var outputStream = File.OpenWrite(filePath))
{
foreach (var item in printableItems.Where(d => d.MeshPath != null))
{
//string sourceFilePath = await item.ResolveFilePath(null, cancellationToken);
//// Load Mesh
//if (File.Exists(sourceFilePath))
//{
// var mesh = StandardMeshReader.ReadMesh(sourceFilePath);
// if (mesh != null)
// {
// sourceMeshes.Add(mesh);
// }
// var printCenter = printerSettings.GetValue<Vector2>(SettingsKey.print_center);
// ApplyTransform(mesh, item.WorldMatrix(), printCenter);
//}
}
//var settings = LoadSettingsForPrinter(printerSettings);
// Construct slicer
//var slicer = new GeometrySlicer();
//slicer.SliceMeshes(sourceMeshes, settings);
//bool valid = slicer.ExtractResultsIfValid(out PrintMeshAssembly meshes, out PlanarSliceStack slices);
//// Construct GCode generator
//var pathGenerator = new ToolpathGenerator();
//pathGenerator.CreateToolPaths(meshes, slices, settings);
//// Write GCode file
//var gcodeWriter = new StandardGCodeWriter();
//var streamWriter = new StreamWriter(outputStream);
//gcodeWriter.WriteFile(pathGenerator.CurrentGCode, streamWriter);
return true;
}
}
public Dictionary<string, ExportField> Exports { get; } = new Dictionary<string, ExportField>()
{
[SettingsKey.bed_size] = new ExportField(""),
[SettingsKey.build_height] = new ExportField(""),
[SettingsKey.make] = new ExportField(""),
[SettingsKey.model] = new ExportField(""),
[SettingsKey.resin_cost] = new ExportField(""),
[SettingsKey.resin_density] = new ExportField(""),
[SettingsKey.sla_auto_support] = new ExportField(""),
[SettingsKey.sla_base_exposure_time] = new ExportField(""),
[SettingsKey.sla_base_min_off_time] = new ExportField(""),
[SettingsKey.sla_min_off_time] = new ExportField(""),
[SettingsKey.sla_base_lift_distance] = new ExportField(""),
[SettingsKey.sla_lift_distance] = new ExportField(""),
[SettingsKey.sla_base_lift_speed] = new ExportField(""),
[SettingsKey.sla_lift_speed] = new ExportField(""),
[SettingsKey.sla_base_layers] = new ExportField(""),
[SettingsKey.sla_create_raft] = new ExportField(""),
[SettingsKey.sla_exposure_time] = new ExportField(""),
[SettingsKey.sla_layer_height] = new ExportField(""),
[SettingsKey.sla_printable_area_inset] = new ExportField(""),
[SettingsKey.sla_resolution] = new ExportField(""),
[SettingsKey.slice_engine] = new ExportField(""),
[SettingsKey.sla_mirror_mode] = new ExportField(""),
[SettingsKey.sla_decend_speed] = new ExportField(""),
};
public bool ValidateFile(string filePath)
{
// TODO: Implement solution
System.Diagnostics.Debugger.Break();
return true;
}
public PrinterType PrinterType => PrinterType.SLA;
}
}
| 39.03937 | 201 | 0.745865 | [
"BSD-2-Clause"
] | Bhalddin/MatterControl | MatterControl.SLA/Slicer/SlaSlicer.cs | 4,960 | C# |
using System.Collections.Generic;
using System.Linq;
using UnitTest.Domain.Entity;
using UnitTest.Domain.Interface;
namespace UnitTest.Infra.Repositories
{
public class Repository : IRepository
{
private readonly Context _context;
public Repository(Context context)
{
_context = context;
}
public Category GetCategoryByName(string categoryName)
{
return _context.Categories.FirstOrDefault(x => x.Name.ToLower() == categoryName);
}
public Author GetAuthorByName(string authorName)
{
return _context.Authors.FirstOrDefault(x => x.Name.ToLower() == authorName.ToLower());
}
public Book GetBookByName(string bookName)
{
return _context.Books.FirstOrDefault(x => x.Title.ToLower() == bookName.ToLower());
}
public List<Book> GetBooksByAuthor(string authorName)
{
return _context.Books
.Where(x => x.Author.Name.ToLower() == authorName.ToLower())
.ToList();
}
public void AddBook(Book book)
{
_context.Books.Add(book);
_context.SaveChanges();
}
public void AddAuthor(Author author)
{
_context.Authors.Add(author);
_context.SaveChanges();
}
public void AddCategory(Category category)
{
_context.Categories.Add(category);
_context.SaveChanges();
}
}
} | 25.114754 | 98 | 0.582245 | [
"MIT"
] | Berthot/UnitTests | UnitTest.Infra/Repositories/Repository.cs | 1,532 | C# |
using Newtonsoft.Json;
namespace ChartMogul.API.Models.Enrichment
{
public class ClearbitModel
{
[JsonProperty(PropertyName = "person")]
public Person Person { get; set; }
[JsonProperty(PropertyName = "company")]
public Company Company { get; set; }
}
public class Company
{
[JsonProperty(PropertyName = "name")]
public string Name { get; set; }
[JsonProperty(PropertyName = "legalName")]
public string LegalName { get; set; }
[JsonProperty(PropertyName = "domain")]
public string Domain { get; set; }
[JsonProperty(PropertyName = "url")]
public string Url { get; set; }
[JsonProperty(PropertyName = "category")]
public Category Category { get; set; }
[JsonProperty(PropertyName = "metrics")]
public Metrics Metrics { get; set; }
}
public class Metrics
{
[JsonProperty(PropertyName = "raised")]
public string Raised { get; set; }
[JsonProperty(PropertyName = "employees")]
public string Employees { get; set; }
[JsonProperty(PropertyName = "googleRank")]
public string GoogleRank { get; set; }
[JsonProperty(PropertyName = "alexaGlobalRank")]
public string AlexaGlobalRank { get; set; }
[JsonProperty(PropertyName = "marketCap")]
public string MarketCap { get; set; }
}
public class Category
{
[JsonProperty(PropertyName = "sector")]
public string Sector { get; set; }
[JsonProperty(PropertyName = "industryGroup")]
public string IndustryGroup { get; set; }
[JsonProperty(PropertyName = "industry")]
public string Industry { get; set; }
[JsonProperty(PropertyName = "subIndustry")]
public string SubIndustry { get; set; }
}
public class Person
{
[JsonProperty(PropertyName = "name")]
public Name Name { get; set; }
[JsonProperty(PropertyName = "employment")]
public Employment Employment { get; set; }
}
public class Employment
{
[JsonProperty(PropertyName = "name")]
public string Name { get; set; }
}
public class Name
{
[JsonProperty(PropertyName = "fullName")]
public string FullName { get; set; }
}
} | 27.267442 | 56 | 0.598294 | [
"MIT"
] | john-craft/chartmogul-dotnet | ChartMogul/Models/Enrichment/ClearbitModel.cs | 2,347 | C# |
using LuisTools.Domain.Contracts;
using System.Collections.Generic;
using System.IO;
using System.Linq;
namespace LuisTools.Data.Disk
{
public class LuDownWriter : ILuDownWriter
{
private readonly ILogger _log;
public LuDownWriter(ILogger logger)
{
_log = logger;
}
public int Write(string outputFolder, string originalFileName, List<string> linesToWrite)
{
_log.Enter(this);
var fileInfo = new FileInfo(originalFileName);
var destinationFileName = fileInfo.Name.Split('.')[0] + ".lu";
var finalFilePath = Path.Combine(outputFolder, destinationFileName);
if (!Directory.Exists(outputFolder))
{
Directory.CreateDirectory(outputFolder);
}
File.WriteAllLines(finalFilePath, linesToWrite);
return linesToWrite.Count();
}
}
}
| 27.114286 | 97 | 0.60274 | [
"MIT"
] | digitaldias/LuisTools | NuanceToLuis/LuisTools.Data.Disk/LuDownWriter.cs | 951 | C# |
namespace Rest4GP.Core.Parameters
{
/// <summary>
/// Parameters used for the query
/// </summary>
public class RestParameters
{
/// <summary>
/// Number of elements to fetch
/// </summary>
public int Take { get; set; }
/// <summary>
/// Number of elements to skip
/// </summary>
public int Skip { get; set; }
/// <summary>
/// Sort by
/// </summary>
public RestSort Sort { get; set; }
/// <summary>
/// Filter to apply
/// </summary>
public RestFilter Filter { get; set; }
/// <summary>
/// Smart filter
/// </summary>
public RestSmartFilter SmartFilter { get; set; }
/// <summary>
/// True if the response has to contains the count field
/// </summary>
public bool WithCount { get; set; } = false;
}
} | 22.804878 | 64 | 0.485561 | [
"MIT"
] | PiGi78/Rest4GP | Rest4GP.Core/Parameters/RestParameters.cs | 935 | C# |
namespace Anthill.AI
{
public class AntAIAction
{
public int cost; // Цена действия.
public string name; // Имя действия.
public string state; // Имя состояния связанного с этим действием.
public AntAICondition pre; // Предстоящие условия.
public AntAICondition post; // Последующие условия.
public AntAIAction(string aName, int aCost = 1)
{
cost = aCost;
name = aName;
state = aName;
pre = new AntAICondition();
post = new AntAICondition();
}
}
} | 25.45 | 75 | 0.656189 | [
"MIT"
] | AntKarlov/GOAP | Assets/Libraries/Anthill/AI/AntAIAction.cs | 604 | C# |
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.AspNetCore.Mvc.Rendering;
using HairSalon.Models;
using System.Collections.Generic;
using System.Linq;
namespace HairSalon.Controllers
{
public class ClientsController : Controller
{
private readonly HairSalonContext _db;
public ClientsController(HairSalonContext db)
{
_db = db;
}
public ActionResult Index()
{
List<Client> model = _db.Clients.Include(client => client.Stylist).ToList();
return View(model);
}
public ActionResult Create()
{
ViewBag.StylistId = new SelectList(_db.Stylists, "StylistId", "Name");
return View();
}
[HttpPost]
public ActionResult Create(Client client)
{
_db.Clients.Add(client);
_db.SaveChanges();
return RedirectToAction("Index");
}
public ActionResult Details(int id)
{
Client thisClient = _db.Clients.Include(client => client.Stylist).FirstOrDefault(client => client.ClientId == id);
return View(thisClient);
}
public ActionResult Edit(int id)
{
Client thisClient = _db.Clients.FirstOrDefault(client => client.ClientId == id);
ViewBag.StylistId = new SelectList(_db.Stylists, "StylistId", "Name");
return View(thisClient);
}
[HttpPost]
public ActionResult Edit(Client client)
{
_db.Entry(client).State = EntityState.Modified;
_db.SaveChanges();
return RedirectToAction("Index");
}
public ActionResult Delete(int id)
{
Client thisClient = _db.Clients.FirstOrDefault(client => client.ClientId == id);
return View(thisClient);
}
[HttpPost, ActionName("Delete")]
public ActionResult DeleteConfirmed(int id)
{
Client thisClient = _db.Clients.FirstOrDefault(client => client.ClientId == id);
_db.Clients.Remove(thisClient);
_db.SaveChanges();
return RedirectToAction("Index");
}
}
} | 28.823529 | 120 | 0.671429 | [
"MIT"
] | kate-skorija/HairSalon.Solution | HairSalon/Controllers/ClientsController.cs | 1,960 | C# |
using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using Extreme.Net.Core;
namespace Extreme.Net
{
/// <summary>
/// Представляет клиент для HTTP прокси-сервера.
/// </summary>
public class HttpProxyClient : ProxyClient
{
#region Константы (закрытые)
private const int BufferSize = 50;
private const int DefaultPort = 8080;
#endregion
#region Конструкторы (открытые)
/// <summary>
/// Инициализирует новый экземпляр класса <see cref="HttpProxyClient"/>.
/// </summary>
public HttpProxyClient()
: this(null) { }
/// <summary>
/// Инициализирует новый экземпляр класса <see cref="HttpProxyClient"/> заданным хостом прокси-сервера, и устанавливает порт равным - 8080.
/// </summary>
/// <param name="host">Хост прокси-сервера.</param>
public HttpProxyClient(string host)
: this(host, DefaultPort) { }
/// <summary>
/// Инициализирует новый экземпляр класса <see cref="HttpProxyClient"/> заданными данными о прокси-сервере.
/// </summary>
/// <param name="host">Хост прокси-сервера.</param>
/// <param name="port">Порт прокси-сервера.</param>
public HttpProxyClient(string host, int port)
: this(host, port, string.Empty, string.Empty) { }
/// <summary>
/// Инициализирует новый экземпляр класса <see cref="HttpProxyClient"/> заданными данными о прокси-сервере.
/// </summary>
/// <param name="host">Хост прокси-сервера.</param>
/// <param name="port">Порт прокси-сервера.</param>
/// <param name="username">Имя пользователя для авторизации на прокси-сервере.</param>
/// <param name="password">Пароль для авторизации на прокси-сервере.</param>
public HttpProxyClient(string host, int port, string username, string password)
: base(ProxyType.Http, host, port, username, password) { }
#endregion
#region Статические методы (открытые)
/// <summary>
/// Преобразует строку в экземпляр класса <see cref="HttpProxyClient"/>.
/// </summary>
/// <param name="proxyAddress">Строка вида - хост:порт:имя_пользователя:пароль. Три последних параметра являются необязательными.</param>
/// <returns>Экземпляр класса <see cref="HttpProxyClient"/>.</returns>
/// <exception cref="System.ArgumentNullException">Значение параметра <paramref name="proxyAddress"/> равно <see langword="null"/>.</exception>
/// <exception cref="System.ArgumentException">Значение параметра <paramref name="proxyAddress"/> является пустой строкой.</exception>
/// <exception cref="System.FormatException">Формат порта является неправильным.</exception>
public static HttpProxyClient Parse(string proxyAddress)
{
return ProxyClient.Parse(ProxyType.Http, proxyAddress) as HttpProxyClient;
}
/// <summary>
/// Преобразует строку в экземпляр класса <see cref="HttpProxyClient"/>. Возвращает значение, указывающее, успешно ли выполнено преобразование.
/// </summary>
/// <param name="proxyAddress">Строка вида - хост:порт:имя_пользователя:пароль. Три последних параметра являются необязательными.</param>
/// <param name="result">Если преобразование выполнено успешно, то содержит экземпляр класса <see cref="HttpProxyClient"/>, иначе <see langword="null"/>.</param>
/// <returns>Значение <see langword="true"/>, если параметр <paramref name="proxyAddress"/> преобразован успешно, иначе <see langword="false"/>.</returns>
public static bool TryParse(string proxyAddress, out HttpProxyClient result)
{
ProxyClient proxy;
if (ProxyClient.TryParse(ProxyType.Http, proxyAddress, out proxy))
{
result = proxy as HttpProxyClient;
return true;
}
else
{
result = null;
return false;
}
}
#endregion
#region Методы (открытые)
/// <summary>
/// Создаёт соединение с сервером через прокси-сервер.
/// </summary>
/// <param name="destinationHost">Хост сервера, с которым нужно связаться через прокси-сервер.</param>
/// <param name="destinationPort">Порт сервера, с которым нужно связаться через прокси-сервер.</param>
/// <param name="tcpClient">Соединение, через которое нужно работать, или значение <see langword="null"/>.</param>
/// <returns>Соединение с сервером через прокси-сервер.</returns>
/// <exception cref="System.InvalidOperationException">
/// Значение свойства <see cref="Host"/> равно <see langword="null"/> или имеет нулевую длину.
/// -или-
/// Значение свойства <see cref="Port"/> меньше 1 или больше 65535.
/// -или-
/// Значение свойства <see cref="Username"/> имеет длину более 255 символов.
/// -или-
/// Значение свойства <see cref="Password"/> имеет длину более 255 символов.
/// </exception>
/// <exception cref="System.ArgumentNullException">Значение параметра <paramref name="destinationHost"/> равно <see langword="null"/>.</exception>
/// <exception cref="System.ArgumentException">Значение параметра <paramref name="destinationHost"/> является пустой строкой.</exception>
/// <exception cref="System.ArgumentOutOfRangeException">Значение параметра <paramref name="destinationPort"/> меньше 1 или больше 65535.</exception>
/// <exception cref="ProxyException">Ошибка при работе с прокси-сервером.</exception>
/// <remarks>Если порт сервера неравен 80, то для подключения используется метод 'CONNECT'.</remarks>
public override TcpClient CreateConnection(string destinationHost, int destinationPort, TcpClient tcpClient = null)
{
CheckState();
#region Проверка параметров
if (destinationHost == null)
{
throw new ArgumentNullException("destinationHost");
}
if (destinationHost.Length == 0)
{
throw ExceptionHelper.EmptyString("destinationHost");
}
if (!ExceptionHelper.ValidateTcpPort(destinationPort))
{
throw ExceptionHelper.WrongTcpPort("destinationPort");
}
#endregion
TcpClient curTcpClient = tcpClient;
if (curTcpClient == null)
{
curTcpClient = CreateConnectionToProxy();
}
if (destinationPort != 80)
{
HttpStatusCode statusCode = HttpStatusCode.OK;
try
{
NetworkStream nStream = curTcpClient.GetStream();
SendConnectionCommand(nStream, destinationHost, destinationPort);
statusCode = ReceiveResponse(nStream);
}
catch (Exception ex)
{
curTcpClient.Close();
if (ex is IOException || ex is SocketException)
{
throw NewProxyException(Resources.ProxyException_Error, ex);
}
throw;
}
if (statusCode != HttpStatusCode.OK)
{
curTcpClient.Close();
throw new ProxyException(string.Format(
Resources.ProxyException_ReceivedWrongStatusCode, statusCode, ToString()), this);
}
}
return curTcpClient;
}
#endregion
#region Методы (закрытые)
private string GenerateAuthorizationHeader()
{
if (!string.IsNullOrEmpty(_username) || !string.IsNullOrEmpty(_password))
{
string data = Convert.ToBase64String(Encoding.UTF8.GetBytes(
string.Format("{0}:{1}", _username, _password)));
return string.Format("Proxy-Authorization: Basic {0}\r\n", data);
}
return string.Empty;
}
private void SendConnectionCommand(NetworkStream nStream, string destinationHost, int destinationPort)
{
var commandBuilder = new StringBuilder();
commandBuilder.AppendFormat("CONNECT {0}:{1} HTTP/1.1\r\n", destinationHost, destinationPort);
commandBuilder.AppendFormat(GenerateAuthorizationHeader());
commandBuilder.AppendLine();
byte[] buffer = Encoding.ASCII.GetBytes(commandBuilder.ToString());
nStream.Write(buffer, 0, buffer.Length);
}
private HttpStatusCode ReceiveResponse(NetworkStream nStream)
{
byte[] buffer = new byte[BufferSize];
var responseBuilder = new StringBuilder();
WaitData(nStream);
do
{
int bytesRead = nStream.Read(buffer, 0, BufferSize);
responseBuilder.Append(Encoding.ASCII.GetString(buffer, 0, bytesRead));
} while (nStream.DataAvailable);
string response = responseBuilder.ToString();
if (response.Length == 0)
{
throw NewProxyException(Resources.ProxyException_ReceivedEmptyResponse);
}
// Выделяем строку статуса. Пример: HTTP/1.1 200 OK\r\n
string strStatus = response.Substring(" ", Http.NewLine);
int simPos = strStatus.IndexOf(' ');
if (simPos == -1)
{
throw NewProxyException(Resources.ProxyException_ReceivedWrongResponse);
}
string statusLine = strStatus.Substring(0, simPos);
if (statusLine.Length == 0)
{
throw NewProxyException(Resources.ProxyException_ReceivedWrongResponse);
}
HttpStatusCode statusCode = (HttpStatusCode)Enum.Parse(
typeof(HttpStatusCode), statusLine);
return statusCode;
}
private void WaitData(NetworkStream nStream)
{
int sleepTime = 0;
int delay = (nStream.ReadTimeout < 10) ?
10 : nStream.ReadTimeout;
while (!nStream.DataAvailable)
{
if (sleepTime >= delay)
{
throw NewProxyException(Resources.ProxyException_WaitDataTimeout);
}
sleepTime += 10;
Thread.Sleep(10);
}
}
#endregion
}
} | 38.255319 | 169 | 0.591676 | [
"MIT"
] | WinoGarcia/Extreme.Net.Core | Extreme.Net.Core/~Proxy/HttpProxyClient.cs | 12,438 | C# |
//*********************************************************
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
//
//
//
//
//
//*********************************************************
using System;
using Bio.Properties;
using Bio.Util.Logging;
namespace Bio.Web
{
/// <summary>
/// A validator for int values that defines an inclusive range of
/// allowed values.
/// </summary>
public class IntRangeValidator : IParameterValidator
{
/// <summary>
/// The lowest allowed value.
/// </summary>
public int First { get; set; }
/// <summary>
/// The highest value allowed.
/// </summary>
public int Last { get; set; }
/// <summary>
/// Constructor
/// </summary>
/// <param name="first">The lowest value.</param>
/// <param name="last">The highest value.</param>
public IntRangeValidator(int first, int last)
{
if (first > last)
{
string message = "IntRangeValidator: Invalid arguments";
Trace.Report(message);
throw new ArgumentOutOfRangeException("first", Resource.ARGUMENT_OUT_OF_RANGE);
}
First = first;
Last = last;
}
/// <summary>
/// Given an int value as an object, return true if the value is in-range.
/// </summary>
/// <param name="parameterValue">The value.</param>
/// <returns>True if the value is valid.</returns>
public bool IsValid(object parameterValue)
{
int? val = parameterValue as int?;
if (val == null)
{
return false;
}
if (val.Value < First || val.Value > Last)
{
return false;
}
return true;
}
/// <summary>
/// Given an int value as a string, return true if the value is in-range.
/// </summary>
/// <param name="parameterValue">The value.</param>
/// <returns>True if the value is valid.</returns>
public bool IsValid(string parameterValue)
{
int val = 0;
if (!int.TryParse(parameterValue, out val))
{
return false;
}
if (val < First || val > Last)
{
return false;
}
return true;
}
}
}
| 27.021739 | 95 | 0.470233 | [
"Apache-2.0"
] | jdm7dv/Microsoft-Biology-Foundation | eLMM/CodePlex/MBF/Web/IntRangeValidator.cs | 2,486 | C# |
/// This code was generated by
/// \ / _ _ _| _ _
/// | (_)\/(_)(_|\/| |(/_ v1.0.0
/// / /
using NUnit.Framework;
using System;
using Twilio.Converters;
using Twilio.TwiML;
using Twilio.TwiML.Messaging;
namespace Twilio.Tests.TwiML
{
[TestFixture]
public class MessagingResponseTest : TwilioTest
{
[Test]
public void TestEmptyElement()
{
var elem = new MessagingResponse();
Assert.AreEqual(
"<?xml version=\"1.0\" encoding=\"utf-8\"?>" + Environment.NewLine +
"<Response></Response>",
elem.ToString()
);
}
[Test]
public void TestElementWithExtraAttributes()
{
var elem = new MessagingResponse();
elem.SetOption("newParam1", "value");
elem.SetOption("newParam2", 1);
Assert.AreEqual(
"<?xml version=\"1.0\" encoding=\"utf-8\"?>" + Environment.NewLine +
"<Response newParam1=\"value\" newParam2=\"1\"></Response>",
elem.ToString()
);
}
[Test]
public void TestNestElement()
{
var elem = new MessagingResponse();
var child = new Message();
elem.Nest(child).Body();
Assert.AreEqual(
"<?xml version=\"1.0\" encoding=\"utf-8\"?>" + Environment.NewLine +
"<Response>" + Environment.NewLine +
" <Message>" + Environment.NewLine +
" <Body></Body>" + Environment.NewLine +
" </Message>" + Environment.NewLine +
"</Response>",
elem.ToString()
);
}
[Test]
public void TestElementWithChildren()
{
var elem = new MessagingResponse();
elem.Message(
"body",
"to",
"from",
new Uri("https://example.com"),
Twilio.Http.HttpMethod.Get,
new Uri("https://example.com")
);
elem.Redirect(new Uri("https://example.com"), Twilio.Http.HttpMethod.Get);
Assert.AreEqual(
"<?xml version=\"1.0\" encoding=\"utf-8\"?>" + Environment.NewLine +
"<Response>" + Environment.NewLine +
" <Message to=\"to\" from=\"from\" action=\"https://example.com\" method=\"GET\" statusCallback=\"https://example.com\">body</Message>" + Environment.NewLine +
" <Redirect method=\"GET\">https://example.com</Redirect>" + Environment.NewLine +
"</Response>",
elem.ToString()
);
}
[Test]
public void TestElementWithTextNode()
{
var elem = new MessagingResponse();
elem.AddText("Here is the content");
Assert.AreEqual(
"<?xml version=\"1.0\" encoding=\"utf-8\"?>" + Environment.NewLine +
"<Response>Here is the content</Response>",
elem.ToString()
);
}
[Test]
public void TestAllowGenericChildNodes()
{
var elem = new MessagingResponse();
elem.AddChild("generic-tag").AddText("Content").SetOption("tag", true);
Assert.AreEqual(
"<?xml version=\"1.0\" encoding=\"utf-8\"?>" + Environment.NewLine +
"<Response>" + Environment.NewLine +
" <generic-tag tag=\"True\">Content</generic-tag>" + Environment.NewLine +
"</Response>",
elem.ToString()
);
}
[Test]
public void TestAllowGenericChildrenOfChildNodes()
{
var elem = new MessagingResponse();
var child = new Message();
elem.Nest(child).AddChild("generic-tag").SetOption("tag", true).AddText("Content");
Assert.AreEqual(
"<?xml version=\"1.0\" encoding=\"utf-8\"?>" + Environment.NewLine +
"<Response>" + Environment.NewLine +
" <Message>" + Environment.NewLine +
" <generic-tag tag=\"True\">Content</generic-tag>" + Environment.NewLine +
" </Message>" + Environment.NewLine +
"</Response>",
elem.ToString()
);
}
[Test]
public void TestMixedContent()
{
var elem = new MessagingResponse();
elem.AddText("before")
.AddChild("Child").AddText("content");
elem.AddText("after");
Assert.AreEqual(
"<?xml version=\"1.0\" encoding=\"utf-8\"?>" + Environment.NewLine +
"<Response>before<Child>content</Child>after</Response>",
elem.ToString()
);
}
}
} | 32.516556 | 176 | 0.482688 | [
"MIT"
] | BrimmingDev/twilio-csharp | test/Twilio.Test/TwiML/MessagingResponseTest.cs | 4,910 | C# |
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Abp.Modules;
using Abp.Reflection.Extensions;
using IdentityServervNextDemo.Configuration;
namespace IdentityServervNextDemo.Web.Startup
{
[DependsOn(typeof(IdentityServervNextDemoWebCoreModule))]
public class IdentityServervNextDemoWebMvcModule : AbpModule
{
private readonly IWebHostEnvironment _env;
private readonly IConfigurationRoot _appConfiguration;
public IdentityServervNextDemoWebMvcModule(IWebHostEnvironment env)
{
_env = env;
_appConfiguration = env.GetAppConfiguration();
}
public override void PreInitialize()
{
Configuration.Navigation.Providers.Add<IdentityServervNextDemoNavigationProvider>();
}
public override void Initialize()
{
IocManager.RegisterAssemblyByConvention(typeof(IdentityServervNextDemoWebMvcModule).GetAssembly());
}
}
}
| 31.1875 | 111 | 0.723447 | [
"MIT"
] | OzBob/aspnetboilerplate-samples | IdentityServervNextDemo/aspnet-core/src/IdentityServervNextDemo.Web.Mvc/Startup/IdentityServervNextDemoWebMvcModule.cs | 1,000 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Web.Senai.ClevelandClinic.Domains;
using Web.Senai.ClevelandClinic.Repositories;
namespace Web.Senai.ClevelandClinic.Controllers
{
[Route("api/[controller]")]
[ApiController]
[Produces("application/json")]
public class MedicosController : ControllerBase
{
MedicoRepository medicoRepository = new MedicoRepository();
[HttpGet]
public IActionResult Listar()
{
return Ok(medicoRepository.Listar());
}
}
} | 27.916667 | 68 | 0.689552 | [
"MIT"
] | CleAurora/Cleveland_Clinic | BackEnd-Projeto/Web.Senai.ClevelandClinic/Web.Senai.ClevelandClinic/Controllers/MedicosController.cs | 672 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
namespace BusinessLight.PhoneBook.Mvc
{
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}
}
| 24.791667 | 99 | 0.594958 | [
"MIT"
] | RudyYang/BusinessLight | samples/BusinessLight.PhoneBook.Mvc/App_Start/RouteConfig.cs | 597 | C# |
namespace DIO.Series
{
public enum Genero
{
Acao = 1,
Aventura = 2,
Comedia = 3,
Documentario = 4,
Drama = 5,
Espionagem = 6,
Faroeste = 7,
Fantasia = 8,
Ficcao_Cientifica = 9,
Musical = 10,
Romance = 11,
Suspense = 12,
Terror = 13
}
} | 18.526316 | 30 | 0.448864 | [
"MIT"
] | mauriciopicirillo/primeiro_app_simples_de_cadastro_.net | DIO.Series/Enum/Genero.cs | 352 | C# |
namespace BC.Loop.Api.Client.Models {
/// <summary>
/// The builtin Loop Event Identifiers
/// </summary>
public enum EventIdentifierType {
IBeacon,
EddystoneUID,
BlueCatsID,
BluetoothAddress
}
} | 16.866667 | 43 | 0.58498 | [
"MIT"
] | bluecats/bluecats-csharp-loop-api-client | Projects/netstandard20/Models/EventIdentifierType.cs | 255 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
namespace SRMAPI
{
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}
}
| 21.125 | 88 | 0.66075 | [
"MIT"
] | DrSophistry/SophisRetailManager | SRMAPI/App_Start/RouteConfig.cs | 509 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class AbilityHandler : MonoBehaviour
{
[SerializeField]
private AbilityVariable currentAbility = default;
private void Update()
{
if (InputSuppressor.IsSuppressed || PauseState.IsPaused)
return;
AbilityInput input = GetInput();
DebugInput(input);
currentAbility.Value.UpdateState(input);
}
private AbilityInput GetInput()
{
Vector3 delta = (Utility.MousePositionInWorld - (Vector2)transform.position).normalized;
return new AbilityInput()
{
TargetPosition = transform.position + delta,
FireButtonStay = Input.GetKey(KeyCode.Mouse0),
ShouldReload = Input.GetKeyDown(KeyCode.R),
FireButtonReleased = Input.GetKeyUp(KeyCode.Mouse0),
};
}
private void DebugInput(AbilityInput input)
{
Debug.DrawLine(transform.position, input.TargetPosition, Color.cyan);
}
}
| 28.945946 | 97 | 0.63212 | [
"MIT"
] | DanielEverland/project-tuba-public | Assets/Scripts/Player/AbilityHandler.cs | 1,073 | C# |
using System;
using System.Diagnostics;
using Autodesk.Revit.UI;
namespace RhinoInside.Revit.External.UI
{
using Extensions;
public abstract class ExternalEventHandler : IExternalEventHandler
{
public abstract string GetName();
string IExternalEventHandler.GetName() =>
GetName();
protected abstract void Execute(UIApplication app);
void IExternalEventHandler.Execute(UIApplication app)
{
var _exception = default(Exception);
try { ActivationGate.Open(() => Execute(app), this); }
catch (Exceptions.CancelException e) { if (!string.IsNullOrEmpty(e.Message)) Debug.Fail(e.Source, e.Message); }
catch (Exceptions.FailException e) { Debug.Fail(e.Source, e.Message); }
catch (Autodesk.Revit.Exceptions.ApplicationException e) { Debug.Fail(e.Source, e.Message); }
catch (Exception e)
{
if (!CatchException(e, app))
throw;
_exception = e;
}
if (_exception is object)
ReportException(_exception, app);
}
protected virtual bool CatchException(Exception e, UIApplication app) =>
app.CatchException(e, this);
protected virtual void ReportException(Exception e, UIApplication app) =>
app.ReportException(e, this);
}
}
| 30 | 117 | 0.684127 | [
"MIT"
] | gokermu/rhino.inside-revit | src/RhinoInside.Revit/External/UI/EventHandler.cs | 1,260 | C# |
using UnityEngine;
using System.Collections;
public class PlayerController : MonoBehaviour
{
public float oxygen = 1f; // Between 0 and 1;
public float oxygenDecPerSec = 0.01f;
public float oxygenDecPerSecBoost = 0.02f;
public float oxygenGainedPerCapsule = 0.3f;
public bool isBoosted = false;
public float horsePowerBoostMultiply = 4f;
public WheelCollider WheelLF;
public WheelCollider WheelLB;
public WheelCollider WheelRF;
public WheelCollider WheelRB;
public Transform WheelLFTransform;
public Transform WheelLBTransform;
public Transform WheelRFTransform;
public Transform WheelRBTransform;
public float brakeSmogFactor;
bool isbraking = false;
public Transform AxleBack;
public Transform AxleFront;
public float currentSpeed;
public float horsePower = 120;
private float HorsePowerApplied;
public float brakeFriction = 10;
public float frictionCoeff = 0;
public float lowSpeedSteerAngle;
public float highSpeedSteerAngle;
private int horseToWatt = 1356;
private float ElevationLF = 0;
private float ElevationLB = 0;
private float ElevationRF = 0;
private float ElevationRB = 0;
private Vector3 offsetAxleB;
private Vector3 offsetAxleF;
public float BackAltitudeDifference;
public float BackLatitudeDifference;
public float FrontAltitudeDifference;
public float FrontLatitudeDifference;
public float BackAngle;
public float FrontAngle;
float dv = 1f;
float dh = 1f;
public ParticleRenderer prLF;
public ParticleRenderer prLB;
public ParticleRenderer prRF;
public ParticleRenderer prRB;
public ParticleEmitter peLF;
public ParticleEmitter peRF;
public float particleSize;
public Material skidMaterial;
ArrowManager arrowManager;
EndUIScript endUIScript;
TimerManager timerScript;
SoundScript soundScript;
bool endLevel = false;
/*void Update()
{
}*/
void Start()
{
// Destroy (GameObject.Find ( "Main Camera Menu"));
arrowManager = GetComponentInChildren<ArrowManager>();
endUIScript = GetComponentInChildren<EndUIScript>();
timerScript = GetComponentInChildren<TimerManager>();
soundScript = GetComponent<SoundScript>();
HorsePowerApplied = horsePower;
GetComponent<Rigidbody>().centerOfMass = Vector3.down * 1.5f;
currentSpeed = 0.0f;
//Compute the vertical and horizontal distance between the wheels in order to make some trigonometry for
//wheels steer angles
dv = Mathf.Abs(WheelLF.transform.position.x - WheelRB.transform.position.x);
dh = Mathf.Abs (WheelLF.transform.position.z - WheelRB.transform.position.z);
//Save the base position of both axle in order to modifiy it according to the suspension
offsetAxleB = AxleBack.localPosition;
offsetAxleF = AxleFront.localPosition;
GameObject respawn = (GameObject)GameObject.FindGameObjectsWithTag("Respawn").GetValue(0);
transform.position = respawn.transform.position;
transform.rotation = respawn.transform.rotation;
GetComponent<Rigidbody>().angularVelocity = Vector3.zero;
timerScript.LaunchTimer();
endUIScript.ResetTime();
}
void OnTriggerEnter(Collider other)
{
switch (other.gameObject.tag)
{
case "Finish":
if (endUIScript.Activate())
this.endLevel = true;
break;
case "capsule":
this.ModifyOxygenByDelta(oxygenGainedPerCapsule);
other.gameObject.SetActive (false);
this.soundScript.PlayBonus();
break;
case "checkpoint":
this.arrowManager.RemoveCheckPoint(other);
break;
}
}
void ModifyOxygenByDelta(float d)
{
this.oxygen += d;
if (this.oxygen > 1f)
this.oxygen = 1f;
else if (this.oxygen < 0f)
this.oxygen = 0f;
}
void FixedUpdate()
{
GetComponent<Rigidbody>().velocity = Vector3.zero;
GetComponent<Rigidbody>().angularVelocity = Vector3.zero;
if (endLevel)
{
return;
}
//Compute the vehicle speed according to the front wheel rotation
currentSpeed = 2*Mathf.PI*WheelLF.radius*Mathf.Abs(WheelLF.rpm*60/1000);
//Apply the torque according to the Power of vehicle and the speed (Use a min speed to limit the torque)
WheelLF.motorTorque = horseToWatt * HorsePowerApplied / Mathf.Max(currentSpeed, 10f) * Input.GetAxis ("Vertical");
WheelRF.motorTorque = horseToWatt * HorsePowerApplied / Mathf.Max(currentSpeed, 10f) * Input.GetAxis ("Vertical");
Debug.Log(WheelLF.motorTorque);
//Play sound of the motor according to the motor speed
this.soundScript.PlayMotor(currentSpeed);
//If the user brake
if (Input.GetAxis ("Vertical") == -1 && currentSpeed > 10 && WheelLF.rpm > 0 ||
Input.GetAxis ("Vertical") == 1 && currentSpeed > 10 && WheelLF.rpm < 0) {
//And the front wheels touch the ground
if (Physics.Raycast (WheelLF.transform.position, -WheelLF.transform.up, WheelLF.radius + WheelLF.suspensionDistance) ||
Physics.Raycast (WheelRF.transform.position, -WheelRF.transform.up, WheelRF.radius + WheelRF.suspensionDistance)) {
//Produce a brake sound
isbraking = true;
this.soundScript.PlayBrake(currentSpeed);
}
else
{
isbraking = false;
}
}
else
{
this.soundScript.StopBrake();
isbraking = false;
}
if (Input.GetButton("Jump"))
{
this.isBoosted = true;
this.ModifyOxygenByDelta (-this.oxygenDecPerSecBoost * Time.deltaTime);
HorsePowerApplied = horsePower * this.horsePowerBoostMultiply;
}
else
{
this.isBoosted = false;
HorsePowerApplied = horsePower;
}
//Compute brake torque according to the speed of the vehicle, and friction coefficient
float brake = currentSpeed * brakeFriction + frictionCoeff;
WheelLF.brakeTorque = brake;
WheelRF.brakeTorque = brake;
//Calculate steer angle of interior wheels according to the speed and the pression on the keyboard
float speedFactor = Mathf.Min(GetComponent<Rigidbody>().velocity.magnitude / 50);
float currentSteerAngle = Mathf.Lerp(lowSpeedSteerAngle, highSpeedSteerAngle, speedFactor);
currentSteerAngle *= Input.GetAxis("Horizontal");
//Calculate steer angle of external wheel according to the dimensions and the internal angle
if (currentSteerAngle > 0)
{
WheelRF.steerAngle = currentSteerAngle;
WheelLF.steerAngle = getExternalWheelAngle(currentSteerAngle, dv, dh);
}
else if(currentSteerAngle < 0)
{
WheelLF.steerAngle = currentSteerAngle;
WheelRF.steerAngle = getExternalWheelAngle(currentSteerAngle, dv, dh);
}
else
{
WheelLF.steerAngle = currentSteerAngle;
WheelRF.steerAngle = currentSteerAngle;
}
if(Input.GetButtonDown("LastCheckpoint"))
{
transform.position = arrowManager.getLastCheckpoint().position;
transform.rotation = arrowManager.getLastCheckpoint().rotation;
GetComponent<Rigidbody>().velocity = Vector3.zero;
GetComponent<Rigidbody>().angularVelocity = Vector3.zero;
}
}
void Update()
{
// woot
this.ModifyOxygenByDelta (-this.oxygenDecPerSec * Time.deltaTime);
//Rotate the Wheel mesh according to the Wheelcollider speed
WheelLFTransform.Rotate (0,0,WheelLF.rpm / 60 * -360 * Time.deltaTime);
WheelRFTransform.Rotate (0,0,WheelRF.rpm / 60 * -360 * Time.deltaTime);
WheelLBTransform.Rotate (0,0,WheelLB.rpm / 60 * -360 * Time.deltaTime);
WheelRBTransform.Rotate (0,0,WheelRB.rpm / 60 * -360 * Time.deltaTime);
//Apply the computed steer angle for front wheels
float newLFYAngle = WheelLF.steerAngle;
float newRFYAngle = WheelRF.steerAngle;
WheelLFTransform.localEulerAngles = new Vector3(WheelLFTransform.localEulerAngles.x, newLFYAngle, WheelLFTransform.localEulerAngles.z);
WheelRFTransform.localEulerAngles = new Vector3(WheelRFTransform.localEulerAngles.x, newRFYAngle, WheelRFTransform.localEulerAngles.z);
//Calculate and apply the position of wheel mesh
WheelPosition ();
//Calculate and apply the position and angle of the axles
AxlePosition ();
//If player ran out of oxygen, the game is over
if(this.oxygen<=0f)
{
endLevel=true;
endUIScript.Oxygenfail();
}
}
void WheelPosition()
{
RaycastHit hit;
Vector3 wheelPos = new Vector3();
//Calculate if the wheels touche the floor.
if (Physics.Raycast(WheelLF.transform.position, -WheelLF.transform.up, out hit, WheelLF.radius+WheelLF.suspensionDistance) )
{
//The wheel touches the floor, hit correspond to the contact point
//Calculate the position of the Wheel to display properly
wheelPos = hit.point+WheelLF.transform.up * WheelLF.radius;
ElevationLF = hit.distance;
prLF.maxParticleSize = currentSpeed/100*particleSize;
//If the vehicle is braking and the wheel touches the floor, the smog becomes heavier
if(isbraking)
{
prLF.maxParticleSize *= brakeSmogFactor;
peLF.maxSize = 6;
}
//If the vehicle is not braking, the particule have a normal size
else
{
peLF.maxSize = 3;
}
prLF.GetComponent<ParticleEmitter>().emit = true;
}
//If the Wheel does not touch the floor, the wheel is placed at the maximum suspension distance, and does not emit smog
else
{
wheelPos = WheelLF.transform.position -WheelLF.transform.up* WheelLF.suspensionDistance;
ElevationLF = WheelLF.suspensionDistance+WheelLF.radius;
prLF.GetComponent<ParticleEmitter>().emit = false;
}
WheelLFTransform.position = wheelPos;
if (Physics.Raycast(WheelRF.transform.position, -WheelRF.transform.up, out hit, WheelRF.radius+WheelRF.suspensionDistance) )
{
wheelPos = hit.point+WheelRF.transform.up * WheelRF.radius;
ElevationRF = hit.distance;
prRF.maxParticleSize = currentSpeed/100*particleSize;
if(isbraking)
{
prRF.maxParticleSize *= brakeSmogFactor;
peRF.maxSize = 6;
}
else
{
peRF.maxSize = 3;
}
prRF.GetComponent<ParticleEmitter>().emit = true;
}
else
{
wheelPos = WheelRF.transform.position -WheelRF.transform.up* WheelRF.suspensionDistance;
ElevationRF = WheelRF.suspensionDistance+WheelRF.radius;
prRF.GetComponent<ParticleEmitter>().emit = false;
}
WheelRFTransform.position = wheelPos;
if (Physics.Raycast(WheelLB.transform.position, -WheelLB.transform.up, out hit, WheelLB.radius+WheelLB.suspensionDistance) )
{
wheelPos = hit.point+WheelLB.transform.up * WheelLB.radius;
ElevationLB = hit.distance;
prLB.maxParticleSize = currentSpeed/100*particleSize;
prLB.GetComponent<ParticleEmitter>().emit = true;
}
else
{
wheelPos = WheelLB.transform.position -WheelLB.transform.up* WheelLB.suspensionDistance;
ElevationLB = WheelLB.suspensionDistance+WheelLB.radius;
prLB.GetComponent<ParticleEmitter>().emit = false;
}
WheelLBTransform.position = wheelPos;
if (Physics.Raycast(WheelRB.transform.position, -WheelRB.transform.up, out hit, WheelRB.radius+WheelRB.suspensionDistance) )
{
wheelPos = hit.point+WheelRB.transform.up * WheelRB.radius;
ElevationRB = hit.distance;
prRB.maxParticleSize = currentSpeed/100*particleSize;
prRB.GetComponent<ParticleEmitter>().emit = true;
}
else
{
wheelPos = WheelRB.transform.position -WheelRB.transform.up* WheelRB.suspensionDistance;
ElevationRB = WheelRB.suspensionDistance+WheelRB.radius;
prRB.GetComponent<ParticleEmitter>().emit = false;
}
WheelRBTransform.position = wheelPos;
}
//Put the axle with the correct angle, following the wheels
void AxlePosition()
{
//Back Axle - Compute angle and position of back axle to join the two wheels according to the suspensions
BackAltitudeDifference = ElevationLB-ElevationRB;
BackLatitudeDifference = Mathf.Abs(WheelRBTransform.transform.localPosition.z-WheelLBTransform.transform.localPosition.z);
BackAngle = Mathf.Atan (BackAltitudeDifference / BackLatitudeDifference) * Mathf.Rad2Deg;
AxleBack.localEulerAngles = new Vector3(0,0,BackAngle);
AxleBack.localPosition = new Vector3 (offsetAxleB.x, offsetAxleB.y - ElevationLB + WheelLB.radius, offsetAxleB.z);
//Front Axle - Compute angle and position of back axle to join the two wheels according to the suspensions
FrontAltitudeDifference = ElevationLF-ElevationRF;
FrontLatitudeDifference = Mathf.Abs(WheelRFTransform.transform.localPosition.z-WheelLFTransform.transform.localPosition.z);
FrontAngle = Mathf.Atan (FrontAltitudeDifference / FrontLatitudeDifference) * Mathf.Rad2Deg;
AxleFront.localEulerAngles = new Vector3(0,0,FrontAngle);
AxleFront.localPosition = new Vector3 (offsetAxleF.x, offsetAxleF.y - ElevationLF + WheelLF.radius, offsetAxleF.z);
}
//Calculate the external wheel angle corresponding to the internal in order to get a perfect direction for a vehicle
//(Epure d'Ackermann)
float getExternalWheelAngle(float internalAngle, float verticalWheelBase, float horizontalWheelBase)
{
return Mathf.Rad2Deg*Mathf.Atan(verticalWheelBase/((verticalWheelBase/Mathf.Tan(Mathf.Deg2Rad*internalAngle))+horizontalWheelBase));
}
}
| 37.114973 | 141 | 0.687198 | [
"MIT"
] | ice-blaze/msr | Assets/Scripts/PlayerController.cs | 13,881 | C# |
using System.ComponentModel;
using System.Reactive;
using Avalonia.Input;
using Avalonia.Threading;
using OpenTracker.Models.BossPlacements;
using OpenTracker.Utils;
using OpenTracker.ViewModels.BossSelect;
using ReactiveUI;
namespace OpenTracker.ViewModels.Items.Adapters
{
/// <summary>
/// This class contains the logic to adapt dungeon boss data to an item control.
/// </summary>
public class BossAdapter : ViewModelBase, IItemAdapter
{
private readonly IBossPlacement _bossPlacement;
public string ImageSource =>
"avares://OpenTracker/Assets/Images/Bosses/" +
(_bossPlacement.Boss.HasValue ? $"{_bossPlacement.Boss.ToString()!.ToLowerInvariant()}1" :
$"{_bossPlacement.DefaultBoss.ToString().ToLowerInvariant()}0") + ".png";
public string? Label { get; } = null;
public string LabelColor { get; } = "#ffffffff";
public IBossSelectPopupVM? BossSelect { get; }
public ReactiveCommand<PointerReleasedEventArgs, Unit> HandleClick { get; }
public delegate BossAdapter Factory(IBossPlacement bossPlacement);
/// <summary>
/// Constructor
/// </summary>
/// <param name="bossSelectFactory">
/// An Autofac factory for creating the boss select popup control ViewModel.
/// </param>
/// <param name="bossPlacement">
/// The boss placement to be represented.
/// </param>
public BossAdapter(IBossSelectPopupVM.Factory bossSelectFactory, IBossPlacement bossPlacement)
{
_bossPlacement = bossPlacement;
BossSelect = bossSelectFactory(_bossPlacement);
HandleClick = ReactiveCommand.Create<PointerReleasedEventArgs>(HandleClickImpl);
_bossPlacement.PropertyChanged += OnBossChanged;
}
/// <summary>
/// Subscribes to the PropertyChanged event on the ISection interface.
/// </summary>
/// <param name="sender">
/// The sending object of the event.
/// </param>
/// <param name="e">
/// The arguments of the PropertyChanged event.
/// </param>
private async void OnBossChanged(object? sender, PropertyChangedEventArgs e)
{
if (e.PropertyName == nameof(IBossPlacement.Boss))
{
await Dispatcher.UIThread.InvokeAsync(() => this.RaisePropertyChanged(nameof(ImageSource)));
}
}
/// <summary>
/// Opens the boss select popup.
/// </summary>
private void OpenBossSelect()
{
if (BossSelect is null)
{
return;
}
BossSelect.PopupOpen = true;
}
/// <summary>
/// Handles clicking the control.
/// </summary>
/// <param name="e">
/// The pointer released event args.
/// </param>
private void HandleClickImpl(PointerReleasedEventArgs e)
{
if (e.InitialPressMouseButton == MouseButton.Left)
{
OpenBossSelect();
}
}
}
} | 32.94898 | 108 | 0.583462 | [
"MIT"
] | AntyMew/OpenTracker | OpenTracker/ViewModels/Items/Adapters/BossAdapter.cs | 3,229 | 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.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Buffers;
namespace System.IO
{
// This abstract base class represents a reader that can read a sequential
// stream of characters. This is not intended for reading bytes -
// there are methods on the Stream class to read bytes.
// A subclass must minimally implement the Peek() and Read() methods.
//
// This class is intended for character input, not bytes.
// There are methods on the Stream class for reading bytes.
public abstract partial class TextReader : MarshalByRefObject, IDisposable
{
public static readonly TextReader Null = new NullTextReader();
protected TextReader() { }
public virtual void Close()
{
Dispose(true);
GC.SuppressFinalize(this);
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
}
// Returns the next available character without actually reading it from
// the input stream. The current position of the TextReader is not changed by
// this operation. The returned value is -1 if no further characters are
// available.
//
// This default method simply returns -1.
//
public virtual int Peek()
{
return -1;
}
// Reads the next character from the input stream. The returned value is
// -1 if no further characters are available.
//
// This default method simply returns -1.
//
public virtual int Read()
{
return -1;
}
// Reads a block of characters. This method will read up to
// count characters from this TextReader into the
// buffer character array starting at position
// index. Returns the actual number of characters read.
//
public virtual int Read(char[] buffer, int index, int count)
{
if (buffer == null)
{
throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer);
}
if (index < 0)
{
throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_NeedNonNegNum);
}
if (count < 0)
{
throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum);
}
if (buffer.Length - index < count)
{
throw new ArgumentException(SR.Argument_InvalidOffLen);
}
int n;
for (n = 0; n < count; n++)
{
int ch = Read();
if (ch == -1) break;
buffer[index + n] = (char)ch;
}
return n;
}
// Reads a span of characters. This method will read up to
// count characters from this TextReader into the
// span of characters Returns the actual number of characters read.
//
public virtual int Read(Span<char> buffer)
{
char[] array = ArrayPool<char>.Shared.Rent(buffer.Length);
try
{
int numRead = Read(array, 0, buffer.Length);
if ((uint)numRead > (uint)buffer.Length)
{
throw new IOException(SR.IO_InvalidReadLength);
}
new Span<char>(array, 0, numRead).CopyTo(buffer);
return numRead;
}
finally
{
ArrayPool<char>.Shared.Return(array);
}
}
// Reads all characters from the current position to the end of the
// TextReader, and returns them as one string.
public virtual string ReadToEnd()
{
char[] chars = new char[4096];
int len;
StringBuilder sb = new StringBuilder(4096);
while ((len = Read(chars, 0, chars.Length)) != 0)
{
sb.Append(chars, 0, len);
}
return sb.ToString();
}
// Blocking version of read. Returns only when count
// characters have been read or the end of the file was reached.
//
public virtual int ReadBlock(char[] buffer, int index, int count)
{
int i, n = 0;
do
{
n += (i = Read(buffer, index + n, count - n));
} while (i > 0 && n < count);
return n;
}
// Blocking version of read for span of characters. Returns only when count
// characters have been read or the end of the file was reached.
//
public virtual int ReadBlock(Span<char> buffer)
{
char[] array = ArrayPool<char>.Shared.Rent(buffer.Length);
try
{
int numRead = ReadBlock(array, 0, buffer.Length);
if ((uint)numRead > (uint)buffer.Length)
{
throw new IOException(SR.IO_InvalidReadLength);
}
new Span<char>(array, 0, numRead).CopyTo(buffer);
return numRead;
}
finally
{
ArrayPool<char>.Shared.Return(array);
}
}
// Reads a line. A line is defined as a sequence of characters followed by
// a carriage return ('\r'), a line feed ('\n'), or a carriage return
// immediately followed by a line feed. The resulting string does not
// contain the terminating carriage return and/or line feed. The returned
// value is null if the end of the input stream has been reached.
//
public virtual string? ReadLine()
{
StringBuilder sb = new StringBuilder();
while (true)
{
int ch = Read();
if (ch == -1) break;
if (ch == '\r' || ch == '\n')
{
if (ch == '\r' && Peek() == '\n')
{
Read();
}
return sb.ToString();
}
sb.Append((char)ch);
}
if (sb.Length > 0)
{
return sb.ToString();
}
return null;
}
#region Task based Async APIs
public virtual Task<string?> ReadLineAsync()
{
return Task<string?>.Factory.StartNew(state =>
{
return ((TextReader)state!).ReadLine();
},
this, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default);
}
public virtual async Task<string> ReadToEndAsync()
{
var sb = new StringBuilder(4096);
char[] chars = ArrayPool<char>.Shared.Rent(4096);
try
{
int len;
while ((len = await ReadAsyncInternal(chars, default).ConfigureAwait(false)) != 0)
{
sb.Append(chars, 0, len);
}
}
finally
{
ArrayPool<char>.Shared.Return(chars);
}
return sb.ToString();
}
public virtual Task<int> ReadAsync(char[] buffer, int index, int count)
{
if (buffer == null)
{
throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer);
}
if (index < 0 || count < 0)
{
throw new ArgumentOutOfRangeException((index < 0 ? nameof(index) : nameof(count)), SR.ArgumentOutOfRange_NeedNonNegNum);
}
if (buffer.Length - index < count)
{
throw new ArgumentException(SR.Argument_InvalidOffLen);
}
return ReadAsyncInternal(new Memory<char>(buffer, index, count), default).AsTask();
}
public virtual ValueTask<int> ReadAsync(Memory<char> buffer, CancellationToken cancellationToken = default) =>
new ValueTask<int>(MemoryMarshal.TryGetArray(buffer, out ArraySegment<char> array) ?
ReadAsync(array.Array!, array.Offset, array.Count) :
Task<int>.Factory.StartNew(state =>
{
var t = (Tuple<TextReader, Memory<char>>)state!;
return t.Item1.Read(t.Item2.Span);
}, Tuple.Create(this, buffer), cancellationToken, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default));
internal virtual ValueTask<int> ReadAsyncInternal(Memory<char> buffer, CancellationToken cancellationToken)
{
var tuple = new Tuple<TextReader, Memory<char>>(this, buffer);
return new ValueTask<int>(Task<int>.Factory.StartNew(state =>
{
var t = (Tuple<TextReader, Memory<char>>)state!;
return t.Item1.Read(t.Item2.Span);
},
tuple, cancellationToken, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default));
}
public virtual Task<int> ReadBlockAsync(char[] buffer, int index, int count)
{
if (buffer == null)
{
throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer);
}
if (index < 0 || count < 0)
{
throw new ArgumentOutOfRangeException(index < 0 ? nameof(index) : nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum);
}
if (buffer.Length - index < count)
{
throw new ArgumentException(SR.Argument_InvalidOffLen);
}
return ReadBlockAsyncInternal(new Memory<char>(buffer, index, count), default).AsTask();
}
public virtual ValueTask<int> ReadBlockAsync(Memory<char> buffer, CancellationToken cancellationToken = default) =>
new ValueTask<int>(MemoryMarshal.TryGetArray(buffer, out ArraySegment<char> array) ?
ReadBlockAsync(array.Array!, array.Offset, array.Count) :
Task<int>.Factory.StartNew(state =>
{
var t = (Tuple<TextReader, Memory<char>>)state!;
return t.Item1.ReadBlock(t.Item2.Span);
}, Tuple.Create(this, buffer), cancellationToken, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default));
internal async ValueTask<int> ReadBlockAsyncInternal(Memory<char> buffer, CancellationToken cancellationToken)
{
int n = 0, i;
do
{
i = await ReadAsyncInternal(buffer.Slice(n), cancellationToken).ConfigureAwait(false);
n += i;
} while (i > 0 && n < buffer.Length);
return n;
}
#endregion
private sealed class NullTextReader : TextReader
{
public NullTextReader() { }
public override int Read(char[] buffer, int index, int count)
{
return 0;
}
public override string? ReadLine()
{
return null;
}
}
public static TextReader Synchronized(TextReader reader)
{
if (reader == null)
throw new ArgumentNullException(nameof(reader));
return reader is SyncTextReader ? reader : new SyncTextReader(reader);
}
internal sealed class SyncTextReader : TextReader
{
internal readonly TextReader _in;
internal SyncTextReader(TextReader t)
{
_in = t;
}
[MethodImpl(MethodImplOptions.Synchronized)]
public override void Close() => _in.Close();
[MethodImpl(MethodImplOptions.Synchronized)]
protected override void Dispose(bool disposing)
{
// Explicitly pick up a potentially methodimpl'ed Dispose
if (disposing)
((IDisposable)_in).Dispose();
}
[MethodImpl(MethodImplOptions.Synchronized)]
public override int Peek() => _in.Peek();
[MethodImpl(MethodImplOptions.Synchronized)]
public override int Read() => _in.Read();
[MethodImpl(MethodImplOptions.Synchronized)]
public override int Read(char[] buffer, int index, int count) => _in.Read(buffer, index, count);
[MethodImpl(MethodImplOptions.Synchronized)]
public override int ReadBlock(char[] buffer, int index, int count) => _in.ReadBlock(buffer, index, count);
[MethodImpl(MethodImplOptions.Synchronized)]
public override string? ReadLine() => _in.ReadLine();
[MethodImpl(MethodImplOptions.Synchronized)]
public override string ReadToEnd() => _in.ReadToEnd();
//
// On SyncTextReader all APIs should run synchronously, even the async ones.
//
[MethodImpl(MethodImplOptions.Synchronized)]
public override Task<string?> ReadLineAsync() => Task.FromResult(ReadLine());
[MethodImpl(MethodImplOptions.Synchronized)]
public override Task<string> ReadToEndAsync() => Task.FromResult(ReadToEnd());
[MethodImpl(MethodImplOptions.Synchronized)]
public override Task<int> ReadBlockAsync(char[] buffer, int index, int count)
{
if (buffer == null)
throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer);
if (index < 0 || count < 0)
throw new ArgumentOutOfRangeException((index < 0 ? nameof(index) : nameof(count)), SR.ArgumentOutOfRange_NeedNonNegNum);
if (buffer.Length - index < count)
throw new ArgumentException(SR.Argument_InvalidOffLen);
return Task.FromResult(ReadBlock(buffer, index, count));
}
[MethodImpl(MethodImplOptions.Synchronized)]
public override Task<int> ReadAsync(char[] buffer, int index, int count)
{
if (buffer == null)
throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer);
if (index < 0 || count < 0)
throw new ArgumentOutOfRangeException((index < 0 ? nameof(index) : nameof(count)), SR.ArgumentOutOfRange_NeedNonNegNum);
if (buffer.Length - index < count)
throw new ArgumentException(SR.Argument_InvalidOffLen);
return Task.FromResult(Read(buffer, index, count));
}
}
}
}
| 36.864078 | 140 | 0.546352 | [
"MIT"
] | Azure-2019/corefx | src/Common/src/CoreLib/System/IO/TextReader.cs | 15,188 | C# |
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Controllers;
using Microsoft.AspNetCore.Mvc.Infrastructure;
using Microsoft.AspNetCore.Mvc.Internal;
namespace Shriek.ServiceProxy.Http.Server.RouteAnalyzer.Impl
{
internal class RouteAnalyzer : IRouteAnalyzer
{
private readonly IActionDescriptorCollectionProvider actionDescriptorCollectionProvider;
public RouteAnalyzer(IActionDescriptorCollectionProvider actionDescriptorCollectionProvider)
{
this.actionDescriptorCollectionProvider = actionDescriptorCollectionProvider;
}
public IEnumerable<RouteInformation> GetAllRouteInformations()
{
var ret = new List<RouteInformation>();
var descriptors = actionDescriptorCollectionProvider.ActionDescriptors.Items;
foreach (var action in descriptors)
{
var info = new RouteInformation();
if (action.ActionConstraints != null)
{
var httpMethod = action.ActionConstraints.Where(x => x is HttpMethodActionConstraint).OfType<HttpMethodActionConstraint>();
info.HttpMethod = string.Join("|", httpMethod.SelectMany(x => x.HttpMethods));
}
if (string.IsNullOrEmpty(info.HttpMethod))
info.HttpMethod = "Get";
// Area
if (action.RouteValues.ContainsKey("area"))
{
info.Area = action.RouteValues["area"];
}
// Path and Invocation of Razor Pages
//if (action is PageActionDescriptor page)
//{
// info.Path = page.ViewEnginePath;
// info.Invocation = page.RelativePath;
//}
// Path of Route Attribute
if (action.AttributeRouteInfo != null)
{
info.Path = $"/{action.AttributeRouteInfo.Template}";
}
// Path and Invocation of Controller/Action
if (action is ControllerActionDescriptor ca)
{
if (string.IsNullOrEmpty(info.Path))
{
info.Path = $"/{ca.ControllerName}/{ca.ActionName}";
}
info.Invocation = $"{ca.ControllerTypeInfo.Name}.{ca.ActionName}";
}
// Special controller path
if (info.Path == "/RouteAnalyzer/ShowAllRoutes")
{
continue;
//info.Path = RouteAnalyzerRouteBuilderExtensions.RouteAnalyzerUrlPath;
}
// Additional information of invocation
info.Invocation += $" ({action.DisplayName})";
// Generating List
ret.Add(info);
}
// Result
return ret;
}
}
} | 36 | 143 | 0.551307 | [
"MIT"
] | 1051324354/shriek-fx | src/Shriek.ServiceProxy.Http.Server/RouteAnalyzer/Impl/RouteAnalyzer.cs | 3,062 | C# |
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using DezignSpiration.Models;
namespace DezignSpiration.Interfaces
{
public interface IQuotesRepository
{
Task<bool> DeleteQuote(DesignQuote designQuote);
Task<bool> InsertQuotes(IEnumerable<DesignQuote> quotes);
Task<DesignQuote> GetQuote(int quoteId);
Task<List<DesignQuote>> GetAllQuotes();
Task<int> CountQuotes();
Task<ObservableRangeCollection<DesignQuote>> GetFreshQuotes();
Task<bool> FlagQuote(DesignQuote quote, int flagReasonId);
Task AddQuote(DesignQuote quote, bool isAnonymous, string deviceId = null);
Task<DesignQuote> GetRandomQuote();
}
}
| 24.333333 | 83 | 0.712329 | [
"MIT"
] | johnxy84/Dezignspiration | DezignSpiration/Interfaces/IQuotesRepository.cs | 732 | C# |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Diagnostics.ContractsLight;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using BuildXL.Native.IO;
using BuildXL.Native.Processes;
using BuildXL.Native.Streams;
using BuildXL.Pips.Operations;
using BuildXL.Processes.Internal;
using BuildXL.Storage;
using BuildXL.Utilities;
using BuildXL.Utilities.Tasks;
using BuildXL.Utilities.Threading;
using Microsoft.Win32.SafeHandles;
#if !FEATURE_SAFE_PROCESS_HANDLE
using SafeProcessHandle = BuildXL.Interop.Windows.SafeProcessHandle;
#endif
namespace BuildXL.Processes
{
/// <summary>
/// A process abstraction for BuildXL that can monitor environment interactions, in particular file accesses, that ensures
/// that all file accesses are on a white-list.
/// Under the hood, the sandboxed process uses Detours.
/// </summary>
/// <remarks>
/// All public static and instance methods of this class are thread safe.
/// </remarks>
public sealed class SandboxedProcess : ISandboxedProcess
{
private const int MaxProcessPathLength = 1024;
private static BinaryPaths s_binaryPaths;
private static readonly Guid s_payloadGuid = new Guid("7CFDBB96-C3D6-47CD-9026-8FA863C52FEC");
private readonly int m_bufferSize;
private PooledObjectWrapper<MemoryStream> m_fileAccessManifestStreamWrapper;
private MemoryStream FileAccessManifestStream => m_fileAccessManifestStreamWrapper.Instance;
private FileAccessManifest m_fileAccessManifest;
private ReadWriteLock m_queryJobDataLock = ReadWriteLock.Create();
private readonly TaskSourceSlim<SandboxedProcessResult> m_resultTaskCompletionSource =
TaskSourceSlim.Create<SandboxedProcessResult>();
private readonly TextReader m_standardInputReader;
private readonly TimeSpan m_nestedProcessTerminationTimeout;
private DetouredProcess m_detouredProcess;
private bool m_processStarted;
private bool m_disposeStarted;
private SandboxedProcessOutputBuilder m_error;
private SandboxedProcessOutputBuilder m_output;
private SandboxedProcessReports m_reports;
private AsyncPipeReader m_reportReader;
private readonly SemaphoreSlim m_reportReaderSemaphore = TaskUtilities.CreateMutex();
private Dictionary<uint, ReportedProcess> m_survivingChildProcesses;
private readonly uint m_timeoutMins;
private readonly Action<int> m_processIdListener;
private TaskSourceSlim<bool> m_standardInputTcs;
private readonly PathTable m_pathTable;
[SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "We own these objects.")]
internal SandboxedProcess(SandboxedProcessInfo info)
{
Contract.Requires(info != null);
Contract.Requires(!info.Timeout.HasValue || info.Timeout.Value <= Process.MaxTimeout);
// there could be a race here, but it just doesn't matter
if (s_binaryPaths == null)
{
s_binaryPaths = new BinaryPaths(); // this can take a while; performs I/O
}
// If unspecified make the injection timeout 10 mins. Also, make it no less than 10 mins.
m_timeoutMins = info.Timeout.HasValue ? ((uint)info.Timeout.Value.TotalMinutes) : 10;
if (m_timeoutMins < 10)
{
m_timeoutMins = 10;
}
m_fileAccessManifest = info.FileAccessManifest;
m_fileAccessManifestStreamWrapper = Pools.MemoryStreamPool.GetInstance();
m_bufferSize = SandboxedProcessInfo.BufferSize;
m_nestedProcessTerminationTimeout = info.NestedProcessTerminationTimeout;
Encoding inputEncoding = info.StandardInputEncoding ?? Console.InputEncoding;
m_standardInputReader = info.StandardInputReader;
m_pathTable = info.PathTable;
Encoding outputEncoding = info.StandardOutputEncoding ?? Console.OutputEncoding;
m_output = new SandboxedProcessOutputBuilder(
outputEncoding,
info.MaxLengthInMemory,
info.FileStorage,
SandboxedProcessFile.StandardOutput,
info.StandardOutputObserver);
Encoding errorEncoding = info.StandardErrorEncoding ?? Console.OutputEncoding;
m_error = new SandboxedProcessOutputBuilder(
errorEncoding,
info.MaxLengthInMemory,
info.FileStorage,
SandboxedProcessFile.StandardError,
info.StandardErrorObserver);
m_reports = m_fileAccessManifest != null ?
new SandboxedProcessReports(
m_fileAccessManifest,
info.PathTable,
info.PipSemiStableHash,
info.PipDescription,
info.LoggingContext,
info.DetoursEventListener) : null;
Contract.Assume(inputEncoding != null);
Contract.Assert(errorEncoding != null);
Contract.Assert(outputEncoding != null);
m_processIdListener = info.ProcessIdListener;
m_detouredProcess =
new DetouredProcess(
SandboxedProcessInfo.BufferSize,
info.GetCommandLine(),
info.WorkingDirectory,
info.GetUnicodeEnvironmentBlock(),
inputEncoding,
errorEncoding,
m_error.AppendLine,
outputEncoding,
m_output.AppendLine,
OnProcessExitingAsync,
OnProcessExited,
info.Timeout,
info.DisableConHostSharing,
info.LoggingContext,
info.TimeoutDumpDirectory);
}
/// <inheritdoc />
public string GetAccessedFileName(ReportedFileAccess reportedFileAccess)
{
return reportedFileAccess.GetPath(m_pathTable);
}
/// <inheritdoc />
public int GetLastMessageCount()
{
if (m_reports == null)
{
return 0; // We didn't count the messages.
}
return m_reports.GetLastMessageCount();
}
/// <inheritdoc />
public int ProcessId { get; private set; }
/// <inheritdoc />
public async Task<SandboxedProcessResult> GetResultAsync()
{
SandboxedProcessResult result = await m_resultTaskCompletionSource.Task;
// await yield to make sure we are not blocking the thread that called us
await Task.Yield();
return result;
}
/// <inheritdoc />
/// <remarks>
/// Gets the peak memory usage for the job object associated with the detoured process while the process is active.
/// </remarks>
public ulong? GetActivePeakMemoryUsage()
{
using (m_queryJobDataLock.AcquireReadLock())
{
var detouredProcess = m_detouredProcess;
if (detouredProcess == null ||
!detouredProcess.HasStarted ||
detouredProcess.HasExited ||
m_disposeStarted)
{
return null;
}
return detouredProcess.GetJobObject()?.GetPeakMemoryUsage();
}
}
/// <inheritdoc />
public long GetDetoursMaxHeapSize()
{
if (m_reports != null)
{
return m_reports.MaxDetoursHeapSize;
}
return 0L;
}
/// <summary>
/// Disposes this instance
/// </summary>
/// <remarks>
/// This may block on process clean-up, if a process is still running at Dispose-time. This ensures
/// that all pipes and outstanding I/O are finished when Dispose returns.
/// </remarks>
[SuppressMessage("Microsoft.Usage", "CA2213:DisposableFieldsShouldBeDisposed", MessageId = "m_detouredProcess")]
[SuppressMessage("Microsoft.Usage", "CA2213:DisposableFieldsShouldBeDisposed", MessageId = "m_reportReader")]
[SuppressMessage("Microsoft.Usage", "CA2213:DisposableFieldsShouldBeDisposed", MessageId = "m_reportReaderSemaphore")]
[SuppressMessage("Microsoft.Usage", "CA2213:DisposableFieldsShouldBeDisposed", MessageId = "m_error")]
[SuppressMessage("Microsoft.Usage", "CA2213:DisposableFieldsShouldBeDisposed", MessageId = "m_output")]
public void Dispose()
{
using (m_queryJobDataLock.AcquireWriteLock())
{
// Prevent further data queries
m_disposeStarted = true;
}
if (m_processStarted)
{
InternalKill();
m_resultTaskCompletionSource.Task.Wait();
}
m_detouredProcess?.Dispose();
m_detouredProcess = null;
m_output?.Dispose();
m_output = null;
m_error?.Dispose();
m_error = null;
m_reports = null;
m_fileAccessManifestStreamWrapper.Dispose();
}
/// <summary>
/// Kill sandboxed process
/// </summary>
/// <remarks>
/// Also kills all nested processes; if the process hasn't already finished by itself, the Result task gets canceled.
/// </remarks>
private void InternalKill()
{
Contract.Assume(m_processStarted);
// this will cause OnProcessExited to be invoked, which will in turn call SetResult(...).
// This allows Dispose to wait on process teardown.
m_detouredProcess?.Kill(ExitCodes.Killed);
}
/// <inheritdoc/>
public Task KillAsync()
{
InternalKill();
return GetResultAsync(); // ignore result, we just want to wait until process has terminated
}
/// <inheritdoc />
/// <remarks>
/// <exception cref="BuildXLException">Thrown if creating or detouring the process fails.</exception>
/// </remarks>
[SuppressMessage("Microsoft.Reliability", "CA2001:AvoidCallingProblematicMethods",
MessageId = "System.Runtime.InteropServices.SafeHandle.DangerousGetHandle", Justification = "We need to get the file handle.")]
[SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope",
Justification = "Objects are embedded in other objects.")]
[SuppressMessage("Microsoft.Naming", "CA2204:LiteralsShouldBeSpelledCorrectly")]
public void Start()
{
Contract.Assume(!m_processStarted);
Encoding reportEncoding = Encoding.Unicode;
SafeFileHandle childHandle = null;
DetouredProcess detouredProcess = m_detouredProcess;
using (m_reportReaderSemaphore.AcquireSemaphore())
{
SafeFileHandle reportHandle;
try
{
Pipes.CreateInheritablePipe(
Pipes.PipeInheritance.InheritWrite,
Pipes.PipeFlags.ReadSideAsync,
readHandle: out reportHandle,
writeHandle: out childHandle);
var setup =
new FileAccessSetup
{
ReportPath = "#" + childHandle.DangerousGetHandle().ToInt64(),
DllNameX64 = s_binaryPaths.DllNameX64,
DllNameX86 = s_binaryPaths.DllNameX86,
};
bool debugFlagsMatch = true;
ArraySegment<byte> manifestBytes = new ArraySegment<byte>();
if (m_fileAccessManifest != null)
{
manifestBytes = m_fileAccessManifest.GetPayloadBytes(setup, FileAccessManifestStream, m_timeoutMins, ref debugFlagsMatch);
}
if (!debugFlagsMatch)
{
throw new BuildXLException("Mismatching build type for BuildXL and DetoursServices.dll.");
}
m_standardInputTcs = TaskSourceSlim.Create<bool>();
detouredProcess.Start(
s_payloadGuid,
manifestBytes,
childHandle,
s_binaryPaths.DllNameX64,
s_binaryPaths.DllNameX86);
// At this point, we believe calling 'kill' will result in an eventual callback for job teardown.
// This knowledge is significant for ensuring correct cleanup if we did vs. did not start a process;
// if started, we expect teardown to happen eventually and clean everything up.
m_processStarted = true;
ProcessId = detouredProcess.GetProcessId();
m_processIdListener?.Invoke(ProcessId);
}
finally
{
// release memory
m_fileAccessManifest = null;
// Note that in the success path, childHandle should already be closed (by Start).
if (childHandle != null && !childHandle.IsInvalid)
{
childHandle.Dispose();
}
}
var reportFile = AsyncFileFactory.CreateAsyncFile(
reportHandle,
FileDesiredAccess.GenericRead,
ownsHandle: true,
kind: FileKind.Pipe);
StreamDataReceived reportLineReceivedCallback = m_reports == null ? (StreamDataReceived)null : m_reports.ReportLineReceived;
m_reportReader = new AsyncPipeReader(reportFile, reportLineReceivedCallback, reportEncoding, m_bufferSize);
m_reportReader.BeginReadLine();
}
// don't wait, we want feeding in of standard input to happen asynchronously
Analysis.IgnoreResult(FeedStandardInputAsync(detouredProcess, m_standardInputReader, m_standardInputTcs));
}
private static async Task FeedStandardInputAsync(DetouredProcess detouredProcess, TextReader reader, TaskSourceSlim<bool> stdInTcs)
{
try
{
// We always have a redirected handle, and we always close it eventually (even if we have no actual input to feed)
if (reader != null)
{
while (true)
{
string line = await reader.ReadLineAsync();
if (line == null)
{
break;
}
await detouredProcess.WriteStandardInputLineAsync(line);
}
}
detouredProcess.CloseStandardInput();
stdInTcs.TrySetResult(true);
}
catch (Exception e)
{
stdInTcs.TrySetException(e);
}
}
private async Task WaitUntilReportEof(bool cancel)
{
using (await m_reportReaderSemaphore.AcquireAsync())
{
if (m_reportReader != null)
{
if (!cancel)
{
await m_reportReader.WaitUntilEofAsync();
}
m_reportReader.Dispose();
m_reportReader = null;
}
}
}
private async Task OnProcessExitingAsync()
{
JobObject jobObject = m_detouredProcess.GetJobObject();
if (jobObject != null)
{
// If there are any remaining child processes, we wait for a moment.
// This should be a rare case, and even if we have to wait it should typically only be for a fraction of a second, so we simply wait synchronously (blocking the current thread).
if (!(await jobObject.WaitAsync(m_nestedProcessTerminationTimeout)))
{
HandleSurvivingChildProcesses(jobObject);
}
}
}
private async Task OnProcessExited()
{
// Wait until all incoming report messages from the detoured process have been handled.
await WaitUntilReportEof(m_detouredProcess.Killed);
// Ensure no further modifications to the report
m_reports?.Freeze();
// We can get extended accounting information (peak memory, etc. rolled up for the entire process tree) if this process was wrapped in a job.
JobObject.AccountingInformation? jobAccountingInformation = null;
JobObject jobObject = m_detouredProcess.GetJobObject();
if (jobObject != null)
{
jobAccountingInformation = jobObject.GetAccountingInformation();
}
ProcessTimes primaryProcessTimes = m_detouredProcess.GetTimesForPrimaryProcess();
IOException standardInputException = null;
try
{
await m_standardInputTcs.Task;
}
catch (IOException ex)
{
standardInputException = ex;
}
// Construct result; note that the process is expected to have exited at this point, even if we decided to forcefully kill it
// (this callback is always a result of the process handle being signaled).
int exitCode = 0;
if (m_reports?.MessageProcessingFailure != null)
{
exitCode = ExitCodes.MessageProcessingFailure;
}
else
{
Contract.Assert(m_detouredProcess.HasExited, "Detoured process has not been marked as exited");
exitCode = m_detouredProcess.GetExitCode();
}
SandboxedProcessResult result =
new SandboxedProcessResult
{
// If there is a message parsing failure, fail the pip.
ExitCode = exitCode,
Killed = m_detouredProcess.Killed,
TimedOut = m_detouredProcess.TimedOut,
HasDetoursInjectionFailures = m_detouredProcess.HasDetoursInjectionFailures,
SurvivingChildProcesses = m_survivingChildProcesses?.Values.ToArray(),
PrimaryProcessTimes = primaryProcessTimes,
JobAccountingInformation = jobAccountingInformation,
StandardOutput = m_output.Freeze(),
StandardError = m_error.Freeze(),
AllUnexpectedFileAccesses = m_reports?.FileUnexpectedAccesses,
FileAccesses = m_reports?.FileAccesses,
DetouringStatuses = m_reports?.ProcessDetoursStatuses,
ExplicitlyReportedFileAccesses = m_reports?.ExplicitlyReportedFileAccesses,
Processes = m_reports?.Processes,
DumpFileDirectory = m_detouredProcess.DumpFileDirectory,
DumpCreationException = m_detouredProcess.DumpCreationException,
StandardInputException = standardInputException,
MessageProcessingFailure = m_reports?.MessageProcessingFailure,
ProcessStartTime = m_detouredProcess.StartTime,
HasReadWriteToReadFileAccessRequest = m_reports?.HasReadWriteToReadFileAccessRequest ?? false,
};
SetResult(result);
}
private void HandleSurvivingChildProcesses(JobObject jobObject)
{
bool tooManySurvivingChildProcesses;
uint[] survivingChildProcessIds;
if (!jobObject.TryGetProcessIds(out survivingChildProcessIds, out tooManySurvivingChildProcesses) ||
(!tooManySurvivingChildProcesses && survivingChildProcessIds.Length == 0))
{
// no surviving child processes reported to us
return;
}
m_survivingChildProcesses = new Dictionary<uint, ReportedProcess>();
if (tooManySurvivingChildProcesses)
{
m_survivingChildProcesses.Add(0, new ReportedProcess(0, "too many surviving processes"));
}
else
{
foreach (uint processId in survivingChildProcessIds)
{
using (SafeProcessHandle processHandle = Native.Processes.ProcessUtilities.OpenProcess(
ProcessSecurityAndAccessRights.PROCESS_QUERY_INFORMATION |
ProcessSecurityAndAccessRights.PROCESS_VM_READ,
false,
processId))
{
if (processHandle.IsInvalid)
{
// we are too late: could not open process
continue;
}
if (!jobObject.ContainsProcess(processHandle))
{
// we are too late: process id got reused by another process
continue;
}
int exitCode;
if (!Native.Processes.ProcessUtilities.GetExitCodeProcess(processHandle, out exitCode))
{
// we are too late: process id got reused by another process
continue;
}
using (PooledObjectWrapper<StringBuilder> wrap = Pools.GetStringBuilder())
{
StringBuilder sb = wrap.Instance;
if (sb.Capacity < MaxProcessPathLength)
{
sb.Capacity = MaxProcessPathLength;
}
if (Native.Processes.ProcessUtilities.GetModuleFileNameEx(processHandle, IntPtr.Zero, sb, (uint)sb.Capacity) <= 0)
{
// we are probably too late
continue;
}
// Attempt to read the process arguments (command line) from the process
// memory. This is not fatal if it does not succeed.
string processArgs = string.Empty;
var basicInfoSize = (uint)Marshal.SizeOf<Native.Processes.Windows.ProcessUtilitiesWin.PROCESS_BASIC_INFORMATION>();
var basicInfoPtr = Marshal.AllocHGlobal((int)basicInfoSize);
uint basicInfoReadLen;
try
{
if (Native.Processes.Windows.ProcessUtilitiesWin.NtQueryInformationProcess(
processHandle,
Native.Processes.Windows.ProcessUtilitiesWin.ProcessInformationClass.ProcessBasicInformation,
basicInfoPtr, basicInfoSize, out basicInfoReadLen) == 0)
{
Native.Processes.Windows.ProcessUtilitiesWin.PROCESS_BASIC_INFORMATION basicInformation = Marshal.PtrToStructure<Native.Processes.Windows.ProcessUtilitiesWin.PROCESS_BASIC_INFORMATION>(basicInfoPtr);
Contract.Assert(basicInformation.UniqueProcessId == processId);
// NativeMethods.ReadProcessStructure and NativeMethods.ReadUnicodeString handle null\zero addresses
// passed into them. Since these are all value types, then there is no need to do any type
// of checking as passing zero through will just result in an empty process args string.
var peb = Native.Processes.Windows.ProcessUtilitiesWin.ReadProcessStructure<Native.Processes.Windows.ProcessUtilitiesWin.PEB>(processHandle, basicInformation.PebBaseAddress);
var processParameters = Native.Processes.Windows.ProcessUtilitiesWin.ReadProcessStructure<Native.Processes.Windows.ProcessUtilitiesWin.RTL_USER_PROCESS_PARAMETERS>(processHandle, peb.ProcessParameters);
processArgs = Native.Processes.Windows.ProcessUtilitiesWin.ReadProcessUnicodeString(processHandle, processParameters.CommandLine);
}
}
finally
{
Marshal.FreeHGlobal(basicInfoPtr);
}
string path = sb.ToString();
m_survivingChildProcesses.Add(processId, new ReportedProcess(processId, path, processArgs));
}
}
}
}
if (m_survivingChildProcesses.Count > 0)
{
m_detouredProcess.Kill(ExitCodes.KilledSurviving);
}
}
private void SetResult(SandboxedProcessResult result)
{
Contract.Requires(m_detouredProcess != null);
m_resultTaskCompletionSource.SetResult(result);
}
/// <summary>
/// Start a sand-boxed process asynchronously. The result will only be available once the process terminates.
/// </summary>
/// <exception cref="BuildXLException">
/// Thrown if the process creation fails in a recoverable manner due do some obscure problem detected by the underlying
/// ProcessCreate call.
/// </exception>
[SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "Object lives on via task result.")]
public static async Task<SandboxedProcess> StartAsync(SandboxedProcessInfo info)
{
var process = await SandboxedProcessFactory.StartAsync(info, forceSandboxing: true);
return (SandboxedProcess)process;
}
}
}
| 44.923948 | 239 | 0.560206 | [
"MIT"
] | blufugen/BuildXL | Public/src/Engine/Processes/SandboxedProcess.cs | 27,763 | C# |
///////////////////////////////////////////////////////////////////////////////
//
// Microsoft Research Singularity
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// File: CategoryAttributes.cs
//
// Warning: This file is compiled into the kernel, and into the runtime.
// In order to get the visibility correct in all cases, some #ifs
// are needed
//
// New Design:
// This now conforms with the ideas presented in the Genesis papers,
// chapter 3. In particular, a device driver is simply a Category,
// and anything that is in an app manifest is either intrinsic to
// apps/installations (and hence not a decoration), or else a
// PropertySet or Category.
using System;
namespace Microsoft.Singularity.Configuration
{
//
// The master Category declaration
//
// Configuration are optional. If none are specified, then the app should
// be thought of as only having one (default) Category.
//
// A class that declares a Category must descend from this class
//
public class CategoryDeclaration
{
}
//////////////////////////////////////////////////////////////////////////
//
// CategoryAttribute
//
// Purpose: Decorates a class derived from CategoryDeclaration to
// indicate that the metadata parser should declare a category
// from the fields in this class
//
// Usage: Must decorate a class derived from CategoryDeclaration
//
[AttributeUsage(AttributeTargets.Class, AllowMultiple = false)]
public class CategoryAttribute : System.Attribute
{
// <<name>> is the name for this category, to distinguish between
// multiple categories in the manifest
private string name;
public CategoryAttribute(string name)
{
this.name = name;
}
}
//
// The Console Category
//
// Console apps are apps that run in a special Category. We will designate this
// by deriving a new class from CategoryDeclaration to represent this
// special Category, and then creating special field annotations that only
// apply to this Category.
//
public abstract class ConsoleCategoryDeclaration : CategoryDeclaration
{
internal abstract int AppMain();
}
//////////////////////////////////////////////////////////////////////////
//
// ConsoleCategoryAttribute
//
// Purpose: Top-level metadata indicating that an assembly implements the
// Console Category
//
// Usage: Must be applied to a class derived from
// ConsoleCategoryDeclaration
//
[AttributeUsage(AttributeTargets.Class, AllowMultiple = false)]
public class ConsoleCategoryAttribute : System.Attribute
{
public ConsoleCategoryAttribute()
{
}
private string action;
private string helpMessage;
private bool defaultAction;
public string HelpMessage
{
get {return helpMessage;}
set {helpMessage = value;}
}
public string Action
{
get {return action;}
set {action = value;}
}
public bool DefaultAction
{
get {return defaultAction;}
set {defaultAction = value;}
}
}
//////////////////////////////////////////////////////////////////////////
//
// InputEndpointAttribute
//
// Purpose: Console Input Unicode Pipe declaration
// kinds are "data" and "control". Control is used for a 2nd
// input pipe such as in More and replaces the "keyboard"
[AttributeUsage(AttributeTargets.Field, AllowMultiple = false)]
public class InputEndpointAttribute : EndpointAttribute {
private string kind;
public InputEndpointAttribute(string kind) {
this.kind = kind;
}
public string Kind {
get {return kind;}
set {kind = value;}
}
}
//////////////////////////////////////////////////////////////////////////
//
// OutputEndpointAttribute
//
// Purpose: Console Input Unicode Pipe declaration
// kinds are "data" and "control". Control is used for a 2nd
// input pipe such as in More and replaces the "keyboard"
[AttributeUsage(AttributeTargets.Field, AllowMultiple = false)]
public class OutputEndpointAttribute : EndpointAttribute {
private string kind;
public OutputEndpointAttribute(string kind) {
this.kind = kind;
}
public string Kind {
get {return kind;}
set {kind = value;}
}
}
//////////////////////////////////////////////////////////////////////////
//
// EndpointAttribute
//
// Purpose: Any non-ServiceProvider that is a requirement ought to be
// declared with this attribute. This will tell CTR to pre-bind
// the endpoint and will tell the config the type of the channel
// so that names can be resolved without the assembly declaring
// them
//
// Usage: Decorates a field within a class decorated with
// [DriverCategory]. The field should be an endpoint.
//
[AttributeUsage(AttributeTargets.Field, AllowMultiple = false)]
public class EndpointAttribute : System.Attribute {
public string bindPath;
public EndpointAttribute() {
}
public string Path {
get {return bindPath;}
set {bindPath = value;}
}
}
//////////////////////////////////////////////////////////////////////////
//
// CustomEndpointAttribute
//
// Purpose: Any endpoint that an app does not want the Binder.LoadManifest
// to fill in should be declared with this attribute.
// This will tell CTR to pre-bind
// the endpoint and will tell the config the type of the channel
// so that names can be resolved without the assembly declaring
// them
//
// Usage: Decorates a field within a class decorated with
// [DriverCategory]. The field should be an endpoint.
//
[AttributeUsage(AttributeTargets.Field, AllowMultiple = false)]
public class CustomEndpointAttribute : EndpointAttribute
{
public CustomEndpointAttribute() {
}
}
//////////////////////////////////////////////////////////////////////////
//
// ExtensionEndpointAttribute
//
// Purpose: Decorate an extension endpoint and indicate that CTR should bind
// the endpoint before client code is invoked.
//
// Usage: Decorates an ExtensionEndpoint field within a class
// decorated with [DriverCategory]
//
[AttributeUsage(AttributeTargets.Field, AllowMultiple = false)]
public class ExtensionEndpointAttribute : EndpointAttribute
{
public ExtensionEndpointAttribute()
{
}
}
//////////////////////////////////////////////////////////////////////////
//
// ServiceEndpointAttribute
//
// Purpose: Decorate a ServiceProvider endpoint. This indicates that the
// endpoint will be pre-bound, so that the kernel can determine
// names and drivers cannot. The parameter indicates the type of
// channel that is created (second order) from this
// ServiceProvider.
//
// Usage: Decorates a ServiceProvider field within a class decorated
// with [DriverCategory]
//
[AttributeUsage(AttributeTargets.Field, AllowMultiple = false)]
public class ServiceEndpointAttribute : EndpointAttribute
{
// <<serviceContractType>> is a required parameter. It gives the type
// of the contract that is served over this ServiceProvider
// The Exp is implicit, that is, we can just specify the contract type
//
private System.Type serviceContractType;
//private string bindPath;
public ServiceEndpointAttribute(System.Type epType)
{
serviceContractType = epType;
}
// public string Path
// {
// get {return bindPath;}
// set {bindPath = value;}
// }
#if SINGULARITY_KERNEL
// <<customname>> is a kernel-only hack to let the Hal console set a
// special name for itself.
private string customName;
public string CustomName
{
get { return customName; }
set { customName = value; }
}
#endif
}
//////////////////////////////////////////////////////////////////////////
///
/// Parameter Attributes
///
//////////////////////////////////////////////////////////////////////////
[AttributeUsage(AttributeTargets.Field, AllowMultiple = false)]
public sealed class StringParameterAttribute : ParameterAttribute
{
private string defaultValue;
//[NotDelayed]
public StringParameterAttribute(string ArgumentName)
:base(ArgumentName)
{
}
public string Default
{
get { return defaultValue; }
set { defaultValue = value; }
}
}
[AttributeUsage(AttributeTargets.Field, AllowMultiple = false)]
public sealed class StringArrayParameterAttribute : ParameterAttribute
{
private string[] defaultValue;
//[NotDelayed]
public StringArrayParameterAttribute(string ArgumentName)
:base(ArgumentName)
{
}
public string[] Default
{
get { return defaultValue; }
set { defaultValue = value; }
}
}
[AttributeUsage(AttributeTargets.Field, AllowMultiple = false)]
public sealed class LongParameterAttribute : ParameterAttribute
{
private long defaultValue;
public LongParameterAttribute(string ArgumentName)
:base(ArgumentName)
{
defaultValue = -1;
Position = -1;
}
public long Default
{
get { return defaultValue; }
set { defaultValue = value; }
}
}
[AttributeUsage(AttributeTargets.Field, AllowMultiple = false)]
public sealed class BoolParameterAttribute : ParameterAttribute
{
private bool defaultValue;
public BoolParameterAttribute(string name)
:base(name)
{
defaultValue = false;
Position = -1;
}
public bool Default
{
get { return defaultValue; }
set { defaultValue = value; }
}
}
[AttributeUsage(AttributeTargets.Field, AllowMultiple = true)]
public class ParameterAttribute : System.Attribute
{
private int position;
private string helpMessage;
private bool mandatory;
private string name;
public ParameterAttribute(string Name)
{
this.name = Name;
}
public bool Mandatory
{
get { return mandatory; }
set { mandatory = value; }
}
public string Name
{
get { return name; }
set { name = value; }
}
public int Position
{
get { return position; }
set { position = value; }
}
public string HelpMessage
{
get { return helpMessage; }
set { helpMessage = value; }
}
}
}
| 31.205656 | 86 | 0.533322 | [
"MIT"
] | sphinxlogic/Singularity-RDK-2.0 | base/Kernel/Singularity/Io/CategoryAttributes.cs | 12,139 | C# |
Subsets and Splits