content stringlengths 5 1.04M | avg_line_length float64 1.75 12.9k | max_line_length int64 2 244k | alphanum_fraction float64 0 0.98 | licenses list | repository_name stringlengths 7 92 | path stringlengths 3 249 | size int64 5 1.04M | lang stringclasses 2
values |
|---|---|---|---|---|---|---|---|---|
using System;
using System.Runtime.Serialization;
using System.Threading.Tasks;
namespace NeuralNetworkConstructor.Structure.Nodes
{
[DataContract]
public class InputNode : IInputNode
{
[DataMember]
private double _data;
public event Action<double> OnOutput;
public event Action<double> OnInput;
public Task Input(double input)
{
OnInput?.Invoke(input);
_data = input;
return Task.CompletedTask;
}
public Task<double> Output()
{
OnOutput?.Invoke(_data);
return Task.FromResult(_data);
}
}
}
| 20.4375 | 50 | 0.593272 | [
"MIT"
] | A1essandro/NeuralNetworkConstructor | NeuralNetworkConstructor/Structure/Nodes/InputNode.cs | 656 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Web;
using System.Web.Mvc;
using System.Web.UI;
using Cake.Web.Core.Content.Blog;
using Cake.Web.Models;
namespace Cake.Web.Helpers
{
public static class BlogHelper
{
public static string GetLink(this HtmlHelper helper, BlogPost post)
{
return LinkHelper.GetLink(post);
}
public static string GetLink(this HtmlHelper helper, BlogCategory category)
{
return LinkHelper.GetLink(category);
}
public static string GetArchiveLink(this HtmlHelper helper, DateTime time)
{
return LinkHelper.GetArchiveLink(time);
}
public static string GetAuthorLink(this HtmlHelper helper, string author)
{
return LinkHelper.GetAuthorLink(author);
}
public static string GetPreviousPageLink(this HtmlHelper helper, BlogPageViewModel model)
{
var parts = new List<string> { "blog" };
if (model.Year != 0)
{
parts.Add(model.Year.ToString());
if (model.Month != 0)
{
parts.Add(model.Month.ToString("D2"));
}
}
else
{
if (!string.IsNullOrWhiteSpace(model.Category))
{
parts.Add("category");
parts.Add(model.Category);
}
}
return $"/{string.Join("/", parts)}/?page={Math.Max(model.CurrentPage - 1, 1)}";
}
public static string GetNextPageLink(this HtmlHelper helper, BlogPageViewModel model)
{
var parts = new List<string> { "blog" };
if (model.Year != 0)
{
parts.Add("archive");
parts.Add(model.Year.ToString());
if (model.Month != 0)
{
parts.Add(model.Month.ToString("D2"));
}
}
else
{
if (!string.IsNullOrWhiteSpace(model.Category))
{
parts.Add("category");
parts.Add(model.Category);
}
if (!string.IsNullOrWhiteSpace(model.Author))
{
parts.Add("author");
parts.Add(model.Author);
}
}
return $"/{string.Join("/", parts)}/?page={model.CurrentPage + 1}";
}
public static IHtmlString RenderCategoryList(this HtmlHelper helper, BlogPost post)
{
var writer = new HtmlTextWriter(new StringWriter());
for (int i = 0; i < post.Categories.Count; i++)
{
writer.AddAttribute(HtmlTextWriterAttribute.Href, LinkHelper.GetLink(post.Categories[i]));
writer.RenderBeginTag(HtmlTextWriterTag.A);
writer.Write(post.Categories[i].Title);
writer.RenderEndTag();
if (i != post.Categories.Count - 1)
{
writer.Write(", ");
}
}
return MvcHtmlString.Create(writer.InnerWriter.ToString());
}
}
} | 30.803738 | 106 | 0.503337 | [
"MIT"
] | kcamp/cake-website | src/Cake.Web/Helpers/BlogHelper.cs | 3,298 | C# |
#pragma warning disable 108 // new keyword hiding
#pragma warning disable 114 // new keyword hiding
namespace Windows.ApplicationModel.UserDataTasks
{
#if __ANDROID__ || __IOS__ || NET46 || __WASM__ || __MACOS__
#if __ANDROID__ || __IOS__ || NET46 || __WASM__ || __MACOS__
[global::Uno.NotImplemented]
#endif
public enum UserDataTaskQuerySortProperty
{
#if __ANDROID__ || __IOS__ || NET46 || __WASM__ || __MACOS__
DueDate,
#endif
}
#endif
}
| 26.941176 | 62 | 0.727074 | [
"Apache-2.0"
] | AlexTrepanier/Uno | src/Uno.UWP/Generated/3.0.0.0/Windows.ApplicationModel.UserDataTasks/UserDataTaskQuerySortProperty.cs | 458 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class IClickable : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
}
}
| 15.473684 | 52 | 0.62585 | [
"MIT"
] | DilaverSerif/PotatoPET | Assets/Scripts/Items/Clickable/IClickable.cs | 294 | C# |
using System;
using System.Diagnostics;
using VertSoft.Peppol.Common.Model;
namespace VertSoft.Peppol.Lookup.Model
{
public class DocumentTypeIdentifierWithUriTest
{
public virtual void simple()
{
DocumentTypeIdentifierWithUri documentTypeIdentifierWithUri
= DocumentTypeIdentifierWithUri.of("9908:991825827", DocumentTypeIdentifier.DEFAULT_SCHEME, new Uri("http://difi.no/"));
Debug.Assert(documentTypeIdentifierWithUri.Identifier != null);
Debug.Assert(documentTypeIdentifierWithUri.Scheme != null);
Debug.Assert(documentTypeIdentifierWithUri.Uri != null);
}
}
} | 29.904762 | 140 | 0.746815 | [
"MIT"
] | BartVertongen/Peppol.NETCoreLib | PeppolNETCoreTest/Lookup/model/DocumentTypeIdentifierWithUriTest.cs | 628 | C# |
using Esri.ArcGISRuntime.Geometry;
using Esri.ArcGISRuntime.Location;
using System;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Threading;
namespace ArcGISRuntimeSDKDotNet_DesktopSamples.Samples
{
/// <summary>
/// This sample demonstrates the location display using the MapView.LocationDisplay attribute to show your location on a map. The user may change Location Provider settings and view basic details about the current location.
/// </summary>
/// <title>Location Display</title>
/// <category>Mapping</category>
public partial class LocationDisplay : UserControl
{
/// <summary>Construct Location Display sample user control</summary>
public LocationDisplay()
{
InitializeComponent();
}
private void providerSelector_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (providerSelector.SelectedIndex == 0)
mapView.LocationDisplay.LocationProvider = new SystemLocationProvider();
else
mapView.LocationDisplay.LocationProvider = new RandomProvider();
}
}
/// <summary>Location provider that provides psuedo random location updates</summary>
public class RandomProvider : ILocationProvider
{
private static Random randomizer = new Random();
private DispatcherTimer timer;
LocationInfo oldPosition;
/// <summary>Construct random provider</summary>
public RandomProvider()
{
timer = new DispatcherTimer() { Interval = TimeSpan.FromSeconds(1) };
timer.Tick += timer_Tick;
// Default start location
StartLatitude = 34.057104;
StartLongitude = -117.196816;
}
// Called when the position timer triggers, and calculates the next position based on current speed and heading,
// and adds a little randomization to current heading, speed and accuracy.
private void timer_Tick(object sender, object e)
{
if (oldPosition == null)
{
oldPosition = new LocationInfo()
{
Location = new MapPoint(StartLongitude, StartLatitude) { SpatialReference = new SpatialReference(4326) },
Speed = 0,
Course = 0,
HorizontalAccuracy = 20,
};
}
var now = DateTime.Now;
TimeSpan timeParsed = timer.Interval;
double acceleration = randomizer.NextDouble() * 5 - 2.5;
double deltaSpeed = acceleration * timeParsed.TotalSeconds;
double newSpeed = Math.Max(0, deltaSpeed + oldPosition.Speed);
double deltaCourse = randomizer.NextDouble() * 30 - 15;
double newCourse = deltaCourse + oldPosition.Course;
while (newCourse < 0) newCourse += 360;
while (newCourse >= 360) newCourse -= 360;
double distanceTravelled = (newSpeed + oldPosition.Speed) * .5 * timeParsed.TotalSeconds;
double accuracy = Math.Min(500, Math.Max(20, oldPosition.HorizontalAccuracy + (randomizer.NextDouble() * 100 - 50)));
var pos = GetPointFromHeadingGeodesic(new Point(oldPosition.Location.X, oldPosition.Location.Y), distanceTravelled, newCourse - 180);
var newPosition = new LocationInfo()
{
Location = new MapPoint(pos.X, pos.Y, new SpatialReference(4326)),
Speed = newSpeed,
Course = newCourse,
HorizontalAccuracy = accuracy,
};
oldPosition = newPosition;
if (LocationChanged != null)
LocationChanged(this, oldPosition);
}
// Gets a point on the globe based on a location, a heading and a distance.
private static Point GetPointFromHeadingGeodesic(Point start, double distance, double heading)
{
double brng = (180 + heading) / 180 * Math.PI;
double lon1 = start.X / 180 * Math.PI;
double lat1 = start.Y / 180 * Math.PI;
double dR = distance / 6378137; //Angular distance in radians
double lat2 = Math.Asin(Math.Sin(lat1) * Math.Cos(dR) + Math.Cos(lat1) * Math.Sin(dR) * Math.Cos(brng));
double lon2 = lon1 + Math.Atan2(Math.Sin(brng) * Math.Sin(dR) * Math.Cos(lat1), Math.Cos(dR) - Math.Sin(lat1) * Math.Sin(lat2));
double lon = lon2 / Math.PI * 180;
double lat = lat2 / Math.PI * 180;
while (lon < -180) lon += 360;
while (lat < -90) lat += 180;
while (lon > 180) lon -= 360;
while (lat > 90) lat -= 180;
return new Point(lon, lat);
}
/// <summary>Starting Latitude</summary>
public double StartLatitude { get; set; }
/// <summary>Starting Longitude</summary>
public double StartLongitude { get; set; }
/// <summary>Starts the location provider</summary>
public Task StartAsync()
{
timer.Start();
return Task.FromResult<bool>(true);
}
/// <summary>Stops the location provider</summary>
public Task StopAsync()
{
timer.Stop();
return Task.FromResult<bool>(true);
}
/// <summary>LocationChanged event (from ILocationProvider)</summary>
public event EventHandler<LocationInfo> LocationChanged;
}
}
| 42.769231 | 228 | 0.602698 | [
"Apache-2.0"
] | boonyachengdu/arcgis-runtime-samples-dotnet | src/Desktop/ArcGISRuntimeSDKDotNet_DesktopSamples/Samples/Mapping/LocationDisplay.xaml.cs | 5,562 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EDIFileGenerator
{
class StringModifiers
{
//Reformats a list of strings into EDI format. Sets new lines based on delimiters in the list
public static List<String> WholeTextParse(String text)
{
List<String> words = new List<String>();
String currentChar;
String currentWord = "";
int length = text.Length;
int counter = 0;
//While loop to check each character and build a list of strings
while (counter < length)
{
//Take next character from string
currentChar = text[counter].ToString();
//If you reach a segment delimeter save the current word to the list and reset your current word
if (currentChar == "|" || currentChar == "*")
{
words.Add(currentWord);
currentWord = "";
}
//If you reach and end of line delimiter add it to the list and skip the appropriate following characters
else if (currentChar == "~" || currentChar == "`")
{
words.Add(currentWord);
if (currentChar == "~")
words.Add("~");
else
words.Add("`");
currentWord = "";
counter += 2;
}
else if (currentChar == "\r")
{
counter++;
}
//Add your current character to the current word
else
{
currentWord += currentChar;
}
//Increment to next character
counter++;
}
return words;
}
//Function to take a list of stirngs and revert them to a contious string for output
public static String PutBackTogether(List<String> inputList)
{
//Put all the words back together with proper delimiters
String output = "";
int counter = 0;
int length = inputList.Count;
//Loop through the entierty of the list
while (counter < length)
{
//If you reach an end of line delimiter as the second in the string add the word and the delimiter to the string
//as well as the appropriate carriage return characters
if (inputList[1] == "~" || inputList[1] == "`")
{
if (inputList[1] == "~")
output += inputList[0] + "~\r\n";
else
output += inputList[0] + "`\r\n";
inputList.RemoveAt(0);
inputList.RemoveAt(0);
counter++;
counter++;
}
//Add the string from the list to the output string as well as a segment delimiter.
else
{
output += inputList[0];
output += "*";
inputList.RemoveAt(0);
counter++;
}
}
return output;
}
}
}
| 34.079208 | 128 | 0.456421 | [
"MIT"
] | AnthonyMarsili/EDIFileGenerator | StringModifiers.cs | 3,444 | C# |
/*
Copyright (C) 2014-2016 de4dot@gmail.com
This file is part of dnSpy
dnSpy is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
dnSpy is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with dnSpy. If not, see <http://www.gnu.org/licenses/>.
*/
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using dndbg.COM.CorDebug;
using dndbg.COM.MetaHost;
namespace dndbg.Engine {
public delegate void DebugCallbackEventHandler(DnDebugger dbg, DebugCallbackEventArgs e);
/// <summary>
/// Only call debugger methods in the dndbg thread since it's not thread safe
/// </summary>
public sealed class DnDebugger : IDisposable {
readonly IDebugMessageDispatcher debugMessageDispatcher;
readonly ICorDebug corDebug;
readonly DebuggerCollection<ICorDebugProcess, DnProcess> processes;
readonly DebugEventBreakpointList<DnDebugEventBreakpoint> debugEventBreakpointList = new DebugEventBreakpointList<DnDebugEventBreakpoint>();
readonly DebugEventBreakpointList<DnAnyDebugEventBreakpoint> anyDebugEventBreakpointList = new DebugEventBreakpointList<DnAnyDebugEventBreakpoint>();
readonly BreakpointList<DnILCodeBreakpoint> ilCodeBreakpointList = new BreakpointList<DnILCodeBreakpoint>();
readonly Dictionary<CorStepper, StepInfo> stepInfos = new Dictionary<CorStepper, StepInfo>();
DebugOptions debugOptions;
sealed class StepInfo {
public readonly Action<DnDebugger, StepCompleteDebugCallbackEventArgs> OnCompleted;
public StepInfo(Action<DnDebugger, StepCompleteDebugCallbackEventArgs> action) {
this.OnCompleted = action;
}
}
public DebugOptions Options {
get { DebugVerifyThread(); return debugOptions; }
set { DebugVerifyThread(); debugOptions = value ?? new DebugOptions(); }
}
public DebuggerProcessState ProcessState {
get {
DebugVerifyThread();
if (hasTerminated)
return DebuggerProcessState.Terminated;
if (continuing)
return DebuggerProcessState.Continuing;
if (managedCallbackCounter != 0)
return DebuggerProcessState.Stopped;
if (!hasReceivedCreateProcessEvent)
return DebuggerProcessState.Starting;
return DebuggerProcessState.Running;
}
}
bool hasReceivedCreateProcessEvent = false;
public event EventHandler<ModuleDebuggerEventArgs> OnModuleAdded;
void CallOnModuleAdded(DnModule module, bool added) {
if (OnModuleAdded != null)
OnModuleAdded(this, new ModuleDebuggerEventArgs(module, added));
}
public event EventHandler<NameChangedDebuggerEventArgs> OnNameChanged;
void CallOnNameChanged(DnAppDomain appDomain, DnThread thread) {
if (OnNameChanged != null)
OnNameChanged(this, new NameChangedDebuggerEventArgs(appDomain, thread));
}
public event EventHandler<DebuggerEventArgs> OnProcessStateChanged;
void CallOnProcessStateChanged() {
if (OnProcessStateChanged != null)
OnProcessStateChanged(this, DebuggerEventArgs.Empty);
}
public event EventHandler<CorModuleDefCreatedEventArgs> OnCorModuleDefCreated;
internal void CorModuleDefCreated(DnModule module) {
DebugVerifyThread();
Debug.Assert(module.CorModuleDef != null);
if (OnCorModuleDefCreated != null)
OnCorModuleDefCreated(this, new CorModuleDefCreatedEventArgs(module, module.CorModuleDef));
}
public DnDebugEventBreakpoint[] DebugEventBreakpoints {
get { DebugVerifyThread(); return debugEventBreakpointList.Breakpoints; }
}
public DnAnyDebugEventBreakpoint[] AnyDebugEventBreakpoints {
get { DebugVerifyThread(); return anyDebugEventBreakpointList.Breakpoints; }
}
public IEnumerable<DnILCodeBreakpoint> ILCodeBreakpoints {
get { DebugVerifyThread(); return ilCodeBreakpointList.GetBreakpoints(); }
}
/// <summary>
/// Gets the last debugger state in <see cref="DebuggerStates"/>. This is never null even if
/// <see cref="DebuggerStates"/> is empty.
/// </summary>
public DebuggerState Current {
get {
DebugVerifyThread();
if (debuggerStates.Count == 0)
return new DebuggerState(null);
return debuggerStates[debuggerStates.Count - 1];
}
}
/// <summary>
/// All collected debugger states. It usually contains just one element, but can contain
/// more if multiple CLR debugger events were queued, eg. an exception was caught or
/// we stepped over a breakpoint (Step event + breakpoint hit event).
/// </summary>
public DebuggerState[] DebuggerStates {
get { DebugVerifyThread(); return debuggerStates.ToArray(); }
}
readonly List<DebuggerState> debuggerStates = new List<DebuggerState>();
/// <summary>
/// true if we attached to a process, false if we started all processes
/// </summary>
public bool HasAttached {
get { return processes.GetAll().Any(p => p.WasAttached); }
}
/// <summary>
/// This is the debuggee version or an empty string if it's not known (eg. if it's CoreCLR)
/// </summary>
public string DebuggeeVersion {
get { return debuggeeVersion; }
}
readonly string debuggeeVersion;
readonly int debuggerManagedThreadId;
DnDebugger(ICorDebug corDebug, DebugOptions debugOptions, IDebugMessageDispatcher debugMessageDispatcher, string debuggeeVersion) {
if (debugMessageDispatcher == null)
throw new ArgumentNullException("debugMessageDispatcher");
this.debuggerManagedThreadId = Thread.CurrentThread.ManagedThreadId;
this.processes = new DebuggerCollection<ICorDebugProcess, DnProcess>(CreateDnProcess);
this.debugMessageDispatcher = debugMessageDispatcher;
this.corDebug = corDebug;
this.debugOptions = debugOptions ?? new DebugOptions();
this.debuggeeVersion = debuggeeVersion ?? string.Empty;
corDebug.Initialize();
corDebug.SetManagedHandler(new CorDebugManagedCallback(this));
}
void ResetDebuggerStates() {
debuggerStates.Clear();
}
void AddDebuggerState(DebuggerState debuggerState) {
debuggerStates.Add(debuggerState);
}
DnProcess CreateDnProcess(ICorDebugProcess comProcess, int id) {
return new DnProcess(this, comProcess, id);
}
[Conditional("DEBUG")]
internal void DebugVerifyThread() {
Debug.Assert(Thread.CurrentThread.ManagedThreadId == this.debuggerManagedThreadId);
}
static ICorDebug CreateCorDebug(string debuggeeVersion) {
var clsid = new Guid("9280188D-0E8E-4867-B30C-7FA83884E8DE");
var riid = typeof(ICLRMetaHost).GUID;
var mh = (ICLRMetaHost)NativeMethods.CLRCreateInstance(ref clsid, ref riid);
riid = typeof(ICLRRuntimeInfo).GUID;
var ri = (ICLRRuntimeInfo)mh.GetRuntime(debuggeeVersion, ref riid);
clsid = new Guid("DF8395B5-A4BA-450B-A77C-A9A47762C520");
riid = typeof(ICorDebug).GUID;
return (ICorDebug)ri.GetInterface(ref clsid, ref riid);
}
public event DebugCallbackEventHandler DebugCallbackEvent;
// Could be called from any thread
internal void OnManagedCallbackFromAnyThread(Func<DebugCallbackEventArgs> func) {
debugMessageDispatcher.ExecuteAsync(() => {
DebugCallbackEventArgs e;
try {
e = func();
}
catch {
// most likely debugger has already stopped
return;
}
OnManagedCallbackInDebuggerThread(e);
});
}
// Same as above method but called by CreateProcess, LoadModule, CreateAppDomain because
// certain methods must be called before we return to the CLR debugger.
internal void OnManagedCallbackFromAnyThread2(Func<DebugCallbackEventArgs> func) {
using (var ev = new ManualResetEvent(false)) {
debugMessageDispatcher.ExecuteAsync(() => {
try {
DebugCallbackEventArgs e;
try {
e = func();
}
catch {
// most likely debugger has already stopped
return;
}
OnManagedCallbackInDebuggerThread(e);
}
finally {
ev.Set();
}
});
ev.WaitOne();
}
}
/// <summary>
/// Gets incremented each time Continue() is called
/// </summary>
public uint ContinueCounter {
get { return continueCounter; }
}
uint continueCounter;
// Called in our dndbg thread
void OnManagedCallbackInDebuggerThread(DebugCallbackEventArgs e) {
DebugVerifyThread();
if (hasTerminated)
return;
managedCallbackCounter++;
if (disposeValues.Count != 0) {
foreach (var value in disposeValues)
value.DisposeHandle();
disposeValues.Clear();
}
try {
HandleManagedCallback(e);
CheckBreakpoints(e);
if (DebugCallbackEvent != null)
DebugCallbackEvent(this, e);
}
catch (Exception ex) {
Debug.WriteLine(string.Format("dndbg: EX:\n\n{0}", ex));
ResetDebuggerStates();
throw;
}
Current.StopStates = e.StopStates;
if (HasQueuedCallbacks(e)) {
ContinueAndDecrementCounter(e);
// DON'T call anything, DON'T write any fields now, the CLR debugger could've already called us again when Continue() was called
}
else if (ShouldStopQueued())
CallOnProcessStateChanged();
else {
ResetDebuggerStates();
ContinueAndDecrementCounter(e);
// DON'T call anything, DON'T write any fields now, the CLR debugger could've already called us again when Continue() was called
}
}
int managedCallbackCounter;
bool ShouldStopQueued() {
foreach (var state in debuggerStates) {
if (state.StopStates.Length != 0)
return true;
}
return false;
}
// This method must be called just before returning to the caller. No fields can be accessed
// and no methods can be called because the CLR debugger could call us before this method
// returns.
void ContinueAndDecrementCounter(DebugCallbackEventArgs e) {
if (e.Type != DebugCallbackType.ExitProcess)
Continue(e.CorDebugController, false); // Also decrements managedCallbackCounter
else
managedCallbackCounter--;
}
bool HasQueuedCallbacks(DebugCallbackEventArgs e) {
var thread = Current.Thread;
if (thread == null)
return false;
int qcbs;
int hr = e.CorDebugController.HasQueuedCallbacks(thread.CorThread.RawObject, out qcbs);
return hr >= 0 && qcbs != 0;
}
// This method must be called just before returning to the caller. No fields can be accessed
// and no methods can be called because the CLR debugger could call us before this method
// returns.
bool Continue(ICorDebugController controller, bool callOnProcessStateChanged) {
Debug.Assert(controller != null);
if (controller == null)
return false;
if (callOnProcessStateChanged && managedCallbackCounter == 1) {
try {
continuing = true;
CallOnProcessStateChanged();
}
finally {
continuing = false;
}
}
managedCallbackCounter--;
continueCounter++;
if (callOnProcessStateChanged && managedCallbackCounter == 0)
CallOnProcessStateChanged();
// As soon as we call Continue(), the CLR debugger could send us another message so it's
// important that we don't access any of our fields and don't call any methods after
// Continue() has been called!
int hr = controller.Continue(0);
bool success = hr >= 0 || hr == CordbgErrors.CORDBG_E_PROCESS_TERMINATED || hr == CordbgErrors.CORDBG_E_OBJECT_NEUTERED;
Debug.WriteLineIf(!success, string.Format("dndbg: ICorDebugController::Continue() failed: 0x{0:X8}", hr));
return success;
}
bool continuing = false;
/// <summary>
/// true if <see cref="Continue()"/> can be called
/// </summary>
public bool CanContinue {
get { DebugVerifyThread(); return ProcessState == DebuggerProcessState.Stopped; }
}
/// <summary>
/// Continue debugging the stopped process
/// </summary>
public void Continue() {
DebugVerifyThread();
if (!CanContinue)
return;
Debug.Assert(managedCallbackCounter > 0);
if (managedCallbackCounter <= 0)
return;
var controller = Current.Controller;
Debug.Assert(controller != null);
if (controller == null)
return;
ResetDebuggerStates();
while (managedCallbackCounter > 0) {
if (!Continue(controller, true)) // Also decrements managedCallbackCounter
return;
}
}
/// <summary>
/// true if we can step into, step out or step over
/// </summary>
public bool CanStep() {
return CanStep(Current.ILFrame);
}
/// <summary>
/// true if we can step into, step out or step over
/// </summary>
/// <param name="frame">Frame</param>
public bool CanStep(CorFrame frame) {
DebugVerifyThread();
return ProcessState == DebuggerProcessState.Stopped && frame != null;
}
CorStepper CreateStepper(CorFrame frame) {
if (frame == null)
return null;
var stepper = frame.CreateStepper();
if (stepper == null)
return null;
if (!stepper.SetInterceptMask(debugOptions.StepperInterceptMask))
return null;
if (!stepper.SetUnmappedStopMask(debugOptions.StepperUnmappedStopMask))
return null;
if (!stepper.SetJMC(debugOptions.StepperJMC))
return null;
return stepper;
}
/// <summary>
/// Step out of current method in the current IL frame
/// </summary>
/// <param name="action">Delegate to call when completed or null</param>
/// <returns></returns>
public bool StepOut(Action<DnDebugger, StepCompleteDebugCallbackEventArgs> action = null) {
return StepOut(Current.ILFrame, action);
}
/// <summary>
/// Step out of current method in the selected frame
/// </summary>
/// <param name="frame">Frame</param>
/// <param name="action">Delegate to call when completed or null</param>
/// <returns></returns>
public bool StepOut(CorFrame frame, Action<DnDebugger, StepCompleteDebugCallbackEventArgs> action = null) {
DebugVerifyThread();
return StepOutInternal(frame, action);
}
bool StepOutInternal(CorFrame frame, Action<DnDebugger, StepCompleteDebugCallbackEventArgs> action) {
if (!CanStep(frame))
return false;
var stepper = CreateStepper(frame);
if (stepper == null)
return false;
if (!stepper.StepOut())
return false;
stepInfos.Add(stepper, new StepInfo(action));
Continue();
return true;
}
/// <summary>
/// Step into
/// </summary>
/// <param name="action">Delegate to call when completed or null</param>
/// <returns></returns>
public bool StepInto(Action<DnDebugger, StepCompleteDebugCallbackEventArgs> action = null) {
DebugVerifyThread();
return StepInto(Current.ILFrame, action);
}
/// <summary>
/// Step into
/// </summary>
/// <param name="frame">Frame</param>
/// <param name="action">Delegate to call when completed or null</param>
/// <returns></returns>
public bool StepInto(CorFrame frame, Action<DnDebugger, StepCompleteDebugCallbackEventArgs> action = null) {
DebugVerifyThread();
return StepIntoOver(frame, true, action);
}
/// <summary>
/// Step over
/// </summary>
/// <param name="action">Delegate to call when completed or null</param>
/// <returns></returns>
public bool StepOver(Action<DnDebugger, StepCompleteDebugCallbackEventArgs> action = null) {
DebugVerifyThread();
return StepOver(Current.ILFrame, action);
}
/// <summary>
/// Step over
/// </summary>
/// <param name="frame">Frame</param>
/// <param name="action">Delegate to call when completed or null</param>
/// <returns></returns>
public bool StepOver(CorFrame frame, Action<DnDebugger, StepCompleteDebugCallbackEventArgs> action = null) {
DebugVerifyThread();
return StepIntoOver(frame, false, action);
}
bool StepIntoOver(CorFrame frame, bool stepInto, Action<DnDebugger, StepCompleteDebugCallbackEventArgs> action = null) {
if (!CanStep(frame))
return false;
var stepper = CreateStepper(frame);
if (stepper == null)
return false;
if (!stepper.Step(stepInto))
return false;
stepInfos.Add(stepper, new StepInfo(action));
Continue();
return true;
}
/// <summary>
/// Step into
/// </summary>
/// <param name="ranges">Ranges to step over</param>
/// <param name="action">Delegate to call when completed or null</param>
/// <returns></returns>
public bool StepInto(StepRange[] ranges, Action<DnDebugger, StepCompleteDebugCallbackEventArgs> action = null) {
DebugVerifyThread();
return StepInto(Current.ILFrame, ranges, action);
}
/// <summary>
/// Step into
/// </summary>
/// <param name="frame">Frame</param>
/// <param name="ranges">Ranges to step over</param>
/// <param name="action">Delegate to call when completed or null</param>
/// <returns></returns>
public bool StepInto(CorFrame frame, StepRange[] ranges, Action<DnDebugger, StepCompleteDebugCallbackEventArgs> action = null) {
DebugVerifyThread();
return StepIntoOver(frame, ranges, true, action);
}
/// <summary>
/// Step over
/// </summary>
/// <param name="ranges">Ranges to step over</param>
/// <param name="action">Delegate to call when completed or null</param>
/// <returns></returns>
public bool StepOver(StepRange[] ranges, Action<DnDebugger, StepCompleteDebugCallbackEventArgs> action = null) {
DebugVerifyThread();
return StepOver(Current.ILFrame, ranges, action);
}
/// <summary>
/// Step over
/// </summary>
/// <param name="frame">Frame</param>
/// <param name="ranges">Ranges to step over</param>
/// <param name="action">Delegate to call when completed or null</param>
/// <returns></returns>
public bool StepOver(CorFrame frame, StepRange[] ranges, Action<DnDebugger, StepCompleteDebugCallbackEventArgs> action = null) {
DebugVerifyThread();
return StepIntoOver(frame, ranges, false, action);
}
bool StepIntoOver(CorFrame frame, StepRange[] ranges, bool stepInto, Action<DnDebugger, StepCompleteDebugCallbackEventArgs> action = null) {
if (ranges == null)
return StepIntoOver(frame, stepInto, action);
if (!CanStep(frame))
return false;
var stepper = CreateStepper(frame);
if (stepper == null)
return false;
if (!stepper.StepRange(stepInto, ranges))
return false;
stepInfos.Add(stepper, new StepInfo(action));
Continue();
return true;
}
CorFrame GetRunToCallee(CorFrame frame) {
if (!CanStep(frame))
return null;
if (frame == null)
return null;
if (!frame.IsILFrame)
return null;
var callee = frame.Callee;
if (callee == null)
return null;
if (!callee.IsILFrame)
return null;
return callee;
}
public bool CanRunTo(CorFrame frame) {
DebugVerifyThread();
return GetRunToCallee(frame) != null;
}
public bool RunTo(CorFrame frame) {
DebugVerifyThread();
var callee = GetRunToCallee(frame);
if (callee == null)
return false;
return StepOutInternal(callee, null);
}
void SetDefaultCurrentProcess(DebugCallbackEventArgs e) {
var ps = Processes;
AddDebuggerState(new DebuggerState(e, ps.Length == 0 ? null : ps[0], null, null));
}
void InitializeCurrentDebuggerState(DebugCallbackEventArgs e, ICorDebugProcess comProcess, ICorDebugAppDomain comAppDomain, ICorDebugThread comThread) {
if (comThread != null) {
if (comProcess == null)
comThread.GetProcess(out comProcess);
if (comAppDomain == null)
comThread.GetAppDomain(out comAppDomain);
}
if (comAppDomain != null) {
if (comProcess == null)
comAppDomain.GetProcess(out comProcess);
}
var process = TryGetValidProcess(comProcess);
DnAppDomain appDomain;
DnThread thread;
if (process != null) {
appDomain = process.TryGetAppDomain(comAppDomain);
thread = process.TryGetThread(comThread);
}
else {
appDomain = null;
thread = null;
}
if (thread == null && appDomain == null && process != null)
appDomain = process.AppDomains.FirstOrDefault();
if (thread == null) {
if (appDomain != null)
thread = appDomain.Threads.FirstOrDefault();
else if (process != null)
thread = process.Threads.FirstOrDefault();
}
if (process == null)
SetDefaultCurrentProcess(e);
else
AddDebuggerState(new DebuggerState(e, process, appDomain, thread));
}
void InitializeCurrentDebuggerState(DebugCallbackEventArgs e, DnProcess process) {
if (process == null) {
SetDefaultCurrentProcess(e);
return;
}
AddDebuggerState(new DebuggerState(e, process, null, null));
}
void OnProcessTerminated(DnProcess process) {
if (process == null)
return;
foreach (var appDomain in process.AppDomains) {
OnAppDomainUnloaded(appDomain);
process.AppDomainExited(appDomain.CorAppDomain.RawObject);
}
}
void OnAppDomainUnloaded(DnAppDomain appDomain) {
if (appDomain == null)
return;
foreach (var assembly in appDomain.Assemblies) {
OnAssemblyUnloaded(assembly);
appDomain.AssemblyUnloaded(assembly.CorAssembly.RawObject);
}
}
void OnAssemblyUnloaded(DnAssembly assembly) {
if (assembly == null)
return;
foreach (var module in assembly.Modules)
OnModuleUnloaded(module);
}
void OnModuleUnloaded(DnModule module) {
module.Assembly.ModuleUnloaded(module);
CallOnModuleAdded(module, false);
RemoveModuleFromBreakpoints(module);
}
void RemoveModuleFromBreakpoints(DnModule module) {
if (module == null)
return;
foreach (var bp in this.ilCodeBreakpointList.GetBreakpoints(module.SerializedDnModule))
bp.RemoveModule(module);
}
void HandleManagedCallback(DebugCallbackEventArgs e) {
bool b;
DnProcess process;
DnAppDomain appDomain;
DnAssembly assembly;
CorClass cls;
switch (e.Type) {
case DebugCallbackType.Breakpoint:
var bpArgs = (BreakpointDebugCallbackEventArgs)e;
InitializeCurrentDebuggerState(e, null, bpArgs.AppDomain, bpArgs.Thread);
break;
case DebugCallbackType.StepComplete:
var scArgs = (StepCompleteDebugCallbackEventArgs)e;
InitializeCurrentDebuggerState(e, null, scArgs.AppDomain, scArgs.Thread);
StepInfo stepInfo;
bool calledStepInfoOnCompleted = false;
var stepperKey = scArgs.CorStepper;
if (stepperKey != null && stepInfos.TryGetValue(stepperKey, out stepInfo)) {
stepInfos.Remove(stepperKey);
if (stepInfo.OnCompleted != null) {
calledStepInfoOnCompleted = true;
stepInfo.OnCompleted(this, scArgs);
}
}
// Don't stop on step/breakpoints when we're evaluating
if (!calledStepInfoOnCompleted && !IsEvaluating)
scArgs.AddStopState(new StepStopState(scArgs.Reason));
break;
case DebugCallbackType.Break:
var bArgs = (BreakDebugCallbackEventArgs)e;
InitializeCurrentDebuggerState(e, null, bArgs.AppDomain, bArgs.Thread);
break;
case DebugCallbackType.Exception:
var ex1Args = (ExceptionDebugCallbackEventArgs)e;
InitializeCurrentDebuggerState(e, null, ex1Args.AppDomain, ex1Args.Thread);
break;
case DebugCallbackType.EvalComplete:
var ecArgs = (EvalCompleteDebugCallbackEventArgs)e;
InitializeCurrentDebuggerState(e, null, ecArgs.AppDomain, ecArgs.Thread);
break;
case DebugCallbackType.EvalException:
var eeArgs = (EvalExceptionDebugCallbackEventArgs)e;
InitializeCurrentDebuggerState(e, null, eeArgs.AppDomain, eeArgs.Thread);
break;
case DebugCallbackType.CreateProcess:
var cpArgs = (CreateProcessDebugCallbackEventArgs)e;
hasReceivedCreateProcessEvent = true;
process = TryAdd(cpArgs.Process);
if (process != null) {
process.CorProcess.EnableLogMessages(debugOptions.LogMessages);
process.CorProcess.DesiredNGENCompilerFlags = debugOptions.JITCompilerFlags;
process.CorProcess.SetWriteableMetadataUpdateMode(WriteableMetadataUpdateMode.AlwaysShowUpdates);
process.CorProcess.EnableExceptionCallbacksOutsideOfMyCode(debugOptions.ExceptionCallbacksOutsideOfMyCode);
process.CorProcess.EnableNGENPolicy(debugOptions.NGENPolicy);
}
InitializeCurrentDebuggerState(e, process);
break;
case DebugCallbackType.ExitProcess:
var epArgs = (ExitProcessDebugCallbackEventArgs)e;
process = processes.TryGet(epArgs.Process);
InitializeCurrentDebuggerState(e, process);
if (process != null)
process.SetHasExited();
processes.Remove(epArgs.Process);
OnProcessTerminated(process);
if (processes.Count == 0)
ProcessesTerminated();
break;
case DebugCallbackType.CreateThread:
var ctArgs = (CreateThreadDebugCallbackEventArgs)e;
process = TryGetValidProcess(ctArgs.Thread);
if (process != null) {
process.TryAdd(ctArgs.Thread);
//TODO: ICorDebugThread::SetDebugState
}
InitializeCurrentDebuggerState(e, null, ctArgs.AppDomain, ctArgs.Thread);
break;
case DebugCallbackType.ExitThread:
var etArgs = (ExitThreadDebugCallbackEventArgs)e;
InitializeCurrentDebuggerState(e, null, etArgs.AppDomain, etArgs.Thread);
process = TryGetValidProcess(etArgs.Thread);
if (process != null)
process.ThreadExited(etArgs.Thread);
break;
case DebugCallbackType.LoadModule:
var lmArgs = (LoadModuleDebugCallbackEventArgs)e;
InitializeCurrentDebuggerState(e, null, lmArgs.AppDomain, null);
assembly = TryGetValidAssembly(lmArgs.AppDomain, lmArgs.Module);
if (assembly != null) {
var module = assembly.TryAdd(lmArgs.Module);
module.CorModule.EnableJITDebugging(debugOptions.ModuleTrackJITInfo, debugOptions.ModuleAllowJitOptimizations);
module.CorModule.EnableClassLoadCallbacks(debugOptions.ModuleClassLoadCallbacks);
module.CorModule.JITCompilerFlags = debugOptions.JITCompilerFlags;
module.CorModule.SetJMCStatus(true);
module.InitializeCachedValues();
AddBreakpoints(module);
CallOnModuleAdded(module, true);
}
break;
case DebugCallbackType.UnloadModule:
var umArgs = (UnloadModuleDebugCallbackEventArgs)e;
InitializeCurrentDebuggerState(e, null, umArgs.AppDomain, null);
assembly = TryGetValidAssembly(umArgs.AppDomain, umArgs.Module);
if (assembly != null) {
var module = assembly.TryGetModule(umArgs.Module);
OnModuleUnloaded(module);
}
break;
case DebugCallbackType.LoadClass:
var lcArgs = (LoadClassDebugCallbackEventArgs)e;
InitializeCurrentDebuggerState(e, null, lcArgs.AppDomain, null);
cls = lcArgs.CorClass;
if (cls != null) {
var module = TryGetModule(lcArgs.CorAppDomain, cls);
if (module != null) {
if (module.CorModuleDef != null)
module.CorModuleDef.LoadClass(cls.Token);
foreach (var bp in ilCodeBreakpointList.GetBreakpoints(module.SerializedDnModule))
bp.AddBreakpoint(module);
}
}
break;
case DebugCallbackType.UnloadClass:
var ucArgs = (UnloadClassDebugCallbackEventArgs)e;
InitializeCurrentDebuggerState(e, null, ucArgs.AppDomain, null);
cls = ucArgs.CorClass;
if (cls != null) {
var module = TryGetModule(ucArgs.CorAppDomain, cls);
if (module != null && module.CorModuleDef != null)
module.CorModuleDef.UnloadClass(cls.Token);
}
break;
case DebugCallbackType.DebuggerError:
var deArgs = (DebuggerErrorDebugCallbackEventArgs)e;
InitializeCurrentDebuggerState(e, deArgs.Process, null, null);
break;
case DebugCallbackType.LogMessage:
var lmsgArgs = (LogMessageDebugCallbackEventArgs)e;
InitializeCurrentDebuggerState(e, null, lmsgArgs.AppDomain, lmsgArgs.Thread);
break;
case DebugCallbackType.LogSwitch:
var lsArgs = (LogSwitchDebugCallbackEventArgs)e;
InitializeCurrentDebuggerState(e, null, lsArgs.AppDomain, lsArgs.Thread);
break;
case DebugCallbackType.CreateAppDomain:
var cadArgs = (CreateAppDomainDebugCallbackEventArgs)e;
process = TryGetValidProcess(cadArgs.Process);
if (process != null && cadArgs.AppDomain != null) {
b = cadArgs.AppDomain.Attach() >= 0;
Debug.WriteLineIf(!b, string.Format("CreateAppDomain: could not attach to AppDomain: {0:X8}", cadArgs.AppDomain.GetHashCode()));
if (b)
process.TryAdd(cadArgs.AppDomain);
}
InitializeCurrentDebuggerState(e, cadArgs.Process, cadArgs.AppDomain, null);
break;
case DebugCallbackType.ExitAppDomain:
var eadArgs = (ExitAppDomainDebugCallbackEventArgs)e;
InitializeCurrentDebuggerState(e, eadArgs.Process, eadArgs.AppDomain, null);
process = processes.TryGet(eadArgs.Process);
if (process != null) {
OnAppDomainUnloaded(process.TryGetAppDomain(eadArgs.AppDomain));
process.AppDomainExited(eadArgs.AppDomain);
}
break;
case DebugCallbackType.LoadAssembly:
var laArgs = (LoadAssemblyDebugCallbackEventArgs)e;
InitializeCurrentDebuggerState(e, null, laArgs.AppDomain, null);
appDomain = TryGetValidAppDomain(laArgs.AppDomain);
if (appDomain != null)
appDomain.TryAdd(laArgs.Assembly);
break;
case DebugCallbackType.UnloadAssembly:
var uaArgs = (UnloadAssemblyDebugCallbackEventArgs)e;
InitializeCurrentDebuggerState(e, null, uaArgs.AppDomain, null);
appDomain = TryGetAppDomain(uaArgs.AppDomain);
if (appDomain != null) {
OnAssemblyUnloaded(appDomain.TryGetAssembly(uaArgs.Assembly));
appDomain.AssemblyUnloaded(uaArgs.Assembly);
}
break;
case DebugCallbackType.ControlCTrap:
var cctArgs = (ControlCTrapDebugCallbackEventArgs)e;
InitializeCurrentDebuggerState(e, cctArgs.Process, null, null);
break;
case DebugCallbackType.NameChange:
var ncArgs = (NameChangeDebugCallbackEventArgs)e;
InitializeCurrentDebuggerState(e, null, ncArgs.AppDomain, ncArgs.Thread);
appDomain = TryGetValidAppDomain(ncArgs.AppDomain);
if (appDomain != null)
appDomain.NameChanged();
var thread = TryGetValidThread(ncArgs.Thread);
if (thread != null)
thread.NameChanged();
CallOnNameChanged(appDomain, thread);
break;
case DebugCallbackType.UpdateModuleSymbols:
var umsArgs = (UpdateModuleSymbolsDebugCallbackEventArgs)e;
InitializeCurrentDebuggerState(e, null, umsArgs.AppDomain, null);
break;
case DebugCallbackType.EditAndContinueRemap:
var encrArgs = (EditAndContinueRemapDebugCallbackEventArgs)e;
InitializeCurrentDebuggerState(e, null, encrArgs.AppDomain, encrArgs.Thread);
break;
case DebugCallbackType.BreakpointSetError:
var bpseArgs = (BreakpointSetErrorDebugCallbackEventArgs)e;
InitializeCurrentDebuggerState(e, null, bpseArgs.AppDomain, bpseArgs.Thread);
break;
case DebugCallbackType.FunctionRemapOpportunity:
var froArgs = (FunctionRemapOpportunityDebugCallbackEventArgs)e;
InitializeCurrentDebuggerState(e, null, froArgs.AppDomain, froArgs.Thread);
break;
case DebugCallbackType.CreateConnection:
var ccArgs = (CreateConnectionDebugCallbackEventArgs)e;
InitializeCurrentDebuggerState(e, ccArgs.Process, null, null);
break;
case DebugCallbackType.ChangeConnection:
var cc2Args = (ChangeConnectionDebugCallbackEventArgs)e;
InitializeCurrentDebuggerState(e, cc2Args.Process, null, null);
break;
case DebugCallbackType.DestroyConnection:
var dcArgs = (DestroyConnectionDebugCallbackEventArgs)e;
InitializeCurrentDebuggerState(e, dcArgs.Process, null, null);
break;
case DebugCallbackType.Exception2:
var ex2Args = (Exception2DebugCallbackEventArgs)e;
InitializeCurrentDebuggerState(e, null, ex2Args.AppDomain, ex2Args.Thread);
break;
case DebugCallbackType.ExceptionUnwind:
var euArgs = (ExceptionUnwindDebugCallbackEventArgs)e;
InitializeCurrentDebuggerState(e, null, euArgs.AppDomain, euArgs.Thread);
break;
case DebugCallbackType.FunctionRemapComplete:
var frcArgs = (FunctionRemapCompleteDebugCallbackEventArgs)e;
InitializeCurrentDebuggerState(e, null, frcArgs.AppDomain, frcArgs.Thread);
break;
case DebugCallbackType.MDANotification:
var mdanArgs = (MDANotificationDebugCallbackEventArgs)e;
InitializeCurrentDebuggerState(e, mdanArgs.Controller as ICorDebugProcess, mdanArgs.Controller as ICorDebugAppDomain, mdanArgs.Thread);
break;
case DebugCallbackType.CustomNotification:
var cnArgs = (CustomNotificationDebugCallbackEventArgs)e;
InitializeCurrentDebuggerState(e, null, cnArgs.AppDomain, cnArgs.Thread);
break;
default:
InitializeCurrentDebuggerState(e, null);
Debug.Fail(string.Format("Unknown debug callback type: {0}", e.Type));
break;
}
}
void CheckBreakpoints(DebugCallbackEventArgs e) {
// Never check breakpoints when we're evaluating
if (IsEvaluating)
return;
var type = DnDebugEventBreakpoint.GetDebugEventBreakpointType(e);
if (type != null) {
foreach (var bp in DebugEventBreakpoints) {
if (bp.IsEnabled && bp.EventType == type.Value && bp.Condition.Hit(new DebugEventBreakpointConditionContext(this, bp, e)))
e.AddStopState(new DebugEventBreakpointStopState(bp));
}
}
foreach (var bp in AnyDebugEventBreakpoints) {
if (bp.IsEnabled && bp.Condition.Hit(new AnyDebugEventBreakpointConditionContext(this, bp, e)))
e.AddStopState(new AnyDebugEventBreakpointStopState(bp));
}
if (e.Type == DebugCallbackType.Breakpoint) {
var bpArgs = (BreakpointDebugCallbackEventArgs)e;
//TODO: Use a dictionary instead of iterating over all breakpoints
foreach (var bp in ilCodeBreakpointList.GetBreakpoints()) {
if (!bp.IsBreakpoint(bpArgs.Breakpoint))
continue;
if (bp.IsEnabled && bp.Condition.Hit(new ILCodeBreakpointConditionContext(this, bp)))
e.AddStopState(new ILCodeBreakpointStopState(bp));
break;
}
}
if (e.Type == DebugCallbackType.Break && !debugOptions.IgnoreBreakInstructions)
e.AddStopReason(DebuggerStopReason.Break);
//TODO: DebugCallbackType.BreakpointSetError
}
void ProcessesTerminated() {
if (!hasTerminated) {
hasTerminated = true;
corDebug.Terminate();
ResetDebuggerStates();
CallOnProcessStateChanged();
}
}
bool hasTerminated = false;
public static DnDebugger DebugProcess(DebugProcessOptions options) {
if (options.DebugMessageDispatcher == null)
throw new ArgumentException("DebugMessageDispatcher is null");
var dbg = CreateDnDebugger(options);
if (dbg == null)
throw new Exception("Couldn't create a debugger instance");
return dbg;
}
static DnDebugger CreateDnDebugger(DebugProcessOptions options) {
switch (options.CLRTypeDebugInfo.CLRType) {
case CLRType.Desktop: return CreateDnDebuggerDesktop(options);
case CLRType.CoreCLR: return CreateDnDebuggerCoreCLR(options);
default:
Debug.Fail("Invalid CLRType");
throw new InvalidOperationException();
}
}
static DnDebugger CreateDnDebuggerDesktop(DebugProcessOptions options) {
var clrType = (DesktopCLRTypeDebugInfo)options.CLRTypeDebugInfo;
var debuggeeVersion = clrType.DebuggeeVersion ?? DebuggeeVersionDetector.GetVersion(options.Filename);
var corDebug = CreateCorDebug(debuggeeVersion);
if (corDebug == null)
throw new Exception("Could not create an ICorDebug instance");
var dbg = new DnDebugger(corDebug, options.DebugOptions, options.DebugMessageDispatcher, debuggeeVersion);
if (options.BreakProcessType != BreakProcessType.None)
new BreakProcessHelper(dbg, options.BreakProcessType, options.Filename);
dbg.CreateProcess(options);
return dbg;
}
static DnDebugger CreateDnDebuggerCoreCLR(DebugProcessOptions options) {
var clrType = (CoreCLRTypeDebugInfo)options.CLRTypeDebugInfo;
var dbg2 = CoreCLRHelper.CreateDnDebugger(options, clrType, () => false, (cd, pid) => {
var dbg = new DnDebugger(cd, options.DebugOptions, options.DebugMessageDispatcher, null);
if (options.BreakProcessType != BreakProcessType.None)
new BreakProcessHelper(dbg, options.BreakProcessType, options.Filename);
ICorDebugProcess comProcess;
cd.DebugActiveProcess((int)pid, 0, out comProcess);
var dnProcess = dbg.TryAdd(comProcess);
if (dnProcess != null)
dnProcess.Initialize(false, options.Filename, options.CurrentDirectory, options.CommandLine);
return dbg;
});
if (dbg2 == null)
throw new Exception("Could not create a debugger instance");
return dbg2;
}
void CreateProcess(DebugProcessOptions options) {
ICorDebugProcess comProcess;
try {
var dwCreationFlags = options.ProcessCreationFlags ?? DebugProcessOptions.DefaultProcessCreationFlags;
var si = new STARTUPINFO();
si.cb = (uint)(4 * 1 + IntPtr.Size * 3 + 4 * 8 + 2 * 2 + IntPtr.Size * 4);
var pi = new PROCESS_INFORMATION();
// We must add the space here if the beginning of the command line appears to be
// the path to a file, eg. "/someOption" or "c:blah" or it won't be passed to the
// debugged program.
var cmdline = " " + (options.CommandLine ?? string.Empty);
corDebug.CreateProcess(options.Filename ?? string.Empty, cmdline, IntPtr.Zero, IntPtr.Zero,
options.InheritHandles ? 1 : 0, dwCreationFlags, IntPtr.Zero, options.CurrentDirectory,
ref si, ref pi, CorDebugCreateProcessFlags.DEBUG_NO_SPECIAL_OPTIONS, out comProcess);
// We don't need these
NativeMethods.CloseHandle(pi.hProcess);
NativeMethods.CloseHandle(pi.hThread);
}
catch {
ProcessesTerminated();
throw;
}
var process = TryAdd(comProcess);
if (process != null)
process.Initialize(false, options.Filename, options.CurrentDirectory, options.CommandLine);
}
public static DnDebugger Attach(AttachProcessOptions options) {
var process = Process.GetProcessById(options.ProcessId);
var filename = process.MainModule.FileName;
string debuggeeVersion;
var corDebug = CreateCorDebug(options, out debuggeeVersion);
if (corDebug == null)
throw new Exception("An ICorDebug instance couldn't be created");
var dbg = new DnDebugger(corDebug, options.DebugOptions, options.DebugMessageDispatcher, debuggeeVersion);
ICorDebugProcess comProcess;
corDebug.DebugActiveProcess(options.ProcessId, 0, out comProcess);
var dnProcess = dbg.TryAdd(comProcess);
if (dnProcess != null)
dnProcess.Initialize(true, filename, string.Empty, string.Empty);
return dbg;
}
static ICorDebug CreateCorDebug(AttachProcessOptions options, out string debuggeeVersion) {
switch (options.CLRTypeAttachInfo.CLRType) {
case CLRType.Desktop: return CreateCorDebugDesktop(options, out debuggeeVersion);
case CLRType.CoreCLR: return CreateCorDebugCoreCLR(options, out debuggeeVersion);
default:
Debug.Fail("Invalid CLRType");
throw new InvalidOperationException();
}
}
static ICorDebug CreateCorDebugDesktop(AttachProcessOptions options, out string debuggeeVersion) {
var clrType = (DesktopCLRTypeAttachInfo)options.CLRTypeAttachInfo;
debuggeeVersion = clrType.DebuggeeVersion;
ICLRRuntimeInfo rtInfo = null;
var process = Process.GetProcessById(options.ProcessId);
var filename = process.MainModule.FileName;
foreach (var t in GetCLRRuntimeInfos(process)) {
if (string.IsNullOrEmpty(clrType.DebuggeeVersion) || t.Item1 == clrType.DebuggeeVersion) {
rtInfo = t.Item2;
break;
}
}
if (rtInfo == null)
throw new Exception("Couldn't find a .NET runtime or the correct .NET runtime");
var clsid = new Guid("DF8395B5-A4BA-450B-A77C-A9A47762C520");
var riid = typeof(ICorDebug).GUID;
return (ICorDebug)rtInfo.GetInterface(ref clsid, ref riid);
}
static ICorDebug CreateCorDebugCoreCLR(AttachProcessOptions options, out string debuggeeVersion) {
debuggeeVersion = null;
var clrType = (CoreCLRTypeAttachInfo)options.CLRTypeAttachInfo;
return CoreCLRHelper.CreateCorDebug(clrType);
}
static IEnumerable<Tuple<string, ICLRRuntimeInfo>> GetCLRRuntimeInfos(Process process) {
var clsid = new Guid("9280188D-0E8E-4867-B30C-7FA83884E8DE");
var riid = typeof(ICLRMetaHost).GUID;
var mh = (ICLRMetaHost)NativeMethods.CLRCreateInstance(ref clsid, ref riid);
IEnumUnknown iter;
int hr = mh.EnumerateLoadedRuntimes(process.Handle, out iter);
if (hr < 0)
yield break;
for (;;) {
object obj;
uint fetched;
hr = iter.Next(1, out obj, out fetched);
if (hr < 0 || fetched == 0)
break;
var rtInfo = (ICLRRuntimeInfo)obj;
uint chBuffer = 0;
var sb = new StringBuilder(300);
hr = rtInfo.GetVersionString(sb, ref chBuffer);
sb.EnsureCapacity((int)chBuffer);
hr = rtInfo.GetVersionString(sb, ref chBuffer);
yield return Tuple.Create(sb.ToString(), rtInfo);
}
}
DnProcess TryAdd(ICorDebugProcess comProcess) {
if (comProcess == null)
return null;
// This method is called twice, once from DebugProcess() and once from the CreateProcess
// handler. It's possible that it's been terminated before DebugProcess() calls this method.
// Check if it's terminated. Error should be 0x8013134F: CORDBG_E_OBJECT_NEUTERED
int running;
if (comProcess.IsRunning(out running) < 0)
return null;
return processes.Add(comProcess);
}
/// <summary>
/// Gets all processes, sorted on the order they were created
/// </summary>
/// <returns></returns>
public DnProcess[] Processes {
get {
DebugVerifyThread();
var list = processes.GetAll();
Array.Sort(list, (a, b) => a.IncrementedId.CompareTo(b.IncrementedId));
return list;
}
}
/// <summary>
/// Gets a process or null if it has exited
/// </summary>
/// <param name="comProcess">Process</param>
/// <returns></returns>
public DnProcess TryGetValidProcess(ICorDebugProcess comProcess) {
DebugVerifyThread();
var process = processes.TryGet(comProcess);
if (process == null)
return null;
if (!process.CheckValid())
return null;
return process;
}
public DnProcess TryGetValidProcess(ICorDebugAppDomain comAppDomain) {
DebugVerifyThread();
if (comAppDomain == null)
return null;
ICorDebugProcess comProcess;
int hr = comAppDomain.GetProcess(out comProcess);
if (hr < 0)
return null;
return TryGetValidProcess(comProcess);
}
public DnProcess TryGetValidProcess(ICorDebugThread comThread) {
DebugVerifyThread();
if (comThread == null)
return null;
ICorDebugProcess comProcess;
int hr = comThread.GetProcess(out comProcess);
if (hr < 0)
return null;
return TryGetValidProcess(comProcess);
}
DnAppDomain TryGetAppDomain(ICorDebugAppDomain comAppDomain) {
DebugVerifyThread();
if (comAppDomain == null)
return null;
ICorDebugProcess comProcess;
int hr = comAppDomain.GetProcess(out comProcess);
if (hr < 0)
return null;
var process = processes.TryGet(comProcess);
return process == null ? null : process.TryGetAppDomain(comAppDomain);
}
public DnAppDomain TryGetValidAppDomain(ICorDebugAppDomain comAppDomain) {
DebugVerifyThread();
if (comAppDomain == null)
return null;
ICorDebugProcess comProcess;
int hr = comAppDomain.GetProcess(out comProcess);
if (hr < 0)
return null;
return TryGetValidAppDomain(comProcess, comAppDomain);
}
public DnAppDomain TryGetValidAppDomain(ICorDebugProcess comProcess, ICorDebugAppDomain comAppDomain) {
DebugVerifyThread();
var process = TryGetValidProcess(comProcess);
if (process == null)
return null;
return process.TryGetValidAppDomain(comAppDomain);
}
public DnAssembly TryGetValidAssembly(ICorDebugAppDomain comAppDomain, ICorDebugModule comModule) {
DebugVerifyThread();
if (comModule == null)
return null;
var appDomain = TryGetValidAppDomain(comAppDomain);
if (appDomain == null)
return null;
ICorDebugAssembly comAssembly;
int hr = comModule.GetAssembly(out comAssembly);
if (hr < 0)
return null;
return appDomain.TryGetAssembly(comAssembly);
}
public DnThread TryGetValidThread(ICorDebugThread comThread) {
DebugVerifyThread();
var process = TryGetValidProcess(comThread);
return process == null ? null : process.TryGetValidThread(comThread);
}
public DnModule TryGetModule(CorAppDomain appDomain, CorClass cls) {
if (appDomain == null || cls == null)
return null;
var clsMod = cls.Module;
if (clsMod == null)
return null;
var ad = TryGetAppDomain(appDomain.RawObject);
if (ad == null)
return null;
var asm = TryGetValidAssembly(appDomain.RawObject, clsMod.RawObject);
if (asm == null)
return null;
return asm.TryGetModule(clsMod.RawObject);
}
/// <summary>
/// Re-add breakpoints to the module. Should be called if the debugged module has breakpoints
/// in decrypted methods and the methods have now been decrypted.
/// </summary>
/// <param name="module"></param>
public void AddBreakpoints(DnModule module) {
foreach (var bp in ilCodeBreakpointList.GetBreakpoints(module.SerializedDnModule))
bp.AddBreakpoint(module);
}
/// <summary>
/// Creates a debug event breakpoint
/// </summary>
/// <param name="eventType">Debug event</param>
/// <param name="cond">Condition</param>
/// <returns></returns>
public DnDebugEventBreakpoint CreateBreakpoint(DebugEventBreakpointType eventType, Predicate<BreakpointConditionContext> cond) {
DebugVerifyThread();
return CreateBreakpoint(eventType, new DelegateBreakpointCondition(cond));
}
/// <summary>
/// Creates a debug event breakpoint
/// </summary>
/// <param name="eventType">Debug event</param>
/// <param name="bpCond">Condition or null</param>
/// <returns></returns>
public DnDebugEventBreakpoint CreateBreakpoint(DebugEventBreakpointType eventType, IBreakpointCondition bpCond = null) {
DebugVerifyThread();
var bp = new DnDebugEventBreakpoint(eventType, bpCond);
debugEventBreakpointList.Add(bp);
return bp;
}
/// <summary>
/// Creates a debug event breakpoint that gets hit on all debug events
/// </summary>
/// <param name="cond">Condition</param>
/// <returns></returns>
public DnAnyDebugEventBreakpoint CreateAnyDebugEventBreakpoint(Predicate<BreakpointConditionContext> cond) {
DebugVerifyThread();
return CreateAnyDebugEventBreakpoint(new DelegateBreakpointCondition(cond));
}
/// <summary>
/// Creates a debug event breakpoint that gets hit on all debug events
/// </summary>
/// <param name="bpCond">Condition or null</param>
/// <returns></returns>
public DnAnyDebugEventBreakpoint CreateAnyDebugEventBreakpoint(IBreakpointCondition bpCond = null) {
DebugVerifyThread();
var bp = new DnAnyDebugEventBreakpoint(bpCond);
anyDebugEventBreakpointList.Add(bp);
return bp;
}
/// <summary>
/// Creates an IL instruction breakpoint
/// </summary>
/// <param name="module">Module</param>
/// <param name="token">Method token</param>
/// <param name="ilOffset">IL offset</param>
/// <param name="cond">Condition</param>
/// <returns></returns>
public DnILCodeBreakpoint CreateBreakpoint(SerializedDnModule module, uint token, uint ilOffset, Predicate<BreakpointConditionContext> cond) {
DebugVerifyThread();
return CreateBreakpoint(module, token, ilOffset, new DelegateBreakpointCondition(cond));
}
/// <summary>
/// Creates an IL instruction breakpoint
/// </summary>
/// <param name="module">Module</param>
/// <param name="token">Method token</param>
/// <param name="ilOffset">IL offset</param>
/// <param name="bpCond">Condition or null</param>
/// <returns></returns>
public DnILCodeBreakpoint CreateBreakpoint(SerializedDnModule module, uint token, uint ilOffset, IBreakpointCondition bpCond = null) {
DebugVerifyThread();
var bp = new DnILCodeBreakpoint(module, token, ilOffset, bpCond);
ilCodeBreakpointList.Add(module, bp);
foreach (var dnMod in GetLoadedDnModules(module))
bp.AddBreakpoint(dnMod);
return bp;
}
IEnumerable<DnModule> GetLoadedDnModules(SerializedDnModule module) {
foreach (var process in processes.GetAll()) {
foreach (var appDomain in process.AppDomains) {
foreach (var assembly in appDomain.Assemblies) {
foreach (var dnMod in assembly.Modules) {
if (dnMod.SerializedDnModule.Equals(module))
yield return dnMod;
}
}
}
}
}
public void RemoveBreakpoint(DnBreakpoint bp) {
DebugVerifyThread();
var debp = bp as DnDebugEventBreakpoint;
if (debp != null) {
debugEventBreakpointList.Remove(debp);
debp.OnRemoved();
return;
}
var adebp = bp as DnAnyDebugEventBreakpoint;
if (adebp != null) {
anyDebugEventBreakpointList.Remove(adebp);
adebp.OnRemoved();
return;
}
var ilbp = bp as DnILCodeBreakpoint;
if (ilbp != null) {
ilCodeBreakpointList.Remove(ilbp.Module, ilbp);
ilbp.OnRemoved();
return;
}
}
public int TryBreakProcesses() {
return TryBreakProcesses(true);
}
int TryBreakProcesses(bool callProcessStopped) {
if (ProcessState != DebuggerProcessState.Starting && ProcessState != DebuggerProcessState.Running)
return -1;
int errorHR = 0;
foreach (var process in processes.GetAll()) {
try {
int hr = process.CorProcess.RawObject.Stop(uint.MaxValue);
if (hr < 0)
errorHR = hr;
else
ProcessStopped(process, callProcessStopped);
}
catch {
if (errorHR == 0)
errorHR = -1;
}
}
return errorHR;
}
void ProcessStopped(DnProcess process, bool addStopState) {
this.managedCallbackCounter++;
if (!addStopState)
return;
DnThread thread = process.GetMainThread();
DnAppDomain appDomain = thread == null ? process.GetMainAppDomain() : thread.AppDomainOrNull;
AddDebuggerState(new DebuggerState(null, process, appDomain, thread) {
StopStates = new DebuggerStopState[] {
new DebuggerStopState(DebuggerStopReason.UserBreak),
}
});
CallOnProcessStateChanged();
}
public void TerminateProcesses() {
TerminateAllProcessesInternal();
Continue();
}
public int TryDetach() {
if (ProcessState == DebuggerProcessState.Starting || ProcessState == DebuggerProcessState.Running) {
int hr = TryBreakProcesses(false);
if (hr < 0)
return hr;
}
foreach (var bp in ilCodeBreakpointList.GetBreakpoints())
bp.OnRemoved();
foreach (var kv in stepInfos) {
if (kv.Key.IsActive)
kv.Key.Deactivate();
}
foreach (var process in processes.GetAll()) {
try {
int hr = process.CorProcess.RawObject.Detach();
if (hr < 0)
return hr;
}
catch (InvalidComObjectException) {
}
}
hasTerminated = true;
ResetDebuggerStates();
CallOnProcessStateChanged();
return 0;
}
~DnDebugger() {
Dispose(false);
}
public void Dispose() {
GC.SuppressFinalize(this);
Dispose(true);
}
void Dispose(bool disposing) {
TerminateAllProcessesInternal();
}
void TerminateAllProcessesInternal() {
foreach (var process in processes.GetAll()) {
try {
int hr = process.CorProcess.RawObject.Stop(uint.MaxValue);
hr = process.CorProcess.RawObject.Terminate(uint.MaxValue);
if (hr != 0) {
Debug.Assert(hr == CordbgErrors.CORDBG_E_UNRECOVERABLE_ERROR);
bool b = NativeMethods.TerminateProcess(process.CorProcess.Handle, uint.MaxValue);
Debug.Assert(b);
}
}
catch {
}
}
}
internal int GetNextModuleId() {
return moduleOrder++;
}
int moduleOrder;
public DnEval CreateEval() {
DebugVerifyThread();
Debug.Assert(ProcessState == DebuggerProcessState.Stopped);
return new DnEval(this, debugMessageDispatcher);
}
public bool IsEvaluating {
get { return evalCounter != 0 && ProcessState != DebuggerProcessState.Terminated; }
}
public bool EvalCompleted {
get { return evalCompletedCounter != 0; }
}
internal void EvalStarted() {
DebugVerifyThread();
Debug.Assert(ProcessState == DebuggerProcessState.Stopped);
evalCounter++;
Continue();
}
int evalCounter;
internal void EvalStopped() {
DebugVerifyThread();
evalCounter--;
}
public void SignalEvalComplete() {
DebugVerifyThread();
Debug.Assert(!IsEvaluating && ProcessState == DebuggerProcessState.Stopped);
evalCompletedCounter++;
try {
CallOnProcessStateChanged();
}
finally {
evalCompletedCounter--;
}
}
int evalCompletedCounter;
public void DisposeHandle(CorValue value) {
if (value == null || !value.IsHandle)
return;
if (ProcessState != DebuggerProcessState.Running)
value.DisposeHandle();
else
disposeValues.Add(value);
}
readonly List<CorValue> disposeValues = new List<CorValue>();
/// <summary>
/// Gets all modules from all processes and app domains
/// </summary>
public IEnumerable<DnModule> Modules {
get {
DebugVerifyThread();
foreach (var p in Processes) {
foreach (var ad in p.AppDomains) {
foreach (var asm in ad.Assemblies) {
foreach (var mod in asm.Modules)
yield return mod;
}
}
}
}
}
/// <summary>
/// Gets all assemblies from all processes and app domains
/// </summary>
public IEnumerable<DnAssembly> Assemblies {
get {
DebugVerifyThread();
foreach (var p in Processes) {
foreach (var ad in p.AppDomains) {
foreach (var asm in ad.Assemblies)
yield return asm;
}
}
}
}
}
}
| 32.577534 | 154 | 0.717196 | [
"MIT"
] | blackunixteam/dnSpy | dndbg/Engine/DnDebugger.cs | 53,364 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated from a template.
//
// Manual changes to this file may cause unexpected behavior in your application.
// Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace OCM.Core.Data
{
using System;
using System.Collections.Generic;
public partial class MetadataGroup
{
public MetadataGroup()
{
this.MetadataFields = new HashSet<MetadataField>();
}
public int ID { get; set; }
public string Title { get; set; }
public bool IsRestrictedEdit { get; set; }
public int DataProviderID { get; set; }
public bool IsPublicInterest { get; set; }
public virtual ICollection<MetadataField> MetadataFields { get; set; }
public virtual DataProvider DataProvider { get; set; }
}
}
| 33.09375 | 85 | 0.539188 | [
"MIT"
] | cybersol795/ocm-system | API/OCM.Net/OCM.API.Core/Data/MetadataGroup.cs | 1,059 | C# |
namespace Xceed.Wpf.Toolkit.Primitives
{
public enum MouseWheelActiveTrigger
{
Focused,
FocusedMouseOver,
MouseOver,
Disabled
}
}
| 12.818182 | 38 | 0.758865 | [
"MIT"
] | ay2015/AYUI8 | Ay/ay/SDK/CONTROLLIB/Large/PropertyGrid/UI/Info/MouseWheelActiveTrigger.cs | 141 | C# |
//---------------------------------------------------------------------------------------------------
// <auto-generated>
// Changes to this file may cause incorrect behavior and will be lost if the code is regenerated.
// Generated by DynamicsCrm.DevKit - https://github.com/phuocle/Dynamics-Crm-DevKit
// </auto-generated>
//---------------------------------------------------------------------------------------------------
using Microsoft.Xrm.Sdk;
using System;
using System.Diagnostics;
namespace Abc.LuckyStar2.Shared.Entities.SubscriptionStatisticsOfflineOptionSets
{
}
namespace Abc.LuckyStar2.Shared.Entities
{
public partial class SubscriptionStatisticsOffline : EntityBase
{
public struct Fields
{
public const string FullSyncRequired = "fullsyncrequired";
public const string ObjectTypeCode = "objecttypecode";
public const string SubscriptionId = "subscriptionid";
}
public const string EntityLogicalName = "subscriptionstatisticsoffline";
public const int EntityTypeCode = 45;
[DebuggerNonUserCode()]
public SubscriptionStatisticsOffline()
{
Entity = new Entity(EntityLogicalName);
PreEntity = CloneThisEntity(Entity);
}
[DebuggerNonUserCode()]
public SubscriptionStatisticsOffline(Guid SubscriptionStatisticsOfflineId)
{
Entity = new Entity(EntityLogicalName, SubscriptionStatisticsOfflineId);
PreEntity = CloneThisEntity(Entity);
}
[DebuggerNonUserCode()]
public SubscriptionStatisticsOffline(string keyName, object keyValue)
{
Entity = new Entity(EntityLogicalName, keyName, keyValue);
PreEntity = CloneThisEntity(Entity);
}
[DebuggerNonUserCode()]
public SubscriptionStatisticsOffline(Entity entity)
{
Entity = entity;
PreEntity = CloneThisEntity(Entity);
}
[DebuggerNonUserCode()]
public SubscriptionStatisticsOffline(Entity entity, Entity merge)
{
Entity = entity;
foreach (var property in merge?.Attributes)
{
var key = property.Key;
var value = property.Value;
Entity[key] = value;
}
PreEntity = CloneThisEntity(Entity);
}
[DebuggerNonUserCode()]
public SubscriptionStatisticsOffline(KeyAttributeCollection keys)
{
Entity = new Entity(EntityLogicalName, keys);
PreEntity = CloneThisEntity(Entity);
}
/// <summary>
/// <para>Is full sync required or not</para>
/// <para>Boolean</para>
/// <para>FullSyncRequired</para>
/// </summary>
[DebuggerNonUserCode()]
public bool? FullSyncRequired
{
get { return Entity.GetAttributeValue<bool?>(Fields.FullSyncRequired); }
set { Entity.Attributes[Fields.FullSyncRequired] = value; }
}
/// <summary>
/// <para>Entity object type code</para>
/// <para>Integer - MinValue: 0 - MaxValue: 2,147,483,647</para>
/// <para>ObjectTypeCode</para>
/// </summary>
[DebuggerNonUserCode()]
public int? ObjectTypeCode
{
get { return Entity.GetAttributeValue<int?>(Fields.ObjectTypeCode); }
set { Entity.Attributes[Fields.ObjectTypeCode] = value; }
}
/// <summary>
/// <para>Subscription Id</para>
/// <para>Uniqueidentifier</para>
/// <para>SubscriptionId</para>
/// </summary>
[DebuggerNonUserCode()]
public Guid? SubscriptionId
{
get { return Entity.GetAttributeValue<Guid?>(Fields.SubscriptionId); }
set { Entity.Attributes[Fields.SubscriptionId] = value; }
}
}
}
| 28.706897 | 102 | 0.678979 | [
"MIT"
] | Kayserheimer/Dynamics-Crm-DevKit | test/v.2.10.31/Abc.LuckyStar2/Abc.LuckyStar2.Shared/Entities/SubscriptionStatisticsOffline.generated.cs | 3,332 | C# |
namespace EZOper.CSharpSolution.WebUI.Areas.Help
{
public class DictionaryModelDescription : KeyValuePairModelDescription
{
}
} | 23.166667 | 74 | 0.776978 | [
"MIT"
] | erikzhouxin/CSharpSolution | WebUI/Areas/Help/Models/DictionaryModelDescription.cs | 139 | C# |
using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("AWSSDK.Route53Domains")]
[assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (3.5) - Amazon Route 53 Domains. Amazon Route 53 is a highly available and scalable cloud Domain Name System (DNS) web service.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyProduct("Amazon Web Services SDK for .NET")]
[assembly: AssemblyCompany("Amazon.com, Inc")]
[assembly: AssemblyCopyright("Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("3.3")]
[assembly: AssemblyFileVersion("3.7.0.17")] | 45.84375 | 199 | 0.748466 | [
"Apache-2.0"
] | KenHundley/aws-sdk-net | sdk/code-analysis/ServiceAnalysis/Route53Domains/Properties/AssemblyInfo.cs | 1,467 | C# |
using UnityEngine;
using UnityEditor;
using UnityEngine.UI;
using UltimateSurvival.GUISystem;
namespace UltimateSurvival.Editor
{
[CanEditMultipleObjects]
[CustomEditor(typeof(GUIController))]
public class GUIControllerEditor : UnityEditor.Editor
{
public override void OnInspectorGUI()
{
base.OnInspectorGUI();
if(!Application.isPlaying)
{
EditorGUILayout.Space();
EditorGUILayout.HelpBox("Will assign the font to all the Text components.", MessageType.Info);
if(GUILayout.Button("Assign Font"))
{
var controller = serializedObject.targetObject as GUIController;
foreach(var text in controller.GetComponentsInChildren<Text>())
text.font = controller.Font;
}
EditorGUILayout.Space();
EditorGUILayout.HelpBox("Equivalent with pressing 'Apply' for all collections.", MessageType.Info);
if(GUILayout.Button("Apply For All Collections"))
{
var controller = serializedObject.targetObject as GUIController;
controller.ApplyForAllCollections();
}
}
}
}
}
| 26.74359 | 103 | 0.733461 | [
"Apache-2.0"
] | alasaidi/file-cs | file/GUIControllerEditor.cs | 1,045 | C# |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Collections.Immutable;
using System.Diagnostics;
using Microsoft.CodeAnalysis.CSharp.Symbols;
namespace Microsoft.CodeAnalysis.CSharp
{
internal sealed partial class BoundFieldAccess
{
public BoundFieldAccess(
SyntaxNode syntax,
BoundExpression receiver,
FieldSymbol fieldSymbol,
ConstantValue constantValueOpt,
bool hasErrors = false)
: this(syntax, receiver, fieldSymbol, constantValueOpt, LookupResultKind.Viable, fieldSymbol.Type.TypeSymbol, hasErrors)
{
}
public BoundFieldAccess(
SyntaxNode syntax,
BoundExpression receiver,
FieldSymbol fieldSymbol,
ConstantValue constantValueOpt,
LookupResultKind resultKind,
TypeSymbol type,
bool hasErrors = false)
: this(syntax, receiver, fieldSymbol, constantValueOpt, resultKind, NeedsByValueFieldAccess(receiver, fieldSymbol), isDeclaration: false, type: type, hasErrors: hasErrors)
{
}
public BoundFieldAccess(
SyntaxNode syntax,
BoundExpression receiver,
FieldSymbol fieldSymbol,
ConstantValue constantValueOpt,
LookupResultKind resultKind,
bool isDeclaration,
TypeSymbol type,
bool hasErrors = false)
: this(syntax, receiver, fieldSymbol, constantValueOpt, resultKind, NeedsByValueFieldAccess(receiver, fieldSymbol), isDeclaration: isDeclaration, type: type, hasErrors: hasErrors)
{
}
public BoundFieldAccess Update(
BoundExpression receiver,
FieldSymbol fieldSymbol,
ConstantValue constantValueOpt,
LookupResultKind resultKind,
TypeSymbol typeSymbol)
{
return this.Update(receiver, fieldSymbol, constantValueOpt, resultKind, this.IsByValue, this.IsDeclaration, typeSymbol);
}
private static bool NeedsByValueFieldAccess(BoundExpression receiver, FieldSymbol fieldSymbol)
{
if (fieldSymbol.IsStatic ||
!fieldSymbol.ContainingType.IsValueType ||
(object)receiver == null) // receiver may be null in error cases
{
return false;
}
switch (receiver.Kind)
{
case BoundKind.FieldAccess:
return ((BoundFieldAccess)receiver).IsByValue;
case BoundKind.Local:
var localSymbol = ((BoundLocal)receiver).LocalSymbol;
return !(localSymbol.IsWritableVariable || localSymbol.IsRef);
default:
return false;
}
}
}
internal partial class BoundCall
{
public static BoundCall ErrorCall(
SyntaxNode node,
BoundExpression receiverOpt,
MethodSymbol method,
ImmutableArray<BoundExpression> arguments,
ImmutableArray<string> namedArguments,
ImmutableArray<RefKind> refKinds,
bool isDelegateCall,
bool invokedAsExtensionMethod,
ImmutableArray<MethodSymbol> originalMethods,
LookupResultKind resultKind,
Binder binder)
{
if (!originalMethods.IsEmpty)
resultKind = resultKind.WorseResultKind(LookupResultKind.OverloadResolutionFailure);
Debug.Assert(arguments.IsDefaultOrEmpty || (object)receiverOpt != (object)arguments[0]);
var call = new BoundCall(node, receiverOpt, method, arguments, namedArguments,
refKinds, isDelegateCall: isDelegateCall, expanded: false, invokedAsExtensionMethod: invokedAsExtensionMethod, argsToParamsOpt: default(ImmutableArray<int>),
resultKind: resultKind, binderOpt: binder, type: method.ReturnType.TypeSymbol, hasErrors: true);
call.OriginalMethodsOpt = originalMethods;
return call;
}
public BoundCall Update(BoundExpression receiverOpt, MethodSymbol method, ImmutableArray<BoundExpression> arguments)
{
return this.Update(receiverOpt, method, arguments, ArgumentNamesOpt, ArgumentRefKindsOpt, IsDelegateCall, Expanded, InvokedAsExtensionMethod, ArgsToParamsOpt, ResultKind, BinderOpt, Type);
}
public static BoundCall Synthesized(SyntaxNode syntax, BoundExpression receiverOpt, MethodSymbol method)
{
return Synthesized(syntax, receiverOpt, method, ImmutableArray<BoundExpression>.Empty);
}
public static BoundCall Synthesized(SyntaxNode syntax, BoundExpression receiverOpt, MethodSymbol method, BoundExpression arg0)
{
return Synthesized(syntax, receiverOpt, method, ImmutableArray.Create(arg0));
}
public static BoundCall Synthesized(SyntaxNode syntax, BoundExpression receiverOpt, MethodSymbol method, BoundExpression arg0, BoundExpression arg1)
{
return Synthesized(syntax, receiverOpt, method, ImmutableArray.Create(arg0, arg1));
}
public static BoundCall Synthesized(SyntaxNode syntax, BoundExpression receiverOpt, MethodSymbol method, ImmutableArray<BoundExpression> arguments)
{
return new BoundCall(syntax,
receiverOpt,
method,
arguments,
argumentNamesOpt: default(ImmutableArray<string>),
argumentRefKindsOpt: method.ParameterRefKinds,
isDelegateCall: false,
expanded: false,
invokedAsExtensionMethod: false,
argsToParamsOpt: default(ImmutableArray<int>),
resultKind: LookupResultKind.Viable,
binderOpt: null,
type: method.ReturnType.TypeSymbol,
hasErrors: method.OriginalDefinition is ErrorMethodSymbol
)
{ WasCompilerGenerated = true };
}
}
internal sealed partial class BoundObjectCreationExpression
{
public BoundObjectCreationExpression(SyntaxNode syntax, MethodSymbol constructor, Binder binderOpt, params BoundExpression[] arguments)
: this(syntax, constructor, ImmutableArray.Create<BoundExpression>(arguments), default(ImmutableArray<string>), default(ImmutableArray<RefKind>), false, default(ImmutableArray<int>), null, null, binderOpt, constructor.ContainingType)
{
}
public BoundObjectCreationExpression(SyntaxNode syntax, MethodSymbol constructor, Binder binderOpt, ImmutableArray<BoundExpression> arguments)
: this(syntax, constructor, arguments, default(ImmutableArray<string>), default(ImmutableArray<RefKind>), false, default(ImmutableArray<int>), null, null, binderOpt, constructor.ContainingType)
{
}
}
internal partial class BoundIndexerAccess
{
public static BoundIndexerAccess ErrorAccess(
SyntaxNode node,
BoundExpression receiverOpt,
PropertySymbol indexer,
ImmutableArray<BoundExpression> arguments,
ImmutableArray<string> namedArguments,
ImmutableArray<RefKind> refKinds,
ImmutableArray<PropertySymbol> originalIndexers)
{
return new BoundIndexerAccess(
node,
receiverOpt,
indexer,
arguments,
namedArguments,
refKinds,
expanded: false,
argsToParamsOpt: default(ImmutableArray<int>),
binderOpt: null,
useSetterForDefaultArgumentGeneration: false,
type: indexer.Type.TypeSymbol,
hasErrors: true)
{
OriginalIndexersOpt = originalIndexers
};
}
}
internal sealed partial class BoundConversion
{
/// <remarks>
/// This method is intended for passes other than the LocalRewriter.
/// Use MakeConversion helper method in the LocalRewriter instead,
/// it generates a synthesized conversion in its lowered form.
/// </remarks>
public static BoundConversion SynthesizedNonUserDefined(SyntaxNode syntax, BoundExpression operand, Conversion conversion, TypeSymbol type, ConstantValue constantValueOpt = null)
{
return new BoundConversion(
syntax,
operand,
conversion,
isBaseConversion: false,
@checked: false,
explicitCastInCode: false,
conversionGroupOpt: null,
constantValueOpt: constantValueOpt,
type: type)
{ WasCompilerGenerated = true };
}
/// <remarks>
/// NOTE: This method is intended for passes other than the LocalRewriter.
/// NOTE: Use MakeConversion helper method in the LocalRewriter instead,
/// NOTE: it generates a synthesized conversion in its lowered form.
/// </remarks>
public static BoundConversion Synthesized(
SyntaxNode syntax,
BoundExpression operand,
Conversion conversion,
bool @checked,
bool explicitCastInCode,
ConversionGroup conversionGroupOpt,
ConstantValue constantValueOpt,
TypeSymbol type,
bool hasErrors = false)
{
return new BoundConversion(
syntax,
operand,
conversion,
@checked,
explicitCastInCode: explicitCastInCode,
conversionGroupOpt,
constantValueOpt,
type,
hasErrors || !conversion.IsValid)
{
WasCompilerGenerated = true
};
}
public BoundConversion(
SyntaxNode syntax,
BoundExpression operand,
Conversion conversion,
bool @checked,
bool explicitCastInCode,
ConversionGroup conversionGroupOpt,
ConstantValue constantValueOpt,
TypeSymbol type,
bool hasErrors = false)
: this(
syntax,
operand,
conversion,
isBaseConversion: false,
@checked: @checked,
explicitCastInCode: explicitCastInCode,
constantValueOpt: constantValueOpt,
conversionGroupOpt,
type: type,
hasErrors: hasErrors || !conversion.IsValid)
{
OriginalUserDefinedConversionsOpt = conversion.OriginalUserDefinedConversions;
}
}
internal sealed partial class BoundUnaryOperator
{
internal BoundUnaryOperator(
SyntaxNode syntax,
UnaryOperatorKind operatorKind,
BoundExpression operand,
ConstantValue constantValueOpt,
MethodSymbol methodOpt,
LookupResultKind resultKind,
ImmutableArray<MethodSymbol> originalUserDefinedOperatorsOpt,
TypeSymbol type,
bool hasErrors = false)
: this(
syntax,
operatorKind,
operand,
constantValueOpt,
methodOpt,
resultKind,
type,
hasErrors)
{
this.OriginalUserDefinedOperatorsOpt = originalUserDefinedOperatorsOpt;
}
}
internal sealed partial class BoundIncrementOperator
{
public BoundIncrementOperator(
SyntaxNode syntax,
UnaryOperatorKind operatorKind,
BoundExpression operand,
MethodSymbol methodOpt,
Conversion operandConversion,
Conversion resultConversion,
LookupResultKind resultKind,
ImmutableArray<MethodSymbol> originalUserDefinedOperatorsOpt,
TypeSymbol type,
bool hasErrors = false)
: this(
syntax,
operatorKind,
operand,
methodOpt,
operandConversion,
resultConversion,
resultKind,
type,
hasErrors)
{
this.OriginalUserDefinedOperatorsOpt = originalUserDefinedOperatorsOpt;
}
}
internal sealed partial class BoundBinaryOperator
{
public BoundBinaryOperator(
SyntaxNode syntax,
BinaryOperatorKind operatorKind,
BoundExpression left,
BoundExpression right,
ConstantValue constantValueOpt,
MethodSymbol methodOpt,
LookupResultKind resultKind,
ImmutableArray<MethodSymbol> originalUserDefinedOperatorsOpt,
TypeSymbol type,
bool hasErrors = false)
: this(
syntax,
operatorKind,
left,
right,
constantValueOpt,
methodOpt,
resultKind,
type,
hasErrors)
{
this.OriginalUserDefinedOperatorsOpt = originalUserDefinedOperatorsOpt;
}
}
internal sealed partial class BoundUserDefinedConditionalLogicalOperator
{
public BoundUserDefinedConditionalLogicalOperator(
SyntaxNode syntax,
BinaryOperatorKind operatorKind,
BoundExpression left,
BoundExpression right,
MethodSymbol logicalOperator,
MethodSymbol trueOperator,
MethodSymbol falseOperator,
LookupResultKind resultKind,
ImmutableArray<MethodSymbol> originalUserDefinedOperatorsOpt,
TypeSymbol type,
bool hasErrors = false)
: this(
syntax,
operatorKind,
left,
right,
logicalOperator,
trueOperator,
falseOperator,
resultKind,
type,
hasErrors)
{
Debug.Assert(operatorKind.IsUserDefined() && operatorKind.IsLogical());
this.OriginalUserDefinedOperatorsOpt = originalUserDefinedOperatorsOpt;
}
}
internal sealed partial class BoundCompoundAssignmentOperator
{
public BoundCompoundAssignmentOperator(
SyntaxNode syntax,
BinaryOperatorSignature @operator,
BoundExpression left,
BoundExpression right,
Conversion leftConversion,
Conversion finalConversion,
LookupResultKind resultKind,
ImmutableArray<MethodSymbol> originalUserDefinedOperatorsOpt,
TypeSymbol type,
bool hasErrors = false)
: this(
syntax,
@operator,
left,
right,
leftConversion,
finalConversion,
resultKind,
type,
hasErrors)
{
this.OriginalUserDefinedOperatorsOpt = originalUserDefinedOperatorsOpt;
}
}
internal sealed partial class BoundParameter
{
public BoundParameter(SyntaxNode syntax, ParameterSymbol parameterSymbol, bool hasErrors = false)
: this(syntax, parameterSymbol, parameterSymbol.Type.TypeSymbol, hasErrors)
{
}
public BoundParameter(SyntaxNode syntax, ParameterSymbol parameterSymbol)
: this(syntax, parameterSymbol, parameterSymbol.Type.TypeSymbol)
{
}
}
internal sealed partial class BoundTypeExpression
{
public BoundTypeExpression(SyntaxNode syntax, AliasSymbol aliasOpt, TypeSymbol type, bool hasErrors = false)
: this(syntax, aliasOpt, false, null, type, hasErrors)
{
}
public BoundTypeExpression(SyntaxNode syntax, AliasSymbol aliasOpt, TypeSymbol type)
: this(syntax, aliasOpt, false, null, type)
{
}
public BoundTypeExpression(SyntaxNode syntax, AliasSymbol aliasOpt, bool inferredType, TypeSymbol type, bool hasErrors = false)
: this(syntax, aliasOpt, inferredType, null, type, hasErrors)
{
}
}
internal sealed partial class BoundNamespaceExpression
{
public BoundNamespaceExpression(SyntaxNode syntax, NamespaceSymbol namespaceSymbol, bool hasErrors = false)
: this(syntax, namespaceSymbol, null, hasErrors)
{
}
public BoundNamespaceExpression(SyntaxNode syntax, NamespaceSymbol namespaceSymbol)
: this(syntax, namespaceSymbol, null)
{
}
public BoundNamespaceExpression Update(NamespaceSymbol namespaceSymbol)
{
return Update(namespaceSymbol, this.AliasOpt);
}
}
internal sealed partial class BoundAssignmentOperator
{
public BoundAssignmentOperator(SyntaxNode syntax, BoundExpression left, BoundExpression right,
TypeSymbol type, bool isRef = false, bool hasErrors = false)
: this(syntax, left, right, isRef, type, hasErrors)
{
}
}
internal sealed partial class BoundBadExpression
{
public BoundBadExpression(SyntaxNode syntax, LookupResultKind resultKind, ImmutableArray<Symbol> symbols, ImmutableArray<BoundExpression> childBoundNodes, TypeSymbol type)
: this(syntax, resultKind, symbols, childBoundNodes, type, true)
{
Debug.Assert((object)type != null);
}
}
internal partial class BoundStatementList
{
public static BoundStatementList Synthesized(SyntaxNode syntax, params BoundStatement[] statements)
{
return Synthesized(syntax, false, statements.AsImmutableOrNull());
}
public static BoundStatementList Synthesized(SyntaxNode syntax, bool hasErrors, params BoundStatement[] statements)
{
return Synthesized(syntax, hasErrors, statements.AsImmutableOrNull());
}
public static BoundStatementList Synthesized(SyntaxNode syntax, ImmutableArray<BoundStatement> statements)
{
return Synthesized(syntax, false, statements);
}
public static BoundStatementList Synthesized(SyntaxNode syntax, bool hasErrors, ImmutableArray<BoundStatement> statements)
{
return new BoundStatementList(syntax, statements, hasErrors) { WasCompilerGenerated = true };
}
}
internal sealed partial class BoundReturnStatement
{
public static BoundReturnStatement Synthesized(SyntaxNode syntax, RefKind refKind, BoundExpression expression, bool hasErrors = false)
{
return new BoundReturnStatement(syntax, refKind, expression, hasErrors) { WasCompilerGenerated = true };
}
}
internal sealed partial class BoundYieldBreakStatement
{
public static BoundYieldBreakStatement Synthesized(SyntaxNode syntax, bool hasErrors = false)
{
return new BoundYieldBreakStatement(syntax, hasErrors) { WasCompilerGenerated = true };
}
}
internal sealed partial class BoundGotoStatement
{
public BoundGotoStatement(SyntaxNode syntax, LabelSymbol label, bool hasErrors = false)
: this(syntax, label, caseExpressionOpt: null, labelExpressionOpt: null, hasErrors: hasErrors)
{
}
}
internal partial class BoundBlock
{
public BoundBlock(SyntaxNode syntax, ImmutableArray<LocalSymbol> locals, ImmutableArray<BoundStatement> statements, bool hasErrors = false) : this(syntax, locals, ImmutableArray<LocalFunctionSymbol>.Empty, statements, hasErrors)
{
}
public static BoundBlock SynthesizedNoLocals(SyntaxNode syntax, BoundStatement statement)
{
return new BoundBlock(syntax, ImmutableArray<LocalSymbol>.Empty, ImmutableArray.Create(statement))
{ WasCompilerGenerated = true };
}
public static BoundBlock SynthesizedNoLocals(SyntaxNode syntax, ImmutableArray<BoundStatement> statements)
{
return new BoundBlock(syntax, ImmutableArray<LocalSymbol>.Empty, statements) { WasCompilerGenerated = true };
}
public static BoundBlock SynthesizedNoLocals(SyntaxNode syntax, params BoundStatement[] statements)
{
return new BoundBlock(syntax, ImmutableArray<LocalSymbol>.Empty, statements.AsImmutableOrNull()) { WasCompilerGenerated = true };
}
}
internal partial class BoundDefaultExpression
{
public BoundDefaultExpression(SyntaxNode syntax, TypeSymbol type, bool hasErrors = false)
: this(syntax, type.GetDefaultValue(), type, hasErrors)
{
}
}
internal partial class BoundTryStatement
{
public BoundTryStatement(SyntaxNode syntax, BoundBlock tryBlock, ImmutableArray<BoundCatchBlock> catchBlocks, BoundBlock finallyBlockOpt)
: this(syntax, tryBlock, catchBlocks, finallyBlockOpt, preferFaultHandler: false, hasErrors: false)
{
}
}
internal partial class BoundDeclarationPattern
{
public BoundDeclarationPattern(SyntaxNode syntax, LocalSymbol localSymbol, BoundTypeExpression declaredType, bool isVar, bool hasErrors = false)
: this(syntax, localSymbol, localSymbol == null ? new BoundDiscardExpression(syntax, declaredType.Type) : (BoundExpression)new BoundLocal(syntax, localSymbol, null, declaredType.Type), declaredType, isVar, hasErrors)
{
}
}
internal partial class BoundAddressOfOperator
{
public BoundAddressOfOperator(SyntaxNode syntax, BoundExpression operand, TypeSymbol type, bool hasErrors = false)
: this(syntax, operand, isManaged: false, type, hasErrors)
{
}
}
}
| 38.523236 | 245 | 0.622241 | [
"Apache-2.0"
] | Ashera138/roslyn | src/Compilers/CSharp/Portable/BoundTree/Constructors.cs | 22,384 | C# |
using System.Collections.Generic;
using System.Linq;
using LinqFasterer.Shared;
using Xunit;
namespace LinqFasterer.Tests
{
public partial class Test
{
[Theory]
[Trait(nameof(EnumerableF.WhereF), null)]
[MemberData(nameof(Utilities.TestArray), typeof(int), 5, 0, 100, MemberType = typeof(Utilities))]
[MemberData(nameof(Utilities.TestArray), typeof(int), 10, 0, 2, MemberType = typeof(Utilities))]
[MemberData(nameof(Utilities.TestArray), typeof(int), 50, 0, 5, MemberType = typeof(Utilities))]
public void WhereTest_Int(IList<int> source)
{
var expected = source.Where(v => v % 2 == 0).ToArray();
var actual = source.WhereF(v => v % 2 == 0, true).ToArrayF();
var actualIndexed = source.WhereF((v, i) => v % 2 == 0, true).ToArrayF();
Assert.Equal(expected, actual);
Assert.Equal(expected, actualIndexed);
}
}
} | 37.96 | 105 | 0.620653 | [
"MIT"
] | Zaczero/LinqFaster | LinqFasterer.Tests/WhereTests.cs | 951 | C# |
// SPDX-License-Identifier: MIT
// Copyright (c) 2018-2021 David Lechner <david@lechnology.com>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;
namespace GISharp.CodeGen.Gir
{
/// <summary>
/// Common base class for all GIR element types
/// </summary>
public abstract class GirNode
{
// Analysis disable InconsistentNaming
private protected static readonly XNamespace gi = Globals.CoreNamespace;
private protected static readonly XNamespace c = Globals.CNamespace;
private protected static readonly XNamespace glib = Globals.GLibNamespace;
private protected static readonly XNamespace gs = Globals.GISharpNamespace;
// Analysis restore InconsistentNaming
/// <summary>
/// The XML element from the GIR file
/// </summary>
public XElement Element { get; }
/// <summary>
/// The parent node
/// </summary>
public GirNode ParentNode { get; }
/// <summary>
/// Gets the ancestors of this node, starting with the parent
/// </summary>
public IEnumerable<GirNode> Ancestors => _Ancestors.Value;
readonly Lazy<List<GirNode>> _Ancestors;
/// <summary>
/// The documentation node, if any
/// </summary>
public Doc Doc => _Doc.Value;
readonly Lazy<Doc> _Doc;
protected GirNode(XElement element, GirNode parent)
{
Element = element ?? throw new ArgumentNullException(nameof(element));
ParentNode = parent;
_Ancestors = new(() => LazyGetAncestors().ToList());
_Doc = new(LazyGetDoc, false);
element.AddAnnotation(this);
}
public static GirNode GetNode(XElement element)
{
if (element is null) {
return null;
}
// if this element already has a node object attached, use it
var node = element.Annotation<GirNode>();
if (node is not null) {
return node;
}
// otherwise, create a new node based on the element name
if (element.Name == gi + "alias") {
return new Alias(element, GetNode(element.Parent));
}
else if (element.Name == gi + "array") {
return new Array(element, GetNode(element.Parent));
}
else if (element.Name == gi + "bitfield") {
return new Bitfield(element, GetNode(element.Parent));
}
else if (element.Name == gi + "callback") {
return new Callback(element, GetNode(element.Parent));
}
else if (element.Name == gi + "class") {
return new Class(element, GetNode(element.Parent));
}
else if (element.Name == gi + "constant") {
return new Constant(element, GetNode(element.Parent));
}
else if (element.Name == gi + "constructor") {
return new Constructor(element, GetNode(element.Parent));
}
else if (element.Name == gi + "doc") {
return new Doc(element, GetNode(element.Parent));
}
else if (element.Name == gi + "doc-deprecated") {
return new DocDeprecated(element, GetNode(element.Parent));
}
else if (element.Name == gi + "enumeration") {
return new Enumeration(element, GetNode(element.Parent));
}
else if (element.Name == gs + "error-parameter") {
return new ErrorParameter(element, GetNode(element.Parent));
}
else if (element.Name == gi + "field") {
return new Field(element, GetNode(element.Parent));
}
else if (element.Name == gi + "function") {
return new Function(element, GetNode(element.Parent));
}
else if (element.Name == gi + "instance-parameter") {
return new InstanceParameter(element, GetNode(element.Parent));
}
else if (element.Name == gi + "interface") {
return new Interface(element, GetNode(element.Parent));
}
else if (element.Name == gi + "implements") {
return new Implements(element, GetNode(element.Parent));
}
else if (element.Name == gs + "managed-property") {
return new ManagedProperty(element, GetNode(element.Parent));
}
else if (element.Name == gs + "managed-parameters") {
return new ManagedParameters(element, GetNode(element.Parent));
}
else if (element.Name == gi + "member") {
return new Member(element, GetNode(element.Parent));
}
else if (element.Name == gi + "method") {
return new Method(element, GetNode(element.Parent));
}
else if (element.Name == gi + "namespace") {
return new Namespace(element, GetNode(element.Parent));
}
else if (element.Name == gi + "package") {
return new Package(element, GetNode(element.Parent));
}
else if (element.Name == gi + "parameter") {
return new Parameter(element, GetNode(element.Parent));
}
else if (element.Name == gi + "parameters") {
return new Parameters(element, GetNode(element.Parent));
}
else if (element.Name == gi + "prerequisite") {
return new Prerequisite(element, GetNode(element.Parent));
}
else if (element.Name == gi + "property") {
return new Property(element, GetNode(element.Parent));
}
else if (element.Name == gi + "record") {
return new Record(element, GetNode(element.Parent));
}
else if (element.Name == gi + "return-value") {
return new ReturnValue(element, GetNode(element.Parent));
}
else if (element.Name == glib + "signal") {
return new Signal(element, GetNode(element.Parent));
}
else if (element.Name == gs + "static-class") {
return new StaticClass(element, GetNode(element.Parent));
}
else if (element.Name == gi + "type") {
return new Type(element, GetNode(element.Parent));
}
else if (element.Name == gi + "union") {
return new Union(element, GetNode(element.Parent));
}
else if (element.Name == gi + "virtual-method") {
return new VirtualMethod(element, GetNode(element.Parent));
}
else if (element.Name == gi + "docsection") {
return new DocSection(element, GetNode(element.Parent));
}
else if (element.Name == glib + "boxed") {
return new Boxed(element, GetNode(element.Parent));
}
else if (element.Name == gi + "source-position") {
return new SourcePosition(element, GetNode(element.Parent));
}
var message = $"Unknown element <{element.Name}>";
throw new ArgumentException(message, nameof(element));
}
IEnumerable<GirNode> LazyGetAncestors()
{
var node = this;
while ((node = node.ParentNode) is not null) {
yield return node;
}
}
Doc LazyGetDoc() => (Doc)GetNode(Element.Element(gi + "doc"));
}
}
| 40.4375 | 83 | 0.534905 | [
"MIT"
] | dlech/gisharp | tools/CodeGen/Gir/GirNode.cs | 7,764 | C# |
#pragma checksum "C:\Users\a\Desktop\angular\new\OnlineStore\Auth\Views\Shared\_Layout.cshtml" "{ff1816ec-aa5e-4d10-87f7-6f4963833460}" "31c859f5f1469ab42009dd188032e94f5caa7ecb"
// <auto-generated/>
#pragma warning disable 1591
[assembly: global::Microsoft.AspNetCore.Razor.Hosting.RazorCompiledItemAttribute(typeof(AspNetCore.Views_Shared__Layout), @"mvc.1.0.view", @"/Views/Shared/_Layout.cshtml")]
namespace AspNetCore
{
#line hidden
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
#nullable restore
#line 1 "C:\Users\a\Desktop\angular\new\OnlineStore\Auth\Views\_ViewImports.cshtml"
using Auth.Models;
#line default
#line hidden
#nullable disable
#nullable restore
#line 2 "C:\Users\a\Desktop\angular\new\OnlineStore\Auth\Views\_ViewImports.cshtml"
using IdentityServer4;
#line default
#line hidden
#nullable disable
#nullable restore
#line 1 "C:\Users\a\Desktop\angular\new\OnlineStore\Auth\Views\Shared\_Layout.cshtml"
using IdentityServer4.Extensions;
#line default
#line hidden
#nullable disable
[global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"31c859f5f1469ab42009dd188032e94f5caa7ecb", @"/Views/Shared/_Layout.cshtml")]
[global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"ae3be0c35d7e35a3ec6e0b31d307bbb2eb16e6d7", @"/Views/_ViewImports.cshtml")]
public class Views_Shared__Layout : global::Microsoft.AspNetCore.Mvc.Razor.RazorPage<dynamic>
{
private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_0 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("rel", new global::Microsoft.AspNetCore.Html.HtmlString("icon"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_1 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("type", new global::Microsoft.AspNetCore.Html.HtmlString("image/x-icon"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_2 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("href", new global::Microsoft.AspNetCore.Html.HtmlString("~/favicon.ico"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_3 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("rel", new global::Microsoft.AspNetCore.Html.HtmlString("shortcut icon"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_4 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("rel", new global::Microsoft.AspNetCore.Html.HtmlString("stylesheet"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_5 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("href", new global::Microsoft.AspNetCore.Html.HtmlString("~/lib/bootstrap/dist/css/bootstrap.css"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_6 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("include", "Development", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_7 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("href", "https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_8 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("asp-fallback-href", "~/lib/bootstrap/dist/css/bootstrap.min.css", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_9 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("asp-fallback-test-class", "sr-only", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_10 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("asp-fallback-test-property", "position", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_11 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("asp-fallback-test-value", "absolute", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_12 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("crossorigin", new global::Microsoft.AspNetCore.Html.HtmlString("anonymous"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_13 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("integrity", new global::Microsoft.AspNetCore.Html.HtmlString("sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_14 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("exclude", "Development", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_15 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("href", new global::Microsoft.AspNetCore.Html.HtmlString("~/css/site.css"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_16 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("class", new global::Microsoft.AspNetCore.Html.HtmlString("navbar-brand"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_17 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("asp-area", "", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_18 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("asp-controller", "Home", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_19 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("asp-action", "Index", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_20 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("class", new global::Microsoft.AspNetCore.Html.HtmlString("nav-link text-dark"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_21 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("src", new global::Microsoft.AspNetCore.Html.HtmlString("~/lib/jquery/dist/jquery.js"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_22 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("src", new global::Microsoft.AspNetCore.Html.HtmlString("~/lib/bootstrap/dist/js/bootstrap.bundle.js"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_23 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("src", "https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_24 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("asp-fallback-src", "~/lib/jquery/dist/jquery.min.js", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_25 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("asp-fallback-test", "window.jQuery", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_26 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("integrity", new global::Microsoft.AspNetCore.Html.HtmlString("sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_27 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("src", "https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.bundle.min.js", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_28 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("asp-fallback-src", "~/lib/bootstrap/dist/js/bootstrap.bundle.min.js", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_29 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("asp-fallback-test", "window.jQuery && window.jQuery.fn && window.jQuery.fn.modal", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_30 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("integrity", new global::Microsoft.AspNetCore.Html.HtmlString("sha384-xrRywqdh3PHs8keKZN+8zzc5TX0GRTLCcmivcbNJWm2rs5C8PRhcEn3czEjhAO9o"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_31 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("src", "~/js/site.js", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
#line hidden
#pragma warning disable 0649
private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperExecutionContext __tagHelperExecutionContext;
#pragma warning restore 0649
private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperRunner __tagHelperRunner = new global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperRunner();
#pragma warning disable 0169
private string __tagHelperStringValueBuffer;
#pragma warning restore 0169
private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperScopeManager __backed__tagHelperScopeManager = null;
private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperScopeManager __tagHelperScopeManager
{
get
{
if (__backed__tagHelperScopeManager == null)
{
__backed__tagHelperScopeManager = new global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperScopeManager(StartTagHelperWritingScope, EndTagHelperWritingScope);
}
return __backed__tagHelperScopeManager;
}
}
private global::Microsoft.AspNetCore.Mvc.Razor.TagHelpers.HeadTagHelper __Microsoft_AspNetCore_Mvc_Razor_TagHelpers_HeadTagHelper;
private global::Microsoft.AspNetCore.Mvc.Razor.TagHelpers.UrlResolutionTagHelper __Microsoft_AspNetCore_Mvc_Razor_TagHelpers_UrlResolutionTagHelper;
private global::Microsoft.AspNetCore.Mvc.TagHelpers.EnvironmentTagHelper __Microsoft_AspNetCore_Mvc_TagHelpers_EnvironmentTagHelper;
private global::Microsoft.AspNetCore.Mvc.TagHelpers.LinkTagHelper __Microsoft_AspNetCore_Mvc_TagHelpers_LinkTagHelper;
private global::Microsoft.AspNetCore.Mvc.Razor.TagHelpers.BodyTagHelper __Microsoft_AspNetCore_Mvc_Razor_TagHelpers_BodyTagHelper;
private global::Microsoft.AspNetCore.Mvc.TagHelpers.AnchorTagHelper __Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper;
private global::Microsoft.AspNetCore.Mvc.TagHelpers.ScriptTagHelper __Microsoft_AspNetCore_Mvc_TagHelpers_ScriptTagHelper;
#pragma warning disable 1998
public async override global::System.Threading.Tasks.Task ExecuteAsync()
{
#nullable restore
#line 2 "C:\Users\a\Desktop\angular\new\OnlineStore\Auth\Views\Shared\_Layout.cshtml"
string name = null;
if (!true.Equals(ViewData["signed-out"]))
{
name = Context.User?.GetDisplayName();
}
#line default
#line hidden
#nullable disable
WriteLiteral("<!DOCTYPE html>\r\n<html>\r\n");
__tagHelperExecutionContext = __tagHelperScopeManager.Begin("head", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "31c859f5f1469ab42009dd188032e94f5caa7ecb15475", async() => {
WriteLiteral("\r\n <meta charset=\"utf-8\" />\r\n <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\">\r\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" />\r\n <title>My Sample ISP</title>\r\n ");
__tagHelperExecutionContext = __tagHelperScopeManager.Begin("link", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.SelfClosing, "31c859f5f1469ab42009dd188032e94f5caa7ecb15957", async() => {
}
);
__Microsoft_AspNetCore_Mvc_Razor_TagHelpers_UrlResolutionTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.Razor.TagHelpers.UrlResolutionTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_Razor_TagHelpers_UrlResolutionTagHelper);
__tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_0);
__tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_1);
__tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_2);
await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);
if (!__tagHelperExecutionContext.Output.IsContentModified)
{
await __tagHelperExecutionContext.SetOutputContentAsync();
}
Write(__tagHelperExecutionContext.Output);
__tagHelperExecutionContext = __tagHelperScopeManager.End();
WriteLiteral("\r\n ");
__tagHelperExecutionContext = __tagHelperScopeManager.Begin("link", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.SelfClosing, "31c859f5f1469ab42009dd188032e94f5caa7ecb17223", async() => {
}
);
__Microsoft_AspNetCore_Mvc_Razor_TagHelpers_UrlResolutionTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.Razor.TagHelpers.UrlResolutionTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_Razor_TagHelpers_UrlResolutionTagHelper);
__tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_3);
__tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_1);
__tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_2);
await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);
if (!__tagHelperExecutionContext.Output.IsContentModified)
{
await __tagHelperExecutionContext.SetOutputContentAsync();
}
Write(__tagHelperExecutionContext.Output);
__tagHelperExecutionContext = __tagHelperScopeManager.End();
WriteLiteral("\r\n ");
__tagHelperExecutionContext = __tagHelperScopeManager.Begin("environment", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "31c859f5f1469ab42009dd188032e94f5caa7ecb18489", async() => {
WriteLiteral("\r\n ");
__tagHelperExecutionContext = __tagHelperScopeManager.Begin("link", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.SelfClosing, "31c859f5f1469ab42009dd188032e94f5caa7ecb18771", async() => {
}
);
__Microsoft_AspNetCore_Mvc_Razor_TagHelpers_UrlResolutionTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.Razor.TagHelpers.UrlResolutionTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_Razor_TagHelpers_UrlResolutionTagHelper);
__tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_4);
__tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_5);
await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);
if (!__tagHelperExecutionContext.Output.IsContentModified)
{
await __tagHelperExecutionContext.SetOutputContentAsync();
}
Write(__tagHelperExecutionContext.Output);
__tagHelperExecutionContext = __tagHelperScopeManager.End();
WriteLiteral("\r\n ");
}
);
__Microsoft_AspNetCore_Mvc_TagHelpers_EnvironmentTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.EnvironmentTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_EnvironmentTagHelper);
__Microsoft_AspNetCore_Mvc_TagHelpers_EnvironmentTagHelper.Include = (string)__tagHelperAttribute_6.Value;
__tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_6);
await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);
if (!__tagHelperExecutionContext.Output.IsContentModified)
{
await __tagHelperExecutionContext.SetOutputContentAsync();
}
Write(__tagHelperExecutionContext.Output);
__tagHelperExecutionContext = __tagHelperScopeManager.End();
WriteLiteral("\r\n ");
__tagHelperExecutionContext = __tagHelperScopeManager.Begin("environment", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "31c859f5f1469ab42009dd188032e94f5caa7ecb20989", async() => {
WriteLiteral("\r\n ");
__tagHelperExecutionContext = __tagHelperScopeManager.Begin("link", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.SelfClosing, "31c859f5f1469ab42009dd188032e94f5caa7ecb21271", async() => {
}
);
__Microsoft_AspNetCore_Mvc_TagHelpers_LinkTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.LinkTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_LinkTagHelper);
__tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_4);
__Microsoft_AspNetCore_Mvc_TagHelpers_LinkTagHelper.Href = (string)__tagHelperAttribute_7.Value;
__tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_7);
__Microsoft_AspNetCore_Mvc_TagHelpers_LinkTagHelper.FallbackHref = (string)__tagHelperAttribute_8.Value;
__tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_8);
__Microsoft_AspNetCore_Mvc_TagHelpers_LinkTagHelper.FallbackTestClass = (string)__tagHelperAttribute_9.Value;
__tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_9);
__Microsoft_AspNetCore_Mvc_TagHelpers_LinkTagHelper.FallbackTestProperty = (string)__tagHelperAttribute_10.Value;
__tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_10);
__Microsoft_AspNetCore_Mvc_TagHelpers_LinkTagHelper.FallbackTestValue = (string)__tagHelperAttribute_11.Value;
__tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_11);
__tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_12);
__tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_13);
await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);
if (!__tagHelperExecutionContext.Output.IsContentModified)
{
await __tagHelperExecutionContext.SetOutputContentAsync();
}
Write(__tagHelperExecutionContext.Output);
__tagHelperExecutionContext = __tagHelperScopeManager.End();
WriteLiteral("\r\n ");
}
);
__Microsoft_AspNetCore_Mvc_TagHelpers_EnvironmentTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.EnvironmentTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_EnvironmentTagHelper);
__Microsoft_AspNetCore_Mvc_TagHelpers_EnvironmentTagHelper.Exclude = (string)__tagHelperAttribute_14.Value;
__tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_14);
await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);
if (!__tagHelperExecutionContext.Output.IsContentModified)
{
await __tagHelperExecutionContext.SetOutputContentAsync();
}
Write(__tagHelperExecutionContext.Output);
__tagHelperExecutionContext = __tagHelperScopeManager.End();
WriteLiteral("\r\n ");
__tagHelperExecutionContext = __tagHelperScopeManager.Begin("link", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.SelfClosing, "31c859f5f1469ab42009dd188032e94f5caa7ecb24663", async() => {
}
);
__Microsoft_AspNetCore_Mvc_Razor_TagHelpers_UrlResolutionTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.Razor.TagHelpers.UrlResolutionTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_Razor_TagHelpers_UrlResolutionTagHelper);
__tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_4);
__tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_15);
await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);
if (!__tagHelperExecutionContext.Output.IsContentModified)
{
await __tagHelperExecutionContext.SetOutputContentAsync();
}
Write(__tagHelperExecutionContext.Output);
__tagHelperExecutionContext = __tagHelperScopeManager.End();
WriteLiteral("\r\n");
}
);
__Microsoft_AspNetCore_Mvc_Razor_TagHelpers_HeadTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.Razor.TagHelpers.HeadTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_Razor_TagHelpers_HeadTagHelper);
await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);
if (!__tagHelperExecutionContext.Output.IsContentModified)
{
await __tagHelperExecutionContext.SetOutputContentAsync();
}
Write(__tagHelperExecutionContext.Output);
__tagHelperExecutionContext = __tagHelperScopeManager.End();
WriteLiteral("\r\n");
__tagHelperExecutionContext = __tagHelperScopeManager.Begin("body", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "31c859f5f1469ab42009dd188032e94f5caa7ecb26547", async() => {
WriteLiteral("\r\n <header>\r\n <nav class=\"navbar navbar-expand-sm navbar-toggleable-sm navbar-light bg-white border-bottom box-shadow mb-3\">\r\n <div class=\"container\">\r\n ");
__tagHelperExecutionContext = __tagHelperScopeManager.Begin("a", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "31c859f5f1469ab42009dd188032e94f5caa7ecb27003", async() => {
WriteLiteral("My Sample Identity Service Provider");
}
);
__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.AnchorTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper);
__tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_16);
__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper.Area = (string)__tagHelperAttribute_17.Value;
__tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_17);
__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper.Controller = (string)__tagHelperAttribute_18.Value;
__tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_18);
__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper.Action = (string)__tagHelperAttribute_19.Value;
__tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_19);
await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);
if (!__tagHelperExecutionContext.Output.IsContentModified)
{
await __tagHelperExecutionContext.SetOutputContentAsync();
}
Write(__tagHelperExecutionContext.Output);
__tagHelperExecutionContext = __tagHelperScopeManager.End();
WriteLiteral(@"
<button class=""navbar-toggler"" type=""button"" data-toggle=""collapse"" data-target="".navbar-collapse"" aria-controls=""navbarSupportedContent""
aria-expanded=""false"" aria-label=""Toggle navigation"">
<span class=""navbar-toggler-icon""></span>
</button>
<div class=""navbar-collapse collapse d-sm-inline-flex flex-sm-row-reverse"">
<ul class=""navbar-nav flex-grow-1"">
<li class=""nav-item"">
");
__tagHelperExecutionContext = __tagHelperScopeManager.Begin("a", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "31c859f5f1469ab42009dd188032e94f5caa7ecb29338", async() => {
WriteLiteral("Home");
}
);
__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.AnchorTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper);
__tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_20);
__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper.Area = (string)__tagHelperAttribute_17.Value;
__tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_17);
__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper.Controller = (string)__tagHelperAttribute_18.Value;
__tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_18);
__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper.Action = (string)__tagHelperAttribute_19.Value;
__tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_19);
await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);
if (!__tagHelperExecutionContext.Output.IsContentModified)
{
await __tagHelperExecutionContext.SetOutputContentAsync();
}
Write(__tagHelperExecutionContext.Output);
__tagHelperExecutionContext = __tagHelperScopeManager.End();
WriteLiteral("\r\n </li>\r\n </ul>\r\n </div>\r\n </div>\r\n </nav>\r\n </header>\r\n <div class=\"container\">\r\n <main role=\"main\" class=\"pb-3\">\r\n ");
#nullable restore
#line 51 "C:\Users\a\Desktop\angular\new\OnlineStore\Auth\Views\Shared\_Layout.cshtml"
Write(RenderBody());
#line default
#line hidden
#nullable disable
WriteLiteral("\r\n </main>\r\n </div>\r\n\r\n <footer class=\"border-top footer text-muted\">\r\n <div class=\"container\">\r\n © 2020 - My Sample ISP\r\n </div>\r\n </footer>\r\n\r\n ");
__tagHelperExecutionContext = __tagHelperScopeManager.Begin("environment", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "31c859f5f1469ab42009dd188032e94f5caa7ecb31749", async() => {
WriteLiteral("\r\n ");
__tagHelperExecutionContext = __tagHelperScopeManager.Begin("script", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "31c859f5f1469ab42009dd188032e94f5caa7ecb32031", async() => {
}
);
__Microsoft_AspNetCore_Mvc_Razor_TagHelpers_UrlResolutionTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.Razor.TagHelpers.UrlResolutionTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_Razor_TagHelpers_UrlResolutionTagHelper);
__tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_21);
await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);
if (!__tagHelperExecutionContext.Output.IsContentModified)
{
await __tagHelperExecutionContext.SetOutputContentAsync();
}
Write(__tagHelperExecutionContext.Output);
__tagHelperExecutionContext = __tagHelperScopeManager.End();
WriteLiteral("\r\n ");
__tagHelperExecutionContext = __tagHelperScopeManager.Begin("script", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "31c859f5f1469ab42009dd188032e94f5caa7ecb33192", async() => {
}
);
__Microsoft_AspNetCore_Mvc_Razor_TagHelpers_UrlResolutionTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.Razor.TagHelpers.UrlResolutionTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_Razor_TagHelpers_UrlResolutionTagHelper);
__tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_22);
await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);
if (!__tagHelperExecutionContext.Output.IsContentModified)
{
await __tagHelperExecutionContext.SetOutputContentAsync();
}
Write(__tagHelperExecutionContext.Output);
__tagHelperExecutionContext = __tagHelperScopeManager.End();
WriteLiteral("\r\n ");
}
);
__Microsoft_AspNetCore_Mvc_TagHelpers_EnvironmentTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.EnvironmentTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_EnvironmentTagHelper);
__Microsoft_AspNetCore_Mvc_TagHelpers_EnvironmentTagHelper.Include = (string)__tagHelperAttribute_6.Value;
__tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_6);
await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);
if (!__tagHelperExecutionContext.Output.IsContentModified)
{
await __tagHelperExecutionContext.SetOutputContentAsync();
}
Write(__tagHelperExecutionContext.Output);
__tagHelperExecutionContext = __tagHelperScopeManager.End();
WriteLiteral("\r\n ");
__tagHelperExecutionContext = __tagHelperScopeManager.Begin("environment", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "31c859f5f1469ab42009dd188032e94f5caa7ecb35328", async() => {
WriteLiteral("\r\n ");
__tagHelperExecutionContext = __tagHelperScopeManager.Begin("script", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "31c859f5f1469ab42009dd188032e94f5caa7ecb35610", async() => {
WriteLiteral("\r\n ");
}
);
__Microsoft_AspNetCore_Mvc_TagHelpers_ScriptTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.ScriptTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_ScriptTagHelper);
__Microsoft_AspNetCore_Mvc_TagHelpers_ScriptTagHelper.Src = (string)__tagHelperAttribute_23.Value;
__tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_23);
__Microsoft_AspNetCore_Mvc_TagHelpers_ScriptTagHelper.FallbackSrc = (string)__tagHelperAttribute_24.Value;
__tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_24);
__Microsoft_AspNetCore_Mvc_TagHelpers_ScriptTagHelper.FallbackTestExpression = (string)__tagHelperAttribute_25.Value;
__tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_25);
__tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_12);
__tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_26);
await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);
if (!__tagHelperExecutionContext.Output.IsContentModified)
{
await __tagHelperExecutionContext.SetOutputContentAsync();
}
Write(__tagHelperExecutionContext.Output);
__tagHelperExecutionContext = __tagHelperScopeManager.End();
WriteLiteral("\r\n ");
__tagHelperExecutionContext = __tagHelperScopeManager.Begin("script", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "31c859f5f1469ab42009dd188032e94f5caa7ecb37557", async() => {
WriteLiteral("\r\n ");
}
);
__Microsoft_AspNetCore_Mvc_TagHelpers_ScriptTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.ScriptTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_ScriptTagHelper);
__Microsoft_AspNetCore_Mvc_TagHelpers_ScriptTagHelper.Src = (string)__tagHelperAttribute_27.Value;
__tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_27);
__Microsoft_AspNetCore_Mvc_TagHelpers_ScriptTagHelper.FallbackSrc = (string)__tagHelperAttribute_28.Value;
__tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_28);
__Microsoft_AspNetCore_Mvc_TagHelpers_ScriptTagHelper.FallbackTestExpression = (string)__tagHelperAttribute_29.Value;
__tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_29);
__tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_12);
__tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_30);
await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);
if (!__tagHelperExecutionContext.Output.IsContentModified)
{
await __tagHelperExecutionContext.SetOutputContentAsync();
}
Write(__tagHelperExecutionContext.Output);
__tagHelperExecutionContext = __tagHelperScopeManager.End();
WriteLiteral("\r\n ");
}
);
__Microsoft_AspNetCore_Mvc_TagHelpers_EnvironmentTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.EnvironmentTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_EnvironmentTagHelper);
__Microsoft_AspNetCore_Mvc_TagHelpers_EnvironmentTagHelper.Exclude = (string)__tagHelperAttribute_14.Value;
__tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_14);
await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);
if (!__tagHelperExecutionContext.Output.IsContentModified)
{
await __tagHelperExecutionContext.SetOutputContentAsync();
}
Write(__tagHelperExecutionContext.Output);
__tagHelperExecutionContext = __tagHelperScopeManager.End();
WriteLiteral("\r\n ");
__tagHelperExecutionContext = __tagHelperScopeManager.Begin("script", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "31c859f5f1469ab42009dd188032e94f5caa7ecb40481", async() => {
}
);
__Microsoft_AspNetCore_Mvc_Razor_TagHelpers_UrlResolutionTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.Razor.TagHelpers.UrlResolutionTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_Razor_TagHelpers_UrlResolutionTagHelper);
__Microsoft_AspNetCore_Mvc_TagHelpers_ScriptTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.ScriptTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_ScriptTagHelper);
__Microsoft_AspNetCore_Mvc_TagHelpers_ScriptTagHelper.Src = (string)__tagHelperAttribute_31.Value;
__tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_31);
#nullable restore
#line 79 "C:\Users\a\Desktop\angular\new\OnlineStore\Auth\Views\Shared\_Layout.cshtml"
__Microsoft_AspNetCore_Mvc_TagHelpers_ScriptTagHelper.AppendVersion = true;
#line default
#line hidden
#nullable disable
__tagHelperExecutionContext.AddTagHelperAttribute("asp-append-version", __Microsoft_AspNetCore_Mvc_TagHelpers_ScriptTagHelper.AppendVersion, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);
if (!__tagHelperExecutionContext.Output.IsContentModified)
{
await __tagHelperExecutionContext.SetOutputContentAsync();
}
Write(__tagHelperExecutionContext.Output);
__tagHelperExecutionContext = __tagHelperScopeManager.End();
WriteLiteral("\r\n\r\n ");
#nullable restore
#line 81 "C:\Users\a\Desktop\angular\new\OnlineStore\Auth\Views\Shared\_Layout.cshtml"
Write(RenderSection("Scripts", required: false));
#line default
#line hidden
#nullable disable
WriteLiteral("\r\n");
}
);
__Microsoft_AspNetCore_Mvc_Razor_TagHelpers_BodyTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.Razor.TagHelpers.BodyTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_Razor_TagHelpers_BodyTagHelper);
await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);
if (!__tagHelperExecutionContext.Output.IsContentModified)
{
await __tagHelperExecutionContext.SetOutputContentAsync();
}
Write(__tagHelperExecutionContext.Output);
__tagHelperExecutionContext = __tagHelperScopeManager.End();
WriteLiteral("\r\n</html>\r\n");
}
#pragma warning restore 1998
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.ViewFeatures.IModelExpressionProvider ModelExpressionProvider { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.IUrlHelper Url { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.IViewComponentHelper Component { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.Rendering.IJsonHelper Json { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.Rendering.IHtmlHelper<dynamic> Html { get; private set; }
}
}
#pragma warning restore 1591
| 92.767442 | 414 | 0.731512 | [
"MIT"
] | Aseeesh/Testing | Auth/obj/Debug/netcoreapp3.1/Razor/Views/Shared/_Layout.cshtml.g.cs | 43,879 | C# |
// <auto-generated />
using System;
using Marketplace.Data;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
namespace Marketplace.Migrations
{
[DbContext(typeof(ApplicationDbContext))]
[Migration("20190822195648_UserToModuleInfo")]
partial class UserToModuleInfo
{
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "2.1.11-servicing-32099")
.HasAnnotation("Relational:MaxIdentifierLength", 128)
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
modelBuilder.Entity("Marketplace.Data.Category", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<string>("Name");
b.Property<int?>("ParentCategoryId");
b.HasKey("Id");
b.HasIndex("ParentCategoryId");
b.ToTable("Categories");
});
modelBuilder.Entity("Marketplace.Data.DatabaseVersion", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<int>("Version");
b.HasKey("Id");
b.ToTable("DatabaseVersions");
});
modelBuilder.Entity("Marketplace.Data.Item", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<string>("AuthorId");
b.Property<int?>("CategoryId");
b.Property<string>("Description");
b.Property<int>("Downloads");
b.Property<int>("LicenseId");
b.Property<string>("Name");
b.Property<int>("Type");
b.Property<string>("Version");
b.HasKey("Id");
b.HasIndex("AuthorId");
b.HasIndex("CategoryId");
b.HasIndex("LicenseId");
b.ToTable("Items");
});
modelBuilder.Entity("Marketplace.Data.License", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<string>("Content");
b.Property<bool>("Custom");
b.Property<string>("Name");
b.HasKey("Id");
b.ToTable("Licenses");
});
modelBuilder.Entity("Marketplace.Data.ModuleInfo", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<string>("Authors");
b.Property<string>("Description");
b.Property<long?>("DownloadCount");
b.Property<string>("IconUrl");
b.Property<string>("LicenseUrl");
b.Property<string>("NuGetId");
b.Property<string>("Owners");
b.Property<string>("ProjectUrl");
b.Property<DateTimeOffset?>("Published");
b.Property<string>("Readme");
b.Property<string>("ReportAbuseUrl");
b.Property<bool>("RequireLicenseAcceptance");
b.Property<string>("SubmittedById");
b.Property<string>("Summary");
b.Property<string>("Tags");
b.Property<string>("Title");
b.Property<int>("Type");
b.Property<string>("Version");
b.HasKey("Id");
b.HasIndex("SubmittedById");
b.ToTable("ModuleInfo");
});
modelBuilder.Entity("Marketplace.Data.Rating", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<string>("AuthorId");
b.Property<int>("ItemId");
b.Property<string>("Text");
b.Property<int>("Value");
b.HasKey("Id");
b.HasIndex("AuthorId");
b.HasIndex("ItemId");
b.ToTable("Ratings");
});
modelBuilder.Entity("Marketplace.Data.Tag", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<string>("Name");
b.HasKey("Id");
b.ToTable("Tags");
});
modelBuilder.Entity("Marketplace.Data.TagItem", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<int>("ItemId");
b.Property<int>("TagId");
b.HasKey("Id");
b.HasIndex("ItemId");
b.HasIndex("TagId");
b.ToTable("TagItems");
});
modelBuilder.Entity("Marketplace.Data.UniversalDashboardVersion", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<string>("Version");
b.HasKey("Id");
b.ToTable("UniversalDashboardVersions");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRole", b =>
{
b.Property<string>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken();
b.Property<string>("Name")
.HasMaxLength(256);
b.Property<string>("NormalizedName")
.HasMaxLength(256);
b.HasKey("Id");
b.HasIndex("NormalizedName")
.IsUnique()
.HasName("RoleNameIndex")
.HasFilter("[NormalizedName] IS NOT NULL");
b.ToTable("AspNetRoles");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<string>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<string>("ClaimType");
b.Property<string>("ClaimValue");
b.Property<string>("RoleId")
.IsRequired();
b.HasKey("Id");
b.HasIndex("RoleId");
b.ToTable("AspNetRoleClaims");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUser", b =>
{
b.Property<string>("Id")
.ValueGeneratedOnAdd();
b.Property<int>("AccessFailedCount");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken();
b.Property<string>("Discriminator")
.IsRequired();
b.Property<string>("Email")
.HasMaxLength(256);
b.Property<bool>("EmailConfirmed");
b.Property<bool>("LockoutEnabled");
b.Property<DateTimeOffset?>("LockoutEnd");
b.Property<string>("NormalizedEmail")
.HasMaxLength(256);
b.Property<string>("NormalizedUserName")
.HasMaxLength(256);
b.Property<string>("PasswordHash");
b.Property<string>("PhoneNumber");
b.Property<bool>("PhoneNumberConfirmed");
b.Property<string>("SecurityStamp");
b.Property<bool>("TwoFactorEnabled");
b.Property<string>("UserName")
.HasMaxLength(256);
b.HasKey("Id");
b.HasIndex("NormalizedEmail")
.HasName("EmailIndex");
b.HasIndex("NormalizedUserName")
.IsUnique()
.HasName("UserNameIndex")
.HasFilter("[NormalizedUserName] IS NOT NULL");
b.ToTable("AspNetUsers");
b.HasDiscriminator<string>("Discriminator").HasValue("IdentityUser");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<string>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<string>("ClaimType");
b.Property<string>("ClaimValue");
b.Property<string>("UserId")
.IsRequired();
b.HasKey("Id");
b.HasIndex("UserId");
b.ToTable("AspNetUserClaims");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<string>", b =>
{
b.Property<string>("LoginProvider")
.HasMaxLength(128);
b.Property<string>("ProviderKey")
.HasMaxLength(128);
b.Property<string>("ProviderDisplayName");
b.Property<string>("UserId")
.IsRequired();
b.HasKey("LoginProvider", "ProviderKey");
b.HasIndex("UserId");
b.ToTable("AspNetUserLogins");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<string>", b =>
{
b.Property<string>("UserId");
b.Property<string>("RoleId");
b.HasKey("UserId", "RoleId");
b.HasIndex("RoleId");
b.ToTable("AspNetUserRoles");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<string>", b =>
{
b.Property<string>("UserId");
b.Property<string>("LoginProvider")
.HasMaxLength(128);
b.Property<string>("Name")
.HasMaxLength(128);
b.Property<string>("Value");
b.HasKey("UserId", "LoginProvider", "Name");
b.ToTable("AspNetUserTokens");
});
modelBuilder.Entity("Marketplace.Areas.Identity.Data.MarketplaceUser", b =>
{
b.HasBaseType("Microsoft.AspNetCore.Identity.IdentityUser");
b.ToTable("MarketplaceUser");
b.HasDiscriminator().HasValue("MarketplaceUser");
});
modelBuilder.Entity("Marketplace.Data.Category", b =>
{
b.HasOne("Marketplace.Data.Category", "ParentCategory")
.WithMany()
.HasForeignKey("ParentCategoryId");
});
modelBuilder.Entity("Marketplace.Data.Item", b =>
{
b.HasOne("Marketplace.Areas.Identity.Data.MarketplaceUser", "Author")
.WithMany("Items")
.HasForeignKey("AuthorId");
b.HasOne("Marketplace.Data.Category", "Category")
.WithMany("Items")
.HasForeignKey("CategoryId");
b.HasOne("Marketplace.Data.License", "License")
.WithMany("Items")
.HasForeignKey("LicenseId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Marketplace.Data.ModuleInfo", b =>
{
b.HasOne("Marketplace.Areas.Identity.Data.MarketplaceUser", "SubmittedBy")
.WithMany()
.HasForeignKey("SubmittedById");
});
modelBuilder.Entity("Marketplace.Data.Rating", b =>
{
b.HasOne("Marketplace.Areas.Identity.Data.MarketplaceUser", "Author")
.WithMany("Ratings")
.HasForeignKey("AuthorId");
b.HasOne("Marketplace.Data.Item", "Item")
.WithMany("Ratings")
.HasForeignKey("ItemId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Marketplace.Data.TagItem", b =>
{
b.HasOne("Marketplace.Data.Item", "Item")
.WithMany("ItemTags")
.HasForeignKey("ItemId")
.OnDelete(DeleteBehavior.Cascade);
b.HasOne("Marketplace.Data.Tag", "Tag")
.WithMany("TagItems")
.HasForeignKey("TagId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<string>", b =>
{
b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole")
.WithMany()
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<string>", b =>
{
b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser")
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<string>", b =>
{
b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser")
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<string>", b =>
{
b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole")
.WithMany()
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.Cascade);
b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser")
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<string>", b =>
{
b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser")
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade);
});
#pragma warning restore 612, 618
}
}
}
| 34.244048 | 125 | 0.471696 | [
"MIT"
] | ironmansoftware/universal-dashboard-marketplace | src/Migrations/20190822195648_UserToModuleInfo.Designer.cs | 17,261 | C# |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Threading;
namespace Roslyn.Utilities
{
internal static class ReaderWriterLockSlimExtensions
{
internal static ReadLockExiter DisposableRead(this ReaderWriterLockSlim @lock)
{
return new ReadLockExiter(@lock);
}
internal struct ReadLockExiter : IDisposable
{
private readonly ReaderWriterLockSlim _lock;
internal ReadLockExiter(ReaderWriterLockSlim @lock)
{
_lock = @lock;
@lock.EnterReadLock();
}
public void Dispose()
{
_lock.ExitReadLock();
}
}
internal static WriteLockExiter DisposableWrite(this ReaderWriterLockSlim @lock)
{
return new WriteLockExiter(@lock);
}
internal struct WriteLockExiter : IDisposable
{
private readonly ReaderWriterLockSlim _lock;
internal WriteLockExiter(ReaderWriterLockSlim @lock)
{
_lock = @lock;
@lock.EnterWriteLock();
}
public void Dispose()
{
_lock.ExitWriteLock();
}
}
internal static void AssertCanRead(this ReaderWriterLockSlim @lock)
{
if (!@lock.IsReadLockHeld && !@lock.IsUpgradeableReadLockHeld && !@lock.IsWriteLockHeld)
{
throw new InvalidOperationException();
}
}
internal static void AssertCanWrite(this ReaderWriterLockSlim @lock)
{
if (!@lock.IsWriteLockHeld)
{
throw new InvalidOperationException();
}
}
}
}
| 27.652174 | 161 | 0.562369 | [
"Apache-2.0"
] | 0x53A/roslyn | src/Compilers/Core/Portable/InternalUtilities/ReaderWriterLockSlimExtensions.cs | 1,910 | C# |
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Linq;
using AppKit;
using Foundation;
using Xamarin.Forms.Internals;
namespace Xamarin.Forms.Platform.MacOS
{
public class ListViewRenderer : ViewRenderer<ListView, NSView>
{
bool _disposed;
NSTableView _table;
ListViewDataSource _dataSource;
IVisualElementRenderer _headerRenderer;
IVisualElementRenderer _footerRenderer;
ITemplatedItemsView<Cell> TemplatedItemsView => Element;
bool? _defaultHorizontalScrollVisibility;
bool? _defaultVerticalScrollVisibility;
public const int DefaultRowHeight = 44;
public NSTableView NativeTableView => _table;
public override void ViewWillDraw()
{
UpdateHeader();
base.ViewWillDraw();
}
protected virtual NSTableView CreateNSTableView(ListView list)
{
NSTableView table = new FormsNSTableView().AsListViewLook();
table.Source = _dataSource = new ListViewDataSource(list, table);
return table;
}
protected override void Dispose(bool disposing)
{
if (disposing && !_disposed)
{
_disposed = true;
var viewsToLookAt = new Stack<NSView>(Subviews);
while (viewsToLookAt.Count > 0)
{
var view = viewsToLookAt.Pop();
var viewCellRenderer = view as ViewCellNSView;
if (viewCellRenderer != null)
viewCellRenderer.Dispose();
else
{
foreach (var child in view.Subviews)
viewsToLookAt.Push(child);
}
}
if (Element != null)
{
var templatedItems = TemplatedItemsView.TemplatedItems;
templatedItems.CollectionChanged -= OnCollectionChanged;
templatedItems.GroupedCollectionChanged -= OnGroupedCollectionChanged;
}
}
if (disposing)
{
ClearHeader();
if (_footerRenderer != null)
{
Platform.DisposeModelAndChildrenRenderers(_footerRenderer.Element);
_footerRenderer = null;
}
}
base.Dispose(disposing);
}
protected override void SetBackgroundColor(Color color)
{
base.SetBackgroundColor(color);
if (_table == null)
return;
_table.BackgroundColor = color.ToNSColor(NSColor.White);
}
protected override void OnElementChanged(ElementChangedEventArgs<ListView> e)
{
if (e.OldElement != null)
{
var listView = e.OldElement;
listView.ScrollToRequested -= OnScrollToRequested;
var templatedItems = ((ITemplatedItemsView<Cell>)e.OldElement).TemplatedItems;
templatedItems.CollectionChanged -= OnCollectionChanged;
templatedItems.GroupedCollectionChanged -= OnGroupedCollectionChanged;
}
if (e.NewElement != null)
{
if (Control == null)
{
var scroller = new NSScrollView
{
AutoresizingMask = NSViewResizingMask.HeightSizable | NSViewResizingMask.WidthSizable,
DocumentView = _table = CreateNSTableView(e.NewElement),
HasVerticalScroller = true
};
SetNativeControl(scroller);
}
var listView = e.NewElement;
listView.ScrollToRequested += OnScrollToRequested;
var templatedItems = ((ITemplatedItemsView<Cell>)e.NewElement).TemplatedItems;
templatedItems.CollectionChanged += OnCollectionChanged;
templatedItems.GroupedCollectionChanged += OnGroupedCollectionChanged;
UpdateRowHeight();
UpdateHeader();
UpdateFooter();
UpdatePullToRefreshEnabled();
UpdateIsRefreshing();
UpdateSeparatorColor();
UpdateSeparatorVisibility();
UpdateVerticalScrollBarVisibility();
UpdateHorizontalScrollBarVisibility();
var selected = e.NewElement.SelectedItem;
if (selected != null)
_dataSource.OnItemSelected(null, new SelectedItemChangedEventArgs(selected));
}
base.OnElementChanged(e);
}
protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
{
base.OnElementPropertyChanged(sender, e);
if (e.PropertyName == ListView.RowHeightProperty.PropertyName)
UpdateRowHeight();
else if (e.PropertyName == ListView.IsGroupingEnabledProperty.PropertyName ||
(e.PropertyName == ListView.HasUnevenRowsProperty.PropertyName))
_dataSource.Update();
else if (e.PropertyName == ListView.IsPullToRefreshEnabledProperty.PropertyName)
UpdatePullToRefreshEnabled();
else if (e.PropertyName == ListView.IsRefreshingProperty.PropertyName)
UpdateIsRefreshing();
else if (e.PropertyName == ListView.SeparatorColorProperty.PropertyName)
UpdateSeparatorColor();
else if (e.PropertyName == ListView.SeparatorVisibilityProperty.PropertyName)
UpdateSeparatorVisibility();
else if (e.PropertyName == "HeaderElement")
UpdateHeader();
else if (e.PropertyName == "FooterElement")
UpdateFooter();
else if (e.PropertyName == "RefreshAllowed")
UpdatePullToRefreshEnabled();
else if (e.PropertyName == ScrollView.VerticalScrollBarVisibilityProperty.PropertyName)
UpdateVerticalScrollBarVisibility();
else if (e.PropertyName == ScrollView.HorizontalScrollBarVisibilityProperty.PropertyName)
UpdateHorizontalScrollBarVisibility();
}
void OnCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
UpdateItems(e, 0, true);
}
void OnGroupedCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
var til = (TemplatedItemsList<ItemsView<Cell>, Cell>)sender;
var templatedItems = TemplatedItemsView.TemplatedItems;
var groupIndex = templatedItems.IndexOf(til.HeaderContent);
UpdateItems(e, groupIndex, false);
}
void UpdateHeader()
{
var header = Element.HeaderElement;
var headerView = (View)header;
if (headerView != null)
{
//Header reuse is not working for now , problem with size of something that is not inside a layout
//if (_headerRenderer != null)
//{
// var reflectableType = _headerRenderer as System.Reflection.IReflectableType;
// var rendererType = reflectableType != null ? reflectableType.GetTypeInfo().AsType() : _headerRenderer.GetType();
// if (header != null && rendererType == Registrar.Registered.GetHandlerTypeForObject(header))
// {
// _headerRenderer.SetElement(headerView);
// _table.HeaderView = new CustomNSTableHeaderView(Bounds.Width, _headerRenderer);
// // Layout();
// //var customNSTableHeaderView = _table.HeaderView as CustomNSTableHeaderView;
// //customNSTableHeaderView?.Update(Bounds.Width, _headerRenderer);
// //NativeView.Layout();
// //NativeView.SetNeedsDisplayInRect(NativeView.Bounds);
// //NativeView.LayoutSubtreeIfNeeded();
// //_table.LayoutSubtreeIfNeeded();
// //_table.NeedsDisplay = true;
// //NativeView.NeedsDisplay = true;
// return;
// }
ClearHeader();
//}
_headerRenderer = Platform.CreateRenderer(headerView);
Platform.SetRenderer(headerView, _headerRenderer);
_table.HeaderView = new CustomNSTableHeaderView(Bounds.Width, _headerRenderer);
//We need this since the NSSCrollView doesn't know of the new size of our header
//TODO: Find a better solution
(Control as NSScrollView)?.ContentView.ScrollToPoint(new CoreGraphics.CGPoint(0, -_table.HeaderView.Frame.Height));
}
else if (_headerRenderer != null)
{
ClearHeader();
}
}
void ClearHeader()
{
_table.HeaderView = null;
if (_headerRenderer == null)
return;
Platform.DisposeModelAndChildrenRenderers(_headerRenderer.Element);
_headerRenderer = null;
}
void UpdateItems(NotifyCollectionChangedEventArgs e, int section, bool resetWhenGrouped)
{
var exArgs = e as NotifyCollectionChangedEventArgsEx;
if (exArgs != null)
_dataSource.Counts[section] = exArgs.Count;
var groupReset = resetWhenGrouped && Element.IsGroupingEnabled;
switch (e.Action)
{
case NotifyCollectionChangedAction.Add:
if (e.NewStartingIndex == -1 || groupReset)
goto case NotifyCollectionChangedAction.Reset;
_table.BeginUpdates();
_table.InsertRows(NSIndexSet.FromArray(Enumerable.Range(e.NewStartingIndex, e.NewItems.Count).ToArray()),
NSTableViewAnimation.SlideUp);
_table.EndUpdates();
break;
case NotifyCollectionChangedAction.Remove:
if (e.OldStartingIndex == -1 || groupReset)
goto case NotifyCollectionChangedAction.Reset;
_table.BeginUpdates();
_table.RemoveRows(NSIndexSet.FromArray(Enumerable.Range(e.OldStartingIndex, e.OldItems.Count).ToArray()),
NSTableViewAnimation.SlideDown);
_table.EndUpdates();
break;
case NotifyCollectionChangedAction.Move:
if (e.OldStartingIndex == -1 || e.NewStartingIndex == -1 || groupReset)
goto case NotifyCollectionChangedAction.Reset;
_table.BeginUpdates();
for (var i = 0; i < e.OldItems.Count; i++)
{
var oldi = e.OldStartingIndex;
var newi = e.NewStartingIndex;
if (e.NewStartingIndex < e.OldStartingIndex)
{
oldi += i;
newi += i;
}
_table.MoveRow(oldi, newi);
}
_table.EndUpdates();
break;
case NotifyCollectionChangedAction.Replace:
case NotifyCollectionChangedAction.Reset:
_table.ReloadData();
return;
}
}
void UpdateRowHeight()
{
var rowHeight = Element.RowHeight;
if (Element.HasUnevenRows && rowHeight == -1)
{
// _table.RowHeight = NoIntrinsicMetric;
}
else
_table.RowHeight = rowHeight <= 0 ? DefaultRowHeight : rowHeight;
}
//TODO: Implement UpdateIsRefreshing
void UpdateIsRefreshing()
{
}
//TODO: Implement PullToRefresh
void UpdatePullToRefreshEnabled()
{
}
//TODO: Implement SeparatorColor
void UpdateSeparatorColor()
{
}
//TODO: Implement UpdateSeparatorVisibility
void UpdateSeparatorVisibility()
{
}
//TODO: Implement ScrollTo
void OnScrollToRequested(object sender, ScrollToRequestedEventArgs e)
{
}
//TODO: Implement Footer
void UpdateFooter()
{
}
void UpdateVerticalScrollBarVisibility()
{
if (_table?.EnclosingScrollView != null)
{
if (_defaultVerticalScrollVisibility == null)
_defaultVerticalScrollVisibility = _table.EnclosingScrollView.HasVerticalScroller;
switch (Element.VerticalScrollBarVisibility)
{
case (ScrollBarVisibility.Always):
_table.EnclosingScrollView.HasVerticalScroller = true;
break;
case (ScrollBarVisibility.Never):
_table.EnclosingScrollView.HasVerticalScroller = false;
break;
case (ScrollBarVisibility.Default):
_table.EnclosingScrollView.HasVerticalScroller = (bool)_defaultVerticalScrollVisibility;
break;
}
}
}
void UpdateHorizontalScrollBarVisibility()
{
if (_table?.EnclosingScrollView != null)
{
if (_defaultHorizontalScrollVisibility == null)
_defaultHorizontalScrollVisibility = _table.EnclosingScrollView.HasHorizontalScroller;
switch (Element.HorizontalScrollBarVisibility)
{
case (ScrollBarVisibility.Always):
_table.EnclosingScrollView.HasHorizontalScroller = true;
break;
case (ScrollBarVisibility.Never):
_table.EnclosingScrollView.HasHorizontalScroller = false;
break;
case (ScrollBarVisibility.Default):
_table.EnclosingScrollView.HasHorizontalScroller = (bool)_defaultHorizontalScrollVisibility;
break;
}
}
}
class FormsNSTableView : NSTableView
{
//NSTableView doesn't support selection notfications after the items is already selected
//so we do it ourselves by hooking mouse down event
public override void MouseDown(NSEvent theEvent)
{
var clickLocation = ConvertPointFromView(theEvent.LocationInWindow, null);
var clickedRow = GetRow(clickLocation);
base.MouseDown(theEvent);
if (clickedRow != -1)
(Source as ListViewDataSource)?.OnRowClicked();
}
}
}
} | 29.631313 | 119 | 0.72047 | [
"MIT"
] | AuriR/Xamarin.Forms | Xamarin.Forms.Platform.MacOS/Renderers/ListViewRenderer.cs | 11,736 | C# |
using Business.Abstract;
using Entities;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace NetCoreWebMvc.Controllers
{
public class CompanyController : Controller
{
ICompanyService _companyService;
public CompanyController(ICompanyService companyService)
{
_companyService = companyService;
}
public IActionResult Index()
{
var get = _companyService.getAll().Data;
return View(get);
}
[HttpPost]
public IActionResult Add(Company company)
{
if (ModelState.IsValid)
{
var result = _companyService.Add(company);
if (result != null)
{
if (result.Success)
{
return RedirectToAction("Index", "Company");
}
else
{
return View("Add", "Company");
}
}
}
return View(company);
}
[HttpPost]
public IActionResult Updated(Company company, int id)
{
var update = _companyService.Update(company);
var id2 = _companyService.getById(id).Data;
if (update.Success)
{
id2.id = company.id;
id2.companyName = company.companyName.Trim();
return RedirectToAction("Index");
}
return View();
}
public IActionResult Deleted(int id)
{
var id2 = _companyService.getById(id).Data;
_companyService.Delete(id2);
return RedirectToAction("Index");
}
public IActionResult Add()
{
return View();
}
public IActionResult Updated(int id)
{
return View();
}
}
}
| 20.838384 | 68 | 0.487155 | [
"MIT"
] | ugurkurekci/CoffeiSoft | NetCoreWebMvc/Areas/Admin/Controllers/CompanyController.cs | 2,065 | C# |
// Developed by Softeq Development Corporation
// http://www.softeq.com
namespace Softeq.NetKit.Payments.SQLRepository.Interfaces
{
public interface IRepositoryFactory
{
IUserRepository UserRepository { get; }
ICardRepository CardRepository { get; }
IInvoiceRepository InvoiceRepository { get; }
ISubscriptionRepository SubscriptionRepository { get; }
ISubscriptionPlanRepository SubscriptionPlanRepository { get; }
IChargeRepository ChargeRepository { get; }
}
} | 35 | 71 | 0.727619 | [
"MIT"
] | Softeq/NetKit.Payment.Stripe | Softeq.NetKit.Payments.SQLRepository/Interfaces/IRepositoryFactory.cs | 527 | C# |
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System;
using System.Threading.Tasks;
using VsRemote.Interfaces;
using VsRemote.Models;
namespace VsRemote.Controllers
{
[Route("[controller]")]
[ApiController]
public class SolutionController : ControllerBase
{
private readonly IVisualStudioService _visualStudioService;
private readonly ILogger<VisualStudioController> _logger;
public SolutionController(IVisualStudioService visualStudioService,
ILogger<VisualStudioController> logger)
{
_visualStudioService = visualStudioService;
_logger = logger;
}
[HttpGet("{id:int}")]
// Used for swagger documentation
[ProducesResponseType(typeof(VsSolution), StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
public async Task<IActionResult> GetAsync(int id)
{
try
{
_logger.LogInformation("Get solution called");
var solutionDetails = await _visualStudioService.GetSolutionDetails(id);
return solutionDetails == null ? NotFound() : (IActionResult)Ok(solutionDetails);
}
catch (Exception ex)
{
_logger.LogError(ex.StackTrace);
}
return BadRequest("Opps something is wrong! Check the logs");
}
[HttpPost("{id:int}")]
[ProducesResponseType(typeof(VsResult), StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
public async Task<IActionResult> PostAsync(int id)
{
try
{
var result = await _visualStudioService.StartBuildAsync(id);
return Ok(result);
}
catch (Exception ex)
{
_logger.LogError(ex.StackTrace);
}
return BadRequest("Opps something is wrong! Check the logs");
}
}
}
| 33.2 | 97 | 0.617702 | [
"MIT"
] | ovintu/vs-remote | VsRemote/VsRemote/Controllers/SolutionController.cs | 2,160 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
namespace Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210
{
using Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.PowerShell;
/// <summary>
/// A PowerShell PSTypeConverter to support converting to an instance of <see cref="InMageVolumeExclusionOptions" />
/// </summary>
public partial class InMageVolumeExclusionOptionsTypeConverter : global::System.Management.Automation.PSTypeConverter
{
/// <summary>
/// Determines if the converter can convert the <see cref="sourceValue"/> parameter to the <see cref="destinationType" />
/// parameter.
/// </summary>
/// <param name="sourceValue">the <see cref="System.Object"/> to convert from</param>
/// <param name="destinationType">the <see cref="System.Type" /> to convert to</param>
/// <returns>
/// <c>true</c> if the converter can convert the <see cref="sourceValue"/> parameter to the <see cref="destinationType" />
/// parameter, otherwise <c>false</c>.
/// </returns>
public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue);
/// <summary>
/// Determines if the converter can convert the <see cref="sourceValue"/> parameter to the <see cref="destinationType" />
/// parameter.
/// </summary>
/// <param name="sourceValue">the <see cref="System.Object" /> instance to check if it can be converted to the <see cref="InMageVolumeExclusionOptions"
/// /> type.</param>
/// <returns>
/// <c>true</c> if the instance could be converted to a <see cref="InMageVolumeExclusionOptions" /> type, otherwise <c>false</c>
/// </returns>
public static bool CanConvertFrom(dynamic sourceValue)
{
if (null == sourceValue)
{
return true;
}
global::System.Type type = sourceValue.GetType();
if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type))
{
// we say yest to PSObjects
return true;
}
if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type))
{
// we say yest to Hashtables/dictionaries
return true;
}
try
{
if (null != sourceValue.ToJsonString())
{
return true;
}
}
catch
{
// Not one of our objects
}
try
{
string text = sourceValue.ToString()?.Trim();
return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonType.Object;
}
catch
{
// Doesn't look like it can be treated as JSON
}
return false;
}
/// <summary>
/// Determines if the <see cref="sourceValue" /> parameter can be converted to the <see cref="destinationType" /> parameter
/// </summary>
/// <param name="sourceValue">the <see cref="System.Object"/> to convert from</param>
/// <param name="destinationType">the <see cref="System.Type" /> to convert to</param>
/// <returns>
/// <c>true</c> if the converter can convert the <see cref="sourceValue" /> parameter to the <see cref="destinationType" />
/// parameter, otherwise <c>false</c>
/// </returns>
public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false;
/// <summary>
/// Converts the <see cref="sourceValue" /> parameter to the <see cref="destinationType" /> parameter using <see cref="formatProvider"
/// /> and <see cref="ignoreCase" />
/// </summary>
/// <param name="sourceValue">the <see cref="System.Object"/> to convert from</param>
/// <param name="destinationType">the <see cref="System.Type" /> to convert to</param>
/// <param name="formatProvider">not used by this TypeConverter.</param>
/// <param name="ignoreCase">when set to <c>true</c>, will ignore the case when converting.</param>
/// <returns>
/// an instance of <see cref="InMageVolumeExclusionOptions" />, or <c>null</c> if there is no suitable conversion.
/// </returns>
public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue);
/// <summary>
/// Converts the <see cref="sourceValue" /> parameter to the <see cref="destinationType" /> parameter using <see cref="formatProvider"
/// /> and <see cref="ignoreCase" />
/// </summary>
/// <param name="sourceValue">the value to convert into an instance of <see cref="InMageVolumeExclusionOptions" />.</param>
/// <returns>
/// an instance of <see cref="InMageVolumeExclusionOptions" />, or <c>null</c> if there is no suitable conversion.
/// </returns>
public static Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.IInMageVolumeExclusionOptions ConvertFrom(dynamic sourceValue)
{
if (null == sourceValue)
{
return null;
}
global::System.Type type = sourceValue.GetType();
if (typeof(Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.IInMageVolumeExclusionOptions).IsAssignableFrom(type))
{
return sourceValue;
}
try
{
return InMageVolumeExclusionOptions.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());;
}
catch
{
// Unable to use JSON pattern
}
if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type))
{
return InMageVolumeExclusionOptions.DeserializeFromPSObject(sourceValue);
}
if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type))
{
return InMageVolumeExclusionOptions.DeserializeFromDictionary(sourceValue);
}
return null;
}
/// <summary>NotImplemented -- this will return <c>null</c></summary>
/// <param name="sourceValue">the <see cref="System.Object"/> to convert from</param>
/// <param name="destinationType">the <see cref="System.Type" /> to convert to</param>
/// <param name="formatProvider">not used by this TypeConverter.</param>
/// <param name="ignoreCase">when set to <c>true</c>, will ignore the case when converting.</param>
/// <returns>will always return <c>null</c>.</returns>
public override object ConvertTo(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => null;
}
} | 52.653061 | 245 | 0.59677 | [
"MIT"
] | Agazoth/azure-powershell | src/Migrate/generated/api/Models/Api20210210/InMageVolumeExclusionOptions.TypeConverter.cs | 7,594 | C# |
using System;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("AWSSDK.CloudHSM")]
#if BCL35
[assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (3.5) - Amazon CloudHSM. The AWS CloudHSM service helps you meet corporate, contractual and regulatory compliance requirements for data security by using dedicated Hardware Security Module (HSM) appliances within the AWS cloud. With CloudHSM, you control the encryption keys and cryptographic operations performed by the HSM.")]
#elif BCL45
[assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (4.5) - Amazon CloudHSM. The AWS CloudHSM service helps you meet corporate, contractual and regulatory compliance requirements for data security by using dedicated Hardware Security Module (HSM) appliances within the AWS cloud. With CloudHSM, you control the encryption keys and cryptographic operations performed by the HSM.")]
#elif NETSTANDARD13
[assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (NetStandard 1.3) - Amazon CloudHSM. The AWS CloudHSM service helps you meet corporate, contractual and regulatory compliance requirements for data security by using dedicated Hardware Security Module (HSM) appliances within the AWS cloud. With CloudHSM, you control the encryption keys and cryptographic operations performed by the HSM.")]
#elif NETSTANDARD20
[assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (NetStandard 2.0) - Amazon CloudHSM. The AWS CloudHSM service helps you meet corporate, contractual and regulatory compliance requirements for data security by using dedicated Hardware Security Module (HSM) appliances within the AWS cloud. With CloudHSM, you control the encryption keys and cryptographic operations performed by the HSM.")]
#elif NETCOREAPP3_1
[assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (.NET Core 3.1) - Amazon CloudHSM. The AWS CloudHSM service helps you meet corporate, contractual and regulatory compliance requirements for data security by using dedicated Hardware Security Module (HSM) appliances within the AWS cloud. With CloudHSM, you control the encryption keys and cryptographic operations performed by the HSM.")]
#else
#error Unknown platform constant - unable to set correct AssemblyDescription
#endif
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyProduct("Amazon Web Services SDK for .NET")]
[assembly: AssemblyCompany("Amazon.com, Inc")]
[assembly: AssemblyCopyright("Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("3.3")]
[assembly: AssemblyFileVersion("3.5.0.8")]
[assembly: System.CLSCompliant(true)]
#if BCL
[assembly: System.Security.AllowPartiallyTrustedCallers]
#endif | 68.339623 | 409 | 0.791552 | [
"Apache-2.0"
] | orinem/aws-sdk-net | sdk/src/Services/CloudHSM/Properties/AssemblyInfo.cs | 3,622 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using JNIGenerator;
using Newtonsoft.Json.Linq;
public class StructSnipet : Snipet
{
public string Name { get; }
public string ModelPackage { get; private set; }
public List<Property> Properties { get; }
public StructSnipet(string template, Api api, Struct strct, Dictionary<string, string> typeMapping, string projectDir, string modelPackage = null) : base(Path.Combine(projectDir, template))
{
Name = strct.Name;
ModelPackage = modelPackage;
Properties = strct.Properties.Select(p => p.Clone()).ToList();
foreach (var prop in Properties)
{
new TypeConverter(typeMapping, api).SetTargetType(prop);
}
}
}
| 32.291667 | 193 | 0.685161 | [
"MIT"
] | agabor/JNIGenerator | JNIGenerator/StructSnipet.cs | 777 | C# |
using System;
namespace Chronoscope.Events
{
/// <summary>
/// Default implementation of <see cref="ITrackerCompletedEvent"/>.
/// </summary>
internal class TrackerCompletedEvent : ITrackerCompletedEvent
{
public TrackerCompletedEvent(Guid scopeId, Guid trackerId, DateTimeOffset timestamp, TimeSpan elapsed)
{
ScopeId = scopeId;
TrackerId = trackerId;
Timestamp = timestamp;
Elapsed = elapsed;
}
public Guid ScopeId { get; }
public Guid TrackerId { get; }
public DateTimeOffset Timestamp { get; }
public TimeSpan Elapsed { get; }
}
} | 25.692308 | 110 | 0.613772 | [
"MIT"
] | JorgeCandeias/Chronoscope | src/Chronoscope.Core/Events/TrackerCompletedEvent.cs | 670 | C# |
using System;
using UnityEngine;
using UnityEngine.Playables;
using UnityEngine.Timeline;
[Serializable]
public class NavAgentTravelClip : PlayableAsset, ITimelineClipAsset
{
public NavAgentTravelBehaviour template = new NavAgentTravelBehaviour ();
public ClipCaps clipCaps
{
get { return ClipCaps.All; }
}
public override Playable CreatePlayable (PlayableGraph graph, GameObject owner)
{
var playable = ScriptPlayable<NavAgentTravelBehaviour>.Create (graph, template);
NavAgentTravelBehaviour clone = playable.GetBehaviour ();
return playable;
}
}
| 26.608696 | 88 | 0.736928 | [
"MIT"
] | JCx7/TSEiAVN | CustomTrack/NavAgentTravel/NavAgentTravelClip.cs | 612 | 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.Linq;
using System.Reflection;
using JetBrains.Annotations;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using Microsoft.EntityFrameworkCore.Metadata.Conventions.Infrastructure;
namespace Microsoft.EntityFrameworkCore.Metadata.Conventions
{
/// <summary>
/// A convention that configures model function mappings based on public static methods on the context marked with
/// <see cref="DbFunctionAttribute" />.
/// </summary>
public class RelationalDbFunctionAttributeConvention : IModelInitializedConvention, IModelFinalizingConvention
{
/// <summary>
/// Creates a new instance of <see cref="RelationalDbFunctionAttributeConvention" />.
/// </summary>
/// <param name="dependencies"> Parameter object containing dependencies for this convention. </param>
/// <param name="relationalDependencies"> Parameter object containing relational dependencies for this convention. </param>
public RelationalDbFunctionAttributeConvention(
[NotNull] ProviderConventionSetBuilderDependencies dependencies,
[NotNull] RelationalConventionSetBuilderDependencies relationalDependencies)
{
Dependencies = dependencies;
}
/// <summary>
/// Parameter object containing service dependencies.
/// </summary>
protected virtual ProviderConventionSetBuilderDependencies Dependencies { get; }
/// <summary>
/// Called after a model is initialized.
/// </summary>
/// <param name="modelBuilder"> The builder for the model. </param>
/// <param name="context"> Additional information associated with convention execution. </param>
public virtual void ProcessModelInitialized(
IConventionModelBuilder modelBuilder,
IConventionContext<IConventionModelBuilder> context)
{
var contextType = Dependencies.ContextType;
while (contextType != null
&& contextType != typeof(DbContext))
{
var functions = contextType.GetMethods(
BindingFlags.Public
| BindingFlags.NonPublic
| BindingFlags.Instance
| BindingFlags.Static
| BindingFlags.DeclaredOnly)
.Where(mi => mi.IsDefined(typeof(DbFunctionAttribute)));
foreach (var function in functions)
{
modelBuilder.HasDbFunction(function);
}
contextType = contextType.BaseType;
}
}
/// <inheritdoc />
public virtual void ProcessModelFinalizing(
IConventionModelBuilder modelBuilder,
IConventionContext<IConventionModelBuilder> context)
{
foreach (var function in modelBuilder.Metadata.GetDbFunctions())
{
ProcessDbFunctionAdded(function.Builder, context);
}
}
/// <summary>
/// Called when an <see cref="IConventionDbFunction" /> is added to the model.
/// </summary>
/// <param name="dbFunctionBuilder"> The builder for the <see cref="IConventionDbFunction" />. </param>
/// <param name="context"> Additional information associated with convention execution. </param>
protected virtual void ProcessDbFunctionAdded(
[NotNull] IConventionDbFunctionBuilder dbFunctionBuilder,
[NotNull] IConventionContext context)
{
var methodInfo = dbFunctionBuilder.Metadata.MethodInfo;
var dbFunctionAttribute = methodInfo?.GetCustomAttributes<DbFunctionAttribute>().SingleOrDefault();
if (dbFunctionAttribute != null)
{
dbFunctionBuilder.HasName(dbFunctionAttribute.Name, fromDataAnnotation: true);
if (dbFunctionAttribute.Schema != null)
{
dbFunctionBuilder.HasSchema(dbFunctionAttribute.Schema, fromDataAnnotation: true);
}
if (dbFunctionAttribute.IsBuiltIn)
{
dbFunctionBuilder.IsBuiltIn(dbFunctionAttribute.IsBuiltIn, fromDataAnnotation: true);
}
if (dbFunctionAttribute.IsNullableHasValue)
{
dbFunctionBuilder.IsNullable(dbFunctionAttribute.IsNullable, fromDataAnnotation: true);
}
}
}
}
}
| 43.851852 | 132 | 0.624578 | [
"Apache-2.0"
] | 0b01/efcore | src/EFCore.Relational/Metadata/Conventions/RelationalDbFunctionAttributeConvention.cs | 4,736 | C# |
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.
using System.IO;
using System.Linq;
using System.Net.Mail;
using System.Text;
using System.Web.WebPages.Scope;
using System.Web.WebPages.TestUtils;
using Microsoft.TestCommon;
namespace System.Web.Helpers.Test
{
public class WebMailTest
{
const string FromAddress = "abc@123.com";
const string Server = "myserver.com";
const int Port = 100;
const string UserName = "My UserName";
const string Password = "My Password";
[Fact]
public void WebMailSmtpServerTests()
{
// All tests prior to setting smtp server go here
// Verify Send throws if no SmtpServer is set
Assert.Throws<InvalidOperationException>(
() => WebMail.Send(to: "test@test.com", subject: "test", body: "test body"),
"\"SmtpServer\" was not specified."
);
// Verify SmtpServer uses scope storage.
// Arrange
var value = "value";
// Act
WebMail.SmtpServer = value;
// Assert
Assert.Equal(WebMail.SmtpServer, value);
Assert.Equal(ScopeStorage.CurrentScope[WebMail.SmtpServerKey], value);
}
[Fact]
public void WebMailSendThrowsIfPriorityIsInvalid()
{
Assert.ThrowsArgument(
() => WebMail.Send(to: "test@test.com", subject: "test", body: "test body", priority: "foo"),
"priority",
"The \"priority\" value is invalid. Valid values are \"Low\", \"Normal\" and \"High\"."
);
}
[Fact]
public void WebMailUsesScopeStorageForSmtpPort()
{
// Arrange
var value = 4;
// Act
WebMail.SmtpPort = value;
// Assert
Assert.Equal(WebMail.SmtpPort, value);
Assert.Equal(ScopeStorage.CurrentScope[WebMail.SmtpPortKey], value);
}
[Fact]
public void WebMailUsesScopeStorageForEnableSsl()
{
// Arrange
var value = true;
// Act
WebMail.EnableSsl = value;
// Assert
Assert.Equal(WebMail.EnableSsl, value);
Assert.Equal(ScopeStorage.CurrentScope[WebMail.EnableSslKey], value);
}
[Fact]
public void WebMailUsesScopeStorageForDefaultCredentials()
{
// Arrange
var value = true;
// Act
WebMail.SmtpUseDefaultCredentials = value;
// Assert
Assert.Equal(WebMail.SmtpUseDefaultCredentials, value);
Assert.Equal(ScopeStorage.CurrentScope[WebMail.SmtpUseDefaultCredentialsKey], value);
}
[Fact]
public void WebMailUsesScopeStorageForUserName()
{
// Arrange
var value = "value";
// Act
WebMail.UserName = value;
// Assert
Assert.Equal(WebMail.UserName, value);
Assert.Equal(ScopeStorage.CurrentScope[WebMail.UserNameKey], value);
}
[Fact]
public void WebMailUsesScopeStorageForPassword()
{
// Arrange
var value = "value";
// Act
WebMail.Password = value;
// Assert
Assert.Equal(WebMail.Password, value);
Assert.Equal(ScopeStorage.CurrentScope[WebMail.PasswordKey], value);
}
[Fact]
public void WebMailUsesScopeStorageForFrom()
{
// Arrange
var value = "value";
// Act
WebMail.From = value;
// Assert
Assert.Equal(WebMail.From, value);
Assert.Equal(ScopeStorage.CurrentScope[WebMail.FromKey], value);
}
[Fact]
public void WebMailThrowsWhenSmtpServerValueIsNullOrEmpty()
{
// Act and Assert
Assert.ThrowsArgumentNullOrEmptyString(() => WebMail.SmtpServer = null, "SmtpServer");
Assert.ThrowsArgumentNullOrEmptyString(() => WebMail.SmtpServer = String.Empty, "SmtpServer");
}
[Fact]
public void ParseHeaderParsesStringInKeyValueFormat()
{
// Arrange
string header = "foo: bar";
// Act
string key, value;
// Assert
Assert.True(WebMail.TryParseHeader(header, out key, out value));
Assert.Equal("foo", key);
Assert.Equal("bar", value);
}
[Fact]
public void ParseHeaderReturnsFalseIfHeaderIsNotInCorrectFormat()
{
// Arrange
string header = "foo bar";
// Act
string key, value;
// Assert
Assert.False(WebMail.TryParseHeader(header, out key, out value));
Assert.Null(key);
Assert.Null(value);
}
[Fact]
public void SetPropertiesOnMessageTest_SetsAllInfoCorrectlyOnMailMessageTest()
{
// Arrange
MailMessage message = new MailMessage();
string to = "abc123@xyz.com";
string subject = "subject1";
string body = "body1";
string from = FromAddress;
string cc = "cc@xyz.com";
string attachmentName = "NETLogo.png";
string bcc = "foo@bar.com";
string replyTo = "x@y.com,z@pqr.com";
string contentEncoding = "utf-8";
string headerEncoding = "utf-16";
var priority = MailPriority.Low;
// Act
string fileToAttach = Path.GetTempFileName();
try
{
TestFile.Create(attachmentName).Save(fileToAttach);
bool isBodyHtml = true;
var additionalHeaders = new[] { "header1:value1" };
WebMail.SetPropertiesOnMessage(message, to, subject, body, from, cc, bcc, replyTo, contentEncoding, headerEncoding, priority, new[] { fileToAttach }, isBodyHtml, additionalHeaders);
// Assert
Assert.Equal(body, message.Body);
Assert.Equal(subject, message.Subject);
Assert.Equal(to, message.To[0].Address);
Assert.Equal(cc, message.CC[0].Address);
Assert.Equal(from, message.From.Address);
Assert.Equal(bcc, message.Bcc[0].Address);
Assert.Equal("x@y.com", message.ReplyToList[0].Address);
Assert.Equal("z@pqr.com", message.ReplyToList[1].Address);
Assert.Equal(MailPriority.Low, message.Priority);
Assert.Equal(Encoding.UTF8, message.BodyEncoding);
Assert.Equal(Encoding.Unicode, message.HeadersEncoding);
Assert.True(message.Headers.AllKeys.Contains("header1"));
Assert.True(message.Attachments.Count == 1);
}
finally
{
try
{
File.Delete(fileToAttach);
}
catch (IOException)
{
} // Try our best to clean up after ourselves
}
}
[Fact]
public void MailSendWithNullInCollection_ThrowsArgumentException()
{
Assert.Throws<ArgumentException>(
() => WebMail.Send("foo@bar.com", "sub", "body", filesToAttach: new string[] { "c:\\foo.txt", null }),
"A string in the collection is null or empty.\r\nParameter name: filesToAttach"
);
Assert.Throws<ArgumentException>(
() => WebMail.Send("foo@bar.com", "sub", "body", additionalHeaders: new string[] { "foo:bar", null }),
"A string in the collection is null or empty.\r\nParameter name: additionalHeaders"
);
}
[Fact]
public void AssignHeaderValuesIgnoresMalformedHeaders()
{
// Arrange
var message = new MailMessage();
var headers = new[] { "foo1:bar1", "foo2", "foo3|bar3", "foo4 bar4" };
// Act
WebMail.AssignHeaderValues(message, headers);
// Assert
Assert.Equal(1, message.Headers.Count);
Assert.Equal("foo1", message.Headers.AllKeys[0]);
Assert.Equal("bar1", message.Headers[0]);
}
[Fact]
public void PropertiesDuplicatedAcrossHeaderAndArgumentDoesNotThrow()
{
// Arrange
var message = new MailMessage();
var headers = new[] { "to:to@test.com" };
// Act
WebMail.SetPropertiesOnMessage(message, "to@test.com", null, null, "from@test.com", null, null, null, null, null, MailPriority.Normal, null, false, headers);
// Assert
Assert.Equal(2, message.To.Count);
Assert.Equal("to@test.com", message.To.First().Address);
Assert.Equal("to@test.com", message.To.Last().Address);
}
[Fact]
public void AssignHeaderValuesSetsPropertiesForKnownHeaderValues()
{
// Arrange
var message = new MailMessage();
var headers = new[]
{
"cc:cc@test.com", "bcc:bcc@test.com,bcc2@test.com", "from:from@test.com", "priority:high", "reply-to:replyto1@test.com,replyto2@test.com",
"sender: sender@test.com", "to:to@test.com"
};
// Act
WebMail.AssignHeaderValues(message, headers);
// Assert
Assert.Equal("cc@test.com", message.CC.Single().Address);
Assert.Equal("bcc@test.com", message.Bcc.First().Address);
Assert.Equal("bcc2@test.com", message.Bcc.Last().Address);
Assert.Equal("from@test.com", message.From.Address);
Assert.Equal(MailPriority.High, message.Priority);
Assert.Equal("replyto1@test.com", message.ReplyToList.First().Address);
Assert.Equal("replyto2@test.com", message.ReplyToList.Last().Address);
Assert.Equal("sender@test.com", message.Sender.Address);
Assert.Equal("to@test.com", message.To.Single().Address);
// Assert we transparently set header values
Assert.Equal(headers.Count(), message.Headers.Count);
}
[Fact]
public void AssignHeaderDoesNotThrowIfPriorityValueIsInvalid()
{
// Arrange
var message = new MailMessage();
var headers = new[] { "priority:invalid-value" };
// Act
WebMail.AssignHeaderValues(message, headers);
// Assert
Assert.Equal(MailPriority.Normal, message.Priority);
// Assert we transparently set header values
Assert.Equal(1, message.Headers.Count);
Assert.Equal("Priority", message.Headers.Keys[0]);
Assert.Equal("invalid-value", message.Headers["Priority"]);
}
[Fact]
public void AssignHeaderDoesNotThrowIfMailAddressIsInvalid()
{
// Arrange
var message = new MailMessage();
var headers = new[] { "to:not-#-email@@" };
// Act
WebMail.AssignHeaderValues(message, headers);
// Assert
Assert.Equal(0, message.To.Count);
// Assert we transparently set header values
Assert.Equal(1, message.Headers.Count);
Assert.Equal("To", message.Headers.Keys[0]);
Assert.Equal("not-#-email@@", message.Headers["To"]);
}
[Fact]
public void AssignHeaderDoesNotThrowIfKnownHeaderValuesAreEmptyOrMalformed()
{
// Arrange
var message = new MailMessage();
var headers = new[] { "to:", ":reply-to", "priority:false" };
// Act
WebMail.AssignHeaderValues(message, headers);
// Assert
Assert.Equal(0, message.To.Count);
// Assert we transparently set header values
Assert.Equal(1, message.Headers.Count);
Assert.Equal("Priority", message.Headers.Keys[0]);
Assert.Equal("false", message.Headers["Priority"]);
}
[Fact]
public void ArgumentsToSendTakePriorityOverHeader()
{
// Arrange
var message = new MailMessage();
var headers = new[] { "from:header-from@test.com", "cc:header-cc@test.com", "priority:low" };
// Act
WebMail.SetPropertiesOnMessage(message, null, null, null, "direct-from@test.com", "direct-cc@test.com", null, null, null, null, MailPriority.High, null, false, headers);
// Assert
Assert.Equal("direct-from@test.com", message.From.Address);
Assert.Equal("header-cc@test.com", message.CC.First().Address);
Assert.Equal("direct-cc@test.com", message.CC.Last().Address);
Assert.Equal(MailPriority.High, message.Priority);
}
}
}
| 34.739474 | 197 | 0.550867 | [
"Apache-2.0"
] | Darth-Fx/AspNetMvcStack | test/System.Web.Helpers.Test/WebMailTest.cs | 13,203 | C# |
// Licensed to Elasticsearch B.V under one or more agreements.
// Elasticsearch B.V licenses this file to you under the Apache 2.0 License.
// See the LICENSE file in the project root for more information
#if !DOTNETCORE
using System.Linq;
using System;
using System.Net;
using System.Threading;
using System.Threading.Tasks;
using Elastic.Xunit.XunitPlumbing;
using Elasticsearch.Net;
using FluentAssertions;
using Nest;
using Tests.Core.ManagedElasticsearch;
using Tests.Core.ManagedElasticsearch.Clusters;
using HttpMethod = Elasticsearch.Net.HttpMethod;
namespace Tests.ClientConcepts.Connection
{
public class HttpWebRequestConnectionTests : ClusterTestClassBase<ReadOnlyCluster>
{
public HttpWebRequestConnectionTests(ReadOnlyCluster cluster) : base(cluster) { }
private RequestData CreateRequestData(
TimeSpan requestTimeout = default,
Uri proxyAddress = null,
bool disableAutomaticProxyDetection = false,
bool httpCompression = false,
bool transferEncodingChunked = false
)
{
if (requestTimeout == default) requestTimeout = TimeSpan.FromSeconds(10);
var node = Client.ConnectionSettings.ConnectionPool.Nodes.First();
var connectionSettings = new ConnectionSettings(node.Uri)
.RequestTimeout(requestTimeout)
.DisableAutomaticProxyDetection(disableAutomaticProxyDetection)
.TransferEncodingChunked(transferEncodingChunked)
.EnableHttpCompression(httpCompression);
if (proxyAddress != null)
connectionSettings.Proxy(proxyAddress, null, (string)null);
var requestData = new RequestData(HttpMethod.POST, "/_search", "{ \"query\": { \"match_all\" : { } } }", connectionSettings,
new SearchRequestParameters(),
new MemoryStreamFactory()) { Node = node };
return requestData;
}
[I] public async Task HttpWebRequestUseTransferEncodingChunkedWhenTransferEncodingChunkedTrue()
{
var connection = new TestableHttpWebRequestConnection();
var requestData = CreateRequestData(transferEncodingChunked: true);
connection.Request<StringResponse>(requestData);
connection.LastRequest.SendChunked.Should().BeTrue();
connection.LastRequest.ContentLength.Should().Be(-1);
await connection.RequestAsync<StringResponse>(requestData, CancellationToken.None).ConfigureAwait(false);
connection.LastRequest.SendChunked.Should().BeTrue();
connection.LastRequest.ContentLength.Should().Be(-1);
}
[I] public async Task HttpWebRequestSetsContentLengthWhenTransferEncodingChunkedFalse()
{
var connection = new TestableHttpWebRequestConnection();
var requestData = CreateRequestData(transferEncodingChunked: false);
connection.Request<StringResponse>(requestData);
connection.LastRequest.SendChunked.Should().BeFalse();
connection.LastRequest.ContentLength.Should().BeGreaterThan(0);
await connection.RequestAsync<StringResponse>(requestData, CancellationToken.None).ConfigureAwait(false);
connection.LastRequest.SendChunked.Should().BeFalse();
connection.LastRequest.ContentLength.Should().BeGreaterThan(0);
}
public class TestableHttpWebRequestConnection : HttpWebRequestConnection
{
public int CallCount { get; private set; }
public HttpWebRequest LastRequest { get; private set; }
public HttpWebResponse LastResponse => LastRequest != null && LastRequest.HaveResponse
? (HttpWebResponse)LastRequest?.GetResponse()
: null;
public override TResponse Request<TResponse>(RequestData requestData)
{
CallCount++;
return base.Request<TResponse>(requestData);
}
public override Task<TResponse> RequestAsync<TResponse>(RequestData requestData, CancellationToken cancellationToken)
{
CallCount++;
return base.RequestAsync<TResponse>(requestData, cancellationToken);
}
protected override HttpWebRequest CreateHttpWebRequest(RequestData requestData)
{
LastRequest = base.CreateHttpWebRequest(requestData);
return LastRequest;
}
}
}
}
#endif
| 35.45045 | 127 | 0.777382 | [
"Apache-2.0"
] | magaum/elasticsearch-net | tests/Tests/ClientConcepts/Connection/HttpWebRequestConnectionTests.cs | 3,937 | C# |
using System;
using System.Linq;
using System.Text.RegularExpressions;
using Dfc.CourseDirectory.Core.DataStore.CosmosDb;
using Dfc.CourseDirectory.Core.DataStore.CosmosDb.Queries;
using FluentValidation;
namespace Dfc.CourseDirectory.Core.Validation.VenueValidation
{
public static class RuleBuilderExtensions
{
private static readonly Regex _addressLinePattern = new Regex(
@"^[a-zA-Z0-9\.\-']+(?: [a-zA-Z0-9\.\-']+)*$",
RegexOptions.Compiled);
private static readonly Regex _countyPattern = new Regex(
@"^[a-zA-Z\.\-']+(?: [a-zA-Z\.\-']+)*$",
RegexOptions.Compiled);
private static readonly Regex _townPattern = new Regex(
@"^[a-zA-Z\.\-']+(?: [a-zA-Z\.\-']+)*$",
RegexOptions.Compiled);
public static void AddressLine1<T>(this IRuleBuilderInitial<T, string> field)
{
field
.NotEmpty()
.WithMessage("Enter address line 1")
.MaximumLength(Constants.AddressLine1MaxLength)
.WithMessage($"Address line 1 must be {Constants.AddressLine1MaxLength} characters or less")
.Matches(_addressLinePattern)
.WithMessage("Address line 1 must only include letters a to z, numbers, hyphens and spaces");
}
public static void AddressLine2<T>(this IRuleBuilderInitial<T, string> field)
{
field
.MaximumLength(Constants.AddressLine2MaxLength)
.WithMessage($"Address line 2 must be {Constants.AddressLine2MaxLength} characters or less")
.Matches(_addressLinePattern)
.WithMessage("Address line 2 must only include letters a to z, numbers, hyphens and spaces");
}
public static void County<T>(this IRuleBuilderInitial<T, string> field)
{
field
.MaximumLength(Constants.CountyMaxLength)
.WithMessage($"County must be {Constants.CountyMaxLength} characters or less")
.Matches(_countyPattern)
.WithMessage("County must only include letters a to z, numbers, hyphens and spaces");
}
public static void Email<T>(this IRuleBuilderInitial<T, string> field)
{
const string emailRegex = @"^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-||_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+([a-z]+|\d|-|\.{0,1}|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])?([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))$";
field
.Matches(emailRegex, RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.ExplicitCapture)
.WithMessage("Enter an email address in the correct format");
}
public static void PhoneNumber<T>(this IRuleBuilderInitial<T, string> field)
{
field
.Apply(Rules.PhoneNumber)
.WithMessage("Enter a telephone number in the correct format");
}
public static void Postcode<T>(this IRuleBuilderInitial<T, string> field)
{
field
.NotEmpty()
.WithMessage("Enter a postcode")
.Apply(Rules.Postcode)
.WithMessage("Enter a real postcode");
}
public static void Town<T>(this IRuleBuilderInitial<T, string> field)
{
field
.NotEmpty()
.WithMessage("Enter a town or city")
.MaximumLength(Constants.TownMaxLength)
.WithMessage($"Town or city must be {Constants.TownMaxLength} characters or less")
.Matches(_townPattern)
.WithMessage("Town or city must only include letters a to z, numbers, hyphens and spaces");
}
public static void VenueName<T>(
this IRuleBuilderInitial<T, string> field,
int providerUkprn,
Guid? venueId,
ICosmosDbQueryDispatcher cosmosDbQueryDispatcher)
{
field
.NotEmpty()
.WithMessage("Enter location name")
.MaximumLength(Constants.NameMaxLength)
.WithMessage($"Location name must be {Constants.NameMaxLength} characters or fewer")
.MustAsync(async (name, _) =>
{
// Venue name must be distinct for this provider
var providerVenues = await cosmosDbQueryDispatcher.ExecuteQuery(new GetVenuesByProvider()
{
ProviderUkprn = providerUkprn
});
var otherVenuesWithSameName = providerVenues
.Where(v => v.VenueName.Equals(name, StringComparison.OrdinalIgnoreCase))
.Where(v => v.Id != venueId);
return !otherVenuesWithSameName.Any();
})
.WithMessage("Location name must not already exist");
}
public static void Website<T>(this IRuleBuilderInitial<T, string> field)
{
field
.Apply(Rules.Website)
.WithMessage("Enter a website in the correct format");
}
}
}
| 47.761905 | 950 | 0.562978 | [
"MIT"
] | uk-gov-mirror/SkillsFundingAgency.dfc-coursedirectory | src/Dfc.CourseDirectory.Core/Validation/VenueValidation/RuleBuilderExtensions.cs | 6,020 | C# |
using System;
namespace Avalonia.OpenGL
{
public interface IGlSurface : IDisposable
{
IGlDisplay Display { get; }
void SwapBuffers();
}
} | 16.6 | 45 | 0.63253 | [
"MIT"
] | intechinfo/Avalonia | src/Avalonia.OpenGL/IGlSurface.cs | 166 | C# |
using System;
using System.Linq;
using Content.Server.Stunnable.Components;
using Content.Server.UserInterface;
using Content.Shared.ActionBlocker;
using Content.Shared.DragDrop;
using Content.Shared.Hands;
using Content.Shared.Instruments;
using Content.Shared.Interaction;
using Content.Shared.Notification.Managers;
using Content.Shared.Standing;
using Content.Shared.Throwing;
using Robust.Server.GameObjects;
using Robust.Server.Player;
using Robust.Shared.Enums;
using Robust.Shared.GameObjects;
using Robust.Shared.Localization;
using Robust.Shared.Network;
using Robust.Shared.Players;
using Robust.Shared.Serialization.Manager.Attributes;
using Robust.Shared.ViewVariables;
namespace Content.Server.Instruments
{
[RegisterComponent]
[ComponentReference(typeof(IActivate))]
public class InstrumentComponent
: SharedInstrumentComponent,
IDropped,
IHandSelected,
IHandDeselected,
IActivate,
IUse,
IThrown
{
private InstrumentSystem _instrumentSystem = default!;
/// <summary>
/// The client channel currently playing the instrument, or null if there's none.
/// </summary>
[ViewVariables]
private IPlayerSession? _instrumentPlayer;
[DataField("handheld")]
private bool _handheld;
[ViewVariables]
private bool _playing = false;
[ViewVariables]
private float _timer = 0f;
[ViewVariables]
private int _batchesDropped = 0;
[ViewVariables]
private int _laggedBatches = 0;
[ViewVariables]
private uint _lastSequencerTick = 0;
[ViewVariables]
private int _midiEventCount = 0;
[DataField("program")]
private byte _instrumentProgram = 1;
[DataField("bank")]
private byte _instrumentBank;
[DataField("allowPercussion")]
private bool _allowPercussion;
[DataField("allowProgramChange")]
private bool _allowProgramChange;
[DataField("respectMidiLimits")]
private bool _respectMidiLimits = true;
public override byte InstrumentProgram { get => _instrumentProgram;
set
{
_instrumentProgram = value;
Dirty();
}
}
public override byte InstrumentBank { get => _instrumentBank;
set
{
_instrumentBank = value;
Dirty();
}
}
public override bool AllowPercussion { get => _allowPercussion;
set
{
_allowPercussion = value;
Dirty();
}
}
public override bool AllowProgramChange { get => _allowProgramChange;
set
{
_allowProgramChange = value;
Dirty();
}
}
public override bool RespectMidiLimits { get => _respectMidiLimits;
set
{
_respectMidiLimits = value;
Dirty();
}
}
/// <summary>
/// Whether the instrument is an item which can be held or not.
/// </summary>
[ViewVariables]
public bool Handheld => _handheld;
/// <summary>
/// Whether the instrument is currently playing or not.
/// </summary>
[ViewVariables]
public bool Playing
{
get => _playing;
set
{
_playing = value;
Dirty();
}
}
public IPlayerSession? InstrumentPlayer
{
get => _instrumentPlayer;
private set
{
Playing = false;
if (_instrumentPlayer != null)
_instrumentPlayer.PlayerStatusChanged -= OnPlayerStatusChanged;
_instrumentPlayer = value;
if (value != null)
_instrumentPlayer!.PlayerStatusChanged += OnPlayerStatusChanged;
}
}
[ViewVariables] private BoundUserInterface? UserInterface => Owner.GetUIOrNull(InstrumentUiKey.Key);
private void OnPlayerStatusChanged(object? sender, SessionStatusEventArgs e)
{
if (e.Session != _instrumentPlayer || e.NewStatus != SessionStatus.Disconnected) return;
InstrumentPlayer = null;
Clean();
}
protected override void Initialize()
{
base.Initialize();
if (UserInterface != null)
{
UserInterface.OnClosed += UserInterfaceOnClosed;
}
_instrumentSystem = EntitySystem.Get<InstrumentSystem>();
}
public override ComponentState GetComponentState(ICommonSession player)
{
return new InstrumentState(Playing, InstrumentProgram, InstrumentBank, AllowPercussion, AllowProgramChange, RespectMidiLimits, _lastSequencerTick);
}
public override void HandleNetworkMessage(ComponentMessage message, INetChannel channel, ICommonSession? session = null)
{
base.HandleNetworkMessage(message, channel, session);
var maxMidiLaggedBatches = _instrumentSystem.MaxMidiLaggedBatches;
var maxMidiEventsPerSecond = _instrumentSystem.MaxMidiEventsPerSecond;
var maxMidiEventsPerBatch = _instrumentSystem.MaxMidiEventsPerBatch;
switch (message)
{
case InstrumentMidiEventMessage midiEventMsg:
if (!Playing || session != _instrumentPlayer || InstrumentPlayer == null) return;
var send = true;
var minTick = midiEventMsg.MidiEvent.Min(x => x.Tick);
if (_lastSequencerTick > minTick)
{
_laggedBatches++;
if (_respectMidiLimits)
{
if (_laggedBatches == (int) (maxMidiLaggedBatches * (1 / 3d) + 1))
{
InstrumentPlayer.AttachedEntity?.PopupMessage(
Loc.GetString("instrument-component-finger-cramps-light-message"));
} else if (_laggedBatches == (int) (maxMidiLaggedBatches * (2 / 3d) + 1))
{
InstrumentPlayer.AttachedEntity?.PopupMessage(
Loc.GetString("instrument-component-finger-cramps-serious-message"));
}
}
if (_laggedBatches > maxMidiLaggedBatches)
{
send = false;
}
}
if (++_midiEventCount > maxMidiEventsPerSecond
|| midiEventMsg.MidiEvent.Length > maxMidiEventsPerBatch)
{
_batchesDropped++;
send = false;
}
if (send || !_respectMidiLimits)
{
SendNetworkMessage(midiEventMsg);
}
var maxTick = midiEventMsg.MidiEvent.Max(x => x.Tick);
_lastSequencerTick = Math.Max(maxTick, minTick);
break;
case InstrumentStartMidiMessage startMidi:
if (session != _instrumentPlayer)
break;
Playing = true;
break;
case InstrumentStopMidiMessage stopMidi:
if (session != _instrumentPlayer)
break;
Playing = false;
Clean();
break;
}
}
private void Clean()
{
Playing = false;
_lastSequencerTick = 0;
_batchesDropped = 0;
_laggedBatches = 0;
}
void IDropped.Dropped(DroppedEventArgs eventArgs)
{
Clean();
SendNetworkMessage(new InstrumentStopMidiMessage());
InstrumentPlayer = null;
UserInterface?.CloseAll();
}
void IThrown.Thrown(ThrownEventArgs eventArgs)
{
Clean();
SendNetworkMessage(new InstrumentStopMidiMessage());
InstrumentPlayer = null;
UserInterface?.CloseAll();
}
void IHandSelected.HandSelected(HandSelectedEventArgs eventArgs)
{
if (eventArgs.User == null || !eventArgs.User.TryGetComponent(out ActorComponent? actor))
return;
var session = actor.PlayerSession;
if (session.Status != SessionStatus.InGame) return;
InstrumentPlayer = session;
}
void IHandDeselected.HandDeselected(HandDeselectedEventArgs eventArgs)
{
Clean();
SendNetworkMessage(new InstrumentStopMidiMessage());
UserInterface?.CloseAll();
}
void IActivate.Activate(ActivateEventArgs eventArgs)
{
if (Handheld)
return;
InteractInstrument(eventArgs.User);
}
bool IUse.UseEntity(UseEntityEventArgs eventArgs)
{
InteractInstrument(eventArgs.User);
return false;
}
private void InteractInstrument(IEntity user)
{
if (!user.TryGetComponent(out ActorComponent? actor)) return;
if ((!Handheld && InstrumentPlayer != null)
|| (Handheld && actor.PlayerSession != InstrumentPlayer)
|| !EntitySystem.Get<ActionBlockerSystem>().CanInteract(user)) return;
InstrumentPlayer = actor.PlayerSession;
OpenUserInterface(InstrumentPlayer);
return;
}
private void UserInterfaceOnClosed(IPlayerSession player)
{
if (Handheld || player != InstrumentPlayer) return;
Clean();
InstrumentPlayer = null;
SendNetworkMessage(new InstrumentStopMidiMessage());
}
private void OpenUserInterface(IPlayerSession session)
{
UserInterface?.Toggle(session);
}
public override void Update(float delta)
{
base.Update(delta);
var maxMidiLaggedBatches = _instrumentSystem.MaxMidiLaggedBatches;
var maxMidiBatchDropped = _instrumentSystem.MaxMidiBatchesDropped;
if (_instrumentPlayer != null
&& (_instrumentPlayer.AttachedEntity == null
|| !EntitySystem.Get<ActionBlockerSystem>().CanInteract(_instrumentPlayer.AttachedEntity)))
{
InstrumentPlayer = null;
Clean();
UserInterface?.CloseAll();
}
if ((_batchesDropped >= maxMidiBatchDropped
|| _laggedBatches >= maxMidiLaggedBatches)
&& InstrumentPlayer != null && _respectMidiLimits)
{
var mob = InstrumentPlayer.AttachedEntity;
SendNetworkMessage(new InstrumentStopMidiMessage());
Playing = false;
UserInterface?.CloseAll();
if (mob != null)
{
if (Handheld)
EntitySystem.Get<StandingStateSystem>().Down(mob, false);
if (mob.TryGetComponent(out StunnableComponent? stun))
{
stun.Stun(1);
Clean();
}
Owner.PopupMessage(mob, "instrument-component-finger-cramps-max-message");
}
InstrumentPlayer = null;
}
_timer += delta;
if (_timer < 1) return;
_timer = 0f;
_midiEventCount = 0;
_laggedBatches = 0;
_batchesDropped = 0;
}
}
}
| 31.266667 | 159 | 0.536165 | [
"MIT"
] | AndrewSmart/space-station-14 | Content.Server/Instruments/InstrumentComponent.cs | 12,194 | C# |
// <auto-generated>
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// </auto-generated>
namespace Microsoft.Azure.Management.DevTestLabs
{
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// Extension methods for CostsOperations.
/// </summary>
public static partial class CostsOperationsExtensions
{
/// <summary>
/// Get cost.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='labName'>
/// The name of the lab.
/// </param>
/// <param name='name'>
/// The name of the cost.
/// </param>
/// <param name='expand'>
/// Specify the $expand query. Example: 'properties($expand=labCostDetails)'
/// </param>
public static LabCost Get(this ICostsOperations operations, string resourceGroupName, string labName, string name, string expand = default(string))
{
return operations.GetAsync(resourceGroupName, labName, name, expand).GetAwaiter().GetResult();
}
/// <summary>
/// Get cost.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='labName'>
/// The name of the lab.
/// </param>
/// <param name='name'>
/// The name of the cost.
/// </param>
/// <param name='expand'>
/// Specify the $expand query. Example: 'properties($expand=labCostDetails)'
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<LabCost> GetAsync(this ICostsOperations operations, string resourceGroupName, string labName, string name, string expand = default(string), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetWithHttpMessagesAsync(resourceGroupName, labName, name, expand, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Create or replace an existing cost.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='labName'>
/// The name of the lab.
/// </param>
/// <param name='name'>
/// The name of the cost.
/// </param>
/// <param name='labCost'>
/// A cost item.
/// </param>
public static LabCost CreateOrUpdate(this ICostsOperations operations, string resourceGroupName, string labName, string name, LabCost labCost)
{
return operations.CreateOrUpdateAsync(resourceGroupName, labName, name, labCost).GetAwaiter().GetResult();
}
/// <summary>
/// Create or replace an existing cost.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='labName'>
/// The name of the lab.
/// </param>
/// <param name='name'>
/// The name of the cost.
/// </param>
/// <param name='labCost'>
/// A cost item.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<LabCost> CreateOrUpdateAsync(this ICostsOperations operations, string resourceGroupName, string labName, string name, LabCost labCost, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.CreateOrUpdateWithHttpMessagesAsync(resourceGroupName, labName, name, labCost, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
}
}
| 40.361538 | 242 | 0.535544 | [
"MIT"
] | 0rland0Wats0n/azure-sdk-for-net | sdk/devtestlabs/Microsoft.Azure.Management.DevTestLabs/src/Generated/CostsOperationsExtensions.cs | 5,247 | C# |
using System;
using NetRuntimeSystem = System;
using System.ComponentModel;
using NetOffice.Attributes;
using NetOffice.OutlookApi;
namespace NetOffice.OutlookApi.Behind
{
/// <summary>
/// DispatchInterface _TextRuleCondition
/// SupportByVersion Outlook, 12,14,15,16
/// </summary>
[SupportByVersion("Outlook", 12,14,15,16)]
[EntityType(EntityType.IsDispatchInterface), BaseType]
public class _TextRuleCondition : COMObject, NetOffice.OutlookApi._TextRuleCondition
{
#pragma warning disable
#region Type Information
/// <summary>
/// Contract Type
/// </summary>
[EditorBrowsable(EditorBrowsableState.Advanced), Browsable(false), Category("NetOffice"), CoreOverridden]
public override Type ContractType
{
get
{
if(null == _contractType)
_contractType = typeof(NetOffice.OutlookApi._TextRuleCondition);
return _contractType;
}
}
private static Type _contractType;
/// <summary>
/// Instance Type
/// </summary>
[EditorBrowsable(EditorBrowsableState.Advanced), Browsable(false), Category("NetOffice"), CoreOverridden]
public override Type InstanceType
{
get
{
return LateBindingApiWrapperType;
}
}
private static Type _type;
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public static Type LateBindingApiWrapperType
{
get
{
if (null == _type)
_type = typeof(_TextRuleCondition);
return _type;
}
}
#endregion
#region Ctor
/// <summary>
/// Stub Ctor, not indented to use
/// </summary>
public _TextRuleCondition() : base()
{
}
#endregion
#region Properties
/// <summary>
/// SupportByVersion Outlook 12, 14, 15, 16
/// Get
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff864761.aspx </remarks>
[SupportByVersion("Outlook", 12,14,15,16)]
[BaseResult]
public virtual NetOffice.OutlookApi._Application Application
{
get
{
return InvokerService.InvokeInternal.ExecuteBaseReferencePropertyGet<NetOffice.OutlookApi._Application>(this, "Application");
}
}
/// <summary>
/// SupportByVersion Outlook 12, 14, 15, 16
/// Get
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff863731.aspx </remarks>
[SupportByVersion("Outlook", 12,14,15,16)]
public virtual NetOffice.OutlookApi.Enums.OlObjectClass Class
{
get
{
return InvokerService.InvokeInternal.ExecuteEnumPropertyGet<NetOffice.OutlookApi.Enums.OlObjectClass>(this, "Class");
}
}
/// <summary>
/// SupportByVersion Outlook 12, 14, 15, 16
/// Get
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff862701.aspx </remarks>
[SupportByVersion("Outlook", 12,14,15,16)]
[BaseResult]
public virtual NetOffice.OutlookApi._NameSpace Session
{
get
{
return InvokerService.InvokeInternal.ExecuteBaseReferencePropertyGet<NetOffice.OutlookApi._NameSpace>(this, "Session");
}
}
/// <summary>
/// SupportByVersion Outlook 12, 14, 15, 16
/// Get
/// Unknown COM Proxy
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff865092.aspx </remarks>
[SupportByVersion("Outlook", 12,14,15,16), ProxyResult]
public virtual object Parent
{
get
{
return InvokerService.InvokeInternal.ExecuteReferencePropertyGet(this, "Parent");
}
}
/// <summary>
/// SupportByVersion Outlook 12, 14, 15, 16
/// Get/Set
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff866402.aspx </remarks>
[SupportByVersion("Outlook", 12,14,15,16)]
public virtual bool Enabled
{
get
{
return InvokerService.InvokeInternal.ExecuteBoolPropertyGet(this, "Enabled");
}
set
{
InvokerService.InvokeInternal.ExecuteValuePropertySet(this, "Enabled", value);
}
}
/// <summary>
/// SupportByVersion Outlook 12, 14, 15, 16
/// Get
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff862988.aspx </remarks>
[SupportByVersion("Outlook", 12,14,15,16)]
public virtual NetOffice.OutlookApi.Enums.OlRuleConditionType ConditionType
{
get
{
return InvokerService.InvokeInternal.ExecuteEnumPropertyGet<NetOffice.OutlookApi.Enums.OlRuleConditionType>(this, "ConditionType");
}
}
/// <summary>
/// SupportByVersion Outlook 12, 14, 15, 16
/// Get/Set
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff865798.aspx </remarks>
[SupportByVersion("Outlook", 12,14,15,16)]
public virtual object Text
{
get
{
return InvokerService.InvokeInternal.ExecuteVariantPropertyGet(this, "Text");
}
set
{
InvokerService.InvokeInternal.ExecuteVariantPropertySet(this, "Text", value);
}
}
#endregion
#region Methods
#endregion
#pragma warning restore
}
}
| 26.314721 | 135 | 0.664159 | [
"MIT"
] | igoreksiz/NetOffice | Source/Outlook/Behind/DispatchInterfaces/_TextRuleCondition.cs | 5,186 | C# |
// -----------------------------------------------------------------------------
// 让 .NET 开发更简单,更通用,更流行。
// Copyright © 2020-2021 Furion, 百小僧, Baiqian Co.,Ltd.
//
// 框架名称:Furion
// 框架作者:百小僧
// 框架版本:2.14.1
// 源码地址:Gitee: https://gitee.com/dotnetchina/Furion
// Github:https://github.com/monksoul/Furion
// 开源协议:Apache-2.0(https://gitee.com/dotnetchina/Furion/blob/master/LICENSE)
// -----------------------------------------------------------------------------
using Furion.DependencyInjection;
using Microsoft.EntityFrameworkCore;
using System;
namespace Furion.DatabaseAccessor
{
/// <summary>
/// 数据库公开类
/// </summary>
[SuppressSniffer]
public static class Db
{
/// <summary>
/// 迁移类库名称
/// </summary>
internal static string MigrationAssemblyName = "Furion.Database.Migrations";
/// <summary>
/// 是否启用自定义租户类型
/// </summary>
internal static bool CustomizeMultiTenants;
/// <summary>
/// 基于表的多租户外键名
/// </summary>
internal static string OnTableTenantId = nameof(Entity.TenantId);
/// <summary>
/// 获取非泛型仓储
/// </summary>
/// <param name="serviceProvider"></param>
/// <returns></returns>
public static IRepository GetRepository(IServiceProvider serviceProvider = default)
{
return App.GetService<IRepository>(serviceProvider);
}
/// <summary>
/// 获取实体仓储
/// </summary>
/// <typeparam name="TEntity">实体类型</typeparam>
/// <param name="serviceProvider"></param>
/// <returns>IRepository{TEntity}</returns>
public static IRepository<TEntity> GetRepository<TEntity>(IServiceProvider serviceProvider = default)
where TEntity : class, IPrivateEntity, new()
{
return App.GetService<IRepository<TEntity>>(serviceProvider);
}
/// <summary>
/// 获取实体仓储
/// </summary>
/// <typeparam name="TEntity">实体类型</typeparam>
/// <typeparam name="TDbContextLocator">数据库上下文定位器</typeparam>
/// <param name="serviceProvider"></param>
/// <returns>IRepository{TEntity, TDbContextLocator}</returns>
public static IRepository<TEntity, TDbContextLocator> GetRepository<TEntity, TDbContextLocator>(IServiceProvider serviceProvider = default)
where TEntity : class, IPrivateEntity, new()
where TDbContextLocator : class, IDbContextLocator
{
return App.GetService<IRepository<TEntity, TDbContextLocator>>(serviceProvider);
}
/// <summary>
/// 根据定位器类型获取仓储
/// </summary>
/// <typeparam name="TEntity"></typeparam>
/// <param name="dbContextLocator"></param>
/// <param name="serviceProvider"></param>
/// <returns></returns>
public static IPrivateRepository<TEntity> GetRepository<TEntity>(Type dbContextLocator, IServiceProvider serviceProvider = default)
where TEntity : class, IPrivateEntity, new()
{
return App.GetService(typeof(IRepository<,>).MakeGenericType(typeof(TEntity), dbContextLocator), serviceProvider) as IPrivateRepository<TEntity>;
}
/// <summary>
/// 获取Sql仓储
/// </summary>
/// <param name="serviceProvider"></param>
/// <returns>ISqlRepository</returns>
public static ISqlRepository GetSqlRepository(IServiceProvider serviceProvider = default)
{
return App.GetService<ISqlRepository>(serviceProvider);
}
/// <summary>
/// 获取Sql仓储
/// </summary>
/// <typeparam name="TDbContextLocator">数据库上下文定位器</typeparam>
/// <param name="serviceProvider"></param>
/// <returns>ISqlRepository{TDbContextLocator}</returns>
public static ISqlRepository<TDbContextLocator> GetSqlRepository<TDbContextLocator>(IServiceProvider serviceProvider = default)
where TDbContextLocator : class, IDbContextLocator
{
return App.GetService<ISqlRepository<TDbContextLocator>>(serviceProvider);
}
/// <summary>
/// 获取随机主从库仓储
/// </summary>
/// <param name="serviceProvider"></param>
/// <returns>ISqlRepository</returns>
public static IMSRepository GetMSRepository(IServiceProvider serviceProvider = default)
{
return App.GetService<IMSRepository>(serviceProvider);
}
/// <summary>
/// 获取随机主从库仓储
/// </summary>
/// <typeparam name="TMasterDbContextLocator">主库数据库上下文定位器</typeparam>
/// <param name="serviceProvider"></param>
/// <returns>IMSRepository{TDbContextLocator}</returns>
public static IMSRepository<TMasterDbContextLocator> GetMSRepository<TMasterDbContextLocator>(IServiceProvider serviceProvider = default)
where TMasterDbContextLocator : class, IDbContextLocator
{
return App.GetService<IMSRepository<TMasterDbContextLocator>>(serviceProvider);
}
/// <summary>
/// 获取Sql代理
/// </summary>
/// <param name="serviceProvider"></param>
/// <returns>ISqlRepository</returns>
public static TSqlDispatchProxy GetSqlProxy<TSqlDispatchProxy>(IServiceProvider serviceProvider = default)
where TSqlDispatchProxy : class, ISqlDispatchProxy
{
return App.GetService<TSqlDispatchProxy>(serviceProvider);
}
/// <summary>
/// 获取作用域数据库上下文
/// </summary>
/// <param name="serviceProvider"></param>
/// <returns></returns>
public static DbContext GetDbContext(IServiceProvider serviceProvider = default)
{
return GetDbContext(typeof(MasterDbContextLocator), serviceProvider);
}
/// <summary>
/// 获取作用域数据库上下文
/// </summary>
/// <param name="dbContextLocator">数据库上下文定位器</param>
/// <param name="serviceProvider"></param>
/// <returns></returns>
public static DbContext GetDbContext(Type dbContextLocator, IServiceProvider serviceProvider = default)
{
// 判断是否注册了数据库上下文
if (!Penetrates.DbContextWithLocatorCached.ContainsKey(dbContextLocator)) return default;
var dbContextResolve = App.GetService<Func<Type, IScoped, DbContext>>(serviceProvider);
return dbContextResolve(dbContextLocator, default);
}
/// <summary>
/// 获取作用域数据库上下文
/// </summary>
/// <typeparam name="TDbContextLocator">数据库上下文定位器</typeparam>
/// <param name="serviceProvider"></param>
/// <returns></returns>
public static DbContext GetDbContext<TDbContextLocator>(IServiceProvider serviceProvider = default)
where TDbContextLocator : class, IDbContextLocator
{
return GetDbContext(typeof(TDbContextLocator), serviceProvider);
}
}
} | 38.723757 | 157 | 0.608361 | [
"Apache-2.0"
] | Cuixq123/Furion | framework/Furion/DatabaseAccessor/Db.cs | 7,500 | C# |
using UnityEngine;
namespace PlayFab.Internal
{
//public to be accessible by Unity engine
public class SingletonMonoBehaviour<T> : MonoBehaviour where T : SingletonMonoBehaviour<T>
{
private static T _instance;
public static T instance
{
get
{
CreateInstance();
return _instance;
}
}
public static void CreateInstance()
{
if (_instance == null)
{
//find existing instance
_instance = FindObjectOfType<T>();
if (_instance == null)
{
//create new instance
var go = new GameObject(typeof(T).Name);
_instance = go.AddComponent<T>();
}
//initialize instance if necessary
if (!_instance.initialized)
{
_instance.Initialize();
_instance.initialized = true;
}
}
}
public virtual void Awake ()
{
if (Application.isPlaying)
{
DontDestroyOnLoad(this);
}
//check if instance already exists when reloading original scene
if (_instance != null)
{
DestroyImmediate (gameObject);
}
}
protected bool initialized;
protected virtual void Initialize() { }
}
}
| 26.016949 | 94 | 0.461889 | [
"MIT"
] | BrianPeek/Scavenger | src/Unity/Assets/PlayFabSdk/Shared/Internal/SingletonMonoBehaviour.cs | 1,535 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.FindSymbols;
using Microsoft.CodeAnalysis.FindSymbols.FindReferences;
using Microsoft.CodeAnalysis.FindUsages;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Remote;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.InheritanceMargin
{
internal static class InheritanceMarginServiceHelper
{
private static readonly SymbolDisplayFormat s_displayFormat = new(
globalNamespaceStyle: SymbolDisplayGlobalNamespaceStyle.OmittedAsContaining,
typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameAndContainingTypes,
genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters,
memberOptions:
SymbolDisplayMemberOptions.IncludeContainingType |
SymbolDisplayMemberOptions.IncludeExplicitInterface,
propertyStyle: SymbolDisplayPropertyStyle.NameOnly,
miscellaneousOptions:
SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers |
SymbolDisplayMiscellaneousOptions.UseSpecialTypes |
SymbolDisplayMiscellaneousOptions.UseErrorTypeSymbolName |
SymbolDisplayMiscellaneousOptions.IncludeNullableReferenceTypeModifier);
public static async ValueTask<ImmutableArray<SerializableInheritanceMarginItem>> GetInheritanceMemberItemAsync(
Solution solution,
ProjectId projectId,
ImmutableArray<(SymbolKey symbolKey, int lineNumber)> symbolKeyAndLineNumbers,
CancellationToken cancellationToken)
{
var remoteClient = await RemoteHostClient.TryGetClientAsync(solution.Workspace, cancellationToken).ConfigureAwait(false);
if (remoteClient != null)
{
// Here the line number is also passed to the remote process. It is done in this way because
// when a set of symbols is passed to remote process, those without inheritance targets would not be returned.
// To match the returned inheritance targets to the line number, we need set an 'Id' when calling the remote process,
// however, given the line number is just an int, setting up an int 'Id' for an int is quite useless, so just passed it to the remote process.
var result = await remoteClient.TryInvokeAsync<IRemoteInheritanceMarginService, ImmutableArray<SerializableInheritanceMarginItem>>(
solution,
(remoteInheritanceMarginService, solutionInfo, cancellationToken) =>
remoteInheritanceMarginService.GetInheritanceMarginItemsAsync(solutionInfo, projectId, symbolKeyAndLineNumbers, cancellationToken),
cancellationToken).ConfigureAwait(false);
if (!result.HasValue)
{
return ImmutableArray<SerializableInheritanceMarginItem>.Empty;
}
return result.Value;
}
else
{
return await GetInheritanceMemberItemInProcAsync(solution, projectId, symbolKeyAndLineNumbers, cancellationToken).ConfigureAwait(false);
}
}
private static async ValueTask<ImmutableArray<SerializableInheritanceMarginItem>> GetInheritanceMemberItemInProcAsync(
Solution solution,
ProjectId projectId,
ImmutableArray<(SymbolKey symbolKey, int lineNumber)> symbolKeyAndLineNumbers,
CancellationToken cancellationToken)
{
var project = solution.GetRequiredProject(projectId);
var compilation = await project.GetRequiredCompilationAsync(cancellationToken).ConfigureAwait(false);
using var _ = ArrayBuilder<SerializableInheritanceMarginItem>.GetInstance(out var builder);
foreach (var (symbolKey, lineNumber) in symbolKeyAndLineNumbers)
{
var symbol = symbolKey.Resolve(compilation, cancellationToken: cancellationToken).Symbol;
if (symbol is INamedTypeSymbol namedTypeSymbol)
{
await AddInheritanceMemberItemsForNamedTypeAsync(solution, namedTypeSymbol, lineNumber, builder, cancellationToken).ConfigureAwait(false);
}
if (symbol is IEventSymbol or IPropertySymbol or IMethodSymbol)
{
await AddInheritanceMemberItemsForMembersAsync(solution, symbol, lineNumber, builder, cancellationToken).ConfigureAwait(false);
}
}
return builder.ToImmutable();
}
private static async ValueTask AddInheritanceMemberItemsForNamedTypeAsync(
Solution solution,
INamedTypeSymbol memberSymbol,
int lineNumber,
ArrayBuilder<SerializableInheritanceMarginItem> builder,
CancellationToken cancellationToken)
{
// Get all base types.
var allBaseSymbols = BaseTypeFinder.FindBaseTypesAndInterfaces(memberSymbol);
// Filter out
// 1. System.Object. (otherwise margin would be shown for all classes)
// 2. System.ValueType. (otherwise margin would be shown for all structs)
// 3. System.Enum. (otherwise margin would be shown for all enum)
// 4. Error type.
// For example, if user has code like this,
// class Bar : ISomethingIsNotDone { }
// The interface has not been declared yet, so don't show this error type to user.
var baseSymbols = allBaseSymbols
.WhereAsArray(symbol => !symbol.IsErrorType() && symbol.SpecialType is not (SpecialType.System_Object or SpecialType.System_ValueType or SpecialType.System_Enum));
// Get all derived types
var allDerivedSymbols = await GetDerivedTypesAndImplementationsAsync(
solution,
memberSymbol,
cancellationToken).ConfigureAwait(false);
// Ensure the user won't be able to see symbol outside the solution for derived symbols.
// For example, if user is viewing 'IEnumerable interface' from metadata, we don't want to tell
// the user all the derived types under System.Collections
var derivedSymbols = allDerivedSymbols.WhereAsArray(symbol => symbol.Locations.Any(l => l.IsInSource));
if (baseSymbols.Any() || derivedSymbols.Any())
{
if (memberSymbol.TypeKind == TypeKind.Interface)
{
var item = await CreateInheritanceMemberItemForInterfaceAsync(
solution,
memberSymbol,
lineNumber,
baseSymbols: baseSymbols.CastArray<ISymbol>(),
derivedTypesSymbols: derivedSymbols.CastArray<ISymbol>(),
cancellationToken).ConfigureAwait(false);
builder.AddIfNotNull(item);
}
else
{
Debug.Assert(memberSymbol.TypeKind is TypeKind.Class or TypeKind.Struct);
var item = await CreateInheritanceItemForClassAndStructureAsync(
solution,
memberSymbol,
lineNumber,
baseSymbols: baseSymbols.CastArray<ISymbol>(),
derivedTypesSymbols: derivedSymbols.CastArray<ISymbol>(),
cancellationToken).ConfigureAwait(false);
builder.AddIfNotNull(item);
}
}
}
private static async ValueTask AddInheritanceMemberItemsForMembersAsync(
Solution solution,
ISymbol memberSymbol,
int lineNumber,
ArrayBuilder<SerializableInheritanceMarginItem> builder,
CancellationToken cancellationToken)
{
if (memberSymbol.ContainingSymbol.IsInterfaceType())
{
// Go down the inheritance chain to find all the implementing targets.
var allImplementingSymbols = await GetImplementingSymbolsForTypeMemberAsync(solution, memberSymbol, cancellationToken).ConfigureAwait(false);
// For all implementing symbols, make sure it is in source.
// For example, if the user is viewing IEnumerable from metadata,
// then don't show the derived overriden & implemented types in System.Collections
var implementingSymbols = allImplementingSymbols.WhereAsArray(symbol => symbol.Locations.Any(l => l.IsInSource));
if (implementingSymbols.Any())
{
var item = await CreateInheritanceMemberItemForInterfaceMemberAsync(solution,
memberSymbol,
lineNumber,
implementingMembers: implementingSymbols,
cancellationToken).ConfigureAwait(false);
builder.AddIfNotNull(item);
}
}
else
{
// Go down the inheritance chain to find all the overriding targets.
var allOverridingSymbols = await SymbolFinder.FindOverridesArrayAsync(memberSymbol, solution, cancellationToken: cancellationToken).ConfigureAwait(false);
// Go up the inheritance chain to find all overridden targets
var overriddenSymbols = GetOverriddenSymbols(memberSymbol);
// Go up the inheritance chain to find all the implemented targets.
var implementedSymbols = GetImplementedSymbolsForTypeMember(memberSymbol, overriddenSymbols);
// For all overriding symbols, make sure it is in source.
// For example, if the user is viewing System.Threading.SynchronizationContext from metadata,
// then don't show the derived overriden & implemented method in the default implementation for System.Threading.SynchronizationContext in metadata
var overridingSymbols = allOverridingSymbols.WhereAsArray(symbol => symbol.Locations.Any(l => l.IsInSource));
if (overridingSymbols.Any() || overriddenSymbols.Any() || implementedSymbols.Any())
{
var item = await CreateInheritanceMemberItemForClassOrStructMemberAsync(solution,
memberSymbol,
lineNumber,
implementedMembers: implementedSymbols,
overridingMembers: overridingSymbols,
overriddenMembers: overriddenSymbols,
cancellationToken).ConfigureAwait(false);
builder.AddIfNotNull(item);
}
}
}
private static async ValueTask<SerializableInheritanceMarginItem> CreateInheritanceMemberItemForInterfaceAsync(
Solution solution,
INamedTypeSymbol interfaceSymbol,
int lineNumber,
ImmutableArray<ISymbol> baseSymbols,
ImmutableArray<ISymbol> derivedTypesSymbols,
CancellationToken cancellationToken)
{
var baseSymbolItems = await baseSymbols
.SelectAsArray(symbol => symbol.OriginalDefinition)
.WhereAsArray(IsNavigableSymbol)
.Distinct()
.SelectAsArrayAsync((symbol, _) => CreateInheritanceItemAsync(
solution,
symbol,
InheritanceRelationship.InheritedInterface,
cancellationToken), cancellationToken)
.ConfigureAwait(false);
var derivedTypeItems = await derivedTypesSymbols
.SelectAsArray(symbol => symbol.OriginalDefinition)
.WhereAsArray(IsNavigableSymbol)
.Distinct()
.SelectAsArrayAsync((symbol, _) => CreateInheritanceItemAsync(solution,
symbol,
InheritanceRelationship.ImplementingType,
cancellationToken), cancellationToken)
.ConfigureAwait(false);
return new SerializableInheritanceMarginItem(
lineNumber,
FindUsagesHelpers.GetDisplayParts(interfaceSymbol),
interfaceSymbol.GetGlyph(),
baseSymbolItems.Concat(derivedTypeItems));
}
private static async ValueTask<SerializableInheritanceMarginItem> CreateInheritanceMemberItemForInterfaceMemberAsync(
Solution solution,
ISymbol memberSymbol,
int lineNumber,
ImmutableArray<ISymbol> implementingMembers,
CancellationToken cancellationToken)
{
var implementedMemberItems = await implementingMembers
.SelectAsArray(symbol => symbol.OriginalDefinition)
.WhereAsArray(IsNavigableSymbol)
.Distinct()
.SelectAsArrayAsync((symbol, _) => CreateInheritanceItemAsync(
solution,
symbol,
InheritanceRelationship.ImplementingMember,
cancellationToken), cancellationToken).ConfigureAwait(false);
return new SerializableInheritanceMarginItem(
lineNumber,
FindUsagesHelpers.GetDisplayParts(memberSymbol),
memberSymbol.GetGlyph(),
implementedMemberItems);
}
private static async ValueTask<SerializableInheritanceMarginItem> CreateInheritanceItemForClassAndStructureAsync(
Solution solution,
INamedTypeSymbol memberSymbol,
int lineNumber,
ImmutableArray<ISymbol> baseSymbols,
ImmutableArray<ISymbol> derivedTypesSymbols,
CancellationToken cancellationToken)
{
// If the target is an interface, it would be shown as 'Inherited interface',
// and if it is an class/struct, it whould be shown as 'Base Type'
var baseSymbolItems = await baseSymbols
.SelectAsArray(symbol => symbol.OriginalDefinition)
.WhereAsArray(IsNavigableSymbol)
.Distinct()
.SelectAsArrayAsync((symbol, _) => CreateInheritanceItemAsync(
solution,
symbol,
symbol.IsInterfaceType() ? InheritanceRelationship.ImplementedInterface : InheritanceRelationship.BaseType,
cancellationToken), cancellationToken).ConfigureAwait(false);
var derivedTypeItems = await derivedTypesSymbols
.SelectAsArray(symbol => symbol.OriginalDefinition)
.WhereAsArray(IsNavigableSymbol)
.Distinct()
.SelectAsArrayAsync((symbol, _) => CreateInheritanceItemAsync(solution,
symbol,
InheritanceRelationship.DerivedType,
cancellationToken), cancellationToken)
.ConfigureAwait(false);
return new SerializableInheritanceMarginItem(
lineNumber,
FindUsagesHelpers.GetDisplayParts(memberSymbol),
memberSymbol.GetGlyph(),
baseSymbolItems.Concat(derivedTypeItems));
}
private static async ValueTask<SerializableInheritanceMarginItem> CreateInheritanceMemberItemForClassOrStructMemberAsync(
Solution solution,
ISymbol memberSymbol,
int lineNumber,
ImmutableArray<ISymbol> implementedMembers,
ImmutableArray<ISymbol> overridingMembers,
ImmutableArray<ISymbol> overriddenMembers,
CancellationToken cancellationToken)
{
var implementedMemberItems = await implementedMembers
.SelectAsArray(symbol => symbol.OriginalDefinition)
.WhereAsArray(IsNavigableSymbol)
.Distinct()
.SelectAsArrayAsync((symbol, _) => CreateInheritanceItemAsync(
solution,
symbol,
InheritanceRelationship.ImplementedMember,
cancellationToken), cancellationToken).ConfigureAwait(false);
var overridenMemberItems = await overriddenMembers
.SelectAsArray(symbol => symbol.OriginalDefinition)
.WhereAsArray(IsNavigableSymbol)
.Distinct()
.SelectAsArrayAsync((symbol, _) => CreateInheritanceItemAsync(
solution,
symbol,
InheritanceRelationship.OverriddenMember,
cancellationToken), cancellationToken).ConfigureAwait(false);
var overridingMemberItems = await overridingMembers
.SelectAsArray(symbol => symbol.OriginalDefinition)
.WhereAsArray(IsNavigableSymbol)
.Distinct()
.SelectAsArrayAsync((symbol, _) => CreateInheritanceItemAsync(
solution,
symbol,
InheritanceRelationship.OverridingMember,
cancellationToken), cancellationToken).ConfigureAwait(false);
return new SerializableInheritanceMarginItem(
lineNumber,
FindUsagesHelpers.GetDisplayParts(memberSymbol),
memberSymbol.GetGlyph(),
implementedMemberItems.Concat(overridenMemberItems).Concat(overridingMemberItems));
}
private static async ValueTask<SerializableInheritanceTargetItem> CreateInheritanceItemAsync(
Solution solution,
ISymbol targetSymbol,
InheritanceRelationship inheritanceRelationship,
CancellationToken cancellationToken)
{
var symbolInSource = await SymbolFinder.FindSourceDefinitionAsync(targetSymbol, solution, cancellationToken).ConfigureAwait(false);
targetSymbol = symbolInSource ?? targetSymbol;
// Right now the targets are not shown in a classified way.
var definition = await ToSlimDefinitionItemAsync(
targetSymbol,
solution,
cancellationToken: cancellationToken).ConfigureAwait(false);
var displayName = targetSymbol.ToDisplayString(s_displayFormat);
return new SerializableInheritanceTargetItem(
inheritanceRelationship,
// Id is used by FAR service for caching, it is not used in inheritance margin
SerializableDefinitionItem.Dehydrate(id: 0, definition),
targetSymbol.GetGlyph(),
displayName);
}
private static ImmutableArray<ISymbol> GetImplementedSymbolsForTypeMember(
ISymbol memberSymbol,
ImmutableArray<ISymbol> overriddenSymbols)
{
if (memberSymbol is IMethodSymbol or IEventSymbol or IPropertySymbol)
{
using var _ = ArrayBuilder<ISymbol>.GetInstance(out var builder);
// 1. Get the direct implementing symbols in interfaces.
var directImplementingSymbols = memberSymbol.ExplicitOrImplicitInterfaceImplementations();
builder.AddRange(directImplementingSymbols);
// 2. Also add the direct implementing symbols for the overridden symbols.
// For example:
// interface IBar { void Foo(); }
// class Bar : IBar { public override void Foo() { } }
// class Bar2 : Bar { public override void Foo() { } }
// For 'Bar2.Foo()', we need to find 'IBar.Foo()'
foreach (var symbol in overriddenSymbols)
{
builder.AddRange(symbol.ExplicitOrImplicitInterfaceImplementations());
}
return builder.ToImmutableArray();
}
return ImmutableArray<ISymbol>.Empty;
}
/// <summary>
/// For the <param name="memberSymbol"/>, get all the implementing symbols.
/// </summary>
private static async Task<ImmutableArray<ISymbol>> GetImplementingSymbolsForTypeMemberAsync(
Solution solution,
ISymbol memberSymbol,
CancellationToken cancellationToken)
{
if (memberSymbol is IMethodSymbol or IEventSymbol or IPropertySymbol
&& memberSymbol.ContainingSymbol.IsInterfaceType())
{
using var _ = ArrayBuilder<ISymbol>.GetInstance(out var builder);
// 1. Find all direct implementations for this member
var implementationSymbols = await SymbolFinder.FindMemberImplementationsArrayAsync(
memberSymbol,
solution,
cancellationToken: cancellationToken).ConfigureAwait(false);
builder.AddRange(implementationSymbols);
// 2. Continue searching the overriden symbols. For example:
// interface IBar { void Foo(); }
// class Bar : IBar { public virtual void Foo() { } }
// class Bar2 : IBar { public override void Foo() { } }
// For 'IBar.Foo()', we need to find 'Bar2.Foo()'
foreach (var implementationSymbol in implementationSymbols)
{
builder.AddRange(await SymbolFinder.FindOverridesArrayAsync(implementationSymbol, solution, cancellationToken: cancellationToken).ConfigureAwait(false));
}
return builder.ToImmutableArray();
}
return ImmutableArray<ISymbol>.Empty;
}
/// <summary>
/// Get overridden members the <param name="memberSymbol"/>.
/// </summary>
private static ImmutableArray<ISymbol> GetOverriddenSymbols(ISymbol memberSymbol)
{
if (memberSymbol is INamedTypeSymbol)
{
return ImmutableArray<ISymbol>.Empty;
}
else
{
using var _ = ArrayBuilder<ISymbol>.GetInstance(out var builder);
for (var overriddenMember = memberSymbol.GetOverriddenMember();
overriddenMember != null;
overriddenMember = overriddenMember.GetOverriddenMember())
{
builder.Add(overriddenMember.OriginalDefinition);
}
return builder.ToImmutableArray();
}
}
/// <summary>
/// Get the derived interfaces and derived classes for <param name="typeSymbol"/>.
/// </summary>
private static async Task<ImmutableArray<INamedTypeSymbol>> GetDerivedTypesAndImplementationsAsync(
Solution solution,
INamedTypeSymbol typeSymbol,
CancellationToken cancellationToken)
{
if (typeSymbol.IsInterfaceType())
{
var allDerivedInterfaces = await SymbolFinder.FindDerivedInterfacesArrayAsync(
typeSymbol,
solution,
transitive: true,
cancellationToken: cancellationToken).ConfigureAwait(false);
var allImplementations = await SymbolFinder.FindImplementationsArrayAsync(
typeSymbol,
solution,
transitive: true,
cancellationToken: cancellationToken).ConfigureAwait(false);
return allDerivedInterfaces.Concat(allImplementations);
}
else
{
return await SymbolFinder.FindDerivedClassesArrayAsync(
typeSymbol,
solution,
transitive: true,
cancellationToken: cancellationToken).ConfigureAwait(false);
}
}
/// <summary>
/// Create the DefinitionItem based on the numbers of locations for <paramref name="symbol"/>.
/// If there is only one location, create the DefinitionItem contains only the documentSpan or symbolKey to save memory.
/// Because in such case, when clicking InheritanceMarginGlpph, it will directly navigate to the symbol.
/// Otherwise, create the full non-classified DefinitionItem. Because in such case we want to display all the locations to the user
/// by reusing the FAR window.
/// </summary>
private static async Task<DefinitionItem> ToSlimDefinitionItemAsync(ISymbol symbol, Solution solution, CancellationToken cancellationToken)
{
RoslynDebug.Assert(IsNavigableSymbol(symbol));
var locations = symbol.Locations;
if (locations.Length > 1)
{
return await symbol.ToNonClassifiedDefinitionItemAsync(
solution,
includeHiddenLocations: false,
cancellationToken: cancellationToken).ConfigureAwait(false);
}
if (locations.Length == 1)
{
var location = locations[0];
if (location.IsInMetadata)
{
return DefinitionItem.CreateMetadataDefinition(
tags: ImmutableArray<string>.Empty,
displayParts: ImmutableArray<TaggedText>.Empty,
nameDisplayParts: ImmutableArray<TaggedText>.Empty,
solution,
symbol);
}
else if (location.IsInSource && location.IsVisibleSourceLocation())
{
var document = solution.GetDocument(location.SourceTree);
if (document != null)
{
var documentSpan = new DocumentSpan(document, location.SourceSpan);
return DefinitionItem.Create(
tags: ImmutableArray<string>.Empty,
displayParts: ImmutableArray<TaggedText>.Empty,
documentSpan,
nameDisplayParts: ImmutableArray<TaggedText>.Empty);
}
}
}
throw ExceptionUtilities.Unreachable;
}
private static bool IsNavigableSymbol(ISymbol symbol)
{
var locations = symbol.Locations;
if (locations.Length == 1)
{
var location = locations[0];
return location.IsInMetadata || (location.IsInSource && location.IsVisibleSourceLocation());
}
return !locations.IsEmpty;
}
}
}
| 48.83779 | 179 | 0.60895 | [
"Apache-2.0"
] | DominikDitoIvosevic/roslyn | src/Features/Core/Portable/InheritanceMargin/InheritanceMarginServiceHelpers.cs | 27,400 | C# |
using System;
using System.Net;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Newtonsoft.Json;
namespace iSHARE.Api.Configurations
{
public static class ExceptionHandler
{
public static IApplicationBuilder UseExceptionHandler(this IApplicationBuilder app, IWebHostEnvironment hostingEnvironment)
{
app.UseExceptionHandler(options =>
{
options.Run(
async context =>
{
context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
context.Response.ContentType = "application/json";
var errorResponse = new
{
error = "server_error",
error_description = "The server encountered an unexpected condition that prevented it from fulfilling the request."
};
await context.Response.WriteAsync(JsonConvert.SerializeObject(errorResponse));
});
});
var configuration = app.ApplicationServices.GetService<IConfiguration>();
var detailedErrors = configuration.GetValue<string>(iSHARE.Configuration.Environments.Variables.AspNetCoreDetailedErrors);
var enableDeveloperPage = detailedErrors?.Equals("1", StringComparison.OrdinalIgnoreCase) ?? false;
enableDeveloperPage |= detailedErrors?.Equals("true", StringComparison.OrdinalIgnoreCase) ?? false;
enableDeveloperPage |= hostingEnvironment.IsDevelopment();
if (enableDeveloperPage)
{
app.UseDeveloperExceptionPage();
}
return app;
}
}
}
| 39.02 | 143 | 0.624295 | [
"Unlicense"
] | iSHARE-Scheme/Authorization-Registry | iSHARE.Api/Configurations/ExceptionHandler.cs | 1,953 | 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: Templates\CSharp\Model\EntityType.cs.tt
namespace Microsoft.Graph
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization;
using Newtonsoft.Json;
/// <summary>
/// The type List Item Version.
/// </summary>
[JsonObject(MemberSerialization = MemberSerialization.OptIn)]
public partial class ListItemVersion : BaseItemVersion
{
///<summary>
/// The ListItemVersion constructor
///</summary>
public ListItemVersion()
{
this.ODataType = "microsoft.graph.listItemVersion";
}
/// <summary>
/// Gets or sets fields.
/// A collection of the fields and values for this version of the list item.
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "fields", Required = Newtonsoft.Json.Required.Default)]
public FieldValueSet Fields { get; set; }
}
}
| 33.046512 | 153 | 0.589022 | [
"MIT"
] | OfficeGlobal/msgraph-beta-sdk-dotnet | src/Microsoft.Graph/Models/Generated/ListItemVersion.cs | 1,421 | C# |
using System;
using System.Collections.Generic;
using System.Text;
namespace service
{
public interface IDemoService
{
}
}
| 12.454545 | 33 | 0.715328 | [
"Apache-2.0"
] | jacksong107/mynetcore | src/01/WebApplication1/service/IService.cs | 139 | C# |
using System.Collections.Generic;
using System.Text.RegularExpressions;
namespace LeapYear.Objects
{
public class LeetSpeakTranslator
{
public string Translate(string plainEnglish)
{
// eventually your code will go here
char[] plainEnglishLetters = plainEnglish.ToCharArray();
List<string> leetArray = new List<string> {};
bool IsFirstLetter = true;
foreach (char letter in plainEnglishLetters)
{
if(letter.ToString().ToLower() == "e")
{
leetArray.Add("3");
}
else if (letter.ToString().ToLower() == "o")
{
leetArray.Add("0");
}
else if (letter.ToString() == "I")
{
leetArray.Add("1");
}
else if (letter.ToString().ToLower() == "s" && !IsFirstLetter)
{
leetArray.Add("z");
}
else
{
leetArray.Add(letter.ToString());
}
if(letter.ToString() == " ")
{
IsFirstLetter=true;
}
else if (Regex.IsMatch(letter.ToString().ToLower(),@"[a-z]"))
{
IsFirstLetter=false;
}
}
string leetString = string.Join("", leetArray);
return leetString;
}
}
}
| 24.9 | 70 | 0.529317 | [
"MIT"
] | CharlesEwel/leapyearcsharp | Objects/LeetSpeakTranslator.cs | 1,245 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
namespace System.Runtime.Serialization
{
using System;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Xml;
using System.Runtime.CompilerServices;
using System.Text;
using System.Security;
using DataContractDictionary = System.Collections.Generic.Dictionary<System.Xml.XmlQualifiedName, DataContract>;
using System.Diagnostics.CodeAnalysis;
public abstract class XmlObjectSerializer
{
[RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)]
public abstract void WriteStartObject(XmlDictionaryWriter writer, object? graph);
[RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)]
public abstract void WriteObjectContent(XmlDictionaryWriter writer, object? graph);
[RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)]
public abstract void WriteEndObject(XmlDictionaryWriter writer);
[RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)]
public virtual void WriteObject(Stream stream!!, object? graph)
{
XmlDictionaryWriter writer = XmlDictionaryWriter.CreateTextWriter(stream, Encoding.UTF8, false /*ownsStream*/);
WriteObject(writer, graph);
writer.Flush();
}
[RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)]
public virtual void WriteObject(XmlWriter writer!!, object? graph)
{
WriteObject(XmlDictionaryWriter.CreateDictionaryWriter(writer), graph);
}
[RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)]
public virtual void WriteStartObject(XmlWriter writer!!, object? graph)
{
WriteStartObject(XmlDictionaryWriter.CreateDictionaryWriter(writer), graph);
}
[RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)]
public virtual void WriteObjectContent(XmlWriter writer!!, object? graph)
{
WriteObjectContent(XmlDictionaryWriter.CreateDictionaryWriter(writer), graph);
}
[RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)]
public virtual void WriteEndObject(XmlWriter writer!!)
{
WriteEndObject(XmlDictionaryWriter.CreateDictionaryWriter(writer));
}
[RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)]
public virtual void WriteObject(XmlDictionaryWriter writer, object? graph)
{
WriteObjectHandleExceptions(new XmlWriterDelegator(writer), graph);
}
[RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)]
internal void WriteObjectHandleExceptions(XmlWriterDelegator writer, object? graph)
{
WriteObjectHandleExceptions(writer, graph, null);
}
[RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)]
internal void WriteObjectHandleExceptions(XmlWriterDelegator writer!!, object? graph, DataContractResolver? dataContractResolver)
{
try
{
InternalWriteObject(writer, graph, dataContractResolver);
}
catch (XmlException ex)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(GetTypeInfoError(SR.ErrorSerializing, GetSerializeType(graph), ex), ex));
}
catch (FormatException ex)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(GetTypeInfoError(SR.ErrorSerializing, GetSerializeType(graph), ex), ex));
}
}
internal virtual DataContractDictionary? KnownDataContracts
{
[RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)]
get
{
return null;
}
}
[RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)]
internal virtual void InternalWriteObject(XmlWriterDelegator writer, object? graph)
{
WriteStartObject(writer.Writer, graph);
WriteObjectContent(writer.Writer, graph);
WriteEndObject(writer.Writer);
}
[RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)]
internal virtual void InternalWriteObject(XmlWriterDelegator writer, object? graph, DataContractResolver? dataContractResolver)
{
InternalWriteObject(writer, graph);
}
[RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)]
internal virtual void InternalWriteStartObject(XmlWriterDelegator writer, object? graph)
{
DiagnosticUtility.DebugAssert("XmlObjectSerializer.InternalWriteStartObject should never get called");
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException());
}
[RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)]
internal virtual void InternalWriteObjectContent(XmlWriterDelegator writer, object? graph)
{
DiagnosticUtility.DebugAssert("XmlObjectSerializer.InternalWriteObjectContent should never get called");
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException());
}
[RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)]
internal virtual void InternalWriteEndObject(XmlWriterDelegator writer)
{
DiagnosticUtility.DebugAssert("XmlObjectSerializer.InternalWriteEndObject should never get called");
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException());
}
[RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)]
internal void WriteStartObjectHandleExceptions(XmlWriterDelegator writer!!, object? graph)
{
try
{
InternalWriteStartObject(writer, graph);
}
catch (XmlException ex)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(GetTypeInfoError(SR.ErrorWriteStartObject, GetSerializeType(graph), ex), ex));
}
catch (FormatException ex)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(GetTypeInfoError(SR.ErrorWriteStartObject, GetSerializeType(graph), ex), ex));
}
}
[RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)]
internal void WriteObjectContentHandleExceptions(XmlWriterDelegator writer!!, object? graph)
{
try
{
if (writer.WriteState != WriteState.Element)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.XmlWriterMustBeInElement, writer.WriteState)));
InternalWriteObjectContent(writer, graph);
}
catch (XmlException ex)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(GetTypeInfoError(SR.ErrorSerializing, GetSerializeType(graph), ex), ex));
}
catch (FormatException ex)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(GetTypeInfoError(SR.ErrorSerializing, GetSerializeType(graph), ex), ex));
}
}
[RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)]
internal void WriteEndObjectHandleExceptions(XmlWriterDelegator writer!!)
{
try
{
InternalWriteEndObject(writer);
}
catch (XmlException ex)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(GetTypeInfoError(SR.ErrorWriteEndObject, null, ex), ex));
}
catch (FormatException ex)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(GetTypeInfoError(SR.ErrorWriteEndObject, null, ex), ex));
}
}
internal void WriteRootElement(XmlWriterDelegator writer, DataContract contract, XmlDictionaryString? name, XmlDictionaryString? ns, bool needsContractNsAtRoot)
{
if (name == null) // root name not set explicitly
{
if (!contract.HasRoot)
return;
contract.WriteRootElement(writer, contract.TopLevelElementName!, contract.TopLevelElementNamespace);
}
else
{
contract.WriteRootElement(writer, name, ns);
if (needsContractNsAtRoot)
{
writer.WriteNamespaceDecl(contract.Namespace);
}
}
}
internal bool CheckIfNeedsContractNsAtRoot(XmlDictionaryString? name, XmlDictionaryString? ns, DataContract contract)
{
if (name == null)
return false;
if (contract.IsBuiltInDataContract || !contract.CanContainReferences)
{
return false;
}
string? contractNs = XmlDictionaryString.GetString(contract.Namespace);
if (string.IsNullOrEmpty(contractNs) || contractNs == XmlDictionaryString.GetString(ns))
return false;
return true;
}
internal static void WriteNull(XmlWriterDelegator writer)
{
writer.WriteAttributeBool(Globals.XsiPrefix, DictionaryGlobals.XsiNilLocalName, DictionaryGlobals.SchemaInstanceNamespace, true);
}
internal static bool IsContractDeclared(DataContract contract, DataContract declaredContract)
{
return (object.ReferenceEquals(contract.Name, declaredContract.Name) && object.ReferenceEquals(contract.Namespace, declaredContract.Namespace))
|| (contract.Name.Value == declaredContract.Name.Value && contract.Namespace.Value == declaredContract.Namespace.Value);
}
[RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)]
public virtual object? ReadObject(Stream stream!!)
{
return ReadObject(XmlDictionaryReader.CreateTextReader(stream, XmlDictionaryReaderQuotas.Max));
}
[RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)]
public virtual object? ReadObject(XmlReader reader!!)
{
return ReadObject(XmlDictionaryReader.CreateDictionaryReader(reader));
}
[RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)]
public virtual object? ReadObject(XmlDictionaryReader reader)
{
return ReadObjectHandleExceptions(new XmlReaderDelegator(reader), true /*verifyObjectName*/);
}
[RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)]
public virtual object? ReadObject(XmlReader reader!!, bool verifyObjectName)
{
return ReadObject(XmlDictionaryReader.CreateDictionaryReader(reader), verifyObjectName);
}
[RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)]
public abstract object? ReadObject(XmlDictionaryReader reader, bool verifyObjectName);
[RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)]
public virtual bool IsStartObject(XmlReader reader!!)
{
return IsStartObject(XmlDictionaryReader.CreateDictionaryReader(reader));
}
[RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)]
public abstract bool IsStartObject(XmlDictionaryReader reader);
[RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)]
internal virtual object? InternalReadObject(XmlReaderDelegator reader, bool verifyObjectName)
{
return ReadObject(reader.UnderlyingReader, verifyObjectName);
}
[RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)]
internal virtual object? InternalReadObject(XmlReaderDelegator reader, bool verifyObjectName, DataContractResolver? dataContractResolver)
{
return InternalReadObject(reader, verifyObjectName);
}
[RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)]
internal virtual bool InternalIsStartObject(XmlReaderDelegator reader)
{
DiagnosticUtility.DebugAssert("XmlObjectSerializer.InternalIsStartObject should never get called");
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException());
}
[RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)]
internal object? ReadObjectHandleExceptions(XmlReaderDelegator reader, bool verifyObjectName)
{
return ReadObjectHandleExceptions(reader, verifyObjectName, null);
}
[RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)]
internal object? ReadObjectHandleExceptions(XmlReaderDelegator reader!!, bool verifyObjectName, DataContractResolver? dataContractResolver)
{
try
{
return InternalReadObject(reader, verifyObjectName, dataContractResolver);
}
catch (XmlException ex)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(GetTypeInfoError(SR.ErrorDeserializing, GetDeserializeType(), ex), ex));
}
catch (FormatException ex)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(GetTypeInfoError(SR.ErrorDeserializing, GetDeserializeType(), ex), ex));
}
}
[RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)]
internal bool IsStartObjectHandleExceptions(XmlReaderDelegator reader!!)
{
try
{
return InternalIsStartObject(reader);
}
catch (XmlException ex)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(GetTypeInfoError(SR.ErrorIsStartObject, GetDeserializeType(), ex), ex));
}
catch (FormatException ex)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(GetTypeInfoError(SR.ErrorIsStartObject, GetDeserializeType(), ex), ex));
}
}
internal bool IsRootXmlAny(XmlDictionaryString? rootName, DataContract contract)
{
return (rootName == null) && !contract.HasRoot;
}
internal bool IsStartElement(XmlReaderDelegator reader)
{
return (reader.MoveToElement() || reader.IsStartElement());
}
[RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)]
internal bool IsRootElement(XmlReaderDelegator reader, DataContract contract, XmlDictionaryString? name, XmlDictionaryString? ns)
{
reader.MoveToElement();
if (name != null) // root name set explicitly
{
return reader.IsStartElement(name, ns ?? XmlDictionaryString.Empty);
}
else
{
if (!contract.HasRoot)
return reader.IsStartElement();
if (reader.IsStartElement(contract.TopLevelElementName!, contract.TopLevelElementNamespace!))
return true;
ClassDataContract? classContract = contract as ClassDataContract;
if (classContract != null)
classContract = classContract.BaseContract;
while (classContract != null)
{
if (reader.IsStartElement(classContract.TopLevelElementName!, classContract.TopLevelElementNamespace!))
return true;
classContract = classContract.BaseContract;
}
if (classContract == null)
{
DataContract objectContract = PrimitiveDataContract.GetPrimitiveDataContract(Globals.TypeOfObject)!;
if (reader.IsStartElement(objectContract.TopLevelElementName!, objectContract.TopLevelElementNamespace!))
return true;
}
return false;
}
}
internal static string TryAddLineInfo(XmlReaderDelegator reader, string errorMessage)
{
if (reader.HasLineInfo())
return string.Create(CultureInfo.InvariantCulture, $"{SR.Format(SR.ErrorInLine, reader.LineNumber, reader.LinePosition)} {errorMessage}");
return errorMessage;
}
internal static Exception CreateSerializationExceptionWithReaderDetails(string errorMessage, XmlReaderDelegator reader)
{
return XmlObjectSerializer.CreateSerializationException(TryAddLineInfo(reader, SR.Format(SR.EncounteredWithNameNamespace, errorMessage, reader.NodeType, reader.LocalName, reader.NamespaceURI)));
}
internal static SerializationException CreateSerializationException(string errorMessage)
{
return XmlObjectSerializer.CreateSerializationException(errorMessage, null);
}
[MethodImpl(MethodImplOptions.NoInlining)]
internal static SerializationException CreateSerializationException(string errorMessage, Exception? innerException)
{
return new SerializationException(errorMessage, innerException);
}
internal static string GetTypeInfoError(string errorMessage, Type? type, Exception innerException)
{
string typeInfo = (type == null) ? string.Empty : SR.Format(SR.ErrorTypeInfo, DataContract.GetClrTypeFullName(type));
string innerExceptionMessage = (innerException == null) ? string.Empty : innerException.Message;
return SR.Format(errorMessage, typeInfo, innerExceptionMessage);
}
internal virtual Type? GetSerializeType(object? graph)
{
return (graph == null) ? null : graph.GetType();
}
internal virtual Type? GetDeserializeType()
{
return null;
}
private static IFormatterConverter? s_formatterConverter;
internal static IFormatterConverter FormatterConverter
{
get
{
if (s_formatterConverter == null)
{
s_formatterConverter = new FormatterConverter();
}
return s_formatterConverter;
}
}
}
}
| 45.687204 | 206 | 0.674637 | [
"MIT"
] | AUTOMATE-2001/runtime | src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlObjectSerializer.cs | 19,280 | C# |
#pragma warning disable CS1591
using System;
using System.Runtime.InteropServices;
using System.Collections.Generic;
using System.Linq;
using System.ComponentModel;
namespace Efl {
/// <summary>Efl boolean model class</summary>
[BooleanModelNativeInherit]
public class BooleanModel : Efl.CompositeModel, Efl.Eo.IWrapper
{
///<summary>Pointer to the native class description.</summary>
public override System.IntPtr NativeClass {
get {
if (((object)this).GetType() == typeof (BooleanModel))
return Efl.BooleanModelNativeInherit.GetEflClassStatic();
else
return Efl.Eo.ClassRegister.klassFromType[((object)this).GetType()];
}
}
[System.Runtime.InteropServices.DllImport(efl.Libs.Ecore)] internal static extern System.IntPtr
efl_boolean_model_class_get();
///<summary>Creates a new instance.</summary>
///<param name="parent">Parent instance.</param>
///<param name="model">Model that is/will be See <see cref="Efl.Ui.IView.SetModel"/></param>
///<param name="index">Position of this object in the parent model. See <see cref="Efl.CompositeModel.SetIndex"/></param>
public BooleanModel(Efl.Object parent
, Efl.IModel model, uint? index = null) :
base(efl_boolean_model_class_get(), typeof(BooleanModel), parent)
{
if (Efl.Eo.Globals.ParamHelperCheck(model))
SetModel(Efl.Eo.Globals.GetParamHelper(model));
if (Efl.Eo.Globals.ParamHelperCheck(index))
SetIndex(Efl.Eo.Globals.GetParamHelper(index));
FinishInstantiation();
}
///<summary>Internal usage: Constructs an instance from a native pointer. This is used when interacting with C code and should not be used directly.</summary>
protected BooleanModel(System.IntPtr raw) : base(raw)
{
RegisterEventProxies();
}
///<summary>Internal usage: Constructor to forward the wrapper initialization to the root class that interfaces with native code. Should not be used directly.</summary>
protected BooleanModel(IntPtr base_klass, System.Type managed_type, Efl.Object parent) : base(base_klass, managed_type, parent) {}
///<summary>Verifies if the given object is equal to this one.</summary>
public override bool Equals(object obj)
{
var other = obj as Efl.Object;
if (other == null)
return false;
return this.NativeHandle == other.NativeHandle;
}
///<summary>Gets the hash code for this object based on the native pointer it points to.</summary>
public override int GetHashCode()
{
return this.NativeHandle.ToInt32();
}
///<summary>Turns the native pointer into a string representation.</summary>
public override String ToString()
{
return $"{this.GetType().Name}@[{this.NativeHandle.ToInt32():x}]";
}
///<summary>Register the Eo event wrappers making the bridge to C# events. Internal usage only.</summary>
protected override void RegisterEventProxies()
{
base.RegisterEventProxies();
}
/// <summary>Add a new named boolean property with a defined default value.</summary>
/// <param name="name"></param>
/// <param name="default_value"></param>
/// <returns></returns>
virtual public void AddBoolean( System.String name, bool default_value) {
Efl.BooleanModelNativeInherit.efl_boolean_model_boolean_add_ptr.Value.Delegate((inherited ? Efl.Eo.Globals.efl_super(this.NativeHandle, this.NativeClass) : this.NativeHandle), name, default_value);
Eina.Error.RaiseIfUnhandledException();
}
/// <summary>Delete an existing named boolean property</summary>
/// <param name="name"></param>
/// <returns></returns>
virtual public void DelBoolean( System.String name) {
Efl.BooleanModelNativeInherit.efl_boolean_model_boolean_del_ptr.Value.Delegate((inherited ? Efl.Eo.Globals.efl_super(this.NativeHandle, this.NativeClass) : this.NativeHandle), name);
Eina.Error.RaiseIfUnhandledException();
}
private static IntPtr GetEflClassStatic()
{
return Efl.BooleanModel.efl_boolean_model_class_get();
}
}
public class BooleanModelNativeInherit : Efl.CompositeModelNativeInherit{
public new static Efl.Eo.NativeModule _Module = new Efl.Eo.NativeModule(efl.Libs.Ecore);
public override System.Collections.Generic.List<Efl_Op_Description> GetEoOps(System.Type type)
{
var descs = new System.Collections.Generic.List<Efl_Op_Description>();
var methods = Efl.Eo.Globals.GetUserMethods(type);
if (efl_boolean_model_boolean_add_static_delegate == null)
efl_boolean_model_boolean_add_static_delegate = new efl_boolean_model_boolean_add_delegate(boolean_add);
if (methods.FirstOrDefault(m => m.Name == "AddBoolean") != null)
descs.Add(new Efl_Op_Description() {api_func = Efl.Eo.FunctionInterop.LoadFunctionPointer(_Module.Module, "efl_boolean_model_boolean_add"), func = Marshal.GetFunctionPointerForDelegate(efl_boolean_model_boolean_add_static_delegate)});
if (efl_boolean_model_boolean_del_static_delegate == null)
efl_boolean_model_boolean_del_static_delegate = new efl_boolean_model_boolean_del_delegate(boolean_del);
if (methods.FirstOrDefault(m => m.Name == "DelBoolean") != null)
descs.Add(new Efl_Op_Description() {api_func = Efl.Eo.FunctionInterop.LoadFunctionPointer(_Module.Module, "efl_boolean_model_boolean_del"), func = Marshal.GetFunctionPointerForDelegate(efl_boolean_model_boolean_del_static_delegate)});
descs.AddRange(base.GetEoOps(type));
return descs;
}
public override IntPtr GetEflClass()
{
return Efl.BooleanModel.efl_boolean_model_class_get();
}
public static new IntPtr GetEflClassStatic()
{
return Efl.BooleanModel.efl_boolean_model_class_get();
}
private delegate void efl_boolean_model_boolean_add_delegate(System.IntPtr obj, System.IntPtr pd, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalTypeRef=typeof(Efl.Eo.StringKeepOwnershipMarshaler))] System.String name, [MarshalAs(UnmanagedType.U1)] bool default_value);
public delegate void efl_boolean_model_boolean_add_api_delegate(System.IntPtr obj, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalTypeRef=typeof(Efl.Eo.StringKeepOwnershipMarshaler))] System.String name, [MarshalAs(UnmanagedType.U1)] bool default_value);
public static Efl.Eo.FunctionWrapper<efl_boolean_model_boolean_add_api_delegate> efl_boolean_model_boolean_add_ptr = new Efl.Eo.FunctionWrapper<efl_boolean_model_boolean_add_api_delegate>(_Module, "efl_boolean_model_boolean_add");
private static void boolean_add(System.IntPtr obj, System.IntPtr pd, System.String name, bool default_value)
{
Eina.Log.Debug("function efl_boolean_model_boolean_add was called");
Efl.Eo.IWrapper wrapper = Efl.Eo.Globals.PrivateDataGet(pd);
if(wrapper != null) {
try {
((BooleanModel)wrapper).AddBoolean( name, default_value);
} catch (Exception e) {
Eina.Log.Warning($"Callback error: {e.ToString()}");
Eina.Error.Set(Eina.Error.UNHANDLED_EXCEPTION);
}
} else {
efl_boolean_model_boolean_add_ptr.Value.Delegate(Efl.Eo.Globals.efl_super(obj, Efl.Eo.Globals.efl_class_get(obj)), name, default_value);
}
}
private static efl_boolean_model_boolean_add_delegate efl_boolean_model_boolean_add_static_delegate;
private delegate void efl_boolean_model_boolean_del_delegate(System.IntPtr obj, System.IntPtr pd, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalTypeRef=typeof(Efl.Eo.StringKeepOwnershipMarshaler))] System.String name);
public delegate void efl_boolean_model_boolean_del_api_delegate(System.IntPtr obj, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalTypeRef=typeof(Efl.Eo.StringKeepOwnershipMarshaler))] System.String name);
public static Efl.Eo.FunctionWrapper<efl_boolean_model_boolean_del_api_delegate> efl_boolean_model_boolean_del_ptr = new Efl.Eo.FunctionWrapper<efl_boolean_model_boolean_del_api_delegate>(_Module, "efl_boolean_model_boolean_del");
private static void boolean_del(System.IntPtr obj, System.IntPtr pd, System.String name)
{
Eina.Log.Debug("function efl_boolean_model_boolean_del was called");
Efl.Eo.IWrapper wrapper = Efl.Eo.Globals.PrivateDataGet(pd);
if(wrapper != null) {
try {
((BooleanModel)wrapper).DelBoolean( name);
} catch (Exception e) {
Eina.Log.Warning($"Callback error: {e.ToString()}");
Eina.Error.Set(Eina.Error.UNHANDLED_EXCEPTION);
}
} else {
efl_boolean_model_boolean_del_ptr.Value.Delegate(Efl.Eo.Globals.efl_super(obj, Efl.Eo.Globals.efl_class_get(obj)), name);
}
}
private static efl_boolean_model_boolean_del_delegate efl_boolean_model_boolean_del_static_delegate;
}
}
| 57.932099 | 280 | 0.696963 | [
"Apache-2.0"
] | wantfire/TizenFX | internals/src/EflSharp/EflSharp/efl/efl_boolean_model.eo.cs | 9,385 | C# |
using System;
using System.Threading.Tasks;
using AVFoundation;
using CoreVideo;
using CoreFoundation;
using Foundation;
using CoreMedia;
namespace PhotoFilterExtension
{
public abstract class ReadWriteSampleBufferChannel
{
readonly AVAssetReaderOutput readerOutput;
protected AVAssetReaderOutput ReaderOutput {
get {
return readerOutput;
}
}
readonly AVAssetWriterInput writerInput;
protected AVAssetWriterInput WriterInput {
get {
return writerInput;
}
}
readonly DispatchQueue serializationQueue;
bool finished;
TaskCompletionSource<object> completionSource;
bool IsStarted {
get {
return completionSource != null;
}
}
public ReadWriteSampleBufferChannel (AVAssetReaderOutput readerOutput, AVAssetWriterInput writerInput)
{
if (readerOutput == null)
throw new ArgumentNullException ("readerOutput");
if (writerInput == null)
throw new ArgumentNullException ("writerInput");
this.readerOutput = readerOutput;
this.writerInput = writerInput;
serializationQueue = new DispatchQueue ("ReadWriteSampleBufferChannel queue");
}
public Task StartAsync ()
{
if (IsStarted)
throw new InvalidProgramException ();
completionSource = new TaskCompletionSource<object> ();
AdjustMediaData ();
return completionSource.Task;
}
void AdjustMediaData ()
{
writerInput.RequestMediaData (serializationQueue, () => {
if(finished)
return;
bool shouldContinue = true;
// Read samples in a loop as long as the asset writer input is ready
while (writerInput.ReadyForMoreMediaData && shouldContinue) {
using (CMSampleBuffer sampleBuffer = readerOutput.CopyNextSampleBuffer ()) {
// TODO: https://trello.com/c/4YM7lofd
bool isBufferValid = sampleBuffer != null && sampleBuffer.IsValid;
shouldContinue = isBufferValid ? Append (sampleBuffer) : false;
}
}
if(!shouldContinue)
CompleteTask ();
});
}
protected abstract bool Append(CMSampleBuffer sampleBuffer);
public void Cancel ()
{
if (IsStarted)
CompleteTask ();
}
void CompleteTask ()
{
if (!finished) {
writerInput.MarkAsFinished (); // let the asset writer know that we will not be appending any more samples to this input
completionSource.SetResult (null);
}
finished = true;
}
}
}
| 22.815534 | 125 | 0.714468 | [
"MIT"
] | Art-Lav/ios-samples | ios8/PhotoFilter/PhotoFilterExtension/ReadWriteChannel/ReadWriteSampleBufferChannel.cs | 2,352 | C# |
using System;
using System.ComponentModel;
namespace EzPasswordValidator.Checks
{
/// <summary>
/// Factory class for generating instances of <see cref="Check"/> classes.
/// </summary>
public static class CheckFactory
{
/// <summary>
/// Creates the a check for the specified check type.
/// </summary>
/// <param name="checkType">Type of check to generate.</param>
/// <param name="minLength">The minimum required length of the password.</param>
/// <param name="maxLength">The maximum allowed length of the password.</param>
/// <param name="letterSequenceLength">The sequence length at which the <see cref="LetterSequenceCheck"/> fails.</param>
/// <param name="letterRepetitionLength">The amount of letter repetitions that result in a failed <see cref="LetterRepetitionCheck"/> check.</param>
/// <param name="symbolRepetitionLength">The amount of symbol repetitions that result in a failed <see cref="SymbolRepetitionCheck"/> check.</param>
/// <param name="digitRepetitionLength">The amount of digit repetitions that result in a failed <see cref="DigitRepetitionCheck"/> check.</param>
/// <param name="numberSequenceLength">The number sequence length at which the <see cref="NumberSequenceCheck"/> fails.</param>
/// <returns>An instance of a <see cref="Check"/> object representing the given check type.</returns>
/// <exception cref="InvalidEnumArgumentException">The check must only contain a single flag.</exception>
/// <exception cref="ArgumentOutOfRangeException">No check found for the given argument.</exception>
public static Check Create(
CheckTypes checkType,
uint minLength,
uint maxLength,
int letterSequenceLength,
int letterRepetitionLength,
int symbolRepetitionLength,
int digitRepetitionLength,
int numberSequenceLength)
{
if (!checkType.IsSingleFlag())
{
throw new InvalidEnumArgumentException("The check must only contain a single flag.");
}
switch (checkType)
{
case CheckTypes.Length:
return new LengthCheck(minLength, maxLength);
case CheckTypes.Numbers:
return new NumberCheck();
case CheckTypes.Letters:
return new LetterCheck();
case CheckTypes.Symbols:
return new SymbolCheck();
case CheckTypes.CaseUpperLower:
return new CaseCheck();
case CheckTypes.NumberSequence:
return new NumberSequenceCheck(numberSequenceLength);
case CheckTypes.DigitRepetition:
return new DigitRepetitionCheck(digitRepetitionLength);
case CheckTypes.NumberMixed:
return new NumberPositionCheck();
case CheckTypes.LetterSequence:
return new LetterSequenceCheck(letterSequenceLength);
case CheckTypes.LetterRepetition:
return new LetterRepetitionCheck(letterRepetitionLength);
case CheckTypes.SymbolRepetition:
return new SymbolRepetitionCheck(symbolRepetitionLength);
default:
throw new ArgumentOutOfRangeException(nameof(checkType), checkType, "No check found for the given argument.");
}
}
}
} | 51.385714 | 156 | 0.618849 | [
"MIT"
] | havardt/EzPasswordValidator | source/EzPasswordValidator/Checks/CheckFactory.cs | 3,599 | C# |
namespace LaunchDarkly.Sdk.Server.Interfaces
{
/// <summary>
/// Optional interface for components to describe their own configuration.
/// </summary>
/// <remarks>
/// <para>
/// The SDK uses a simplified JSON representation of its configuration when recording diagnostics data.
/// Any class that implements <see cref="IDataStoreFactory"/>, <see cref="IDataSourceFactory"/>,
/// <see cref="IEventProcessorFactory"/>, or <see cref="IPersistentDataStoreFactory"/> may choose to
/// contribute values to this representation, although the SDK may or may not use them.
/// </para>
/// <para>
/// The <see cref="DescribeConfiguration"/> method should return either <see cref="LdValue.Null"/>or a
/// JSON value. For custom components, the value must be a string that describes the basic nature of
/// this component implementation (e.g. "Redis"). Built-in LaunchDarkly components may instead return a
/// JSON object containing multiple properties specific to the LaunchDarkly diagnostic schema.
/// </para>
/// </remarks>
public interface IDiagnosticDescription
{
/// <summary>
/// Called internally by the SDK to inspect the configuration. Applications do not need to call
/// this method.
/// </summary>
/// <param name="basic">the basic global configuration of the SDK</param>
/// <returns>a JSON value</returns>
LdValue DescribeConfiguration(BasicConfiguration basic);
}
}
| 47.25 | 107 | 0.677249 | [
"Apache-2.0"
] | launchdarkly/dotnet-client | src/LaunchDarkly.ServerSdk/Interfaces/IDiagnosticDescription.cs | 1,514 | C# |
namespace PhotoShare.Client.Core.Commands
{
using System;
using Attributes;
using Data;
using Models;
using System;
using System.Data.Entity;
public class ShareAlbumCommand : Command
{
[Inject]
private PhotoShareContext context;
[Inject]
private DbSet<User> users;
[Inject]
private DbSet<Album> albums;
[Inject]
private DbSet<Picture> pictures;
[Inject]
private DbSet<Tag> tags;
[Inject]
private DbSet<AlbumRole> albumRoles;
[Inject]
private DbSet<Town> towns;
public ShareAlbumCommand(string[] data) : base(data)
{
}
//ShareAlbum <albumId> <username> <permission>
//For example:
//ShareAlbum 4 dragon321 Owner
//ShareAlbum 4 dragon11 Viewer
public override string Execute()
{
throw new NotImplementedException();
}
}
}
| 23.512195 | 60 | 0.579876 | [
"MIT"
] | ivajlotokiew/Databases_Entity_Framework | Best_Practices_And_Architecture/PhotoShare.Client/Core/Commands/ShareAlbumCommand.cs | 966 | C# |
// ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------------------------------------------------------------
namespace Microsoft.WindowsAzure.Commands.Test.Websites
{
using System.Collections.Generic;
using System.IO;
using System.Text;
using Commands.Utilities.Common;
using Commands.Utilities.Websites;
using Moq;
using Utilities.Common;
using Utilities.Websites;
using Commands.Utilities.Websites.Services.WebEntities;
using Commands.Websites;
using VisualStudio.TestTools.UnitTesting;
[TestClass]
public class SaveAzureWebsiteLogTests : WebsitesTestBase
{
private Site site1 = new Site
{
Name = "website1",
WebSpace = "webspace1",
SiteProperties = new SiteProperties
{
Properties = new List<NameValuePair>
{
new NameValuePair {Name = "repositoryuri", Value = "http"},
new NameValuePair {Name = "PublishingUsername", Value = "user1"},
new NameValuePair {Name = "PublishingPassword", Value = "password1"}
}
}
};
private string slot = "staging";
private List<WebSpace> spaces = new List<WebSpace>
{
new WebSpace {Name = "webspace1"},
new WebSpace {Name = "webspace2"}
};
private Mock<IWebsitesClient> clientMock;
[TestInitialize]
public void Setup()
{
clientMock = new Mock<IWebsitesClient>();
clientMock.Setup(c => c.GetWebsite("website1", null))
.Returns(site1);
clientMock.Setup(c => c.GetWebsite("website1", slot))
.Returns(site1);
clientMock.Setup(c => c.ListWebSpaces())
.Returns(spaces);
}
[TestMethod]
public void SaveAzureWebsiteLogTest()
{
// Setup
SimpleDeploymentServiceManagement deploymentChannel = new SimpleDeploymentServiceManagement
{
DownloadLogsThunk = ar => new MemoryStream(Encoding.UTF8.GetBytes("test"))
};
// Test
SaveAzureWebsiteLogCommand getAzureWebsiteLogCommand = new SaveAzureWebsiteLogCommand(deploymentChannel)
{
Name = "website1",
ShareChannel = true,
WebsitesClient = clientMock.Object,
CommandRuntime = new MockCommandRuntime(),
CurrentSubscription = new WindowsAzureSubscription { SubscriptionId = base.subscriptionId }
};
getAzureWebsiteLogCommand.DefaultCurrentPath = "";
getAzureWebsiteLogCommand.ExecuteCmdlet();
Assert.AreEqual("test", File.ReadAllText(SaveAzureWebsiteLogCommand.DefaultOutput));
}
[TestMethod]
public void SaveAzureWebsiteLogWithNoFileExtensionTest()
{
// Setup
string expectedOutput = "file_without_ext.zip";
SimpleDeploymentServiceManagement deploymentChannel = new SimpleDeploymentServiceManagement
{
DownloadLogsThunk = ar => new MemoryStream(Encoding.UTF8.GetBytes("test with no extension"))
};
// Test
SaveAzureWebsiteLogCommand getAzureWebsiteLogCommand = new SaveAzureWebsiteLogCommand(deploymentChannel)
{
Name = "website1",
ShareChannel = true,
WebsitesClient = clientMock.Object,
CommandRuntime = new MockCommandRuntime(),
CurrentSubscription = new WindowsAzureSubscription { SubscriptionId = base.subscriptionId },
Output = "file_without_ext"
};
getAzureWebsiteLogCommand.DefaultCurrentPath = "";
getAzureWebsiteLogCommand.ExecuteCmdlet();
Assert.AreEqual("test with no extension", File.ReadAllText(expectedOutput));
}
[TestMethod]
public void SaveAzureWebsiteLogWithSlotTest()
{
// Setup
SimpleDeploymentServiceManagement deploymentChannel = new SimpleDeploymentServiceManagement
{
DownloadLogsThunk = ar => new MemoryStream(Encoding.UTF8.GetBytes("test"))
};
// Test
SaveAzureWebsiteLogCommand getAzureWebsiteLogCommand = new SaveAzureWebsiteLogCommand(deploymentChannel)
{
Name = "website1",
ShareChannel = true,
WebsitesClient = clientMock.Object,
CommandRuntime = new MockCommandRuntime(),
CurrentSubscription = new WindowsAzureSubscription { SubscriptionId = base.subscriptionId },
Slot = slot
};
getAzureWebsiteLogCommand.DefaultCurrentPath = "";
getAzureWebsiteLogCommand.ExecuteCmdlet();
Assert.AreEqual("test", File.ReadAllText(SaveAzureWebsiteLogCommand.DefaultOutput));
}
}
}
| 40.068493 | 117 | 0.579145 | [
"MIT"
] | Milstein/azure-sdk-tools | WindowsAzurePowershell/src/Commands.Test/Websites/SaveAzureWebsiteLogTests.cs | 5,707 | C# |
<<<<<<< HEAD
namespace CharacterCreator.Winform
=======
<<<<<<< HEAD:classwork/MovieLibrary - Original/Itse1430.MovieLib.Host/AboutBox1.Designer.cs
namespace Itse1430.MovieLib.Host
=======
namespace CharacterCreator.Winform
>>>>>>> 68cf341013862ab2bb00b6ceee97f1db28444cf4:labs/Lab 2/CharacterCreator.Winform/OnAboutBox.Designer.cs
>>>>>>> 68cf341013862ab2bb00b6ceee97f1db28444cf4
{
partial class OnAboutBox
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose ( bool disposing )
{
if (disposing && (components != null))
{
components.Dispose ();
}
base.Dispose (disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent ()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(OnAboutBox));
this.tableLayoutPanel = new System.Windows.Forms.TableLayoutPanel();
this.logoPictureBox = new System.Windows.Forms.PictureBox();
this.labelProductName = new System.Windows.Forms.Label();
this.labelVersion = new System.Windows.Forms.Label();
this.labelCopyright = new System.Windows.Forms.Label();
this.labelCompanyName = new System.Windows.Forms.Label();
this.textBoxDescription = new System.Windows.Forms.TextBox();
this.okButton = new System.Windows.Forms.Button();
this.tableLayoutPanel.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.logoPictureBox)).BeginInit();
this.SuspendLayout();
//
// tableLayoutPanel
//
this.tableLayoutPanel.ColumnCount = 2;
this.tableLayoutPanel.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 33F));
this.tableLayoutPanel.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 67F));
this.tableLayoutPanel.Controls.Add(this.logoPictureBox, 0, 0);
this.tableLayoutPanel.Controls.Add(this.labelProductName, 1, 0);
this.tableLayoutPanel.Controls.Add(this.labelVersion, 1, 1);
this.tableLayoutPanel.Controls.Add(this.labelCopyright, 1, 2);
this.tableLayoutPanel.Controls.Add(this.labelCompanyName, 1, 3);
this.tableLayoutPanel.Controls.Add(this.textBoxDescription, 1, 4);
this.tableLayoutPanel.Controls.Add(this.okButton, 1, 5);
this.tableLayoutPanel.Dock = System.Windows.Forms.DockStyle.Fill;
this.tableLayoutPanel.Location = new System.Drawing.Point(9, 9);
this.tableLayoutPanel.Name = "tableLayoutPanel";
this.tableLayoutPanel.RowCount = 6;
this.tableLayoutPanel.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 10F));
this.tableLayoutPanel.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 10F));
this.tableLayoutPanel.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 10F));
this.tableLayoutPanel.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 10F));
this.tableLayoutPanel.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 50F));
this.tableLayoutPanel.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 10F));
this.tableLayoutPanel.Size = new System.Drawing.Size(417, 265);
this.tableLayoutPanel.TabIndex = 0;
//
// logoPictureBox
//
this.logoPictureBox.Dock = System.Windows.Forms.DockStyle.Fill;
this.logoPictureBox.Image = ((System.Drawing.Image)(resources.GetObject("logoPictureBox.Image")));
this.logoPictureBox.Location = new System.Drawing.Point(3, 3);
this.logoPictureBox.Name = "logoPictureBox";
this.tableLayoutPanel.SetRowSpan(this.logoPictureBox, 6);
this.logoPictureBox.Size = new System.Drawing.Size(131, 259);
this.logoPictureBox.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage;
this.logoPictureBox.TabIndex = 12;
this.logoPictureBox.TabStop = false;
//
// labelProductName
//
this.labelProductName.Dock = System.Windows.Forms.DockStyle.Fill;
this.labelProductName.Location = new System.Drawing.Point(143, 0);
this.labelProductName.Margin = new System.Windows.Forms.Padding(6, 0, 3, 0);
this.labelProductName.MaximumSize = new System.Drawing.Size(0, 17);
this.labelProductName.Name = "labelProductName";
this.labelProductName.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.labelProductName.Size = new System.Drawing.Size(271, 17);
this.labelProductName.TabIndex = 19;
this.labelProductName.Text = "Shelby Jones";
this.labelProductName.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
<<<<<<< HEAD
=======
this.labelProductName.Click += new System.EventHandler(this.LabelProductName_Click);
>>>>>>> 68cf341013862ab2bb00b6ceee97f1db28444cf4
//
// labelVersion
//
this.labelVersion.Dock = System.Windows.Forms.DockStyle.Fill;
this.labelVersion.Location = new System.Drawing.Point(143, 26);
this.labelVersion.Margin = new System.Windows.Forms.Padding(6, 0, 3, 0);
this.labelVersion.MaximumSize = new System.Drawing.Size(0, 17);
this.labelVersion.Name = "labelVersion";
this.labelVersion.Size = new System.Drawing.Size(271, 17);
this.labelVersion.TabIndex = 0;
this.labelVersion.Text = "Version";
this.labelVersion.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// labelCopyright
//
this.labelCopyright.Dock = System.Windows.Forms.DockStyle.Fill;
this.labelCopyright.Location = new System.Drawing.Point(143, 52);
this.labelCopyright.Margin = new System.Windows.Forms.Padding(6, 0, 3, 0);
this.labelCopyright.MaximumSize = new System.Drawing.Size(0, 17);
this.labelCopyright.Name = "labelCopyright";
this.labelCopyright.Size = new System.Drawing.Size(271, 17);
this.labelCopyright.TabIndex = 21;
this.labelCopyright.Text = "Character Creator";
this.labelCopyright.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// labelCompanyName
//
this.labelCompanyName.Dock = System.Windows.Forms.DockStyle.Fill;
this.labelCompanyName.Location = new System.Drawing.Point(143, 78);
this.labelCompanyName.Margin = new System.Windows.Forms.Padding(6, 0, 3, 0);
this.labelCompanyName.MaximumSize = new System.Drawing.Size(0, 17);
this.labelCompanyName.Name = "labelCompanyName";
this.labelCompanyName.Size = new System.Drawing.Size(271, 17);
this.labelCompanyName.TabIndex = 22;
this.labelCompanyName.Text = "ITSE 1430";
this.labelCompanyName.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// textBoxDescription
//
this.textBoxDescription.Dock = System.Windows.Forms.DockStyle.Fill;
this.textBoxDescription.Location = new System.Drawing.Point(143, 107);
this.textBoxDescription.Margin = new System.Windows.Forms.Padding(6, 3, 3, 3);
this.textBoxDescription.Multiline = true;
this.textBoxDescription.Name = "textBoxDescription";
this.textBoxDescription.ReadOnly = true;
this.textBoxDescription.ScrollBars = System.Windows.Forms.ScrollBars.Both;
this.textBoxDescription.Size = new System.Drawing.Size(271, 126);
this.textBoxDescription.TabIndex = 23;
this.textBoxDescription.TabStop = false;
this.textBoxDescription.Text = "Description";
//
// okButton
//
this.okButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.okButton.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.okButton.Location = new System.Drawing.Point(339, 239);
this.okButton.Name = "okButton";
this.okButton.Size = new System.Drawing.Size(75, 23);
this.okButton.TabIndex = 24;
this.okButton.Text = "&OK";
//
<<<<<<< HEAD
// OnAboutBox
=======
<<<<<<< HEAD:classwork/MovieLibrary - Original/Itse1430.MovieLib.Host/AboutBox1.Designer.cs
// AboutBox1
=======
// OnAboutBox
>>>>>>> 68cf341013862ab2bb00b6ceee97f1db28444cf4:labs/Lab 2/CharacterCreator.Winform/OnAboutBox.Designer.cs
>>>>>>> 68cf341013862ab2bb00b6ceee97f1db28444cf4
//
this.AcceptButton = this.okButton;
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
<<<<<<< HEAD
this.ClientSize = new System.Drawing.Size(435, 283);
=======
<<<<<<< HEAD:classwork/MovieLibrary - Original/Itse1430.MovieLib.Host/AboutBox1.Designer.cs
this.ClientSize = new System.Drawing.Size(580, 348);
=======
this.ClientSize = new System.Drawing.Size(435, 283);
>>>>>>> 68cf341013862ab2bb00b6ceee97f1db28444cf4:labs/Lab 2/CharacterCreator.Winform/OnAboutBox.Designer.cs
>>>>>>> 68cf341013862ab2bb00b6ceee97f1db28444cf4
this.Controls.Add(this.tableLayoutPanel);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Name = "OnAboutBox";
this.Padding = new System.Windows.Forms.Padding(9);
this.ShowIcon = false;
this.ShowInTaskbar = false;
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
this.Text = "OnAboutBox";
this.tableLayoutPanel.ResumeLayout(false);
this.tableLayoutPanel.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.logoPictureBox)).EndInit();
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.TableLayoutPanel tableLayoutPanel;
private System.Windows.Forms.PictureBox logoPictureBox;
private System.Windows.Forms.Label labelProductName;
private System.Windows.Forms.Label labelVersion;
private System.Windows.Forms.Label labelCopyright;
private System.Windows.Forms.Label labelCompanyName;
private System.Windows.Forms.TextBox textBoxDescription;
private System.Windows.Forms.Button okButton;
}
}
| 53.898148 | 159 | 0.651263 | [
"MIT"
] | Shelbyjones42/itse1430 | labs/labs/Lab 2/CharacterCreator.Winform/OnAboutBox.Designer.cs | 11,648 | C# |
#region Copyright
/*Copyright (C) 2015 Wosad 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.
*/
#endregion
using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Wosad.Loads.ASCE.ASCE7_10.DeadLoads;
using Wosad.Loads.ASCE.ASCE7_10.DeadLoads.Components;
namespace Wosad.Loads.Tests.ASCE7.ASCE7_10.C03_DeadLoads
{
[TestFixture]
public partial class AsceComponentDeadWeightTests
{
[Test]
public void RoofMetalDeckReturnsValue1_5In()
{
ComponentRoofDeck rd = new ComponentRoofDeck(0, 0, 0);
var rdEntr = rd.Weight;
Assert.AreEqual(2.0, rdEntr);
}
}
}
| 30.121951 | 75 | 0.720648 | [
"Apache-2.0"
] | Wosad/Wosad.Design | Tests/Wosad.Loads.Tests/ASCE7/ASCE7_10/C03_DeadLoads/RoofMetalDeckTests.cs | 1,237 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ProcessCollision : MonoBehaviour
{
public int points = 0;
private void OnTriggerEnter(Collider collision)
{
Debug.Log("Collision: " + collision.gameObject.tag);
if (collision.gameObject.tag == "Player")
{
GameManager.Instance.score += points;
GameManager.Instance.triggerScoreUpdate();
Destroy(gameObject);
}
}
}
| 24.761905 | 61 | 0.611538 | [
"CC0-1.0"
] | Sunno/ggj-perros-hermanos | Assets/Scripts/ProcessCollision.cs | 520 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using Android.App;
// 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("GraphicsControls.Sample.Android")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("GraphicsControls.Sample.Android")]
[assembly: AssemblyCopyright("Copyright © 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
// Add some common permissions, these can be removed if not needed
[assembly: UsesPermission(Android.Manifest.Permission.Internet)]
[assembly: UsesPermission(Android.Manifest.Permission.WriteExternalStorage)]
| 36.935484 | 77 | 0.770306 | [
"MIT"
] | mbarbierato/GraphicsControls | src/GraphicsControls.Sample.Android/Properties/AssemblyInfo.cs | 1,148 | C# |
using System;
using System.Collections.Generic;
using System.Text;
using SQLite;
using MotorPremiumCalculator.Shared.Repository.Tables;
using System.IO;
namespace MotorPremiumCalculator.Shared.Repository
{
public class TwoWheelerDb : SQLiteConnection
{
static object syncObj = new object();
public TwoWheelerDb(string path) : base(path)
{
//CreateTables();
//InsertData();
}
public TwoWheeler GetTwoWheelerData(string zoneName,string cc, int vechicleAge, bool isPaToDriver, bool isPaToPillionRider )
{
lock (syncObj)
{
var result = CustomSQLExecution();
int zoneId = GetZoneId(zoneName);
int ccId = GetTwoWheelerCcId(cc);
int vechicleAgeId = GetVechicleAge1Id(vechicleAge);
var actTwowheeler = this.Get<TwoWheeler>(act => act.ZoneId == zoneId && act.CCId == ccId && act.VechicleAgeId == vechicleAgeId);
return actTwowheeler;
}
}
private List<TwoWheeler> CustomSQLExecution()
{
List<TwoWheeler> data = this.Query<TwoWheeler>("SELECT * FROM TwoWheeler INNER JOIN Zone ON TwoWheeler.ZoneId= Zone._id WHERE Zone.ZoneName = ?","A");
var cmd = NewCommand();
cmd.CommandText = "SELECT * FROM TwoWheeler INNER JOIN Zone ON TwoWheeler.ZoneId= Zone._id WHERE Zone.ZoneName = ?";
cmd.Bind("A");
List<TwoWheeler> result = cmd.ExecuteQuery<TwoWheeler>();
return result;
}
public int GetZoneId(string zoneName)
{
lock (syncObj)
{
return this.Get<Zone>(name => name.ZoneName.Equals(zoneName)).ID;
}
}
public int GetTwoWheelerCcId(string selectedCc)
{
lock (syncObj)
{
int cc = Convert.ToInt32(selectedCc);
//string cmd = "SELECT * FROM 'TwoWheelerCC' WHERE [CCMin] <= ? AND [CcMax] >= ?";
//SQLiteCommand command = this.CreateCommand(cmd,cc,cc);
//var a = command.ExecuteScalar<TwoWheelerCC>();
return this.Get<TwoWheelerCC>(name => name.CCMin <= cc && name.CcMax >= cc).ID;
}
}
public int GetVechicleAge1Id(int vechicleAge )
{
lock (this)
{
return this.Get<VechicleAge1>(age => age.AgeMin <= vechicleAge && age.AgeMax >= vechicleAge).ID;
}
}
#region Data insertion
private void InsertData()
{
InsertZoneData();
InsertVechicleAge1Data();
InsertVechicleAge2Data();
InsertTwoWheelerCcData();
}
private void InsertTwoWheelerCcData()
{
lock (syncObj)
{
this.Insert(new TwoWheelerCC { CCMin = 0, CcMax = 150 });
this.Insert(new TwoWheelerCC { CCMin = 151, CcMax = 350 });
this.Insert(new TwoWheelerCC { CCMin = 351, CcMax = 1000 });
}
}
private void InsertZoneData()
{
lock (syncObj)
{
this.Insert(new Zone { ZoneName = "A" });
this.Insert(new Zone { ZoneName = "B" });
this.Insert(new Zone { ZoneName = "C" });
}
}
private void InsertVechicleAge1Data()
{
lock (syncObj)
{
this.Insert(new VechicleAge1 { AgeMin = 0, AgeMax = 5});
this.Insert(new VechicleAge1 { AgeMin = 5, AgeMax = 10 });
this.Insert(new VechicleAge1 { AgeMin = 10, AgeMax = 100 });
}
}
private void InsertVechicleAge2Data()
{
lock (syncObj)
{
this.Insert(new VechicleAge2 { AgeMin = 0, AgeMax = 5 });
this.Insert(new VechicleAge2 { AgeMin = 5, AgeMax = 7 });
this.Insert(new VechicleAge2 { AgeMin = 7, AgeMax = 100 });
}
}
#endregion
#region Table Creation
private void CreateTables()
{
CreateTable<Zone>();
CreateTable<VechicleAge1>();
CreateTable<VechicleAge2>();
CreateTable<TwoWheelerCC>();
CreateTable<PrivateCarCC>();
CreateTable<TwoWheeler>();
}
#endregion
}
}
| 34.137405 | 162 | 0.528399 | [
"Apache-2.0"
] | JDSRAO/MPC_V1 | MotorPremiumCalculator.Shared.Repository/TwoWheelerDb.cs | 4,474 | C# |
// *** WARNING: this file was generated by the Pulumi SDK Generator. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.AzureNative.Compute.V20171201.Inputs
{
/// <summary>
/// Specifies information about the image to use. You can specify information about platform images, marketplace images, or virtual machine images. This element is required when you want to use a platform image, marketplace image, or virtual machine image, but is not used in other creation operations. NOTE: Image reference publisher and offer can only be set when you create the scale set.
/// </summary>
public sealed class ImageReferenceArgs : Pulumi.ResourceArgs
{
/// <summary>
/// Resource Id
/// </summary>
[Input("id")]
public Input<string>? Id { get; set; }
/// <summary>
/// Specifies the offer of the platform image or marketplace image used to create the virtual machine.
/// </summary>
[Input("offer")]
public Input<string>? Offer { get; set; }
/// <summary>
/// The image publisher.
/// </summary>
[Input("publisher")]
public Input<string>? Publisher { get; set; }
/// <summary>
/// The image SKU.
/// </summary>
[Input("sku")]
public Input<string>? Sku { get; set; }
/// <summary>
/// Specifies the version of the platform image or marketplace image used to create the virtual machine. The allowed formats are Major.Minor.Build or 'latest'. Major, Minor, and Build are decimal numbers. Specify 'latest' to use the latest version of an image available at deploy time. Even if you use 'latest', the VM image will not automatically update after deploy time even if a new version becomes available.
/// </summary>
[Input("version")]
public Input<string>? Version { get; set; }
public ImageReferenceArgs()
{
}
}
}
| 40.528302 | 421 | 0.647114 | [
"Apache-2.0"
] | polivbr/pulumi-azure-native | sdk/dotnet/Compute/V20171201/Inputs/ImageReferenceArgs.cs | 2,148 | C# |
// Copyright (c) 2017 Trevor Redfern
//
// This software is released under the MIT License.
// https://opensource.org/licenses/MIT
namespace SilverNeedle.Characters.SpecialAbilities
{
public class AuraOfProtection : AbilityDisplayAsName
{
}
} | 22.083333 | 56 | 0.716981 | [
"MIT"
] | shortlegstudio/silverneedle-web | silverneedle/lib/Characters/SpecialAbilities/AuraOfProtection.cs | 265 | C# |
using Common.Contracts;
using Common.Contracts.Repo;
using Common.Models;
using Common.Sessions;
using System.Collections.Generic;
using System.Linq;
namespace Infrastructure.Repo
{
public class TradeRepo: BaseXMLRepo<Trade>, ITradeRepo
{
public TradeRepo(SessionProvider session, ILogger logger) : base(session, logger) { }
}
public class TradeSummaryAuditRepo : BaseXMLRepo<TradeSummaryAudit>, ITradeSummaryAuditRepo
{
public TradeSummaryAuditRepo(SessionProvider session, ILogger logger) : base(session, logger) { }
}
public class TradeSummaryRepo : BaseXMLRepo<TradeSummary>, ITradeSummaryRepo
{
private readonly ITickerRepo tickerRepo;
public TradeSummaryRepo(SessionProvider session, ILogger logger, ITickerRepo tickerRepo) : base(session, logger)
{
this.tickerRepo = tickerRepo;
}
public ICollection<TradeSummary> FindBySymbol(string symbol)
{
var tickers = tickerRepo.GetAll();
var summary = GetAll();
var result = from t1 in tickers
join t2 in summary
on t1.Id equals t2.TickerId
where t1.Symbol.Contains(symbol)
select t2;
return result.ToList();
}
public TradeSummary GetBySymbol(string symbol)
{
var tickers = tickerRepo.GetAll();
var summary = GetAll();
var result = from t1 in tickers
join t2 in summary
on t1.Id equals t2.TickerId
where t1.Symbol == symbol
select t2;
return result.FirstOrDefault();
}
public TradeSummary GetByTickerId(int tickerId)
{
return GetAll().Where(p => p.TickerId == tickerId).FirstOrDefault();
}
}
}
| 33.465517 | 121 | 0.589387 | [
"MIT"
] | flipsee/PortfolioTrackerApp | Infrastructure/Repo/TradeRepo.cs | 1,943 | C# |
using System;
using _03BarracksFactory.Contracts;
namespace _03BarracksFactory.Core.Commands
{
internal class FightUnitCommand : IExecutable
{
private string[] data;
private IRepository repository;
private IUnitFactory unitFactory;
public FightUnitCommand(string[] data, IRepository repository, IUnitFactory unitFactory)
{
this.data = data;
this.repository = repository;
this.unitFactory = unitFactory;
}
public string Execute()
{
Environment.Exit(0);
return null;
}
}
} | 25.68 | 97 | 0.5919 | [
"MIT"
] | viktorMirev/SoftUni-tasks-others | OOPAdvanced/Reflection/BarracksFactory(CommandPattern)/Core/Commands/FightUnitCommand.cs | 644 | C# |
/*
* Location Intelligence APIs
*
* Incorporate our extensive geodata into everyday applications, business processes and workflows.
*
* OpenAPI spec version: 8.5.0
*
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*
* 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.Linq;
using System.IO;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
namespace pb.locationIntelligence.Model
{
/// <summary>
/// PBKeyAddressRequest
/// </summary>
[DataContract]
public partial class PBKeyAddressRequest : IEquatable<PBKeyAddressRequest>
{
/// <summary>
/// Initializes a new instance of the <see cref="PBKeyAddressRequest" /> class.
/// </summary>
[JsonConstructorAttribute]
protected PBKeyAddressRequest() { }
/// <summary>
/// Initializes a new instance of the <see cref="PBKeyAddressRequest" /> class.
/// </summary>
/// <param name="Addresses">Addresses (required).</param>
public PBKeyAddressRequest(List<CommonAddress> Addresses = null)
{
// to ensure "Addresses" is required (not null)
if (Addresses == null)
{
throw new InvalidDataException("Addresses is a required property for PBKeyAddressRequest and cannot be null");
}
else
{
this.Addresses = Addresses;
}
}
/// <summary>
/// Gets or Sets Addresses
/// </summary>
[DataMember(Name="addresses", EmitDefaultValue=false)]
public List<CommonAddress> Addresses { get; set; }
/// <summary>
/// Returns the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("class PBKeyAddressRequest {\n");
sb.Append(" Addresses: ").Append(Addresses).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public string ToJson()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="obj">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object obj)
{
// credit: http://stackoverflow.com/a/10454552/677735
return this.Equals(obj as PBKeyAddressRequest);
}
/// <summary>
/// Returns true if PBKeyAddressRequest instances are equal
/// </summary>
/// <param name="other">Instance of PBKeyAddressRequest to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(PBKeyAddressRequest other)
{
// credit: http://stackoverflow.com/a/10454552/677735
if (other == null)
return false;
return
(
this.Addresses == other.Addresses ||
this.Addresses != null &&
this.Addresses.SequenceEqual(other.Addresses)
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
// credit: http://stackoverflow.com/a/263416/677735
unchecked // Overflow is fine, just wrap
{
int hash = 41;
// Suitable nullity checks etc, of course :)
if (this.Addresses != null)
hash = hash * 59 + this.Addresses.GetHashCode();
return hash;
}
}
}
}
| 33.742857 | 126 | 0.583404 | [
"Apache-2.0"
] | PitneyBowes/LocationIntelligenceSDK-CSharp | src/pb.locationIntelligence/Model/PBKeyAddressRequest.cs | 4,724 | C# |
namespace Reusable.CRUD.JsonEntities
{
public class Catalog
{
public int id { get; set; }
public string Value { get; set; }
}
}
| 17.333333 | 41 | 0.583333 | [
"Apache-2.0"
] | JFigue27/MRO-Generated | backend/Reusable/CRUD/JsonEntities/Catalog.cs | 156 | 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.Dbs.Model.V20190306;
namespace Aliyun.Acs.Dbs.Transform.V20190306
{
public class CreateIncrementBackupSetDownloadResponseUnmarshaller
{
public static CreateIncrementBackupSetDownloadResponse Unmarshall(UnmarshallerContext context)
{
CreateIncrementBackupSetDownloadResponse createIncrementBackupSetDownloadResponse = new CreateIncrementBackupSetDownloadResponse();
createIncrementBackupSetDownloadResponse.HttpResponse = context.HttpResponse;
createIncrementBackupSetDownloadResponse.Success = context.BooleanValue("CreateIncrementBackupSetDownload.Success");
createIncrementBackupSetDownloadResponse.ErrCode = context.StringValue("CreateIncrementBackupSetDownload.ErrCode");
createIncrementBackupSetDownloadResponse.ErrMessage = context.StringValue("CreateIncrementBackupSetDownload.ErrMessage");
createIncrementBackupSetDownloadResponse.HttpStatusCode = context.IntegerValue("CreateIncrementBackupSetDownload.HttpStatusCode");
createIncrementBackupSetDownloadResponse.RequestId = context.StringValue("CreateIncrementBackupSetDownload.RequestId");
createIncrementBackupSetDownloadResponse.BackupSetDownloadTaskId = context.StringValue("CreateIncrementBackupSetDownload.BackupSetDownloadTaskId");
return createIncrementBackupSetDownloadResponse;
}
}
}
| 49.866667 | 150 | 0.809715 | [
"Apache-2.0"
] | bbs168/aliyun-openapi-net-sdk | aliyun-net-sdk-dbs/Dbs/Transform/V20190306/CreateIncrementBackupSetDownloadResponseUnmarshaller.cs | 2,244 | C# |
namespace VSCC.Controls.Dialogs
{
using System.Windows;
using System.Windows.Controls;
using VSCC.Roll20.AdvancedIntegration;
/// <summary>
/// Interaction logic for NewScalableDamageLineDialog.xaml
/// </summary>
public partial class NewScalableDamageLineDialog : Window
{
public ScalableDamageLine Value { get; set; }
public NewScalableDamageLineDialog(ScalableDamageLine die)
{
this.DataContext = this.Value = die;
this.InitializeComponent();
this.Btn_Constant.DataContext =
this.Btn_DieSide.DataContext =
this.Btn_NumDice.DataContext =
this.TB_Label.DataContext =
this.Value;
}
private void Button_Click(object sender, RoutedEventArgs e)
{
this.DialogResult = false;
this.Close();
}
private void Button_Click_1(object sender, RoutedEventArgs e)
{
this.DialogResult = true;
this.Close();
}
private void Btn_NumDice_Click(object sender, RoutedEventArgs e)
{
ScalableValue sv = this.Value.Die.NumDice.Copy();
ScalableValueDialog svd = new ScalableValueDialog(sv);
if (svd.ShowDialog() ?? false)
{
this.Value.Die.NumDice = sv;
}
this.Btn_NumDice.GetBindingExpression(Button.ContentProperty).UpdateTarget();
}
private void Btn_DieSide_Click(object sender, RoutedEventArgs e)
{
ScalableValue sv = this.Value.Die.DieSide.Copy();
ScalableValueDialog svd = new ScalableValueDialog(sv);
if (svd.ShowDialog() ?? false)
{
this.Value.Die.DieSide = sv;
}
this.Btn_DieSide.GetBindingExpression(Button.ContentProperty).UpdateTarget();
}
private void Btn_Constant_Click(object sender, RoutedEventArgs e)
{
ScalableValue sv = this.Value.ConstantNumber.Copy();
ScalableValueDialog svd = new ScalableValueDialog(sv);
if (svd.ShowDialog() ?? false)
{
this.Value.ConstantNumber = sv;
}
this.Btn_Constant.GetBindingExpression(Button.ContentProperty).UpdateTarget();
}
}
}
| 31.32 | 90 | 0.592167 | [
"MIT"
] | skyloutyr/VSCC | VSCC/Controls/Dialogs/NewScalableDamageLineDialog.xaml.cs | 2,351 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public enum ADSType {
Scope,
Aim,
}
public enum BulletType {
Small,
Shotgun,
Medium,
Large,
Elemental,
}
public class GunStats : MonoBehaviour {
[Header("Base")]
public float bulletDamage = 150f;
public float range = 100f;
[Header("Shoot Speed")]
public float fireRate = 0.15f;
public bool auto = false;
[Header("Reload Settings")]
public BulletType type;
public int magazine = 1;
public int shotCost = 1;
public int ammo = 1000;
public float reloadTime = 1f;
[Header("Multipliers")]
public float recoil = 1f;
public float bulletSpeed = 3f;
[Header("Camera")]
public ADSType aimType = ADSType.Aim;
public float hipFOV = 60f;
public float adsFOV = 40f;
public float scopeInSpeed = 4f;
public float scopeOutSpeed = 12f;
public float aimStep = 0.1f;
}
| 19.782609 | 40 | 0.683516 | [
"MIT"
] | FloppyDisk69420/Orion | March/Scripts/Stats/GunStats.cs | 912 | C# |
using System;
using Newtonsoft.Json;
namespace Smartling.Api.Authentication
{
public class AuthApiClient : ApiClientBase
{
public const string AUTH_API_V2_AUTHENTICATE = "/auth-api/v2/authenticate";
public const string AUTH_API_V2_REFRESH = "/auth-api/v2/authenticate/refresh";
private readonly string userIdentifier;
private readonly string userSecret;
public AuthApiClient(string userIdentifier, string userSecret)
{
this.userIdentifier = userIdentifier;
this.userSecret = userSecret;
}
public virtual AuthResponse Authenticate()
{
var command = new AuthCommand() { userIdentifier = this.userIdentifier, userSecret = this.userSecret };
var request = PrepareJsonPostRequest(ApiGatewayUrl + AUTH_API_V2_AUTHENTICATE, command, String.Empty);
var jsonResponse = GetResponse(request);
var authResponse = JsonConvert.DeserializeObject<AuthResponseWrapper>(jsonResponse);
return authResponse.response;
}
public virtual AuthResponse Refresh(string refreshToken)
{
var command = new RefreshCommand() { refreshToken = refreshToken };
var request = PrepareJsonPostRequest(ApiGatewayUrl + AUTH_API_V2_REFRESH, command, string.Empty);
var jsonResponse = GetResponse(request);
var refreshResponse = JsonConvert.DeserializeObject<AuthResponseWrapper>(jsonResponse);
return refreshResponse.response;
}
}
} | 36.615385 | 109 | 0.745098 | [
"Apache-2.0"
] | Smartling/api-sdk-net | Smartling.API/Authentication/AuthApiClient.cs | 1,430 | C# |
namespace Strategy
{
using System.Collections.Generic;
/// <summary>
/// The abstract sort strategy.
/// </summary>
public abstract class AbstractSortStrategy
{
/// <summary>
/// The sort.
/// </summary>
/// <param name="list">
/// The list.
/// </param>
public abstract void Sort(List<string> list);
}
} | 21.666667 | 53 | 0.523077 | [
"MIT"
] | enriqueescobar-askida/Kinito.Patterns.Behavioral | Strategy/AbstractSortStrategy.cs | 392 | C# |
// ASM: a very small and fast Java bytecode manipulation framework
// Copyright (c) 2000-2011 INRIA, France Telecom
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// 1. Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// 3. Neither the name of the copyright holders nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
using System;
namespace ObjectWeb.Asm
{
/// <summary>
/// A visitor to visit a Java module. The methods of this class must be called in the following
/// order: ( {@code visitMainClass} | ( {@code visitPackage} | {@code visitRequire} | {@code
/// visitExport} | {@code visitOpen} | {@code visitUse} | {@code visitProvide} )* ) {@code visitEnd}.
/// @author Remi Forax
/// @author Eric Bruneton
/// </summary>
public abstract class ModuleVisitor
{
/// <summary>
/// The ASM API version implemented by this visitor. The value of this field must be one of {@link
/// Opcodes#ASM6} or <seealso cref="IIOpcodes.Asm7 />.
/// </summary>
protected internal readonly int api;
/// <summary>
/// The module visitor to which this visitor must delegate method calls. May be {@literal null}.
/// </summary>
protected internal ModuleVisitor mv;
/// <summary>
/// Constructs a new <seealso cref="ModuleVisitor" />.
/// </summary>
/// <param name="api">
/// the ASM API version implemented by this visitor. Must be one of <seealso cref="IIOpcodes.Asm6 />
/// or <seealso cref="IIOpcodes.Asm7 />.
/// </param>
public ModuleVisitor(int api) : this(api, null)
{
}
/// <summary>
/// Constructs a new <seealso cref="ModuleVisitor" />.
/// </summary>
/// <param name="api">
/// the ASM API version implemented by this visitor. Must be one of <seealso cref="IIOpcodes.Asm6 />
/// or <seealso cref="IIOpcodes.Asm7 />.
/// </param>
/// <param name="moduleVisitor">
/// the module visitor to which this visitor must delegate method calls. May
/// be null.
/// </param>
public ModuleVisitor(int api, ModuleVisitor moduleVisitor)
{
if (api != IOpcodes.Asm9 && api != IOpcodes.Asm8 && api != IOpcodes.Asm7 && api != IOpcodes.Asm6 &&
api != IOpcodes.Asm5 && api != IOpcodes.Asm4 &&
api != IOpcodes.Asm10_Experimental) throw new ArgumentException("Unsupported api " + api);
if (api == IOpcodes.Asm10_Experimental) Constants.CheckAsmExperimental(this);
this.api = api;
mv = moduleVisitor;
}
/// <summary>
/// Visit the main class of the current module.
/// </summary>
/// <param name="mainClass"> the internal name of the main class of the current module. </param>
public virtual void VisitMainClass(string mainClass)
{
if (mv != null) mv.VisitMainClass(mainClass);
}
/// <summary>
/// Visit a package of the current module.
/// </summary>
/// <param name="packaze"> the internal name of a package. </param>
public virtual void VisitPackage(string packaze)
{
if (mv != null) mv.VisitPackage(packaze);
}
/// <summary>
/// Visits a dependence of the current module.
/// </summary>
/// <param name="module"> the fully qualified name (using dots) of the dependence. </param>
/// <param name="access">
/// the access flag of the dependence among {@code ACC_TRANSITIVE}, {@code
/// ACC_STATIC_PHASE}, {@code ACC_SYNTHETIC} and {@code ACC_MANDATED}.
/// </param>
/// <param name="version"> the module version at compile time, or {@literal null}. </param>
public virtual void VisitRequire(string module, int access, string version)
{
if (mv != null) mv.VisitRequire(module, access, version);
}
/// <summary>
/// Visit an exported package of the current module.
/// </summary>
/// <param name="packaze"> the internal name of the exported package. </param>
/// <param name="access">
/// the access flag of the exported package, valid values are among {@code
/// ACC_SYNTHETIC} and {@code ACC_MANDATED}.
/// </param>
/// <param name="modules">
/// the fully qualified names (using dots) of the modules that can access the public
/// classes of the exported package, or {@literal null}.
/// </param>
public virtual void VisitExport(string packaze, int access, params string[] modules)
{
if (mv != null) mv.VisitExport(packaze, access, modules);
}
/// <summary>
/// Visit an open package of the current module.
/// </summary>
/// <param name="packaze"> the internal name of the opened package. </param>
/// <param name="access">
/// the access flag of the opened package, valid values are among {@code
/// ACC_SYNTHETIC} and {@code ACC_MANDATED}.
/// </param>
/// <param name="modules">
/// the fully qualified names (using dots) of the modules that can use deep
/// reflection to the classes of the open package, or {@literal null}.
/// </param>
public virtual void VisitOpen(string packaze, int access, params string[] modules)
{
if (mv != null) mv.VisitOpen(packaze, access, modules);
}
/// <summary>
/// Visit a service used by the current module. The name must be the internal name of an interface
/// or a class.
/// </summary>
/// <param name="service"> the internal name of the service. </param>
public virtual void VisitUse(string service)
{
if (mv != null) mv.VisitUse(service);
}
/// <summary>
/// Visit an implementation of a service.
/// </summary>
/// <param name="service"> the internal name of the service. </param>
/// <param name="providers">
/// the internal names of the implementations of the service (there is at least
/// one provider).
/// </param>
public virtual void VisitProvide(string service, params string[] providers)
{
if (mv != null) mv.VisitProvide(service, providers);
}
/// <summary>
/// Visits the end of the module. This method, which is the last one to be called, is used to
/// inform the visitor that everything have been visited.
/// </summary>
public virtual void VisitEnd()
{
if (mv != null) mv.VisitEnd();
}
}
} | 45.153005 | 112 | 0.600992 | [
"BSD-3-Clause"
] | CursedJvmSharp/ObjectWeb.Asm | ObjectWeb.Asm/ObjectWeb/Asm/ModuleVisitor.cs | 8,265 | C# |
namespace Spark
{
public class NullCacheService : ICacheService
{
public object Get(string identifier)
{
return null;
}
public void Store(string identifier, CacheExpires expires, ICacheSignal signal, object item)
{
}
}
} | 21.857143 | 101 | 0.565359 | [
"Apache-2.0"
] | RobertTheGrey/spark | src/Spark/NullCacheService.cs | 306 | C# |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
using System.Collections.Generic;
using Aliyun.Acs.Core;
namespace Aliyun.Acs.CCC.Model.V20200701
{
public class SignInGroupResponse : AcsResponse
{
private string code;
private int? httpStatusCode;
private string message;
private string requestId;
private List<string> _params;
private SignInGroup_Data data;
public string Code
{
get
{
return code;
}
set
{
code = value;
}
}
public int? HttpStatusCode
{
get
{
return httpStatusCode;
}
set
{
httpStatusCode = value;
}
}
public string Message
{
get
{
return message;
}
set
{
message = value;
}
}
public string RequestId
{
get
{
return requestId;
}
set
{
requestId = value;
}
}
public List<string> _Params
{
get
{
return _params;
}
set
{
_params = value;
}
}
public SignInGroup_Data Data
{
get
{
return data;
}
set
{
data = value;
}
}
public class SignInGroup_Data
{
private string extension;
private string workMode;
private string deviceId;
private string jobId;
private string userId;
private string breakCode;
private string instanceId;
private bool? outboundScenario;
private string userState;
private List<string> signedSkillGroupIdList;
public string Extension
{
get
{
return extension;
}
set
{
extension = value;
}
}
public string WorkMode
{
get
{
return workMode;
}
set
{
workMode = value;
}
}
public string DeviceId
{
get
{
return deviceId;
}
set
{
deviceId = value;
}
}
public string JobId
{
get
{
return jobId;
}
set
{
jobId = value;
}
}
public string UserId
{
get
{
return userId;
}
set
{
userId = value;
}
}
public string BreakCode
{
get
{
return breakCode;
}
set
{
breakCode = value;
}
}
public string InstanceId
{
get
{
return instanceId;
}
set
{
instanceId = value;
}
}
public bool? OutboundScenario
{
get
{
return outboundScenario;
}
set
{
outboundScenario = value;
}
}
public string UserState
{
get
{
return userState;
}
set
{
userState = value;
}
}
public List<string> SignedSkillGroupIdList
{
get
{
return signedSkillGroupIdList;
}
set
{
signedSkillGroupIdList = value;
}
}
}
}
}
| 14.447471 | 63 | 0.550229 | [
"Apache-2.0"
] | pengweiqhca/aliyun-openapi-net-sdk | aliyun-net-sdk-ccc/CCC/Model/V20200701/SignInGroupResponse.cs | 3,713 | C# |
using System.Collections.Generic;
using Avocado.DependenciesVisualizer.Base.Editor.Scripts.State;
using DependenciesVisualizer.Base.Editor.Scripts.ReorderList;
using UnityEditor;
using UnityEditorInternal;
using UnityEngine;
namespace Avocado.DependenciesVisualizer.Base.Editor.Scripts {
public class LayersWindow {
public const string DefaultLayerName = "Default";
public List<LayerData> Layers => _layers;
private readonly List<LayerData> _layers;
private readonly VisualizerState _state;
private ReorderableList _layersList;
private Rect _windowRect;
public LayersWindow(VisualizerState state) {
_state = state;
_layers = _state.layers;
_windowRect = new Rect(_state.LayersWindowPosition, new Vector2(330, 300));
}
public void Draw() {
_windowRect.size = new Vector2(330, _layers.Count * 22 + 50);
_state.LayersWindowPosition = _windowRect.position;
_windowRect = GUI.Window(
1000,
_windowRect,
i => {
ReorderableListGUI.ListField(_layers, CustomListItem, DrawEmpty);
GUI.DragWindow();
}, "Layers");
}
private LayerData CustomListItem(Rect position, LayerData itemValue) {
var getPriorityByIndex = _layers.FindIndex(test => test == itemValue);
if (itemValue is null) {
itemValue = new LayerData();
itemValue.Name = "Default_" + getPriorityByIndex;
itemValue.Color = _state.layerDefaultColor;
}
position.x = 30;
position.width = 25;
EditorGUI.LabelField(position, getPriorityByIndex.ToString());
itemValue.Priority = getPriorityByIndex;
/*position.x = 50;
position.width = 50;
EditorGUI.LabelField(position, "Name");*/
position.width -= 50;
position.x = 50;
position.xMax = 200;
itemValue.Name = EditorGUI.TextField(position, itemValue.Name);
position.x = 210;
position.width = 75;
itemValue.Color = EditorGUI.ColorField(position, itemValue.Color);
_state.layerDefaultColor = itemValue.Color;
return itemValue;
}
private void DrawEmpty() {
GUILayout.Label("No items in list.", EditorStyles.miniLabel);
}
}
}
| 36.478873 | 87 | 0.582625 | [
"MIT"
] | gadget114514/unityeditorextensions | Assets/Plugins/Avocado/DependenciesVisualizer/Base/Editor/Scripts/LayersWindow.cs | 2,590 | C# |
using System;
using EP.IdentityIsolation.Infra.CrossCutting.Identity.Model;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.Owin;
using Microsoft.Owin.Security.DataProtection;
namespace EP.IdentityIsolation.Infra.CrossCutting.Identity.Configuration
{
public class ApplicationUserManager : UserManager<ApplicationUser>
{
public ApplicationUserManager(IUserStore<ApplicationUser> store)
: base(store)
{
// Configurando validator para nome de usuario
UserValidator = new UserValidator<ApplicationUser>(this)
{
AllowOnlyAlphanumericUserNames = false,
RequireUniqueEmail = true
};
// Logica de validação e complexidade de senha
PasswordValidator = new PasswordValidator
{
RequiredLength = 6,
RequireNonLetterOrDigit = false,
RequireDigit = false,
RequireLowercase = false,
RequireUppercase = false,
};
// Configuração de Lockout
UserLockoutEnabledByDefault = true;
DefaultAccountLockoutTimeSpan = TimeSpan.FromMinutes(5);
MaxFailedAccessAttemptsBeforeLockout = 5;
// Providers de Two Factor Autentication
RegisterTwoFactorProvider("Código via SMS", new PhoneNumberTokenProvider<ApplicationUser>
{
MessageFormat = "Seu código de segurança é: {0}"
});
RegisterTwoFactorProvider("Código via E-mail", new EmailTokenProvider<ApplicationUser>
{
Subject = "Código de Segurança",
BodyFormat = "Seu código de segurança é: {0}"
});
// Definindo a classe de serviço de e-mail
EmailService = new EmailService();
// Definindo a classe de serviço de SMS
SmsService = new SmsService();
var provider = new DpapiDataProtectionProvider("Eduardo");
var dataProtector = provider.Create("ASP.NET Identity");
UserTokenProvider = new DataProtectorTokenProvider<ApplicationUser>(dataProtector);
}
}
} | 36.377049 | 101 | 0.617395 | [
"MIT"
] | EduardoPires/IdentityIsolation | src/EP.IdentityIsolation.Infra.CrossCutting.Identity/Configuration/ApplicationUserManager.cs | 2,237 | C# |
using UnityEngine;
using System;
using LuaInterface;
using SLua;
using System.Collections.Generic;
public class Lua_UnityEngine_CollisionDetectionMode2D : LuaObject {
static public void reg(IntPtr l) {
getEnumTable(l,"UnityEngine.CollisionDetectionMode2D");
addMember(l,0,"None");
addMember(l,1,"Continuous");
LuaDLL.lua_pop(l, 1);
}
}
| 24.785714 | 67 | 0.769452 | [
"MIT"
] | LunaFramework/Luna | luna/Assets/LuaObject/Unity/Lua_UnityEngine_CollisionDetectionMode2D.cs | 349 | C# |
using NUnit.Framework;
namespace TDD
{
[TestFixture]
public class RomanNumeralsTests
{
[Test]
public void Parse()
{
Assert.AreEqual(1, Roman.Parse("I"));
}
}
public class Roman
{
public static in Parse(string roman)
{
return 0;
}
}
}
| 11.521739 | 40 | 0.637736 | [
"MIT"
] | JackieG19/TestDrivenDevelopment | TestDrivenDevelopment/RomanNumerals/TestCase1/RomanNumeralsTest1.cs | 265 | C# |
using System;
using System.Collections;
using System.Collections.Generic;
namespace OneUpside.Reactive
{
/// <summary>
/// An ordered collection of <see cref="IDisposable"/>'s.
/// </summary>
public sealed class MultiDisposable : IDisposable, IEnumerable<IDisposable>
{
/// <summary>
/// The ordered <see cref="IDisposable"/>'s.
/// </summary>
private readonly IEnumerable<IDisposable> Disposables;
/// <summary>
/// Construct a <see cref="MultiDisposable"/>.
/// </summary>
/// <param name="disposables">
/// The ordered <see cref="IDisposable"/>'s.
/// </param>
public MultiDisposable(IEnumerable<IDisposable> disposables)
{
Disposables = disposables;
}
/// <summary>
/// Construct a <see cref="MultiDisposable"/>.
/// </summary>
/// <param name="disposables">
/// The ordered <see cref="IDisposable"/>'s.
/// </param>
public MultiDisposable(params IDisposable[] disposables)
{
Disposables = disposables;
}
/// <summary>
/// Call .Dispose() on every <see cref="IDisposable"/> in order.
/// </summary>
public void Dispose()
{
foreach (var d in Disposables)
{
d.Dispose();
}
}
public IEnumerator<IDisposable> GetEnumerator()
{
return Disposables.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
}
| 22.703125 | 77 | 0.602891 | [
"BSD-3-Clause"
] | 1Upside/OneUpside-Reactive | MultiDisposable.cs | 1,455 | C# |
using System;
using System.Web.Http;
using System.Web.Mvc;
using APIChrysallis.Areas.HelpPage.ModelDescriptions;
using APIChrysallis.Areas.HelpPage.Models;
namespace APIChrysallis.Areas.HelpPage.Controllers
{
/// <summary>
/// The controller that will handle requests for the help page.
/// </summary>
public class HelpController : Controller
{
private const string ErrorViewName = "Error";
public HelpController()
: this(GlobalConfiguration.Configuration)
{
}
public HelpController(HttpConfiguration config)
{
Configuration = config;
}
public HttpConfiguration Configuration { get; private set; }
public ActionResult Index()
{
ViewBag.DocumentationProvider = Configuration.Services.GetDocumentationProvider();
return View(Configuration.Services.GetApiExplorer().ApiDescriptions);
}
public ActionResult Api(string apiId)
{
if (!String.IsNullOrEmpty(apiId))
{
HelpPageApiModel apiModel = Configuration.GetHelpPageApiModel(apiId);
if (apiModel != null)
{
return View(apiModel);
}
}
return View(ErrorViewName);
}
public ActionResult ResourceModel(string modelName)
{
if (!String.IsNullOrEmpty(modelName))
{
ModelDescriptionGenerator modelDescriptionGenerator = Configuration.GetModelDescriptionGenerator();
ModelDescription modelDescription;
if (modelDescriptionGenerator.GeneratedModels.TryGetValue(modelName, out modelDescription))
{
return View(modelDescription);
}
}
return View(ErrorViewName);
}
}
} | 30.126984 | 115 | 0.599052 | [
"MIT"
] | shuansanchez/APIChrysallis | APIChrysallis/Areas/HelpPage/Controllers/HelpController.cs | 1,898 | C# |
using System;
using AutoFixture;
using BookLovers.Base.Domain.Rules;
using BookLovers.Readers.Domain.ProfileManagers;
using BookLovers.Readers.Domain.ProfileManagers.Services;
using BookLovers.Readers.Events.ProfileManagers;
using BookLovers.Shared.Privacy;
using FluentAssertions;
using NUnit.Framework;
namespace BookLovers.Readers.Tests.UnitTests.Aggregates
{
[TestFixture]
public class ProfilePrivacyManagerTests
{
private Fixture _fixture;
private ProfilePrivacyManager _privacyManager;
[Test]
public void ChangePrivacy_WhenCalled_ShouldChangePrivacyOption()
{
_privacyManager.ChangePrivacy(new SelectedProfileOption(
PrivacyOption.Public,
ProfilePrivacyType.AddressPrivacy));
var addressPrivacy = _privacyManager.GetPrivacyOption(ProfilePrivacyType.AddressPrivacy);
addressPrivacy.PrivacyOption.Should().Be(PrivacyOption.Public);
}
[Test]
public void ChangePrivacy_WhenCalledAndAggregateIsNotActive_ShouldThrowBusinessRuleNotMeetException()
{
_privacyManager.ApplyChange(new ProfilePrivacyManagerArchived(_fixture.Create<Guid>()));
Action act = () =>
_privacyManager.ChangePrivacy(new SelectedProfileOption(
PrivacyOption.Public,
ProfilePrivacyType.AddressPrivacy));
act.Should().Throw<BusinessRuleNotMetException>();
}
[Test]
public void ChangePrivacy_WhenCalledAndPrivacyOptionIsNotValid_ShouldThrowBusinessRuleNotMeetException()
{
Action act = () =>
_privacyManager.ChangePrivacy(new SelectedProfileOption(10, ProfilePrivacyType.GenderPrivacy.Value));
act.Should().Throw<BusinessRuleNotMetException>();
}
public void ChangePrivacy_WhenCalledAndPrivacyTypeIsNotValid_ShouldThrowBusinessRuleNotMeetException()
{
Action act = () => _privacyManager.ChangePrivacy(new SelectedProfileOption(PrivacyOption.Public.Value, 20));
act.Should().Throw<BusinessRuleNotMetException>();
}
[SetUp]
public void SetUp()
{
_fixture = new Fixture();
_privacyManager = new ProfilePrivacyManager(_fixture.Create<Guid>(), _fixture.Create<Guid>());
var addressPrivacyOptionAdded = ProfilePrivacyOptionAdded.Initialize()
.WithAggregate(_privacyManager.Guid)
.WithOption(PrivacyOption.Public.Value, PrivacyOption.Public.Name)
.WithPrivacyType(ProfilePrivacyType.AddressPrivacy.Value, ProfilePrivacyType.AddressPrivacy.Name);
var favouritesPrivacyOptionAdded = ProfilePrivacyOptionAdded.Initialize()
.WithAggregate(_privacyManager.Guid)
.WithOption(PrivacyOption.Public.Value, PrivacyOption.Public.Name)
.WithPrivacyType(ProfilePrivacyType.FavouritesPrivacy.Value, ProfilePrivacyType.FavouritesPrivacy.Name);
var genderPrivacyOptionAdded = ProfilePrivacyOptionAdded.Initialize()
.WithAggregate(_privacyManager.Guid)
.WithOption(PrivacyOption.Public.Value, PrivacyOption.Public.Name)
.WithPrivacyType(ProfilePrivacyType.GenderPrivacy.Value, ProfilePrivacyType.GenderPrivacy.Name);
var identityPrivacyOptionAdded = ProfilePrivacyOptionAdded.Initialize()
.WithAggregate(_privacyManager.Guid)
.WithOption(PrivacyOption.Public.Value, PrivacyOption.Public.Name)
.WithPrivacyType(ProfilePrivacyType.AddressPrivacy.Value, ProfilePrivacyType.IdentityPrivacy.Name);
_privacyManager.ApplyChange(addressPrivacyOptionAdded);
_privacyManager.ApplyChange(favouritesPrivacyOptionAdded);
_privacyManager.ApplyChange(genderPrivacyOptionAdded);
_privacyManager.ApplyChange(identityPrivacyOptionAdded);
}
}
} | 43.543478 | 120 | 0.702446 | [
"MIT"
] | kamilk08/BookLoversApi | BookLovers.Readers.Tests/UnitTests/Aggregates/ProfilePrivacyManagerTests.cs | 4,008 | C# |
using Ship;
using SubPhases;
using System;
using Tokens;
namespace Ship
{
namespace FirstEdition.StarViper
{
public class Thweek : StarViper
{
public Thweek() : base()
{
PilotInfo = new PilotCardInfo(
"Thweek",
4,
28,
isLimited: true,
abilityType: typeof(Abilities.FirstEdition.ThweekAbility)
);
}
}
}
}
namespace Abilities.FirstEdition
{
public class ThweekAbility : GenericAbility
{
public override void Initialize(GenericShip host)
{
base.Initialize(host);
IsAppliesConditionCard = true;
}
public override void ActivateAbility()
{
Phases.Events.OnSetupStart += RegisterSelectThweekTarget;
}
public override void DeactivateAbility()
{
Phases.Events.OnSetupStart -= RegisterSelectThweekTarget;
}
private void RegisterSelectThweekTarget()
{
RegisterAbilityTrigger(TriggerTypes.OnSetupStart, SelectThweekTarget);
}
private void SelectThweekTarget(object Sender, System.EventArgs e)
{
ThweekTargetDecisionSubPhase selectTargetForThweekDecisionSubPhase = (ThweekTargetDecisionSubPhase)Phases.StartTemporarySubPhaseNew(
Name,
typeof(ThweekTargetDecisionSubPhase),
delegate { }
);
foreach (var enemyShip in Roster.GetPlayer(Roster.AnotherPlayer(HostShip.Owner.PlayerNo)).Ships)
{
selectTargetForThweekDecisionSubPhase.AddDecision(
enemyShip.Value.ShipId + ": " + enemyShip.Value.PilotInfo.PilotName,
delegate { SelectAbility(enemyShip.Value); }
);
}
selectTargetForThweekDecisionSubPhase.DescriptionShort = "Thweek";
selectTargetForThweekDecisionSubPhase.DescriptionLong = "Select enemy ship";
selectTargetForThweekDecisionSubPhase.ImageSource = HostShip;
GenericShip bestEnemyAce = GetEnemyPilotWithHighestSkill();
selectTargetForThweekDecisionSubPhase.DefaultDecisionName = bestEnemyAce.ShipId + ": " + bestEnemyAce.PilotInfo.PilotName;
selectTargetForThweekDecisionSubPhase.RequiredPlayer = HostShip.Owner.PlayerNo;
selectTargetForThweekDecisionSubPhase.Start();
}
private GenericShip GetEnemyPilotWithHighestSkill()
{
GenericShip bestAce = null;
int maxPilotSkill = 0;
foreach (var enemyShip in Roster.GetPlayer(Roster.AnotherPlayer(HostShip.Owner.PlayerNo)).Ships)
{
if (enemyShip.Value.State.Initiative > maxPilotSkill)
{
bestAce = enemyShip.Value;
maxPilotSkill = enemyShip.Value.State.Initiative;
}
}
return bestAce;
}
private void SelectAbility(GenericShip targetShip)
{
SubPhases.DecisionSubPhase.ConfirmDecision();
ThweekAbilityDecisionSubPhase selectAbilityForThweekDecisionSubPhase = (ThweekAbilityDecisionSubPhase)Phases.StartTemporarySubPhaseNew(
Name,
typeof(ThweekAbilityDecisionSubPhase),
Triggers.FinishTrigger
);
selectAbilityForThweekDecisionSubPhase.AddDecision("Mimicked", delegate { Mimicked(targetShip); });
selectAbilityForThweekDecisionSubPhase.AddTooltip("Mimicked", (new Conditions.Mimicked(targetShip)).Tooltip);
selectAbilityForThweekDecisionSubPhase.AddDecision("Shadowed", delegate { Shadowed(targetShip); });
selectAbilityForThweekDecisionSubPhase.AddTooltip("Shadowed", (new Conditions.Shadowed(targetShip)).Tooltip);
selectAbilityForThweekDecisionSubPhase.DescriptionShort = "Thweek";
selectAbilityForThweekDecisionSubPhase.DescriptionLong = "Select ability to copy";
selectAbilityForThweekDecisionSubPhase.ImageSource = HostShip;
selectAbilityForThweekDecisionSubPhase.DefaultDecisionName = "Shadowed";
selectAbilityForThweekDecisionSubPhase.RequiredPlayer = HostShip.Owner.PlayerNo;
selectAbilityForThweekDecisionSubPhase.Start();
}
private void Mimicked(GenericShip targetShip)
{
bool abilityIsFound = false;
foreach (var ability in targetShip.PilotAbilities)
{
if (!ability.IsAppliesConditionCard)
{
Messages.ShowInfo(targetShip.PilotInfo.PilotName + "'s ability has been mimicked!");
HostShip.PilotAbilities.Add((GenericAbility)Activator.CreateInstance(ability.GetType()));
HostShip.PilotAbilities[1].Initialize(HostShip);
abilityIsFound = true;
break;
}
}
if (!abilityIsFound)
{
Messages.ShowError(targetShip.PilotInfo.PilotName + " doesn't have abilities to be mimicked");
}
targetShip.Tokens.AssignCondition(typeof(Conditions.Mimicked));
DecisionSubPhase.ConfirmDecision();
}
private void Shadowed(GenericShip targetShip)
{
Messages.ShowInfo("The Pilot skill of " + targetShip.PilotInfo.PilotName + " is shadowed");
new ThweekPilotSkillModifier(HostShip, targetShip.State.Initiative);
targetShip.Tokens.AssignCondition(typeof(Conditions.Shadowed));
DecisionSubPhase.ConfirmDecision();
}
private class ThweekPilotSkillModifier : IModifyPilotSkill
{
private GenericShip host;
private int newPilotSkill;
public ThweekPilotSkillModifier(GenericShip host, int newPilotSkill)
{
this.host = host;
this.newPilotSkill = newPilotSkill;
host.State.AddPilotSkillModifier(this);
}
public void ModifyPilotSkill(ref int pilotSkill)
{
pilotSkill = newPilotSkill;
}
private void RemoveSwarmTacticsModifieer()
{
host.State.RemovePilotSkillModifier(this);
}
}
private class ThweekTargetDecisionSubPhase : DecisionSubPhase
{
public override void PrepareDecision(Action callBack)
{
UI.ShowSkipButton();
callBack();
}
public override void SkipButton()
{
UI.HideSkipButton();
Phases.FinishSubPhase(Phases.CurrentSubPhase.GetType());
Triggers.FinishTrigger();
}
}
private class ThweekAbilityDecisionSubPhase : DecisionSubPhase
{
public override void PrepareDecision(Action callBack)
{
UI.ShowSkipButton();
callBack();
}
public override void SkipButton()
{
UI.HideSkipButton();
Phases.FinishSubPhase(Phases.CurrentSubPhase.GetType());
Triggers.FinishTrigger();
}
}
}
}
namespace Conditions
{
public class Mimicked : GenericToken
{
public Mimicked(GenericShip host) : base(host)
{
Name = ImageName = "Thweek Condition";
Temporary = false;
Tooltip = "https://raw.githubusercontent.com/guidokessels/xwing-data/master/images/conditions/mimicked.png";
}
}
public class Shadowed : GenericToken
{
public Shadowed(GenericShip host) : base(host)
{
Name = ImageName = "Thweek Condition";
Temporary = false;
Tooltip = "https://raw.githubusercontent.com/guidokessels/xwing-data/master/images/conditions/shadowed.png";
}
}
}
| 34.621277 | 147 | 0.599803 | [
"MIT"
] | 97saundersj/FlyCasual | Assets/Scripts/Model/Content/FirstEdition/Pilots/StarViper/Thweek.cs | 8,138 | C# |
using System;
namespace adrapi.Ldap
{
public class LdapServer
{
public string FQDN { get; set; }
public int Port { get; set; }
public LdapServer()
{
}
}
}
| 13.1875 | 40 | 0.511848 | [
"Apache-2.0"
] | ffquintella/adrapi | adrapi/Ldap/LdapServer.cs | 213 | C# |
using System;
using System.Diagnostics;
using System.Threading.Tasks;
using System.Xml.Linq;
using Windows.Storage.Streams;
using Windows.Web.Http;
using DIALClient.Model;
namespace DIALClient
{
/// <summary>
/// DIAL Rest Service class used to interact with specified discovered device.
/// </summary>
public static class DialRestService
{
public static async Task<IApplicationInfo> GetApplicationInfo(IDeviceInfo deviceInfo, string applicationCode)
{
return await GetApplicationInfo<ApplicationInfo>(deviceInfo, applicationCode);
}
/// <summary>
/// Returns application information of specified application name.
/// </summary>
/// <param name="deviceInfo"></param>
/// <param name="applicationCode">Application name.</param>
/// <returns>Application information.</returns>
public static async Task<IApplicationInfo> GetApplicationInfo<T>(IDeviceInfo deviceInfo, string applicationCode) where T : ApplicationInfo
{
if (string.IsNullOrEmpty(applicationCode))
{
throw new ArgumentNullException(applicationCode);
}
if (deviceInfo.ApplicationUrlBase == null)
{
throw new InvalidOperationException("Current device does not have application url base.");
}
using (var client = new HttpClient())
{
var applicationResourceUrl = new Uri(deviceInfo.ApplicationUrlBase + applicationCode);
#if DEBUG
Debug.WriteLine(string.Format("GET REQUEST: Url = {0}", applicationResourceUrl));
#endif
var response = await client.GetAsync(applicationResourceUrl);
#if DEBUG
Debug.WriteLine(string.Format("GET RESPONSE: IsSuccessStatusCode = {0}", response.IsSuccessStatusCode));
#endif
if (!response.IsSuccessStatusCode)
{
return null;
}
T appInfo;
try
{
appInfo = (T)Activator.CreateInstance(typeof (T), XDocument.Parse(await response.Content.ReadAsStringAsync()));
}
catch (Exception)
{
throw new InvalidOperationException("Invalid ApplicationInfo class. Constructor class must have just one argument of type XDocument.");
}
appInfo.DeviceInfo = deviceInfo;
appInfo.Code = applicationCode;
return appInfo;
}
}
/// <summary>
/// Install specified application on DIAL Server device.
/// </summary>
/// <param name="installUrl">Install Url.</param>
public static async Task InstallApplication(Uri installUrl)
{
if (installUrl == null)
{
throw new ArgumentNullException("installUrl");
}
using (var client = new HttpClient())
{
#if DEBUG
Debug.WriteLine(string.Format("GET REQUEST: Url = {0}", installUrl));
#endif
await client.GetAsync(installUrl);
}
}
/// <summary>
/// Executes application in DIAL Server device.
/// </summary>
/// <param name="applicationUrl">Application Url.</param>
/// <param name="parameters">Application constructor parameters.</param>
/// <returns>Application Instance.</returns>
public static async Task<Uri> RunApplication(Uri applicationUrl, string parameters = null)
{
if (applicationUrl == null)
{
throw new ArgumentNullException("applicationUrl");
}
using (var client = new HttpClient())
{
HttpStringContent content = null;
if (!string.IsNullOrEmpty(parameters))
{
content = new HttpStringContent(parameters,UnicodeEncoding.Utf8,"text/plain");
}
else
{
client.DefaultRequestHeaders.TryAppendWithoutValidation("CONTENT-LENGTH","0");
}
#if DEBUG
Debug.WriteLine(string.Format("POST REQUEST: Url = {0}, Content = {1}", applicationUrl, parameters ?? "<null>"));
#endif
var response = await client.PostAsync(applicationUrl, content);
#if DEBUG
Debug.WriteLine(string.Format("POST RESPONSE: IsSuccessStatusCode = {0}", response.IsSuccessStatusCode));
#endif
if (response.IsSuccessStatusCode)
{
return new Uri(response.Headers.Location.AbsoluteUri);
}
return null;
}
}
/// <summary>
/// Stop running application on DIAL Server device.
/// </summary>
public static async Task StopApplication(Uri instanceUrl)
{
using (var client = new HttpClient())
{
#if DEBUG
Debug.WriteLine(string.Format("DELETE REQUEST: Url = {0}", instanceUrl));
#endif
await client.DeleteAsync(instanceUrl);
}
}
}
}
| 36.137931 | 155 | 0.569656 | [
"MIT"
] | santoro-mariano/dial-client | DIALPhone/src/DialRestService.cs | 5,242 | C# |
using System.Security.Cryptography;
namespace Apocryph.FunctionApp.Model
{
public struct ValidatorSignature
{
public byte[] Bytes { get; set; }
}
} | 18.666667 | 41 | 0.684524 | [
"MIT"
] | cyppan/apocryph | src/Apocryph.FunctionApp/Model/ValidatorSignature.cs | 168 | C# |
using UnityEngine;
using UnityEngine.Events;
namespace SweatyChair.InputSystem {
[System.Serializable]
public class ButtonStateChangeEvent : UnityEvent<ButtonState> { }
[System.Serializable]
public class ButtonValueChangeEvent : UnityEvent<bool> { }
[System.Serializable]
public class AxisValueChangeEvent : UnityEvent<float> { }
[System.Serializable]
public class GenericVector2Event : UnityEvent<Vector2> { }
[System.Serializable]
public class DragPayloadEvent : UnityEvent<InputDragPayload> { }
} | 23.545455 | 66 | 0.783784 | [
"MIT"
] | Sweaty-Chair/SC-Essentials | Assets/SweatyChair/Essentials/Inputs/GenericInputManager/InputEvents.cs | 520 | C# |
using System;
using System.Collections.Generic;
using System.Data;
namespace LinqToDB.DataProvider.MySql
{
using System.Collections;
using System.Threading;
using System.Threading.Tasks;
using Common;
using Data;
using Mapping;
using SqlProvider;
public class MySqlDataProvider : DynamicDataProviderBase<MySqlProviderAdapter>
{
public MySqlDataProvider(string name)
: this(name, null)
{
}
protected MySqlDataProvider(string name, MappingSchema? mappingSchema)
: base(
name,
mappingSchema != null
? new MappingSchema(mappingSchema, MySqlProviderAdapter.GetInstance(name).MappingSchema)
: GetMappingSchema(name, MySqlProviderAdapter.GetInstance(name).MappingSchema),
MySqlProviderAdapter.GetInstance(name))
{
SqlProviderFlags.IsDistinctOrderBySupported = true;
SqlProviderFlags.IsSubQueryOrderBySupported = true;
SqlProviderFlags.IsCommonTableExpressionsSupported = true;
SqlProviderFlags.IsDistinctSetOperationsSupported = false;
SqlProviderFlags.IsUpdateFromSupported = false;
_sqlOptimizer = new MySqlSqlOptimizer(SqlProviderFlags);
// configure provider-specific data readers
if (Adapter.GetMySqlDecimalMethodName != null)
{
// SetProviderField is not needed for this type
SetToTypeField(Adapter.MySqlDecimalType!, Adapter.GetMySqlDecimalMethodName, Adapter.DataReaderType);
}
if (Adapter.GetDateTimeOffsetMethodName != null)
{
SetProviderField(typeof(DateTimeOffset), Adapter.GetDateTimeOffsetMethodName, Adapter.DataReaderType);
SetToTypeField (typeof(DateTimeOffset), Adapter.GetDateTimeOffsetMethodName, Adapter.DataReaderType);
}
SetProviderField(Adapter.MySqlDateTimeType, Adapter.GetMySqlDateTimeMethodName, Adapter.DataReaderType);
SetToTypeField (Adapter.MySqlDateTimeType, Adapter.GetMySqlDateTimeMethodName, Adapter.DataReaderType);
}
public override SchemaProvider.ISchemaProvider GetSchemaProvider()
{
return new MySqlSchemaProvider(this);
}
public override ISqlBuilder CreateSqlBuilder(MappingSchema mappingSchema)
{
return new MySqlSqlBuilder(this, mappingSchema, GetSqlOptimizer(), SqlProviderFlags);
}
private static MappingSchema GetMappingSchema(string name, MappingSchema providerSchema)
{
return name switch
{
ProviderName.MySqlConnector => new MySqlMappingSchema.MySqlConnectorMappingSchema(providerSchema),
_ => new MySqlMappingSchema.MySqlOfficialMappingSchema(providerSchema),
};
}
readonly ISqlOptimizer _sqlOptimizer;
public override ISqlOptimizer GetSqlOptimizer()
{
return _sqlOptimizer;
}
#if !NETFRAMEWORK
public override bool? IsDBNullAllowed(IDataReader reader, int idx)
{
return true;
}
#endif
public override void SetParameter(DataConnection dataConnection, IDbDataParameter parameter, string name, DbDataType dataType, object? value)
{
switch (dataType.DataType)
{
case DataType.Decimal :
case DataType.VarNumeric:
if (Adapter.MySqlDecimalGetter != null && value != null && value.GetType() == Adapter.MySqlDecimalType)
value = Adapter.MySqlDecimalGetter(value);
break;
}
base.SetParameter(dataConnection, parameter, name, dataType, value);
}
protected override void SetParameterType(DataConnection dataConnection, IDbDataParameter parameter, DbDataType dataType)
{
// VarNumeric - mysql.data trims fractional part
// Date/DateTime2 - mysql.data trims time part
switch (dataType.DataType)
{
case DataType.VarNumeric: parameter.DbType = DbType.Decimal; return;
case DataType.Date:
case DataType.DateTime2 : parameter.DbType = DbType.DateTime; return;
case DataType.BitArray : parameter.DbType = DbType.UInt64; return;
}
base.SetParameterType(dataConnection, parameter, dataType);
}
#region BulkCopy
public override BulkCopyRowsCopied BulkCopy<T>(
ITable<T> table, BulkCopyOptions options, IEnumerable<T> source)
{
if (source == null)
throw new ArgumentException(nameof(source));
return new MySqlBulkCopy(this).BulkCopy(
options.BulkCopyType == BulkCopyType.Default ? MySqlTools.DefaultBulkCopyType : options.BulkCopyType,
table,
options,
source);
}
public override Task<BulkCopyRowsCopied> BulkCopyAsync<T>(
ITable<T> table, BulkCopyOptions options, IEnumerable<T> source, CancellationToken cancellationToken)
{
if (source == null)
throw new ArgumentException(nameof(source));
return new MySqlBulkCopy(this).BulkCopyAsync(
options.BulkCopyType == BulkCopyType.Default ? MySqlTools.DefaultBulkCopyType : options.BulkCopyType,
table,
options,
source,
cancellationToken);
}
#if !NETFRAMEWORK
public override Task<BulkCopyRowsCopied> BulkCopyAsync<T>(
ITable<T> table, BulkCopyOptions options, IAsyncEnumerable<T> source, CancellationToken cancellationToken)
{
if (source == null)
throw new ArgumentException(nameof(source));
return new MySqlBulkCopy(this).BulkCopyAsync(
options.BulkCopyType == BulkCopyType.Default ? MySqlTools.DefaultBulkCopyType : options.BulkCopyType,
table,
options,
source,
cancellationToken);
}
#endif
#endregion
}
}
| 32.554217 | 144 | 0.73057 | [
"MIT"
] | Edward-Alchikha/linq2db | Source/LinqToDB/DataProvider/MySql/MySqlDataProvider.cs | 5,241 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.OleDb; // Ole DB
namespace TFR_cons
{
class Program
{
static void Main(string[] args)
{
//Console.WriteLine("Hello from MDB tutorial file!");
//DataBase.DBCreate();
//DataBase.DBReadTable();
//Smartcom.Begin();
//ArraySync.GenerateArray();
Console.ReadKey();
}
}
}
| 16.111111 | 56 | 0.682759 | [
"MIT"
] | dacoders77/TFR | MDB_access for tfr/Program.cs | 437 | C# |
using System;
using System.ComponentModel.Design;
using System.Windows.Forms;
using Microsoft.VisualStudio.Shell;
using WebLinter;
namespace WebLinterVsix
{
internal sealed class ResetConfigFilesCommand
{
private readonly Package _package;
private ResetConfigFilesCommand(Package package)
{
_package = package;
OleMenuCommandService commandService = ServiceProvider.GetService(typeof(IMenuCommandService)) as OleMenuCommandService;
var menuCommandID = new CommandID(PackageGuids.ConfigFileCmdSet, PackageIds.ResetConfigFiles);
var menuItem = new OleMenuCommand(ResetConfigurationFiles, menuCommandID);
commandService.AddCommand(menuItem);
}
public static ResetConfigFilesCommand Instance { get; private set; }
private IServiceProvider ServiceProvider
{
get { return _package; }
}
public static void Initialize(Package package)
{
Instance = new ResetConfigFilesCommand(package);
}
private async void ResetConfigurationFiles(object sender, EventArgs e)
{
string msg = "This will reset the configuration for all the linters to their defaults.\n\nDo you wish to continue?";
var result = MessageBox.Show(msg, Vsix.Name, MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (result == DialogResult.Yes)
{
await LinterService.EnsureDefaultsAsync(true);
WebLinterPackage.Settings.ResetSettings();
WebLinterPackage.Dte.StatusBar.Text = "Web Linter configuration files have been reset";
Telemetry.TrackEvent($"VS Reset Configs");
}
}
}
}
| 34.72549 | 132 | 0.664032 | [
"Apache-2.0"
] | madskristensen/WebAnalyzer | src/WebLinterVsix/Commnads/ResetConfigFilesCommand.cs | 1,773 | C# |
using Microsoft.AspNetCore.Mvc.ViewFeatures;
using Newtonsoft.Json;
namespace Michaelsoft.BodyGuard.Common.Extensions
{
public static class TempDataExtension
{
/// <summary>
/// Sets an object into the TempData by first serializing it to JSON.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="tempData"></param>
/// <param name="key"></param>
/// <param name="value"></param>
public static void Set<T>(this ITempDataDictionary tempData,
string key,
T value) where T : class
{
tempData[key] = JsonConvert.SerializeObject(value);
}
/// <summary>
/// Gets an object from the TempData by deserializing it from JSON.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="tempData"></param>
/// <param name="key"></param>
/// <returns></returns>
public static T Get<T>(this ITempDataDictionary tempData,
string key) where T : class, new()
{
tempData.TryGetValue(key, out var o);
return o == null ? new T() : JsonConvert.DeserializeObject<T>((string) o);
}
}
} | 34.210526 | 86 | 0.536154 | [
"MIT"
] | michaeldisaro/BodyGuard | Michaelsoft.BodyGuard.Common/Extensions/TempDataExtension.cs | 1,302 | C# |
using System;
namespace PowerForensics.Windows.Registry
{
/// <summary>
///
/// </summary>
public class SecurityDescriptor
{
#region Enums
/// <summary>
///
/// </summary>
[Flags]
public enum SECURITY_KEY_CONTROLS
{
/// <summary>
///
/// </summary>
SeOwnerDefaulted = 0x0001,
/// <summary>
///
/// </summary>
SeGroupDefaulted = 0x0002,
/// <summary>
///
/// </summary>
SeDaclPresent = 0x0004,
/// <summary>
///
/// </summary>
SeDaclDefaulted = 0x0008,
/// <summary>
///
/// </summary>
SeSaclPresent = 0x0010,
/// <summary>
///
/// </summary>
SeSaclDefaulted = 0x0020,
/// <summary>
///
/// </summary>
SeDaclAutoInheritReq = 0x0100,
/// <summary>
///
/// </summary>
SeSaclAutoInheritReq = 0x0200,
/// <summary>
///
/// </summary>
SeDaclAutoInherited = 0x0400,
/// <summary>
///
/// </summary>
SeSaclAutoInherited = 0x0800,
/// <summary>
///
/// </summary>
SeDaclProtected = 0x1000,
/// <summary>
///
/// </summary>
SeSaclProtected = 0x2000,
/// <summary>
///
/// </summary>
SeRmControlValid = 0x4000,
/// <summary>
///
/// </summary>
SeSelfRelative = 0x8000,
}
#endregion Enums
#region Properties
/// <summary>
///
/// </summary>
public readonly SECURITY_KEY_CONTROLS Control;
internal readonly uint OwnerOffset;
internal readonly uint GroupOffset;
internal readonly uint SACLOffset;
internal readonly uint DACLOffset;
/// <summary>
///
/// </summary>
public readonly byte[] Owner;
/// <summary>
///
/// </summary>
public readonly byte[] Group;
/// <summary>
///
/// </summary>
public readonly byte[] SACL;
/// <summary>
///
/// </summary>
public readonly byte[] DACL;
#endregion Properties
#region Constructors
internal SecurityDescriptor(byte[] bytes)
{
Control = (SECURITY_KEY_CONTROLS)BitConverter.ToUInt16(bytes, 0x02);
OwnerOffset = BitConverter.ToUInt32(bytes, 0x04);
GroupOffset = BitConverter.ToUInt32(bytes, 0x08);
SACLOffset = BitConverter.ToUInt32(bytes, 0x0C);
DACLOffset = BitConverter.ToUInt32(bytes, 0x10);
Owner = Helper.GetSubArray(bytes, (int)OwnerOffset, 0x10);
Group = Helper.GetSubArray(bytes, (int)GroupOffset, 0x0C);
SACL = Helper.GetSubArray(bytes, (int)SACLOffset, 0x08);
DACL = Helper.GetSubArray(bytes, (int)DACLOffset, 0x84);
}
#endregion Constructors
}
} | 23.275862 | 80 | 0.443556 | [
"MIT"
] | Cyberdeep/PowerForensics | src/PowerForensicsCore/src/PowerForensics.Windows.Registry/Cells/SecurityDescriptor.cs | 3,377 | C# |
// Copyright (c) Bruno Brant. All rights reserved.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
using Sprache;
namespace TinyJavaParser
{
/// <summary>
/// Extensions for Enum types.
/// </summary>
public static class EnumExtensions
{
/// <summary>
/// Creates a sprache parser for an <see cref="Enum"/>.
/// </summary>
/// <typeparam name="T">The enum type.</typeparam>
/// <returns>The sprache <see cref="Parser{T}"/> that parsers the enum.</returns>
public static Parser<T> CreateParser<T>()
where T : struct, Enum
{
return
GetFields<T>()
.Select(field => new { value = (T)field.GetRawConstantValue()!, description = field.GetDescription() })
.OrderByDescending(_ => _.description.Length) // must match first longer strings to avoid mistakes
.Select(_ => Parse.String(_.description).Token().Return(_.value))
.Aggregate((x, y) => x.Or(y));
}
/// <summary>
/// Gets value of the <see cref="DescriptionAttribute"/> that annotates the enum value.
/// </summary>
/// <param name="fieldInfo">
/// A FieldInfo metadata of a enum member.
/// </param>
/// <returns>
/// A string that is the value of the <see cref="DescriptionAttribute"/> that annotates the field.
/// </returns>
public static string GetDescription(this FieldInfo fieldInfo)
{
return fieldInfo.GetCustomAttributes<DescriptionAttribute>().SingleOrDefault()?.Description
?? throw new Exception($"Field {fieldInfo.Name} doesn't have a {nameof(DescriptionAttribute)}.");
}
/// <summary>
/// Gets the <see cref="FieldInfo"/> for all enum members.
/// </summary>
/// <typeparam name="T">
/// The type of the enum.
/// </typeparam>
/// <returns>
/// Enumerates each field of the enum.
/// </returns>
public static IEnumerable<FieldInfo> GetFields<T>()
where T : struct, Enum
{
var typeOfT = typeof(T);
return Enum.GetNames<T>().Select(name => typeOfT.GetField(name)!);
}
}
}
| 31 | 107 | 0.65738 | [
"MIT"
] | bruno-brant/dotnet-java-dependency-analyser | src/TinyJavaParser/EnumExtensions.cs | 2,046 | C# |
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Features;
namespace Positron.Server.Hosting.Internal
{
internal abstract class RequestFrame : IFeatureCollection
{
private Dictionary<Type, object> _extraFeatures;
public IHttpRequestFeature Request { get; }
public PositronResponse Response { get; }
protected RequestFrame(IHttpRequestFeature requestContext)
{
Request = requestContext;
Response = new PositronResponse();
}
public abstract Task ProcessRequestAsync();
protected void InitializeHeaders()
{
if (Request.Headers == null)
{
Request.Headers = new HeaderDictionary();
}
if (Response.Headers == null)
{
Response.Headers = new HeaderDictionary();
}
}
protected void InitializeStreams()
{
if (Response.Body == null)
{
Response.Body = new MemoryStream();
}
}
#region Features
private IEnumerable<KeyValuePair<Type, object>> GetFeatures()
{
yield return new KeyValuePair<Type, object>(typeof(IHttpRequestFeature), Request);
yield return new KeyValuePair<Type, object>(typeof(IHttpResponseFeature), Response);
if (_extraFeatures != null)
{
foreach (var pair in _extraFeatures)
{
yield return pair;
}
}
}
public IEnumerator<KeyValuePair<Type, object>> GetEnumerator()
{
return GetFeatures().GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
public TFeature Get<TFeature>()
{
return (TFeature) this[typeof(TFeature)];
}
public void Set<TFeature>(TFeature instance)
{
this[typeof(TFeature)] = instance;
}
public bool IsReadOnly => false;
public int Revision { get; private set; }
public object this[Type key]
{
get
{
if (key == typeof(IHttpRequestFeature))
{
return Request;
}
if (key == typeof(IHttpResponseFeature))
{
return Response;
}
if (_extraFeatures != null)
{
object extra;
if (_extraFeatures.TryGetValue(key, out extra))
{
return extra;
}
}
return null;
}
set
{
if (key == typeof(IHttpRequestFeature))
{
throw new NotImplementedException();
}
if (key == typeof(IHttpResponseFeature))
{
throw new NotImplementedException();
}
if (_extraFeatures == null)
{
_extraFeatures = new Dictionary<Type, object>(2);
}
_extraFeatures[key] = value;
}
}
#endregion
}
}
| 26.545455 | 96 | 0.488584 | [
"Apache-2.0"
] | CenterEdge/Positron | src/Positron.Server.Hosting/Internal/RequestFrame.cs | 3,506 | C# |
using System;
namespace Api.Models
{
public class Beer
{
public int Id { get; set; }
public string Name { get; set; }
public decimal AlcoholVol { get; set; }
public int BreweryId { get; set; }
public Brewery Brewery { get; set; }
public Uri ImageUri { get; set; }
}
}
| 16.75 | 47 | 0.552239 | [
"MIT"
] | BuildItBusk/Alecademy | Api/Models/Beer.cs | 337 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.Collections.Generic;
using System.Linq;
namespace Azure.Core.TestFramework
{
public class MockRequest : Request
{
public MockRequest()
{
ClientRequestId = Guid.NewGuid().ToString();
}
private readonly Dictionary<string, List<string>> _headers = new Dictionary<string, List<string>>(StringComparer.OrdinalIgnoreCase);
public bool IsDisposed { get; private set; }
public override RequestContent Content
{
get { return base.Content; }
set
{
if (value != null && value.TryComputeLength(out long length))
{
_headers["Content-Length"] = new List<string> { length.ToString() };
}
else
{
_headers.Remove("Content-Length");
}
base.Content = value;
}
}
#if HAS_INTERNALS_VISIBLE_CORE
internal
#endif
protected override void AddHeader(string name, string value)
{
if (!_headers.TryGetValue(name, out List<string> values))
{
_headers[name] = values = new List<string>();
}
values.Add(value);
}
#if HAS_INTERNALS_VISIBLE_CORE
internal
#endif
protected override bool TryGetHeader(string name, out string value)
{
if (_headers.TryGetValue(name, out List<string> values))
{
value = JoinHeaderValue(values);
return true;
}
value = null;
return false;
}
#if HAS_INTERNALS_VISIBLE_CORE
internal
#endif
protected override bool TryGetHeaderValues(string name, out IEnumerable<string> values)
{
var result = _headers.TryGetValue(name, out List<string> valuesList);
values = valuesList;
return result;
}
#if HAS_INTERNALS_VISIBLE_CORE
internal
#endif
protected override bool ContainsHeader(string name)
{
return TryGetHeaderValues(name, out _);
}
#if HAS_INTERNALS_VISIBLE_CORE
internal
#endif
protected override bool RemoveHeader(string name)
{
return _headers.Remove(name);
}
#if HAS_INTERNALS_VISIBLE_CORE
internal
#endif
protected override IEnumerable<HttpHeader> EnumerateHeaders() => _headers.Select(h => new HttpHeader(h.Key, JoinHeaderValue(h.Value)));
private static string JoinHeaderValue(IEnumerable<string> values)
{
return string.Join(",", values);
}
public override string ClientRequestId { get; set; }
public override string ToString() => $"{Method} {Uri}";
public override void Dispose()
{
IsDisposed = true;
}
}
}
| 26.482456 | 143 | 0.572044 | [
"MIT"
] | AzureDataBox/azure-sdk-for-net | sdk/core/Azure.Core.TestFramework/src/MockRequest.cs | 3,021 | C# |
using System;
using System.Runtime.Serialization;
namespace LibGit2Sharp
{
/// <summary>
/// The exception that is thrown when the provided specification cannot uniquely identify a reference, an object or a path.
/// </summary>
[Serializable]
public class AmbiguousSpecificationException : LibGit2SharpException
{
/// <summary>
/// Initializes a new instance of the <see cref = "AmbiguousSpecificationException" /> class.
/// </summary>
public AmbiguousSpecificationException()
{
}
/// <summary>
/// Initializes a new instance of the <see cref = "AmbiguousSpecificationException" /> class with a specified error message.
/// </summary>
/// <param name = "message">A message that describes the error. </param>
public AmbiguousSpecificationException(string message)
: base(message)
{
}
/// <summary>
/// Initializes a new instance of the <see cref = "AmbiguousSpecificationException" /> class with a specified error message and a reference to the inner exception that is the cause of this exception.
/// </summary>
/// <param name = "message">The error message that explains the reason for the exception. </param>
/// <param name = "innerException">The exception that is the cause of the current exception. If the <paramref name = "innerException" /> parameter is not a null reference, the current exception is raised in a catch block that handles the inner exception.</param>
public AmbiguousSpecificationException(string message, Exception innerException)
: base(message, innerException)
{
}
/// <summary>
/// Initializes a new instance of the <see cref = "AmbiguousSpecificationException" /> class with a serialized data.
/// </summary>
/// <param name = "info">The <see cref="SerializationInfo "/> that holds the serialized object data about the exception being thrown.</param>
/// <param name = "context">The <see cref="StreamingContext"/> that contains contextual information about the source or destination.</param>
protected AmbiguousSpecificationException(SerializationInfo info, StreamingContext context)
: base(info, context)
{
}
}
}
| 48.020408 | 270 | 0.660433 | [
"MIT"
] | improvedk/libgit2sharp | LibGit2Sharp/AmbiguousSpecificationException.cs | 2,353 | C# |
namespace FirstTest.Areas.HelpPage.ModelDescriptions
{
public class EnumValueDescription
{
public string Documentation { get; set; }
public string Name { get; set; }
public string Value { get; set; }
}
} | 21.909091 | 52 | 0.643154 | [
"MIT"
] | romeoroman/first-test | FirstTest/Areas/HelpPage/ModelDescriptions/EnumValueDescription.cs | 241 | C# |
// Copyright 2020 New Relic, Inc. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
#if NETFRAMEWORK
using NewRelic.Core.Logging;
using System;
using System.Collections.Concurrent;
using System.Diagnostics;
using System.Linq;
namespace NewRelic.SystemInterfaces
{
public interface IPerformanceCounterProxy : IDisposable
{
float NextValue();
}
public class PerformanceCounterProxy : IPerformanceCounterProxy
{
private readonly PerformanceCounter _counter;
private bool _counterIsDisposed = false;
public PerformanceCounterProxy(string categoryName, string counterName, string instanceName)
{
_counter = new PerformanceCounter(categoryName, counterName, instanceName);
}
public float NextValue()
{
return _counter.NextValue();
}
public void Dispose()
{
if (_counter != null && !_counterIsDisposed)
{
_counter.Dispose();
_counterIsDisposed = true;
}
}
}
public interface IPerformanceCounterCategoryProxy
{
string[] GetInstanceNames();
}
public class PerformanceCounterCategoryProxy : IPerformanceCounterCategoryProxy
{
private readonly PerformanceCounterCategory _performanceCounterCategory;
public PerformanceCounterCategoryProxy(string categoryName)
{
_performanceCounterCategory = new PerformanceCounterCategory(categoryName);
}
public string[] GetInstanceNames()
{
return _performanceCounterCategory.GetInstanceNames();
}
}
public interface IPerformanceCounterProxyFactory
{
IPerformanceCounterProxy CreatePerformanceCounterProxy(string categoryName, string counterName, string instanceName);
string GetCurrentProcessInstanceNameForCategory(string categoryName, string lastKnownName);
}
public class PerformanceCounterProxyFactory : IPerformanceCounterProxyFactory
{
public const string ProcessIdCounterName = "Process ID";
private readonly IProcessStatic _processStatic;
/// <summary>
/// Function used to create the performance counter category which is used to list the
/// instance names of the processes that are reporting information for that performance counter
/// category. This is dependency injected so that we can manipulate its behavior for testing purposes
/// </summary>
private readonly Func<string, IPerformanceCounterCategoryProxy> _createPerformanceCounterCategory;
/// <summary>
/// Function used to create the actual performance counter proxy.
/// This is dependency injected so that we can manipulate its behavior for testing purposes
/// Func params: categoryName, perfCounterName, instanceName
/// </summary>
private readonly Func<string, string, string, IPerformanceCounterProxy> _createPerformanceCounter;
public PerformanceCounterProxyFactory(IProcessStatic processStatic, Func<string, IPerformanceCounterCategoryProxy> performanceCounterCategoryProxyFactory, Func<string, string, string, IPerformanceCounterProxy> performanceCounterCreator)
{
_processStatic = processStatic;
_createPerformanceCounterCategory = performanceCounterCategoryProxyFactory;
_createPerformanceCounter = performanceCounterCreator;
}
/// <summary>
/// Used by dependency injection to resolve the factory for creating a perf counter category proxy
/// </summary>
/// <param name="categoryName"></param>
/// <returns></returns>
public static IPerformanceCounterCategoryProxy DefaultCreatePerformanceCounterCategoryProxy(string categoryName)
{
return new PerformanceCounterCategoryProxy(categoryName);
}
/// <summary>
/// Used by dependency injection to resolve the factory for creating a perf counter
/// </summary>
/// <param name="categoryName"></param>
/// <returns></returns>
public static IPerformanceCounterProxy DefaultCreatePerformanceCounterProxy(string categoryName, string counterName, string instanceName)
{
return new PerformanceCounterProxy(categoryName, counterName, instanceName);
}
/// <summary>
/// Responsible for obtaining the instance name for the current process for a perf counter
/// category.
/// </summary>
/// <returns>the instance name or NULL if one could not be identified.</returns>
/// <param name="categoryName"></param>
public string GetCurrentProcessInstanceNameForCategory(string categoryName, string lastKnownName)
{
var processName = _processStatic.GetCurrentProcess().ProcessName;
var pid = _processStatic.GetCurrentProcess().Id;
var result = GetInstanceNameForProcessAndCategory(categoryName, processName, pid, lastKnownName);
return result;
}
public IPerformanceCounterProxy CreatePerformanceCounterProxy(string categoryName, string counterName, string instanceName)
{
if (string.IsNullOrWhiteSpace(instanceName)) throw new ArgumentException(nameof(instanceName));
if (string.IsNullOrWhiteSpace(counterName)) throw new ArgumentException(nameof(counterName));
if (string.IsNullOrWhiteSpace(categoryName)) throw new ArgumentException(nameof(categoryName));
return _createPerformanceCounter(categoryName, counterName, instanceName);
}
/// <summary>
/// The instance name of a performance counter is a combination of the process Name and an index id to
/// uniquely identify it when multiple of the same process are running. For example "TestApp #1" pid=82, "TestApp #2" pid=134
/// are two instances of the same executable, TestApp. In order to determine if an instance matches a process,
/// an additional performance counter "Process ID" must be used which returns the PID of the process.
/// </summary>
/// <param name="perfCategoryName"></param>
/// <param name="processName"></param>
/// <param name="pid"></param>
/// <returns>The instance name that will be used to collect performance counter data for the process</returns>
private string GetInstanceNameForProcessAndCategory(string perfCategoryName, string processName, int pid, string lastKnownName)
{
var performanceCategory = _createPerformanceCounterCategory(perfCategoryName);
var instanceNames = performanceCategory.GetInstanceNames()
.Where(x => x.StartsWith(processName, StringComparison.OrdinalIgnoreCase))
.OrderByDescending(x => x == lastKnownName)
.ToList();
foreach (var instanceName in instanceNames)
{
try
{
using (var pcPid = _createPerformanceCounter(perfCategoryName, ProcessIdCounterName, instanceName))
{
if ((int)pcPid.NextValue() == pid)
{
return instanceName;
}
}
}
catch (UnauthorizedAccessException)
{
//The caller should handle this specificially. It indicates that the
//current user does not have access to pull performance counter values.
throw;
}
catch (Exception ex)
{
//Log a message here and continue because this instance may not be relevant to the process that we are looking for.
Log.Finest($"Error determining if instance '{instanceName}' is process '{processName}'({pid}). Error: {ex}");
}
}
//At this point a match was not found. The caller should handle accordingly
return null;
}
}
}
#endif
| 42.884817 | 244 | 0.656574 | [
"Apache-2.0"
] | JoshuaColeman/newrelic-dotnet-agent | src/NewRelic.Core/NewRelic.SystemInterfaces/PerformanceCounterProxy.cs | 8,191 | C# |
using System;
using Newtonsoft.Json;
namespace Infinity.Models
{
/// <summary>
/// The item changed in a Git commit.
/// </summary>
public class CommitItem
{
/// <summary>
/// The type of object changed (blob or tree).
/// </summary>
[JsonProperty("gitObjectType")]
public ObjectType Type { get; set; }
/// <summary>
/// Whether the item is a folder.
/// </summary>
public bool IsFolder { get; set; }
/// <summary>
/// The path to the changed item.
/// </summary>
public string Path { get; set; }
/// <summary>
/// The commit ID that changed this item.
/// </summary>
[JsonConverter(typeof(ObjectId.JsonConverter))]
public ObjectId CommitId { get; set; }
/// <summary>
/// The URL of the REST endpoint of the changed item.
/// </summary>
public Uri Url { get; set; }
}
}
| 25.051282 | 61 | 0.5261 | [
"Apache-2.0"
] | ethomson/infinity.net | Infinity/Models/CommitItem.cs | 979 | C# |
// Distrubuted under the MIT license
// ===================================================
// SharperMC uses the permissive MIT license.
//
// 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.
//
// ©Copyright SharperMC - 2020
using System;
using System.Collections;
using SharperMC.Core.Entity;
using SharperMC.Core.Enums;
using SharperMC.Core.Utils;
using SharperMC.Core.Utils.Items;
using SharperMC.Core.Utils.Vectors;
using SharperMC.Core.Worlds;
namespace SharperMC.Core.Items
{
/// <summary>
/// Items are objects which only exist within the player's inventory and hands - which means, they cannot be placed in
/// the game world. Some items simply place blocks or entities into the game world when used. They are thus an item
/// when in the inventory and a block when placed. Some examples of objects which exhibit these properties are item
/// frames, which turn into an entity when placed, and beds, which turn into a group of blocks when placed. When
/// equipped, items (and blocks) briefly display their names above the HUD.
/// </summary>
public class Item
{
private short _fuelEfficiency;
internal Item(ushort id, byte metadata)
{
Id = id;
Metadata = metadata;
ItemMaterial = ItemMaterial.None;
ItemType = ItemType.Item;
IsUsable = false;
MaxStackSize = 64;
IsBlock = false;
}
protected Item(ushort id, byte metadata, short fuelEfficiency) : this(id, metadata)
{
FuelEfficiency = fuelEfficiency;
}
public ushort Id { get; set; }
public ItemMaterial ItemMaterial { get; set; }
public ItemType ItemType { get; set; }
public byte Metadata { get; set; }
public bool IsUsable { get; set; }
public int MaxStackSize { get; set; }
public ItemStack[] CraftingItems { get; set; }
public bool IsBlock { get; set; }
protected short FuelEfficiency
{
set { _fuelEfficiency = value; }
}
public virtual void UseItem(Level world, Player player, Vector3 blockCoordinates, BlockFace face)
{
}
protected Vector3 GetNewCoordinatesFromFace(Vector3 target, BlockFace face)
{
switch (face)
{
case BlockFace.NegativeY:
target.Y--;
break;
case BlockFace.PositiveY:
target.Y++;
break;
case BlockFace.NegativeZ:
target.Z--;
break;
case BlockFace.PositiveZ:
target.Z++;
break;
case BlockFace.NegativeX:
target.X--;
break;
case BlockFace.PositiveX:
target.X++;
break;
}
return target;
}
public int GetDamage()
{
switch (ItemType)
{
case ItemType.Sword:
return GetSwordDamage(ItemMaterial);
case ItemType.Item:
return 1;
case ItemType.Axe:
return GetAxeDamage(ItemMaterial);
case ItemType.PickAxe:
return GetPickAxeDamage(ItemMaterial);
case ItemType.Shovel:
return GetShovelDamage(ItemMaterial);
default:
return 1;
}
}
protected int GetSwordDamage(ItemMaterial itemMaterial)
{
switch (itemMaterial)
{
case ItemMaterial.None:
return 1;
case ItemMaterial.Gold:
case ItemMaterial.Wood:
return 5;
case ItemMaterial.Stone:
return 6;
case ItemMaterial.Iron:
return 7;
case ItemMaterial.Diamond:
return 8;
default:
return 1;
}
}
private int GetAxeDamage(ItemMaterial itemMaterial)
{
return GetSwordDamage(itemMaterial) - 1;
}
private int GetPickAxeDamage(ItemMaterial itemMaterial)
{
return GetSwordDamage(itemMaterial) - 2;
}
private int GetShovelDamage(ItemMaterial itemMaterial)
{
return GetSwordDamage(itemMaterial) - 3;
}
public virtual short GetFuelEfficiency()
{
return _fuelEfficiency;
}
public virtual Item GetSmelt()
{
return null;
}
public ItemStack GetItemStack()
{
return new ItemStack((short)Id, 1, Metadata);
}
public byte ConvertToByte(BitArray bits)
{
if (bits.Count != 8)
{
throw new ArgumentException("bits");
}
byte[] bytes = new byte[1];
bits.CopyTo(bytes, 0);
return bytes[0];
}
}
} | 26.856383 | 123 | 0.692414 | [
"MIT"
] | SharperMC/SharperMC | SharperMC/SharperMC.Core/SharperMC.Core/Items/Item.cs | 5,060 | C# |
// ReSharper disable All
namespace OpenTl.Schema
{
using System;
using System.Collections;
using System.Text;
using OpenTl.Schema;
using OpenTl.Schema.Serialization.Attributes;
[Serialize(0xa187d66f)]
public sealed class TSendMessageRecordVideoAction : ISendMessageAction
{
}
}
| 16.277778 | 71 | 0.778157 | [
"MIT"
] | zzz8415/OpenTl.Schema | src/OpenTl.Schema/_generated/_Entities/SendMessageAction/TSendMessageRecordVideoAction.cs | 295 | C# |
using System;
using System.Runtime.InteropServices;
public class Taskbar
{
private ITaskbarList3 Instance = (ITaskbarList3)new TaskBarCommunication();
public IntPtr Handle { get; set; }
public Taskbar(IntPtr handle) => Handle = handle;
[ComImportAttribute]
[InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
[GuidAttribute("ea1afb91-9e28-4b86-90e9-9e9f8a5eefaf")]
private interface ITaskbarList3
{
// ITaskbarList
[PreserveSig] void HrInit();
[PreserveSig] void AddTab(IntPtr hwnd);
[PreserveSig] void DeleteTab(IntPtr hwnd);
[PreserveSig] void ActivateTab(IntPtr hwnd);
[PreserveSig] void SetActiveAlt(IntPtr hwnd);
// ITaskbarList2
[PreserveSig] void MarkFullscreenWindow(IntPtr hwnd, [MarshalAs(UnmanagedType.Bool)] bool fFullscreen);
// ITaskbarList3
[PreserveSig] void SetProgressValue(IntPtr hwnd, UInt64 ullCompleted, UInt64 ullTotal);
[PreserveSig] void SetProgressState(IntPtr hwnd, TaskbarStates state);
}
[ComImportAttribute]
[ClassInterfaceAttribute(ClassInterfaceType.None)]
[GuidAttribute("56FDF344-FD6D-11d0-958A-006097C9A090")]
private class TaskBarCommunication { }
public void SetState(TaskbarStates taskbarState)
{
Instance.SetProgressState(Handle, taskbarState);
}
public void SetValue(double progressValue, double progressMax)
{
Instance.SetProgressValue(Handle, (UInt64)progressValue, (UInt64)progressMax);
}
}
public enum TaskbarStates
{
NoProgress = 0,
Indeterminate = 0x1,
Normal = 0x2,
Error = 0x4,
Paused = 0x8
} | 31.320755 | 111 | 0.706024 | [
"MIT"
] | floppyD/mpv.net | mpv.net/Native/Taskbar.cs | 1,662 | C# |
using System;
using System.Collections.Generic;
namespace GrafFeladat_CSharp
{
/// <summary>
/// Irányítatlan, egyszeres gráf.
/// </summary>
class Graf
{
int csucsokSzama;
/// <summary>
/// A gráf élei.
/// Ha a lista tartalmaz egy(A, B) élt, akkor tartalmaznia kell
/// a(B, A) vissza irányú élt is.
/// </summary>
readonly List<El> elek = new List<El>();
/// <summary>
/// A gráf csúcsai.
/// A gráf létrehozása után új csúcsot nem lehet felvenni.
/// </summary>
readonly List<Csucs> csucsok = new List<Csucs>();
/// <summary>
/// Létehoz egy úgy, N pontú gráfot, élek nélkül.
/// </summary>
/// <param name="csucsok">A gráf csúcsainak száma</param>
public Graf(int csucsok)
{
this.csucsokSzama = csucsok;
// Minden csúcsnak hozzunk létre egy új objektumot
for (int i = 0; i < csucsok; i++)
{
this.csucsok.Add(new Csucs(i));
}
}
/// <summary>
/// Hozzáad egy új élt a gráfhoz.
/// Mindkét csúcsnak érvényesnek kell lennie:
/// 0 <= cs < csúcsok száma.
/// </summary>
/// <param name="cs1">Az él egyik pontja</param>
/// <param name="cs2">Az él másik pontja</param>
public void Hozzaad(int cs1, int cs2)
{
if (cs1 < 0 || cs1 >= csucsokSzama ||
cs2 < 0 || cs2 >= csucsokSzama)
{
throw new ArgumentOutOfRangeException("Hibas csucs index");
}
// Ha már szerepel az él, akkor nem kell felvenni
foreach (var el in elek)
{
if (el.Csucs1 == cs1 && el.Csucs2 == cs2)
{
return;
}
}
elek.Add(new El(cs1, cs2));
elek.Add(new El(cs2, cs1));
}
public void Torles(int cs1, int cs2)
{
if (cs1 < 0 || cs1 >= csucsokSzama ||
cs2 < 0 || cs2 >= csucsokSzama)
{
throw new ArgumentOutOfRangeException("Hibas csucs index");
}
for (int i = 0; i < elek.Count-1; i++)
{
var el = elek[i];
if ((el.Csucs1 == cs1 && el.Csucs2 == cs2) || (el.Csucs1 == cs2 && el.Csucs2 == cs1))
{
elek.Remove(el);
el = elek[i];
elek.Remove(el);
}
}
}
public void SzelessegiBejar(int kezdopont)
{
// Kezdetben egy pontot sem jártunk be
HashSet<int> bejart = new HashSet<int>();
// A következőnek vizsgált elem a kezdőpont
Queue<int> kovetkezok = new Queue<int>();
kovetkezok.Enqueue(kezdopont);
bejart.Add(kezdopont);
// Amíg van következő, addig megyünk
while (kovetkezok.Count != 0)
{
// A sor elejéről vesszük ki
int k = kovetkezok.Dequeue();
// Elvégezzük a bejárási műveletet, pl. a konzolra kiírást:
Console.WriteLine(this.csucsok[k]);
foreach (var el in this.elek)
{
// Megkeressük azokat az éleket, amelyek k-ból indulnak
// Ha az él másik felét még nem vizsgáltuk, akkor megvizsgáljuk
if ((el.Csucs1 == k) && (!bejart.Contains(el.Csucs2)))
{
// A sor végére és a bejártak közé szúrjuk be
kovetkezok.Enqueue(el.Csucs2);
bejart.Add(el.Csucs2);
}
}
// Jöhet a sor szerinti következő elem
}
}
public void MelysegiBejar(int kezdopont)
{
// Kezdetben egy pontot sem jártunk be
HashSet<int> bejart = new HashSet<int>();
// A következőnek vizsgált elem a kezdőpont
Stack<int> kovetkezok = new Stack<int>();
kovetkezok.Push(kezdopont);
bejart.Add(kezdopont);
// Amíg van következő, addig megyünk
while (kovetkezok.Count != 0)
{
// A verem tetejéről vesszük le
int k = kovetkezok.Pop();
// Elvégezzük a bejárási műveletet, pl. a konzolra kiírást:
Console.WriteLine(this.csucsok[k]);
foreach (var el in this.elek)
{
// Megkeressük azokat az éleket, amelyek k-ból indulnak
// Ha az él másik felét még nem vizsgáltuk, akkor megvizsgáljuk
if ((el.Csucs1 == k) && (!bejart.Contains(el.Csucs2)))
{
// A verem tetejére és a bejártak közé adjuk hozzá
kovetkezok.Push(el.Csucs2);
bejart.Add(el.Csucs2);
}
}
// Jöhet a sor szerinti következő elem
}
}
public bool Osszefuggo()
{
HashSet<int> bejart = new HashSet<int>();
Queue<int> kovetkezok = new Queue<int>();
kovetkezok.Enqueue(0); // Tetszőleges, mondjuk 0 kezdőpont
bejart.Add(0);
while (kovetkezok.Count != 0)
{
int k = kovetkezok.Dequeue();
// Bejárás közben nem kell semmit csinálni
foreach (var el in this.elek)
{
if ((el.Csucs1 == k) && (!bejart.Contains(el.Csucs2)))
{
kovetkezok.Enqueue(el.Csucs2);
bejart.Add(el.Csucs2);
}
}
}
// A végén megvizsgáljuk, hogy minden pontot bejártunk-e
if (bejart.Count == this.csucsokSzama)
{
return true;
}
else
{
return false;
}
}
public Graf Feszitofa()
{
// Új, kezdetben él nélküli gráf
Graf fa = new Graf(this.csucsokSzama);
// Bejáráshoz szükséges adatszerkezetek
HashSet<int> bejart = new HashSet<int>();
Queue<int> kovetkezok = new Queue<int>();
// Tetszőleges, mondjuk 0 kezdőpont
kovetkezok.Enqueue(0);
bejart.Add(0);
// Szélességi bejárás
while (kovetkezok.Count != 0)
{
int aktualisCsucs = kovetkezok.Dequeue();
foreach (var el in this.elek)
{
if (el.Csucs1 == aktualisCsucs)
{
if (!bejart.Contains(el.Csucs2))
{
bejart.Add(el.Csucs2);
kovetkezok.Enqueue(el.Csucs2);
// A fába is vegyük bele az élt
fa.Hozzaad(el.Csucs1, el.Csucs2);
}
}
}
}
// Az eredményül kapott gráf az eredeti gráf feszítőfája
return fa;
}
public override string ToString()
{
string str = "Csucsok:\n";
foreach (var cs in csucsok)
{
str += cs + "\n";
}
str += "Elek:\n";
foreach (var el in elek)
{
str += el + "\n";
}
return str;
}
}
} | 31.379032 | 101 | 0.443845 | [
"MIT"
] | FullPXL/GrafFeladat_CSharp | GrafFeladat_CSharp/Graf.cs | 7,939 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace KisiKayitOtomasyon.Properties
{
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0")]
internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase
{
private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
public static Settings Default
{
get
{
return defaultInstance;
}
}
}
}
| 34.612903 | 151 | 0.584343 | [
"Unlicense"
] | ahmetas/kisi-kayit-otomasyon | KisiKayitOtomasyon/KisiKayitOtomasyon/Properties/Settings.Designer.cs | 1,075 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.