content
stringlengths
5
1.04M
avg_line_length
float64
1.75
12.9k
max_line_length
int64
2
244k
alphanum_fraction
float64
0
0.98
licenses
list
repository_name
stringlengths
7
92
path
stringlengths
3
249
size
int64
5
1.04M
lang
stringclasses
2 values
///////////////////////////////////////////////////////////////////////////////////////////////// // // Favalon - An Interactive Shell Based on a Typed Lambda Calculus. // Copyright (c) 2018-2020 Kouji Matsui (@kozy_kekyo, @kekyo2) // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ///////////////////////////////////////////////////////////////////////////////////////////////// using System.ComponentModel; using Favalet.Contexts; using Favalet.Expressions.Specialized; using Favalet.Ranges; using System.Diagnostics; namespace Favalet.Expressions.Algebraic { public interface IAndExpression : IBinaryExpression { } public sealed class AndExpression : BinaryExpression<IAndExpression>, IAndExpression { [DebuggerStepThrough] private AndExpression( IExpression left, IExpression right, IExpression higherOrder, TextRange range) : base(left, right, higherOrder, range) { } [DebuggerStepThrough] internal override IExpression OnCreate( IExpression left, IExpression right, IExpression higherOrder, TextRange range) => new AndExpression(left, right, higherOrder, range); [DebuggerStepThrough] public static AndExpression Create( IExpression left, IExpression right, TextRange range) => new AndExpression(left, right, UnspecifiedTerm.Instance, range); [DebuggerStepThrough] [EditorBrowsable(EditorBrowsableState.Never)] public static AndExpression UnsafeCreate( IExpression left, IExpression right, IExpression higherOrder, TextRange range) => new AndExpression(left, right, higherOrder, range); } }
37.745763
98
0.645263
[ "Apache-2.0" ]
kekyo/Favalon
Favalet.Core/Expressions/Algebraic/AndExpression.cs
2,229
C#
using System; namespace RuriLib.Exceptions { public class LoliCodeParsingException : Exception { public int LineNumber { get; set; } public LoliCodeParsingException(int lineNumber) { LineNumber = lineNumber; } public LoliCodeParsingException(int lineNumber, string message) : base($"[Line {lineNumber}] {message}") { LineNumber = lineNumber; } public LoliCodeParsingException(int lineNumber, string message, Exception inner) : base($"[Line {lineNumber}] {message}", inner) { LineNumber = lineNumber; } } }
24.555556
88
0.588235
[ "MIT" ]
542980940984363224858439616269115634540/OpenBullet2
RuriLib/Exceptions/LoliCodeParsingException.cs
665
C#
//#define USE_LAYER using System; using System.Reactive.Disposables; using System.Reactive.Linq; using AppKit; using Foundation; using ReactiveUI; using UniversalGraphics.Quartz2D; using UniversalGraphics.Test.Infrastructures; using UniversalGraphics.Test.ViewModels; namespace UniversalGraphics.Test { public partial class ViewController : ReactiveViewController<ViewModel> { private readonly NSString INDEX_OF_SELECTED_ITEM_PROPERTY_NAME = new NSString("indexOfSelectedItem"); private CompositeDisposable _disposables; #if USE_LAYER private UGCanvasCALayer _layer; #else private UGCanvasView _canvas; #endif public ViewController(IntPtr handle) : base(handle) { _disposables = new CompositeDisposable(); } protected override void Dispose(bool disposing) { base.Dispose(disposing); if (disposing) { #if USE_LAYER if (_layer != null) { _layer.RemoveFromSuperLayer(); _layer.Dispose(); _layer = null; } #else if (_canvas != null) { _canvas.Dispose(); _canvas = null; } #endif } } public override void ViewDidLoad() { base.ViewDidLoad(); var frame = View.Frame; frame.Height -= delegatePopUpButton.VisibleRect().Height; #if USE_LAYER View.WantsLayer = true; var layer = new UGCanvasCALayer(); layer.Frame = View.Frame; View.Layer.AddSublayer(layer); _layer = layer; #else var canvas = new UGCanvasView(frame) { AutoresizingMask = NSViewResizingMask.WidthSizable | NSViewResizingMask.HeightSizable, }; View.AddSubview(canvas); _canvas = canvas; #endif ViewModel = new ViewModel(); this.WhenAnyValue(v => v.ViewModel.Data) .Subscribe(data => { delegatePopUpButton.RemoveAllItems(); delegatePopUpButton.AddItems(data); }) .AddTo(_disposables); this.WhenAnyValue(v => v.ViewModel.SelectedIndex) .Subscribe(idx => delegatePopUpButton.SelectItem(idx)) .AddTo(_disposables); Observable.FromEvent<EventHandler, EventArgs>( f => (s, e) => f(e), h => delegatePopUpButton.Activated += h, h => delegatePopUpButton.Activated -= h) .Subscribe(_ => ViewModel.SelectedIndex = (int)delegatePopUpButton.IndexOfSelectedItem) .AddTo(_disposables); #if USE_LAYER this.OneWayBind(ViewModel, vm => vm.Delegate, v => v._layer.CanvasDelegate) .AddTo(_disposables); #else this.OneWayBind(ViewModel, vm => vm.Delegate, v => v._canvas.Delegate) .AddTo(_disposables); #endif } } }
23.855769
103
0.708988
[ "MIT" ]
mntone/UniversalGraphics
test/Quartz2D/ViewController.cs
2,483
C#
// Copyright (c) Benjamin Proemmer. All rights reserved. // See License in the project root for license information. using Dacs7.Protocols.SiemensPlc; using System.Collections.Generic; namespace Dacs7.Protocols { internal sealed class WritePackage { private const int _writeItemHeaderSize = SiemensPlcProtocolContext.WriteParameterItem + SiemensPlcProtocolContext.WriteDataItem; private const int _minimumSize = _writeItemHeaderSize + 1; private readonly int _maxSize; private readonly List<WriteItem> _items = new List<WriteItem>(); public bool Handled { get; private set; } public bool Full => Free < _minimumSize; public int Size { get; private set; } = SiemensPlcProtocolContext.WriteHeader + SiemensPlcProtocolContext.WriteParameter; public int Free => _maxSize - Size; public IEnumerable<WriteItem> Items => _items; public WritePackage(int pduSize) => _maxSize = pduSize; // minimum header = 12 read 14 readack public WritePackage Return() { Handled = true; return this; } public bool TryAdd(WriteItem item) { var size = item.NumberOfItems; var itemSize = _writeItemHeaderSize + size; if (Free >= itemSize) { _items.Add(item); Size += itemSize; if (Size % 2 != 0) { Size++; // set the next item to a even address } return true; } return false; } } }
28.051724
136
0.595575
[ "Apache-2.0" ]
proemmer/dacs7
dacs7/src/Dacs7/Protocols/WritePackage.cs
1,629
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Slower : Enemy { [SerializeField] float _slowAmount = 5; protected override void PlayerImpact(Player player) { TankController controller = player.GetComponent<TankController>(); controller.MoveSpeed -= _slowAmount; gameObject.SetActive(false); } }
21.764706
69
0.743243
[ "MIT" ]
gummiez/CaoTyty_4368_P01A
Assets/Scripts/Slower.cs
372
C#
using UnityEngine; using System; using LuaInterface; using SLua; using System.Collections.Generic; public class Lua_UnityEngine_Application : LuaObject { [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int constructor(IntPtr l) { try { UnityEngine.Application o; o=new UnityEngine.Application(); pushValue(l,o); return 1; } catch(Exception e) { LuaDLL.luaL_error(l, e.ToString()); return 0; } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int Quit_s(IntPtr l) { try { UnityEngine.Application.Quit(); return 0; } catch(Exception e) { LuaDLL.luaL_error(l, e.ToString()); return 0; } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int CancelQuit_s(IntPtr l) { try { UnityEngine.Application.CancelQuit(); return 0; } catch(Exception e) { LuaDLL.luaL_error(l, e.ToString()); return 0; } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int LoadLevel_s(IntPtr l) { try { int argc = LuaDLL.lua_gettop(l); if(matchType(l,argc,1,typeof(int))){ System.Int32 a1; checkType(l,1,out a1); UnityEngine.Application.LoadLevel(a1); return 0; } else if(matchType(l,argc,1,typeof(string))){ System.String a1; checkType(l,1,out a1); UnityEngine.Application.LoadLevel(a1); return 0; } LuaDLL.luaL_error(l,"No matched override function to call"); return 0; } catch(Exception e) { LuaDLL.luaL_error(l, e.ToString()); return 0; } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int LoadLevelAsync_s(IntPtr l) { try { int argc = LuaDLL.lua_gettop(l); if(matchType(l,argc,1,typeof(int))){ System.Int32 a1; checkType(l,1,out a1); UnityEngine.AsyncOperation ret=UnityEngine.Application.LoadLevelAsync(a1); pushValue(l,ret); return 1; } else if(matchType(l,argc,1,typeof(string))){ System.String a1; checkType(l,1,out a1); UnityEngine.AsyncOperation ret=UnityEngine.Application.LoadLevelAsync(a1); pushValue(l,ret); return 1; } LuaDLL.luaL_error(l,"No matched override function to call"); return 0; } catch(Exception e) { LuaDLL.luaL_error(l, e.ToString()); return 0; } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int LoadLevelAdditiveAsync_s(IntPtr l) { try { int argc = LuaDLL.lua_gettop(l); if(matchType(l,argc,1,typeof(int))){ System.Int32 a1; checkType(l,1,out a1); UnityEngine.AsyncOperation ret=UnityEngine.Application.LoadLevelAdditiveAsync(a1); pushValue(l,ret); return 1; } else if(matchType(l,argc,1,typeof(string))){ System.String a1; checkType(l,1,out a1); UnityEngine.AsyncOperation ret=UnityEngine.Application.LoadLevelAdditiveAsync(a1); pushValue(l,ret); return 1; } LuaDLL.luaL_error(l,"No matched override function to call"); return 0; } catch(Exception e) { LuaDLL.luaL_error(l, e.ToString()); return 0; } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int LoadLevelAdditive_s(IntPtr l) { try { int argc = LuaDLL.lua_gettop(l); if(matchType(l,argc,1,typeof(int))){ System.Int32 a1; checkType(l,1,out a1); UnityEngine.Application.LoadLevelAdditive(a1); return 0; } else if(matchType(l,argc,1,typeof(string))){ System.String a1; checkType(l,1,out a1); UnityEngine.Application.LoadLevelAdditive(a1); return 0; } LuaDLL.luaL_error(l,"No matched override function to call"); return 0; } catch(Exception e) { LuaDLL.luaL_error(l, e.ToString()); return 0; } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int GetStreamProgressForLevel_s(IntPtr l) { try { int argc = LuaDLL.lua_gettop(l); if(matchType(l,argc,1,typeof(int))){ System.Int32 a1; checkType(l,1,out a1); System.Single ret=UnityEngine.Application.GetStreamProgressForLevel(a1); pushValue(l,ret); return 1; } else if(matchType(l,argc,1,typeof(string))){ System.String a1; checkType(l,1,out a1); System.Single ret=UnityEngine.Application.GetStreamProgressForLevel(a1); pushValue(l,ret); return 1; } LuaDLL.luaL_error(l,"No matched override function to call"); return 0; } catch(Exception e) { LuaDLL.luaL_error(l, e.ToString()); return 0; } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int CanStreamedLevelBeLoaded_s(IntPtr l) { try { int argc = LuaDLL.lua_gettop(l); if(matchType(l,argc,1,typeof(int))){ System.Int32 a1; checkType(l,1,out a1); System.Boolean ret=UnityEngine.Application.CanStreamedLevelBeLoaded(a1); pushValue(l,ret); return 1; } else if(matchType(l,argc,1,typeof(string))){ System.String a1; checkType(l,1,out a1); System.Boolean ret=UnityEngine.Application.CanStreamedLevelBeLoaded(a1); pushValue(l,ret); return 1; } LuaDLL.luaL_error(l,"No matched override function to call"); return 0; } catch(Exception e) { LuaDLL.luaL_error(l, e.ToString()); return 0; } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int CaptureScreenshot_s(IntPtr l) { try { int argc = LuaDLL.lua_gettop(l); if(argc==2){ System.String a1; checkType(l,1,out a1); System.Int32 a2; checkType(l,2,out a2); UnityEngine.Application.CaptureScreenshot(a1,a2); return 0; } else if(argc==1){ System.String a1; checkType(l,1,out a1); UnityEngine.Application.CaptureScreenshot(a1); return 0; } LuaDLL.luaL_error(l,"No matched override function to call"); return 0; } catch(Exception e) { LuaDLL.luaL_error(l, e.ToString()); return 0; } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int HasProLicense_s(IntPtr l) { try { System.Boolean ret=UnityEngine.Application.HasProLicense(); pushValue(l,ret); return 1; } catch(Exception e) { LuaDLL.luaL_error(l, e.ToString()); return 0; } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int ExternalCall_s(IntPtr l) { try { System.String a1; checkType(l,1,out a1); System.Object[] a2; checkParams(l,2,out a2); UnityEngine.Application.ExternalCall(a1,a2); return 0; } catch(Exception e) { LuaDLL.luaL_error(l, e.ToString()); return 0; } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int OpenURL_s(IntPtr l) { try { System.String a1; checkType(l,1,out a1); UnityEngine.Application.OpenURL(a1); return 0; } catch(Exception e) { LuaDLL.luaL_error(l, e.ToString()); return 0; } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int RequestUserAuthorization_s(IntPtr l) { try { UnityEngine.UserAuthorization a1; checkEnum(l,1,out a1); UnityEngine.AsyncOperation ret=UnityEngine.Application.RequestUserAuthorization(a1); pushValue(l,ret); return 1; } catch(Exception e) { LuaDLL.luaL_error(l, e.ToString()); return 0; } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int HasUserAuthorization_s(IntPtr l) { try { UnityEngine.UserAuthorization a1; checkEnum(l,1,out a1); System.Boolean ret=UnityEngine.Application.HasUserAuthorization(a1); pushValue(l,ret); return 1; } catch(Exception e) { LuaDLL.luaL_error(l, e.ToString()); return 0; } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int get_loadedLevel(IntPtr l) { try { pushValue(l,UnityEngine.Application.loadedLevel); return 1; } catch(Exception e) { LuaDLL.luaL_error(l, e.ToString()); return 0; } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int get_loadedLevelName(IntPtr l) { try { pushValue(l,UnityEngine.Application.loadedLevelName); return 1; } catch(Exception e) { LuaDLL.luaL_error(l, e.ToString()); return 0; } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int get_isLoadingLevel(IntPtr l) { try { pushValue(l,UnityEngine.Application.isLoadingLevel); return 1; } catch(Exception e) { LuaDLL.luaL_error(l, e.ToString()); return 0; } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int get_levelCount(IntPtr l) { try { pushValue(l,UnityEngine.Application.levelCount); return 1; } catch(Exception e) { LuaDLL.luaL_error(l, e.ToString()); return 0; } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int get_streamedBytes(IntPtr l) { try { pushValue(l,UnityEngine.Application.streamedBytes); return 1; } catch(Exception e) { LuaDLL.luaL_error(l, e.ToString()); return 0; } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int get_isPlaying(IntPtr l) { try { pushValue(l,UnityEngine.Application.isPlaying); return 1; } catch(Exception e) { LuaDLL.luaL_error(l, e.ToString()); return 0; } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int get_isEditor(IntPtr l) { try { pushValue(l,UnityEngine.Application.isEditor); return 1; } catch(Exception e) { LuaDLL.luaL_error(l, e.ToString()); return 0; } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int get_isWebPlayer(IntPtr l) { try { pushValue(l,UnityEngine.Application.isWebPlayer); return 1; } catch(Exception e) { LuaDLL.luaL_error(l, e.ToString()); return 0; } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int get_platform(IntPtr l) { try { pushEnum(l,(int)UnityEngine.Application.platform); return 1; } catch(Exception e) { LuaDLL.luaL_error(l, e.ToString()); return 0; } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int get_isMobilePlatform(IntPtr l) { try { pushValue(l,UnityEngine.Application.isMobilePlatform); return 1; } catch(Exception e) { LuaDLL.luaL_error(l, e.ToString()); return 0; } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int get_isConsolePlatform(IntPtr l) { try { pushValue(l,UnityEngine.Application.isConsolePlatform); return 1; } catch(Exception e) { LuaDLL.luaL_error(l, e.ToString()); return 0; } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int get_runInBackground(IntPtr l) { try { pushValue(l,UnityEngine.Application.runInBackground); return 1; } catch(Exception e) { LuaDLL.luaL_error(l, e.ToString()); return 0; } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int set_runInBackground(IntPtr l) { try { bool v; checkType(l,2,out v); UnityEngine.Application.runInBackground=v; return 0; } catch(Exception e) { LuaDLL.luaL_error(l, e.ToString()); return 0; } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int get_dataPath(IntPtr l) { try { pushValue(l,UnityEngine.Application.dataPath); return 1; } catch(Exception e) { LuaDLL.luaL_error(l, e.ToString()); return 0; } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int get_streamingAssetsPath(IntPtr l) { try { pushValue(l,UnityEngine.Application.streamingAssetsPath); return 1; } catch(Exception e) { LuaDLL.luaL_error(l, e.ToString()); return 0; } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int get_persistentDataPath(IntPtr l) { try { pushValue(l,UnityEngine.Application.persistentDataPath); return 1; } catch(Exception e) { LuaDLL.luaL_error(l, e.ToString()); return 0; } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int get_temporaryCachePath(IntPtr l) { try { pushValue(l,UnityEngine.Application.temporaryCachePath); return 1; } catch(Exception e) { LuaDLL.luaL_error(l, e.ToString()); return 0; } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int get_srcValue(IntPtr l) { try { pushValue(l,UnityEngine.Application.srcValue); return 1; } catch(Exception e) { LuaDLL.luaL_error(l, e.ToString()); return 0; } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int get_absoluteURL(IntPtr l) { try { pushValue(l,UnityEngine.Application.absoluteURL); return 1; } catch(Exception e) { LuaDLL.luaL_error(l, e.ToString()); return 0; } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int get_unityVersion(IntPtr l) { try { pushValue(l,UnityEngine.Application.unityVersion); return 1; } catch(Exception e) { LuaDLL.luaL_error(l, e.ToString()); return 0; } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int get_version(IntPtr l) { try { pushValue(l,UnityEngine.Application.version); return 1; } catch(Exception e) { LuaDLL.luaL_error(l, e.ToString()); return 0; } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int get_bundleIdentifier(IntPtr l) { try { pushValue(l,UnityEngine.Application.bundleIdentifier); return 1; } catch(Exception e) { LuaDLL.luaL_error(l, e.ToString()); return 0; } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int get_installMode(IntPtr l) { try { pushEnum(l,(int)UnityEngine.Application.installMode); return 1; } catch(Exception e) { LuaDLL.luaL_error(l, e.ToString()); return 0; } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int get_sandboxType(IntPtr l) { try { pushEnum(l,(int)UnityEngine.Application.sandboxType); return 1; } catch(Exception e) { LuaDLL.luaL_error(l, e.ToString()); return 0; } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int get_productName(IntPtr l) { try { pushValue(l,UnityEngine.Application.productName); return 1; } catch(Exception e) { LuaDLL.luaL_error(l, e.ToString()); return 0; } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int get_companyName(IntPtr l) { try { pushValue(l,UnityEngine.Application.companyName); return 1; } catch(Exception e) { LuaDLL.luaL_error(l, e.ToString()); return 0; } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int get_cloudProjectId(IntPtr l) { try { pushValue(l,UnityEngine.Application.cloudProjectId); return 1; } catch(Exception e) { LuaDLL.luaL_error(l, e.ToString()); return 0; } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int get_webSecurityEnabled(IntPtr l) { try { pushValue(l,UnityEngine.Application.webSecurityEnabled); return 1; } catch(Exception e) { LuaDLL.luaL_error(l, e.ToString()); return 0; } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int get_webSecurityHostUrl(IntPtr l) { try { pushValue(l,UnityEngine.Application.webSecurityHostUrl); return 1; } catch(Exception e) { LuaDLL.luaL_error(l, e.ToString()); return 0; } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int get_targetFrameRate(IntPtr l) { try { pushValue(l,UnityEngine.Application.targetFrameRate); return 1; } catch(Exception e) { LuaDLL.luaL_error(l, e.ToString()); return 0; } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int set_targetFrameRate(IntPtr l) { try { int v; checkType(l,2,out v); UnityEngine.Application.targetFrameRate=v; return 0; } catch(Exception e) { LuaDLL.luaL_error(l, e.ToString()); return 0; } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int get_systemLanguage(IntPtr l) { try { pushEnum(l,(int)UnityEngine.Application.systemLanguage); return 1; } catch(Exception e) { LuaDLL.luaL_error(l, e.ToString()); return 0; } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int get_backgroundLoadingPriority(IntPtr l) { try { pushEnum(l,(int)UnityEngine.Application.backgroundLoadingPriority); return 1; } catch(Exception e) { LuaDLL.luaL_error(l, e.ToString()); return 0; } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int set_backgroundLoadingPriority(IntPtr l) { try { UnityEngine.ThreadPriority v; checkEnum(l,2,out v); UnityEngine.Application.backgroundLoadingPriority=v; return 0; } catch(Exception e) { LuaDLL.luaL_error(l, e.ToString()); return 0; } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int get_internetReachability(IntPtr l) { try { pushEnum(l,(int)UnityEngine.Application.internetReachability); return 1; } catch(Exception e) { LuaDLL.luaL_error(l, e.ToString()); return 0; } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int get_genuine(IntPtr l) { try { pushValue(l,UnityEngine.Application.genuine); return 1; } catch(Exception e) { LuaDLL.luaL_error(l, e.ToString()); return 0; } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int get_genuineCheckAvailable(IntPtr l) { try { pushValue(l,UnityEngine.Application.genuineCheckAvailable); return 1; } catch(Exception e) { LuaDLL.luaL_error(l, e.ToString()); return 0; } } static public void reg(IntPtr l) { getTypeTable(l,"UnityEngine.Application"); addMember(l,Quit_s); addMember(l,CancelQuit_s); addMember(l,LoadLevel_s); addMember(l,LoadLevelAsync_s); addMember(l,LoadLevelAdditiveAsync_s); addMember(l,LoadLevelAdditive_s); addMember(l,GetStreamProgressForLevel_s); addMember(l,CanStreamedLevelBeLoaded_s); addMember(l,CaptureScreenshot_s); addMember(l,HasProLicense_s); addMember(l,ExternalCall_s); addMember(l,OpenURL_s); addMember(l,RequestUserAuthorization_s); addMember(l,HasUserAuthorization_s); addMember(l,"loadedLevel",get_loadedLevel,null,false); addMember(l,"loadedLevelName",get_loadedLevelName,null,false); addMember(l,"isLoadingLevel",get_isLoadingLevel,null,false); addMember(l,"levelCount",get_levelCount,null,false); addMember(l,"streamedBytes",get_streamedBytes,null,false); addMember(l,"isPlaying",get_isPlaying,null,false); addMember(l,"isEditor",get_isEditor,null,false); addMember(l,"isWebPlayer",get_isWebPlayer,null,false); addMember(l,"platform",get_platform,null,false); addMember(l,"isMobilePlatform",get_isMobilePlatform,null,false); addMember(l,"isConsolePlatform",get_isConsolePlatform,null,false); addMember(l,"runInBackground",get_runInBackground,set_runInBackground,false); addMember(l,"dataPath",get_dataPath,null,false); addMember(l,"streamingAssetsPath",get_streamingAssetsPath,null,false); addMember(l,"persistentDataPath",get_persistentDataPath,null,false); addMember(l,"temporaryCachePath",get_temporaryCachePath,null,false); addMember(l,"srcValue",get_srcValue,null,false); addMember(l,"absoluteURL",get_absoluteURL,null,false); addMember(l,"unityVersion",get_unityVersion,null,false); addMember(l,"version",get_version,null,false); addMember(l,"bundleIdentifier",get_bundleIdentifier,null,false); addMember(l,"installMode",get_installMode,null,false); addMember(l,"sandboxType",get_sandboxType,null,false); addMember(l,"productName",get_productName,null,false); addMember(l,"companyName",get_companyName,null,false); addMember(l,"cloudProjectId",get_cloudProjectId,null,false); addMember(l,"webSecurityEnabled",get_webSecurityEnabled,null,false); addMember(l,"webSecurityHostUrl",get_webSecurityHostUrl,null,false); addMember(l,"targetFrameRate",get_targetFrameRate,set_targetFrameRate,false); addMember(l,"systemLanguage",get_systemLanguage,null,false); addMember(l,"backgroundLoadingPriority",get_backgroundLoadingPriority,set_backgroundLoadingPriority,false); addMember(l,"internetReachability",get_internetReachability,null,false); addMember(l,"genuine",get_genuine,null,false); addMember(l,"genuineCheckAvailable",get_genuineCheckAvailable,null,false); createTypeMetatable(l,constructor, typeof(UnityEngine.Application)); } }
26.965517
109
0.716408
[ "MIT" ]
zhukunqian/unity5-slua
Assets/Slua/LuaObject/Unity/Lua_UnityEngine_Application.cs
20,334
C#
using Fur.DependencyInjection; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using System; using System.Linq; using System.Runtime.CompilerServices; namespace Fur.DatabaseAccessor { /// <summary> /// 时态查询拓展 /// </summary> [SkipScan] public static class TemporalExtensions { /// <summary> /// 返回属于当前表和历史记录表的行的联合 /// </summary> /// <typeparam name="TEntity"></typeparam> /// <param name="dbSet"></param> /// <returns></returns> public static IQueryable<TEntity> AsTemporalAll<TEntity>(this DbSet<TEntity> dbSet) where TEntity : class, new() { return dbSet.AsTemporal("ALL"); } /// <summary> /// 返回一个包含实际值(当前)的行的表。 /// </summary> /// <typeparam name="TEntity"></typeparam> /// <param name="dbSet"></param> /// <param name="date"></param> /// <returns></returns> public static IQueryable<TEntity> AsTemporalAsOf<TEntity>(this DbSet<TEntity> dbSet, DateTime date) where TEntity : class, new() { return dbSet.AsTemporal("AS OF {0}", date.ToUniversalTime()); } /// <summary> /// 返回一个表,其中具有在指定的时间范围,无论它们是否在 /// </summary> /// <typeparam name="TEntity"></typeparam> /// <param name="dbSet"></param> /// <param name="startDate"></param> /// <param name="endDate"></param> /// <returns></returns> public static IQueryable<TEntity> AsTemporalFrom<TEntity>(this DbSet<TEntity> dbSet, DateTime startDate, DateTime endDate) where TEntity : class, new() { return dbSet.AsTemporal("FROM {0} TO {1}", startDate.ToUniversalTime(), endDate.ToUniversalTime()); } /// <summary> /// 返回一个表,其中具有在指定的时间范围,无论它们是否在,但是结束时间有边界值 /// </summary> /// <typeparam name="TEntity"></typeparam> /// <param name="dbSet"></param> /// <param name="startDate"></param> /// <param name="endDate"></param> /// <returns></returns> public static IQueryable<TEntity> AsTemporalBetween<TEntity>(this DbSet<TEntity> dbSet, DateTime startDate, DateTime endDate) where TEntity : class, new() { return dbSet.AsTemporal("BETWEEN {0} AND {1}", startDate.ToUniversalTime(), endDate.ToUniversalTime()); } /// <summary> /// 返回一个表,该表包含已打开和关闭的所有行版本的值 /// </summary> /// <typeparam name="TEntity"></typeparam> /// <param name="dbSet"></param> /// <param name="startDate"></param> /// <param name="endDate"></param> /// <returns></returns> public static IQueryable<TEntity> AsTemporalContained<TEntity>(this DbSet<TEntity> dbSet, DateTime startDate, DateTime endDate) where TEntity : class, new() { return dbSet.AsTemporal("CONTAINED IN ({0}, {1})", startDate.ToUniversalTime(), endDate.ToUniversalTime()); } /// <summary> /// 创建时态表 /// </summary> /// <typeparam name="TEntity"></typeparam> /// <param name="dbSet"></param> /// <param name="temporalCriteria"></param> /// <param name="arguments"></param> /// <returns></returns> private static IQueryable<TEntity> AsTemporal<TEntity>(this DbSet<TEntity> dbSet, string temporalCriteria, params object[] arguments) where TEntity : class, new() { // 获取当前数据库上下文 var table = dbSet .GetService<ICurrentDbContext>() .GetTableName<TEntity>(); var selectSql = $"SELECT * FROM {table}"; var sql = FormattableStringFactory.Create(selectSql + " FOR SYSTEM_TIME " + temporalCriteria, arguments); return dbSet.FromSqlInterpolated(sql); } /// <summary> /// 获取表名 /// </summary> /// <typeparam name="TEntity"></typeparam> /// <param name="dbContext"></param> /// <returns></returns> private static string GetTableName<TEntity>(this ICurrentDbContext dbContext) where TEntity : class, new() { var entityType = dbContext.Context.Model.FindEntityType(typeof(TEntity)); var schema = entityType.GetSchema().GetSqlSafeName(); var table = entityType.GetTableName().GetSqlSafeName(); return string.IsNullOrEmpty(schema) ? table : string.Join(".", schema, table); } /// <summary> /// 获取 Sql 安全名 /// </summary> /// <param name="sqlName"></param> /// <returns></returns> private static string GetSqlSafeName(this string sqlName) { return string.IsNullOrEmpty(sqlName) ? string.Empty : $"[{sqlName}]"; } } }
36.925373
141
0.563056
[ "Apache-2.0" ]
LiveFly/Fur
framework/Fur/DatabaseAccessor/Extensions/TemporalExtensions.cs
5,256
C#
// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information. // Ported from um/wincrypt.h in the Windows SDK for Windows 10.0.20348.0 // Original source is Copyright © Microsoft. All rights reserved. using NUnit.Framework; using System; using System.Runtime.InteropServices; namespace TerraFX.Interop.UnitTests { /// <summary>Provides validation of the <see cref="CERT_ECC_SIGNATURE" /> struct.</summary> public static unsafe class CERT_ECC_SIGNATURETests { /// <summary>Validates that the <see cref="CERT_ECC_SIGNATURE" /> struct is blittable.</summary> [Test] public static void IsBlittableTest() { Assert.That(Marshal.SizeOf<CERT_ECC_SIGNATURE>(), Is.EqualTo(sizeof(CERT_ECC_SIGNATURE))); } /// <summary>Validates that the <see cref="CERT_ECC_SIGNATURE" /> struct has the right <see cref="LayoutKind" />.</summary> [Test] public static void IsLayoutSequentialTest() { Assert.That(typeof(CERT_ECC_SIGNATURE).IsLayoutSequential, Is.True); } /// <summary>Validates that the <see cref="CERT_ECC_SIGNATURE" /> struct has the correct size.</summary> [Test] public static void SizeOfTest() { if (Environment.Is64BitProcess) { Assert.That(sizeof(CERT_ECC_SIGNATURE), Is.EqualTo(32)); } else { Assert.That(sizeof(CERT_ECC_SIGNATURE), Is.EqualTo(16)); } } } }
36.522727
145
0.640324
[ "MIT" ]
phizch/terrafx.interop.windows
tests/Interop/Windows/um/wincrypt/CERT_ECC_SIGNATURETests.cs
1,609
C#
/* Copyright (C) 2011-2013 Jeroen Frijters This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. Jeroen Frijters jeroen@frijters.net */ using System; using System.Reflection; using System.Reflection.Emit; using IKVM.Internal; using java.lang.invoke; using jlClass = java.lang.Class; static class Java_java_lang_invoke_BoundMethodHandle { public static object createDelegate(MethodType newType, MethodHandle mh, int argnum, object argument) { #if FIRST_PASS return null; #else Delegate del = (Delegate)mh.vmtarget; if (argnum == 0 && del.Target == null // we don't have to check for instance methods on a Value Type, because DirectMethodHandle can't use a direct delegate for that anyway && (!del.Method.IsStatic || !del.Method.GetParameters()[0].ParameterType.IsValueType) && !ReflectUtil.IsDynamicMethod(del.Method)) { return Delegate.CreateDelegate(MethodHandleUtil.CreateDelegateType(newType), argument, del.Method); } else { // slow path where we're generating a DynamicMethod if (mh.type().parameterType(argnum).isPrimitive()) { argument = JVM.Unbox(argument); } MethodHandleUtil.DynamicMethodBuilder dm = new MethodHandleUtil.DynamicMethodBuilder("BoundMethodHandle", newType, mh, argument); for (int i = 0, count = mh.type().parameterCount(), pos = 0; i < count; i++) { if (i == argnum) { dm.LoadValue(); } else { dm.Ldarg(pos++); } } dm.CallTarget(); dm.Ret(); return dm.CreateDelegate(); } #endif } } static class Java_java_lang_invoke_CallSite { public static object createIndyCallSite(object target) { return Activator.CreateInstance(typeof(IKVM.Runtime.IndyCallSite<>).MakeGenericType(target.GetType()), true); } } static class Java_java_lang_invoke_DirectMethodHandle { public static object createDelegate(MethodType type, MemberName m, bool doDispatch, jlClass lookupClass) { #if FIRST_PASS return null; #else int index = m.getVMIndex(); if (index == Int32.MaxValue) { bool invokeExact = m.getName() == "invokeExact"; Type targetDelegateType = MethodHandleUtil.CreateDelegateType(invokeExact ? type.dropParameterTypes(0, 1) : type); MethodHandleUtil.DynamicMethodBuilder dm = new MethodHandleUtil.DynamicMethodBuilder("DirectMethodHandle." + m.getName(), type, typeof(IKVM.Runtime.InvokeCache<>).MakeGenericType(targetDelegateType)); dm.Ldarg(0); if (invokeExact) { dm.Call(ByteCodeHelperMethods.GetDelegateForInvokeExact.MakeGenericMethod(targetDelegateType)); } else { dm.LoadValueAddress(); dm.Call(ByteCodeHelperMethods.GetDelegateForInvoke.MakeGenericMethod(targetDelegateType)); dm.Ldarg(0); } for (int i = 1, count = type.parameterCount(); i < count; i++) { dm.Ldarg(i); } dm.CallDelegate(targetDelegateType); dm.Ret(); return dm.CreateDelegate(); } else { TypeWrapper tw = (TypeWrapper)typeof(MemberName).GetField("vmtarget", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(m); tw.Finish(); MethodWrapper mw = tw.GetMethods()[index]; if (mw.IsDynamicOnly) { MethodHandleUtil.DynamicMethodBuilder dm = new MethodHandleUtil.DynamicMethodBuilder("CustomInvoke:" + mw.Name, type, mw); if (mw.IsStatic) { dm.LoadNull(); dm.BoxArgs(0); } else { dm.Ldarg(0); dm.BoxArgs(1); } dm.Callvirt(typeof(MethodWrapper).GetMethod("Invoke", BindingFlags.Instance | BindingFlags.NonPublic)); dm.UnboxReturnValue(); dm.Ret(); return dm.CreateDelegate(); } // HACK this code is duplicated in compiler.cs if (mw.IsProtected && (mw.DeclaringType == CoreClasses.java.lang.Object.Wrapper || mw.DeclaringType == CoreClasses.java.lang.Throwable.Wrapper)) { TypeWrapper thisType = TypeWrapper.FromClass(lookupClass); TypeWrapper cli_System_Object = ClassLoaderWrapper.LoadClassCritical("cli.System.Object"); TypeWrapper cli_System_Exception = ClassLoaderWrapper.LoadClassCritical("cli.System.Exception"); // HACK we may need to redirect finalize or clone from java.lang.Object/Throwable // to a more specific base type. if (thisType.IsAssignableTo(cli_System_Object)) { mw = cli_System_Object.GetMethodWrapper(mw.Name, mw.Signature, true); } else if (thisType.IsAssignableTo(cli_System_Exception)) { mw = cli_System_Exception.GetMethodWrapper(mw.Name, mw.Signature, true); } else if (thisType.IsAssignableTo(CoreClasses.java.lang.Throwable.Wrapper)) { mw = CoreClasses.java.lang.Throwable.Wrapper.GetMethodWrapper(mw.Name, mw.Signature, true); } } mw.ResolveMethod(); MethodInfo mi = mw.GetMethod() as MethodInfo; if (mi != null && !mw.HasCallerID && !tw.IsRemapped && !tw.IsGhost && !tw.IsNonPrimitiveValueType && type.parameterCount() <= MethodHandleUtil.MaxArity // FXBUG we should be able to use a normal (unbound) delegate for virtual methods // (when doDispatch is set), but the x64 CLR crashes when doing a virtual method dispatch on // a null reference && (!mi.IsVirtual || (doDispatch && IntPtr.Size == 4)) && (doDispatch || !mi.IsVirtual)) { return Delegate.CreateDelegate(MethodHandleUtil.CreateDelegateType(tw, mw), mi); } else { // slow path where we emit a DynamicMethod MethodHandleUtil.DynamicMethodBuilder dm = new MethodHandleUtil.DynamicMethodBuilder(mw.DeclaringType.TypeAsBaseType, "DirectMethodHandle:" + mw.Name, type, mw.HasCallerID ? ikvm.@internal.CallerID.create(lookupClass) : null); for (int i = 0, count = type.parameterCount(); i < count; i++) { if (i == 0 && !mw.IsStatic && (tw.IsGhost || tw.IsNonPrimitiveValueType)) { dm.LoadFirstArgAddress(); } else { dm.Ldarg(i); } } if (mw.HasCallerID) { dm.LoadCallerID(); } if (doDispatch && !mw.IsStatic) { dm.Callvirt(mw); } else { dm.Call(mw); } dm.Ret(); return dm.CreateDelegate(); } } #endif } } static class Java_java_lang_invoke_MethodHandle { private static IKVM.Runtime.InvokeCache<IKVM.Runtime.MH<MethodHandle, object[], object>> cache; public static object invokeExact(MethodHandle mh, object[] args) { #if FIRST_PASS return null; #else return IKVM.Runtime.ByteCodeHelper.GetDelegateForInvokeExact<IKVM.Runtime.MH<object[], object>>(mh)(args); #endif } public static object invoke(MethodHandle mh, object[] args) { #if FIRST_PASS return null; #else MethodType type = mh.type(); if (mh.isVarargsCollector()) { java.lang.Class varargType = type.parameterType(type.parameterCount() - 1); if (type.parameterCount() == args.Length) { if (!varargType.isInstance(args[args.Length - 1])) { Array arr = (Array)java.lang.reflect.Array.newInstance(varargType.getComponentType(), 1); arr.SetValue(args[args.Length - 1], 0); args[args.Length - 1] = arr; } } else if (type.parameterCount() - 1 > args.Length) { throw new WrongMethodTypeException(); } else { object[] newArgs = new object[type.parameterCount()]; Array.Copy(args, newArgs, newArgs.Length - 1); Array varargs = (Array)java.lang.reflect.Array.newInstance(varargType.getComponentType(), args.Length - (newArgs.Length - 1)); Array.Copy(args, newArgs.Length - 1, varargs, 0, varargs.Length); newArgs[newArgs.Length - 1] = varargs; args = newArgs; } } if (mh.type().parameterCount() != args.Length) { throw new WrongMethodTypeException(); } mh = mh.asSpreader(typeof(object[]), args.Length); return IKVM.Runtime.ByteCodeHelper.GetDelegateForInvoke<IKVM.Runtime.MH<MethodHandle, object[], object>>(mh, ref cache)(mh, args); #endif } } static partial class MethodHandleUtil { internal static Type CreateDelegateType(MethodType type) { #if FIRST_PASS return null; #else TypeWrapper[] args = new TypeWrapper[type.parameterCount()]; for (int i = 0; i < args.Length; i++) { args[i] = TypeWrapper.FromClass(type.parameterType(i)); args[i].Finish(); } TypeWrapper ret = TypeWrapper.FromClass(type.returnType()); ret.Finish(); return CreateDelegateType(args, ret); #endif } #if !FIRST_PASS private static Type[] GetParameterTypes(MethodBase mb) { ParameterInfo[] pi = mb.GetParameters(); Type[] args = new Type[pi.Length]; for (int i = 0; i < args.Length; i++) { args[i] = pi[i].ParameterType; } return args; } private static Type[] GetParameterTypes(Type thisType, MethodBase mb) { ParameterInfo[] pi = mb.GetParameters(); Type[] args = new Type[pi.Length + 1]; args[0] = thisType; for (int i = 1; i < args.Length; i++) { args[i] = pi[i - 1].ParameterType; } return args; } internal static MethodType GetDelegateMethodType(Type type) { java.lang.Class[] types; MethodInfo mi = GetDelegateInvokeMethod(type); ParameterInfo[] pi = mi.GetParameters(); if (pi.Length > 0 && IsPackedArgsContainer(pi[pi.Length - 1].ParameterType)) { System.Collections.Generic.List<java.lang.Class> list = new System.Collections.Generic.List<java.lang.Class>(); for (int i = 0; i < pi.Length - 1; i++) { list.Add(ClassLoaderWrapper.GetWrapperFromType(pi[i].ParameterType).ClassObject); } Type[] args = pi[pi.Length - 1].ParameterType.GetGenericArguments(); while (IsPackedArgsContainer(args[args.Length - 1])) { for (int i = 0; i < args.Length - 1; i++) { list.Add(ClassLoaderWrapper.GetWrapperFromType(args[i]).ClassObject); } args = args[args.Length - 1].GetGenericArguments(); } for (int i = 0; i < args.Length; i++) { list.Add(ClassLoaderWrapper.GetWrapperFromType(args[i]).ClassObject); } types = list.ToArray(); } else { types = new java.lang.Class[pi.Length]; for (int i = 0; i < types.Length; i++) { types[i] = ClassLoaderWrapper.GetWrapperFromType(pi[i].ParameterType).ClassObject; } } return MethodType.methodType(ClassLoaderWrapper.GetWrapperFromType(mi.ReturnType).ClassObject, types); } internal sealed class DynamicMethodBuilder { private readonly MethodType type; private readonly int firstArg; private readonly Type delegateType; private readonly object firstBoundValue; private readonly object secondBoundValue; private readonly Type container; private readonly DynamicMethod dm; private readonly CodeEmitter ilgen; private readonly Type packedArgType; private readonly int packedArgPos; sealed class Container<T1, T2> { public T1 target; public T2 value; public Container(T1 target, T2 value) { this.target = target; this.value = value; } } private DynamicMethodBuilder(string name, MethodType type, Type container, object target, object value, Type owner) { this.type = type; this.delegateType = CreateDelegateType(type); this.firstBoundValue = target; this.secondBoundValue = value; this.container = container; MethodInfo mi = GetDelegateInvokeMethod(delegateType); Type[] paramTypes; if (container != null) { this.firstArg = 1; paramTypes = GetParameterTypes(container, mi); } else if (target != null) { this.firstArg = 1; paramTypes = GetParameterTypes(target.GetType(), mi); } else { paramTypes = GetParameterTypes(mi); } if (!ReflectUtil.CanOwnDynamicMethod(owner)) { owner = typeof(DynamicMethodBuilder); } this.dm = new DynamicMethod(name, mi.ReturnType, paramTypes, owner, true); this.ilgen = CodeEmitter.Create(dm); if (type.parameterCount() > MaxArity) { ParameterInfo[] pi = mi.GetParameters(); this.packedArgType = pi[pi.Length - 1].ParameterType; this.packedArgPos = pi.Length - 1 + firstArg; } else { this.packedArgPos = Int32.MaxValue; } } internal DynamicMethodBuilder(Type owner, string name, MethodType type, ikvm.@internal.CallerID callerID) : this(name, type, null, callerID, null, owner) { } internal DynamicMethodBuilder(string name, MethodType type, MethodHandle target) : this(name, type, null, target.vmtarget, null, null) { ilgen.Emit(OpCodes.Ldarg_0); } internal DynamicMethodBuilder(string name, MethodType type, MethodWrapper target) : this(name, type, null, target, null, null) { ilgen.Emit(OpCodes.Ldarg_0); } internal DynamicMethodBuilder(string name, MethodType type, MethodHandle target, object value) : this(name, type, typeof(Container<,>).MakeGenericType(target.vmtarget.GetType(), value.GetType()), target.vmtarget, value, null) { ilgen.Emit(OpCodes.Ldarg_0); ilgen.Emit(OpCodes.Ldfld, container.GetField("target")); } internal DynamicMethodBuilder(string name, MethodType type, Type valueType) : this(name, type, typeof(Container<,>).MakeGenericType(typeof(object), valueType), null, null, null) { } internal void Call(MethodInfo method) { ilgen.Emit(OpCodes.Call, method); } internal void Callvirt(MethodInfo method) { ilgen.Emit(OpCodes.Callvirt, method); } internal void Call(MethodWrapper mw) { mw.EmitCall(ilgen); } internal void Callvirt(MethodWrapper mw) { mw.EmitCallvirt(ilgen); } internal void CallDelegate(Type delegateType) { EmitCallDelegateInvokeMethod(ilgen, delegateType); } internal void LoadFirstArgAddress() { ilgen.EmitLdarga(firstArg); } internal void Ldarg(int i) { i += firstArg; if (i >= packedArgPos) { ilgen.EmitLdarga(packedArgPos); int fieldPos = i - packedArgPos; Type type = packedArgType; while (fieldPos >= MaxArity || (fieldPos == MaxArity - 1 && IsPackedArgsContainer(type.GetField("t8").FieldType))) { FieldInfo field = type.GetField("t8"); type = field.FieldType; ilgen.Emit(OpCodes.Ldflda, field); fieldPos -= MaxArity - 1; } ilgen.Emit(OpCodes.Ldfld, type.GetField("t" + (1 + fieldPos))); } else { ilgen.EmitLdarg(i); } } internal void LoadArrayElement(int index, TypeWrapper tw) { ilgen.EmitLdc_I4(index); if (tw.IsNonPrimitiveValueType) { ilgen.Emit(OpCodes.Ldelema, tw.TypeAsArrayType); ilgen.Emit(OpCodes.Ldobj, tw.TypeAsArrayType); } else if (tw == PrimitiveTypeWrapper.BYTE || tw == PrimitiveTypeWrapper.BOOLEAN) { ilgen.Emit(OpCodes.Ldelem_I1); } else if (tw == PrimitiveTypeWrapper.SHORT) { ilgen.Emit(OpCodes.Ldelem_I2); } else if (tw == PrimitiveTypeWrapper.CHAR) { ilgen.Emit(OpCodes.Ldelem_U2); } else if (tw == PrimitiveTypeWrapper.INT) { ilgen.Emit(OpCodes.Ldelem_I4); } else if (tw == PrimitiveTypeWrapper.LONG) { ilgen.Emit(OpCodes.Ldelem_I8); } else if (tw == PrimitiveTypeWrapper.FLOAT) { ilgen.Emit(OpCodes.Ldelem_R4); } else if (tw == PrimitiveTypeWrapper.DOUBLE) { ilgen.Emit(OpCodes.Ldelem_R8); } else { ilgen.Emit(OpCodes.Ldelem_Ref); if (tw.IsGhost) { tw.EmitConvStackTypeToSignatureType(ilgen, null); } } } internal void Convert(java.lang.Class srcType, java.lang.Class dstType, int level) { EmitConvert(ilgen, srcType, dstType, level); } internal void CallTarget() { EmitCallDelegateInvokeMethod(ilgen, firstBoundValue.GetType()); } internal void LoadCallerID() { ilgen.Emit(OpCodes.Ldarg_0); } internal void LoadValueAddress() { ilgen.Emit(OpCodes.Ldarg_0); ilgen.Emit(OpCodes.Ldflda, container.GetField("value")); } internal void LoadValue() { ilgen.Emit(OpCodes.Ldarg_0); ilgen.Emit(OpCodes.Ldfld, container.GetField("value")); } internal void CallValue() { EmitCallDelegateInvokeMethod(ilgen, secondBoundValue.GetType()); } internal void Ret() { ilgen.Emit(OpCodes.Ret); } internal Delegate CreateDelegate() { ilgen.DoEmit(); return ValidateDelegate(firstArg == 0 ? dm.CreateDelegate(delegateType) : dm.CreateDelegate(delegateType, container == null ? firstBoundValue : Activator.CreateInstance(container, firstBoundValue, secondBoundValue))); } internal AdapterMethodHandle CreateAdapter() { return new AdapterMethodHandle(type, CreateDelegate()); } internal void BoxArgs(int start) { int paramCount = type.parameterCount(); ilgen.EmitLdc_I4(paramCount - start); ilgen.Emit(OpCodes.Newarr, Types.Object); for (int i = start; i < paramCount; i++) { ilgen.Emit(OpCodes.Dup); ilgen.EmitLdc_I4(i - start); Ldarg(i); TypeWrapper tw = TypeWrapper.FromClass(type.parameterType(i)); if (tw.IsPrimitive || tw.IsGhost) { ilgen.Emit(OpCodes.Box, tw.TypeAsSignatureType); } else if (tw.IsNonPrimitiveValueType) { tw.EmitBox(ilgen); } ilgen.Emit(OpCodes.Stelem_Ref); } } internal void UnboxReturnValue() { TypeWrapper tw = TypeWrapper.FromClass(type.returnType()); if (tw == PrimitiveTypeWrapper.VOID) { ilgen.Emit(OpCodes.Pop); } else if (tw.IsPrimitive || tw.IsGhost) { ilgen.Emit(OpCodes.Unbox, tw.TypeAsSignatureType); ilgen.Emit(OpCodes.Ldobj, tw.TypeAsSignatureType); } else if (tw.IsNonPrimitiveValueType) { tw.EmitUnbox(ilgen); } else if (tw != CoreClasses.java.lang.Object.Wrapper) { tw.EmitCheckcast(ilgen); } } internal void LoadNull() { ilgen.Emit(OpCodes.Ldnull); } } #if DEBUG [System.Security.SecuritySafeCritical] #endif private static Delegate ValidateDelegate(Delegate d) { #if DEBUG try { System.Runtime.CompilerServices.RuntimeHelpers.PrepareDelegate(d); } catch (Exception x) { JVM.CriticalFailure("Delegate failed to JIT", x); } #endif return d; } private struct BoxUtil { private static readonly BoxUtil[] boxers = new BoxUtil[] { BoxUtil.Create<java.lang.Boolean, bool>(java.lang.Boolean.TYPE, "boolean", "Boolean"), BoxUtil.Create<java.lang.Byte, byte>(java.lang.Byte.TYPE, "byte", "Byte"), BoxUtil.Create<java.lang.Character, char>(java.lang.Character.TYPE, "char", "Character"), BoxUtil.Create<java.lang.Short, short>(java.lang.Short.TYPE, "short", "Short"), BoxUtil.Create<java.lang.Integer, int>(java.lang.Integer.TYPE, "int", "Integer"), BoxUtil.Create<java.lang.Long, int>(java.lang.Long.TYPE, "long", "Long"), BoxUtil.Create<java.lang.Float, float>(java.lang.Float.TYPE, "float", "Float"), BoxUtil.Create<java.lang.Double, double>(java.lang.Double.TYPE, "double", "Double"), }; private readonly jlClass clazz; private readonly jlClass type; private readonly MethodInfo box; private readonly MethodInfo unbox; private readonly MethodInfo unboxObject; private BoxUtil(jlClass clazz, jlClass type, MethodInfo box, MethodInfo unbox, MethodInfo unboxObject) { this.clazz = clazz; this.type = type; this.box = box; this.unbox = unbox; this.unboxObject = unboxObject; } private static BoxUtil Create<T, P>(jlClass type, string name, string longName) { return new BoxUtil(ikvm.@internal.ClassLiteral<T>.Value, type, typeof(T).GetMethod("valueOf", new Type[] { typeof(P) }), typeof(T).GetMethod(name + "Value", Type.EmptyTypes), typeof(sun.invoke.util.ValueConversions).GetMethod("unbox" + longName, BindingFlags.Static | BindingFlags.NonPublic)); } internal static void Box(CodeEmitter ilgen, jlClass srcClass, jlClass dstClass, int level) { for (int i = 0; i < boxers.Length; i++) { if (boxers[i].type == srcClass) { ilgen.Emit(OpCodes.Call, boxers[i].box); EmitConvert(ilgen, boxers[i].clazz, dstClass, level); return; } } throw new InvalidOperationException(); } internal static void Unbox(CodeEmitter ilgen, jlClass srcClass, jlClass dstClass, int level) { for (int i = 0; i < boxers.Length; i++) { if (boxers[i].clazz == srcClass) { // typed unboxing ilgen.Emit(OpCodes.Call, boxers[i].unbox); EmitConvert(ilgen, boxers[i].type, dstClass, level); return; } } for (int i = 0; i < boxers.Length; i++) { if (boxers[i].type == dstClass) { // untyped unboxing ilgen.EmitLdc_I4(level > 1 ? 1 : 0); ilgen.Emit(OpCodes.Call, boxers[i].unboxObject); return; } } throw new InvalidOperationException(); } } private static void EmitConvert(CodeEmitter ilgen, java.lang.Class srcClass, java.lang.Class dstClass, int level) { if (srcClass != dstClass) { TypeWrapper src = TypeWrapper.FromClass(srcClass); TypeWrapper dst = TypeWrapper.FromClass(dstClass); src.Finish(); dst.Finish(); if (src.IsNonPrimitiveValueType) { src.EmitBox(ilgen); } if (dst == PrimitiveTypeWrapper.VOID) { ilgen.Emit(OpCodes.Pop); } else if (src.IsPrimitive) { if (dst.IsPrimitive) { if (src == PrimitiveTypeWrapper.BYTE) { ilgen.Emit(OpCodes.Conv_I1); } if (dst == PrimitiveTypeWrapper.FLOAT) { ilgen.Emit(OpCodes.Conv_R4); } else if (dst == PrimitiveTypeWrapper.DOUBLE) { ilgen.Emit(OpCodes.Conv_R8); } else if (dst == PrimitiveTypeWrapper.LONG) { if (src == PrimitiveTypeWrapper.FLOAT) { ilgen.Emit(OpCodes.Call, ByteCodeHelperMethods.f2l); } else if (src == PrimitiveTypeWrapper.DOUBLE) { ilgen.Emit(OpCodes.Call, ByteCodeHelperMethods.d2l); } else { ilgen.Emit(OpCodes.Conv_I8); } } else if (dst == PrimitiveTypeWrapper.BOOLEAN) { if (src == PrimitiveTypeWrapper.FLOAT) { ilgen.Emit(OpCodes.Call, ByteCodeHelperMethods.f2i); } else if (src == PrimitiveTypeWrapper.DOUBLE) { ilgen.Emit(OpCodes.Call, ByteCodeHelperMethods.d2i); } else { ilgen.Emit(OpCodes.Conv_I4); } ilgen.Emit(OpCodes.Ldc_I4_1); ilgen.Emit(OpCodes.And); } else if (src == PrimitiveTypeWrapper.LONG) { ilgen.Emit(OpCodes.Conv_I4); } else if (src == PrimitiveTypeWrapper.FLOAT) { ilgen.Emit(OpCodes.Call, ByteCodeHelperMethods.f2i); } else if (src == PrimitiveTypeWrapper.DOUBLE) { ilgen.Emit(OpCodes.Call, ByteCodeHelperMethods.d2i); } } else { BoxUtil.Box(ilgen, srcClass, dstClass, level); } } else if (src.IsGhost) { src.EmitConvSignatureTypeToStackType(ilgen); EmitConvert(ilgen, ikvm.@internal.ClassLiteral<java.lang.Object>.Value, dstClass, level); } else if (srcClass == ikvm.@internal.ClassLiteral<sun.invoke.empty.Empty>.Value) { ilgen.Emit(OpCodes.Pop); ilgen.Emit(OpCodes.Ldloc, ilgen.DeclareLocal(dst.TypeAsSignatureType)); } else if (dst.IsPrimitive) { BoxUtil.Unbox(ilgen, srcClass, dstClass, level); } else if (dst.IsGhost) { dst.EmitConvStackTypeToSignatureType(ilgen, null); } else if (dst.IsNonPrimitiveValueType) { dst.EmitUnbox(ilgen); } else { dst.EmitCheckcast(ilgen); } } } internal static void Dump(MethodHandle mh) { Console.WriteLine("----"); Dump((Delegate)mh.vmtarget, 0); } private static void WriteNest(int nest) { for (int i = 0; i < nest; i++) { Console.Write(" "); } } private static void Dump(Delegate d, int nest) { if (nest > 0) { WriteNest(nest - 1); Console.Write("->"); } Console.Write(d.Method.Name + "("); string sep = ""; foreach (ParameterInfo pi in d.Method.GetParameters()) { Console.WriteLine(sep); WriteNest(nest); Console.Write(" {0}", TypeToString(pi.ParameterType)); sep = ","; } Console.WriteLine(")"); WriteNest(nest); Console.WriteLine(" : {0}", TypeToString(d.Method.ReturnType)); if (d.Target is Delegate) { Dump((Delegate)d.Target, nest == 0 ? 1 : nest); } else if (d.Target != null) { FieldInfo field = d.Target.GetType().GetField("value"); if (field != null && field.GetValue(d.Target) is Delegate) { WriteNest(nest + 1); Console.WriteLine("Collector:"); Dump((Delegate)field.GetValue(d.Target), nest + 2); } field = d.Target.GetType().GetField("target"); if (field != null && field.GetValue(d.Target) != null) { Dump((Delegate)field.GetValue(d.Target), nest == 0 ? 1 : nest); } } } private static string TypeToString(Type type) { if (type.IsGenericType && type.Namespace == "IKVM.Runtime" && (type.Name.StartsWith("MH`") || type.Name.StartsWith("MHV`"))) { return type.Name.Substring(0, type.Name.IndexOf('`')) + "<" + TypesToString(type.GetGenericArguments()) + ">"; } else if (type.DeclaringType == typeof(DynamicMethodBuilder)) { return "C<" + TypesToString(type.GetGenericArguments()) + ">"; } else if (ReflectUtil.IsVector(type)) { return TypeToString(type.GetElementType()) + "[]"; } else if (type == typeof(object)) { return "object"; } else if (type == typeof(string)) { return "string"; } else if (type.IsPrimitive) { return type.Name.ToLowerInvariant(); } else { return type.ToString(); } } private static string TypesToString(Type[] types) { System.Text.StringBuilder sb = new System.Text.StringBuilder(); foreach (Type type in types) { if (sb.Length != 0) { sb.Append(", "); } sb.Append(TypeToString(type)); } return sb.ToString(); } #endif } static class Java_java_lang_invoke_AdapterMethodHandle { public static MethodHandle makePairwiseConvert(MethodType newType, MethodHandle target, int level) { #if FIRST_PASS return null; #else MethodType oldType = target.type(); MethodHandleUtil.DynamicMethodBuilder dm = new MethodHandleUtil.DynamicMethodBuilder("AdapterMethodHandle.pairwiseConvert", newType, target); for (int i = 0, count = newType.parameterCount(); i < count; i++) { dm.Ldarg(i); dm.Convert(newType.parameterType(i), oldType.parameterType(i), level); } dm.CallTarget(); dm.Convert(oldType.returnType(), newType.returnType(), level); dm.Ret(); return dm.CreateAdapter(); #endif } public static MethodHandle makeRetype(MethodType newType, MethodHandle target, bool raw) { #if FIRST_PASS return null; #else MethodType oldType = target.type(); if (oldType == newType) { return target; } if (!AdapterMethodHandle.canRetype(newType, oldType, raw)) { return null; } // TODO does raw translate into a level? return makePairwiseConvert(newType, target, 0); #endif } public static MethodHandle makeSpreadArguments(MethodType newType, MethodHandle target, java.lang.Class spreadArgType, int spreadArgPos, int spreadArgCount) { #if FIRST_PASS return null; #else TypeWrapper twComponent = TypeWrapper.FromClass(spreadArgType).ElementTypeWrapper; MethodHandleUtil.DynamicMethodBuilder dm = new MethodHandleUtil.DynamicMethodBuilder("AdapterMethodHandle.spreadArguments", newType, target); for (int i = 0, count = newType.parameterCount(); i < count; i++) { if (i == spreadArgPos) { for (int j = 0; j < spreadArgCount; j++) { dm.Ldarg(i); dm.LoadArrayElement(j, twComponent); dm.Convert(twComponent.ClassObject, target.type().parameterType(i + j), 0); } } else { dm.Ldarg(i); } } dm.CallTarget(); dm.Ret(); return dm.CreateAdapter(); #endif } public static MethodHandle makeCollectArguments(MethodHandle target, MethodHandle collector, int collectArgPos, bool retainOriginalArgs) { #if FIRST_PASS return null; #else MethodType targetType = target.type(); MethodType collectorType = collector.type(); bool isfilter = collectorType.returnType() == java.lang.Void.TYPE; MethodType newType = targetType.dropParameterTypes(collectArgPos, collectArgPos + (isfilter ? 0 : 1)); if (!retainOriginalArgs) { newType = newType.insertParameterTypes(collectArgPos, collectorType.parameterList()); } MethodHandleUtil.DynamicMethodBuilder dm = new MethodHandleUtil.DynamicMethodBuilder("AdapterMethodHandle.collectArguments", newType, target, collector.vmtarget); for (int i = 0, count = newType.parameterCount(); i < count || i == collectArgPos; i++) { if (i == collectArgPos) { dm.LoadValue(); for (int j = 0; j < collectorType.parameterCount(); j++) { dm.Ldarg(i + j); } dm.CallValue(); collectArgPos = -1; i--; if (!retainOriginalArgs) { i += collectorType.parameterCount(); } } else { dm.Ldarg(i); } } dm.CallTarget(); dm.Ret(); return dm.CreateAdapter(); #endif } } static class Java_java_lang_invoke_MethodHandleImpl { public static MethodHandle permuteArguments(MethodHandle target, MethodType newType, MethodType oldType, int[] permutationOrNull) { #if FIRST_PASS return null; #else // LAME why does OpenJDK name the parameter permutationOrNull while it is not allowed to be null? if (permutationOrNull.Length != oldType.parameterCount()) { throw new java.lang.IllegalArgumentException("wrong number of arguments in permutation"); } MethodHandleUtil.DynamicMethodBuilder dm = new MethodHandleUtil.DynamicMethodBuilder("MethodHandleImpl.permuteArguments", newType, target); for (int i = 0, argCount = newType.parameterCount(); i < permutationOrNull.Length; i++) { // make sure to only read each array element once, to avoid having to make a defensive copy of the array int perm = permutationOrNull[i]; if (perm < 0 || perm >= argCount) { throw new java.lang.IllegalArgumentException("permutation argument out of range"); } dm.Ldarg(perm); dm.Convert(oldType.parameterType(i), newType.parameterType(perm), 0); } dm.CallTarget(); dm.Convert(oldType.returnType(), newType.returnType(), 0); dm.Ret(); return dm.CreateAdapter(); #endif } } static class Java_java_lang_invoke_MethodHandleNatives { public static void init(MemberName self, object r) { #if !FIRST_PASS if (r is java.lang.reflect.Method || r is java.lang.reflect.Constructor) { MethodWrapper mw = MethodWrapper.FromMethodOrConstructor(r); int index = Array.IndexOf(mw.DeclaringType.GetMethods(), mw); if (index != -1) { // TODO self.setVMIndex(index); typeof(MemberName).GetField("vmindex", BindingFlags.NonPublic | BindingFlags.Instance).SetValue(self, index); typeof(MemberName).GetField("vmtarget", BindingFlags.NonPublic | BindingFlags.Instance).SetValue(self, mw.DeclaringType); int flags = (int)mw.Modifiers; if (r is java.lang.reflect.Method) { flags |= MemberName.IS_METHOD; } else { flags |= MemberName.IS_CONSTRUCTOR; } typeof(MemberName).GetField("flags", BindingFlags.NonPublic | BindingFlags.Instance).SetValue(self, flags); } } else if (r is java.lang.reflect.Field) { FieldWrapper fw = FieldWrapper.FromField((java.lang.reflect.Field)r); int index = Array.IndexOf(fw.DeclaringType.GetFields(), fw); if (index != -1) { // TODO self.setVMIndex(index); typeof(MemberName).GetField("vmindex", BindingFlags.NonPublic | BindingFlags.Instance).SetValue(self, index); typeof(MemberName).GetField("flags", BindingFlags.NonPublic | BindingFlags.Instance).SetValue(self, (int)fw.Modifiers | MemberName.IS_FIELD); } } else { throw new InvalidOperationException(); } #endif } public static void expand(MemberName self) { throw new NotImplementedException(); } public static void resolve(MemberName self, jlClass caller) { #if !FIRST_PASS if (self.isMethod() || self.isConstructor()) { TypeWrapper tw = TypeWrapper.FromClass(self.getDeclaringClass()); if (tw == CoreClasses.java.lang.invoke.MethodHandle.Wrapper && (self.getName() == "invoke" || self.getName() == "invokeExact")) { typeof(MemberName).GetField("vmindex", BindingFlags.NonPublic | BindingFlags.Instance).SetValue(self, Int32.MaxValue); return; } MethodWrapper mw = tw.GetMethodWrapper(self.getName(), self.getSignature().Replace('/', '.'), true); if (mw != null) { tw = mw.DeclaringType; int index = Array.IndexOf(tw.GetMethods(), mw); if (index != -1) { // TODO self.setVMIndex(index); typeof(MemberName).GetField("vmindex", BindingFlags.NonPublic | BindingFlags.Instance).SetValue(self, index); typeof(MemberName).GetField("vmtarget", BindingFlags.NonPublic | BindingFlags.Instance).SetValue(self, tw); int flags = (int)mw.Modifiers; if (self.isMethod()) { flags |= MemberName.IS_METHOD; } else { flags |= MemberName.IS_CONSTRUCTOR; } typeof(MemberName).GetField("flags", BindingFlags.NonPublic | BindingFlags.Instance).SetValue(self, flags); } } } else if (self.isField()) { TypeWrapper tw = TypeWrapper.FromClass(self.getDeclaringClass()); // TODO should we look in base classes? FieldWrapper fw = tw.GetFieldWrapper(self.getName(), self.getSignature().Replace('/', '.')); if (fw != null) { int index = Array.IndexOf(fw.DeclaringType.GetFields(), fw); if (index != -1) { // TODO self.setVMIndex(index); typeof(MemberName).GetField("vmindex", BindingFlags.NonPublic | BindingFlags.Instance).SetValue(self, index); typeof(MemberName).GetField("flags", BindingFlags.NonPublic | BindingFlags.Instance).SetValue(self, (int)fw.Modifiers | MemberName.IS_FIELD); } } } else { throw new InvalidOperationException(); } #endif } public static int getMembers(jlClass defc, string matchName, string matchSig, int matchFlags, jlClass caller, int skip, object[] results) { return 1; } }
28.365591
203
0.681344
[ "Apache-2.0" ]
Distrotech/mono
external/ikvm/runtime/openjdk/java.lang.invoke.cs
34,294
C#
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ using Aliyun.Acs.Core; using Aliyun.Acs.Core.Http; using Aliyun.Acs.Core.Transform; using Aliyun.Acs.Core.Utils; using Aliyun.Acs.aegis.Transform; using Aliyun.Acs.aegis.Transform.V20161111; using System.Collections.Generic; namespace Aliyun.Acs.aegis.Model.V20161111 { public class DescribeSuspiciousEventsRequest : RpcAcsRequest<DescribeSuspiciousEventsResponse> { public DescribeSuspiciousEventsRequest() : base("aegis", "2016-11-11", "DescribeSuspiciousEvents", "vipaegis", "openAPI") { } private long? resourceOwnerId; private string sourceIp; public long? ResourceOwnerId { get { return resourceOwnerId; } set { resourceOwnerId = value; DictionaryUtil.Add(QueryParameters, "ResourceOwnerId", value.ToString()); } } public string SourceIp { get { return sourceIp; } set { sourceIp = value; DictionaryUtil.Add(QueryParameters, "SourceIp", value); } } public override bool CheckShowJsonItemName() { return false; } public override DescribeSuspiciousEventsResponse GetResponse(Core.Transform.UnmarshallerContext unmarshallerContext) { return DescribeSuspiciousEventsResponseUnmarshaller.Unmarshall(unmarshallerContext); } } }
28.289474
124
0.707907
[ "Apache-2.0" ]
brightness007/unofficial-aliyun-openapi-net-sdk
aliyun-net-sdk-aegis/Aegis/Model/V20161111/DescribeSuspiciousEventsRequest.cs
2,150
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. namespace Microsoft.Diagnostics.Tools.Monitor.CollectionRules { internal static class KnownCollectionRuleTriggers { // Startup Triggers public const string Startup = nameof(Startup); // Event Source Triggers public const string AspNetRequestCount = nameof(AspNetRequestCount); public const string AspNetRequestDuration = nameof(AspNetRequestDuration); public const string AspNetResponseStatus = nameof(AspNetResponseStatus); public const string EventCounter = nameof(EventCounter); } }
40
82
0.740789
[ "MIT" ]
ScriptBox21/dotnet-monitor
src/Tools/dotnet-monitor/CollectionRules/KnownCollectionRuleTriggers.cs
762
C#
using System.Linq; using Content.Server.Atmos; using Content.Server.Atmos.EntitySystems; using Content.Server.NodeContainer.Nodes; using Content.Shared.Atmos; using Robust.Shared.Utility; namespace Content.Server.NodeContainer.NodeGroups { public interface IPipeNet : INodeGroup, IGasMixtureHolder { /// <summary> /// Causes gas in the PipeNet to react. /// </summary> void Update(); } [NodeGroup(NodeGroupID.Pipe)] public sealed class PipeNet : BaseNodeGroup, IPipeNet { [ViewVariables] public GasMixture Air { get; set; } = new() {Temperature = Atmospherics.T20C}; [ViewVariables] private AtmosphereSystem? _atmosphereSystem; public EntityUid Grid => GridId; public override void Initialize(Node sourceNode) { base.Initialize(sourceNode); _atmosphereSystem = EntitySystem.Get<AtmosphereSystem>(); _atmosphereSystem.AddPipeNet(this); } public void Update() { _atmosphereSystem?.React(Air, this); } public override void LoadNodes(List<Node> groupNodes) { base.LoadNodes(groupNodes); foreach (var node in groupNodes) { var pipeNode = (PipeNode) node; Air.Volume += pipeNode.Volume; } } public override void RemoveNode(Node node) { base.RemoveNode(node); // if the node is simply being removed into a separate group, we do nothing, as gas redistribution will be // handled by AfterRemake(). But if it is being deleted, we actually want to remove the gas stored in this node. if (!node.Deleting || node is not PipeNode pipe) return; Air.Multiply(1f - pipe.Volume / Air.Volume); Air.Volume -= pipe.Volume; } public override void AfterRemake(IEnumerable<IGrouping<INodeGroup?, Node>> newGroups) { RemoveFromGridAtmos(); var newAir = new List<GasMixture>(newGroups.Count()); foreach (var newGroup in newGroups) { if (newGroup.Key is IPipeNet newPipeNet) newAir.Add(newPipeNet.Air); } _atmosphereSystem!.DivideInto(Air, newAir); } private void RemoveFromGridAtmos() { DebugTools.AssertNotNull(_atmosphereSystem); _atmosphereSystem?.RemovePipeNet(this); } public override string GetDebugData() { return @$"Pressure: { Air.Pressure:G3} Temperature: {Air.Temperature:G3} Volume: {Air.Volume:G3}"; } } }
29.630435
124
0.594644
[ "MIT" ]
space-syndicate/space-station-14
Content.Server/NodeContainer/NodeGroups/PipeNet.cs
2,726
C#
// NoRealm licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; namespace NoRealm.ExpressionLite.Token { /// <summary> /// Default implementation for <see cref="ILexemeConverter"/> /// </summary> public class DefaultLexemeConverter : ILexemeConverter { /// <inheritdoc /> public virtual object Convert(string lexeme, Type targetType) { if (lexeme == null) return null; if (targetType == KnownTypes.String) return ConvertString(lexeme); if (targetType == KnownTypes.DateTime) return ConvertDateTime(lexeme); if (targetType == KnownTypes.Number) return ConvertNumber(lexeme); return null; } #region string type /// <summary> /// Convert input value to string /// </summary> /// <param name="lexeme">lexeme to convert</param> /// <returns>the converted string</returns> protected virtual string ConvertString(string lexeme) => lexeme == null ? null : ProcessString(lexeme); /// <summary> /// when overriden modify the string content before returned /// </summary> /// <param name="value">string to process</param> /// <returns>the final string</returns> protected virtual string ProcessString(string value) => value; #endregion #region number type /// <summary> /// Convert input value to decimal /// </summary> /// <param name="lexeme">lexeme to convert</param> /// <returns>the converted number</returns> protected virtual decimal? ConvertNumber(string lexeme) { if (lexeme == null) return null; var content = LexemeToNumber(lexeme); if (content == null) return null; return ProcessNumber(content.Value); } /// <summary> /// when overriden convert string to decimal number /// </summary> /// <param name="lexeme">lexeme to convert</param> /// <returns>the converted number; null for invalid format</returns> protected virtual decimal? LexemeToNumber(string lexeme) => decimal.TryParse(lexeme, out var n) ? n : null; /// <summary> /// when overriden modify the input number before returned /// </summary> /// <param name="value">value to process</param> /// <returns>the modified number</returns> protected virtual decimal ProcessNumber(decimal value) => value; #endregion #region datetime type /// <summary> /// Convert input value to datetime /// </summary> /// <param name="lexeme">lexeme to convert</param> /// <returns>the converted datetime</returns> protected virtual DateTime? ConvertDateTime(string lexeme) { if (lexeme == null) return null; var content = LexemeToDateTime(lexeme); if (content == null) return null; return ProcessDateTime(content.Value); } /// <summary> /// when overriden convert string to datetime value /// </summary> /// <param name="lexeme">lexeme to convert</param> /// <returns>the converted value; null for invalid format</returns> protected virtual DateTime? LexemeToDateTime(string lexeme) => DateTime.TryParse(lexeme, out var dt) ? dt : null; /// <summary> /// when overriden modify the input value before returned /// </summary> /// <param name="value">value to process</param> /// <returns>the modified value</returns> protected virtual DateTime ProcessDateTime(DateTime value) => value; #endregion } }
33.134454
76
0.581283
[ "MIT" ]
norealm/expression-lite
src/lib/Token/DefaultLexemeConverter.cs
3,945
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Enums")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Enums")] [assembly: AssemblyCopyright("Copyright © 2013")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("251f1fa2-76aa-4923-936d-f061b3d03da9")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
37.378378
84
0.742589
[ "MIT" ]
PrasadHonrao/Learn.CSharp
Language/Enums/Enums/Properties/AssemblyInfo.cs
1,386
C#
using System; namespace Calamari.Tests.Shared.LogParser { public class ProcessOutput { public ProcessOutput(ProcessOutputSource source, string text) : this(source, text, DateTimeOffset.UtcNow) { } public ProcessOutput(ProcessOutputSource source, string text, DateTimeOffset occurred) { this.Source = source; this.Text = text; this.Occurred = occurred; } public ProcessOutputSource Source { get; } public DateTimeOffset Occurred { get; } public string Text { get; } } }
24.24
94
0.607261
[ "Apache-2.0" ]
OctopusDeploy/Sashimi
source/Calamari.Tests.Shared/LogParser/ProcessOutput.cs
608
C#
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ using System; using System.Collections.Generic; using Aliyun.Acs.Core.Transform; using Aliyun.Acs.Ecs.Model.V20140526; namespace Aliyun.Acs.Ecs.Transform.V20140526 { public class DeleteImageResponseUnmarshaller { public static DeleteImageResponse Unmarshall(UnmarshallerContext _ctx) { DeleteImageResponse deleteImageResponse = new DeleteImageResponse(); deleteImageResponse.HttpResponse = _ctx.HttpResponse; deleteImageResponse.RequestId = _ctx.StringValue("DeleteImage.RequestId"); return deleteImageResponse; } } }
34.8
78
0.750718
[ "Apache-2.0" ]
AxiosCros/aliyun-openapi-net-sdk
aliyun-net-sdk-ecs/Ecs/Transform/V20140526/DeleteImageResponseUnmarshaller.cs
1,392
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. namespace System.Windows.Forms { using System; using System.Collections; using System.ComponentModel; using System.ComponentModel.Design; using System.ComponentModel.Design.Serialization; using System.Globalization; [TypeConverterAttribute(typeof(TableLayoutPanelCellPositionTypeConverter))] public struct TableLayoutPanelCellPosition { private int row; private int column; public TableLayoutPanelCellPosition(int column, int row) { if (row < -1) { throw new ArgumentOutOfRangeException("row", string.Format(SR.InvalidArgument, "row", (row).ToString(CultureInfo.CurrentCulture))); } if (column < -1) { throw new ArgumentOutOfRangeException("column", string.Format(SR.InvalidArgument, "column", (column).ToString(CultureInfo.CurrentCulture))); } this.row = row; this.column = column; } public int Row { get { return row; } set { row = value; } } public int Column { get { return column; } set { column = value; } } public override bool Equals(object other) { if(other is TableLayoutPanelCellPosition) { TableLayoutPanelCellPosition dpeOther = (TableLayoutPanelCellPosition) other; return (dpeOther.row == row && dpeOther.column == column); } return false; } public static bool operator ==(TableLayoutPanelCellPosition p1, TableLayoutPanelCellPosition p2) { return p1.Row == p2.Row && p1.Column == p2.Column; } public static bool operator !=(TableLayoutPanelCellPosition p1, TableLayoutPanelCellPosition p2) { return !(p1 == p2); } public override string ToString() { return Column.ToString(CultureInfo.CurrentCulture) + "," + Row.ToString(CultureInfo.CurrentCulture); } public override int GetHashCode() { // Structs should implement GetHashCode for perf return WindowsFormsUtils.GetCombinedHashCodes( this.row, this.column); } } internal class TableLayoutPanelCellPositionTypeConverter : TypeConverter { public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType) { if (destinationType == typeof(InstanceDescriptor)) { return true; } return base.CanConvertTo(context, destinationType); } public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType) { if (sourceType == typeof(string)) { return true; } return base.CanConvertFrom(context, sourceType); } public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) { if (value is string) { string text = ((string)value).Trim(); if (text.Length == 0) { return null; } else { // Parse 2 integer values. // if (culture == null) { culture = CultureInfo.CurrentCulture; } char sep = culture.TextInfo.ListSeparator[0]; string[] tokens = text.Split(new char[] {sep}); int[] values = new int[tokens.Length]; TypeConverter intConverter = TypeDescriptor.GetConverter(typeof(int)); for (int i = 0; i < values.Length; i++) { // Note: ConvertFromString will raise exception if value cannot be converted. values[i] = (int)intConverter.ConvertFromString(context, culture, tokens[i]); } if (values.Length == 2) { return new TableLayoutPanelCellPosition(values[0], values[1]); } else { throw new ArgumentException(string.Format(SR.TextParseFailedFormat, text, "column, row")); } } } return base.ConvertFrom(context, culture, value); } public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) { if (destinationType == null) { throw new ArgumentNullException("destinationType"); } if (destinationType == typeof(InstanceDescriptor) && value is TableLayoutPanelCellPosition) { TableLayoutPanelCellPosition cellPosition = (TableLayoutPanelCellPosition) value; return new InstanceDescriptor( typeof(TableLayoutPanelCellPosition).GetConstructor(new Type[] {typeof(int), typeof(int)}), new object[] {cellPosition.Column, cellPosition.Row}); } return base.ConvertTo(context, culture, value, destinationType); } public override object CreateInstance(ITypeDescriptorContext context, IDictionary propertyValues) { return new TableLayoutPanelCellPosition( (int)propertyValues["Column"], (int)propertyValues["Row"] ); } public override bool GetCreateInstanceSupported(ITypeDescriptorContext context) { return true; } public override PropertyDescriptorCollection GetProperties(ITypeDescriptorContext context, object value, Attribute[] attributes) { PropertyDescriptorCollection props = TypeDescriptor.GetProperties(typeof(TableLayoutPanelCellPosition), attributes); return props.Sort(new string[] {"Column","Row"}); } public override bool GetPropertiesSupported(ITypeDescriptorContext context) { return true; } } }
39.271676
156
0.543862
[ "MIT" ]
abbaye/winforms
src/System.Windows.Forms/src/System/Windows/Forms/TableLayoutPanelCellPosition.cs
6,794
C#
using System; using System.Globalization; using System.Text.RegularExpressions; using System.Xml; namespace commercetools.Sdk.Linq { public static class StringExtensions { public static string ToCamelCase(this string value) { if (!string.IsNullOrEmpty(value) && value.Length > 1) { return char.ToLowerInvariant(value[0]) + value.Substring(1); } return value; } public static string WrapInQuotes(this string value) { return string.Format(CultureInfo.InvariantCulture, "\"{0}\"", value); } /// <summary> /// If string contains a dash (-) or starts with a digit, escape it using backticks (`) /// </summary> /// <param name="value">name of field or attribute</param> /// <returns>string wrapped in backticks if string matched conditions</returns> public static string WrapInBackticksIfNeeded(this string value) { bool wrap = value.Contains("-") || Regex.IsMatch(value, @"^\d"); var result = wrap ? string.Format(CultureInfo.InvariantCulture, "`{0}`", value) : value; return result; } public static string RemoveQuotes(this string value) { return value.Replace("\"", string.Empty); } public static string ToUtcIso8601(this DateTime dt, bool onlyDate = false) { string dateFormatted; if (onlyDate) { dateFormatted = dt.ToString("yyyy'-'MM'-'dd", CultureInfo.InvariantCulture); } else { dateFormatted = dt.ToUniversalTime() .ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffK", CultureInfo.InvariantCulture); } return dateFormatted; } public static string ToIso8601(this TimeSpan time) { return time.ToString("hh':'mm':'ss'.'fff", CultureInfo.InvariantCulture); } } }
31.984375
100
0.56424
[ "Apache-2.0" ]
commercetools/commercetools-dotnet-core-sdk
commercetools.Sdk/commercetools.Sdk.Linq/StringExtensions.cs
2,049
C#
using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using Steeltoe.Discovery.Client; using Steeltoe.Management.Tracing; namespace Microsoft.Azure.SpringCloud.Sample.SolarSystemWeather { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddLogging(configure => configure.AddConsole()); services.AddDiscoveryClient(Configuration); services.AddDistributedTracing(Configuration, builder => builder.UseZipkinWithTraceOptions(services)); services.AddControllers(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseDiscoveryClient(); app.UseRouting(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); } } }
31.14
114
0.660886
[ "MIT" ]
Azure-Samples/Azure-Spring-Cloud-Samples
steeltoe-sample/src/solar-system-weather/Startup.cs
1,557
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Buffers; using System.Buffers.Text; using System.Diagnostics; using System.Globalization; using System.Runtime.CompilerServices; using System.Text; namespace SpanJson { partial struct Utf8JsonWriter { /// <summary> /// Writes the <see cref="float"/> value (as a JSON number) as an element of a JSON array. /// </summary> /// <param name="value">The value to write.</param> /// <exception cref="InvalidOperationException"> /// Thrown if this would result in invalid JSON being written (while validation is enabled). /// </exception> /// <remarks> /// Writes the <see cref="float"/> using the default <see cref="StandardFormat"/> on .NET Core 3 or higher /// and 'G9' on any other framework. /// </remarks> public void WriteNumberValue(float value) { JsonWriterHelper.ValidateSingle(value); ValidateWritingValue(); if (_options.Indented) { WriteNumberValueIndented(value); } else { WriteNumberValueMinimized(value); } SetFlagToAddListSeparatorBeforeNextItem(); _tokenType = JsonTokenType.Number; } private void WriteNumberValueMinimized(float value) { int maxRequired = JsonSharedConstant.MaximumFormatSingleLength + 1; // Optionally, 1 list separator ref var pos = ref _pos; EnsureUnsafe(pos, maxRequired); ref byte output = ref PinnableAddress; if ((uint)_currentDepth > JsonSharedConstant.TooBigOrNegative) { Unsafe.Add(ref output, pos++) = JsonUtf8Constant.ListSeparator; } bool result = TryFormatSingle(value, FreeSpan, out int bytesWritten); Debug.Assert(result); pos += bytesWritten; } private void WriteNumberValueIndented(float value) { int indent = Indentation; Debug.Assert(indent <= 2 * JsonSharedConstant.MaxWriterDepth); int maxRequired = indent + JsonSharedConstant.MaximumFormatSingleLength + 1 + JsonWriterHelper.NewLineLength; // Optionally, 1 list separator and 1-2 bytes for new line ref var pos = ref _pos; EnsureUnsafe(pos, maxRequired); ref byte output = ref PinnableAddress; if ((uint)_currentDepth > JsonSharedConstant.TooBigOrNegative) { Unsafe.Add(ref output, pos++) = JsonUtf8Constant.ListSeparator; } if (_tokenType != JsonTokenType.PropertyName) { if (_tokenType != JsonTokenType.None) { WriteNewLine(ref output, ref pos); } JsonWriterHelper.WriteIndentation(ref output, indent, ref pos); } bool result = TryFormatSingle(value, FreeSpan, out int bytesWritten); Debug.Assert(result); pos += bytesWritten; } private static bool TryFormatSingle(float value, Span<byte> destination, out int bytesWritten) { // Frameworks that are not .NET Core 3.0 or higher do not produce roundtrippable strings by // default. Further, the Utf8Formatter on older frameworks does not support taking a precision // specifier for 'G' nor does it represent other formats such as 'R'. As such, we duplicate // the .NET Core 3.0 logic of forwarding to the UTF16 formatter and transcoding it back to UTF8, // with some additional changes to remove dependencies on Span APIs which don't exist downlevel. #if NETCOREAPP_2_X_GREATER || NETSTANDARD_2_0_GREATER return Utf8Formatter.TryFormat(value, destination, out bytesWritten); #else const string FormatString = "G9"; string utf16Text = value.ToString(FormatString, CultureInfo.InvariantCulture); // Copy the value to the destination, if it's large enough. if (utf16Text.Length > destination.Length) { bytesWritten = 0; return false; } try { byte[] bytes = Encoding.UTF8.GetBytes(utf16Text); if (bytes.Length > destination.Length) { bytesWritten = 0; return false; } bytes.CopyTo(destination); bytesWritten = bytes.Length; return true; } catch { bytesWritten = 0; return false; } #endif } } }
34.93007
180
0.583984
[ "MIT" ]
cuteant/SpanJson
src/SpanJson.Extensions/Writer/Utf8JsonWriter.WriteValues.Float.cs
4,997
C#
using Esri.ArcGISRuntime.Geometry; using Esri.ArcGISRuntime.Security; using System; using System.ComponentModel; using System.Runtime.CompilerServices; using System.Threading.Tasks; using System.Windows; using Windows.ApplicationModel.Core; using Windows.UI; using Windows.UI.Core; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Data; using Windows.UI.Xaml.Media; namespace ArcGISRuntimeSDKDotNet_PhoneSamples.Samples { /// <summary> /// This sample demonstrates how to use the IdentityManager to access a secured service. Here, the map contains a public basemap and a secure dynamic layer. Click Login to enter credentials to access the secure service. /// </summary> /// <title>ArcGIS Token Secured Services</title> /// <category>Security</category> public partial class TokenSecuredServices : Page { private TaskCompletionSource<Credential> _loginTCS; /// <summary>Construct Token Secured Services sample control</summary> public TokenSecuredServices() { InitializeComponent(); IdentityManager.Current.ChallengeHandler = new ChallengeHandler(Challenge); } // Base Challenge method that dispatches to the UI thread if necessary private async Task<Credential> Challenge(CredentialRequestInfo cri) { var dispatcher = CoreApplication.MainView.CoreWindow.Dispatcher; if (dispatcher == null) { return await ChallengeUI(cri); } else { await dispatcher.RunAsync(CoreDispatcherPriority.Normal, async () => { await ChallengeUI(cri); }); return await _loginTCS.Task; } } // Challenge method that checks for service access with known credentials //private async Task<IdentityManager.Credential> Challenge_KnownCredentials(IdentityManager.CredentialRequestInfo cri) //{ // try // { // // Obtain credentials from a secure source // string username = "user1"; // string password = (cri.ServiceUri.Contains("USA_secure_user1")) ? "user1" : "pass.word1"; // return await IdentityManager.Current.GenerateCredentialAsync(cri.ServiceUri, username, password, cri.GenerateTokenOptions); // } // catch (Exception ex) // { // var _x = new MessageDialog("Access to " + cri.ServiceUri + " denied. " + ex.Message, "Credential Error").ShowAsync(); // } // return await Task.FromResult<IdentityManager.Credential>(null); //} // Challenge method that prompts for username / password private async Task<Credential> ChallengeUI(CredentialRequestInfo cri) { try { string username = "user1"; string password = (cri.ServiceUri.Contains("USA_secure_user1")) ? "user1" : "pass.word1"; loginPanel.DataContext = new LoginInfo(cri, username, password); _loginTCS = new TaskCompletionSource<Credential>(loginPanel.DataContext); loginPanel.Visibility = Visibility.Visible; return await _loginTCS.Task; } finally { LoginFlyout.Hide(); } } // Login button handler - checks entered credentials private async void btnLogin_Click(object sender, RoutedEventArgs e) { if (_loginTCS == null || _loginTCS.Task == null || _loginTCS.Task.AsyncState == null) return; var loginInfo = _loginTCS.Task.AsyncState as LoginInfo; try { var credentials = await IdentityManager.Current.GenerateCredentialAsync(loginInfo.ServiceUrl, loginInfo.UserName, loginInfo.Password, loginInfo.RequestInfo.GenerateTokenOptions); _loginTCS.TrySetResult(credentials); } catch (Exception ex) { loginInfo.ErrorMessage = ex.Message; loginInfo.AttemptCount++; if (loginInfo.AttemptCount >= 3) { _loginTCS.TrySetException(ex); } } } } // Helper class to contain login information internal class LoginInfo : INotifyPropertyChanged { private CredentialRequestInfo _requestInfo; public CredentialRequestInfo RequestInfo { get { return _requestInfo; } set { _requestInfo = value; OnPropertyChanged(); } } private string _serviceUrl; public string ServiceUrl { get { return _serviceUrl; } set { _serviceUrl = value; OnPropertyChanged(); } } private string _userName; public string UserName { get { return _userName; } set { _userName = value; OnPropertyChanged(); } } private string _password; public string Password { get { return _password; } set { _password = value; OnPropertyChanged(); } } private string _errorMessage; public string ErrorMessage { get { return _errorMessage; } set { _errorMessage = value; OnPropertyChanged(); } } private int _attemptCount; public int AttemptCount { get { return _attemptCount; } set { _attemptCount = value; OnPropertyChanged(); } } public LoginInfo(CredentialRequestInfo cri, string user, string pwd) { RequestInfo = cri; ServiceUrl = new Uri(cri.ServiceUri).GetComponents(UriComponents.AbsoluteUri & ~UriComponents.Query, UriFormat.UriEscaped); UserName = user; Password = pwd; ErrorMessage = string.Empty; AttemptCount = 0; } public event PropertyChangedEventHandler PropertyChanged; private void OnPropertyChanged([CallerMemberName] string propertyName = null) { var handler = PropertyChanged; if (handler != null) { handler(this, new PropertyChangedEventArgs(propertyName)); } } } public class ValueToForegroundColorConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, string language) { SolidColorBrush brush; if (value.ToString() == "Initializing") brush = new SolidColorBrush(Colors.Red); else if (value.ToString() == "Initialized") brush = new SolidColorBrush(Colors.Green); else brush = new SolidColorBrush(Colors.Black); return brush; } public object ConvertBack(object value, Type targetType, object parameter, string language) { throw new NotImplementedException(); } } }
27.835681
220
0.716478
[ "Apache-2.0" ]
mikedorais/arcgis-runtime-samples-dotnet
src/Phone/ArcGISRuntimeSDKDotNet_PhoneSamples/Samples/Security/TokenSecuredServices.xaml.cs
5,931
C#
// Copyright 2018 yinyue200.com // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System.Collections.Generic; using LottieSharp.Model.Content; using SkiaSharp; namespace LottieSharp.Animation.Keyframe { internal class MaskKeyframeAnimation { private readonly List<IBaseKeyframeAnimation<ShapeData, SKPath>> _maskAnimations; private readonly List<IBaseKeyframeAnimation<int?, int?>> _opacityAnimations; internal MaskKeyframeAnimation(List<Mask> masks) { Masks = masks; _maskAnimations = new List<IBaseKeyframeAnimation<ShapeData, SKPath>>(masks.Count); _opacityAnimations = new List<IBaseKeyframeAnimation<int?, int?>>(masks.Count); for (var i = 0; i < masks.Count; i++) { _maskAnimations.Add(masks[i].MaskPath.CreateAnimation()); var opacity = masks[i].Opacity; _opacityAnimations.Add(opacity.CreateAnimation()); } } internal List<Mask> Masks { get; } internal List<IBaseKeyframeAnimation<ShapeData, SKPath>> MaskAnimations => _maskAnimations; internal List<IBaseKeyframeAnimation<int?, int?>> OpacityAnimations => _opacityAnimations; } }
40.181818
99
0.686086
[ "Apache-2.0" ]
alex-harper/LottieSkiaSharp
LottieSkiaSharp/Animation/Keyframe/MaskKeyframeAnimation.cs
1,770
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace MessageBox.Messages { public interface IReplyWithPayloadMessage : IReplyMessage, IDisposable { /// <summary> /// Type name of the object serialized in the Payload property /// </summary> string PayloadType { get; } /// <summary> /// Optional payload data /// </summary> ReadOnlyMemory<byte> Payload { get; } } }
23.5
74
0.636364
[ "MIT" ]
adospace/message-box
src/MessageBox.Core/Messages/IReplyWithPayloadMessage.cs
519
C#
Console.Write("Please type in the name of the file " + "containing the names of the people to be cold called > "); string? fileName = Console.ReadLine(); if (fileName != null) { ColdCallFileReaderLoop1(fileName); Console.WriteLine(); //ColdCallFileReaderLoop2(fileName); //Console.WriteLine(); } Console.ReadLine(); // with using declaration instead of try/finally void ColdCallFileReaderLoop2(string fileName) { using ColdCallFileReader peopleToRing = new(); try { peopleToRing.Open(fileName); for (int i = 0; i < peopleToRing.NPeopleToRing; i++) { peopleToRing.ProcessNextPerson(); } Console.WriteLine("All callers processed correctly"); } catch (FileNotFoundException) { Console.WriteLine($"The file {fileName} does not exist"); } catch (ColdCallFileFormatException ex) { Console.WriteLine($"The file {fileName} appears to have been corrupted"); Console.WriteLine($"Details of problem are: {ex.Message}"); if (ex.InnerException != null) { Console.WriteLine($"Inner exception was: {ex.InnerException.Message}"); } } catch (Exception ex) { Console.WriteLine($"Exception occurred:\n{ex.Message}"); } } void ColdCallFileReaderLoop1(string fileName) { ColdCallFileReader peopleToRing = new(); try { peopleToRing.Open(fileName); for (int i = 0; i < peopleToRing.NPeopleToRing; i++) { peopleToRing.ProcessNextPerson(); } Console.WriteLine("All callers processed correctly"); } catch (FileNotFoundException) { Console.WriteLine($"The file {fileName} does not exist"); } catch (ColdCallFileFormatException ex) { Console.WriteLine($"The file {fileName} appears to have been corrupted"); Console.WriteLine($"Details of problem are: {ex.Message}"); if (ex.InnerException != null) { Console.WriteLine($"Inner exception was: {ex.InnerException.Message}"); } } catch (Exception ex) { Console.WriteLine($"Exception occurred:\n{ex.Message}"); } finally { peopleToRing.Dispose(); } }
27.876543
83
0.622232
[ "MIT" ]
christiannagel/ProfessionalCSharp2021
1_CS/ErrorsAndExceptions/SolicitColdCall/Program.cs
2,260
C#
using Microsoft.EntityFrameworkCore.Migrations; namespace GameSpace.Data.Migrations { public partial class UpdateColumnMessageInNotificationTable : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.AlterColumn<string>( name: "Message", table: "Notifications", type: "nvarchar(100)", maxLength: 100, nullable: false, oldClrType: typeof(string), oldType: "nvarchar(60)", oldMaxLength: 60); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.AlterColumn<string>( name: "Message", table: "Notifications", type: "nvarchar(60)", maxLength: 60, nullable: false, oldClrType: typeof(string), oldType: "nvarchar(100)", oldMaxLength: 100); } } }
31.029412
75
0.532701
[ "MIT" ]
Simeon-Yankov/GameSpace
GameSpace.Data/Migrations/20210805131108_UpdateColumnMessageInNotificationTable.cs
1,057
C#
//Write a program that converts a decimal number N to its hexadecimal representation. using System; using System.Text; class DecimalToHexadecimal { static void Main() { long num = long.Parse(Console.ReadLine()); Console.WriteLine(ConvertDecimalToHexadecimal(num)); } static string ConvertDecimalToHexadecimal(long number) { var hexNum = new StringBuilder(); while (number > 0) { hexNum.Insert(0, symbols[number % 16]); number /= 16; } return hexNum.ToString(); } }
21.62963
86
0.606164
[ "MIT" ]
nina75/C-Sharp-Advanced
NumeraSystems/DecimalToHexadecimal/DecimalToHexadecimal.cs
586
C#
using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Blazor.Extensions.MergeStyles { public struct CssValue : IComparable<string>, IComparable<double>, IComparable<bool>, IComparable<int> { public CssValue(int value) { this.Integer = value; this.Double = null; this.String = null; this.Bolean = null; } public CssValue(double value) { this.Double = value; this.String = null; this.Bolean = null; this.Integer = null; } public CssValue(string value) { this.String = value; this.Double = null; this.Bolean = null; this.Integer = null; } public CssValue(bool value) { this.Bolean = value; this.Double = null; this.String = null; this.Integer = null; } public bool IsDouble => this.Double.HasValue; public bool IsInteger => this.Integer.HasValue; public bool IsNumber => this.IsDouble || this.IsInteger; public bool IsBolean => this.Bolean.HasValue; public string String { get; internal set; } public bool? Bolean { get; internal set; } public double? Double { get; internal set; } public int? Integer { get; internal set; } public bool IsString => !this.IsNumber && !this.IsBolean; public static implicit operator CssValue(in double value) => new CssValue(value); public static implicit operator CssValue(in int value) => new CssValue(value); public static implicit operator CssValue(in string value) => new CssValue(value); public static implicit operator CssValue(in bool value) => new CssValue(value); public static implicit operator CssValue(in AlignContent value) => new CssValue { String = JsonConvert.SerializeObject(value, RawConverter.Settings) }; public static explicit operator string(in CssValue rule) => rule.IsString ? rule.String : throw new InvalidCastException($"The rule {rule} is not a string value"); public static explicit operator double(in CssValue rule) => rule.Double ?? throw new InvalidCastException($"The rule {rule} is not a double value"); public static explicit operator int(in CssValue rule) => rule.Integer ?? throw new InvalidCastException($"The rule {rule} is not a integer value"); public static explicit operator bool(in CssValue rule) => rule.Bolean ?? throw new InvalidCastException($"The rule {rule} is not a bolean value"); public bool IsNull => this.String is null && this.Double is null && this.Bolean is null && this.Integer is null; public override bool Equals(object obj) { if (!(obj is CssValue other)) { return false; } if (other.IsDouble) return other.Double == this.Double; if (other.IsInteger) return other.Integer == this.Integer; else if (other.IsBolean) return other.Bolean == this.Bolean; return other.String == this.String; } public override int GetHashCode() { if (this.IsDouble) return this.Double.Value.GetHashCode(); if (this.IsInteger) return this.Integer.Value.GetHashCode(); if (this.IsBolean) return this.Bolean.Value.GetHashCode(); return this.String.GetHashCode(); } public static bool operator ==(CssValue rule, string value) => rule.String == value; public static bool operator !=(CssValue rule, string value) => rule.String != value; public static bool operator ==(CssValue rule1, CssValue rule2) { if (rule1.IsNull || rule2.IsNull) return false; return rule1.String == rule2.String || rule1.Double == rule2.Double || rule1.Integer == rule2.Integer; } public static bool operator !=(CssValue rule1, CssValue rule2) { if (rule1.IsNull || rule2.IsNull) return true; return rule1.String == rule2.String || rule1.Double == rule2.Double || rule1.Integer == rule1.Integer; } public override string ToString() { return this.Double?.ToString() ?? this.Integer?.ToString() ?? this.String ?? this.Bolean?.ToString(); } public string Replace(string oldValue, string newValue) { if (!this.IsString) throw new InvalidOperationException($"This rule is not a string, value {this}"); return this.String.Replace(oldValue, newValue); } public int CompareTo(double other) { if (!this.IsDouble) return 1; return this.Double == other ? 0 : 1; } public int CompareTo(string other) { if (this.String != null) return 1; return this.String == other ? 0 : 1; } public int CompareTo(bool other) { if (!this.IsBolean) return 1; return this.Bolean == other ? 0 : 1; } public int CompareTo(int other) { if (!this.IsInteger) return 1; return this.Integer == other ? 0 : 1; } } }
33.12426
171
0.574312
[ "MIT" ]
BlazorExtensions/Blazor.Extensions.OfficeUIFabric
src/Blazor.Extensions.MergeStyles.Core/CssValue.cs
5,598
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("02. Basic Stack Operations")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("02. Basic Stack Operations")] [assembly: AssemblyCopyright("Copyright © 2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("a7bf4d88-d37e-4f6f-9d37-d15015db5b87")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
38.378378
84
0.747183
[ "MIT" ]
sevdalin/Software-University-SoftUni
C-sharp-Web-Developer/C# Advanced/StacksAndQueues/02. Basic Stack Operations/Properties/AssemblyInfo.cs
1,423
C#
using System.IO; using Sep.Git.Tfs.Commands; using StructureMap.AutoMocking; using NDesk.Options; using Xunit; namespace Sep.Git.Tfs.Test.Commands { public class InitOptionsTest { private RhinoAutoMocker<InitOptions> mocks; public InitOptionsTest() { mocks = new RhinoAutoMocker<InitOptions>(); } [Fact] public void AutoCrlfDefault() { Assert.Equal("false", mocks.ClassUnderTest.GitInitAutoCrlf); } [Fact] public void AutoCrlfProvideTrue() { string[] args = {"init", "--autocrlf=true", "http://example.com/tfs", "$/Junk"}; mocks.ClassUnderTest.OptionSet.Parse(args); Assert.Equal("true", mocks.ClassUnderTest.GitInitAutoCrlf); } [Fact] public void AutoCrlfProvideFalse() { string[] args = { "init", "--autocrlf=false", "http://example.com/tfs", "$/Junk" }; mocks.ClassUnderTest.OptionSet.Parse(args); Assert.Equal("false", mocks.ClassUnderTest.GitInitAutoCrlf); } [Fact] public void AutoCrlfProvideAuto() { string[] args = { "init", "--autocrlf=auto", "http://example.com/tfs", "$/Junk" }; mocks.ClassUnderTest.OptionSet.Parse(args); Assert.Equal("auto", mocks.ClassUnderTest.GitInitAutoCrlf); } [Fact] public void AutoCrlfProvideInvalidOption() { string[] args = { "init", "--autocrlf=windows", "http://example.com/tfs", "$/Junk" }; Assert.Throws<OptionException>(() => mocks.ClassUnderTest.OptionSet.Parse(args)); Assert.Equal("false", mocks.ClassUnderTest.GitInitAutoCrlf); } } }
30.413793
97
0.581066
[ "Apache-2.0" ]
spraints/git-tfs
GitTfsTest/Commands/InitOptionsTest.cs
1,766
C#
using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Diagnostics; using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; namespace Coercive.CSharp.Usage { [DiagnosticAnalyzer(LanguageNames.CSharp)] public class RemovePrivateMethodNeverUsedAnalyzer : DiagnosticAnalyzer { internal const string Title = "Unused Method"; internal const string Message = "Method is not used."; internal const string Category = SupportedCategories.Usage; const string Description = "Unused private methods can be safely removed as they are unnecessary."; internal static readonly DiagnosticDescriptor Rule = new DiagnosticDescriptor( DiagnosticId.RemovePrivateMethodNeverUsed.ToDiagnosticId(), Title, Message, Category, DiagnosticSeverity.Info, isEnabledByDefault: true, description: Description, helpLinkUri: HelpLink.ForDiagnostic(DiagnosticId.RemovePrivateMethodNeverUsed)); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Rule); public override void Initialize(AnalysisContext context) => context.RegisterSyntaxNodeAction(AnalyzeNode, SyntaxKind.MethodDeclaration); private static void AnalyzeNode(SyntaxNodeAnalysisContext context) { if (context.IsGenerated()) return; var methodDeclaration = (MethodDeclarationSyntax)context.Node; if (methodDeclaration.ExplicitInterfaceSpecifier != null) return; var methodSymbol = context.SemanticModel.GetDeclaredSymbol(methodDeclaration); if (methodSymbol.DeclaredAccessibility != Accessibility.Private) return; if (IsMethodAttributeAnException(methodDeclaration)) return; if (IsMethodUsed(methodDeclaration, context.SemanticModel)) return; if (IsMainMethodEntryPoint(methodDeclaration, context.SemanticModel)) return; if (methodDeclaration.Modifiers.Any(SyntaxKind.ExternKeyword)) return; if (IsWinformsPropertyDefaultValueDefinitionMethod(methodDeclaration, context.SemanticModel)) return; var props = new Dictionary<string, string> { { "identifier", methodDeclaration.Identifier.Text } }.ToImmutableDictionary(); var diagnostic = Diagnostic.Create(Rule, methodDeclaration.GetLocation(), props); context.ReportDiagnostic(diagnostic); } private static bool IsMethodAttributeAnException(MethodDeclarationSyntax methodDeclaration) { if (methodDeclaration == null) return false; foreach (var attributeList in methodDeclaration.AttributeLists) { foreach (var attribute in attributeList.Attributes) { var identifierName = attribute.Name as IdentifierNameSyntax; string nameText = null; if (identifierName != null) { nameText = identifierName?.Identifier.Text; } else { var qualifiedName = attribute.Name as QualifiedNameSyntax; if (qualifiedName != null) nameText = qualifiedName.Right?.Identifier.Text; } if (nameText == null) continue; if (IsExcludedAttributeName(nameText)) return true; } } return false; } // Some Attributes make it valid to have an unused private Method, this is a list of them private static readonly string[] excludedAttributeNames = { "Fact", "ContractInvariantMethod", "DataMember" }; private static bool IsExcludedAttributeName(string attributeName) => excludedAttributeNames.Contains(attributeName); private static bool IsMethodUsed(MethodDeclarationSyntax methodTarget, SemanticModel semanticModel) { var typeDeclaration = methodTarget.Parent as TypeDeclarationSyntax; if (typeDeclaration == null) return true; if (!typeDeclaration.Modifiers.Any(SyntaxKind.PartialKeyword)) return IsMethodUsed(methodTarget, typeDeclaration); var symbol = semanticModel.GetDeclaredSymbol(typeDeclaration); return symbol == null || symbol.DeclaringSyntaxReferences.Any(reference => IsMethodUsed(methodTarget, reference.GetSyntax())); } private static bool IsMethodUsed(MethodDeclarationSyntax methodTarget, SyntaxNode typeDeclaration) { var descendents = typeDeclaration.DescendantNodes(); var hasIdentifier = descendents.OfType<IdentifierNameSyntax>(); if (hasIdentifier.Any(a => a != null && a.Identifier.ValueText.Equals(methodTarget.Identifier.ValueText))) return true; var genericNames = descendents.OfType<GenericNameSyntax>(); return genericNames.Any(n => n != null && n.Identifier.ValueText.Equals(methodTarget.Identifier.ValueText)); } private static bool IsMainMethodEntryPoint(MethodDeclarationSyntax methodTarget, SemanticModel semanticModel) { if (!methodTarget.Identifier.Text.Equals("Main", StringComparison.Ordinal)) return false; if (!methodTarget.Modifiers.Any(SyntaxKind.StaticKeyword)) return false; var returnType = semanticModel.GetTypeInfo(methodTarget.ReturnType).Type; if (returnType == null) return false; if (!returnType.Name.Equals("Void", StringComparison.OrdinalIgnoreCase) && !returnType.Name.Equals("Int32", StringComparison.OrdinalIgnoreCase)) return false; var parameters = methodTarget.ParameterList.Parameters; if (parameters.Count > 1) return false; if (parameters.Count == 0) return true; var parameterType = semanticModel.GetTypeInfo(parameters.First().Type).Type; if (!parameterType.OriginalDefinition.ToString().Equals("String[]", StringComparison.OrdinalIgnoreCase)) return false; return true; } // see https://msdn.microsoft.com/en-us/library/53b8022e(v=vs.110).aspx private static bool IsWinformsPropertyDefaultValueDefinitionMethod(MethodDeclarationSyntax methodTarget, SemanticModel semanticModel) { var propertyName = GetPropertyNameForWinformDefaultValueMethods(methodTarget, semanticModel); if (string.IsNullOrWhiteSpace(propertyName)) return false; if (!ExistsProperty(propertyName, methodTarget, semanticModel)) return false; return true; } private static string GetPropertyNameForWinformDefaultValueMethods(MethodDeclarationSyntax methodTarget, SemanticModel semanticModel) => GetPropertyNameForMethodWithSignature(methodTarget, semanticModel, "Reset", "Void") ?? GetPropertyNameForMethodWithSignature(methodTarget, semanticModel, "ShouldSerialize", "Boolean"); private static string GetPropertyNameForMethodWithSignature(MethodDeclarationSyntax methodTarget, SemanticModel semanticModel, string startsWith, string returnType) { var methodName = methodTarget.Identifier.Text; if (methodName.StartsWith(startsWith)) if (methodTarget.ParameterList.Parameters.Count == 0) { var returnTypeInfo = semanticModel.GetTypeInfo(methodTarget.ReturnType).Type; if (returnTypeInfo.Name.Equals(returnType, StringComparison.OrdinalIgnoreCase)) return methodName.Substring(startsWith.Length); ; } return null; } private static bool ExistsProperty(string propertyName, SyntaxNode nodeInType, SemanticModel semanticModel) { var typeDeclaration = nodeInType.AncestorsAndSelf().OfType<TypeDeclarationSyntax>().FirstOrDefault(); if (typeDeclaration == null) return false; var propertyDeclarations = typeDeclaration.DescendantNodes().OfType<PropertyDeclarationSyntax>(); return propertyDeclarations.Any(pd => pd.Identifier.Text == propertyName); } } }
51.654545
172
0.671477
[ "Apache-2.0" ]
RefactorForce/Coercive
Coercive.CSharp/Usage/RemovePrivateMethodNeverUsedAnalyzer.cs
8,525
C#
//******************************************************************************************************************************************************************************************// // Copyright (c) 2020 @redhook62 (adfsmfa@gmail.com) // // // // 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. // // // // https://adfsmfa.codeplex.com // // https://github.com/neos-sdi/adfsmfa // // // //******************************************************************************************************************************************************************************************// using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using Microsoft.ManagementConsole; using Neos.IdentityServer.MultiFactor.Administration; using System.Threading; using Neos.IdentityServer.MultiFactor; using System.DirectoryServices; using Neos.IdentityServer.Console.Controls; using Microsoft.ManagementConsole.Advanced; namespace Neos.IdentityServer.Console { public partial class SecurityCustomViewControl : UserControl, IFormViewControl, IMMCNotificationData { private Control oldParent; private ServiceSecurityCustomFormView _frm = null; private bool _isnotifsenabled = true; private SecurityConfigurationCustomControl _ctrl; public SecurityCustomViewControl() { InitializeComponent(); } /// <summary> /// Initialize method /// </summary> public void Initialize(FormView view) { FormView = (ServiceSecurityCustomFormView)view; OnInitialize(); } /// <summary> /// OnInitialize method /// </summary> protected virtual void OnInitialize() { this.SuspendLayout(); try { ControlInstance = new SecurityConfigurationCustomControl(this, this.SnapIn); this.tableLayoutPanel.Controls.Add(ControlInstance, 0, 1); } finally { this.ResumeLayout(true); } } #region Properties /// <summary> /// FormView property implementation /// </summary> protected ServiceSecurityCustomFormView FormView { get { return _frm; } private set { _frm = value; } } /// <summary> /// ControlInstance property implmentation /// </summary> protected SecurityConfigurationCustomControl ControlInstance { get { return _ctrl; } private set { _ctrl = value; } } /// <summary> /// SnapIn method implementation /// </summary> protected NamespaceSnapInBase SnapIn { get { return this.FormView.ScopeNode.SnapIn; } } /// <summary> /// ScopeNode method implementation /// </summary> protected ServiceCustomSecurityScopeNode ScopeNode { get { return this.FormView.ScopeNode as ServiceCustomSecurityScopeNode; } } /// <summary> /// OnParentChanged method override /// </summary> protected override void OnParentChanged(EventArgs e) { if (Parent != null) { if (!DesignMode) Size = Parent.ClientSize; Parent.SizeChanged += Parent_SizeChanged; } if (oldParent != null) { oldParent.SizeChanged -= Parent_SizeChanged; } oldParent = Parent; base.OnParentChanged(e); } /// <summary> /// Parent_SizeChanged event /// </summary> private void Parent_SizeChanged(object sender, EventArgs e) { if (!DesignMode) Size = Parent.ClientSize; } #endregion /// <summary> /// RefreshData method implementation /// </summary> internal void RefreshData() { this.SuspendLayout(); this.Cursor = Cursors.WaitCursor; this._isnotifsenabled = false; try { ManagementService.ADFSManager.ReadConfiguration(null); ((IMMCRefreshData)ControlInstance).DoRefreshData(); } finally { this._isnotifsenabled = true; this.Cursor = Cursors.Default; this.ResumeLayout(); } } /// <summary> /// CancelData method implementation /// </summary> internal void CancelData() { try { MessageBoxParameters messageBoxParameters = new MessageBoxParameters(); ComponentResourceManager resources = new ComponentResourceManager(typeof(SecurityCustomViewControl)); messageBoxParameters.Text = resources.GetString("SMSVALIDSAVE"); messageBoxParameters.Buttons = MessageBoxButtons.YesNo; messageBoxParameters.Icon = MessageBoxIcon.Question; if (this.SnapIn.Console.ShowDialog(messageBoxParameters) == DialogResult.Yes) RefreshData(); } catch (Exception ex) { MessageBoxParameters messageBoxParameters = new MessageBoxParameters(); messageBoxParameters.Text = ex.Message; messageBoxParameters.Buttons = MessageBoxButtons.OK; messageBoxParameters.Icon = MessageBoxIcon.Error; this.SnapIn.Console.ShowDialog(messageBoxParameters); } } /// <summary> /// SaveData method implementation /// </summary> internal void SaveData() { if (this.ValidateChildren()) { this.Cursor = Cursors.WaitCursor; this._isnotifsenabled = false; try { ManagementService.ADFSManager.WriteConfiguration(null); } catch (Exception ex) { this.Cursor = Cursors.Default; MessageBoxParameters messageBoxParameters = new MessageBoxParameters(); messageBoxParameters.Text = ex.Message; messageBoxParameters.Buttons = MessageBoxButtons.OK; messageBoxParameters.Icon = MessageBoxIcon.Error; this.SnapIn.Console.ShowDialog(messageBoxParameters); } finally { this._isnotifsenabled = true; this.Cursor = Cursors.Default; } } } /// <summary> /// IsNotifsEnabled method implementation /// </summary> public bool IsNotifsEnabled() { return _isnotifsenabled; } /// <summary> /// RefreshProviderInformation method implementation /// </summary> public void RefreshProviderInformation() { this.ScopeNode.RefreshDescription(); ComponentResourceManager resources = new ComponentResourceManager(typeof(SecurityCustomViewControl)); this.ProviderTitle.Text = string.Format(resources.GetString("ProviderTitle.Text"), this.ScopeNode.DisplayName); } } }
43.923077
210
0.470422
[ "MIT" ]
k-korn/adfsmfa
Neos.IdentityServer 3.0/Neos.IdentityServer.Console/Forms/Neos.IdentityServer.Console.SecurityCustomViewControl.cs
10,280
C#
/* Copyright (c) 2006 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #region Using directives #define USE_TRACING using System; using System.Xml; using System.Globalization; using System.ComponentModel; using System.Runtime.InteropServices; #endregion ////////////////////////////////////////////////////////////////////// // Contains AtomBaseLink. ////////////////////////////////////////////////////////////////////// namespace Google.GData.Client { #if WindowsCE || PocketPC #else ////////////////////////////////////////////////////////////////////// /// <summary>TypeConverter, so that AtomBaseLink shows up in the property pages /// </summary> ////////////////////////////////////////////////////////////////////// [ComVisible(false)] public class AtomBaseLinkConverter : ExpandableObjectConverter { ///<summary>Standard type converter method</summary> public override bool CanConvertTo(ITypeDescriptorContext context, System.Type destinationType) { if (destinationType == typeof(AtomBaseLink) || destinationType == typeof(AtomId) || destinationType == typeof(AtomIcon) || destinationType == typeof(AtomLogo) ) return true; return base.CanConvertTo(context, destinationType); } /// <summary>standard ConvertTo typeconverter code</summary> ///<summary>Standard type converter method</summary> public override object ConvertTo(ITypeDescriptorContext context,CultureInfo culture, object value, System.Type destinationType) { AtomBaseLink link = value as AtomBaseLink; if (destinationType == typeof(System.String) && link != null) { return "Uri: " + link.Uri; } return base.ConvertTo(context, culture, value, destinationType); } } ///////////////////////////////////////////////////////////////////////////// #endif ////////////////////////////////////////////////////////////////////// /// <summary>AtomBaselink is an intermediate object that adds the URI property /// used as the parent class for a lot of other objects (like atomlink, atomicon, etc) /// </summary> ////////////////////////////////////////////////////////////////////// public abstract class AtomBaseLink : AtomBase { /// <summary>holds the string rep</summary> private AtomUri uriString; ////////////////////////////////////////////////////////////////////// /// <summary>accessor method public string Uri</summary> /// <returns> </returns> ////////////////////////////////////////////////////////////////////// public AtomUri Uri { get {return this.uriString;} set {this.Dirty = true; this.uriString = value;} } ///////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// /// <summary>public Uri AbsoluteUri</summary> ////////////////////////////////////////////////////////////////////// public string AbsoluteUri { get { return GetAbsoluteUri(this.Uri.ToString()); } } ///////////////////////////////////////////////////////////////////////////// #region Persistence overloads ////////////////////////////////////////////////////////////////////// /// <summary>saves the inner state of the element</summary> /// <param name="writer">the xmlWriter to save into </param> ////////////////////////////////////////////////////////////////////// protected override void SaveInnerXml(XmlWriter writer) { base.SaveInnerXml(writer); WriteEncodedString(writer, this.Uri); } ///////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// /// <summary>figures out if this object should be persisted</summary> /// <returns> true, if it's worth saving</returns> ////////////////////////////////////////////////////////////////////// public override bool ShouldBePersisted() { if (base.ShouldBePersisted() == false) { return Utilities.IsPersistable(this.uriString); } return true; } ///////////////////////////////////////////////////////////////////////////// #endregion } ///////////////////////////////////////////////////////////////////////////// } /////////////////////////////////////////////////////////////////////////////
38.642857
136
0.430684
[ "MIT" ]
FoxCouncil/YUP
YUM/YUM Modules/YouTube/API/Core/atombaselink.cs
5,410
C#
// Copyright(c) Microsoft Corporation // All rights reserved. // // Licensed under the Apache License, Version 2.0 (the License); you may not use // this file except in compliance with the License. You may obtain a copy of the // License at http://www.apache.org/licenses/LICENSE-2.0 // // THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS // OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY // IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, // MERCHANTABILITY OR NON-INFRINGEMENT. // // See the Apache Version 2.0 License for specific language governing // permissions and limitations under the License. using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Text.RegularExpressions; using Microsoft.Python.Analysis.Core.Interpreter; namespace Microsoft.Python.Parsing.Tests { internal class UnixPythonInstallPathResolver : IPythonInstallPathResolver { private static readonly Regex _pythonNameRegex = new Regex(@"^python(\d+(.\d+)?)?$", RegexOptions.Compiled); private readonly Dictionary<Version, InterpreterConfiguration> _coreCache; private readonly Dictionary<Version, InterpreterConfiguration> _condaCache; public UnixPythonInstallPathResolver() { _coreCache = new Dictionary<Version, InterpreterConfiguration>(); _condaCache = new Dictionary<Version, InterpreterConfiguration>(); GetConfigurationsFromKnownPaths(); GetConfigurationsFromConda(); } public InterpreterConfiguration GetCorePythonConfiguration(InterpreterArchitecture architecture, Version version) => architecture == InterpreterArchitecture.x86 ? null : _coreCache.TryGetValue(version, out var interpreterConfiguration) ? interpreterConfiguration : null; public InterpreterConfiguration GetCondaPythonConfiguration(InterpreterArchitecture architecture, Version version) => architecture == InterpreterArchitecture.x86 ? null : _condaCache.TryGetValue(version, out var interpreterConfiguration) ? interpreterConfiguration : null; private void GetConfigurationsFromKnownPaths() { var homePath = Environment.GetEnvironmentVariable("HOME"); var foldersFromPathVariable = Environment.GetEnvironmentVariable("PATH")?.Split(':') ?? Array.Empty<string>(); var knownFolders = new[] { "/usr/local/bin", "/usr/bin", "/bin", "/usr/sbin", "/sbin", "/usr/local/sbin" }; var folders = knownFolders.Concat(knownFolders.Select(p => Path.Combine(homePath, p))).Union(foldersFromPathVariable); foreach (var folder in folders) { try { var filePaths = Directory.EnumerateFiles(folder) .Where(p => _pythonNameRegex.IsMatch(Path.GetFileName(p))); foreach (var filePath in filePaths) { var configuration = GetConfiguration("Python Core", filePath); _coreCache.TryAdd(configuration.Version, configuration); } } catch (IOException) { } } } private void GetConfigurationsFromConda() { var homePath = Environment.GetEnvironmentVariable("HOME"); var condaEnvironmentsPath = Path.Combine(homePath, ".conda", "environments.txt"); IEnumerable<string> paths; try { paths = File.ReadAllLines(condaEnvironmentsPath) .Where(p => !string.IsNullOrWhiteSpace(p)) .Select(p => Path.Combine(p.Trim(), "bin", "python")); } catch (IOException) { return; } foreach (var path in paths) { var configuration = GetConfiguration("Conda", path); _coreCache.TryAdd(configuration.Version, configuration); _condaCache.TryAdd(configuration.Version, configuration); } } private InterpreterConfiguration GetConfiguration(string idPrefix, string pythonFilePath) { var configurationStrings = GetConfigurationString(pythonFilePath); var version = Version.Parse(configurationStrings[0]); var prefix = configurationStrings[1]; var architecture = bool.Parse(configurationStrings[2]) ? InterpreterArchitecture.x64 : InterpreterArchitecture.x86; var libPath = GetLibraryLocation(pythonFilePath); var sitePackagesPath = GetSitePackagesLocation(pythonFilePath); return new InterpreterConfiguration( interpreterPath: pythonFilePath, pathVar: pythonFilePath, libPath: libPath, sitePackagesPath: sitePackagesPath, architecture: architecture, version: version); } private static string[] GetConfigurationString(string pythonFilePath) => RunPythonAndGetOutput(pythonFilePath, "-c \"import sys; print('.'.join(str(x) for x in sys.version_info[:2])); print(sys.prefix); print(sys.maxsize > 2**32)\""); private static string GetLibraryLocation(string pythonFilePath) => RunPythonAndGetOutput(pythonFilePath, "-c \"import os, inspect; print(os.path.dirname(inspect.getfile(os)))\"").FirstOrDefault(); private static string GetSitePackagesLocation(string pythonFilePath) => RunPythonAndGetOutput(pythonFilePath, "-c \"import site; print(site.getsitepackages())\"").FirstOrDefault(s => s.Contains("site-packages")); private static string[] RunPythonAndGetOutput(string pythonFilePath, string arguments) { try { var processStartInfo = new ProcessStartInfo { FileName = pythonFilePath, Arguments = arguments, RedirectStandardOutput = true, UseShellExecute = false, CreateNoWindow = true }; var process = Process.Start(processStartInfo); var result = process.StandardOutput.ReadToEnd(); process.WaitForExit(); return result.Split(new[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries); } catch (Exception) { return Array.Empty<string>(); } } } }
50.10687
169
0.642748
[ "Apache-2.0" ]
6paklata/python-language-server
src/Parsing/Test/UnixPythonInstallPathResolver.cs
6,566
C#
using System; using System.Collections.Generic; using System.Text; using SequelNet.Connector; namespace SequelNet.Phrases { public class Add : IPhrase { public List<ValueWrapper> Values = new List<ValueWrapper>(); #region Constructors public Add(params ValueWrapper[] values) { this.Values.AddRange(values); } public Add( string tableName1, string columnName1, string tableName2, string columnName2) : this( ValueWrapper.Column(tableName1, columnName1), ValueWrapper.Column(tableName2, columnName2)) { } public Add( string tableName1, string columnName1, object value2, ValueObjectType valueType2) : this( ValueWrapper.Column(tableName1, columnName1), ValueWrapper.Make(value2, valueType2)) { } public Add( object value1, ValueObjectType valueType1, string tableName2, string columnName2) : this( ValueWrapper.Make(value1, valueType1), ValueWrapper.Column(tableName2, columnName2)) { } public Add( object value1, ValueObjectType valueType1, object value2, ValueObjectType valueType2) : this( ValueWrapper.Make(value1, valueType1), ValueWrapper.Make(value2, valueType2)) { } public Add(string tableName1, string columnName1, Int32 value2) : this( ValueWrapper.Column(tableName1, columnName1), ValueWrapper.From(value2)) { } public Add(string tableName1, string columnName1, Int64 value2) : this( ValueWrapper.Column(tableName1, columnName1), ValueWrapper.From(value2)) { } public Add(string tableName1, string columnName1, decimal value2) : this( ValueWrapper.Column(tableName1, columnName1), ValueWrapper.From(value2)) { } public Add(string tableName1, string columnName1, double value2) : this( ValueWrapper.Column(tableName1, columnName1), ValueWrapper.From(value2)) { } public Add(string tableName1, string columnName1, float value2) : this( ValueWrapper.Column(tableName1, columnName1), ValueWrapper.From(value2)) { } public Add(string columnName1, Int32 value2) : this( ValueWrapper.Column(columnName1), ValueWrapper.From(value2)) { } public Add(string columnName1, Int64 value2) : this( ValueWrapper.Column(columnName1), ValueWrapper.From(value2)) { } public Add(string columnName1, decimal value2) : this( ValueWrapper.Column(columnName1), ValueWrapper.From(value2)) { } public Add(string columnName1, double value2) : this( ValueWrapper.Column(columnName1), ValueWrapper.From(value2)) { } public Add(string columnName1, float value2) : this( ValueWrapper.Column(columnName1), ValueWrapper.From(value2)) { } #endregion public void Build(StringBuilder sb, ConnectorBase conn, Query relatedQuery = null) { bool first = true; foreach (var value in Values) { if (first) first = false; else sb.Append(" + "); sb.Append(value.Build(conn, relatedQuery)); } } } }
28.234043
90
0.525998
[ "MIT" ]
danielgindi/SequelNet
SequelNet/Sql/Phrases/Math/Add.cs
3,983
C#
// using point = System.Drawing.Point; struct point { int x,y; public point(int x, int y) { this.x = x; this.y = y; } override public string ToString() { return System.String.Format("({0},{1})", x, y); } } public class test { static point[,] x = new point[2,4]; public static void Main() { for (int i = 0; i < 2; i++) for (int j = 0; j < 4; j++) x[i,j] = new point(i, j); print(x); } static void print(System.Collections.IEnumerable x) { foreach (point p in x) System.Console.WriteLine(p); } }
24.590909
87
0.57671
[ "MIT" ]
sphinxlogic/Singularity-RDK-2.0
base/Windows/csic/test/2darray2.cs
541
C#
namespace Kissinjer.Scopes { using System; using System.Collections.Concurrent; public class SingletonScopeProvider : IScopeProvider { private readonly IScope _scope; public SingletonScopeProvider() { _scope = new Scope(); } public bool TryGetScope(out IScope scope) { scope = _scope; return true; } public TService GetOrAdd<TService>(Func<TService> createService) { if(!TryGetScope(out var scope)) { throw new InvalidScopeException(); } return scope.GetOrAdd(createService); } private class Scope : IScope { private readonly ConcurrentDictionary<Type, Lazy<object>> _values = new ConcurrentDictionary<Type, Lazy<object>>(); public TService GetOrAdd<TService>(Func<TService> createService) { return (TService)_values.GetOrAdd(typeof(TService), _ => { return new Lazy<object>(() => createService()); }).Value; } } } }
25.162162
119
0.677766
[ "Apache-2.0" ]
smohekey/Kissinjer
src/Kissinjer/Scopes/SingletonScopeProvider.cs
933
C#
namespace Checkout.Payments { /// <summary> /// 3D-Secure Enrollment Data. /// </summary> public class ThreeDSEnrollment { /// <summary> /// Gets a value that indicates whether this was a 3D-Secure payment downgraded to Non-3D-Secure (when <see cref="PaymentRequest.AttemptN3D"/> is specified). /// </summary> public bool Downgraded { get; set; } /// <summary> /// Gets the 3D-Secure enrollment status of the issuer: /// Y - Issuer enrolled /// N - Customer not enrolled /// U - Unknown /// </summary> public string Enrolled { get; set; } /// <summary> /// Gets a value that indicates the validity of the signature. /// </summary> public string SignatureValid { get; set; } /// <summary> /// Gets a value that indicates whether or not the cardholder was authenticated: /// Y - Customer authenticated /// N - Customer not authenticated /// A - An authentication attempt occurred but could not be completed /// U - Unable to perform authentication /// </summary> public string AuthenticationResponse { get; set; } /// <summary> /// Gets the cryptographic identifier used by the card schemes to validate the integrity of the 3D secure payment data. /// </summary> public string Cryptogram { get; set; } /// <summary> /// Gets the unique identifier for the transaction assigned by the MPI. /// </summary> public string Xid { get; set; } } }
36.533333
165
0.576642
[ "MIT" ]
bymyslf/checkout-sdk-net
src/CheckoutSdk/Payments/ThreeDsEnrollment.cs
1,644
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.ComponentModel; using Moq; using WinForms.Common.Tests; using Xunit; namespace System.Windows.Forms.Tests { public class TimerTests : IClassFixture<ThreadExceptionFixture> { [WinFormsFact] public void Timer_Ctor_Default() { using var timer = new SubTimer(); Assert.Null(timer.Container); Assert.False(timer.DesignMode); Assert.False(timer.Enabled); Assert.Equal(100, timer.Interval); Assert.Null(timer.Site); Assert.Null(timer.Tag); } [WinFormsFact] public void Timer_Ctor_IContainer() { using var container = new Container(); using var timer = new SubTimer(container); Assert.Same(container, timer.Container); Assert.False(timer.DesignMode); Assert.False(timer.Enabled); Assert.Equal(100, timer.Interval); Assert.NotNull(timer.Site); Assert.Null(timer.Tag); } [WinFormsFact] public void Timer_Ctor_NullContainer_ThrowsArgumentNullException() { Assert.Throws<ArgumentNullException>("container", () => new Timer(null)); } [WinFormsTheory] [CommonMemberData(nameof(CommonTestHelper.GetBoolTheoryData))] public void Timer_Enabled_Set_GetReturnsExpected(bool value) { using var timer = new Timer { Enabled = value }; Assert.Equal(value, timer.Enabled); // Set same. timer.Enabled = value; Assert.Equal(value, timer.Enabled); } [WinFormsTheory] [CommonMemberData(nameof(CommonTestHelper.GetBoolTheoryData))] public void Timer_Enabled_SetDesignMode_GetReturnsExpected(bool value) { using var timer = new SubTimer(); var mockSite = new Mock<ISite>(MockBehavior.Strict); mockSite .Setup(s => s.DesignMode) .Returns(true); timer.Site = mockSite.Object; Assert.True(timer.DesignMode); timer.Enabled = value; Assert.Equal(value, timer.Enabled); // Set same. timer.Enabled = value; Assert.Equal(value, timer.Enabled); // NB: disposing the component with strictly mocked object causes tests to fail // Moq.MockException : ISite.Container invocation failed with mock behavior Strict. All invocations on the mock must have a corresponding setup. timer.Site = null; } [WinFormsTheory] [CommonMemberData(nameof(CommonTestHelper.GetBoolTheoryData))] public void Timer_Enabled_SetDesignModeAfterEnabling_GetReturnsExpected(bool value) { using var timer = new SubTimer(); var mockSite = new Mock<ISite>(MockBehavior.Strict); mockSite .Setup(s => s.DesignMode) .Returns(true); timer.Site = mockSite.Object; Assert.True(timer.DesignMode); timer.Start(); mockSite .Setup(s => s.DesignMode) .Returns(false); timer.Enabled = value; Assert.Equal(value, timer.Enabled); // Set same. timer.Enabled = value; Assert.Equal(value, timer.Enabled); // NB: disposing the component with strictly mocked object causes tests to fail // Moq.MockException : ISite.Container invocation failed with mock behavior Strict. All invocations on the mock must have a corresponding setup. timer.Site = null; } [WinFormsTheory] [InlineData(1)] [InlineData(100)] public void Timer_Interval_Set_GetReturnsExpected(int value) { using var timer = new Timer { Interval = value }; Assert.Equal(value, timer.Interval); // Set same. timer.Interval = value; Assert.Equal(value, timer.Interval); } [WinFormsTheory] [InlineData(1)] [InlineData(100)] public void Timer_Interval_SetStarted_GetReturnsExpected(int value) { using var timer = new Timer(); timer.Start(); timer.Interval = value; Assert.Equal(value, timer.Interval); // Set same. timer.Interval = value; Assert.Equal(value, timer.Interval); } [WinFormsTheory] [InlineData(1)] [InlineData(100)] public void Timer_Interval_SetStopped_GetReturnsExpected(int value) { using var timer = new Timer(); timer.Start(); timer.Stop(); timer.Interval = value; Assert.Equal(value, timer.Interval); // Set same. timer.Interval = value; Assert.Equal(value, timer.Interval); } [WinFormsTheory] [InlineData(1)] [InlineData(100)] public void Timer_Interval_SetDesignMode_GetReturnsExpected(int value) { using var timer = new SubTimer(); var mockSite = new Mock<ISite>(MockBehavior.Strict); mockSite .Setup(s => s.DesignMode) .Returns(true); timer.Site = mockSite.Object; Assert.True(timer.DesignMode); timer.Interval = value; Assert.Equal(value, timer.Interval); // Set same. timer.Interval = value; Assert.Equal(value, timer.Interval); // NB: disposing the component with strictly mocked object causes tests to fail // Moq.MockException : ISite.Container invocation failed with mock behavior Strict. All invocations on the mock must have a corresponding setup. timer.Site = null; } [WinFormsTheory] [InlineData(1)] [InlineData(100)] public void Timer_Interval_SetDesignModeAfterEnabling_GetReturnsExpected(int value) { using var timer = new SubTimer(); var mockSite = new Mock<ISite>(MockBehavior.Strict); mockSite .Setup(s => s.DesignMode) .Returns(true); timer.Site = mockSite.Object; Assert.True(timer.DesignMode); timer.Start(); mockSite .Setup(s => s.DesignMode) .Returns(false); timer.Interval = value; Assert.Equal(value, timer.Interval); // Set same. timer.Interval = value; Assert.Equal(value, timer.Interval); // NB: disposing the component with strictly mocked object causes tests to fail // Moq.MockException : ISite.Container invocation failed with mock behavior Strict. All invocations on the mock must have a corresponding setup. timer.Site = null; } [WinFormsTheory] [InlineData(0)] [InlineData(-1)] public void Timer_Interval_SetInvalid_ThrowsArgumentOutOfRangeException(int value) { using var timer = new Timer(); Assert.Throws<ArgumentOutOfRangeException>("value", () => timer.Interval = value); } [WinFormsTheory] [CommonMemberData(nameof(CommonTestHelper.GetStringWithNullTheoryData))] public void Timer_Tag_Set_GetReturnsExpected(object value) { using var timer = new Timer { Tag = value }; Assert.Same(value, timer.Tag); // Set same. timer.Tag = value; Assert.Same(value, timer.Tag); } [WinFormsTheory] [CommonMemberData(nameof(CommonTestHelper.GetStringWithNullTheoryData))] public void Timer_Tag_SetDesignMode_GetReturnsExpected(object value) { using var timer = new SubTimer(); var mockSite = new Mock<ISite>(MockBehavior.Strict); mockSite .Setup(s => s.DesignMode) .Returns(true); timer.Site = mockSite.Object; Assert.True(timer.DesignMode); timer.Tag = value; Assert.Same(value, timer.Tag); // Set same. timer.Tag = value; Assert.Same(value, timer.Tag); // NB: disposing the component with strictly mocked object causes tests to fail // Moq.MockException : ISite.Container invocation failed with mock behavior Strict. All invocations on the mock must have a corresponding setup. timer.Site = null; } [WinFormsTheory] [CommonMemberData(nameof(CommonTestHelper.GetBoolTheoryData))] public void Timer_Start_Stop_Success(bool designMode) { using var timer = new SubTimer(); var mockSite = new Mock<ISite>(MockBehavior.Strict); mockSite .Setup(s => s.DesignMode) .Returns(designMode); timer.Site = mockSite.Object; Assert.Equal(designMode, timer.DesignMode); // Start timer.Start(); Assert.True(timer.Enabled); // Stop. timer.Stop(); Assert.False(timer.Enabled); // NB: disposing the component with strictly mocked object causes tests to fail // Moq.MockException : ISite.Container invocation failed with mock behavior Strict. All invocations on the mock must have a corresponding setup. timer.Site = null; } [WinFormsTheory] [CommonMemberData(nameof(CommonTestHelper.GetBoolTheoryData))] public void Timer_Start_MultipleTimes_Success(bool designMode) { using var timer = new SubTimer(); var mockSite = new Mock<ISite>(MockBehavior.Strict); mockSite .Setup(s => s.DesignMode) .Returns(designMode); timer.Site = mockSite.Object; Assert.Equal(designMode, timer.DesignMode); // Start timer.Start(); Assert.True(timer.Enabled); // Start again. timer.Start(); Assert.True(timer.Enabled); // NB: disposing the component with strictly mocked object causes tests to fail // Moq.MockException : ISite.Container invocation failed with mock behavior Strict. All invocations on the mock must have a corresponding setup. timer.Site = null; } [WinFormsTheory] [CommonMemberData(nameof(CommonTestHelper.GetBoolTheoryData))] public void Timer_Stop_Restart_Success(bool designMode) { using var timer = new SubTimer(); var mockSite = new Mock<ISite>(MockBehavior.Strict); mockSite .Setup(s => s.DesignMode) .Returns(designMode); timer.Site = mockSite.Object; Assert.Equal(designMode, timer.DesignMode); // Start timer.Start(); Assert.True(timer.Enabled); // Stop. timer.Stop(); Assert.False(timer.Enabled); // Start again. timer.Start(); Assert.True(timer.Enabled); // Stop again. timer.Stop(); Assert.False(timer.Enabled); // NB: disposing the component with strictly mocked object causes tests to fail // Moq.MockException : ISite.Container invocation failed with mock behavior Strict. All invocations on the mock must have a corresponding setup. timer.Site = null; } [WinFormsTheory] [CommonMemberData(nameof(CommonTestHelper.GetBoolTheoryData))] public void Timer_Stop_MultipleTimes_Success(bool designMode) { using var timer = new SubTimer(); var mockSite = new Mock<ISite>(MockBehavior.Strict); mockSite .Setup(s => s.DesignMode) .Returns(designMode); timer.Site = mockSite.Object; Assert.Equal(designMode, timer.DesignMode); // Start timer.Start(); Assert.True(timer.Enabled); // Stop. timer.Stop(); Assert.False(timer.Enabled); // Stop again. timer.Stop(); Assert.False(timer.Enabled); // NB: disposing the component with strictly mocked object causes tests to fail // Moq.MockException : ISite.Container invocation failed with mock behavior Strict. All invocations on the mock must have a corresponding setup. timer.Site = null; } [WinFormsFact] public void Timer_OnTick_Invoke_CallsTick() { using var timer = new SubTimer(); var eventArgs = new EventArgs(); int callCount = 0; EventHandler handler = (sender, e) => { Assert.Same(timer, sender); Assert.Same(eventArgs, e); callCount++; }; // Call with handler. timer.Tick += handler; timer.OnTick(eventArgs); Assert.Equal(1, callCount); // Remove handler. timer.Tick -= handler; timer.OnTick(eventArgs); Assert.Equal(1, callCount); } [WinFormsFact] public void Timer_Dispose_NotStarted_Success() { using var timer = new Timer(); timer.Dispose(); Assert.False(timer.Enabled); // Call again. timer.Dispose(); Assert.False(timer.Enabled); } [WinFormsFact] public void Timer_Dispose_Started_Success() { using var timer = new Timer(); timer.Start(); timer.Dispose(); Assert.False(timer.Enabled); // Call again. timer.Dispose(); Assert.False(timer.Enabled); } [WinFormsFact] public void Timer_Dispose_Stopped_Success() { using var timer = new Timer(); timer.Start(); timer.Stop(); timer.Dispose(); Assert.False(timer.Enabled); // Call again. timer.Dispose(); Assert.False(timer.Enabled); } [WinFormsFact] public void Timer_ToString_Invoke_ReturnsExpected() { using var timer = new Timer(); Assert.Equal("System.Windows.Forms.Timer, Interval: 100", timer.ToString()); } private class SubTimer : Timer { public SubTimer() : base() { } public SubTimer(IContainer container) : base(container) { } public new bool DesignMode => base.DesignMode; public new void OnTick(EventArgs e) => base.OnTick(e); } } }
33.014989
156
0.560384
[ "MIT" ]
al757/winforms-001
src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/TimerTests.cs
15,420
C#
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Framework.Graphics.Shapes; using osu.Framework.Graphics.Sprites; using osu.Game.Graphics.Sprites; using osuTK; using osuTK.Graphics; using System.Collections.Generic; namespace osu.Game.Graphics.UserInterface { public class ShowMoreButton : LoadingButton { private const int duration = 200; private Color4 chevronIconColour; protected Color4 ChevronIconColour { get => chevronIconColour; set => chevronIconColour = leftChevron.Colour = rightChevron.Colour = value; } public string Text { get => text.Text; set => text.Text = value; } protected override IEnumerable<Drawable> EffectTargets => new[] { background }; private ChevronIcon leftChevron; private ChevronIcon rightChevron; private SpriteText text; private Box background; private FillFlowContainer textContainer; public ShowMoreButton() { AutoSizeAxes = Axes.Both; } protected override Drawable CreateContent() => new CircularContainer { Masking = true, Size = new Vector2(140, 30), Children = new Drawable[] { background = new Box { RelativeSizeAxes = Axes.Both, }, textContainer = new FillFlowContainer { Anchor = Anchor.Centre, Origin = Anchor.Centre, AutoSizeAxes = Axes.Both, Direction = FillDirection.Horizontal, Spacing = new Vector2(7), Children = new Drawable[] { leftChevron = new ChevronIcon(), text = new OsuSpriteText { Anchor = Anchor.Centre, Origin = Anchor.Centre, Font = OsuFont.GetFont(size: 12, weight: FontWeight.Bold), Text = "show more".ToUpper(), }, rightChevron = new ChevronIcon(), } } } }; protected override void OnLoadStarted() => textContainer.FadeOut(duration, Easing.OutQuint); protected override void OnLoadFinished() => textContainer.FadeIn(duration, Easing.OutQuint); private class ChevronIcon : SpriteIcon { private const int icon_size = 8; public ChevronIcon() { Anchor = Anchor.Centre; Origin = Anchor.Centre; Size = new Vector2(icon_size); Icon = FontAwesome.Solid.ChevronDown; } } } }
32.721649
101
0.515123
[ "MIT" ]
Altenhh/osu
osu.Game/Graphics/UserInterface/ShowMoreButton.cs
3,080
C#
using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; namespace Coravel.Mailer.ViewComponents { public class EmailLinkButton : ViewComponent { public async Task<IViewComponentResult> InvokeAsync( string text, string url, string backgroundColor = null, string textColor = null ) { ViewBag.Text = text; ViewBag.url = url; ViewBag.BackgroundColor = backgroundColor ?? "#539be2"; ViewBag.TextColor = textColor ?? "#ffffff"; var view = View(); return await Task.FromResult(view); } } }
30.85
91
0.612642
[ "MIT" ]
Blinke/coravel
Src/Coravel.Mailer/ViewComponents/EmailLinkButton.cs
617
C#
using System; namespace Triangulo { class Program { static void Main(string[] args) { string linha = Console.ReadLine(); string[] lados = linha.Split(' '); double a = Convert.ToDouble(lados[0]); double b = Convert.ToDouble(lados[1]); double c = Convert.ToDouble(lados[2]); double perimetro, area; if ((a + b > c) && (a + c > b) && (c + b > a)) { perimetro = a + b + c; Console.WriteLine("Perimetro = {0}", perimetro.ToString("0.0")); } else { area = ((a + b) / 2) * c; Console.WriteLine("Area = {0}", area.ToString("0.0")); } } } }
25.16129
80
0.423077
[ "MIT" ]
douglas-ssouza/URI
Exercicios/iniciante/1043_Triangulo.cs
780
C#
using System; using System.Collections.Generic; using FluentAssertions; using NUnit.Framework; namespace Ruzzie.Mtg.Core.UnitTests { [TestFixture] public class EnumFlagHelperTests { [Test] [TestCase(0)] [TestCase(1)] [TestCase(2)] [TestCase(4)] [TestCase(8)] [TestCase(16)] [TestCase(6)] [TestCase(10)] [TestCase(12)] [TestCase(13)] [TestCase(18)] [TestCase(20)] [TestCase(21)] [TestCase(24)] [TestCase(25)] [TestCase(26)] [TestCase(28)] public void ListOfAllPossibleUniqueFlagsCombinationsFlagsTest(int colorCode) { var listAllPossibleUniqueFlagsCombinations = EnumFlagHelpers<Color>.ListAllPossibleUniqueFlagsCombinations(); Assert.That(listAllPossibleUniqueFlagsCombinations, Contains.Item((Color) colorCode)); } [Test] public void ListOfAllPossibleUniqueFlagsCombinationsTest() { Assert.That(EnumFlagHelpers<Color>.ListAllPossibleUniqueFlagsCombinations().Count, Is.EqualTo(32)); } [Test] public void ListOfAllPossibleUniqueForBasicTypesTest() { var listAllPossibleUniqueFlagsCombinations = EnumFlagHelpers<BasicType>.ListAllPossibleUniqueFlagsCombinations(); Assert.That(listAllPossibleUniqueFlagsCombinations.Count, Is.EqualTo(168)); } [Test] public void ListOfAllPossibleUniqueForShortEnum() { Assert.That(EnumFlagHelpers<ShortFlagTypeEnum>.ListAllPossibleUniqueFlagsCombinations().Count, Is.EqualTo(4)); } [Test] public void ListOfAllPossibleUniqueForUintEnum() { Assert.That(EnumFlagHelpers<UintFlagTypeEnum>.ListAllPossibleUniqueFlagsCombinations().Count, Is.EqualTo(4)); } [Test] public void ListOfAllPossibleUniqueForLongEnum() { IReadOnlyCollection<LongFlagTypeEnum> combinations = EnumFlagHelpers<LongFlagTypeEnum>.ListAllPossibleUniqueFlagsCombinations(); Assert.That(combinations.Count, Is.EqualTo(4)); Assert.That(combinations, Contains.Item(LongFlagTypeEnum.A) .And.Contains(LongFlagTypeEnum.B) .And.Contains(LongFlagTypeEnum.C) .And.Contains(LongFlagTypeEnum.B | LongFlagTypeEnum.C) ); } ///Unneeded test now , Enum can now be used as a type constraint /// /[Test] //public void NonEnumTypeThrowsException() //{ // Assert.That(EnumFlagHelpers<int>.ListAllPossibleUniqueFlagsCombinations, Throws.ArgumentException); //} [Test] public void NonEnumFlagTypeThrowsException() { Assert.That(EnumFlagHelpers<NonFlagTypeEnum>.ListAllPossibleUniqueFlagsCombinations, Throws.ArgumentException); } [Test] public void GetValueWithAllFlagsSet() { var value = EnumFlagHelpers<ShortFlagTypeEnum>.GetValueWithAllFlagsSet(); value.Should().Be(ShortFlagTypeEnum.A | ShortFlagTypeEnum.B | ShortFlagTypeEnum.C); } // ReSharper disable UnusedMember.Local enum NonFlagTypeEnum { None, A, B } [Flags] enum ShortFlagTypeEnum : short { A = 0, B = 1, C = 2 } [Flags] enum UintFlagTypeEnum : uint { A = 0, B = 1, C = 2 } [Flags] enum LongFlagTypeEnum : long { A = 0, B = 1, C = 2 } // ReSharper restore UnusedMember.Local } }
30.362205
140
0.584544
[ "Apache-2.0" ]
Ruzzie/Ruzzie.Mtg.Core
src/RuzzieMtgCore/Ruzzie.Mtg.Core.UnitTests/EnumFlagHelperTests.cs
3,856
C#
using System.Runtime.CompilerServices; using System.Windows; [assembly: InternalsVisibleTo("Chatterbox.Client.Tests")] [assembly: ThemeInfo( ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located //(used if a resource is not found in the page, // or application resource dictionaries) ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located //(used if a resource is not found in the page, // app, or any theme specific resource dictionaries) )]
53.230769
98
0.604046
[ "MIT" ]
doklem/chatterbox
Chatterbox.Client/AssemblyInfo.cs
692
C#
using System; using System.Collections.Generic; using System.ComponentModel; using System.ComponentModel.DataAnnotations; using System.Linq; using Blockcore.Features.Wallet.Validations; using Blockcore.Utilities.ValidationAttributes; using Microsoft.AspNetCore.Mvc; using Newtonsoft.Json; using Newtonsoft.Json.Converters; namespace Blockcore.Features.Wallet.Api.Models { /// <summary> /// A class containing the necessary parameters for a wallet resynchronization request /// which takes the hash of the block to resync after. /// </summary> public class HashModel { /// <summary> /// The hash of the block to resync after. /// </summary> [Required(AllowEmptyStrings = false)] public string Hash { get; set; } } public class RequestModel { public override string ToString() { return JsonConvert.SerializeObject(this, Formatting.Indented); } } /// <summary> /// A class containing the necessary parameters for a create wallet request. /// </summary> public class WalletCreationRequest : RequestModel { /// <summary> /// The mnemonic used to create the HD wallet. /// </summary> public string Mnemonic { get; set; } /// <summary> /// A password used to encrypt the wallet for secure storage. /// </summary> [Required(ErrorMessage = "A password is required.")] public string Password { get; set; } /// <summary> /// An optional additional seed, which is joined together with the <see cref="Mnemonic"/> /// when the wallet is created. /// Although you will be prompted to enter a passphrase, an empty string is still valid. /// </summary> /// <remarks> /// The passphrase can be an empty string. /// </remarks> [Required(ErrorMessage = "A passphrase is required.", AllowEmptyStrings = true)] public string Passphrase { get; set; } /// <summary> /// The name of the wallet. /// </summary> [Required(ErrorMessage = "The name of the wallet to create is missing.")] public string Name { get; set; } } /// <summary> /// A class containing the necessary parameters for a load wallet request. /// </summary> public class WalletLoadRequest : RequestModel { /// <summary> /// The password that was used to create the wallet. /// </summary> [Required(ErrorMessage = "A password is required.")] public string Password { get; set; } /// <summary> /// The name of the wallet. /// </summary> [Required(ErrorMessage = "The name of the wallet is missing.")] public string Name { get; set; } } /// <summary> /// A class containing the necessary parameters for a wallet recovery request. /// </summary> public class WalletRecoveryRequest : RequestModel { /// <summary> /// The mnemonic that was used to create the wallet. /// </summary> [Required(ErrorMessage = "A mnemonic is required.")] public string Mnemonic { get; set; } /// <summary> /// The password that was used to create the wallet. /// </summary> [Required(ErrorMessage = "A password is required.")] public string Password { get; set; } /// <summary> /// The passphrase that was used to create the wallet. /// </summary> /// <remarks> /// If the wallet was created before <see cref="Passphrase"/> was available as a parameter, set the passphrase to be the same as the password. /// </remarks> [Required(ErrorMessage = "A passphrase is required.", AllowEmptyStrings = true)] public string Passphrase { get; set; } /// <summary> /// The name of the wallet. /// </summary> [Required(ErrorMessage = "The name of the wallet is missing.")] public string Name { get; set; } [JsonConverter(typeof(IsoDateTimeConverter))] public DateTime CreationDate { get; set; } /// <summary> /// Optional CoinType to overwrite the default <see cref="Blockcore.Consensus.IConsensus.CoinType"/>. /// </summary> public int? CoinType { get; set; } } /// <summary> /// A class containing the necessary parameters for a wallet recovery request using its extended public key. /// Note that the recovered wallet will not have a private key and is /// only suitable for returning the wallet history using further API calls. As such, /// only the extended public key is used in the recovery process. /// </summary> public class WalletExtPubRecoveryRequest : RequestModel { /// <summary> /// The extended public key used by the wallet. /// </summary> [Required(ErrorMessage = "An extended public key is required.")] public string ExtPubKey { get; set; } /// <summary> /// The index of the account to generate for the wallet. For example, specifying a value of 0 /// generates "account0". /// </summary> [Required(ErrorMessage = "An account number is required. E.g. 0.")] public int AccountIndex { get; set; } /// <summary> /// The name to give the recovered wallet. /// </summary> [Required(ErrorMessage = "The name of the wallet is missing.")] public string Name { get; set; } /// <summary> /// The creation date and time to give the recovered wallet. /// </summary> [JsonConverter(typeof(IsoDateTimeConverter))] public DateTime CreationDate { get; set; } } /// <summary> /// A class containing the necessary parameters for a wallet history request. /// </summary> public class WalletHistoryRequest : RequestModel { public WalletHistoryRequest() { this.AccountName = WalletManager.DefaultAccount; } /// <summary> /// The name of the wallet to recover the history for. /// </summary> [Required(ErrorMessage = "The name of the wallet is missing.")] public string WalletName { get; set; } /// <summary> /// Optional. The name of the account to recover the history for. If no account name is specified, /// the entire history of the wallet is recovered. /// </summary> public string AccountName { get; set; } /// <summary> /// Optional. If set, will filter the transaction history for all transactions made to or from the given address. /// </summary> [IsBitcoinAddress(Required = false)] public string Address { get; set; } /// <summary> /// An optional value allowing (with Take) pagination of the wallet's history. If given, /// the member specifies the numbers of records in the wallet's history to skip before /// beginning record retrieval; otherwise the wallet history records are retrieved starting from 0. /// </summary> public int? Skip { get; set; } /// <summary> /// An optional value allowing (with Skip) pagination of the wallet's history. If given, /// the member specifies the number of records in the wallet's history to retrieve in this call; otherwise all /// wallet history records are retrieved. /// </summary> public int? Take { get; set; } /// <summary> /// An optional string that can be used to match different data in the transaction records. /// It is possible to match on the following: the transaction ID, the address at which funds where received, /// and the address to which funds where sent. /// </summary> [JsonProperty(PropertyName = "q")] public string SearchQuery { get; set; } } /// <summary> /// A class containing the necessary parameters for a wallet balance request. /// </summary> public class WalletBalanceRequest : RequestModel { public WalletBalanceRequest() { this.AccountName = WalletManager.DefaultAccount; } /// <summary> /// The name of the wallet to retrieve the balance for. /// </summary> [Required(ErrorMessage = "The name of the wallet is missing.")] public string WalletName { get; set; } /// <summary> /// The name of the account to retrieve the balance for. If no account name is supplied, /// then the balance for the entire wallet (all accounts) is retrieved. /// </summary> public string AccountName { get; set; } } /// <summary> /// A class containing the necessary parameters for a request to get the maximum /// spendable amount for a specific wallet account. /// </summary> /// <seealso cref="RequestModel" /> public class WalletMaximumBalanceRequest : RequestModel { public WalletMaximumBalanceRequest() { this.AccountName = WalletManager.DefaultAccount; } /// <summary> /// The name of the wallet to retrieve the maximum spendable amount for. /// </summary> [Required(ErrorMessage = "The name of the wallet is missing.")] public string WalletName { get; set; } /// <summary> /// The name of the account to retrieve the maximum spendable amount for. /// </summary> public string AccountName { get; set; } /// <summary> /// The type of fee to use when working out the fee required to spend the amount. /// Specify "low", "medium", or "high". /// </summary> [Required(ErrorMessage = "A fee type is required. It can be 'low', 'medium' or 'high'.")] public string FeeType { get; set; } /// <summary> /// A flag that specifies whether to include the unconfirmed amounts held at account addresses /// as spendable. /// </summary> public bool AllowUnconfirmed { get; set; } } /// <summary> /// Model object to use as input to the Api request for getting the balance for an address. /// </summary> /// <seealso cref="RequestModel" /> public class ReceivedByAddressRequest : RequestModel { [Required(ErrorMessage = "An address is required.")] public string Address { get; set; } } public class WalletName : RequestModel { [Required(ErrorMessage = "The name of the wallet is missing.")] public string Name { get; set; } } public class ToggleColdRequest : RequestModel { [Required(ErrorMessage = "The name of the wallet is missing.")] public string Name { get; set; } public bool isColdHotWallet { get; set; } } /// <summary> /// A class containing the necessary parameters for a transaction fee estimate request. /// </summary> /// <seealso cref="RequestModel" /> public class TxFeeEstimateRequest : RequestModel { public TxFeeEstimateRequest() { this.AccountName = WalletManager.DefaultAccount; } /// <summary> /// The name of the wallet containing the UTXOs to use in the transaction. /// </summary> [Required(ErrorMessage = "The name of the wallet is missing.")] public string WalletName { get; set; } /// <summary> /// The name of the account containing the UTXOs to use in the transaction. /// </summary> public string AccountName { get; set; } /// <summary> /// A list of outpoints to use as inputs for the transaction. /// </summary> public List<OutpointRequest> Outpoints { get; set; } /// <summary> /// A list of transaction recipients. For each recipient, specify the Pubkey script and the amount the /// recipient will receive in STRAT (or a sidechain coin). If the transaction was realized, /// both the values would be used to create the UTXOs for the transaction recipients. /// </summary> public List<RecipientModel> Recipients { get; set; } /// <summary> /// A string containing any OP_RETURN output data to store as part of the transaction. /// </summary> public string OpReturnData { get; set; } /// <summary> /// The funds in STRAT (or a sidechain coin) to include with the OP_RETURN output. Currently, specifying /// some funds helps OP_RETURN outputs be relayed around the network. /// </summary> [MoneyFormat(isRequired: false, ErrorMessage = "The op return amount is not in the correct format.")] public string OpReturnAmount { get; set; } /// <summary> /// The type of fee to use when working out the fee for the transaction. Specify "low", "medium", or "high". /// </summary> public string FeeType { get; set; } /// <summary> /// A flag that specifies whether to include the unconfirmed amounts as inputs to the transaction. /// If this flag is not set, at least one confirmation is required for each input. /// </summary> public bool AllowUnconfirmed { get; set; } /// <summary> /// A flag that specifies whether to shuffle the transaction outputs for increased privacy. Randomizing the /// the order in which the outputs appear when the transaction is being built stops it being trivial to /// determine whether a transaction output is payment or change. This helps defeat unsophisticated /// chain analysis algorithms. /// Defaults to true. /// </summary> public bool? ShuffleOutputs { get; set; } /// <summary> /// The address to which the change from the transaction should be returned. If this is not set, /// the default behaviour from the <see cref="WalletTransactionHandler"/> will be used to determine the change address. /// </summary> [IsBitcoinAddress(Required = false)] public string ChangeAddress { get; set; } } public class OutpointRequest : RequestModel { /// <summary> /// The transaction ID. /// </summary> [Required(ErrorMessage = "The transaction id is missing.")] public string TransactionId { get; set; } /// <summary> /// The index of the output in the transaction. /// </summary> [Required(ErrorMessage = "The index of the output in the transaction is missing.")] public int Index { get; set; } } public class RecipientModel { /// <summary> /// The destination address. /// </summary> [Required(ErrorMessage = "A destination address is required.")] [IsBitcoinAddress()] public string DestinationAddress { get; set; } /// <summary> /// The amount that will be sent. /// </summary> [Required(ErrorMessage = "An amount is required.")] [MoneyFormat(ErrorMessage = "The amount is not in the correct format.")] public string Amount { get; set; } } /// <summary> /// A class containing the necessary parameters for a build transaction request. /// </summary> public class BuildTransactionRequest : TxFeeEstimateRequest, IValidatableObject { /// <summary> /// The fee for the transaction in STRAT (or a sidechain coin). /// </summary> [MoneyFormat(isRequired: false, ErrorMessage = "The fee is not in the correct format.")] public string FeeAmount { get; set; } /// <summary> /// The password for the wallet containing the funds for the transaction. /// </summary> [Required(ErrorMessage = "A password is required.")] public string Password { get; set; } /// <summary> /// Whether to send the change to a P2WPKH (segwit bech32) addresses, or a regular P2PKH address /// </summary> public bool SegwitChangeAddress { get; set; } /// <inheritdoc /> public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) { if (!string.IsNullOrEmpty(this.FeeAmount) && !string.IsNullOrEmpty(this.FeeType)) { yield return new ValidationResult( $"The query parameters '{nameof(this.FeeAmount)}' and '{nameof(this.FeeType)}' cannot be set at the same time. " + $"Please use '{nameof(this.FeeAmount)}' if you'd like to set the fee manually, or '{nameof(this.FeeType)}' if you want the wallet to calculate it for you.", new[] { $"{nameof(this.FeeType)}" }); } if (string.IsNullOrEmpty(this.FeeAmount) && string.IsNullOrEmpty(this.FeeType)) { yield return new ValidationResult( $"One of parameters '{nameof(this.FeeAmount)}' and '{nameof(this.FeeType)}' is required. " + $"Please use '{nameof(this.FeeAmount)}' if you'd like to set the fee manually, or '{nameof(this.FeeType)}' if you want the wallet to calculate it for you.", new[] { $"{nameof(this.FeeType)}" }); } } } /// <summary> /// A class containing the necessary parameters for a send transaction request. /// </summary> public class SendTransactionRequest : RequestModel { public SendTransactionRequest() { } public SendTransactionRequest(string transactionHex) { this.Hex = transactionHex; } /// <summary> /// A string containing the transaction in hexadecimal format. /// </summary> [Required(ErrorMessage = "A transaction in hexadecimal format is required.")] /// <summary> /// The transaction as a hexadecimal string. /// </summary> public string Hex { get; set; } } /// <summary> /// A class containing the necessary parameters for a remove transactions request. /// </summary> /// <seealso cref="RequestModel" /> public class RemoveTransactionsModel : RequestModel, IValidatableObject { /// <summary> /// The name of the wallet to remove the transactions from. /// </summary> [Required(ErrorMessage = "The name of the wallet is required.")] public string WalletName { get; set; } /// <summary> /// The IDs of the transactions to remove. /// </summary> [FromQuery(Name = "ids")] public IEnumerable<string> TransactionsIds { get; set; } /// <summary> /// A date and time after which all transactions should be removed. /// </summary> [JsonConverter(typeof(IsoDateTimeConverter))] [FromQuery(Name = "fromDate")] public DateTime FromDate { get; set; } /// <summary> /// A flag that specifies whether to delete all transactions from a wallet. /// </summary> [FromQuery(Name = "all")] public bool DeleteAll { get; set; } /// <summary> /// A flag that specifies whether to resync the wallet after removing the transactions. /// </summary> [JsonProperty(PropertyName = "reSync")] public bool ReSync { get; set; } /// <inheritdoc /> public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) { // Check that one of the filters is set. if (!this.DeleteAll && (this.TransactionsIds == null || !this.TransactionsIds.Any()) && this.FromDate == default(DateTime)) { yield return new ValidationResult( $"One of the query parameters '{nameof(this.DeleteAll)}', '{nameof(this.TransactionsIds)}' or '{nameof(this.FromDate)}' must be set.", new[] { $"{nameof(this.DeleteAll)}" }); } // Check that only one of the filters is set. if ((this.DeleteAll && this.TransactionsIds != null) || (this.DeleteAll && this.FromDate != default(DateTime)) || (this.TransactionsIds != null && this.FromDate != default(DateTime))) { yield return new ValidationResult( $"Only one out of the query parameters '{nameof(this.DeleteAll)}', '{nameof(this.TransactionsIds)}' or '{nameof(this.FromDate)}' can be set.", new[] { $"{nameof(this.DeleteAll)}" }); } // Check that transaction ids doesn't contain empty elements. if (this.TransactionsIds != null && this.TransactionsIds.Any(trx => trx == null)) { yield return new ValidationResult( $"'{nameof(this.TransactionsIds)}' must not contain any null ids.", new[] { $"{nameof(this.TransactionsIds)}" }); } } } /// <summary> /// A class containing the necessary parameters for a list accounts request. /// </summary> public class ListAccountsModel : RequestModel { /// <summary> /// The name of the wallet for which to list the accounts. /// </summary> [Required(ErrorMessage = "The name of the wallet is required.")] public string WalletName { get; set; } } /// <summary> /// A class containing the necessary parameters for an unused address request. /// </summary> public class GetUnusedAddressModel : RequestModel { public GetUnusedAddressModel() { this.AccountName = WalletManager.DefaultAccount; } /// <summary> /// The name of the wallet from which to get the address. /// </summary> [Required] public string WalletName { get; set; } /// <summary> /// The name of the account for which to get the address. /// </summary> public string AccountName { get; set; } /// <summary> /// Whether to return the P2WPKH (segwit bech32) addresses, or a regular P2PKH address /// </summary> public bool Segwit { get; set; } } /// <summary> /// A class containing the necessary parameters for an unused addresses request. /// </summary> public class GetUnusedAddressesModel : RequestModel { public GetUnusedAddressesModel() { this.AccountName = WalletManager.DefaultAccount; } /// <summary> /// The name of the wallet from which to get the addresses. /// </summary> [Required] public string WalletName { get; set; } /// <summary> /// The name of the account for which to get the addresses. /// </summary> public string AccountName { get; set; } /// <summary> /// The number of addresses to retrieve. /// </summary> [Required] public string Count { get; set; } /// <summary> /// Whether to return the P2WPKH (segwit bech32) addresses, or a regular P2PKH address /// </summary> public bool Segwit { get; set; } } /// <summary> /// A class containing the necessary parameters for a retrieve all addresses request. /// </summary> public class GetAllAddressesModel : RequestModel { public GetAllAddressesModel() { this.AccountName = WalletManager.DefaultAccount; } /// <summary> /// The name of the wallet from which to get the addresses. /// </summary> [Required] public string WalletName { get; set; } /// <summary> /// The name of the account for which to get the addresses. /// </summary> public string AccountName { get; set; } /// <summary> /// Whether to return the P2WPKH (segwit bech32) addresses, or a regular P2PKH address /// </summary> public bool Segwit { get; set; } } /// <summary> /// A class containing the necessary parameters for an extended public key request. /// </summary> public class GetExtPubKeyModel : RequestModel { public GetExtPubKeyModel() { this.AccountName = WalletManager.DefaultAccount; } /// <summary> /// The name of the wallet from which to get the extended public key. /// </summary> [Required] public string WalletName { get; set; } /// <summary> /// The name of the account for which to get the extended public key. /// <summary> public string AccountName { get; set; } } /// <summary> /// A class containing the necessary parameters for a private key retrieval request. /// </summary> public class RetrievePrivateKeyModel : RequestModel { public RetrievePrivateKeyModel() { this.AccountName = WalletManager.DefaultAccount; } /// <summary> /// The password for the wallet. /// </summary> [Required] public string Password { get; set; } /// <summary> /// The name of the wallet from which to get the private key. /// </summary> [Required] public string WalletName { get; set; } /// <summary> /// The name of the account for which to get the private key. /// <summary> public string AccountName { get; set; } /// <summary> /// The address to retrieve the private key for. /// </summary> [Required] public string Address { get; set; } } /// <summary> /// A class containing the necessary parameters for a new account request. /// </summary> public class GetUnusedAccountModel : RequestModel { /// <summary> /// The name of the wallet in which to create the account. /// </summary> [Required] public string WalletName { get; set; } /// <summary> /// The password for the wallet. /// </summary> [Required] public string Password { get; set; } } /// <summary> /// A class containing the necessary parameters for a wallet resynchronization request. /// </summary> public class WalletSyncFromDateRequest : RequestModel { /// <summary> /// The date and time from which to resync the wallet. /// </summary> [JsonConverter(typeof(IsoDateTimeConverter))] public DateTime Date { get; set; } } /// <summary> /// A class containing the necessary parameters for a wallet stats request. /// </summary> public class WalletStatsRequest : RequestModel { public WalletStatsRequest() { this.AccountName = WalletManager.DefaultAccount; } /// <summary> /// The name of the wallet for which to get the stats. /// </summary> [Required] public string WalletName { get; set; } /// <summary> /// The name of the account for which to get the stats. /// <summary> public string AccountName { get; set; } /// <summary> /// The minimum number of confirmations a transaction needs to have to be included. /// To include unconfirmed transactions, set this value to 0. /// </summary> public int MinConfirmations { get; set; } /// <summary> /// Should the request return a more detailed output /// </summary> public bool Verbose { get; set; } } /// <summary> /// A class containing the necessary parameters to perform an add address book entry request. /// </summary> /// <seealso cref="RequestModel" /> public class AddressBookEntryRequest : RequestModel { /// <summary> /// A label to attach to the address book entry. /// </summary> [Required(ErrorMessage = "A label is required.")] [MaxLength(200)] public string Label { get; set; } /// <summary> /// The address to enter in the address book. /// </summary> [Required(ErrorMessage = "An address is required.")] [IsBitcoinAddress()] public string Address { get; set; } } /// <summary> /// A class containing the necessary parameters to perform a spendable transactions request. /// </summary> /// <seealso cref="RequestModel" /> public class SpendableTransactionsRequest : RequestModel { public SpendableTransactionsRequest() { this.AccountName = WalletManager.DefaultAccount; } /// <summary> /// The name of the wallet to retrieve the spendable transactions for. /// </summary> [Required(ErrorMessage = "The name of the wallet is missing.")] public string WalletName { get; set; } /// <summary> /// The name of the account to retrieve the spendable transaction for. If no account name is specified, /// the entire history of the wallet is recovered. public string AccountName { get; set; } /// <summary> /// The minimum number of confirmations a transaction needs to have to be included. /// To include unconfirmed transactions, set this value to 0. /// </summary> public int MinConfirmations { get; set; } } public class SplitCoinsRequest : RequestModel { public SplitCoinsRequest() { this.AccountName = WalletManager.DefaultAccount; } [Required(ErrorMessage = "The name of the wallet is missing.")] public string WalletName { get; set; } public string AccountName { get; set; } [Required(ErrorMessage = "A password is required.")] public string WalletPassword { get; set; } /// <summary>The amount that will be sent.</summary> [Required(ErrorMessage = "An amount is required.")] [MoneyFormat(ErrorMessage = "The amount is not in the correct format.")] public string TotalAmountToSplit { get; set; } [Required] public int UtxosCount { get; set; } } public sealed class DistributeUtxosRequest : RequestModel, IValidatableObject { public DistributeUtxosRequest() { this.AccountName = WalletManager.DefaultAccount; } [Required(ErrorMessage = "The name of the wallet is missing.")] public string WalletName { get; set; } public string AccountName { get; set; } [Required(ErrorMessage = "A password is required.")] public string WalletPassword { get; set; } [DefaultValue(false)] public bool UseUniqueAddressPerUtxo { get; set; } [DefaultValue(true)] public bool ReuseAddresses { get; set; } [DefaultValue(false)] public bool UseChangeAddresses { get; set; } [Required] public int UtxosCount { get; set; } [Required] public int UtxoPerTransaction { get; set; } [DefaultValue(0)] public int TimestampDifferenceBetweenTransactions { get; set; } /// <summary> /// The minimum number of confirmations a transaction needs to have to be included. /// To include unconfirmed transactions, set this value to 0. /// </summary> [DefaultValue(1)] public int MinConfirmations { get; set; } /// <summary> /// A list of outpoints to use as inputs for the transaction. /// </summary> public List<OutpointRequest> Outpoints { get; set; } [Required] public bool DryRun { get; set; } public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) { if (this.UtxoPerTransaction > this.UtxosCount) { yield return new ValidationResult( $"The number of UTXOs per transaction ('{nameof(this.UtxoPerTransaction)}') has to be equal or smaller than total number of UTXOs ('{nameof(this.UtxosCount)}')", new[] { $"{nameof(this.UtxoPerTransaction)}", $"{nameof(this.UtxosCount)}" }); } } } /// <summary> /// Object to sign a message. /// </summary> public class SignMessageRequest : RequestModel { [Required(ErrorMessage = "The name of the wallet is missing.")] public string WalletName { get; set; } [Required(ErrorMessage = "A password is required.")] public string Password { get; set; } [Required(ErrorMessage = "The name of the account is missing.")] public string AccountName { get; set; } [Required(ErrorMessage = "An address is required.")] public string ExternalAddress { get; set; } [Required(ErrorMessage = "A message is required.")] public string Message { get; set; } } /// <summary> /// Object to verify a signed message. /// </summary> public class VerifyRequest : RequestModel { [Required(ErrorMessage = "A signature is required.")] public string Signature { get; set; } [Required(ErrorMessage = "An address is required.")] public string ExternalAddress { get; set; } [Required(ErrorMessage = "A message is required.")] public string Message { get; set; } } public class SweepRequest : RequestModel { [Required(ErrorMessage = "One or more private keys is required.")] public List<string> PrivateKeys { get; set; } [Required(ErrorMessage = "A destination address is required.")] public string DestinationAddress { get; set; } public bool Broadcast { get; set; } } }
36.121951
181
0.592872
[ "MIT" ]
x42protocol/x42-BlockCore
src/Features/Blockcore.Features.Wallet/Api/Models/RequestModels.cs
34,065
C#
using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc.Rendering; using Microsoft.AspNetCore.Razor.TagHelpers; namespace IdentityServer.Admin.Helpers.TagHelpers { [HtmlTargetElement("toggle-button")] public class SwitchTagHelper : TagHelper { public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output) { var childContent = await output.GetChildContentAsync(); var divSlider = new TagBuilder("div"); divSlider.AddCssClass("slider round bg-primary"); output.TagName = "label"; output.Attributes.Add("class", "switch"); output.Content.AppendHtml(childContent); output.Content.AppendHtml(divSlider); output.TagMode = TagMode.StartTagAndEndTag; } } }
34.25
97
0.673966
[ "MIT" ]
Olek-HZQ/IdentityServerManagement
src/IdentityServer.Admin/Helpers/TagHelpers/SwitchTagHelper.cs
824
C#
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Windows; using System.Windows.Controls; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Animation; using System.Windows.Shapes; using Microsoft.Phone.Controls; namespace NDG.Views { public partial class SearchPage : PhoneApplicationPage { public SearchPage() { InitializeComponent(); } } }
22.869565
59
0.701521
[ "BSD-3-Clause" ]
nokiadatagathering/WP7-Official
NDG/Views/SearchPage.xaml.cs
528
C#
using System; using System.Collections.Generic; using System.Text.Json; using System.Text.Json.Serialization; namespace System.Text.Json.Converters { public class StringTypedInt32IListConverter : JsonConverter<IList<int>?> { private readonly JsonConverter<List<int>?> _converter = new StringTypedInt32ListConverter(); public override IList<int>? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { return _converter.Read(ref reader, typeToConvert, options); } public override void Write(Utf8JsonWriter writer, IList<int>? value, JsonSerializerOptions options) { _converter.Write(writer, ConvertIListToList(value), options); } private List<int>? ConvertIListToList(IList<int>? src) { if (src == null) return null; List<int>? dest = src as List<int>; if (dest != null) return dest; return new List<int>(src); } } }
29.971429
118
0.633937
[ "MIT" ]
KimMeng2015/DotNetCore.SKIT.FlurlHttpClient.Wechat
src/SKIT.FlurlHttpClient.Wechat/Converters/System.Text.Json/StringTypedInt32IListConverter.cs
1,051
C#
using System.Drawing; using SpaceSim.SolarSystem; namespace SpaceSim.Structures { class LaunchMount : StructureBase { //public override double Width { get { return 17; } } //public override double Height { get { return 30; } } public override double Width { get { return 12; } } public override double Height { get { return 7; } } public override Color IconColor { get { return Color.White; } } public LaunchMount(double surfaceAngle, double height, IMassiveBody parent) //: base(surfaceAngle, height, "Textures/Structures/LaunchMount.png", parent) : base(surfaceAngle, height, "Textures/Structures/TestMount.png", parent) { } } }
33.136364
89
0.648834
[ "MIT" ]
JohnnyOneSpeed/SpaceSim
src/SpaceSim/Structures/LaunchMount.cs
731
C#
// Copyright (c) MOSA Project. Licensed under the New BSD License. // This code was generated by an automated template. using Mosa.Compiler.Framework; namespace Mosa.Platform.x64.Instructions { /// <summary> /// IRetd /// </summary> /// <seealso cref="Mosa.Platform.x64.X64Instruction" /> public sealed class IRetd : X64Instruction { public override int ID { get { return 425; } } internal IRetd() : base(0, 0) { } public override FlowControl FlowControl { get { return FlowControl.Return; } } public override bool HasUnspecifiedSideEffect { get { return true; } } public override bool IsZeroFlagUnchanged { get { return true; } } public override bool IsZeroFlagUndefined { get { return true; } } public override bool IsCarryFlagUnchanged { get { return true; } } public override bool IsCarryFlagUndefined { get { return true; } } public override bool IsSignFlagUnchanged { get { return true; } } public override bool IsSignFlagUndefined { get { return true; } } public override bool IsOverflowFlagUnchanged { get { return true; } } public override bool IsOverflowFlagUndefined { get { return true; } } public override bool IsParityFlagUnchanged { get { return true; } } public override bool IsParityFlagUndefined { get { return true; } } public override void Emit(InstructionNode node, BaseCodeEmitter emitter) { System.Diagnostics.Debug.Assert(node.ResultCount == 0); System.Diagnostics.Debug.Assert(node.OperandCount == 0); emitter.OpcodeEncoder.AppendByte(0xCF); } } }
28.145455
80
0.720284
[ "BSD-3-Clause" ]
kthompson/MOSA-Project
Source/Mosa.Platform.x64/Instructions/IRetd.cs
1,548
C#
/* * OpaqueMail (http://opaquemail.org/). * * Licensed according to the MIT License (http://mit-license.org/). * * Copyright © Bert Johnson (http://bertjohnson.net/) of Bkip Inc. (http://bkip.com/). * * 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.Collections.Generic; using System.Linq; using System.Net.Mime; using System.Security.Cryptography.Pkcs; using System.Security.Cryptography.X509Certificates; using System.Text; using System.Threading.Tasks; namespace OpaqueMail.Net { /// <summary> /// Represents a node in a MIME encoded message tree. /// </summary> public class MimePart { #region Public Members // add this field for two reasons: // first, let constructor can set it directly, // secondly, play as cache private string _body = null; /// <summary>Return the string representation of the body.</summary> public string Body { get { if (_body == null) { if (!string.IsNullOrEmpty(CharSet)) _body = Encoding.GetEncoding(CharSet).GetString(BodyBytes); else _body = Encoding.UTF8.GetString(BodyBytes); } return _body; } } /// <summary>Raw contents of the MIME part's body.</summary> public byte[] BodyBytes; /// <summary>Character Set used to encode the MIME part.</summary> public string CharSet = ""; /// <summary>ID of the MIME part.</summary> public string ContentID = ""; /// <summary>Content Type of the MIME part.</summary> public string ContentType = ""; /// <summary>Content Transfer Encoding of the MIME part.</summary> public TransferEncoding ContentTransferEncoding = TransferEncoding.Unknown; /// <summary>Filename of the MIME part.</summary> public string Name = ""; /// <summary>Whether the MIME part is part of an S/MIME encrypted envelope.</summary> public bool SmimeEncryptedEnvelope = false; /// <summary>Whether the MIME part is S/MIME signed.</summary> public bool SmimeSigned = false; /// <summary>Certificates used when signing messages.</summary> public X509Certificate2Collection SmimeSigningCertificates = null; /// <summary>Whether the MIME part was S/MIME signed, had its envelope encrypted, and was then signed again.</summary> public bool SmimeTripleWrapped = false; #endregion Public Members #region Constructors /// <summary> /// Instantiate a MIME part based on the string representation of its body. /// </summary> /// <param name="name">Filename of the MIME part.</param> /// <param name="contentType">Content Type of the MIME part.</param> /// <param name="charset">Character Set used to encode the MIME part.</param> /// <param name="contentID">ID of the MIME part.</param> /// <param name="contentTransferEncoding">Content Transfer Encoding string of the MIME part.</param> /// <param name="body">String representation of the MIME part's body.</param> public MimePart(string name, string contentType, string charset, string contentID, string contentTransferEncoding, string body) : this(name, contentType, charset, contentID, contentTransferEncoding, (byte[])null) { Encoding encoding = Encoding.UTF8; try { encoding = Encoding.GetEncoding(charset); } catch { } BodyBytes = encoding.GetBytes(body); } /// <summary> /// Instantiate a MIME part based on its body's byte array. /// </summary> /// <param name="name">Filename of the MIME part.</param> /// <param name="contentType">Content Type of the MIME part.</param> /// <param name="charset">Character Set used to encode the MIME part.</param> /// <param name="contentID">ID of the MIME part.</param> /// <param name="contentTransferEncoding">Content Transfer Encoding string of the MIME part.</param> /// <param name="bodyBytes">The MIME part's raw bytes.</param> public MimePart(string name, string contentType, string charset, string contentID, string contentTransferEncoding, byte[] bodyBytes) { BodyBytes = bodyBytes; ContentType = contentType; ContentID = contentID; CharSet = charset; Name = Functions.DecodeMailHeader(name).Replace("\r", "").Replace("\n", ""); switch (contentTransferEncoding.ToLower()) { case "base64": ContentTransferEncoding = TransferEncoding.Base64; break; case "quoted-printable": ContentTransferEncoding = TransferEncoding.QuotedPrintable; break; case "7bit": ContentTransferEncoding = TransferEncoding.SevenBit; break; case "8bit": ContentTransferEncoding = TransferEncoding.EightBit; break; default: ContentTransferEncoding = TransferEncoding.Unknown; break; } } #endregion Constructors #region Public Methods /// <summary> /// Extract a list of MIME parts from a multipart/* MIME encoded message. /// </summary> /// <param name="contentType">Content Type of the outermost MIME part.</param> /// <param name="charSet">Character set of the outermost MIME part.</param> /// <param name="contentTransferEncoding">Encoding of the outermost MIME part.</param> /// <param name="body">The outermost MIME part's contents.</param> /// <param name="processingFlags">Flags determining whether specialized properties are returned with a ReadOnlyMailMessage.</param> public static List<MimePart> ExtractMIMEParts(string contentType, string charSet, string contentTransferEncoding, string body, ReadOnlyMailMessageProcessingFlags processingFlags) { List<MimePart> mimeParts = new List<MimePart>(); string contentTypeToUpper = contentType.ToUpper(); if (contentTypeToUpper.StartsWith("MULTIPART/")) { // Prepare to process each part of the multipart/* message. int cursor = 0; // Prepend the body with a carriage return and linefeed for consistent boundary matching. body = "\r\n" + body; // Determine the outermost boundary name. string boundaryName = Functions.ReturnBetween(contentType, "boundary=\"", "\""); if (boundaryName.Length < 1) { cursor = contentType.IndexOf("boundary=", StringComparison.OrdinalIgnoreCase); if (cursor > -1) boundaryName = contentType.Substring(cursor + 9); cursor = boundaryName.IndexOf(";"); if (cursor > -1) boundaryName = boundaryName.Substring(0, cursor); if (boundaryName.StartsWith("\"") && boundaryName.EndsWith("\"")) boundaryName = boundaryName.Substring(1, boundaryName.Length - 2); else { // Remove linear whitespace from boundary names. boundaryName = boundaryName.Trim(); } } int boundaryNameLength = boundaryName.Length; // Variables used for record keeping with signed S/MIME parts. int signatureBlock = -1; List<string> mimeBlocks = new List<string>(); cursor = body.IndexOf("\r\n--" + boundaryName, 0, StringComparison.Ordinal); while (cursor > -1) { // Calculate the end boundary of the current MIME part. int mimeStartPosition = cursor + boundaryNameLength + 4; int mimeEndPosition = body.IndexOf("\r\n--" + boundaryName, mimeStartPosition, StringComparison.Ordinal); if (mimeEndPosition > -1) { string afterBoundaryEnd = body.Substring(mimeEndPosition + 4 + boundaryNameLength, 2); if (afterBoundaryEnd == "\r\n" || afterBoundaryEnd == "--") { string mimeContents = body.Substring(mimeStartPosition, mimeEndPosition - mimeStartPosition); // Extract the header portion of the current MIME part. int mimeDivider = mimeContents.IndexOf("\r\n\r\n"); string mimeHeaders, mimeBody; if (mimeDivider > -1) { mimeHeaders = mimeContents.Substring(0, mimeDivider); mimeBody = mimeContents.Substring(mimeDivider + 4); } else { // The following is a workaround to handle malformed MIME bodies. mimeHeaders = mimeContents; mimeBody = ""; int linePos = 0, lastLinePos = 0; while (linePos > -1) { lastLinePos = linePos; linePos = mimeHeaders.IndexOf("\r\n", lastLinePos); if (linePos > -1) { string currentLine = mimeContents.Substring(lastLinePos, linePos - lastLinePos); if (currentLine.Length > 0 && currentLine.IndexOf(":") < 0) { mimeBody = mimeContents.Substring(lastLinePos + 2, mimeContents.Length - lastLinePos - 4); linePos = -1; } else linePos += 2; } } } mimeBlocks.Add(mimeContents); // Divide the MIME part's headers into its components. string mimeCharSet = "", mimeContentDisposition = "", mimeContentID = "", mimeContentType = "", mimeContentTransferEncoding = "", mimeFileName = ""; ExtractMimeHeaders(mimeHeaders, out mimeContentType, out mimeCharSet, out mimeContentTransferEncoding, out mimeContentDisposition, out mimeFileName, out mimeContentID); string mimeContentTypeToUpper = mimeContentType.ToUpper(); if (mimeContentTypeToUpper.StartsWith("MULTIPART/")) { // Recurse through embedded MIME parts. List<MimePart> returnedMIMEParts = ExtractMIMEParts(mimeContentType, mimeCharSet, mimeContentTransferEncoding, mimeBody, processingFlags); foreach (MimePart returnedMIMEPart in returnedMIMEParts) mimeParts.Add(returnedMIMEPart); } else { // Keep track of whether this MIME part's body has already been processed. bool processed = false; if (mimeContentTypeToUpper.StartsWith("APPLICATION/PKCS7-SIGNATURE") || mimeContentTypeToUpper.StartsWith("APPLICATION/X-PKCS7-SIGNATURE")) { // Unless a flag has been set to include this *.p7s block, exclude it from attachments. if ((processingFlags & ReadOnlyMailMessageProcessingFlags.IncludeSmimeSignedData) == 0) processed = true; // Remember the signature block to use for later verification. signatureBlock = mimeBlocks.Count() - 1; } else if (mimeContentTypeToUpper.StartsWith("APPLICATION/PKCS7-MIME") || mimeContentTypeToUpper.StartsWith("APPLICATION/X-PKCS7-MIME")) { // Unless a flag has been set to include this *.p7m block, exclude it from attachments. processed = (processingFlags & ReadOnlyMailMessageProcessingFlags.IncludeSmimeEncryptedEnvelopeData) == 0; // Decrypt the MIME part and recurse through embedded MIME parts. List<MimePart> returnedMIMEParts = ReturnDecryptedMimeParts(mimeContentType, mimeContentTransferEncoding, mimeBody, processingFlags); if (returnedMIMEParts != null) { foreach (MimePart returnedMIMEPart in returnedMIMEParts) mimeParts.Add(returnedMIMEPart); } else { // If we were unable to decrypt, return this MIME part as-is. processed = false; } } else if (mimeContentTypeToUpper.StartsWith("APPLICATION/MS-TNEF") || mimeFileName.ToUpper() == "WINMAIL.DAT") { // Process the TNEF encoded message. processed = true; TnefEncoding tnef = new TnefEncoding(Convert.FromBase64String(mimeBody)); // If we were unable to extract content from this MIME, include it as an attachment. if ((tnef.Body.Length < 1 && tnef.MimeAttachments.Count < 1) || (processingFlags & ReadOnlyMailMessageProcessingFlags.IncludeWinMailData) > 0) processed = false; else { // Unless a flag has been set to include this winmail.dat block, exclude it from attachments. if ((processingFlags & ReadOnlyMailMessageProcessingFlags.IncludeWinMailData) > 0) { if (!string.IsNullOrEmpty(tnef.Body)) mimeParts.Add(new MimePart("winmail.dat", tnef.ContentType, "", "", mimeContentTransferEncoding, Encoding.UTF8.GetBytes(tnef.Body))); } foreach (MimePart mimePart in tnef.MimeAttachments) mimeParts.Add(mimePart); } } else if (mimeContentTypeToUpper == "MESSAGE/RFC822") { if ((processingFlags & ReadOnlyMailMessageProcessingFlags.IncludeNestedRFC822Messages) > 0) { // Recurse through the RFC822 container. processed = true; mimeDivider = mimeBody.IndexOf("\r\n\r\n"); if (mimeDivider > -1) { mimeHeaders = Functions.UnfoldWhitespace(mimeBody.Substring(0, mimeDivider)); mimeBody = mimeBody.Substring(mimeDivider + 4); mimeContentType = Functions.ReturnBetween(mimeHeaders, "Content-Type:", "\r\n").Trim(); mimeContentTransferEncoding = Functions.ReturnBetween(mimeHeaders, "Content-Transfer-Encoding:", "\r\n").Trim(); mimeCharSet = Functions.ExtractMimeParameter(mimeContentType, "charset").Replace("\"", ""); List<MimePart> returnedMIMEParts = ExtractMIMEParts(mimeContentType, mimeCharSet, mimeContentTransferEncoding, mimeBody, processingFlags); foreach (MimePart returnedMIMEPart in returnedMIMEParts) mimeParts.Add(returnedMIMEPart); } } } if (!processed) { // Decode and add the message to the MIME parts collection. switch (mimeContentTransferEncoding.ToLower()) { case "base64": mimeBody = mimeBody.Replace("\r\n", ""); if (mimeBody.Length % 4 != 0) mimeBody += new String('=', 4 - (mimeBody.Length % 4)); mimeParts.Add(new MimePart(mimeFileName, mimeContentType, mimeCharSet, mimeContentID, mimeContentTransferEncoding, Convert.FromBase64String(mimeBody))); break; case "quoted-printable": mimeParts.Add(new MimePart(mimeFileName, mimeContentType, mimeCharSet, mimeContentID, mimeContentTransferEncoding, Functions.FromQuotedPrintable(mimeBody, mimeCharSet, null))); break; case "binary": case "7bit": case "8bit": default: mimeParts.Add(new MimePart(mimeFileName, mimeContentType, mimeCharSet, mimeContentID, mimeContentTransferEncoding, mimeBody)); break; } } } } cursor = mimeEndPosition; } else cursor = -1; } // If a PKCS signature was found and there's one other MIME part, verify the signature. if (signatureBlock > -1 && mimeBlocks.Count == 2) { // Verify the signature and track the signing certificates. X509Certificate2Collection signingCertificates; if (VerifySignature(mimeBlocks[signatureBlock], mimeBlocks[1 - signatureBlock], out signingCertificates)) { // Stamp each MIME part found so far as signed, and if relevant, triple wrapped. foreach (MimePart mimePart in mimeParts) { mimePart.SmimeSigningCertificates = signingCertificates; if (mimePart.SmimeSigned && mimePart.SmimeEncryptedEnvelope) mimePart.SmimeTripleWrapped = true; mimePart.SmimeSigned = true; } } } } else if (contentTypeToUpper.StartsWith("APPLICATION/MS-TNEF")) { // Process the TNEF encoded message. TnefEncoding tnef = new TnefEncoding(Convert.FromBase64String(body)); // Unless a flag has been set to include this winmail.dat block, exclude it from attachments. if ((processingFlags & ReadOnlyMailMessageProcessingFlags.IncludeWinMailData) > 0) { if (!string.IsNullOrEmpty(tnef.Body)) mimeParts.Add(new MimePart("winmail.dat", tnef.ContentType, "", "", "", Encoding.UTF8.GetBytes(tnef.Body))); } foreach (MimePart mimePart in tnef.MimeAttachments) mimeParts.Add(mimePart); } else if (contentTypeToUpper.StartsWith("APPLICATION/PKCS7-MIME") || contentTypeToUpper.StartsWith("APPLICATION/X-PKCS7-MIME")) { // Don't attempt to decrypt if this is a signed message only. if (contentType.IndexOf("smime-type=signed-data") < 0) { // Unless a flag has been set to include this *.p7m block, exclude it from attachments. if ((processingFlags & ReadOnlyMailMessageProcessingFlags.IncludeSmimeEncryptedEnvelopeData) > 0) mimeParts.Add(new MimePart("smime.p7m", contentType, "", "", "", body)); // Decrypt the MIME part and recurse through embedded MIME parts. List<MimePart> returnedMIMEParts = ReturnDecryptedMimeParts(contentType, contentTransferEncoding, body, processingFlags); if (returnedMIMEParts != null) { foreach (MimePart returnedMIMEPart in returnedMIMEParts) mimeParts.Add(returnedMIMEPart); } else { // If we were unable to decrypt the message, pass it along as-is. mimeParts.Add(new MimePart(Functions.ReturnBetween(contentType + ";", "name=", ";").Replace("\"", ""), contentType, "", "", contentTransferEncoding, body)); } } else { // Hydrate the signature CMS object. SignedCms signedCms = new SignedCms(); try { // Attempt to decode the signature block and verify the passed in signature. signedCms.Decode(Convert.FromBase64String(body)); signedCms.CheckSignature(true); string mimeContents = Encoding.UTF8.GetString(signedCms.ContentInfo.Content); int mimeDivider = mimeContents.IndexOf("\r\n\r\n"); string mimeHeaders; if (mimeDivider > -1) mimeHeaders = mimeContents.Substring(0, mimeDivider); else mimeHeaders = mimeContents; if (mimeHeaders.Length > 0) { // Extract the body portion of the current MIME part. string mimeBody = mimeContents.Substring(mimeDivider + 4); string mimeCharSet = "", mimeContentDisposition = "", mimeContentID = "", mimeContentType = "", mimeContentTransferEncoding = "", mimeFileName = ""; ExtractMimeHeaders(mimeHeaders, out mimeContentType, out mimeCharSet, out mimeContentTransferEncoding, out mimeContentDisposition, out mimeFileName, out mimeContentID); List<MimePart> returnedMIMEParts = ExtractMIMEParts(mimeContentType, mimeCharSet, mimeContentTransferEncoding, mimeBody, processingFlags); foreach (MimePart returnedMIMEPart in returnedMIMEParts) mimeParts.Add(returnedMIMEPart); } } catch { // If an exception occured, the signature could not be verified. } } } else if (contentTypeToUpper == "MESSAGE/RFC822") { int mimeDivider = body.IndexOf("\r\n\r\n"); if (mimeDivider > -1) { string mimeHeaders = Functions.UnfoldWhitespace(body.Substring(0, mimeDivider)); string mimeBody = body.Substring(mimeDivider + 4); string mimeContentType = Functions.ReturnBetween(mimeHeaders, "Content-Type:", "\r\n").Trim(); string mimeContentTransferEncoding = Functions.ReturnBetween(mimeHeaders, "Content-Transfer-Encoding:", "\r\n").Trim(); string mimeCharSet = Functions.ExtractMimeParameter(mimeContentType, "charset"); List<MimePart> returnedMIMEParts = ExtractMIMEParts(mimeContentType, mimeCharSet, mimeContentTransferEncoding, mimeBody, processingFlags); foreach (MimePart returnedMIMEPart in returnedMIMEParts) mimeParts.Add(returnedMIMEPart); } } else { // Decode the message. switch (contentTransferEncoding.ToLower()) { case "base64": body = Functions.FromBase64(body); break; case "quoted-printable": body = Functions.FromQuotedPrintable(body, charSet, null); break; case "binary": case "7bit": case "8bit": break; } // Extract the headers from this MIME part. string mimeHeaders; int mimeDivider = body.IndexOf("\r\n\r\n"); if (mimeDivider > -1 ) mimeHeaders = body.Substring(0, mimeDivider); else mimeHeaders = body; // Divide the MIME part's headers into its components. string mimeCharSet = "", mimeContentDisposition = "", mimeContentID = "", mimeContentType = "", mimeContentTransferEncoding = "", mimeFileName = ""; ExtractMimeHeaders(mimeHeaders, out mimeContentType, out mimeCharSet, out mimeContentTransferEncoding, out mimeContentDisposition, out mimeFileName, out mimeContentID); // If this MIME part's content type is null, fall back to the overall content type. if ((string.IsNullOrEmpty(mimeContentType) && !string.IsNullOrEmpty(contentType)) || (contentTypeToUpper.StartsWith("MESSAGE/PARTIAL"))) { mimeCharSet = charSet; mimeContentType = contentType; } else { if (body.Length > (mimeDivider + 4)) body = body.Substring(mimeDivider + 4); else body = ""; } // Add the message to the MIME parts collection. mimeParts.Add(new MimePart(mimeFileName, mimeContentType, mimeCharSet, mimeContentID, mimeContentTransferEncoding, body)); } return mimeParts; } /// <summary> /// Decrypt the encrypted S/MIME envelope. /// </summary> /// <param name="contentType">Content Type of the outermost MIME part.</param> /// <param name="contentTransferEncoding">Encoding of the outermost MIME part.</param> /// <param name="envelopeText">The MIME envelope.</param> /// <param name="processingFlags">Flags determining whether specialized properties are returned with a ReadOnlyMailMessage.</param> public static List<MimePart> ReturnDecryptedMimeParts(string contentType, string contentTransferEncoding, string envelopeText, ReadOnlyMailMessageProcessingFlags processingFlags) { try { // Hydrate the envelope CMS object. EnvelopedCms envelope = new EnvelopedCms(); // Attempt to decrypt the envelope. envelope.Decode(Convert.FromBase64String(envelopeText)); envelope.Decrypt(); string body = Encoding.UTF8.GetString(envelope.ContentInfo.Content); int divider = body.IndexOf("\r\n\r\n"); string mimeHeaders = body.Substring(0, divider); body = body.Substring(divider + 4); // Divide the MIME part's headers into its components. string mimeContentType = "", mimeCharSet = "", mimeContentTransferEncoding = "", mimeFileName = "", mimeContentDisposition = "", mimeContentID = ""; ExtractMimeHeaders(mimeHeaders, out mimeContentType, out mimeCharSet, out mimeContentTransferEncoding, out mimeContentDisposition, out mimeFileName, out mimeContentID); // Recurse through embedded MIME parts. List<MimePart> mimeParts = ExtractMIMEParts(mimeContentType, mimeCharSet, mimeContentTransferEncoding, body, processingFlags); foreach (MimePart mimePart in mimeParts) mimePart.SmimeEncryptedEnvelope = true; return mimeParts; } catch (Exception) { // If unable to decrypt the body, return null. return null; } } /// <summary> /// Verify the S/MIME signature. /// </summary> /// <param name="signatureBlock">The S/MIME signature block.</param> /// <param name="body">The message's raw body.</param> /// <param name="signingCertificates">Collection of certificates to be used when signing.</param> public static bool VerifySignature(string signatureBlock, string body, out X509Certificate2Collection signingCertificates) { // Ignore MIME headers for the signature block. signatureBlock = signatureBlock.Substring(signatureBlock.IndexOf("\r\n\r\n") + 4); // Bypass any leading carriage returns and line feeds in the body. int bodyOffset = 0; while (body.Substring(bodyOffset).StartsWith("\r\n")) bodyOffset += 2; // Hydrate the signature CMS object. ContentInfo contentInfo = new ContentInfo(Encoding.UTF8.GetBytes(body.Substring(bodyOffset))); SignedCms signedCms = new SignedCms(contentInfo, true); try { // Attempt to decode the signature block and verify the passed in signature. signedCms.Decode(Convert.FromBase64String(signatureBlock)); signedCms.CheckSignature(true); signingCertificates = signedCms.Certificates; return true; } catch { // If an exception occured, the signature could not be verified. signingCertificates = null; return false; } } /// <summary> /// Divide a MIME part's headers into its components. /// </summary> /// <param name="mimeHeaders">The raw headers portion of the MIME part.</param> /// <param name="mimeContentType">Content Type of the MIME part.</param> /// <param name="mimeCharset">Character Set used to encode the MIME part.</param> /// <param name="mimeContentDisposition">Content disposition, such as file metadata, of the MIME part.</param> /// <param name="mimeFileName">Filename of the MIME part.</param> /// <param name="mimeContentID">ID of the MIME part.</param> private static void ExtractMimeHeaders(string mimeHeaders, out string mimeContentType, out string mimeCharSet, out string mimeContentTransferEncoding, out string mimeContentDisposition, out string mimeFileName, out string mimeContentID) { // Initialize all headers as blank strings. mimeContentType = mimeCharSet = mimeContentTransferEncoding = mimeContentDisposition = mimeFileName = mimeContentID = ""; // Record keeping variable to handle headers that spawn multiple lines. string lastMimeHeaderType = ""; // Unfold any unneeded whitespace, then Loop through each line of the headers. string[] mimeHeaderLines = Functions.UnfoldWhitespace(mimeHeaders).Replace("\r", "").Split('\n'); foreach (string header in mimeHeaderLines) { // Split header {name:value} pairs by the first colon found. int colonPos = header.IndexOf(":"); if (colonPos > -1 && colonPos < header.Length - 1) { string[] headerParts = new string[] { header.Substring(0, colonPos), header.Substring(colonPos + 1).Trim() }; string headerType = headerParts[0].ToLower(); string headerValue = headerParts[1]; // Process each header's value based on its name. switch (headerType) { case "content-disposition": mimeContentDisposition += headerValue.Trim(); break; case "content-id": // Ignore opening and closing <> characters. mimeContentID = headerValue.Trim(); if (mimeContentID.StartsWith("<")) mimeContentID = mimeContentID.Substring(1); if (mimeContentID.EndsWith(">")) mimeContentID = mimeContentID.Substring(0, mimeContentID.Length - 1); break; case "content-transfer-encoding": mimeContentTransferEncoding = headerValue.ToLower(); break; case "content-type": if (string.IsNullOrEmpty(mimeContentType)) mimeContentType = headerValue; break; default: break; } lastMimeHeaderType = headerType; } } // If a content disposition has been specified, extract the filename. if (mimeContentDisposition.Length > 0) mimeFileName = Functions.ExtractMimeParameter(mimeContentDisposition, "name"); // If a content disposition has not been specified, search elsewhere in the content type string for the filename. if (string.IsNullOrEmpty(mimeFileName)) mimeFileName = Functions.ExtractMimeParameter(mimeContentType, "name"); mimeCharSet = Functions.ExtractMimeParameter(mimeContentType, "charset"); } #endregion Public Methods } }
55.784314
463
0.522996
[ "MIT" ]
percyboy/OpaqueMail
OpaqueMail.Net/MimePart.cs
36,996
C#
#pragma warning disable 108 // new keyword hiding #pragma warning disable 114 // new keyword hiding namespace Windows.UI.Xaml.Controls.Primitives { #if false || false || false || false || false [global::Uno.NotImplemented] #endif public partial class PivotHeaderPanel : global::Windows.UI.Xaml.Controls.Canvas { // Skipping already declared method Windows.UI.Xaml.Controls.Primitives.PivotHeaderPanel.PivotHeaderPanel() // Forced skipping of method Windows.UI.Xaml.Controls.Primitives.PivotHeaderPanel.PivotHeaderPanel() } }
38.285714
109
0.777985
[ "Apache-2.0" ]
06needhamt/uno
src/Uno.UI/Generated/3.0.0.0/Windows.UI.Xaml.Controls.Primitives/PivotHeaderPanel.cs
536
C#
#region Copyright (c) 2018 Scott L. Carter // //Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in //compliance with the License. You may obtain a copy of the License at //http://www.apache.org/licenses/LICENSE-2.0 // //Unless required by applicable law or agreed to in writing, software distributed under the License is //distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. //See the License for the specific language governing permissions and limitations under the License. #endregion namespace NStateManager.Tests { public class TestPayment { public TestPayment(double amount) { Amount = amount; } public double Amount { get; } } }
34.652174
107
0.712673
[ "Apache-2.0" ]
scottctr/NStateManager
Tests/NStateManager.Tests/TestPayment.cs
799
C#
// Copyright © Microsoft Open Technologies, Inc. // // All Rights Reserved // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS // OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION // ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A // PARTICULAR PURPOSE, MERCHANTABILITY OR NON-INFRINGEMENT. // // See the Apache License, Version 2.0 for the specific language // governing permissions and limitations under the License. namespace Microsoft.Azure.ActiveDirectory.GraphClient { /// <summary> /// Enumeration of key types. /// </summary> public enum KeyType { /// <summary> /// Symmetric keys. /// </summary> Symmetric = 0, /// <summary> /// X509 certificate (Asymmetric) key /// </summary> AsymmetricX509Cert = 1, } }
29.540541
72
0.666972
[ "Apache-2.0" ]
Mimeo/azuread-graphapi-library-for-dotnet
DirectoryObjects/Helpers/KeyType.cs
1,097
C#
// *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AzureNextGen.Compute.V20200930.Inputs { /// <summary> /// Contains encryption settings for a data disk image. /// </summary> public sealed class DataDiskImageEncryptionArgs : Pulumi.ResourceArgs { /// <summary> /// A relative URI containing the resource ID of the disk encryption set. /// </summary> [Input("diskEncryptionSetId")] public Input<string>? DiskEncryptionSetId { get; set; } /// <summary> /// This property specifies the logical unit number of the data disk. This value is used to identify data disks within the Virtual Machine and therefore must be unique for each data disk attached to the Virtual Machine. /// </summary> [Input("lun", required: true)] public Input<int> Lun { get; set; } = null!; public DataDiskImageEncryptionArgs() { } } }
34.4
227
0.665282
[ "Apache-2.0" ]
pulumi/pulumi-azure-nextgen
sdk/dotnet/Compute/V20200930/Inputs/DataDiskImageEncryptionArgs.cs
1,204
C#
using Microsoft.VisualStudio.TestTools.UnitTesting; using BojkoSoft.Transformations.Constants; using Tests; namespace BojkoSoft.Transformations.Tests { [TestClass()] public class TestBGSWithTPS { private static Transformations tr; [ClassInitialize] public static void ClassInitialize(TestContext context) { tr = new Transformations(); } #region BGS 1930 [TestMethod()] public void TransformFromBGS1930() { // 24 degrees IPoint input = new TestPoint(4728966.163, 8607005.227); IPoint expected = new TestPoint(4728401.432, 483893.508); //IPoint result = tr.TransformBGSCoordinates(input, enumProjection.BGS_1930_24, enumProjection.BGS_2005_KK); IPoint result = tr.Transform(input, enumProjection.BGS_1930_24, enumProjection.BGS_2005_KK); Common.CheckResults(expected, result, Common.DELTA_BGS); // 27 degrees input = new TestPoint(4729531.133, 9361175.733); //result = tr.TransformBGSCoordinates(input, enumProjection.BGS_1930_27, enumProjection.BGS_2005_KK); result = tr.Transform(input, enumProjection.BGS_1930_27, enumProjection.BGS_2005_KK); Common.CheckResults(expected, result, Common.DELTA_BGS); } [TestMethod()] public void TransformToBGS1930() { // 24 degrees IPoint input = new TestPoint(4728401.432, 483893.508); IPoint expected = new TestPoint(4728966.163, 8607005.227); //IPoint result = tr.TransformBGSCoordinates(input, enumProjection.BGS_2005_KK, enumProjection.BGS_1930_24); IPoint result = tr.Transform(input, enumProjection.BGS_2005_KK, enumProjection.BGS_1930_24); Common.CheckResults(expected, result, Common.DELTA_BGS); // 27 degrees expected = new TestPoint(4729531.133, 9361175.733); //result = tr.TransformBGSCoordinates(input, enumProjection.BGS_2005_KK, enumProjection.BGS_1930_27); result = tr.Transform(input, enumProjection.BGS_2005_KK, enumProjection.BGS_1930_27); Common.CheckResults(expected, result, Common.DELTA_BGS); } #endregion #region BGS 1950 [TestMethod()] public void TransformFromBGS1950() { // 3 deg 24 degrees IPoint input = new TestPoint(4729331.175, 8606933.614); IPoint expected = new TestPoint(4728401.432, 483893.508); //IPoint result = tr.TransformBGSCoordinates(input, enumProjection.BGS_1950_3_24, enumProjection.BGS_2005_KK); IPoint result = tr.Transform(input, enumProjection.BGS_1950_3_24, enumProjection.BGS_2005_KK); Common.CheckResults(expected, result, Common.DELTA_BGS); // 3 deg 27 degrees input = new TestPoint(4729899.053, 9361082.960); //result = tr.TransformBGSCoordinates(input, enumProjection.BGS_1950_3_27, enumProjection.BGS_2005_KK); result = tr.Transform(input, enumProjection.BGS_1950_3_27, enumProjection.BGS_2005_KK); Common.CheckResults(expected, result, Common.DELTA_BGS); // 6 deg 21 degrees input = new TestPoint(4737501.141, 4852808.182); //result = tr.TransformBGSCoordinates(input, enumProjection.BGS_1950_6_21, enumProjection.BGS_2005_KK); result = tr.Transform(input, enumProjection.BGS_1950_6_21, enumProjection.BGS_2005_KK); Common.CheckResults(expected, result, Common.DELTA_BGS); // 6 deg 27 degrees input = new TestPoint(4729899.053, 5361082.960); //result = tr.TransformBGSCoordinates(input, enumProjection.BGS_1950_6_27, enumProjection.BGS_2005_KK); result = tr.Transform(input, enumProjection.BGS_1950_6_27, enumProjection.BGS_2005_KK); Common.CheckResults(expected, result, Common.DELTA_BGS); } [TestMethod()] public void TransformToBGS1950() { // 3 deg 24 degrees IPoint input = new TestPoint(4728401.432, 483893.508); IPoint expected = new TestPoint(4729331.175, 8606933.614); //IPoint result = tr.TransformBGSCoordinates(input, enumProjection.BGS_2005_KK, enumProjection.BGS_1950_3_24); IPoint result = tr.Transform(input, enumProjection.BGS_2005_KK, enumProjection.BGS_1950_3_24); Common.CheckResults(expected, result, Common.DELTA_BGS); // 3 deg 27 degrees expected = new TestPoint(4729899.053, 9361082.960); //result = tr.TransformBGSCoordinates(input, enumProjection.BGS_2005_KK, enumProjection.BGS_1950_3_27); result = tr.Transform(input, enumProjection.BGS_2005_KK, enumProjection.BGS_1950_3_27); Common.CheckResults(expected, result, Common.DELTA_BGS); // 6 deg 21 degrees expected = new TestPoint(4737501.141, 4852808.182); //result = tr.TransformBGSCoordinates(input, enumProjection.BGS_2005_KK, enumProjection.BGS_1950_6_21); result = tr.Transform(input, enumProjection.BGS_2005_KK, enumProjection.BGS_1950_6_21); Common.CheckResults(expected, result, Common.DELTA_BGS); // 6 deg 27 degrees expected = new TestPoint(4729899.053, 5361082.960); //result = tr.TransformBGSCoordinates(input, enumProjection.BGS_2005_KK, enumProjection.BGS_1950_6_27); result = tr.Transform(input, enumProjection.BGS_2005_KK, enumProjection.BGS_1950_6_27); Common.CheckResults(expected, result, Common.DELTA_BGS); } #endregion #region BGS Sofia [TestMethod()] public void TransformFromBGSSofia() { IPoint input = new TestPoint(48276.705, 45420.988); IPoint expected = new TestPoint(4730215.229, 322402.935); //IPoint result = tr.TransformBGSCoordinates(input, enumProjection.BGS_SOFIA, enumProjection.BGS_2005_KK); IPoint result = tr.Transform(input, enumProjection.BGS_SOFIA, enumProjection.BGS_2005_KK); Common.CheckResults(expected, result, Common.DELTA_BGS); } [TestMethod()] public void TransformToBGSSofia() { IPoint input = new TestPoint(4730215.229, 322402.935); IPoint expected = new TestPoint(48276.705, 45420.988); //IPoint result = tr.TransformBGSCoordinates(input, enumProjection.BGS_2005_KK, enumProjection.BGS_SOFIA); IPoint result = tr.Transform(input, enumProjection.BGS_2005_KK, enumProjection.BGS_SOFIA); Common.CheckResults(expected, result, Common.DELTA_BGS); } #endregion #region BGS 1970 [TestMethod()] public void TransformFromBGS1970() { // K3 IPoint input = new TestPoint(4725270.684, 8515734.475); IPoint expected = new TestPoint(4816275.680, 332535.401); //IPoint result = tr.TransformBGSCoordinates(input, enumProjection.BGS_1970_K3, enumProjection.BGS_2005_KK); IPoint result = tr.Transform(input, enumProjection.BGS_1970_K3, enumProjection.BGS_2005_KK); Common.CheckResults(expected, result, Common.DELTA_BGS); // K5 input = new TestPoint(4613479.192, 9493233.633); expected = new TestPoint(4679669.825, 569554.918); //result = tr.TransformBGSCoordinates(input, enumProjection.BGS_1970_K5, enumProjection.BGS_2005_KK); result = tr.Transform(input, enumProjection.BGS_1970_K5, enumProjection.BGS_2005_KK); Common.CheckResults(expected, result, Common.DELTA_BGS); // K7 input = new TestPoint(4708089.898, 9570974.988); expected = new TestPoint(4810276.431, 626498.611); //result = tr.TransformBGSCoordinates(input, enumProjection.BGS_1970_K7, enumProjection.BGS_2005_KK); result = tr.Transform(input, enumProjection.BGS_1970_K7, enumProjection.BGS_2005_KK); Common.CheckResults(expected, result, Common.DELTA_BGS); // K9 input = new TestPoint(4547844.976, 8508858.179); expected = new TestPoint(4675440.847, 330568.434); //result = tr.TransformBGSCoordinates(input, enumProjection.BGS_1970_K9, enumProjection.BGS_2005_KK); result = tr.Transform(input, enumProjection.BGS_1970_K9, enumProjection.BGS_2005_KK); Common.CheckResults(expected, result, Common.DELTA_BGS); } [TestMethod()] public void TransformToBGS1970() { // K3 IPoint input = new TestPoint(4816275.680, 332535.401); IPoint expected = new TestPoint(4725270.684, 8515734.475); //IPoint result = tr.TransformBGSCoordinates(input, enumProjection.BGS_2005_KK, enumProjection.BGS_1970_K3); IPoint result = tr.Transform(input, enumProjection.BGS_2005_KK, enumProjection.BGS_1970_K3); Common.CheckResults(expected, result, Common.DELTA_BGS); // K5 input = new TestPoint(4679669.825, 569554.918); expected = new TestPoint(4613479.192, 9493233.633); //result = tr.TransformBGSCoordinates(input, enumProjection.BGS_2005_KK, enumProjection.BGS_1970_K5); result = tr.Transform(input, enumProjection.BGS_2005_KK, enumProjection.BGS_1970_K5); Common.CheckResults(expected, result, Common.DELTA_BGS); // K7 input = new TestPoint(4810276.431, 626498.611); expected = new TestPoint(4708089.898, 9570974.988); //result = tr.TransformBGSCoordinates(input, enumProjection.BGS_2005_KK, enumProjection.BGS_1970_K7); result = tr.Transform(input, enumProjection.BGS_2005_KK, enumProjection.BGS_1970_K7); Common.CheckResults(expected, result, Common.DELTA_BGS); // K9 input = new TestPoint(4675440.847, 330568.434); expected = new TestPoint(4547844.976, 8508858.179); //result = tr.TransformBGSCoordinates(input, enumProjection.BGS_2005_KK, enumProjection.BGS_1970_K9); result = tr.Transform(input, enumProjection.BGS_2005_KK, enumProjection.BGS_1970_K9); Common.CheckResults(expected, result, Common.DELTA_BGS); } #endregion #region BGS 2005 // same as above tests [TestMethod()] public void PointCloseToBorder() { // k3 : k9 IPoint input = new TestPoint(4753610.10997237, 318581.541736281); IPoint expected = new TestPoint(4625700.505, 8494949.232); //IPoint result = tr.TransformBGSCoordinates(input, enumProjection.BGS_2005_KK, enumProjection.BGS_1970_K9); IPoint result = tr.Transform(input, enumProjection.BGS_2005_KK, enumProjection.BGS_1970_K9); Common.CheckResults(expected, result, Common.DELTA_BGS); } #endregion region } }
48.563319
122
0.659203
[ "MIT" ]
bojko108/Transformations.NET
Tests/TestBGSWithTPS.cs
11,123
C#
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! namespace Google.Cloud.Dialogflow.Cx.V3.Snippets { using Google.Cloud.Dialogflow.Cx.V3; using Google.LongRunning; public sealed partial class GeneratedEnvironmentsClientStandaloneSnippets { /// <summary>Snippet for RunContinuousTest</summary> /// <remarks> /// This snippet has been automatically generated for illustrative purposes only. /// It may require modifications to work in your environment. /// </remarks> public void RunContinuousTestRequestObject() { // Create client EnvironmentsClient environmentsClient = EnvironmentsClient.Create(); // Initialize request argument(s) RunContinuousTestRequest request = new RunContinuousTestRequest { EnvironmentAsEnvironmentName = EnvironmentName.FromProjectLocationAgentEnvironment("[PROJECT]", "[LOCATION]", "[AGENT]", "[ENVIRONMENT]"), }; // Make the request Operation<RunContinuousTestResponse, RunContinuousTestMetadata> response = environmentsClient.RunContinuousTest(request); // Poll until the returned long-running operation is complete Operation<RunContinuousTestResponse, RunContinuousTestMetadata> completedResponse = response.PollUntilCompleted(); // Retrieve the operation result RunContinuousTestResponse result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name Operation<RunContinuousTestResponse, RunContinuousTestMetadata> retrievedResponse = environmentsClient.PollOnceRunContinuousTest(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result RunContinuousTestResponse retrievedResult = retrievedResponse.Result; } } } }
46.254237
156
0.691829
[ "Apache-2.0" ]
googleapis/googleapis-gen
google/cloud/dialogflow/cx/v3/google-cloud-dialogflow-cx-v3-csharp/Google.Cloud.Dialogflow.Cx.V3.StandaloneSnippets/EnvironmentsClient.RunContinuousTestRequestObjectSnippet.g.cs
2,729
C#
using System; using System.Collections.Generic; using System.Data; using DbUp.Builder; using DbUp.Engine; using DbUp.Engine.Output; using DbUp.Engine.Transactions; using DbUp.Support.SqlServer; using NSubstitute; using NUnit.Framework; namespace DbUp.Tests.Engine { public class UpgradeEngineTests { public class when_upgrading_a_database_with_variable_substitution : SpecificationFor<UpgradeEngine> { private IJournal versionTracker; private IScriptProvider scriptProvider; private IScriptExecutor scriptExecutor; private IDbConnection dbConnection; private IDbCommand dbCommand; public override UpgradeEngine Given() { scriptProvider = Substitute.For<IScriptProvider>(); scriptProvider.GetScripts(Arg.Any<IConnectionManager>()).Returns(new List<SqlScript> { new SqlScript("1234", "foo") }); versionTracker = Substitute.For<IJournal>(); dbConnection = Substitute.For<IDbConnection>(); dbCommand = Substitute.For<IDbCommand>(); dbConnection.CreateCommand().Returns(dbCommand); var connectionManager = new TestConnectionManager(dbConnection); scriptExecutor = new SqlScriptExecutor(() => connectionManager, () => new TraceUpgradeLog(), null, () => true, null); var builder = new UpgradeEngineBuilder() .WithScript(new SqlScript("1234", "create table $var$ (Id int)")) .JournalTo(versionTracker) .WithVariable("var", "sub"); builder.Configure(c => c.ScriptExecutor = scriptExecutor); builder.Configure(c => c.ConnectionManager = connectionManager); var upgrader = builder.Build(); return upgrader; } public override void When() { Subject.PerformUpgrade(); } [Then] public void substitutes_variable() { Assert.AreEqual("create table sub (Id int)", dbCommand.CommandText); } } public class when_marking_scripts_as_read : SpecificationFor<UpgradeEngine> { private IJournal versionTracker; private IScriptProvider scriptProvider; private IScriptExecutor scriptExecutor; public override UpgradeEngine Given() { scriptProvider = Substitute.For<IScriptProvider>(); scriptProvider.GetScripts(Arg.Any<IConnectionManager>()).Returns(new List<SqlScript> { new SqlScript("1234", "foo") }); versionTracker = Substitute.For<IJournal>(); scriptExecutor = Substitute.For<IScriptExecutor>(); var config = new UpgradeConfiguration(); config.ConnectionManager = new TestConnectionManager(); config.ScriptProviders.Add(scriptProvider); config.ScriptExecutor = scriptExecutor; config.Journal = versionTracker; var upgrader = new UpgradeEngine(config); return upgrader; } public override void When() { Subject.MarkAsExecuted(); } [Then] public void the_scripts_are_journalled() { versionTracker.Received().StoreExecutedScript(Arg.Is<SqlScript>(s => s.Name == "1234")); } [Then] public void the_scripts_are_not_run() { scriptExecutor.DidNotReceiveWithAnyArgs().Execute(null); } } } }
37.767677
135
0.587858
[ "MIT" ]
DamianMac/DbUp
src/DbUp.Tests/Engine/UpgradeEngineTests.cs
3,739
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("06.GenerateExelReportsFromMySqlAndSqlLite")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("06.GenerateExelReportsFromMySqlAndSqlLite")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("6975dec9-677c-49fb-ac4a-54ce4cb1f062")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
39.324324
84
0.753952
[ "MIT" ]
Databases-Team-Aluminium/Team-Aluminium
TeamAluminium/06.GenerateExelReportsFromMySqlAndSqlLite/Properties/AssemblyInfo.cs
1,458
C#
using System; using System.Collections.Generic; namespace FreeAgent.Model { public class TrialBalance { public Uri Category { get; set; } public string NominalCode { get; set; } public string Name { get; set; } public float Total { get; set; } public Uri BankAccount { get; set; } public Uri User { get; set; } } public class TrialBalanceWrapper { public IEnumerable<TrialBalance> TrialBalanceSummary { get; set; } } }
20.636364
68
0.685022
[ "Apache-2.0" ]
arrowflex/FreeAgent
src/FreeAgent/Model/TrialBalance.cs
454
C#
/* Yet Another Forum.NET * Copyright (C) 2003-2005 Bjørnar Henden * Copyright (C) 2006-2013 Jaben Cargman * Copyright (C) 2014-2016 Ingo Herbote * http://www.yetanotherforum.net/ * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ namespace YAF.Controls { #region Using using System.Web.UI; using YAF.Core; #endregion /// <summary> /// Makes a very simple localized label /// </summary> public class LocalizedLabel : BaseControl, ILocalizationSupport { #region Constants and Fields #endregion #region Constructors and Destructors /// <summary> /// Initializes a new instance of the <see cref="LocalizedLabel"/> class. /// </summary> public LocalizedLabel() { this.LocalizedPage = string.Empty; this.EnableBBCode = false; this.LocalizedTag = string.Empty; this.Param2 = string.Empty; this.Param1 = string.Empty; this.Param0 = string.Empty; } #endregion #region Properties /// <summary> /// Gets or sets a value indicating whether EnableBBCode. /// </summary> public bool EnableBBCode { get; set; } /// <summary> /// Gets or sets LocalizedPage. /// </summary> public string LocalizedPage { get; set; } /// <summary> /// Gets or sets LocalizedTag. /// </summary> public string LocalizedTag { get; set; } /// <summary> /// Gets or sets Parameter 0. /// </summary> public string Param0 { get; set; } /// <summary> /// Gets or sets Parameter 1. /// </summary> public string Param1 { get; set; } /// <summary> /// Gets or sets Parameter 2. /// </summary> public string Param2 { get; set; } #endregion #region Methods /// <summary> /// Shows the localized text string (if available) /// </summary> /// <param name="output">The output.</param> protected override void Render(HtmlTextWriter output) { output.BeginRender(); if (!this.DesignMode) { output.Write(this.LocalizeAndRender(this)); } else { output.Write("[{0}][{1}]", this.LocalizedPage, this.LocalizedTag); } output.EndRender(); } #endregion } }
28.711864
83
0.56464
[ "Apache-2.0" ]
hismightiness/YAFNET
yafsrc/YAF.Controls/Localized/LocalizedLabel.cs
3,272
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; using Microsoft.EntityFrameworkCore; using OSS.App.Data; using OSS.Domain.Entities; namespace OSS.Web.Pages.ShiftTypes { public class IndexModel : PageModel { private readonly OSS.App.Data.AppIdentityDbContext _context; public IndexModel(OSS.App.Data.AppIdentityDbContext context) { _context = context; } public IList<ShiftType> ShiftType { get; set; } public async Task OnGetAsync() { ShiftType = await _context.ShiftTypes.OrderBy(st => st.ShiftSequence).ToListAsync(); } } }
25.133333
96
0.692308
[ "MIT" ]
nagasudhirpulla/open_shift_scheduler
src/OSS.Web/Pages/ShiftTypes/Index.cshtml.cs
756
C#
using Playnite.SDK; using Playnite.SDK.Models; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Playnite.Database { public class FeaturesCollection : ItemCollection<GameFeature> { private readonly GameDatabase db; public FeaturesCollection(GameDatabase database) : base(type: GameDatabaseCollection.Features) { db = database; } private void RemoveUsage(Guid id) { foreach (var game in db.Games.Where(a => a.FeatureIds?.Contains(id) == true)) { game.FeatureIds.Remove(id); db.Games.Update(game); } } public override bool Remove(GameFeature itemToRemove) { RemoveUsage(itemToRemove.Id); return base.Remove(itemToRemove); } public override bool Remove(Guid id) { RemoveUsage(id); return base.Remove(id); } public override bool Remove(IEnumerable<GameFeature> itemsToRemove) { if (itemsToRemove.HasItems()) { foreach (var item in itemsToRemove) { RemoveUsage(item.Id); } } return base.Remove(itemsToRemove); } } }
26.5
103
0.539483
[ "MIT" ]
1gjunior/Playnite
source/Playnite/Database/Collections/FeaturesCollection.cs
1,433
C#
using Microsoft.AspNetCore.Mvc; namespace PokemonApi.Controllers; [ApiController] [Route("[controller]")] public class WeatherForecastController : ControllerBase { private static readonly string[] Summaries = new[] { "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching" }; private readonly ILogger<WeatherForecastController> _logger; public WeatherForecastController(ILogger<WeatherForecastController> logger) { _logger = logger; } [HttpGet(Name = "GetWeatherForecast")] public IEnumerable<WeatherForecast> Get() { return Enumerable.Range(1, 5).Select(index => new WeatherForecast { Date = DateTime.Now.AddDays(index), TemperatureC = Random.Shared.Next(-20, 55), Summary = Summaries[Random.Shared.Next(Summaries.Length)] }) .ToArray(); } }
27.088235
106
0.65038
[ "MIT" ]
220328-uta-sh-net-ext/Harsh-Tamakuwala
Training/PokemonApp/PokemonApi/Controllers/WeatherForecastController.cs
923
C#
// Copyright (c) 2020 Yann Crumeyrolle. All rights reserved. // Licensed under the MIT license. See LICENSE in the project root for license information. using System; namespace JsonWebToken.Cryptography { /// <summary>Represents a salt generator for cryptographic operation</summary> public interface ISaltGenerator { /// <summary>Generates a salt.</summary> void Generate(Span<byte> salt); } }
28.666667
91
0.713953
[ "MIT" ]
signature-opensource/Jwt
src/JsonWebToken/Cryptography/ISaltGenerator.cs
432
C#
using System; using System.Linq; using LiteDB; using Moviebase.Core.Utils; using Moviebase.DAL; using Moviebase.DAL.Entities; // ReSharper disable once InconsistentNaming namespace Moviebase.Core.App { /// <inheritdoc /> public class MoviebaseDAL : IMoviebaseDAL { /// <inheritdoc /> public Movie MapMovieToEntity(TMDbLib.Objects.Movies.Movie match, string imageUri) { return new Movie { TmdbId = match.Id, ImdbId = match.ImdbId, Title = match.Title, ReleaseDate = match.ReleaseDate, Overview = match.Overview, Adult = match.Adult, Collection = match.BelongsToCollection?.Name.Replace(" - Collezione", string.Empty), Duration = TimeSpan.FromMinutes(match.Runtime.GetValueOrDefault()), Genres = match.Genres.Select(g => new Genre { Id = g.Id, Name = g.Name }).ToList(), ImageUri = imageUri, OriginalLanguage = match.OriginalLanguage, OriginalTitle = match.OriginalTitle, Popularity = match.Popularity, VoteAverage = match.VoteAverage, VoteCount = match.VoteCount, }; } /// <inheritdoc /> public Movie GetMovieByImdbId(string imdbId) { using (var db = new LiteDatabase(GlobalSettings.Default.ConnectionString)) { var movieCollection = db.GetCollection<Movie>(); return movieCollection.FindOne(x => x.ImdbId == imdbId); } } /// <inheritdoc /> public void RecordScanFile(AnalyzedFile file, Movie movie) { using (var db = new LiteDatabase(GlobalSettings.Default.ConnectionString)) { // update movie data var movieCollection = db.GetCollection<Movie>(); movieCollection.Upsert(movie); // update data hash var hashCollection = db.GetCollection<MediaFileHash>(); var hashEntity = hashCollection.FindOne(x => x.Hash == file.Hash) ?? new MediaFileHash(); hashEntity.Hash = file.Hash; hashEntity.ImdbId = movie.ImdbId; hashEntity.Title = movie.Title; hashEntity.Year = movie.Year; hashCollection.Upsert(hashEntity); // update media file var mediaCollection = db.GetCollection<MediaFile>(); var mediaEntity = mediaCollection.FindOne(x => x.Hash == file.Hash) ?? new MediaFile(); mediaEntity.TmdbId = movie.TmdbId; mediaEntity.Hash = file.Hash; mediaEntity.FullPath = file.FullPath; mediaEntity.LastSync = DateTime.Now; mediaCollection.Upsert(mediaEntity); } } } }
36.085366
105
0.558297
[ "MIT" ]
GreenDragonflyStudio/Moviebase
Moviebase.Core/App/MoviebaseDAL.cs
2,961
C#
/* Copyright 2011 Google Inc Licensed under the Apache License, Version 2.0(the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using System; using System.Net; using DotNetOpenAuth.OAuth2; using Google.Apis.Authentication.OAuth2.DotNetOpenAuth; using NUnit.Framework; namespace Google.Apis.Authentication.OAuth2.Tests { /// <summary> /// Tests for the OAuth2Authenticator class /// </summary> [TestFixture] public class OAuth2AuthenticatorTest { /// <summary> /// Tests the constructor of this class /// </summary> [Test] public void ConstructTest() { var client = new NativeApplicationClient(new Uri("http://example.com")); var auth = new OAuth2Authenticator<NativeApplicationClient>(client, (clt) => new AuthorizationState()); Assert.IsNull(auth.State); } /// <summary> /// Tests that the authorization delegate of this class is called. /// </summary> [Test] public void DelegateTest() { var state = new AuthorizationState() { AccessToken = "Test" }; var client = new NativeApplicationClient(new Uri("http://example.com")); var auth = new OAuth2Authenticator<NativeApplicationClient>(client, (clt) => state); // Check that the state was set. auth.LoadAccessToken(); Assert.AreEqual(state, auth.State); } /// <summary> /// Tests that an authorization is performed if no access token is available. /// </summary> [Test] public void CheckForValidAccessTokenTest() { int accessTokenCounter = 1; var state = new AuthorizationState(); var client = new NativeApplicationClient(new Uri("http://example.com")); var auth = new OAuth2Authenticator<NativeApplicationClient>( client, (clt) => { // Load a "cached" access token. state.AccessToken = "token" + (accessTokenCounter++); return state; }); // Check that the initial state is null. Assert.IsNull(auth.State); // Check that the state was set when .LoadAccessToken() is called. auth.LoadAccessToken(); Assert.AreEqual(state, auth.State); Assert.AreEqual("token1", auth.State.AccessToken); // Check that it wont be set again. auth.LoadAccessToken(); Assert.AreEqual("token1", auth.State.AccessToken); // Check that it is set if our state gets invalid. state.AccessToken = null; auth.LoadAccessToken(); Assert.AreEqual("token2", auth.State.AccessToken); } /// <summary> /// Tests that the authorization header is added to a web request. /// </summary> [Test] public void ApplyAuthenticationToRequestTest() { var request = (HttpWebRequest)WebRequest.Create("http://example.com"); var state = new AuthorizationState() { AccessToken = "Test" }; var client = new NativeApplicationClient(new Uri("http://example.com")); var auth = new OAuth2Authenticator<NativeApplicationClient>(client, (clt) => state); // Confirm that the request header gets modified. auth.ApplyAuthenticationToRequest(request); Assert.AreEqual(1, request.Headers.Count); } } }
36.550459
115
0.611446
[ "Apache-2.0" ]
Dmiri/Xamarin.google-apis
src/Externals/google-api-dotnet-client/Src/GoogleApis.Authentication.OAuth2.Tests/OAuth2AuthenticatorTest.cs
3,986
C#
using System; using System.Collections.Generic; #nullable disable namespace KZ.AdventureWorks.Products.Api.Models { public partial class SalesOrderHeader { public SalesOrderHeader() { SalesOrderDetails = new HashSet<SalesOrderDetail>(); SalesOrderHeaderSalesReasons = new HashSet<SalesOrderHeaderSalesReason>(); } public int SalesOrderId { get; set; } public byte RevisionNumber { get; set; } public DateTime OrderDate { get; set; } public DateTime DueDate { get; set; } public DateTime? ShipDate { get; set; } public byte Status { get; set; } public bool? OnlineOrderFlag { get; set; } public string SalesOrderNumber { get; set; } public string PurchaseOrderNumber { get; set; } public string AccountNumber { get; set; } public int CustomerId { get; set; } public int? SalesPersonId { get; set; } public int? TerritoryId { get; set; } public int BillToAddressId { get; set; } public int ShipToAddressId { get; set; } public int ShipMethodId { get; set; } public int? CreditCardId { get; set; } public string CreditCardApprovalCode { get; set; } public int? CurrencyRateId { get; set; } public decimal SubTotal { get; set; } public decimal TaxAmt { get; set; } public decimal Freight { get; set; } public decimal TotalDue { get; set; } public string Comment { get; set; } public Guid Rowguid { get; set; } public DateTime ModifiedDate { get; set; } public virtual Address BillToAddress { get; set; } public virtual CreditCard CreditCard { get; set; } public virtual CurrencyRate CurrencyRate { get; set; } public virtual Customer Customer { get; set; } public virtual SalesPerson SalesPerson { get; set; } public virtual ShipMethod ShipMethod { get; set; } public virtual Address ShipToAddress { get; set; } public virtual SalesTerritory Territory { get; set; } public virtual ICollection<SalesOrderDetail> SalesOrderDetails { get; set; } public virtual ICollection<SalesOrderHeaderSalesReason> SalesOrderHeaderSalesReasons { get; set; } } }
41.727273
106
0.640087
[ "MIT" ]
az00s/KZ.AdventureWorks.Products.Api
KZ.AdventureWorks.Products.Api/Models/SalesOrderHeader.cs
2,297
C#
using System; using System.Collections.Generic; using System.Linq; using System.Reactive.Linq; using System.Threading; using System.Threading.Tasks; using Autofac; using Miningcore.Blockchain.Ergo.Configuration; using NLog; using Miningcore.Configuration; using Miningcore.Extensions; using Miningcore.Messaging; using Miningcore.Notifications.Messages; using Miningcore.Stratum; using Miningcore.Time; using Miningcore.Util; using Newtonsoft.Json; using Contract = Miningcore.Contracts.Contract; using static Miningcore.Util.ActionUtils; namespace Miningcore.Blockchain.Ergo { public class ErgoJobManager : JobManagerBase<ErgoJob> { public ErgoJobManager( IComponentContext ctx, IMessageBus messageBus, IMasterClock clock, IExtraNonceProvider extraNonceProvider) : base(ctx, messageBus) { Contract.RequiresNonNull(clock, nameof(clock)); Contract.RequiresNonNull(extraNonceProvider, nameof(extraNonceProvider)); this.clock = clock; this.extraNonceProvider = extraNonceProvider; extraNonceSize = 8 - extraNonceProvider.ByteSize; } private ErgoCoinTemplate coin; private ErgoClient ergoClient; private string network; private readonly List<ErgoJob> validJobs = new(); private int maxActiveJobs = 4; private readonly int extraNonceSize; private readonly IExtraNonceProvider extraNonceProvider; private readonly IMasterClock clock; private ErgoPoolConfigExtra extraPoolConfig; private int blockVersion; private void SetupJobUpdates() { var blockFound = blockFoundSubject.Synchronize(); var pollTimerRestart = blockFoundSubject.Synchronize(); var triggers = new List<IObservable<(bool Force, string Via, string Data)>> { blockFound.Select(_ => (false, JobRefreshBy.BlockFound, (string) null)) }; if(extraPoolConfig?.BtStream != null) { var btStream = BtStreamSubscribe(extraPoolConfig.BtStream); triggers.Add(btStream .Select(json => (false, JobRefreshBy.BlockTemplateStream, json)) .Publish() .RefCount()); } // periodically update block-template var pollingInterval = poolConfig.BlockRefreshInterval > 0 ? poolConfig.BlockRefreshInterval : 1000; triggers.Add(Observable.Timer(TimeSpan.FromMilliseconds(pollingInterval)) .TakeUntil(pollTimerRestart) .Select(_ => (false, JobRefreshBy.Poll, (string) null)) .Repeat()); // get initial blocktemplate triggers.Add(Observable.Interval(TimeSpan.FromMilliseconds(1000)) .Select(_ => (false, JobRefreshBy.Initial, (string) null)) .TakeWhile(_ => !hasInitialBlockTemplate)); Jobs = Observable.Merge(triggers) .Select(x => Observable.FromAsync(() => UpdateJob(x.Force, x.Via, x.Data))) .Concat() .Where(x => x.IsNew || x.Force) .Do(x => { if(x.IsNew) hasInitialBlockTemplate = true; }) .Select(x => GetJobParamsForStratum(x.IsNew)) .Publish() .RefCount(); } private async Task<(bool IsNew, bool Force)> UpdateJob(bool forceUpdate, string via = null, string json = null) { logger.LogInvoke(); try { var blockTemplate = string.IsNullOrEmpty(json) ? await GetBlockTemplateAsync() : GetBlockTemplateFromJson(json); var job = currentJob; var isNew = job == null || (blockTemplate != null && (job.BlockTemplate?.Msg != blockTemplate.Msg || blockTemplate.Height > job.BlockTemplate.Height)); if(isNew) messageBus.NotifyChainHeight(poolConfig.Id, blockTemplate.Height, poolConfig.Template); if(isNew || forceUpdate) { job = new ErgoJob(); job.Init(blockTemplate, blockVersion, extraNonceSize, NextJobId()); lock(jobLock) { validJobs.Insert(0, job); // trim active jobs while(validJobs.Count > maxActiveJobs) validJobs.RemoveAt(validJobs.Count - 1); } if(isNew) { if(via != null) logger.Info(() => $"Detected new block {job.Height} [{via}]"); else logger.Info(() => $"Detected new block {job.Height}"); // update stats var inode = await Guard(() => ergoClient.GetNodeInfoAsync(), ex => logger.Debug(ex)); var blockTimeAvg = 120; var DiffN = (double)inode.Difficulty; // update stats BlockchainStats.LastNetworkBlockTime = clock.Now; BlockchainStats.BlockHeight = job.Height; BlockchainStats.ConnectedPeers = inode.PeersCount; BlockchainStats.NetworkDifficulty = DiffN; BlockchainStats.NetworkHashrate = BlockchainStats.NetworkDifficulty / blockTimeAvg; } else { if(via != null) logger.Debug(() => $"Template update {job.Height} [{via}]"); else logger.Debug(() => $"Template update {job.Height}"); } currentJob = job; } return (isNew, forceUpdate); } catch(ApiException<ApiError> ex) { logger.Error(() => $"Error during {nameof(UpdateJob)}: {ex.Result.Detail ?? ex.Result.Reason}"); } catch(Exception ex) { logger.Error(ex, () => $"Error during {nameof(UpdateJob)}"); } return (false, forceUpdate); } private async Task<WorkMessage> GetBlockTemplateAsync() { logger.LogInvoke(); var work = await ergoClient.MiningRequestBlockCandidateAsync(CancellationToken.None); return work; } private WorkMessage GetBlockTemplateFromJson(string json) { logger.LogInvoke(); return JsonConvert.DeserializeObject<WorkMessage>(json); } private async Task ShowDaemonSyncProgressAsync() { var info = await Guard(() => ergoClient.GetNodeInfoAsync(), ex => logger.Debug(ex)); if(info?.FullHeight.HasValue == true && info.HeadersHeight.HasValue) { var percent = (double) info.FullHeight.Value / info.HeadersHeight.Value * 100; logger.Info(() => $"Daemon has downloaded {percent:0.00}% of blockchain from {info.PeersCount} peers"); } else logger.Info(() => $"Daemon is downloading headers ..."); } private void ConfigureRewards() { // Donation to MiningCore development if(network == "mainnet" && DevDonation.Addresses.TryGetValue(poolConfig.Template.Symbol, out var address)) { poolConfig.RewardRecipients = poolConfig.RewardRecipients.Concat(new[] { new RewardRecipient { Address = address, Percentage = DevDonation.Percent, Type = "dev" } }).ToArray(); } } private async Task<bool> SubmitBlockAsync(Share share, string nonce) { try { await ergoClient.MiningSubmitSolutionAsync(new PowSolutions { N = nonce, }); return true; } catch(ApiException<ApiError> ex) { logger.Warn(() => $"Block {share.BlockHeight} submission failed with: {ex.Result.Detail ?? ex.Result.Reason ?? ex.Message}"); messageBus.SendMessage(new AdminNotification("Block submission failed", $"Pool {poolConfig.Id} {(!string.IsNullOrEmpty(share.Source) ? $"[{share.Source.ToUpper()}] " : string.Empty)}failed to submit block {share.BlockHeight}: {ex.Result.Detail ?? ex.Result.Reason}")); } catch(Exception ex) { logger.Warn(() => $"Block {share.BlockHeight} submission failed with: {ex.Message}"); messageBus.SendMessage(new AdminNotification("Block submission failed", $"Pool {poolConfig.Id} {(!string.IsNullOrEmpty(share.Source) ? $"[{share.Source.ToUpper()}] " : string.Empty)}failed to submit block {share.BlockHeight}: {ex.Message}")); } return false; } #region API-Surface public IObservable<object[]> Jobs { get; private set; } public BlockchainStats BlockchainStats { get; } = new(); public string Network => network; public ErgoCoinTemplate Coin => coin; public object[] GetSubscriberData(StratumConnection worker) { Contract.RequiresNonNull(worker, nameof(worker)); var context = worker.ContextAs<ErgoWorkerContext>(); // assign unique ExtraNonce1 to worker (miner) context.ExtraNonce1 = extraNonceProvider.Next(); // setup response data var responseData = new object[] { context.ExtraNonce1, extraNonceSize, }; return responseData; } public async ValueTask<Share> SubmitShareAsync(StratumConnection worker, object submission, double stratumDifficultyBase, CancellationToken ct) { Contract.RequiresNonNull(worker, nameof(worker)); Contract.RequiresNonNull(submission, nameof(submission)); logger.LogInvoke(new[] { worker.ConnectionId }); if(submission is not object[] submitParams) throw new StratumException(StratumError.Other, "invalid params"); var context = worker.ContextAs<ErgoWorkerContext>(); // extract params var workerValue = (submitParams[0] as string)?.Trim(); var jobId = submitParams[1] as string; var extraNonce2 = submitParams[2] as string; var nTime = submitParams[3] as string; var nonce = submitParams[4] as string; if(string.IsNullOrEmpty(workerValue)) throw new StratumException(StratumError.Other, "missing or invalid workername"); ErgoJob job; lock(jobLock) { job = validJobs.FirstOrDefault(x => x.JobId == jobId); } if(job == null) throw new StratumException(StratumError.JobNotFound, "job not found"); // validate & process var share = job.ProcessShare(worker, extraNonce2, nTime, nonce); // enrich share with common data share.PoolId = poolConfig.Id; share.IpAddress = worker.RemoteEndpoint.Address.ToString(); share.Miner = context.Miner; share.Worker = context.Worker; share.UserAgent = context.UserAgent; share.Source = clusterConfig.ClusterName; share.Created = clock.Now; // if block candidate, submit & check if accepted by network if(share.IsBlockCandidate) { logger.Info(() => $"Submitting block {share.BlockHeight} [{share.BlockHash}]"); var acceptResponse = await SubmitBlockAsync(share, nonce); // is it still a block candidate? share.IsBlockCandidate = acceptResponse; if(share.IsBlockCandidate) { logger.Info(() => $"Daemon accepted block {share.BlockHeight} [{share.BlockHash}] submitted by {context.Miner}"); OnBlockFound(); // persist the nonce to make block unlocking a bit more reliable share.TransactionConfirmationData = nonce; } else { // clear fields that no longer apply share.TransactionConfirmationData = null; } } return share; } public async Task<bool> ValidateAddress(string address, CancellationToken ct) { if(string.IsNullOrEmpty(address)) return false; var validity = await Guard(() => ergoClient.CheckAddressValidityAsync(address, ct), ex => logger.Debug(ex)); return validity?.IsValid == true; } #endregion // API-Surface #region Overrides protected override async Task PostStartInitAsync(CancellationToken ct) { // validate pool address if(string.IsNullOrEmpty(poolConfig.Address)) logger.ThrowLogPoolStartupException($"Pool address is not configured"); var validity = await Guard(() => ergoClient.CheckAddressValidityAsync(poolConfig.Address, ct), ex=> logger.ThrowLogPoolStartupException($"Error validating pool address: {ex}")); if(!validity.IsValid) logger.ThrowLogPoolStartupException($"Daemon reports pool address {poolConfig.Address} as invalid: {validity.Error}"); var info = await Guard(() => ergoClient.GetNodeInfoAsync(ct), ex=> logger.ThrowLogPoolStartupException($"Daemon reports: {ex.Message}")); blockVersion = info.Parameters.BlockVersion; // chain detection var m = ErgoConstants.RegexChain.Match(info.Name); if(!m.Success) logger.ThrowLogPoolStartupException($"Unable to identify network type ({info.Name}"); network = m.Groups[1].Value.ToLower(); // Payment-processing setup if(clusterConfig.PaymentProcessing?.Enabled == true && poolConfig.PaymentProcessing?.Enabled == true) { // check configured address belongs to wallet var walletAddresses = await ergoClient.WalletAddressesAsync(ct); if(!walletAddresses.Contains(poolConfig.Address)) logger.ThrowLogPoolStartupException($"Pool address {poolConfig.Address} is not controlled by wallet"); ConfigureRewards(); } // update stats BlockchainStats.NetworkType = network; BlockchainStats.RewardType = "POW"; SetupJobUpdates(); } public override void Configure(PoolConfig poolConfig, ClusterConfig clusterConfig) { coin = poolConfig.Template.As<ErgoCoinTemplate>(); extraPoolConfig = poolConfig.Extra.SafeExtensionDataAs<ErgoPoolConfigExtra>(); if(extraPoolConfig?.MaxActiveJobs.HasValue == true) maxActiveJobs = extraPoolConfig.MaxActiveJobs.Value; base.Configure(poolConfig, clusterConfig); } protected override void ConfigureDaemons() { ergoClient = ErgoClientFactory.CreateClient(poolConfig, clusterConfig, logger); } protected override async Task<bool> AreDaemonsHealthyAsync(CancellationToken ct) { var info = await Guard(() => ergoClient.GetNodeInfoAsync(ct), ex=> logger.ThrowLogPoolStartupException($"Daemon reports: {ex.Message}")); if(info?.IsMining != true) logger.ThrowLogPoolStartupException($"Mining is disabled in Ergo Daemon"); return true; } protected override async Task<bool> AreDaemonsConnectedAsync(CancellationToken ct) { var info = await Guard(() => ergoClient.GetNodeInfoAsync(ct), ex=> logger.Debug(ex)); return info?.PeersCount > 0; } protected override async Task EnsureDaemonsSynchedAsync(CancellationToken ct) { var syncPendingNotificationShown = false; while(true) { var info = await Guard(() => ergoClient.GetNodeInfoAsync(ct), ex=> logger.Debug(ex)); var isSynched = info?.FullHeight.HasValue == true && info?.HeadersHeight.HasValue == true && info.FullHeight.Value >= info.HeadersHeight.Value; if(isSynched) { logger.Info(() => "Daemon is synced with blockchain"); break; } if(!syncPendingNotificationShown) { logger.Info(() => "Daemon is still syncing with network. Manager will be started once synced"); syncPendingNotificationShown = true; } await ShowDaemonSyncProgressAsync(); // delay retry by 5s await Task.Delay(5000, ct); } } private object[] GetJobParamsForStratum(bool isNew) { var job = currentJob; return job?.GetJobParams(isNew); } #endregion // Overrides } }
36.651822
284
0.552414
[ "MIT" ]
kevinmarceloph/miningcore
src/Miningcore/Blockchain/Ergo/ErgoJobManager.cs
18,106
C#
using System; using System.CodeDom.Compiler; using System.ComponentModel; using System.Diagnostics; using System.Runtime.CompilerServices; using System.Xml.Schema; using System.Xml.Serialization; namespace Workday.FinancialManagement { [GeneratedCode("System.Xml", "4.6.1590.0"), DesignerCategory("code"), DebuggerStepThrough, XmlType(Namespace = "urn:com.workday/bsvc")] [Serializable] public class Currency_Rate_TypeObjectType : INotifyPropertyChanged { private Currency_Rate_TypeObjectIDType[] idField; private string descriptorField; [method: CompilerGenerated] [CompilerGenerated] public event PropertyChangedEventHandler PropertyChanged; [XmlElement("ID", Order = 0)] public Currency_Rate_TypeObjectIDType[] ID { get { return this.idField; } set { this.idField = value; this.RaisePropertyChanged("ID"); } } [XmlAttribute(Form = XmlSchemaForm.Qualified)] public string Descriptor { get { return this.descriptorField; } set { this.descriptorField = value; this.RaisePropertyChanged("Descriptor"); } } protected void RaisePropertyChanged(string propertyName) { PropertyChangedEventHandler propertyChanged = this.PropertyChanged; if (propertyChanged != null) { propertyChanged(this, new PropertyChangedEventArgs(propertyName)); } } } }
22.245902
136
0.73692
[ "MIT" ]
matteofabbri/Workday.WebServices
Workday.FinancialManagement/Currency_Rate_TypeObjectType.cs
1,357
C#
using Aiursoft.Scanner; using Aiursoft.XelNaga.Tests.Models; using Microsoft.Extensions.DependencyInjection; using Microsoft.VisualStudio.TestTools.UnitTesting; using System; using System.Threading.Tasks; namespace Aiursoft.XelNaga.Tests.Services { [TestClass] public class CannonQueueTests { private IServiceProvider _serviceProvider; [TestInitialize] public void Init() { var dbContext = new SqlDbContext(); dbContext.Database.EnsureDeleted(); dbContext.Database.EnsureCreated(); _serviceProvider = new ServiceCollection() .AddLogging() .AddLibraryDependencies() .AddDbContext<SqlDbContext>() .BuildServiceProvider(); } [TestCleanup] public void Clean() { DemoService.DoneTimes = 0; DemoService.Done = false; DemoService.DoneAsync = false; } [TestMethod] public async Task TestCannonQueueMultipleTimes() { await TestCannonQueue(); await Task.Delay(100); Clean(); await TestCannonQueue(); } [TestMethod] public async Task TestCannonQueue() { var controller = _serviceProvider.GetRequiredService<DemoController>(); var startTime = DateTime.UtcNow; controller.QueueActionAsync(); var endTime = DateTime.UtcNow; Assert.IsTrue(endTime - startTime < TimeSpan.FromMilliseconds(1000), "Demo action should finish very fast."); Assert.AreEqual(false, DemoService.DoneAsync, "When demo action finished, work is not over yet."); startTime = DateTime.UtcNow; while (DemoService.DoneTimes != 32) { await Task.Delay(20); Console.WriteLine($"Waitted for {DateTime.UtcNow - startTime}. And {DemoService.DoneTimes} tasks are finished."); } endTime = DateTime.UtcNow; Assert.IsTrue(endTime - startTime < TimeSpan.FromMilliseconds(5000), "All actions should finish in 5 seconds."); } } }
32.865672
129
0.601726
[ "MIT" ]
AiursoftWeb/Infrastructures
tests/XelNaga.Tests/Services/CannonQueue.Tests.cs
2,204
C#
using System; using System.Collections.Generic; using SaaSOvation.Collaboration.Application.Calendars.Data; using SaaSOvation.Common.Port.Adapters.Persistence; namespace SaaSOvation.Collaboration.Application.Calendars { public class CalendarEntryQueryService : AbstractQueryService { public CalendarEntryQueryService(string providerName, string connectionString) : base(connectionString, providerName) { } public CalendarEntryData GetCalendarEntryDataById(string tenantId, string calendarEntryId) { return QueryObject<CalendarEntryData>( "select " + "entry.calendar_entry_id, entry.alarm_alarm_units, entry.alarm_alarm_units_type, " + "entry.calendar_id, entry.description, entry.location, " + "entry.owner_email_address, entry.owner_identity, entry.owner_name, " + "entry.repetition_ends, entry.repetition_type, entry.tenant_id, " + "entry.time_span_begins, entry.time_span_ends, " + "invitee.calendar_entry_id as o_invitees_calendar_entry_id, " + "invitee.participant_email_address as o_invitees_participant_email_address, " + "invitee.participant_identity as o_invitees_participant_identity, " + "invitee.participant_name as o_invitees_participant_name, " + "invitee.tenant_id as o_invitees_tenant_id " + "from tbl_vw_calendar_entry as entry left outer join tbl_vw_calendar_entry_invitee as invitee " + " on entry.calendar_entry_id = invitee.calendar_entry_id " + "where entry.tenant_id = ? and entry.calendar_entry_id = ?", new JoinOn("calendar_entry_id", "o_invitees_calendar_entry_id"), tenantId, calendarEntryId); } public IList<CalendarEntryData> GetCalendarEntryDataByCalendarId(string tenantId, string calendarId) { return QueryObjects<CalendarEntryData>( "select " + "entry.calendar_entry_id, entry.alarm_alarm_units, entry.alarm_alarm_units_type, " + "entry.calendar_id, entry.description, entry.location, " + "entry.owner_email_address, entry.owner_identity, entry.owner_name, " + "entry.repetition_ends, entry.repetition_type, entry.tenant_id, " + "entry.time_span_begins, entry.time_span_ends, " + "invitee.calendar_entry_id as o_invitees_calendar_entry_id, " + "invitee.participant_email_address as o_invitees_participant_email_address, " + "invitee.participant_identity as o_invitees_participant_identity, " + "invitee.participant_name as o_invitees_participant_name, " + "invitee.tenant_id as o_invitees_tenant_id " + "from tbl_vw_calendar_entry as entry left outer join tbl_vw_calendar_entry_invitee as invitee " + " on entry.calendar_entry_id = invitee.calendar_entry_id " + "where entry.tenant_id = ? and entry.calendar_id = ?", new JoinOn("calendar_entry_id", "o_invitees_calendar_entry_id"), tenantId, calendarId); } public IList<CalendarEntryData> GetCalendarEntriesSpanning(string tenantId, string calendarId, DateTime beginsOn, DateTime endsOn) { return QueryObjects<CalendarEntryData>( "select " + "entry.calendar_entry_id, entry.alarm_alarm_units, entry.alarm_alarm_units_type, " + "entry.calendar_id, entry.description, entry.location, " + "entry.owner_email_address, entry.owner_identity, entry.owner_name, " + "entry.repetition_ends, entry.repetition_type, entry.tenant_id, " + "entry.time_span_begins, entry.time_span_ends, " + "invitee.calendar_entry_id as o_invitees_calendar_entry_id, " + "invitee.participant_email_address as o_invitees_participant_email_address, " + "invitee.participant_identity as o_invitees_participant_identity, " + "invitee.participant_name as o_invitees_participant_name, " + "invitee.tenant_id as o_invitees_tenant_id " + "from tbl_vw_calendar_entry as entry left outer join tbl_vw_calendar_entry_invitee as invitee " + " on entry.calendar_entry_id = invitee.calendar_entry_id " + "where entry.tenant_id = ? and entry.calendar_id = ? and " + "((entry.time_span_begins between ? and ?) or " + " (entry.repetition_ends between ? and ?))", new JoinOn("calendar_entry_id", "o_invitees_calendar_entry_id"), tenantId, calendarId, beginsOn, endsOn, beginsOn, endsOn); } } }
58.764045
138
0.614149
[ "Apache-2.0" ]
GermanKuber-zz/IDDD_Samples_NET
iddd_collaboration/Application/Calendars/CalendarEntryQueryService.cs
5,232
C#
// Generated on 12/11/2014 19:01:48 using System; using System.Collections.Generic; using System.Linq; using BlueSheep.Common.Protocol.Types; using BlueSheep.Common.IO; using BlueSheep.Engine.Types; namespace BlueSheep.Common.Protocol.Messages { public class ExchangeBidPriceMessage : Message { public new const uint ID =5755; public override uint ProtocolID { get { return ID; } } public short genericId; public int averagePrice; public ExchangeBidPriceMessage() { } public ExchangeBidPriceMessage(short genericId, int averagePrice) { this.genericId = genericId; this.averagePrice = averagePrice; } public override void Serialize(BigEndianWriter writer) { writer.WriteVarShort(genericId); writer.WriteVarInt(averagePrice); } public override void Deserialize(BigEndianReader reader) { genericId = reader.ReadVarShort(); if (genericId < 0) throw new Exception("Forbidden value on genericId = " + genericId + ", it doesn't respect the following condition : genericId < 0"); averagePrice = reader.ReadVarInt(); } } }
23.293103
148
0.592894
[ "MIT" ]
Sadikk/BlueSheep
BlueSheep/Common/Protocol/messages/game/inventory/exchanges/ExchangeBidPriceMessage.cs
1,351
C#
using UnityEngine; using UnityEngine.UI; using System; using System.Collections; using System.Collections.Generic; public class shrineContextMenu : MonoBehaviour { public Button sampleButton; public GameObject ritualList; public static MonoBehaviour currentOffering; public static MonoBehaviour currentOffering2; public static event Action TriggerRainDanceSummon; private List<ContextMenuItem> contextMenuItems; private Dictionary<string, Type> scriptToRitual = new Dictionary<string, Type>() { { "wheatContextMenu", typeof(RainDance) } }; void Awake() { contextMenuItems = new List<ContextMenuItem>(); Action<Image> sacrifice = new Action<Image>(OfferWheatAction); Action<Image> raindance = new Action<Image>(RainDanceAction); Action<Image> insult = new Action<Image>(InsultAction); contextMenuItems.Add(new ContextMenuItem("Offer Wheat", sampleButton, sacrifice)); contextMenuItems.Add(new ContextMenuItem("Rain Dance", sampleButton, raindance)); contextMenuItems.Add(new ContextMenuItem("Insult", sampleButton, insult)); } void OnMouseOver() { if (Input.GetMouseButtonDown(1)) { Vector3 pos = Camera.main.WorldToScreenPoint(transform.position); ContextMenu.Instance.CreateContextMenu(contextMenuItems, new Vector2(pos.x, pos.y)); } } public void OfferWheatAction(Image contextPanel) { if (currentOffering != null && currentOffering.name == "wheatToken") { var wheatRitual = new OfferWheat(); EventManager.AddRitual(wheatRitual); Destroy(currentOffering.gameObject); } Destroy(contextPanel.gameObject); } public void RainDanceAction(Image contextPanel) { RainDance raindance = new RainDance(); EventManager.AddRitual(raindance); } public void InsultAction(Image contextPanel) { Insult insult = new Insult(); EventManager.AddRitual(insult); insult.triggerLightning(); } }
35.551724
131
0.691077
[ "CC0-1.0" ]
Fuskalachi/Village-God
Assets/Scripts/Game Structures/Village Buildings/Shrine/shrineContextMenu.cs
2,064
C#
// ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ // **NOTE** This file was generated by a tool and any changes will be overwritten. // <auto-generated/> // Template Source: MethodRequestBuilder.cs.tt namespace Microsoft.Graph { using System; using System.Collections.Generic; using System.IO; /// <summary> /// The type WorkbookFunctionsBinom_DistRequestBuilder. /// </summary> public partial class WorkbookFunctionsBinom_DistRequestBuilder : BaseActionMethodRequestBuilder<IWorkbookFunctionsBinom_DistRequest>, IWorkbookFunctionsBinom_DistRequestBuilder { /// <summary> /// Constructs a new <see cref="WorkbookFunctionsBinom_DistRequestBuilder"/>. /// </summary> /// <param name="requestUrl">The URL for the request.</param> /// <param name="client">The <see cref="IBaseClient"/> for handling requests.</param> /// <param name="numberS">A numberS parameter for the OData method call.</param> /// <param name="trials">A trials parameter for the OData method call.</param> /// <param name="probabilityS">A probabilityS parameter for the OData method call.</param> /// <param name="cumulative">A cumulative parameter for the OData method call.</param> public WorkbookFunctionsBinom_DistRequestBuilder( string requestUrl, IBaseClient client, Newtonsoft.Json.Linq.JToken numberS, Newtonsoft.Json.Linq.JToken trials, Newtonsoft.Json.Linq.JToken probabilityS, Newtonsoft.Json.Linq.JToken cumulative) : base(requestUrl, client) { this.SetParameter("numberS", numberS, true); this.SetParameter("trials", trials, true); this.SetParameter("probabilityS", probabilityS, true); this.SetParameter("cumulative", cumulative, true); } /// <summary> /// A method used by the base class to construct a request class instance. /// </summary> /// <param name="functionUrl">The request URL to </param> /// <param name="options">The query and header options for the request.</param> /// <returns>An instance of a specific request class.</returns> protected override IWorkbookFunctionsBinom_DistRequest CreateRequest(string functionUrl, IEnumerable<Option> options) { var request = new WorkbookFunctionsBinom_DistRequest(functionUrl, this.Client, options); if (this.HasParameter("numberS")) { request.RequestBody.NumberS = this.GetParameter<Newtonsoft.Json.Linq.JToken>("numberS"); } if (this.HasParameter("trials")) { request.RequestBody.Trials = this.GetParameter<Newtonsoft.Json.Linq.JToken>("trials"); } if (this.HasParameter("probabilityS")) { request.RequestBody.ProbabilityS = this.GetParameter<Newtonsoft.Json.Linq.JToken>("probabilityS"); } if (this.HasParameter("cumulative")) { request.RequestBody.Cumulative = this.GetParameter<Newtonsoft.Json.Linq.JToken>("cumulative"); } return request; } } }
44.708861
180
0.612967
[ "MIT" ]
DamienTehDemon/msgraph-sdk-dotnet
src/Microsoft.Graph/Generated/requests/WorkbookFunctionsBinom_DistRequestBuilder.cs
3,532
C#
using Bit.Core.Models.Api; using Bit.Core.Models.Table; using Bit.Core.Enums; using Bit.Core.Repositories; using IdentityServer4.Models; using IdentityServer4.Validation; using Microsoft.AspNetCore.Identity; using System; using System.Collections.Generic; using System.Security.Claims; using System.Threading.Tasks; using Bit.Core.Services; using System.Linq; using Bit.Core.Models; using Bit.Core.Identity; using Bit.Core.Models.Data; namespace Bit.Core.IdentityServer { public class ResourceOwnerPasswordValidator : IResourceOwnerPasswordValidator { private UserManager<User> _userManager; private readonly IDeviceRepository _deviceRepository; private readonly IDeviceService _deviceService; private readonly IUserService _userService; private readonly IEventService _eventService; private readonly IOrganizationDuoWebTokenProvider _organizationDuoWebTokenProvider; private readonly IOrganizationRepository _organizationRepository; private readonly IOrganizationUserRepository _organizationUserRepository; private readonly IApplicationCacheService _applicationCacheService; private readonly CurrentContext _currentContext; public ResourceOwnerPasswordValidator( UserManager<User> userManager, IDeviceRepository deviceRepository, IDeviceService deviceService, IUserService userService, IEventService eventService, IOrganizationDuoWebTokenProvider organizationDuoWebTokenProvider, IOrganizationRepository organizationRepository, IOrganizationUserRepository organizationUserRepository, IApplicationCacheService applicationCacheService, CurrentContext currentContext) { _userManager = userManager; _deviceRepository = deviceRepository; _deviceService = deviceService; _userService = userService; _eventService = eventService; _organizationDuoWebTokenProvider = organizationDuoWebTokenProvider; _organizationRepository = organizationRepository; _organizationUserRepository = organizationUserRepository; _applicationCacheService = applicationCacheService; _currentContext = currentContext; } public async Task ValidateAsync(ResourceOwnerPasswordValidationContext context) { var twoFactorToken = context.Request.Raw["TwoFactorToken"]?.ToString(); var twoFactorProvider = context.Request.Raw["TwoFactorProvider"]?.ToString(); var twoFactorRemember = context.Request.Raw["TwoFactorRemember"]?.ToString() == "1"; var twoFactorRequest = !string.IsNullOrWhiteSpace(twoFactorToken) && !string.IsNullOrWhiteSpace(twoFactorProvider); if(string.IsNullOrWhiteSpace(context.UserName)) { await BuildErrorResultAsync(false, context, null); return; } var user = await _userManager.FindByEmailAsync(context.UserName.ToLowerInvariant()); if(user == null || !await _userManager.CheckPasswordAsync(user, context.Password)) { await BuildErrorResultAsync(false, context, user); return; } var twoFactorRequirement = await RequiresTwoFactorAsync(user); if(twoFactorRequirement.Item1) { var twoFactorProviderType = TwoFactorProviderType.Authenticator; // Just defaulting it if(!twoFactorRequest || !Enum.TryParse(twoFactorProvider, out twoFactorProviderType)) { await BuildTwoFactorResultAsync(user, twoFactorRequirement.Item2, context); return; } var verified = await VerifyTwoFactor(user, twoFactorRequirement.Item2, twoFactorProviderType, twoFactorToken); if(!verified && twoFactorProviderType != TwoFactorProviderType.Remember) { await BuildErrorResultAsync(true, context, user); return; } else if(!verified && twoFactorProviderType == TwoFactorProviderType.Remember) { await Task.Delay(2000); // Delay for brute force. await BuildTwoFactorResultAsync(user, twoFactorRequirement.Item2, context); return; } } else { twoFactorRequest = false; twoFactorRemember = false; twoFactorToken = null; } var device = await SaveDeviceAsync(user, context); await BuildSuccessResultAsync(user, context, device, twoFactorRequest && twoFactorRemember); return; } private async Task BuildSuccessResultAsync(User user, ResourceOwnerPasswordValidationContext context, Device device, bool sendRememberToken) { await _eventService.LogUserEventAsync(user.Id, EventType.User_LoggedIn); var claims = new List<Claim>(); if(device != null) { claims.Add(new Claim("device", device.Identifier)); } var customResponse = new Dictionary<string, object>(); if(!string.IsNullOrWhiteSpace(user.PrivateKey)) { customResponse.Add("PrivateKey", user.PrivateKey); } if(!string.IsNullOrWhiteSpace(user.Key)) { customResponse.Add("Key", user.Key); } if(sendRememberToken) { var token = await _userManager.GenerateTwoFactorTokenAsync(user, TwoFactorProviderType.Remember.ToString()); customResponse.Add("TwoFactorToken", token); } context.Result = new GrantValidationResult(user.Id.ToString(), "Application", identityProvider: "bitwarden", claims: claims.Count > 0 ? claims : null, customResponse: customResponse); } private async Task BuildTwoFactorResultAsync(User user, Organization organization, ResourceOwnerPasswordValidationContext context) { var providerKeys = new List<byte>(); var providers = new Dictionary<byte, Dictionary<string, object>>(); var enabledProviders = new List<KeyValuePair<TwoFactorProviderType, TwoFactorProvider>>(); if(organization?.GetTwoFactorProviders() != null) { enabledProviders.AddRange(organization.GetTwoFactorProviders().Where( p => organization.TwoFactorProviderIsEnabled(p.Key))); } if(user.GetTwoFactorProviders() != null) { enabledProviders.AddRange( user.GetTwoFactorProviders().Where(p => user.TwoFactorProviderIsEnabled(p.Key))); } if(!enabledProviders.Any()) { await BuildErrorResultAsync(false, context, user); return; } foreach(var provider in enabledProviders) { providerKeys.Add((byte)provider.Key); var infoDict = await BuildTwoFactorParams(organization, user, provider.Key, provider.Value); providers.Add((byte)provider.Key, infoDict); } context.Result = new GrantValidationResult(TokenRequestErrors.InvalidGrant, "Two factor required.", new Dictionary<string, object> { { "TwoFactorProviders", providers.Keys }, { "TwoFactorProviders2", providers } }); if(enabledProviders.Count() == 1 && enabledProviders.First().Key == TwoFactorProviderType.Email) { // Send email now if this is their only 2FA method await _userService.SendTwoFactorEmailAsync(user); } } private async Task BuildErrorResultAsync(bool twoFactorRequest, ResourceOwnerPasswordValidationContext context, User user) { if(user != null) { await _eventService.LogUserEventAsync(user.Id, twoFactorRequest ? EventType.User_FailedLogIn2fa : EventType.User_FailedLogIn); } await Task.Delay(2000); // Delay for brute force. context.Result = new GrantValidationResult(TokenRequestErrors.InvalidGrant, customResponse: new Dictionary<string, object> {{ "ErrorModel", new ErrorResponseModel(twoFactorRequest ? "Two-step token is invalid. Try again." : "Username or password is incorrect. Try again.") }}); } public async Task<Tuple<bool, Organization>> RequiresTwoFactorAsync(User user) { var individualRequired = _userManager.SupportsUserTwoFactor && await _userManager.GetTwoFactorEnabledAsync(user) && (await _userManager.GetValidTwoFactorProvidersAsync(user)).Count > 0; Organization firstEnabledOrg = null; var orgs = (await _currentContext.OrganizationMembershipAsync(_organizationUserRepository, user.Id)) .Where(o => o.Status == OrganizationUserStatusType.Confirmed).ToList(); if(orgs.Any()) { var orgAbilities = await _applicationCacheService.GetOrganizationAbilitiesAsync(); var twoFactorOrgs = orgs.Where(o => OrgUsing2fa(orgAbilities, o.OrganizationId)); if(twoFactorOrgs.Any()) { var userOrgs = await _organizationRepository.GetManyByUserIdAsync(user.Id); firstEnabledOrg = userOrgs.FirstOrDefault( o => orgs.Any(om => om.OrganizationId == o.Id) && o.TwoFactorIsEnabled()); } } return new Tuple<bool, Organization>(individualRequired || firstEnabledOrg != null, firstEnabledOrg); } private bool OrgUsing2fa(IDictionary<Guid, OrganizationAbility> orgAbilities, Guid orgId) { return orgAbilities != null && orgAbilities.ContainsKey(orgId) && orgAbilities[orgId].Enabled && orgAbilities[orgId].Using2fa; } private Device GetDeviceFromRequest(ResourceOwnerPasswordValidationContext context) { var deviceIdentifier = context.Request.Raw["DeviceIdentifier"]?.ToString(); var deviceType = context.Request.Raw["DeviceType"]?.ToString(); var deviceName = context.Request.Raw["DeviceName"]?.ToString(); var devicePushToken = context.Request.Raw["DevicePushToken"]?.ToString(); if(string.IsNullOrWhiteSpace(deviceIdentifier) || string.IsNullOrWhiteSpace(deviceType) || string.IsNullOrWhiteSpace(deviceName) || !Enum.TryParse(deviceType, out DeviceType type)) { return null; } return new Device { Identifier = deviceIdentifier, Name = deviceName, Type = type, PushToken = string.IsNullOrWhiteSpace(devicePushToken) ? null : devicePushToken }; } private async Task<bool> VerifyTwoFactor(User user, Organization organization, TwoFactorProviderType type, string token) { switch(type) { case TwoFactorProviderType.Authenticator: case TwoFactorProviderType.Duo: case TwoFactorProviderType.YubiKey: case TwoFactorProviderType.U2f: case TwoFactorProviderType.Remember: if(type != TwoFactorProviderType.Remember && !user.TwoFactorProviderIsEnabled(type)) { return false; } return await _userManager.VerifyTwoFactorTokenAsync(user, type.ToString(), token); case TwoFactorProviderType.Email: if(!user.TwoFactorProviderIsEnabled(type)) { return false; } return await _userService.VerifyTwoFactorEmailAsync(user, token); case TwoFactorProviderType.OrganizationDuo: if(!organization?.TwoFactorProviderIsEnabled(type) ?? true) { return false; } return await _organizationDuoWebTokenProvider.ValidateAsync(token, organization, user); default: return false; } } private async Task<Dictionary<string, object>> BuildTwoFactorParams(Organization organization, User user, TwoFactorProviderType type, TwoFactorProvider provider) { switch(type) { case TwoFactorProviderType.Duo: case TwoFactorProviderType.U2f: case TwoFactorProviderType.Email: case TwoFactorProviderType.YubiKey: if(!user.TwoFactorProviderIsEnabled(type)) { return null; } var token = await _userManager.GenerateTwoFactorTokenAsync(user, type.ToString()); if(type == TwoFactorProviderType.Duo) { return new Dictionary<string, object> { ["Host"] = provider.MetaData["Host"], ["Signature"] = token }; } else if(type == TwoFactorProviderType.U2f) { return new Dictionary<string, object> { ["Challenges"] = token }; } else if(type == TwoFactorProviderType.Email) { return new Dictionary<string, object> { ["Email"] = RedactEmail((string)provider.MetaData["Email"]) }; } else if(type == TwoFactorProviderType.YubiKey) { return new Dictionary<string, object> { ["Nfc"] = (bool)provider.MetaData["Nfc"] }; } return null; case TwoFactorProviderType.OrganizationDuo: if(await _organizationDuoWebTokenProvider.CanGenerateTwoFactorTokenAsync(organization)) { return new Dictionary<string, object> { ["Host"] = provider.MetaData["Host"], ["Signature"] = await _organizationDuoWebTokenProvider.GenerateAsync(organization, user) }; } return null; default: return null; } } private static string RedactEmail(string email) { var emailParts = email.Split('@'); string shownPart = null; if(emailParts[0].Length > 2 && emailParts[0].Length <= 4) { shownPart = emailParts[0].Substring(0, 1); } else if(emailParts[0].Length > 4) { shownPart = emailParts[0].Substring(0, 2); } else { shownPart = string.Empty; } string redactedPart = null; if(emailParts[0].Length > 4) { redactedPart = new string('*', emailParts[0].Length - 2); } else { redactedPart = new string('*', emailParts[0].Length - shownPart.Length); } return $"{shownPart}{redactedPart}@{emailParts[1]}"; } private async Task<Device> SaveDeviceAsync(User user, ResourceOwnerPasswordValidationContext context) { var device = GetDeviceFromRequest(context); if(device != null) { var existingDevice = await _deviceRepository.GetByIdentifierAsync(device.Identifier, user.Id); if(existingDevice == null) { device.UserId = user.Id; await _deviceService.SaveAsync(device); return device; } return existingDevice; } return null; } } }
41.7
116
0.564777
[ "MPL-2.0" ]
carloskcheung/fossa-cli
test/fixtures/nuget/src/Core/IdentityServer/ResourceOwnerPasswordValidator.cs
17,099
C#
// This file was modified by Kin Ecosystem (2019) using Newtonsoft.Json; using Kin.Base.responses; using System; using System.Collections.Generic; using System.Text; namespace Kin.Base.responses { public class FriendBotResponse { [JsonProperty(PropertyName = "_links")] public FriendBotResponseLinks Links { get; set; } [JsonProperty(PropertyName = "type")] public string Type { get; set; } [JsonProperty(PropertyName = "title")] public string Title { get; set; } [JsonProperty(PropertyName = "status")] public string Status { get; set; } [JsonProperty(PropertyName = "extras")] public SubmitTransactionResponse.Extras Extras { get; set; } [JsonProperty(PropertyName = "detail")] public string Detail { get; set; } [JsonProperty(PropertyName = "hash")] public string Hash { get; set; } [JsonProperty(PropertyName = "ledger")] public string Ledger { get; set; } [JsonProperty(PropertyName = "envelope_xdr")] public string EnvelopeXdr { get; private set; } [JsonProperty(PropertyName = "result_xdr")] public string ResultXdr { get; private set; } [JsonProperty(PropertyName = "result_meta_xdr")] public string ResultMetaXdr { get; private set; } } }
30.422222
81
0.631118
[ "Apache-2.0" ]
kinecosystem/dotnet-stellar-sdk
kin-base/responses/FriendBotResponse.cs
1,369
C#
namespace BalkanAir.Web.Account { using System; using System.Web; using System.Web.UI; using Microsoft.AspNet.Identity; using Microsoft.AspNet.Identity.Owin; using Auth; using Common; public partial class ChangePassword : Page { protected string SuccessMessage { get; private set; } protected void Page_Load(object sender, EventArgs e) { var manager = Context.GetOwinContext().GetUserManager<ApplicationUserManager>(); if (!this.IsPostBack) { if (!this.Context.User.Identity.IsAuthenticated) { this.Response.Redirect(Pages.LOGIN); } // Determine the sections to render if (this.HasPassword(manager)) { this.changePasswordHolder.Visible = true; } else { this.setPassword.Visible = true; this.changePasswordHolder.Visible = false; } // Render success message var message = Request.QueryString["m"]; if (message != null) { // Strip the query string from action Form.Action = this.ResolveUrl("~/Account/Manage"); } } } protected void ChangePassword_Click(object sender, EventArgs e) { if (this.Page.IsValid) { var manager = Context.GetOwinContext().GetUserManager<ApplicationUserManager>(); var signInManager = Context.GetOwinContext().Get<ApplicationSignInManager>(); IdentityResult result = manager.ChangePassword(User.Identity.GetUserId(), CurrentPassword.Text, NewPassword.Text); if (result.Succeeded) { var user = manager.FindById(User.Identity.GetUserId()); signInManager.SignIn(user, isPersistent: false, rememberBrowser: false); Response.Redirect("~/Account/Manage?m=ChangePwdSuccess"); } else { this.AddErrors(result); } } } protected void SetPassword_Click(object sender, EventArgs e) { if (this.Page.IsValid) { // Create the local login info and link the local account to the user var manager = Context.GetOwinContext().GetUserManager<ApplicationUserManager>(); IdentityResult result = manager.AddPassword(User.Identity.GetUserId(), password.Text); if (result.Succeeded) { Response.Redirect("~/Account/Manage?m=SetPwdSuccess"); } else { this.AddErrors(result); } } } private bool HasPassword(ApplicationUserManager manager) { return manager.HasPassword(User.Identity.GetUserId()); } private void AddErrors(IdentityResult result) { foreach (var error in result.Errors) { ModelState.AddModelError(string.Empty, error); } } } }
33.63
130
0.517693
[ "MIT" ]
itplamen/Balkan-Air
Balkan Air/Web/BalkanAir.Web/Account/ChangePassword.aspx.cs
3,365
C#
using Microsoft.AspNetCore.Mvc; using Naspinski.Data.Interfaces; using Naspinski.FoodTruck.Data; using Naspinski.FoodTruck.Data.Distribution.Handlers.Specials; using Naspinski.FoodTruck.Data.Distribution.Models.Specials; using System.Collections.Generic; using System.Linq; namespace Naspinski.FoodTruck.WebApp.Controllers { [Route("api/specials")] [ApiController] public class SpecialController : BaseController { private ICrudHandler<SpecialModel, FoodTruckContext, SpecialModel> _handler; public SpecialController(FoodTruckContext context) : base(context) { _handler = new SpecialHandler(_context, "system"); } [HttpGet] [Route("")] public Dictionary<string, List<SpecialModel>> Get() { var specials = _handler.GetAll(false).OrderBy(x => x.Begins).ThenBy(x => x.Name); var models = new Dictionary<string, List<SpecialModel>>() { {"Sunday", specials.Where(x => x.IsSunday).ToList() }, {"Monday", specials.Where(x => x.IsMonday).ToList() }, {"Tuesday", specials.Where(x => x.IsTuesday).ToList() }, {"Wednesday", specials.Where(x => x.IsWednesday).ToList() }, {"Thursday", specials.Where(x => x.IsThursday).ToList() }, {"Friday", specials.Where(x => x.IsFriday).ToList() }, {"Saturday", specials.Where(x => x.IsSaturday).ToList() } }; var sortedSpecials = new Dictionary<string, List<SpecialModel>>(); foreach (var key in models.Keys) { if (!models[key].Any()) { models.Remove(key); } } foreach (var key in models.Keys) { var sorted = models[key].Where(x => !x.Name.Contains("happy hour", System.StringComparison.InvariantCultureIgnoreCase)).ToList(); sorted.AddRange(models[key].Where(x => x.Name.Contains("happy hour", System.StringComparison.InvariantCultureIgnoreCase)).ToList()); sortedSpecials.Add(key, sorted); } return sortedSpecials; } } }
41.259259
148
0.587522
[ "MIT" ]
naspinski/FoodTruck.WebApp
Naspinski.FoodTruck.WebApp/Controllers/SpecialController.cs
2,230
C#
using System.Text.Json.Serialization; namespace Essensoft.Paylink.Alipay.Domain { /// <summary> /// AlipayIserviceCcmSwTreeCreateModel Data Structure. /// </summary> public class AlipayIserviceCcmSwTreeCreateModel : AlipayObject { /// <summary> /// 子部门ID,不传为默认部门 /// </summary> [JsonPropertyName("ccs_instance_id")] public string CcsInstanceId { get; set; } /// <summary> /// 类目名称 /// </summary> [JsonPropertyName("name")] public string Name { get; set; } } }
24.652174
66
0.590829
[ "MIT" ]
Frunck8206/payment
src/Essensoft.Paylink.Alipay/Domain/AlipayIserviceCcmSwTreeCreateModel.cs
599
C#
using System; using System.Collections.Generic; using System.Linq; using BlazQ.Player; namespace BlazQ.Game { public class GameSession { public static Dictionary<Int32, String> PlayerKeys { get; } = new Dictionary<int, String> { { 0, "a" }, { 1, "f" }, { 2, "u" }, { 3, "l" }, }; public List<QuestionViewModel> Questions { get; } = new List<QuestionViewModel> { new QuestionViewModel { Text = "What number is NOT a Fibonacci number?", Options = new List<String> { "1", "2", "8", "20" }, CorrectOptionIndex = 3 }, new QuestionViewModel { Text = "What was the name of the supernatural computer in »The hitchhiker's guide to the galaxy«?", Options = new List<String> { "Who cares", "Think deep", "Deep Thought", "42" }, CorrectOptionIndex = 2 }, new QuestionViewModel { Text = "According to Scott Pilgrim, how many vegan law violations can you commit without losing your vegan superpowers?", Options = new List<String> { "4", "3", "2", "1" }, CorrectOptionIndex = 1 }, new QuestionViewModel { Text = "You know what? (F is for Familiy)", Options = new List<String> { "You know what?", "You know what? You know what?", "You know what? You know what? You know what? ", "You know what? You know what? You know what? You know what?" }, CorrectOptionIndex = 1 }, }; public List<PlayerViewModel> Players { get; init; } public List<Player> _internalPlayers = new List<Player>(); public List<GameSessionReportViewModel> Reports { get; private set; } public Int32 QuestionIndex { get; private set; } = 0; private DateTime _started; public GameSession(List<PlayerViewModel> players) { Players = players; _started = DateTime.Now; _internalPlayers = new List<Player>(); foreach (var item in players) { _internalPlayers.Add(new Player(item)); } } public QuestionViewModel GetCurrentQuestion() { return Questions[QuestionIndex]; } public Boolean MoveToNextQuestion() { if (QuestionIndex < Questions.Count - 1) { foreach (var item in _internalPlayers) { item.FinishQuestions(QuestionIndex); } QuestionIndex = QuestionIndex + 1; return true; } if (Reports == null) { Reports = new(); for (int i = 0; i < Players.Count; i++) { var player = Players[i]; GameSessionReportViewModel report = new GameSessionReportViewModel { TotalQuestions = Questions.Count, CorrectAnswers = _internalPlayers[i].CountCorrectAnswers(), WrongAnswers = _internalPlayers[i].CountWrongAnswers(), Duration = DateTime.Now - _started, Player = player, }; Reports.Add(report); } } return false; } public Boolean AnswerWasCorrect(Int32 playerIndex, Int32 questionIndex) { return _internalPlayers[playerIndex].AnswerWasCorrect(questionIndex); } public Boolean SubmitAnswer(Int32 playerIndex, Int32 answerIndex) { Boolean isCorrect = answerIndex == GetCurrentQuestion().CorrectOptionIndex; _internalPlayers[playerIndex].SubmitAnswer(QuestionIndex,isCorrect); return isCorrect; } public Boolean AllPlayersHaveAnswered() { foreach (var item in _internalPlayers) { if(item.HasAnswered(QuestionIndex) == false) { return false; } } return true; } public Boolean PlayerHasAlreadyAnswered(Int32 playerIndex) { return _internalPlayers[playerIndex].HasAnswered(QuestionIndex); } public void Restart() { QuestionIndex = 0; foreach (var item in _internalPlayers) { item.RestAnswers(); } } } }
34.565891
299
0.539807
[ "MIT" ]
just-the-benno/BlazQ
episode4/BlazQ.Episode4Finished/BlazQ.Episode4/Game/GameSession.cs
4,461
C#
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace LollipopUiDemo { public partial class Form1 : Form { public Form1() { InitializeComponent(); } } }
17.761905
37
0.686327
[ "MIT" ]
SaLaaRHuSyN/LollipopUiDemo
LollipopUiDemo/Form1.cs
375
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using SmartSql.Starter.API.Message; using SmartSql.Starter.API.Message.Request.User; using SmartSql.Starter.API.Message.Response.User; using SmartSql.Starter.Entitiy; using SmartSql.Starter.Repository; using SmartSql.Starter.Service; namespace SmartSql.Starter.API.Controllers { [Route("[controller]/[action]")] public class UserController : Controller { private readonly UserService _userService; private readonly IUserRepository _userRepository; public UserController(UserService userService, IUserRepository userRepository) { this._userService = userService; this._userRepository = userRepository; } /// <summary> /// Add /// </summary> /// <param name="request"></param> /// <returns></returns> [HttpPost] public ResponseMessageWraper<long> Add([FromBody]AddRequest request) { var userId = _userService.Add(request); return new ResponseMessageWraper<long> { Body = userId }; } /// <summary> /// Query /// </summary> /// <param name="request"></param> /// <returns></returns> [HttpPost] public ResponseMessageWraper<QueryResponse<Item>> Query([FromBody]QueryRequest request) { var list = _userRepository.Query<Item>(request); return new ResponseMessageWraper<QueryResponse<Item>> { Body = new QueryResponse<Item> { List = list } }; } /// <summary> /// QueryByPage /// </summary> /// <param name="request"></param> /// <returns></returns> [HttpPost] public ResponseMessageWraper<QueryByPageResponse<Item>> QueryByPage([FromBody] Message.Request.User.QueryByPageRequest request) { var list = _userRepository.QueryByPage<Item>(request); var total = _userRepository.GetRecord(request); return new ResponseMessageWraper<QueryByPageResponse<Item>> { Body = new QueryByPageResponse<Item> { List = list, Total = total } }; } /// <summary> /// QueryByPage /// </summary> /// <param name="request"></param> /// <returns></returns> [HttpPost] public ResponseMessageWraper<QueryByPageResponse<Item>> QueryByPageM([FromBody] Message.Request.User.QueryByPageRequest request) { var result = _userRepository.QueryByPage_M<QueryByPageResponse<Item>>(request); return new ResponseMessageWraper<QueryByPageResponse<Item>> { Body = result }; } [HttpPost] public ResponseMessageWraper<User> GetById([FromBody]GetByIdRequest reqMsg) { return new ResponseMessageWraper<User> { Body = _userRepository.GetById(reqMsg.Id) }; } [HttpPost] public ResponseMessageWraper<User> GetById_RealSql([FromBody]GetByIdRequest reqMsg) { return new ResponseMessageWraper<User> { Body = _userRepository.GetById_RealSql(reqMsg.Id) }; } #region Extend [HttpPost] public ResponseMessageWraper<int> AddExtendData([FromBody]AddExtendDataRequest reqMsg) { return new ResponseMessageWraper<int> { Body = _userService.AddExtendData(reqMsg) }; } [HttpPost] public ResponseMessageWraper<int> UpdateExtendData([FromBody]UpdateExtendDataRequest reqMsg) { return new ResponseMessageWraper<int> { Body = _userService.UpdateExtendData(reqMsg) }; } [HttpPost] public ResponseMessageWraper<UserExtendData> GetExtendData([FromBody]GetExtendDataRequest reqMsg) { return new ResponseMessageWraper<UserExtendData> { Body = _userRepository.GetExtendData(reqMsg.UserId) }; } [HttpPost] public ResponseMessageWraper<GetUserInfoResponse> GetUserInfo([FromBody]GetByIdRequest reqMsg) { var data = _userRepository.GetUserInfo<Item>(reqMsg.Id); return new ResponseMessageWraper<GetUserInfoResponse> { Body = new GetUserInfoResponse { User = data.Item1, ExtendData = data.Item2 } }; } #endregion } }
32.668874
136
0.567809
[ "Apache-2.0" ]
KenyonLi/SmartSql-Starter
src/SmartSql.Starter.API/Controllers/UserController.cs
4,935
C#
using System; using System.Collections.Immutable; using System.Linq; string[] input = System.IO.File.ReadAllLines("input.txt"); var lines = input[1] .Split(',') .Select((id, index) => (id: id, offset: index)) .Where(line => line.id != "x") .Select(line => new BusLine(long.Parse(line.id), (long)line.offset)) .ToImmutableArray(); long time = lines[0].Id; long period = lines[0].Id; foreach (var line in lines.Skip(1)) { while ((time + line.Offset) % line.Id != 0) time += period; period *= line.Id; } Console.WriteLine(time); record BusLine(long Id, long Offset);
21.481481
69
0.663793
[ "MIT" ]
Karl255/advent-of-code-2020
AoC2020-13-2/Program.cs
582
C#
using System; using System.Collections.Generic; using System.IO; using System.Threading.Tasks; using System.Xml.Linq; using AccidentalFish.ApplicationSupport.Azure; using AccidentalFish.ApplicationSupport.Azure.Configuration; using AccidentalFish.ApplicationSupport.Core; using AccidentalFish.ApplicationSupport.Core.Configuration; using AccidentalFish.ApplicationSupport.DependencyResolver; using AccidentalFish.ApplicationSupport.Unity; using Microsoft.Practices.Unity; using Microsoft.ServiceBus; using Microsoft.ServiceBus.Messaging; using Microsoft.WindowsAzure.Storage; using Microsoft.WindowsAzure.Storage.Blob; using Microsoft.WindowsAzure.Storage.Queue; using Microsoft.WindowsAzure.Storage.Shared.Protocol; using Microsoft.WindowsAzure.Storage.Table; using Nito.AsyncEx; namespace NewApplicationResources { /// <summary> /// Currently a straight and somewhat painful copy of the PS cmdlet. Am not refactoring as a upcoming version /// is moving to a pluggable configuration system to better support different resource types and providers /// </summary> class Program { private static bool _isVerbose; static void Main(string[] args) { Options options = new Options(); if (CommandLine.Parser.Default.ParseArguments(args, options)) { _isVerbose = options.Verbose; ConsoleColor oldColor = Console.ForegroundColor; try { AsyncContext.Run(() => AsyncMain(options)); } catch (ConsoleAppException ex) { Console.WriteLine(ex.Message); } finally { Console.ForegroundColor = oldColor; } } } private static async Task AsyncMain(Options options) { WriteVerbose($"Processing configuration file {options.Configuration}"); if (!File.Exists(options.Configuration)) { throw new ConsoleAppException("Configuration file does not exist"); } IDependencyResolver dependencyResolver = new UnityApplicationFrameworkDependencyResolver(new UnityContainer()); dependencyResolver.UseCore().UseAzure(); bool useKeyVault = !string.IsNullOrWhiteSpace(options.KeyVaultClientId) && !string.IsNullOrWhiteSpace(options.KeyVaultClientKey) && !string.IsNullOrWhiteSpace(options.KeyVaultUri); IAsyncConfiguration keyVaultConfiguration = null; if (useKeyVault) { dependencyResolver.UseAsyncKeyVaultApplicationConfiguration(options.KeyVaultClientId, options.KeyVaultClientKey, options.KeyVaultUri); keyVaultConfiguration = dependencyResolver.Resolve<IAsyncKeyVaultConfiguration>(); WriteVerbose($"Using key vault {options.KeyVaultUri}"); } WriteVerbose("Reading settings"); string[] settingsFiles = options.Settings.Split(','); ApplicationConfigurationSettings settings = ApplicationConfigurationSettings.FromFiles(settingsFiles); WriteVerbose("Reading configuration"); ApplicationConfiguration configuration = await ApplicationConfiguration.FromFileAsync(options.Configuration, settings, options.CheckForMissingSettings, keyVaultConfiguration, WriteVerbose); ApplyCorsRules(configuration); foreach (ApplicationComponent component in configuration.ApplicationComponents) { if (component.UsesServiceBus) { WriteVerbose($"Creating service bus resources for component {component.Fqn}"); if (!String.IsNullOrWhiteSpace(component.DefaultTopicName)) { NamespaceManager namespaceManager = NamespaceManager.CreateFromConnectionString(component.ServiceBusConnectionString); if (!namespaceManager.TopicExists(component.DefaultTopicName)) { namespaceManager.CreateTopic(new TopicDescription(component.DefaultTopicName)); } if (!String.IsNullOrWhiteSpace(component.DefaultSubscriptionName)) { if ( !namespaceManager.SubscriptionExists(component.DefaultTopicName, component.DefaultSubscriptionName)) { namespaceManager.CreateSubscription( new SubscriptionDescription(component.DefaultTopicName, component.DefaultSubscriptionName)); } } } if (!String.IsNullOrWhiteSpace(component.DefaultBrokeredMessageQueueName)) { NamespaceManager namespaceManager = NamespaceManager.CreateFromConnectionString(component.ServiceBusConnectionString); if (!namespaceManager.QueueExists(component.DefaultBrokeredMessageQueueName)) { namespaceManager.CreateQueue(component.DefaultBrokeredMessageQueueName); } } foreach (ApplicationComponentSetting setting in component.Settings) { string resourceType = setting.ResourceType; if (resourceType != null) { resourceType = resourceType.ToLower(); if (resourceType == "topic") { NamespaceManager namespaceManager = NamespaceManager.CreateFromConnectionString(component.ServiceBusConnectionString); if (!namespaceManager.TopicExists(setting.Value)) { namespaceManager.CreateTopic(new TopicDescription(setting.Value)); } } else if (resourceType == "subscription") { NamespaceManager namespaceManager = NamespaceManager.CreateFromConnectionString(component.ServiceBusConnectionString); string topicPath = setting.Attributes["topic"]; if (!namespaceManager.TopicExists(topicPath)) { namespaceManager.CreateTopic(new TopicDescription(topicPath)); } if (!namespaceManager.SubscriptionExists(topicPath, setting.Value)) { namespaceManager.CreateSubscription(new SubscriptionDescription(topicPath, setting.Value)); } } else if (resourceType == "brokered-message-queue") { NamespaceManager namespaceManager = NamespaceManager.CreateFromConnectionString(component.ServiceBusConnectionString); if (!namespaceManager.QueueExists(setting.Value)) { namespaceManager.CreateQueue(setting.Value); } } } } } if (component.UsesAzureStorage) { CloudStorageAccount storageAccount = CloudStorageAccount.Parse(component.StorageAccountConnectionString); if (!string.IsNullOrWhiteSpace(component.DefaultBlobContainerName)) { CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient(); CloudBlobContainer blobContainer = blobClient.GetContainerReference(component.DefaultBlobContainerName); blobContainer.CreateIfNotExists( BlobContainerPublicAccessType(component.DefaultBlobContainerAccessType)); WriteVerbose($"Creating blob container {component.DefaultBlobContainerName} in {storageAccount.BlobEndpoint}"); if (component.Uploads != null) { foreach (string uploadFilename in component.Uploads) { string fullUploadFilename = Path.Combine(Path.GetDirectoryName(options.Configuration), uploadFilename); CloudBlockBlob blob = blobContainer.GetBlockBlobReference(Path.GetFileName(uploadFilename)); blob.UploadFromFile(fullUploadFilename); WriteVerbose($"Uploading file {uploadFilename} to blob container {component.DefaultBlobContainerName}"); } } } if (!string.IsNullOrWhiteSpace(component.DefaultLeaseBlockName)) { CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient(); CloudBlobContainer blobContainer = blobClient.GetContainerReference(component.DefaultLeaseBlockName); blobContainer.CreateIfNotExists( BlobContainerPublicAccessType(component.DefaultBlobContainerAccessType)); WriteVerbose($"Creating lease block container {component.DefaultLeaseBlockName} in {storageAccount.BlobEndpoint}"); } if (!string.IsNullOrWhiteSpace(component.DefaultQueueName)) { CloudQueueClient queueClient = storageAccount.CreateCloudQueueClient(); CloudQueue queue = queueClient.GetQueueReference(component.DefaultQueueName); queue.CreateIfNotExists(); WriteVerbose($"Creating queue {component.DefaultQueueName} in {storageAccount.QueueEndpoint}"); } if (!string.IsNullOrWhiteSpace(component.DefaultTableName)) { CloudTableClient tableClient = storageAccount.CreateCloudTableClient(); CloudTable table = tableClient.GetTableReference(component.DefaultTableName); table.CreateIfNotExists(); WriteVerbose($"Creating table {component.DefaultTableName} in {storageAccount.TableEndpoint}"); if (!string.IsNullOrWhiteSpace(component.TableData)) { XDocument document; string tableDataFilename = Path.Combine(Path.GetDirectoryName(options.Configuration), component.TableData); try { using (StreamReader reader = new StreamReader(tableDataFilename)) { document = XDocument.Load(reader); } } catch (Exception ex) { document = null; WriteVerbose($"Unable to load table data document {tableDataFilename}. Error: {ex.Message}"); } if (document != null) { UploadTableData(table, document); } } } foreach (ApplicationComponentSetting setting in component.Settings) { string resourceType = setting.ResourceType; if (resourceType != null) { resourceType = resourceType.ToLower(); if (resourceType == "table") { CloudTableClient tableClient = storageAccount.CreateCloudTableClient(); CloudTable table = tableClient.GetTableReference(setting.Value); table.CreateIfNotExists(); WriteVerbose($"Creating table {setting.Value} in {storageAccount.TableEndpoint}"); } else if (resourceType == "queue") { CloudQueueClient queueClient = storageAccount.CreateCloudQueueClient(); CloudQueue queue = queueClient.GetQueueReference(setting.Value); queue.CreateIfNotExists(); WriteVerbose($"Creating queue {setting.Value} in {storageAccount.TableEndpoint}"); } else if (resourceType == "blob-container") { CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient(); CloudBlobContainer blobContainer = blobClient.GetContainerReference(setting.Value); blobContainer.CreateIfNotExists(); WriteVerbose($"Creating blob container {setting.Value} in {storageAccount.TableEndpoint}"); } } } } } } private static void WriteVerbose(string message) { if (_isVerbose) { Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine(message); } } private static BlobContainerPublicAccessType BlobContainerPublicAccessType( BlobContainerPublicAccessTypeEnum value) { switch (value) { case BlobContainerPublicAccessTypeEnum.Off: return Microsoft.WindowsAzure.Storage.Blob.BlobContainerPublicAccessType.Off; case BlobContainerPublicAccessTypeEnum.Blob: return Microsoft.WindowsAzure.Storage.Blob.BlobContainerPublicAccessType.Blob; case BlobContainerPublicAccessTypeEnum.Container: return Microsoft.WindowsAzure.Storage.Blob.BlobContainerPublicAccessType.Container; } throw new InvalidOperationException("Invalid blob access type"); } private static void UploadTableData(CloudTable table, XDocument document) { foreach (XElement xEntity in document.Root.Elements("entity")) { string partitionKey = xEntity.Element("PartitionKey").Value; XElement xRowKey = xEntity.Element("RowKey"); string rowKey = xRowKey != null ? xRowKey.Value : ""; DynamicTableEntity tableEntity = new DynamicTableEntity(partitionKey, rowKey); foreach (XElement xProperty in xEntity.Elements()) { if (xProperty.Name != "PartitionKey" && xProperty.Name != "RowKey") { EntityProperty property = GetEntityProperty(xProperty); tableEntity[xProperty.Name.LocalName] = property; } } table.Execute(TableOperation.InsertOrReplace(tableEntity)); } } private static EntityProperty GetEntityProperty(XElement xProperty) { XAttribute type = xProperty.Attribute("type"); if (type != null) { return GetEntityPropertyForType(type.Value, xProperty.Value); } else { return GetEntityPropertyByInference(xProperty.Value); } } private static EntityProperty GetEntityPropertyByInference(string value) { DateTime dateTimeValue; DateTimeOffset dateTimeOffsetValue; Guid guidValue; double doubleValue; bool boolValue; if (Guid.TryParse(value, out guidValue)) { return new EntityProperty(guidValue); } if (DateTimeOffset.TryParse(value, out dateTimeOffsetValue)) { return new EntityProperty(dateTimeOffsetValue); } if (DateTime.TryParse(value, out dateTimeValue)) { return new EntityProperty(dateTimeValue); } if (bool.TryParse(value, out boolValue)) { return new EntityProperty(boolValue); } if (double.TryParse(value, out doubleValue)) { return new EntityProperty(doubleValue); } return new EntityProperty(value); } private static EntityProperty GetEntityPropertyForType(string type, string value) { if (type == "datetime") { DateTime? typedValue = string.IsNullOrWhiteSpace(value) ? null : new DateTime?(DateTime.Parse(value)); return new EntityProperty(typedValue); } if (type == "datetimeoffset") { DateTimeOffset? typedValue = string.IsNullOrWhiteSpace(value) ? null : new DateTimeOffset?(DateTimeOffset.Parse(value)); return new EntityProperty(typedValue); } if (type == "guid") { Guid? typedValue = string.IsNullOrWhiteSpace(value) ? null : new Guid?(Guid.Parse(value)); return new EntityProperty(typedValue); } if (type == "int") { int? typedValue = string.IsNullOrWhiteSpace(value) ? null : new int?(int.Parse(value)); return new EntityProperty(typedValue); } if (type == "double") { double? typedValue = string.IsNullOrWhiteSpace(value) ? null : new double?(double.Parse(value)); return new EntityProperty(typedValue); } if (type == "long") { long? typedValue = string.IsNullOrWhiteSpace(value) ? null : new long?(long.Parse(value)); return new EntityProperty(typedValue); } if (type == "bool") { bool? typedValue = string.IsNullOrWhiteSpace(value) ? null : new bool?(bool.Parse(value)); return new EntityProperty(typedValue); } if (type == "string") { return new EntityProperty(value); } throw new InvalidOperationException($"Type {type} not understood"); } private static void ApplyCorsRules(ApplicationConfiguration configuration) { foreach (ApplicationStorageAccount storageAccount in configuration.StorageAccounts.Values) { CloudStorageAccount cloudStorageAccount = null; CloudTableClient tableClient = null; ServiceProperties tableProperties = null; CloudBlobClient blobClient = null; ServiceProperties blobProperties = null; CloudQueueClient queueClient = null; ServiceProperties queueProperties = null; foreach (ApplicationCorsRule rule in storageAccount.CorsRules) { if (cloudStorageAccount == null) { cloudStorageAccount = CloudStorageAccount.Parse(storageAccount.ConnectionString); } if (rule.ApplyToTables) { if (tableClient == null) { tableClient = cloudStorageAccount.CreateCloudTableClient(); tableProperties = tableClient.GetServiceProperties(); } tableProperties.Cors.CorsRules.Add(CreateCorsRule(rule)); } if (rule.ApplyToQueues) { if (queueClient == null) { queueClient = cloudStorageAccount.CreateCloudQueueClient(); queueProperties = queueClient.GetServiceProperties(); } queueProperties.Cors.CorsRules.Add(CreateCorsRule(rule)); } if (rule.ApplyToBlobs) { if (blobClient == null) { blobClient = cloudStorageAccount.CreateCloudBlobClient(); blobProperties = blobClient.GetServiceProperties(); } blobProperties.Cors.CorsRules.Add(CreateCorsRule(rule)); } } tableClient?.SetServiceProperties(tableProperties); blobClient?.SetServiceProperties(blobProperties); queueClient?.SetServiceProperties(queueProperties); } } private static CorsRule CreateCorsRule(ApplicationCorsRule rule) { return new CorsRule { AllowedHeaders = new List<string>(rule.AllowedHeaders.Split(',')), AllowedMethods = GetCorsMethods(rule.AllowedVerbs), AllowedOrigins = new List<string>(rule.AllowedOrigins.Split(',')), ExposedHeaders = new List<string>(rule.ExposedHeaders.Split(',')), MaxAgeInSeconds = rule.MaxAgeSeconds }; } private static CorsHttpMethods GetCorsMethods(string verbString) { Dictionary<string, CorsHttpMethods> lookup = new Dictionary<string, CorsHttpMethods> { {"PUT", CorsHttpMethods.Put}, {"POST", CorsHttpMethods.Post}, {"GET", CorsHttpMethods.Get}, {"DELETE", CorsHttpMethods.Delete}, {"HEAD", CorsHttpMethods.Head}, {"OPTIONS", CorsHttpMethods.Options}, {"TRACE", CorsHttpMethods.Trace}, {"MERGE", CorsHttpMethods.Merge}, {"CONNECT", CorsHttpMethods.Connect} }; CorsHttpMethods result = CorsHttpMethods.None; string[] verbs = verbString.Split(','); foreach (string verb in verbs) { result |= lookup[verb]; } return result; } } }
46.717092
192
0.523571
[ "MIT" ]
JamesRandall/AccidentalFish.ApplicationSupport
Source/CmdLine/NewApplicationResources/Program.cs
23,781
C#
using System; using System.IO; using System.Linq; using System.Text; using RT.TagSoup; using RT.Util; using RT.Util.ExtensionMethods; namespace KtaneStuff { static class CheapCheckout { [Flags] enum Categories { None = 0, FixedPrice = 1 << 0, Sweet = 1 << 1, Fruit = 1 << 2, ContainsS = 1 << 3 } public static void DoCheatSheet() { var items = Ut.NewArray( new { Name = "Candy Canes", Price = 3.51m }, new { Name = "Socks", Price = 6.97m }, new { Name = "Lotion", Price = 7.97m }, new { Name = "Cheese", Price = 4.49m }, new { Name = "Mints", Price = 6.39m }, new { Name = "Grape Jelly", Price = 2.98m }, new { Name = "Honey", Price = 8.25m }, new { Name = "Sugar", Price = 2.08m }, new { Name = "Soda", Price = 2.05m }, new { Name = "Tissues", Price = 3.94m }, new { Name = "White Bread", Price = 2.43m }, new { Name = "Canola Oil", Price = 2.28m }, new { Name = "Mustard", Price = 2.36m }, new { Name = "Deodorant", Price = 3.97m }, new { Name = "White Milk", Price = 3.62m }, new { Name = "Pasta Sauce", Price = 2.30m }, new { Name = "Lollipops", Price = 2.61m }, new { Name = "Cookies", Price = 2.00m }, new { Name = "Paper Towels", Price = 9.46m }, new { Name = "Tea", Price = 2.35m }, new { Name = "Coffee Beans", Price = 7.85m }, new { Name = "Mayonnaise", Price = 3.99m }, new { Name = "Chocolate Milk", Price = 5.68m }, new { Name = "Fruit Punch", Price = 2.08m }, new { Name = "Potato Chips", Price = 3.25m }, new { Name = "Shampoo", Price = 4.98m }, new { Name = "Toothpaste", Price = 2.50m }, new { Name = "Peanut Butter", Price = 5.00m }, new { Name = "Gum", Price = 1.12m }, new { Name = "Water Bottles", Price = 9.37m }, new { Name = "Spaghetti", Price = 2.92m }, new { Name = "Chocolate Bar", Price = 2.10m }, new { Name = "Ketchup", Price = 3.59m }, new { Name = "Cereal", Price = 4.19m }); var itemsLb = Ut.NewArray( new { Name = "Turkey", Price = 2.98m }, new { Name = "Chicken", Price = 1.99m }, new { Name = "Steak", Price = 4.97m }, new { Name = "Pork", Price = 4.14m }, new { Name = "Lettuce", Price = 1.10m }, new { Name = "Potatoes", Price = 0.68m }, new { Name = "Tomatoes", Price = 1.80m }, new { Name = "Broccoli", Price = 1.39m }, new { Name = "Oranges", Price = 0.80m }, new { Name = "Lemons", Price = 1.74m }, new { Name = "Bananas", Price = 0.87m }, new { Name = "Grapefruit", Price = 1.08m }); var fruits = new[] { "Bananas", "Grapefruit", "Lemons", "Oranges", "Tomatoes" }; var sweets = new[] { "Candy Canes", "Mints", "Honey", "Soda", "Lollipops", "Gum", "Chocolate Bar", "Fruit Punch", "Cookies", "Sugar", "Grape Jelly" }; var days = Ut.NewArray( new { Name = "Monday", FlavourText = "Meddle with murderous money on Malleable Monday!", Rules = Ut.NewArray( new { Name = "1/3|5", Rule = Ut.Lambda((decimal d, Categories categories) => categories.HasFlag(Categories.FixedPrice) ? decimal.Round(d * .85m, 2, MidpointRounding.AwayFromZero) : d) }, new { Name = "2/4|6", Rule = Ut.Lambda((decimal d, Categories categories) => !categories.HasFlag(Categories.FixedPrice) ? decimal.Round(d * .85m, 2, MidpointRounding.AwayFromZero) : d) }) }, new { Name = "Tuesday", FlavourText = "Tickle your tots throwing tremendous tantrums on Troublesome Tuesday!", Rules = Ut.NewArray(new { Name = "", Rule = Ut.Lambda((decimal d, Categories categories) => categories.HasFlag(Categories.FixedPrice) ? d + ((int) (d * 100) - 1) % 9 + 1 : d) }) }, new { Name = "Wednesday", FlavourText = "Wander the winds in the Wild West on Wacky Wednesday!", Rules = Ut.NewArray(new { Name = "", Rule = Ut.Lambda((decimal d, Categories categories) => { int val = (int) (d % 10m); int val2 = (int) (d * 10m) % 10; int val3 = (int) (d * 100m) % 10; int highest = Math.Max(Math.Max(val, val2), val3); int lowest = Math.Min(Math.Min(val, val2), val3); return decimal.Parse(d.ToString("N2").Where(ch => ch != '.').Select(ch => ch - '0').Select(dgt => dgt == highest ? lowest : dgt == lowest ? highest : dgt).JoinString()) * .01m; }) }) }, new { Name = "Thursday", FlavourText = "Throw out your thunderous things throughout Thrilling Thursday!", Rules = Ut.NewArray( new { Name = "1/3|5", Rule = Ut.Lambda((decimal d, Categories categories) => decimal.Round(d / 2, 2, MidpointRounding.AwayFromZero)) }, new { Name = "2/4|6", Rule = Ut.Lambda((decimal d, Categories categories) => d) }) }, new { Name = "Friday", FlavourText = "Fancy your fellow fleshy friends on Fruity Friday!", Rules = Ut.NewArray(new { Name = "", Rule = Ut.Lambda((decimal d, Categories categories) => categories.HasFlag(Categories.Fruit) ? decimal.Round(d * 1.25m, 2, MidpointRounding.AwayFromZero) : d) }) }, new { Name = "Saturday", FlavourText = "Stock up your supply of satisfying sugary surprises on Sweet Saturday!", Rules = Ut.NewArray(new { Name = "", Rule = Ut.Lambda((decimal d, Categories categories) => categories.HasFlag(Categories.Sweet) ? decimal.Round(d * .65m, 2, MidpointRounding.AwayFromZero) : d) }) }, new { Name = "Sunday", FlavourText = "Set the scene for seeing smashing stuff on Special Sunday!", Rules = Ut.NewArray(new { Name = "", Rule = Ut.Lambda((decimal d, Categories categories) => categories.HasFlag(Categories.FixedPrice) && categories.HasFlag(Categories.ContainsS) ? d + 2.15m : d) }) } ); File.WriteAllText(@"D:\c\KTANE\Public\HTML\Cheap Checkout cheat sheet (Timwi).html", $@"<!DOCTYPE html> <html class='no-js'> <head> <meta content='text/html; charset=utf-8' http-equiv='Content-Type'> <meta content='IE=edge' http-equiv='X-UA-Compatible'> <title>Cheap Checkout — Keep Talking and Nobody Explodes</title> <meta content='initial-scale=1' name='viewport'> <link href='css/font.css' rel='stylesheet' type='text/css'> <link href='css/normalize.css' rel='stylesheet' type='text/css'> <link href='css/main.css' rel='stylesheet' type='text/css'> <script src='js/highlighter.js'></script> <style> table {{ font-size: 90%; }} table.fixed-price-items {{ float: left; }} table.non-fixed-price-items {{ float: right; margin-top: 2em; }} div.clear {{ clear: both; }} th.item {{ text-align: left; }} </style> </head> <body> <div class='section'> {days.Select((day, ix) => $@" <div class='page page-bg-0{ix + 1}'> <div class='page-header'> <span class='page-header-doc-title'>Keep Talking and Nobody Explodes Mod</span> <span class='page-header-section-title'>Cheap Checkout</span> </div> <div class='page-content'> <h2>On the Subject of Cheap Checkouts on {day.Name}</h2> <p class='flavour-text'>{day.FlavourText} {new[] { 0, 1 }.Select(tblIx => new TABLE { class_ = $"fixed-price-items fixed-price-items-{tblIx + 1}" }._( new TR(new TH("Item"), day.Rules.Select(r => new TH(r.Name.Contains('|') ? r.Name.Split('|')[0] : r.Name))), items.OrderBy(item => item.Name).Skip(23 * tblIx).Take(23).Select(item => new TR(new TH { class_ = "item" }._(item.Name), day.Rules.Select(r => new TD(r.Rule(item.Price, (item.Name.ToLowerInvariant().Contains('s') ? Categories.ContainsS : 0) | (fruits.Contains(item.Name) ? Categories.Fruit : 0) | (sweets.Contains(item.Name) ? Categories.Sweet : 0) | Categories.FixedPrice).ToString("N2")))))).ToString()).JoinString()} {new TABLE { class_ = "non-fixed-price-items" }._( day.Rules.Length == 1 ? new TR(new TH("Item"), day.Rules.Select(r => new[] { "½ lb", "1 lb", "1½ lb" }.Select(x => new TH(x)))) : (object) Ut.NewArray( new TR(new TH { rowspan = 2 }._("Item"), day.Rules.Select(r => new TH { colspan = 3 }._(r.Name.Contains('|') ? r.Name.Split('|')[1] : r.Name))), new TR(day.Rules.Select(r => new[] { "½ lb", "1 lb", "1½ lb" }.Select(x => new TH(x)))) ), itemsLb.OrderBy(item => item.Name).Select(item => new TR(new TH { class_ = "item" }._(item.Name), day.Rules.SelectMany(r => new[] { .5m, 1m, 1.5m }.Select(x => new TD(r.Rule(decimal.Round(item.Price * x, 2, MidpointRounding.AwayFromZero), (item.Name.ToLowerInvariant().Contains('s') ? Categories.ContainsS : 0) | (fruits.Contains(item.Name) ? Categories.Fruit : 0) | (sweets.Contains(item.Name) ? Categories.Sweet : 0)).ToString("N2"))))))).ToString()} <div class='clear'></div> </div> <div class='page-footer relative-footer'>Page {ix + 1} of 7 ({day.Name})</div> </div> ").JoinString()} </div> </body></html> "); } } }
54.346734
258
0.483773
[ "MIT" ]
CaitSith2/KtaneStuff
Src/CheapCheckout.cs
10,823
C#
// *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.Pagerduty.Inputs { public sealed class ServiceAlertGroupingParametersGetArgs : Pulumi.ResourceArgs { /// <summary> /// Alert grouping parameters dependant on `type`. If `type` is set to `intelligent` or empty then `config` can be empty. /// </summary> [Input("config")] public Input<Inputs.ServiceAlertGroupingParametersConfigGetArgs>? Config { get; set; } /// <summary> /// The type of scheduled action. Currently, this must be set to `urgency_change`. /// </summary> [Input("type")] public Input<string>? Type { get; set; } public ServiceAlertGroupingParametersGetArgs() { } } }
32.25
129
0.658915
[ "ECL-2.0", "Apache-2.0" ]
pulumi/pulumi-pagerduty
sdk/dotnet/Inputs/ServiceAlertGroupingParametersGetArgs.cs
1,032
C#
/* * Written by Trevor Barnett, <mr.ullet@gmail.com>, 2015 * Released to the Public Domain. See http://unlicense.org/ or the * UNLICENSE file accompanying this source code. */ using System; using NUnit.Framework; namespace Ullet.Strix.Generic.Tests.Unit { [TestFixture] public class MutableTests { [Test] public void CanCreateWithoutValue() { Assert.That(new Mutable<int>().HasValue, Is.False); } [Test] public void CanCreateWithValue() { var m = new Mutable<double>(3.6); Assert.That( m, Has.Property("HasValue").EqualTo(true) & Has.Property("Value").EqualTo(3.6d).Within(0.000001)); } [Test] public void ThrowsExceptionIfGetValueWhenValueNotSet() { Assert.Throws<InvalidOperationException>( () => ((Func<long>)(() => new Mutable<long>().Value))()); } [Test] public void CanModifyValue() { // ReSharper disable once UseObjectOrCollectionInitializer var m = new Mutable<char>('A'); m.Value = 'B'; Assert.That(m.Value, Is.EqualTo('B')); } [Test] public void ModifyingValueDoesNotCreateANewMutableInstance() { var m = new Mutable<float>(1.0f); var original = m; m.Value = 2.0f; Assert.That(m, Is.SameAs(original)); } [Test] public void CanExplicitlyConvertValueTypeToMutable() { const int value = 73; var m = (Mutable<int>) value; Assert.That( m, Is.InstanceOf<Mutable<int>>() & Has.Property("HasValue").EqualTo(true) & Has.Property("Value").EqualTo(value)); } [Test] public void CanImplicitlyConvertValueTypeToMutable() { const long value = 123; // Assigning to a variable of a different type is an implicit conversion. Mutable<long> m = value; Assert.That( m, Is.InstanceOf<Mutable<long>>() & Has.Property("HasValue").EqualTo(true) & Has.Property("Value").EqualTo(value)); } [Test] public void CanExplicitlyConvertMutableToValueType() { var m = new Mutable<int>(61); var value = (int) m; Assert.That(value, Is.EqualTo(m.Value)); } [Test] public void CanImplicitlyConvertMutableToValueType() { var m = new Mutable<byte>(212); // Assigning to a variable of a different type is an implicit conversion. byte value = m; Assert.That(value, Is.EqualTo(m.Value)); } [Test] public void ThrowsExceptionIfConvertToValueTypeWhenValueNotSet() { Assert.Throws<InvalidOperationException>( () => ((Func<long>)(() => (long)new Mutable<long>()))()); } [Test] public void CanExplicitlyConvertMutableWithValueToNullableOfValueType() { var m = new Mutable<int>(1); var value = (int?)m; Assert.That(value.HasValue, Is.True); // ReSharper disable once PossibleInvalidOperationException Assert.That(value.Value, Is.EqualTo(m.Value)); } [Test] public void CanExplicitlyConvertMutableWithoutValueToNullableOfValueType() { var m = new Mutable<int>(); var value = (int?)m; Assert.That(value.HasValue, Is.False); } [Test] public void CanImplicitlyConvertMutableWithValueToNullableOfValueType() { var m = new Mutable<int>(1); int? value = m; // ReSharper disable once ConditionIsAlwaysTrueOrFalse Assert.That(value.HasValue, Is.True); // ReSharper disable once PossibleInvalidOperationException Assert.That(value.Value, Is.EqualTo(m.Value)); } [Test] public void CanImplicitlyConvertMutableWithoutValueToNullableOfValueType() { var m = new Mutable<int>(); int? value = m; // ReSharper disable once ConditionIsAlwaysTrueOrFalse Assert.That(value.HasValue, Is.False); } [Test] public void ThrowsExceptionIfConvertNullToValueType() { Mutable<long> m = null; // ReSharper disable once ExpressionIsAlwaysNull Assert.Throws<NullReferenceException>( () => ((Func<long>)(() => (long)m))()); } [Test] public void ConvertsNullToNullableOfValueTypeWithoutValueSet() { Mutable<double> m = null; // ReSharper disable once ExpressionIsAlwaysNull var nullable = (double?) m; Assert.That(nullable.HasValue, Is.False); } } }
23.725806
79
0.625878
[ "Unlicense" ]
ullet/some_csharp_code
Ullet/Strix/Tests/Unit/Generic/MutableTests.cs
4,415
C#
using LINGYUN.Abp.Saas.Editions; using LINGYUN.Abp.Saas.Tenants; using Microsoft.EntityFrameworkCore; using Volo.Abp; using Volo.Abp.EntityFrameworkCore.Modeling; namespace LINGYUN.Abp.Saas.EntityFrameworkCore; public static class AbpSaasDbContextModelCreatingExtensions { public static void ConfigureSaas( this ModelBuilder builder) { Check.NotNull(builder, nameof(builder)); if (builder.IsTenantOnlyDatabase()) { return; } builder.Entity<Edition>(b => { b.ToTable(AbpSaasDbProperties.DbTablePrefix + "Editions", AbpSaasDbProperties.DbSchema); b.ConfigureByConvention(); b.Property(t => t.DisplayName) .HasMaxLength(EditionConsts.MaxDisplayNameLength) .IsRequired(); b.HasIndex(u => u.DisplayName); b.ApplyObjectExtensionMappings(); }); builder.Entity<Tenant>(b => { b.ToTable(AbpSaasDbProperties.DbTablePrefix + "Tenants", AbpSaasDbProperties.DbSchema); b.ConfigureByConvention(); b.Property(t => t.Name).IsRequired().HasMaxLength(TenantConsts.MaxNameLength); b.HasMany(u => u.ConnectionStrings).WithOne().HasForeignKey(uc => uc.TenantId).IsRequired(); b.HasIndex(u => u.Name); b.ApplyObjectExtensionMappings(); }); builder.Entity<TenantConnectionString>(b => { b.ToTable(AbpSaasDbProperties.DbTablePrefix + "TenantConnectionStrings", AbpSaasDbProperties.DbSchema); b.ConfigureByConvention(); b.HasKey(x => new { x.TenantId, x.Name }); b.Property(cs => cs.Name).IsRequired().HasMaxLength(TenantConnectionStringConsts.MaxNameLength); b.Property(cs => cs.Value).IsRequired().HasMaxLength(TenantConnectionStringConsts.MaxValueLength); b.ApplyObjectExtensionMappings(); }); builder.TryConfigureObjectExtensions<SaasDbContext>(); } }
29.926471
115
0.640295
[ "MIT" ]
colinin/abp-next-admin
aspnet-core/modules/saas/LINGYUN.Abp.Saas.EntityFrameworkCore/LINGYUN/Abp/Saas/EntityFrameworkCore/AbpSaasDbContextModelCreatingExtensions.cs
2,035
C#
namespace PathfinderRPG.Entities.Races.Languages { public class Elven : Language { /// <summary> /// Sets the display name for the specific language /// </summary> protected override void SetDisplayName() { DisplayName = "Elven"; } } }
23
60
0.537267
[ "MIT" ]
UnityDevelopment/PathFinderRPG
Assets/Scripts/Entities/Langauges/Elven.cs
324
C#
using System; using System.IO; using System.Linq; using System.Collections.Generic; using static System.IO.Directory; namespace CodeDocs.Generator { public static class Generate { public static void Examples() { int counter = 0; var nestedType1 = (new ExampleTemplate("struct", "NestedType1", () => (++counter).ToString(), "")).TransformText(); var nestedType2 = (new ExampleTemplate("class", "NestedType2", () => (++counter).ToString(), nestedType1)).TransformText(); var primaryType = (new ExampleTemplate("class", "PrimaryType", () => (++counter).ToString(), nestedType2)).TransformText(); var wrapper = (new ExampleWrapperTemplate(primaryType, counter)).TransformText(); File.WriteAllText("../CodeDocs.Examples/Generated.cs", wrapper); } const string workingPath = "../CodeDocs/Generated/"; public static void CodeDocAttributes() { Reset(); GenerateAttributes(); } static void Reset() { Delete(workingPath, true); CreateDirectory(workingPath); } static void GenerateAttributes() => Definition.List.ForEach(GenerateFile); static void GenerateFile(Definition definition) => File.WriteAllText($"{workingPath}{definition.Name}.generated.cs", GenerateText(definition)); static string GenerateText(Definition definition) => (new CodeDocAttributeTemplate(definition)).TransformText(); } }
27.684211
135
0.619138
[ "MIT" ]
rskopecek/CodeDocs
src/CodeDocs.Generator/Generate.cs
1,580
C#
// <copyright file="RemoteTimeouts.cs" company="WebDriver Committers"> // Copyright 2007-2011 WebDriver committers // Copyright 2007-2011 Google Inc. // Portions copyright 2011 Software Freedom Conservancy // // 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. // </copyright> using System; using System.Collections.Generic; using System.Text; namespace OpenQA.Selenium.Remote { /// <summary> /// Defines the interface through which the user can define timeouts. /// </summary> internal class RemoteTimeouts : ITimeouts { private RemoteWebDriver driver; /// <summary> /// Initializes a new instance of the RemoteTimeouts class /// </summary> /// <param name="driver">The driver that is currently in use</param> public RemoteTimeouts(RemoteWebDriver driver) { this.driver = driver; } #region ITimeouts Members /// <summary> /// Specifies the amount of time the driver should wait when searching for an /// element if it is not immediately present. /// </summary> /// <param name="timeToWait">A <see cref="TimeSpan"/> structure defining the amount of time to wait.</param> /// <returns>A self reference</returns> /// <remarks> /// When searching for a single element, the driver should poll the page /// until the element has been found, or this timeout expires before throwing /// a <see cref="NoSuchElementException"/>. When searching for multiple elements, /// the driver should poll the page until at least one element has been found /// or this timeout has expired. /// <para> /// Increasing the implicit wait timeout should be used judiciously as it /// will have an adverse effect on test run time, especially when used with /// slower location strategies like XPath. /// </para> /// </remarks> public ITimeouts ImplicitlyWait(TimeSpan timeToWait) { // The *correct* approach to this timeout is to use the below // commented line of code and remove the remainder of this method. // However, we need to use the hard-coded timeout commmand for now, // since all drivers don't yet understand the generic "timeouts" // command endpoint. // this.ExecuteSetTimeout("implicit", timeToWait); double milliseconds = timeToWait.TotalMilliseconds; if (timeToWait == TimeSpan.MinValue) { milliseconds = -1; } Dictionary<string, object> parameters = new Dictionary<string, object>(); parameters.Add("ms", milliseconds); this.driver.InternalExecute(DriverCommand.ImplicitlyWait, parameters); return this; } /// <summary> /// Specifies the amount of time the driver should wait when executing JavaScript asynchronously. /// </summary> /// <param name="timeToWait">A <see cref="TimeSpan"/> structure defining the amount of time to wait. /// Setting this parameter to <see cref="TimeSpan.MinValue"/> will allow the script to run indefinitely.</param> /// <returns>A self reference</returns> public ITimeouts SetScriptTimeout(TimeSpan timeToWait) { // The *correct* approach to this timeout is to use the below // commented line of code and remove the remainder of this method. // However, we need to use the hard-coded timeout commmand for now, // since all drivers don't yet understand the generic "timeouts" // command endpoint. // this.ExecuteSetTimeout("script", timeToWait); double milliseconds = timeToWait.TotalMilliseconds; if (timeToWait == TimeSpan.MinValue) { milliseconds = -1; } Dictionary<string, object> parameters = new Dictionary<string, object>(); parameters.Add("ms", milliseconds); this.driver.InternalExecute(DriverCommand.SetAsyncScriptTimeout, parameters); return this; } /// <summary> /// Specifies the amount of time the driver should wait for a page to load when setting the <see cref="IWebDriver.Url"/> property. /// </summary> /// <param name="timeToWait">A <see cref="TimeSpan"/> structure defining the amount of time to wait. /// Setting this parameter to <see cref="TimeSpan.MinValue"/> will allow the page to load indefinitely.</param> /// <returns>A self reference</returns> public ITimeouts SetPageLoadTimeout(TimeSpan timeToWait) { this.ExecuteSetTimeout("page load", timeToWait); return this; } #endregion private void ExecuteSetTimeout(string timeoutType, TimeSpan timeToWait) { double milliseconds = timeToWait.TotalMilliseconds; if (timeToWait == TimeSpan.MinValue) { milliseconds = -1; } Dictionary<string, object> parameters = new Dictionary<string, object>(); parameters.Add("type", timeoutType); parameters.Add("ms", milliseconds); this.driver.InternalExecute(DriverCommand.SetTimeout, parameters); } } }
44.067164
138
0.633531
[ "Apache-2.0" ]
GiannisPapadakis/selenium
dotnet/src/webdriver/Remote/RemoteTimeouts.cs
5,907
C#
/* Copyright (c) 2017 Marcin Szeniak (https://github.com/Klocman/) Apache License Version 2.0 */ using System; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Drawing; using System.IO; using System.Linq; using System.Windows.Forms; using Klocman.Extensions; using Klocman.Forms; using Klocman.Forms.Tools; using Klocman.Tools; using UninstallTools.Properties; using UninstallTools.Startup; using UninstallTools.Startup.Browser; using UninstallTools.Startup.Normal; using UninstallTools.Startup.Service; using UninstallTools.Startup.Task; namespace UninstallTools.Dialogs { public partial class StartupManagerWindow : Form { private StartupManagerWindow() { InitializeComponent(); comboBoxFilter.SelectedIndex = 0; } private List<StartupEntryBase> AllItems { get; set; } private IEnumerable<StartupEntryBase> Selection { get { return listView1.SelectedItems.Cast<ListViewItem>().Select(x => x.Tag as StartupEntryBase); } } /*private IEnumerable<StartupEntryBase> VisibleItems { get { return listView1.Items.Cast<ListViewItem>().Select(x => x.Tag as StartupEntryBase); } }*/ /// <summary> /// Show startup manager dialog. Returns latest startup entry list. /// </summary> /// <param name="owner">Parent form</param> public static IEnumerable<StartupEntryBase> ShowManagerDialog(Form owner) { using (var window = new StartupManagerWindow()) { if (owner != null) { window.StartPosition = FormStartPosition.CenterParent; window.Icon = owner.Icon; } window.ShowDialog(owner); return window.AllItems; } } public static StartupManagerWindow ShowManagerWindow() { var window = new StartupManagerWindow(); try { window.Icon = ProcessTools.GetIconFromEntryExe(); } catch (Exception e) { Console.WriteLine(e); } return window; } private void buttonExport_Click(object sender, EventArgs e) { exportDialog.ShowDialog(); } private void buttonRefresh_Click(object sender, EventArgs e) { ReloadItems(sender, e); } private void contextMenuStrip1_Opening(object sender, CancelEventArgs e) { e.Cancel = true; moveToRegistryToolStripMenuItem.Enabled = false; CheckState? enableCheckState = null; CheckState? allUserCheckState = null; foreach (var item in Selection) { e.Cancel = false; if (!enableCheckState.HasValue) enableCheckState = item.Disabled ? CheckState.Unchecked : CheckState.Checked; else if (enableCheckState.Value != (item.Disabled ? CheckState.Unchecked : CheckState.Checked)) enableCheckState = CheckState.Indeterminate; if (item is StartupEntry normalStartupEntry) { if (!allUserCheckState.HasValue) allUserCheckState = normalStartupEntry.AllUsers ? CheckState.Checked : CheckState.Unchecked; else if (allUserCheckState.Value != (normalStartupEntry.AllUsers ? CheckState.Checked : CheckState.Unchecked)) allUserCheckState = CheckState.Indeterminate; if (!normalStartupEntry.IsRegKey) moveToRegistryToolStripMenuItem.Enabled = true; } } enableToolStripMenuItem.Enabled = enableCheckState.HasValue; enableToolStripMenuItem.CheckState = enableCheckState ?? CheckState.Unchecked; runForAllUsersToolStripMenuItem.Enabled = allUserCheckState.HasValue; runForAllUsersToolStripMenuItem.CheckState = allUserCheckState ?? CheckState.Unchecked; } private void copyToClipboardToolStripMenuItem_Click(object sender, EventArgs e) { var parts = Selection.Select(x => x.ToLongString()).ToArray(); if (parts.Any()) { try { Clipboard.SetText(string.Join(Environment.NewLine, parts)); } catch (Exception ex) { PremadeDialogs.GenericError(ex); } } } private void DeleteSelected() { if (CustomMessageBox.ShowDialog(this, new CmbBasicSettings( Localisation.StartupManager_Message_Delete_Title, Localisation.StartupManager_Message_Delete_Header, Localisation.StartupManager_Message_Delete_Details, SystemIcons.Question, Buttons.ButtonRemove, Buttons.ButtonCancel)) == CustomMessageBox.PressedButton.Middle) { try { foreach (var item in Selection) { item.Delete(); } } catch (Exception ex) { PremadeDialogs.GenericError(ex); } } } private void deleteToolStripMenuItem_Click(object sender, EventArgs e) { DeleteSelected(); ReloadItems(sender, e); } private void listView1_MouseClick(object sender, MouseEventArgs e) { if (e.Button == MouseButtons.Right) { if (listView1.SelectedItems.Count > 0 && listView1.FocusedItem.Bounds.Contains(e.Location)) { contextMenuStrip.Show(Cursor.Position); } } } private void listView1_MouseDoubleClick(object sender, MouseEventArgs e) { if (listView1.SelectedItems.Count > 0 && listView1.FocusedItem.Bounds.Contains(e.Location)) { openFileLocationToolStripMenuItem_Click(sender, e); } } private void openFileLocationToolStripMenuItem_Click(object sender, EventArgs e) { foreach (var item in Selection) { try { if (item.CommandFilePath == null) throw new IOException(Localisation.Error_InvalidPath + "\n" + item.Command); WindowsTools.OpenExplorerFocusedOnObject(item.CommandFilePath); } catch (Exception ex) { PremadeDialogs.GenericError(ex); } } } private void openLinkLocationToolStripMenuItem_Click(object sender, EventArgs e) { try { StartupManager.OpenStartupEntryLocations(Selection); } catch (Exception ex) { PremadeDialogs.GenericError(ex); } } private void ReloadItems(object sender, EventArgs e) { Cursor = Cursors.WaitCursor; if (listView1.Items.Count < 1) { listView1.Items.Add(Localisation.StartupManager_Loading); listView1.Update(); } SelectionChanged(sender, e); listView1.BeginUpdate(); AllItems = StartupManager.GetAllStartupItems().ToList(); // Get icons if (listView1.SmallImageList == null) listView1.SmallImageList = new ImageList(); listView1.SmallImageList.Images.Clear(); listView1.SmallImageList.Images.Add(SystemIcons.Warning); foreach (var entry in AllItems) { if (entry.CommandFilePath != null && !listView1.SmallImageList.Images.ContainsKey(entry.ProgramName)) { var icon = UninstallToolsGlobalConfig.TryExtractAssociatedIcon(entry.CommandFilePath); if (icon != null) listView1.SmallImageList.Images.Add(entry.ProgramName, icon); } } UpdateList(false); listView1.EndUpdate(); Cursor = Cursors.Default; } private void UpdateList(bool pauseLvUpdates = true) { if (pauseLvUpdates) { Cursor = Cursors.WaitCursor; listView1.BeginUpdate(); } var query = from item in AllItems where comboBoxFilter.SelectedIndex == 0 || comboBoxFilter.SelectedIndex == 1 && item is StartupEntry || comboBoxFilter.SelectedIndex == 2 && item is TaskEntry || comboBoxFilter.SelectedIndex == 3 && item is BrowserHelperEntry || comboBoxFilter.SelectedIndex == 4 && item is ServiceEntry orderby item.ProgramName ascending select new ListViewItem(new[] { item.ProgramName, (!item.Disabled).ToYesNo(), item.Company, item.ParentShortName, item.Command }) { Tag = item, ForeColor = item.Disabled ? SystemColors.GrayText : SystemColors.ControlText, ImageIndex = Math.Max(listView1.SmallImageList.Images.IndexOfKey(item.ProgramName), 0) }; // Populate list items listView1.Items.Clear(); listView1.Items.AddRange(query.ToArray()); if (pauseLvUpdates) { listView1.EndUpdate(); Cursor = Cursors.Default; } } private void runCommandToolStripMenuItem_Click(object sender, EventArgs e) { foreach (var command in Selection) { if (!PremadeDialogs.StartProcessSafely(command.Command)) break; } } private void saveFileDialog1_FileOk(object sender, CancelEventArgs e) { var parts = Selection.Select(x => x.ToLongString()).ToArray(); if (parts.Any()) { try { File.WriteAllText(exportDialog.FileName, string.Join(Environment.NewLine, parts)); } catch (Exception ex) { PremadeDialogs.GenericError(ex); e.Cancel = true; } } } private void SelectionChanged(object sender, EventArgs e) { var sel = listView1.SelectedItems.Count > 0; buttonExport.Enabled = sel; } private void StartupManagerWindow_Shown(object sender, EventArgs e) { Refresh(); ReloadItems(sender, e); } private void enableToolStripMenuItem_Click(object sender, EventArgs e) { enableToolStripMenuItem.CheckState = enableToolStripMenuItem.CheckState == CheckState.Unchecked ? CheckState.Checked : CheckState.Unchecked; foreach (var item in Selection) { try { item.Disabled = enableToolStripMenuItem.CheckState == CheckState.Unchecked; } catch (Exception ex) { PremadeDialogs.GenericError(ex); } } UpdateList(); } private void runForAllUsersToolStripMenuItem_Click(object sender, EventArgs e) { runForAllUsersToolStripMenuItem.CheckState = runForAllUsersToolStripMenuItem.CheckState == CheckState.Unchecked ? CheckState.Checked : CheckState.Unchecked; foreach (var item in Selection.OfType<StartupEntry>()) { try { item.AllUsers = runForAllUsersToolStripMenuItem.CheckState == CheckState.Checked; } catch (Exception ex) { PremadeDialogs.GenericError(ex); } } UpdateList(); } private void moveToRegistryToolStripMenuItem_Click(object sender, EventArgs e) { foreach (var item in Selection.OfType<StartupEntry>()) { try { StartupEntryManager.MoveToRegistry(item); } catch (Exception ex) { PremadeDialogs.GenericError(ex); } } UpdateList(); } private void createBackupToolStripMenuItem_Click(object sender, EventArgs e) { folderBrowserDialog.ShowDialog(this); if (!Directory.Exists(folderBrowserDialog.SelectedPath)) return; foreach (var item in Selection) { try { item.CreateBackup(folderBrowserDialog.SelectedPath); } catch (Exception ex) { PremadeDialogs.GenericError(ex); } } Process.Start(new ProcessStartInfo(folderBrowserDialog.SelectedPath) { UseShellExecute = true }); UpdateList(); } private void comboBoxFilter_SelectedIndexChanged(object sender, EventArgs e) { if (AllItems != null) UpdateList(); } private void buttonCancel_Click(object sender, EventArgs e) { DialogResult = DialogResult.OK; Close(); } } }
34.620609
118
0.512278
[ "Apache-2.0" ]
102464/Bulk-Crap-Uninstaller
source/UninstallTools/Dialogs/StartupManagerWindow.cs
14,785
C#
using Microsoft.WindowsAzure.Storage.Auth; using Microsoft.WindowsAzure.Storage.Blob.Protocol; using Microsoft.WindowsAzure.Storage.Core; using Microsoft.WindowsAzure.Storage.Core.Auth; using Microsoft.WindowsAzure.Storage.Core.Executor; using Microsoft.WindowsAzure.Storage.Core.Util; using Microsoft.WindowsAzure.Storage.RetryPolicies; using Microsoft.WindowsAzure.Storage.Shared.Protocol; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Threading; using System.Threading.Tasks; namespace Microsoft.WindowsAzure.Storage.Blob { public class CloudBlobClient { public AuthenticationScheme AuthenticationScheme { get { throw new System.NotImplementedException(); } set { throw new System.NotImplementedException(); } } public IBufferManager BufferManager { get; set; } public StorageCredentials Credentials { get; private set; } public Uri BaseUri { get { throw new System.NotImplementedException(); } } public StorageUri StorageUri { get; private set; } public BlobRequestOptions DefaultRequestOptions { get; set; } [Obsolete("Use DefaultRequestOptions.RetryPolicy.")] public IRetryPolicy RetryPolicy { get { throw new System.NotImplementedException(); } set { throw new System.NotImplementedException(); } } public string DefaultDelimiter { get { throw new System.NotImplementedException(); } set { throw new System.NotImplementedException(); } } internal bool UsePathStyleUris { get; private set; } public CloudBlobClient(Uri baseUri) : this(baseUri, (StorageCredentials) null) { throw new System.NotImplementedException(); } public CloudBlobClient(Uri baseUri, StorageCredentials credentials) : this(new StorageUri(baseUri), credentials) { throw new System.NotImplementedException(); } public CloudBlobClient(StorageUri storageUri, StorageCredentials credentials) { throw new System.NotImplementedException(); } public virtual Task<ContainerResultSegment> ListContainersSegmentedAsync(BlobContinuationToken currentToken) { throw new System.NotImplementedException(); } public virtual Task<ContainerResultSegment> ListContainersSegmentedAsync(string prefix, BlobContinuationToken currentToken) { throw new System.NotImplementedException(); } public virtual Task<ContainerResultSegment> ListContainersSegmentedAsync(string prefix, ContainerListingDetails detailsIncluded, int? maxResults, BlobContinuationToken currentToken, BlobRequestOptions options, OperationContext operationContext) { throw new System.NotImplementedException(); } public virtual Task<ContainerResultSegment> ListContainersSegmentedAsync(string prefix, ContainerListingDetails detailsIncluded, int? maxResults, BlobContinuationToken currentToken, BlobRequestOptions options, OperationContext operationContext, CancellationToken cancellationToken) { throw new System.NotImplementedException(); } public virtual Task<BlobResultSegment> ListBlobsSegmentedAsync(string prefix, BlobContinuationToken currentToken) { throw new System.NotImplementedException(); } [DoesServiceRequest] public virtual Task<BlobResultSegment> ListBlobsSegmentedAsync(string prefix, bool useFlatBlobListing, BlobListingDetails blobListingDetails, int? maxResults, BlobContinuationToken currentToken, BlobRequestOptions options, OperationContext operationContext) { throw new System.NotImplementedException(); } [DoesServiceRequest] public virtual Task<ICloudBlob> GetBlobReferenceFromServerAsync(Uri blobUri) { throw new System.NotImplementedException(); } [DoesServiceRequest] public virtual Task<ICloudBlob> GetBlobReferenceFromServerAsync(Uri blobUri, AccessCondition accessCondition, BlobRequestOptions options, OperationContext operationContext) { throw new System.NotImplementedException(); } [DoesServiceRequest] public virtual Task<ICloudBlob> GetBlobReferenceFromServerAsync(StorageUri blobUri, AccessCondition accessCondition, BlobRequestOptions options, OperationContext operationContext) { throw new System.NotImplementedException(); } [DoesServiceRequest] public virtual Task<ICloudBlob> GetBlobReferenceFromServerAsync(StorageUri blobUri, AccessCondition accessCondition, BlobRequestOptions options, OperationContext operationContext, CancellationToken cancellationToken) { throw new System.NotImplementedException(); } private RESTCommand<ResultSegment<CloudBlobContainer>> ListContainersImpl(string prefix, ContainerListingDetails detailsIncluded, BlobContinuationToken currentToken, int? maxResults, BlobRequestOptions options) { throw new System.NotImplementedException(); } private RESTCommand<ICloudBlob> GetBlobReferenceImpl(StorageUri blobUri, AccessCondition accessCondition, BlobRequestOptions options) { throw new System.NotImplementedException(); } [DoesServiceRequest] public virtual Task<ServiceProperties> GetServicePropertiesAsync() { throw new System.NotImplementedException(); } public virtual Task<ServiceProperties> GetServicePropertiesAsync(BlobRequestOptions options, OperationContext operationContext) { throw new System.NotImplementedException(); } public virtual Task<ServiceProperties> GetServicePropertiesAsync(BlobRequestOptions options, OperationContext operationContext, CancellationToken cancellationToken) { throw new System.NotImplementedException(); } private RESTCommand<ServiceProperties> GetServicePropertiesImpl(BlobRequestOptions requestOptions) { throw new System.NotImplementedException(); } [DoesServiceRequest] public virtual Task SetServicePropertiesAsync(ServiceProperties properties) { throw new System.NotImplementedException(); } [DoesServiceRequest] public virtual Task SetServicePropertiesAsync(ServiceProperties properties, BlobRequestOptions requestOptions, OperationContext operationContext) { throw new System.NotImplementedException(); } [DoesServiceRequest] public virtual Task SetServicePropertiesAsync(ServiceProperties properties, BlobRequestOptions requestOptions, OperationContext operationContext, CancellationToken cancellationToken) { throw new System.NotImplementedException(); } private RESTCommand<NullType> SetServicePropertiesImpl(ServiceProperties properties, BlobRequestOptions requestOptions) { throw new System.NotImplementedException(); } [DoesServiceRequest] public virtual Task<ServiceStats> GetServiceStatsAsync() { throw new System.NotImplementedException(); } public virtual Task<ServiceStats> GetServiceStatsAsync(BlobRequestOptions options, OperationContext operationContext) { throw new System.NotImplementedException(); } public virtual Task<ServiceStats> GetServiceStatsAsync(BlobRequestOptions options, OperationContext operationContext, CancellationToken cancellationToken) { throw new System.NotImplementedException(); } private RESTCommand<ServiceStats> GetServiceStatsImpl(BlobRequestOptions requestOptions) { throw new System.NotImplementedException(); } public virtual CloudBlobContainer GetRootContainerReference() { throw new System.NotImplementedException(); } public virtual CloudBlobContainer GetContainerReference(string containerName) { throw new System.NotImplementedException(); } internal ICanonicalizer GetCanonicalizer() { throw new System.NotImplementedException(); } private static void ParseUserPrefix(string prefix, out string containerName, out string listingPrefix) { throw new System.NotImplementedException(); } } }
36.414847
285
0.740976
[ "Apache-2.0" ]
Meertman/azure-storage-net
Lib/AspNet/Microsoft.WindowsAzure.Storage.Facade/FacadeLib/Microsoft.WindowsAzure.Storage.Blob.CloudBlobClient.cs
8,339
C#
using SharpenedMinecraft.Types.Blocks; using System; using System.Collections.Generic; using System.Text; namespace SharpenedMinecraft.Types.Items { public class PeonyItem : ItemStack { public override string Id => "minecraft:peony"; public override Int32 ProtocolId => 302; public override void OnUse(World world, Vector3 Pos, Player player) { world.SetBlock(Pos, new PeonyBlock(), player); } } }
21.863636
75
0.650728
[ "MIT" ]
SharpenedMinecraft/SM1
Main/Types/Items/PeonyItem.cs
481
C#
using System.Threading.Tasks; using MonzoNet.Models.Transactions; using Refit; namespace MonzoNet.Client { public interface IMonzoTransactionApi { [Get("/transactions/{transaction_id}")] Task<RetrieveTransactionResponse> RetrieveTransaction( [AliasAs("transaction_id")] string transactionId, [Header("Authorization")] string bearerToken); [Get("/transactions")] Task<ListTransactionsResponse> ListTransactions( [AliasAs("account_id")] string accountId, [Header("Authorization")] string bearerToken); [Patch("/transactions/{transaction_id}")] Task<AnnotateTransactionResponse> AnnotateTransaction( [AliasAs("transaction_id")] string transactionId, [Header("Authorization")] string bearerToken); } }
34.32
63
0.656177
[ "MIT" ]
ryancormack/Monzo.NET
src/MonzoNet.Client/IMonzoTransactionApi.cs
860
C#
using NServiceBus; public class AuthorizeTransaction : ICommand { public string OrderId { get; set; } }
18.166667
44
0.733945
[ "MIT" ]
HEskandari/NServiceBus.Router
src/Shared/AuthorizeTransaction.cs
111
C#
/** * The MIT License * Copyright (c) 2016 Population Register Centre (VRK) * * 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.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Net; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Filters; using PTV.Framework.ServiceManager; using System.Linq; namespace PTV.Framework.Attributes { /// <summary> /// Base class for validating REST api parameters. /// </summary> public class ValidationBaseAttribute : ActionFilterAttribute { private string keyName; private ValidationAttribute validator; private bool decode; /// <summary> /// Initializes a new instance of the <see cref="ValidationBaseAttribute"/> class. /// </summary> /// <param name="keyName">Name of the key.</param> /// <param name="validator">The validator.</param> public ValidationBaseAttribute(string keyName, ValidationAttribute validator, bool decode = false) { if (string.IsNullOrEmpty(keyName) || string.IsNullOrWhiteSpace(keyName)) { throw new PtvArgumentException("keyName cannot be null, empty string or whitespaces."); } this.keyName = keyName; this.validator = validator ?? throw new PtvArgumentException("validator cannot be null."); this.decode = decode; } /// <summary> /// Validation of request when action is executing /// </summary> /// <param name="context"></param> /// <inheritdoc /> public override void OnActionExecuting(ActionExecutingContext context) { try { var value = context.ActionArguments[keyName]; if (value != null) { if (decode) { value = WebUtility.UrlDecode(value as string); } var attributes = new List<ValidationAttribute>() { validator }; var results = new List<ValidationResult>(); bool isValid = Validator.TryValidateValue(value, new ValidationContext(value), results, attributes); if (!isValid) { context.HttpContext.Response.StatusCode = (int)HttpStatusCode.BadRequest; context.ModelState.AddModelError(keyName, results.First()?.ErrorMessage); context.Result = new BadRequestObjectResult(context.ModelState); } } } catch (KeyNotFoundException) { context.HttpContext.Response.StatusCode = (int)HttpStatusCode.BadRequest; context.ModelState.AddModelError(keyName, validator.FormatErrorMessage(keyName)); context.Result = new BadRequestObjectResult(context.ModelState); } base.OnActionExecuting(context); } } }
40.247619
106
0.614292
[ "MIT" ]
MikkoVirenius/ptv-1.7
src/PTV.Framework/Attributes/ValidationBaseAttribute.cs
4,228
C#
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using BasicTestApp; using Microsoft.AspNetCore.Components.E2ETest.Infrastructure; using Microsoft.AspNetCore.Components.E2ETest.Infrastructure.ServerFixtures; using Microsoft.AspNetCore.E2ETesting; using OpenQA.Selenium; using OpenQA.Selenium.Support.UI; using Xunit; using Xunit.Abstractions; namespace Microsoft.AspNetCore.Components.E2ETest.Tests { public class BindTest : BasicTestAppTestBase { public BindTest( BrowserFixture browserFixture, ToggleExecutionModeServerFixture<Program> serverFixture, ITestOutputHelper output) : base(browserFixture, serverFixture, output) { } protected override void InitializeAsyncCore() { // On WebAssembly, page reloads are expensive so skip if possible Navigate(ServerPathBase, noReload: _serverFixture.ExecutionMode == ExecutionMode.Client); MountTestComponent<BindCasesComponent>(); WaitUntilExists(By.Id("bind-cases")); } [Fact] public void CanBindTextbox_InitiallyBlank() { var target = Browser.FindElement(By.Id("textbox-initially-blank")); var boundValue = Browser.FindElement(By.Id("textbox-initially-blank-value")); var mirrorValue = Browser.FindElement(By.Id("textbox-initially-blank-mirror")); var setNullButton = Browser.FindElement(By.Id("textbox-initially-blank-setnull")); Assert.Equal(string.Empty, target.GetAttribute("value")); Assert.Equal(string.Empty, boundValue.Text); Assert.Equal(string.Empty, mirrorValue.GetAttribute("value")); // Modify target; verify value is updated and that textboxes linked to the same data are updated target.SendKeys("Changed value"); Assert.Equal(string.Empty, boundValue.Text); // Doesn't update until change event Assert.Equal(string.Empty, mirrorValue.GetAttribute("value")); target.SendKeys("\t"); Browser.Equal("Changed value", () => boundValue.Text); Assert.Equal("Changed value", mirrorValue.GetAttribute("value")); // Remove the value altogether setNullButton.Click(); Browser.Equal(string.Empty, () => target.GetAttribute("value")); Assert.Equal(string.Empty, boundValue.Text); Assert.Equal(string.Empty, mirrorValue.GetAttribute("value")); } [Fact] public void CanBindTextbox_InitiallyPopulated() { var target = Browser.FindElement(By.Id("textbox-initially-populated")); var boundValue = Browser.FindElement(By.Id("textbox-initially-populated-value")); var mirrorValue = Browser.FindElement(By.Id("textbox-initially-populated-mirror")); var setNullButton = Browser.FindElement(By.Id("textbox-initially-populated-setnull")); Assert.Equal("Hello", target.GetAttribute("value")); Assert.Equal("Hello", boundValue.Text); Assert.Equal("Hello", mirrorValue.GetAttribute("value")); // Modify target; verify value is updated and that textboxes linked to the same data are updated target.Clear(); target.SendKeys("Changed value\t"); Browser.Equal("Changed value", () => boundValue.Text); Assert.Equal("Changed value", mirrorValue.GetAttribute("value")); // Remove the value altogether setNullButton.Click(); Browser.Equal(string.Empty, () => target.GetAttribute("value")); Assert.Equal(string.Empty, boundValue.Text); Assert.Equal(string.Empty, mirrorValue.GetAttribute("value")); } [Fact] public void CanBindTextArea_InitiallyBlank() { var target = Browser.FindElement(By.Id("textarea-initially-blank")); var boundValue = Browser.FindElement(By.Id("textarea-initially-blank-value")); Assert.Equal(string.Empty, target.GetAttribute("value")); Assert.Equal(string.Empty, boundValue.Text); // Modify target; verify value is updated target.SendKeys("Changed value"); Assert.Equal(string.Empty, boundValue.Text); // Don't update as there's no change event fired yet. target.SendKeys("\t"); Browser.Equal("Changed value", () => boundValue.Text); } [Fact] public void CanBindTextArea_InitiallyPopulated() { var target = Browser.FindElement(By.Id("textarea-initially-populated")); var boundValue = Browser.FindElement(By.Id("textarea-initially-populated-value")); Assert.Equal("Hello", target.GetAttribute("value")); Assert.Equal("Hello", boundValue.Text); // Modify target; verify value is updated target.Clear(); target.SendKeys("Changed value\t"); Browser.Equal("Changed value", () => boundValue.Text); } [Fact] public void CanBindCheckbox_InitiallyNull() { var target = Browser.FindElement(By.Id("checkbox-initially-null")); var boundValue = Browser.FindElement(By.Id("checkbox-initially-null-value")); var invertButton = Browser.FindElement(By.Id("checkbox-initially-null-invert")); Assert.False(target.Selected); Assert.Equal(string.Empty, boundValue.Text); // Modify target; verify value is updated target.Click(); Browser.True(() => target.Selected); Browser.Equal("True", () => boundValue.Text); // Modify data; verify checkbox is updated invertButton.Click(); Browser.False(() => target.Selected); Browser.Equal("False", () => boundValue.Text); } [Fact] public void CanBindCheckbox_InitiallyUnchecked() { var target = Browser.FindElement(By.Id("checkbox-initially-unchecked")); var boundValue = Browser.FindElement(By.Id("checkbox-initially-unchecked-value")); var invertButton = Browser.FindElement(By.Id("checkbox-initially-unchecked-invert")); Assert.False(target.Selected); Assert.Equal("False", boundValue.Text); // Modify target; verify value is updated target.Click(); Browser.True(() => target.Selected); Browser.Equal("True", () => boundValue.Text); // Modify data; verify checkbox is updated invertButton.Click(); Browser.False(() => target.Selected); Browser.Equal("False", () => boundValue.Text); } [Fact] public void CanBindCheckbox_InitiallyChecked() { var target = Browser.FindElement(By.Id("checkbox-initially-checked")); var boundValue = Browser.FindElement(By.Id("checkbox-initially-checked-value")); var invertButton = Browser.FindElement(By.Id("checkbox-initially-checked-invert")); Assert.True(target.Selected); Assert.Equal("True", boundValue.Text); // Modify target; verify value is updated target.Click(); Browser.False(() => target.Selected); Browser.Equal("False", () => boundValue.Text); // Modify data; verify checkbox is updated invertButton.Click(); Browser.True(() => target.Selected); Browser.Equal("True", () => boundValue.Text); } [Fact] public void CanBindSelect() { var target = new SelectElement(Browser.FindElement(By.Id("select-box"))); var boundValue = Browser.FindElement(By.Id("select-box-value")); Assert.Equal("Second choice", target.SelectedOption.Text); Assert.Equal("Second", boundValue.Text); // Modify target; verify value is updated target.SelectByText("Third choice"); Browser.Equal("Third", () => boundValue.Text); // Also verify we can add and select new options atomically // Don't move this into a separate test, because then the previous assertions // would be dependent on test execution order (or would require a full page reload) Browser.FindElement(By.Id("select-box-add-option")).Click(); Browser.Equal("Fourth", () => boundValue.Text); Assert.Equal("Fourth choice", target.SelectedOption.Text); } [Fact] public void CanBindTextboxInt() { var target = Browser.FindElement(By.Id("textbox-int")); var boundValue = Browser.FindElement(By.Id("textbox-int-value")); var mirrorValue = Browser.FindElement(By.Id("textbox-int-mirror")); Assert.Equal("-42", target.GetAttribute("value")); Assert.Equal("-42", boundValue.Text); Assert.Equal("-42", mirrorValue.GetAttribute("value")); // Modify target; value is not updated because it's not convertable. target.Clear(); Browser.Equal("-42", () => boundValue.Text); Assert.Equal("-42", mirrorValue.GetAttribute("value")); // Modify target; verify value is updated and that textboxes linked to the same data are updated target.SendKeys("42\t"); Browser.Equal("42", () => boundValue.Text); Assert.Equal("42", mirrorValue.GetAttribute("value")); } [Fact] public void CanBindTextboxNullableInt() { var target = Browser.FindElement(By.Id("textbox-nullable-int")); var boundValue = Browser.FindElement(By.Id("textbox-nullable-int-value")); var mirrorValue = Browser.FindElement(By.Id("textbox-nullable-int-mirror")); Assert.Equal(string.Empty, target.GetAttribute("value")); Assert.Equal(string.Empty, boundValue.Text); Assert.Equal(string.Empty, mirrorValue.GetAttribute("value")); // Modify target; verify value is updated and that textboxes linked to the same data are updated target.Clear(); Browser.Equal("", () => boundValue.Text); Assert.Equal("", mirrorValue.GetAttribute("value")); // Modify target; verify value is updated and that textboxes linked to the same data are updated target.SendKeys("-42\t"); Browser.Equal("-42", () => boundValue.Text); Assert.Equal("-42", mirrorValue.GetAttribute("value")); // Modify target; verify value is updated and that textboxes linked to the same data are updated target.Clear(); target.SendKeys("42\t"); Browser.Equal("42", () => boundValue.Text); Assert.Equal("42", mirrorValue.GetAttribute("value")); // Modify target; verify value is updated and that textboxes linked to the same data are updated target.Clear(); target.SendKeys("\t"); Browser.Equal(string.Empty, () => boundValue.Text); Assert.Equal(string.Empty, mirrorValue.GetAttribute("value")); } [Fact] public void CanBindTextboxLong() { var target = Browser.FindElement(By.Id("textbox-long")); var boundValue = Browser.FindElement(By.Id("textbox-long-value")); var mirrorValue = Browser.FindElement(By.Id("textbox-long-mirror")); Assert.Equal("3000000000", target.GetAttribute("value")); Assert.Equal("3000000000", boundValue.Text); Assert.Equal("3000000000", mirrorValue.GetAttribute("value")); // Modify target; value is not updated because it's not convertable. target.Clear(); Browser.Equal("3000000000", () => boundValue.Text); Assert.Equal("3000000000", mirrorValue.GetAttribute("value")); // Modify target; verify value is updated and that textboxes linked to the same data are updated target.SendKeys("-3000000000\t"); Browser.Equal("-3000000000", () => boundValue.Text); Assert.Equal("-3000000000", mirrorValue.GetAttribute("value")); } [Fact] public void CanBindTextboxNullableLong() { var target = Browser.FindElement(By.Id("textbox-nullable-long")); var boundValue = Browser.FindElement(By.Id("textbox-nullable-long-value")); var mirrorValue = Browser.FindElement(By.Id("textbox-nullable-long-mirror")); Assert.Equal(string.Empty, target.GetAttribute("value")); Assert.Equal(string.Empty, boundValue.Text); Assert.Equal(string.Empty, mirrorValue.GetAttribute("value")); // Modify target; verify value is updated and that textboxes linked to the same data are updated target.Clear(); Browser.Equal("", () => boundValue.Text); Assert.Equal("", mirrorValue.GetAttribute("value")); // Modify target; verify value is updated and that textboxes linked to the same data are updated target.SendKeys("3000000000\t"); Browser.Equal("3000000000", () => boundValue.Text); Assert.Equal("3000000000", mirrorValue.GetAttribute("value")); // Modify target; verify value is updated and that textboxes linked to the same data are updated target.Clear(); target.SendKeys("-3000000000\t"); Browser.Equal("-3000000000", () => boundValue.Text); Assert.Equal("-3000000000", mirrorValue.GetAttribute("value")); // Modify target; verify value is updated and that textboxes linked to the same data are updated target.Clear(); target.SendKeys("\t"); Browser.Equal(string.Empty, () => boundValue.Text); Assert.Equal(string.Empty, mirrorValue.GetAttribute("value")); } [Fact] public void CanBindTextboxFloat() { var target = Browser.FindElement(By.Id("textbox-float")); var boundValue = Browser.FindElement(By.Id("textbox-float-value")); var mirrorValue = Browser.FindElement(By.Id("textbox-float-mirror")); Assert.Equal("3.141", target.GetAttribute("value")); Assert.Equal("3.141", boundValue.Text); Assert.Equal("3.141", mirrorValue.GetAttribute("value")); // Modify target; value is not updated because it's not convertable. target.Clear(); Browser.Equal("3.141", () => boundValue.Text); Assert.Equal("3.141", mirrorValue.GetAttribute("value")); // Modify target; verify value is updated and that textboxes linked to the same data are updated target.SendKeys("-3.141\t"); Browser.Equal("-3.141", () => boundValue.Text); Assert.Equal("-3.141", mirrorValue.GetAttribute("value")); } [Fact] public void CanBindTextboxNullableFloat() { var target = Browser.FindElement(By.Id("textbox-nullable-float")); var boundValue = Browser.FindElement(By.Id("textbox-nullable-float-value")); var mirrorValue = Browser.FindElement(By.Id("textbox-nullable-float-mirror")); Assert.Equal(string.Empty, target.GetAttribute("value")); Assert.Equal(string.Empty, boundValue.Text); Assert.Equal(string.Empty, mirrorValue.GetAttribute("value")); // Modify target; verify value is updated and that textboxes linked to the same data are updated target.Clear(); Browser.Equal("", () => boundValue.Text); Assert.Equal("", mirrorValue.GetAttribute("value")); // Modify target; verify value is updated and that textboxes linked to the same data are updated target.SendKeys("3.141\t"); Browser.Equal("3.141", () => boundValue.Text); Assert.Equal("3.141", mirrorValue.GetAttribute("value")); // Modify target; verify value is updated and that textboxes linked to the same data are updated target.Clear(); target.SendKeys("-3.141\t"); Browser.Equal("-3.141", () => boundValue.Text); Assert.Equal("-3.141", mirrorValue.GetAttribute("value")); // Modify target; verify value is updated and that textboxes linked to the same data are updated target.Clear(); target.SendKeys("\t"); Browser.Equal(string.Empty, () => boundValue.Text); Assert.Equal(string.Empty, mirrorValue.GetAttribute("value")); } [Fact] public void CanBindTextboxDouble() { var target = Browser.FindElement(By.Id("textbox-double")); var boundValue = Browser.FindElement(By.Id("textbox-double-value")); var mirrorValue = Browser.FindElement(By.Id("textbox-double-mirror")); Assert.Equal("3.14159265359", target.GetAttribute("value")); Assert.Equal("3.14159265359", boundValue.Text); Assert.Equal("3.14159265359", mirrorValue.GetAttribute("value")); // Modify target; value is not updated because it's not convertable. target.Clear(); Browser.Equal("3.14159265359", () => boundValue.Text); Assert.Equal("3.14159265359", mirrorValue.GetAttribute("value")); // Modify target; verify value is updated and that textboxes linked to the same data are updated target.SendKeys("-3.14159265359\t"); Browser.Equal("-3.14159265359", () => boundValue.Text); Assert.Equal("-3.14159265359", mirrorValue.GetAttribute("value")); // Modify target; verify value is updated and that textboxes linked to the same data are updated // Double shouldn't preserve trailing zeros target.Clear(); target.SendKeys("0.010\t"); Browser.Equal("0.01", () => boundValue.Text); Assert.Equal("0.01", mirrorValue.GetAttribute("value")); } [Fact] public void CanBindTextboxNullableDouble() { var target = Browser.FindElement(By.Id("textbox-nullable-double")); var boundValue = Browser.FindElement(By.Id("textbox-nullable-double-value")); var mirrorValue = Browser.FindElement(By.Id("textbox-nullable-double-mirror")); Assert.Equal(string.Empty, target.GetAttribute("value")); Assert.Equal(string.Empty, boundValue.Text); Assert.Equal(string.Empty, mirrorValue.GetAttribute("value")); // Modify target; verify value is updated and that textboxes linked to the same data are updated target.Clear(); Browser.Equal("", () => boundValue.Text); Assert.Equal("", mirrorValue.GetAttribute("value")); // Modify target; verify value is updated and that textboxes linked to the same data are updated target.SendKeys("3.14159265359\t"); Browser.Equal("3.14159265359", () => boundValue.Text); Assert.Equal("3.14159265359", mirrorValue.GetAttribute("value")); // Modify target; verify value is updated and that textboxes linked to the same data are updated target.Clear(); target.SendKeys("-3.14159265359\t"); Browser.Equal("-3.14159265359", () => boundValue.Text); Assert.Equal("-3.14159265359", mirrorValue.GetAttribute("value")); // Modify target; verify value is updated and that textboxes linked to the same data are updated // Double shouldn't preserve trailing zeros target.Clear(); target.SendKeys("0.010\t"); Browser.Equal("0.01", () => boundValue.Text); Assert.Equal("0.01", mirrorValue.GetAttribute("value")); // Modify target; verify value is updated and that textboxes linked to the same data are updated target.Clear(); target.SendKeys("\t"); Browser.Equal(string.Empty, () => boundValue.Text); Assert.Equal(string.Empty, mirrorValue.GetAttribute("value")); } [Fact] public void CanBindTextboxDecimal() { var target = Browser.FindElement(By.Id("textbox-decimal")); var boundValue = Browser.FindElement(By.Id("textbox-decimal-value")); var mirrorValue = Browser.FindElement(By.Id("textbox-decimal-mirror")); Assert.Equal("0.0000000000000000000000000001", target.GetAttribute("value")); Assert.Equal("0.0000000000000000000000000001", boundValue.Text); Assert.Equal("0.0000000000000000000000000001", mirrorValue.GetAttribute("value")); // Modify target; value is not updated because it's not convertable. target.Clear(); Browser.Equal("0.0000000000000000000000000001", () => boundValue.Text); Assert.Equal("0.0000000000000000000000000001", mirrorValue.GetAttribute("value")); // Modify target; verify value is updated and that textboxes linked to the same data are updated // Decimal should preserve trailing zeros target.SendKeys("0.010\t"); Browser.Equal("0.010", () => boundValue.Text); Assert.Equal("0.010", mirrorValue.GetAttribute("value")); } [Fact] public void CanBindTextboxNullableDecimal() { var target = Browser.FindElement(By.Id("textbox-nullable-decimal")); var boundValue = Browser.FindElement(By.Id("textbox-nullable-decimal-value")); var mirrorValue = Browser.FindElement(By.Id("textbox-nullable-decimal-mirror")); Assert.Equal(string.Empty, target.GetAttribute("value")); Assert.Equal(string.Empty, boundValue.Text); Assert.Equal(string.Empty, mirrorValue.GetAttribute("value")); // Modify target; verify value is updated and that textboxes linked to the same data are updated target.Clear(); Browser.Equal("", () => boundValue.Text); Assert.Equal("", mirrorValue.GetAttribute("value")); // Modify target; verify value is updated and that textboxes linked to the same data are updated target.SendKeys("0.0000000000000000000000000001\t"); Browser.Equal("0.0000000000000000000000000001", () => boundValue.Text); Assert.Equal("0.0000000000000000000000000001", mirrorValue.GetAttribute("value")); // Modify target; verify value is updated and that textboxes linked to the same data are updated // Decimal should preserve trailing zeros target.Clear(); target.SendKeys("0.010\t"); Browser.Equal("0.010", () => boundValue.Text); Assert.Equal("0.010", mirrorValue.GetAttribute("value")); // Modify target; verify value is updated and that textboxes linked to the same data are updated target.Clear(); target.SendKeys("\t"); Browser.Equal(string.Empty, () => boundValue.Text); Assert.Equal(string.Empty, mirrorValue.GetAttribute("value")); } // This tests what happens you put invalid (unconvertable) input in. This is separate from the // other tests because it requires type="text" - the other tests use type="number" [Fact] public void CanBindTextbox_Decimal_InvalidInput() { var target = Browser.FindElement(By.Id("textbox-decimal-invalid")); var boundValue = Browser.FindElement(By.Id("textbox-decimal-invalid-value")); var mirrorValue = Browser.FindElement(By.Id("textbox-decimal-invalid-mirror")); Assert.Equal("0.0000000000000000000000000001", target.GetAttribute("value")); Assert.Equal("0.0000000000000000000000000001", boundValue.Text); Assert.Equal("0.0000000000000000000000000001", mirrorValue.GetAttribute("value")); // Modify target; verify value is updated and that textboxes linked to the same data are updated target.Clear(); target.SendKeys("0.01\t"); Browser.Equal("0.01", () => boundValue.Text); Assert.Equal("0.01", mirrorValue.GetAttribute("value")); // Modify target to something invalid - the invalid value is preserved in the input, the other displays // don't change and still have the last value valid. target.SendKeys("A\t"); Browser.Equal("0.01", () => boundValue.Text); Assert.Equal("0.01", mirrorValue.GetAttribute("value")); Assert.Equal("0.01A", target.GetAttribute("value")); // Modify target to something valid. target.SendKeys(Keys.Backspace); target.SendKeys("1\t"); Browser.Equal("0.011", () => boundValue.Text); Assert.Equal("0.011", mirrorValue.GetAttribute("value")); } // This tests what happens you put invalid (unconvertable) input in. This is separate from the // other tests because it requires type="text" - the other tests use type="number" [Fact] public void CanBindTextbox_NullableDecimal_InvalidInput() { var target = Browser.FindElement(By.Id("textbox-nullable-decimal-invalid")); var boundValue = Browser.FindElement(By.Id("textbox-nullable-decimal-invalid-value")); var mirrorValue = Browser.FindElement(By.Id("textbox-nullable-decimal-invalid-mirror")); Assert.Equal(string.Empty, target.GetAttribute("value")); Assert.Equal(string.Empty, boundValue.Text); Assert.Equal(string.Empty, mirrorValue.GetAttribute("value")); // Modify target; verify value is updated and that textboxes linked to the same data are updated target.Clear(); target.SendKeys("0.01\t"); Browser.Equal("0.01", () => boundValue.Text); Assert.Equal("0.01", mirrorValue.GetAttribute("value")); // Modify target to something invalid - the invalid value is preserved in the input, the other displays // don't change and still have the last value valid. target.SendKeys("A\t"); Browser.Equal("0.01", () => boundValue.Text); Assert.Equal("0.01", mirrorValue.GetAttribute("value")); Assert.Equal("0.01A", target.GetAttribute("value")); // Modify target to something valid. target.SendKeys(Keys.Backspace); target.SendKeys("1\t"); Browser.Equal("0.011", () => boundValue.Text); Assert.Equal("0.011", mirrorValue.GetAttribute("value")); } [Fact] public void CanBindTextboxGenericInt() { var target = Browser.FindElement(By.Id("textbox-generic-int")); var boundValue = Browser.FindElement(By.Id("textbox-generic-int-value")); var mirrorValue = Browser.FindElement(By.Id("textbox-generic-int-mirror")); Assert.Equal("-42", target.GetAttribute("value")); Assert.Equal("-42", boundValue.Text); Assert.Equal("-42", mirrorValue.GetAttribute("value")); // Modify target; value is not updated because it's not convertable. target.Clear(); Browser.Equal("-42", () => boundValue.Text); Assert.Equal("-42", mirrorValue.GetAttribute("value")); // Modify target; verify value is updated and that textboxes linked to the same data are updated target.SendKeys("42\t"); Browser.Equal("42", () => boundValue.Text); Assert.Equal("42", mirrorValue.GetAttribute("value")); } [Fact] public void CanBindTextboxGenericGuid() { var target = Browser.FindElement(By.Id("textbox-generic-guid")); var boundValue = Browser.FindElement(By.Id("textbox-generic-guid-value")); var mirrorValue = Browser.FindElement(By.Id("textbox-generic-guid-mirror")); Assert.Equal("00000000-0000-0000-0000-000000000000", target.GetAttribute("value")); Assert.Equal("00000000-0000-0000-0000-000000000000", boundValue.Text); Assert.Equal("00000000-0000-0000-0000-000000000000", mirrorValue.GetAttribute("value")); // Modify target; value is not updated because it's not convertable. target.Clear(); Browser.Equal("00000000-0000-0000-0000-000000000000", () => boundValue.Text); Assert.Equal("00000000-0000-0000-0000-000000000000", mirrorValue.GetAttribute("value")); // Modify target; verify value is updated and that textboxes linked to the same data are updated var newValue = Guid.NewGuid().ToString(); target.SendKeys(newValue + "\t"); Browser.Equal(newValue, () => boundValue.Text); Assert.Equal(newValue, mirrorValue.GetAttribute("value")); } } }
49.986371
115
0.615807
[ "Apache-2.0" ]
FluentGuru/AspNetCore
src/Components/test/E2ETest/Tests/BindTest.cs
29,342
C#
using AzureDevOpsJanitor.Domain.Aggregates.Release; using AzureDevOpsJanitor.Domain.Repository; using AzureDevOpsJanitor.Domain.Services; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; namespace AzureDevOpsJanitor.Application.Services { public sealed class ReleaseService : IReleaseService { private readonly IReleaseRepository _releaseRepository; public ReleaseService(IReleaseRepository releaseRepository) { _releaseRepository = releaseRepository; } public async Task<IEnumerable<ReleaseRoot>> GetAsync() { return await _releaseRepository.GetAsync((release) => true); } public async Task<ReleaseRoot> GetAsync(int releaseId) { var result = await _releaseRepository.GetAsync(r => r.Id == releaseId); return result.SingleOrDefault(); } public async Task<ReleaseRoot> AddAsync(string name, CancellationToken cancellationToken = default) { var release = _releaseRepository.Add(new ReleaseRoot(name)); await _releaseRepository.UnitOfWork.SaveChangesAsync(cancellationToken); return release; } public async Task DeleteAsync(int releaseId, CancellationToken cancellationToken = default) { var release = await GetAsync(releaseId); if (release != null) { _releaseRepository.Delete(release); await _releaseRepository.UnitOfWork.SaveChangesAsync(cancellationToken); } } public async Task<ReleaseRoot> UpdateAsync(ReleaseRoot release, CancellationToken cancellationToken = default) { release = _releaseRepository.Update(release); await _releaseRepository.UnitOfWork.SaveChangesAsync(cancellationToken); return release; } } }
31.015873
118
0.67042
[ "MIT" ]
dfds/azure-devops-janitor
src/AzureDevOpsJanitor.Application/Services/ReleaseService.cs
1,956
C#
using Dapper; using Microsoft.Extensions.Configuration; using System.Collections.Generic; using System.Data; using Microsoft.Data.SqlClient; using System.Linq; using System.Threading.Tasks; namespace DotNetNote.Models.RecruitManager { public interface IRecruitSettingRepository { RecruitSetting Add(RecruitSetting model); // 입력 Task<RecruitSetting> AddAsync(RecruitSetting model); // 입력 List<RecruitSetting> GetAll(); // 출력 Task<IEnumerable<RecruitSetting>> GetAllAsync(); // 출력 RecruitSetting GetById(int id); // 상세 Task<RecruitSetting> GetByIdAsync(int id); // 상세 RecruitSetting Update(RecruitSetting model); // 수정 Task<RecruitSetting> UpdateAsync(RecruitSetting model); // 수정 void Remove(int id); // 삭제 bool IsRecruitSettings(string boardName, int boardNum); bool IsClosedRecruit(string boardName, int boardNum); bool IsFinishedRecruit(string boardName, int boardNum); } public class RecruitSettingRepository : IRecruitSettingRepository { // 데이터베이스 연결 문자열 가져온 후 DB 개체 생성하기 private IConfiguration _config; private IDbConnection db; public RecruitSettingRepository(IConfiguration config) { _config = config; db = new SqlConnection( _config.GetSection("ConnectionStrings") .GetSection("DefaultConnection").Value); } #region 모집 정보 설정 기록 /// <summary> /// 모집 정보 설정 기록 /// </summary> public RecruitSetting Add(RecruitSetting model) { var sql = @" Insert Into RecruitSettings ( Remarks, BoardName, BoardNum, BoardTitle, BoardContent, StartDate, EventDate, EndDate, MaxCount ) Values ( @Remarks, @BoardName, @BoardNum, @BoardTitle, @BoardContent, @StartDate, @EventDate, @EndDate, @MaxCount ); Select Cast(SCOPE_IDENTITY() As Int); "; var id = db.Query<int>(sql, model).Single(); model.Id = id; return model; } /// <summary> /// 모집 정보 설정 기록 /// </summary> public async Task<RecruitSetting> AddAsync(RecruitSetting model) { var sql = @" Insert Into RecruitSettings ( Remarks, BoardName, BoardNum, BoardTitle, BoardContent, StartDate, EventDate, EndDate, MaxCount ) Values ( @Remarks, @BoardName, @BoardNum, @BoardTitle, @BoardContent, @StartDate, @EventDate, @EndDate, @MaxCount ); Select Cast(SCOPE_IDENTITY() As Int); "; var id = await db.QuerySingleAsync<int>(sql, model); model.Id = id; return model; } #endregion #region 전체 모집 정보 출력 /// <summary> /// 전체 모집 정보 출력 /// </summary> public List<RecruitSetting> GetAll() { string sql = @" Select * From RecruitSettings Order By Id Desc "; return db.Query<RecruitSetting>(sql).ToList(); } /// <summary> /// 전체 모집 정보 출력 /// </summary> public async Task<IEnumerable<RecruitSetting>> GetAllAsync() { string sql = @" Select * From RecruitSettings Order By Id Desc "; return await db.QueryAsync<RecruitSetting>(sql); } #endregion #region 상세보기 액션 메서드들 /// <summary> /// 상세 /// </summary> public RecruitSetting GetById(int id) { string sql = @" Select * From RecruitSettings Where Id = @Id "; return db.Query<RecruitSetting>(sql, new { id }).SingleOrDefault(); } /// <summary> /// 상세 /// </summary> public async Task<RecruitSetting> GetByIdAsync(int id) { string sql = @" Select * From RecruitSettings Where Id = @Id "; return await db.QuerySingleOrDefaultAsync<RecruitSetting>(sql, new { id }); } #endregion /// <summary> /// 모집 설정 정보 수정 /// </summary> public RecruitSetting Update(RecruitSetting model) { var sql = " Update RecruitSettings " + " Set " + " Remarks = @Remarks, " + " BoardName = @BoardName, " + " BoardNum = @BoardNum, " + " BoardTitle = @BoardTitle, " + " BoardContent = @BoardContent, " + " StartDate = @StartDate, " + " EventDate = @EventDate, " + " EndDate = @EndDate, " + " MaxCount = @MaxCount " + " Where Id = @Id "; db.Execute(sql, model); return model; } /// <summary> /// 모집 설정 정보 수정 /// </summary> public async Task<RecruitSetting> UpdateAsync(RecruitSetting model) { var sql = " Update RecruitSettings " + " Set " + " Remarks = @Remarks, " + " BoardName = @BoardName, " + " BoardNum = @BoardNum, " + " BoardTitle = @BoardTitle, " + " BoardContent = @BoardContent, " + " StartDate = @StartDate, " + " EventDate = @EventDate, " + " EndDate = @EndDate, " + " MaxCount = @MaxCount " + " Where Id = @Id "; await db.ExecuteAsync(sql, model); return model; } /// <summary> /// 모집 정보 삭제 /// </summary> public void Remove(int id) { string sql = "Delete From RecruitSettings Where Id = @Id"; db.Execute(sql, new { Id = id }); } /// <summary> /// 특정 게시판에 대한 모집 관련 세부 설정이 되었는지 안되었는지 확인 /// </summary> /// <param name="boardName">게시판 별칭</param> /// <param name="boardNum">게시판 아티클 번호</param> /// <returns>True면 이미 세부 설정이 완료됨</returns> public bool IsRecruitSettings(string boardName, int boardNum) { var sqlCount = @" Select Count(*) From RecruitSettings Where BoardName = @BoardName And BoardNum = @BoardNum "; var count = db.Query<int>(sqlCount, new { BoardName = boardName, BoardNum = boardNum }).Single(); if (count > 0) { return true; // 이미 이벤트 관련 세부 설정이 등록된 상태 } return false; } /// <summary> /// 모집 종료: 최대 등록 인원을 0으로 설정하면 종료된 이벤트로 처리 /// </summary> public bool IsClosedRecruit(string boardName, int boardNum) { var sql = @" Select MaxCount From RecruitSettings Where BoardName = @BoardName And BoardNum = @BoardNum"; var cnt = this.db.Query<int>(sql, new { BoardName = boardName, BoardNum = boardNum }).SingleOrDefault(); if (cnt == 0) { return true; // 최대 등록자 수를 0으로 두면 종료된 이벤트 } return false; } /// <summary> /// 모집 마감 여부 확인 /// </summary> /// <param name="boardName">모집 게시판 별칭</param> /// <param name="boardNum">모집 게시판 번호</param> /// <returns>모집 마감(true), 마감 전(false)</returns> public bool IsFinishedRecruit(string boardName, int boardNum) { // 최대 모집 카운트 var sqlCount1 = @" Select MaxCount From RecruitSettings Where BoardName = @BoardName And BoardNum = @BoardNum"; var count1 = db.Query<int>( sqlCount1, new { BoardName = boardName, BoardNum = boardNum } ).SingleOrDefault(); // 모집 등록 카운트 var sqlCount2 = @" Select Count(*) From RecruitSettings Where BoardName = @BoardName And BoardNum = @BoardNum"; var count2 = db.Query<int>( sqlCount2, new { BoardName = boardName, BoardNum = boardNum } ).Single(); // 모집에 등록된 숫자가 같거나, 더 많으면 마감된 모집로 봄 if (count1 != 0 && count1 <= count2) { return true; // 모집 마감 } return false; // 모집 중... } } }
31.9
78
0.409328
[ "MIT" ]
VisualAcademy/DotNetNote
DotNetNote/DotNetNote/Models/RecruitManager/RecruitSettingRepository.cs
11,145
C#