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 Daddoon.Blazor.Xam.Common.Interfaces;
using Daddoon.Blazor.Xam.Interop;
using System;
using System.IO;
using System.IO.Compression;
using System.Net;
using System.Runtime.CompilerServices;
using Waher.Networking.HTTP;
using Xamarin.Forms;
[assembly: InternalsVisibleTo("Daddoon.Blazor.Xamarin.Android")]
[assembly: InternalsVisibleTo("Daddoon.Blazor.Xamarin.UWP")]
namespace Daddoon.Blazor.Xam.Services
{
public static class WebApplicationFactory
{
private static HttpServer server;
private static bool _isStarted = false;
private static bool IsStarted()
{
return _isStarted;
}
private static Func<Stream> _appResolver = null;
/// <summary>
/// Register how you get the Stream to your Blazor zipped application
/// <para>For a performant unique entry point, getting a Stream from an</para>
/// <para>Assembly manifest resource stream is recommended.</para>
/// <para></para>
/// <para>See <see cref="System.Reflection.Assembly.GetManifestResourceStream(string)"/></para>
/// </summary>
public static void RegisterAppStreamResolver(Func<Stream> resolver)
{
_appResolver = resolver;
//Calling Init if not yet done. This will be a no-op if already called
//We register init like this, as because of some linker problem with Xamarin,
//we need to call the initializer from the "specialized project" (like Android)
//that init itself and his components/renderer, then initializing this
//
//As iOS and UWP doesn't need a specific initialize at the moment but we may need
//to call a generic init, the generic init is call in RegisterAppStream
Init();
}
internal static MemoryStream GetResourceStream(string path)
{
if (_appResolver == null)
{
throw new NullReferenceException("The Blazor app resolver was not set! Please call WebApplicationFactory.RegisterAppStreamResolver method before launching your app");
}
using (Stream dataSource = _appResolver())
{
ZipArchive archive = null;
archive = new ZipArchive(dataSource, ZipArchiveMode.Read);
//data will contain found file output as stream
MemoryStream data = new MemoryStream();
ZipArchiveEntry entry = archive.GetEntry(path);
if (entry != null)
{
entry.Open().CopyTo(data);
data.Seek(0, SeekOrigin.Begin);
}
else
{
data?.Dispose();
return null;
}
archive?.Dispose();
return data;
}
}
internal static byte[] GetResource(string path)
{
MemoryStream content = GetResourceStream(path);
if (content == null)
return null;
byte[] resultSet = content?.ToArray();
content?.Dispose();
return resultSet;
}
internal static string GetContentType(string path)
{
if (path.EndsWith(".wasm"))
{
return "application/wasm";
}
if (path.EndsWith(".dll"))
{
return "application/octet-stream";
}
//No critical mimetypes to check
return MimeTypes.GetMimeType(path);
}
private const int HttpPort = 8888;
public static int GetHttpPort()
{
return HttpPort;
}
public static string GetBaseURL()
{
return $"http://localhost:{GetHttpPort()}";
}
internal static string GetQueryPath(string path)
{
path = WebUtility.UrlDecode(path.TrimStart('/'));
if (string.IsNullOrEmpty(path))
{
//We are calling the index page. We must call index.html but hide it from url for Blazor routing.
path = "index.html";
}
return path;
}
internal static void ManageRequest(IWebResponse response)
{
response.SetEncoding("UTF-8");
string path = GetQueryPath(response.GetRequestedPath());
var content = GetResourceStream(path);
response.AddResponseHeader("Cache-Control", "no-cache");
response.AddResponseHeader("Access-Control-Allow-Origin", GetBaseURL());
if (content == null)
{
//Content not found
response.SetStatutCode(404);
response.SetReasonPhrase("Not found");
response.SetMimeType("text/plain");
return;
}
response.SetStatutCode(200);
response.SetReasonPhrase("OK");
response.SetMimeType(GetContentType(path));
response.SetData(content);
}
private static bool _firstCall = true;
/// <summary>
/// Init the WebApplicationFactory with the given app stream resolver.
/// Shorthand for <see cref="WebApplicationFactory.RegisterAppStreamResolver" />
/// </summary>
/// <param name="appStreamResolver"></param>
internal static void Init(Func<Stream> appStreamResolver)
{
RegisterAppStreamResolver(appStreamResolver);
}
internal static void Init()
{
if (_firstCall)
{
//Register IBlazorXamarinDeviceService for getting base metadata for Blazor
DependencyService.Register<IBlazorXamarinDeviceService, BlazorXamarinDeviceService>();
//Do something in the future if required
_firstCall = false;
}
}
public static void StartWebServer()
{
Init(); //No-op if called twice
//Request are managed by the WebView on Android
if (Device.RuntimePlatform != Device.Android)
{
server = new HttpServer(HttpPort);
server.Register(string.Empty, (req, resp) =>
{
var response = new StdWebResponse(req, resp);
ManageRequest(response);
}, true, true);
return;
}
_isStarted = true;
}
public static void StopWebServer()
{
server?.Dispose();
server = null;
_isStarted = false;
}
}
}
| 32.07619
| 182
| 0.554632
|
[
"MIT"
] |
hippermoloo/Blazor.Xamarin
|
src/Daddoon.Blazor.Xamarin/Services/WebApplicationFactory.cs
| 6,738
|
C#
|
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Reflection;
namespace Google.Maps
{
public abstract class JsonCreationConverter<T> : JsonConverter
{
protected abstract T Create(Type objectType, JObject jsonObject);
public override bool CanConvert(Type objectType) => typeof(T).GetTypeInfo().IsAssignableFrom(objectType.GetTypeInfo());
public override object ReadJson(JsonReader reader,
Type objectType,
object existingValue,
JsonSerializer serializer)
{
var jsonObject = JObject.Load(reader);
var target = Create(objectType, jsonObject);
serializer.Populate(jsonObject.CreateReader(), target);
return target;
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) => throw new NotImplementedException();
}
}
| 28.931034
| 132
| 0.753278
|
[
"Apache-2.0"
] |
J0rgeSerran0/gmaps-api-net
|
src/Google.Maps/JsonCreationConverter.cs
| 841
|
C#
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class PauseMenu : MonoBehaviour
{
public GameObject Pause;
// Start is called before the first frame update
void Start()
{
Pause.SetActive(false);
}
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown(KeyCode.Escape))
Pause.SetActive(true);
}
public void OnResumeButtonClicked()
{
Pause.SetActive(false);
}
public void OnMainMenuButtonClicked()
{
LevelManager.LoadLevel(0);
}
}
| 19.060606
| 52
| 0.647059
|
[
"MIT"
] |
JosepLleal/GameJam_S-Team
|
S-Team/Assets/Game/Scripts/PauseMenu.cs
| 631
|
C#
|
using CommunityPlugin.Non_Native_Modifications.SideMenu.Controls;
using CommunityPlugin.Objects;
using CommunityPlugin.Objects.Helpers;
using CommunityPlugin.Objects.Interface;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace CommunityPlugin.Non_Native_Modifications.SideMenu
{
public class SideMenuUI
{
public static bool Created = false;
private static Form EncompassForm = FormWrapper.EncompassForm;
public const int PluginWidth = 350;
private static MenuButton menuButton;
public static void Closing()
{
SideMenuUI.Created = false;
}
public static void Click()
{
if (SideMenuUI.menuButton == null)
return;
SideMenuUI.menuButton.PerformClick();
}
public static async void CreateMenu(bool load)
{
if (SideMenuUI.EncompassForm == null || SideMenuUI.Created)
return;
try
{
Panel _rightPanel = await Task.Run<Panel>((Func<Panel>)(() =>
{
while (SideMenuUI.RightPanel() == null)
Thread.Sleep(500);
return SideMenuUI.RightPanel();
}));
if (!SideMenuUI.Created)
{
SideMenuUI.RemoveControlById("pnlMain", _rightPanel);
SideMenuUI.RemoveControlById("pnlMenuButton", _rightPanel);
if (load)
{
SideMenuUI.menuButton = new MenuButton();
SideMenuUI.menuButton.BackColor = Color.White;
MenuPanel MenuPanel = new MenuPanel(SideMenuUI.GetMenu(), SideMenuUI.menuButton);
MenuPanel.Name = "pnlMain";
MenuPanel.Dock = DockStyle.Right;
MenuPanel.AutoScroll = false;
MenuPanel.HorizontalScroll.Enabled = false;
MenuPanel.AutoScroll = true;
MenuPanel.Visible = false;
Panel panel = new Panel();
panel.Name = "pnlMenuButton";
panel.Width = 27;
panel.Dock = DockStyle.Right;
panel.Controls.Add((Control)SideMenuUI.menuButton);
_rightPanel.Controls.Add((Control)MenuPanel);
_rightPanel.Controls.Add((Control)panel);
SideMenuUI.Created = true;
_rightPanel = (Panel)null;
SideMenuUI.menuButton = (MenuButton)null;
MenuPanel = (MenuPanel)null;
panel = (Panel)null;
MenuPanel = (MenuPanel)null;
panel = (Panel)null;
}
}
_rightPanel = (Panel)null;
}
catch (Exception ex)
{
Logger.HandleError(ex, nameof(SideMenuUI));
}
}
public static List<MenuPanelSection> GetMenu()
{
List<MenuPanelSection> source = new List<MenuPanelSection>();
foreach (System.Type type in ((IEnumerable<System.Type>)typeof(SideMenuUI).Assembly.GetTypes()).Where<System.Type>((Func<System.Type, bool>)(type => type.IsSubclassOf(typeof(LoanMenuControl)))).ToList<System.Type>())
{
LoanMenuControl loanMenuControl = Activator.CreateInstance(type) as LoanMenuControl;
if (loanMenuControl != null && (loanMenuControl.CanRun()) && source.FirstOrDefault<MenuPanelSection>((Func<MenuPanelSection, bool>)(x => x.GetType() == loanMenuControl.GetType())) == null)
{
source.Add(new MenuPanelSection(SideMenuUI.GetHeading(loanMenuControl.Name), true, (loanMenuControl.CanShow() ? 1 : 0) != 0, new Control[1]
{
(Control) loanMenuControl
}));
loanMenuControl.RunBase();
}
}
return source;
}
public static Panel RightPanel()
{
try
{
return SideMenuUI.EncompassForm.Controls.Find("rightPanel", true)[0] as Panel;
}
catch (Exception ex)
{
Logger.HandleError(ex, nameof(SideMenuUI));
return (Panel)null;
}
}
public static TabControl TabControl()
{
try
{
return SideMenuUI.MainForm().Controls.Find("tabControl", true)[0] as TabControl;
}
catch (Exception ex)
{
Logger.HandleError(ex, nameof(SideMenuUI));
return (TabControl)null;
}
}
public static Form MainForm()
{
return SideMenuUI.FindForm("Encompass");
}
private static Form FindForm(string name)
{
Form form = (Form)null;
foreach (Form openForm in (ReadOnlyCollectionBase)Application.OpenForms)
{
if (openForm.Text.ToLower().Contains("encompass"))
{
form = openForm;
SideMenuUI.EncompassForm = form;
break;
}
}
return form;
}
public static void RemoveControlById(string controlID, Panel panel)
{
Control[] controlArray = panel.Controls.Find(controlID, true);
if (((IEnumerable<Control>)controlArray).Count<Control>() <= 0)
return;
for (int index = 0; index < ((IEnumerable<Control>)controlArray).Count<Control>(); ++index)
controlArray[index].Parent.Controls.Remove(controlArray[index]);
}
private static Label GetHeading(string text)
{
Label label = new Label();
label.Anchor = AnchorStyles.Left | AnchorStyles.Right;
label.AutoSize = true;
label.BackColor = Color.FromArgb(227, 227, 227);
label.Font = new Font("Segoe UI", 8.25f, FontStyle.Regular, GraphicsUnit.Point, (byte)0);
label.Location = new Point(0, 0);
label.Margin = new Padding(0);
label.Name = "lbl1";
label.Padding = new Padding(7);
label.Size = new Size(350, 23);
label.TabIndex = 0;
label.Text = text;
return label;
}
}
}
| 38.305085
| 228
| 0.523304
|
[
"MIT"
] |
BPenPen/CommunityPlugin-1
|
CommunityPlugin/Non Native Modifications/SideMenu/SideMenuUI.cs
| 6,782
|
C#
|
// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.Collections.Generic;
using ICSharpCode.Decompiler.Util;
namespace ICSharpCode.Decompiler.TypeSystem.Implementation
{
/// <summary>
/// References an entity by its type and name.
/// This class can be used to refer to all members except for constructors and explicit interface implementations.
/// </summary>
/// <remarks>
/// Resolving a DefaultMemberReference requires a context that provides enough information for resolving the declaring type reference
/// and the parameter types references.
/// </remarks>
[Serializable]
public sealed class DefaultMemberReference : IMemberReference, ISupportsInterning
{
readonly SymbolKind symbolKind;
readonly ITypeReference typeReference;
readonly string name;
readonly int typeParameterCount;
readonly IList<ITypeReference> parameterTypes;
public DefaultMemberReference(SymbolKind symbolKind, ITypeReference typeReference, string name, int typeParameterCount = 0, IList<ITypeReference> parameterTypes = null)
{
if (typeReference == null)
throw new ArgumentNullException("typeReference");
if (name == null)
throw new ArgumentNullException("name");
if (typeParameterCount != 0 && symbolKind != SymbolKind.Method)
throw new ArgumentException("Type parameter count > 0 is only supported for methods.");
this.symbolKind = symbolKind;
this.typeReference = typeReference;
this.name = name;
this.typeParameterCount = typeParameterCount;
this.parameterTypes = parameterTypes ?? EmptyList<ITypeReference>.Instance;
}
public ITypeReference DeclaringTypeReference {
get { return typeReference; }
}
public IMember Resolve(ITypeResolveContext context)
{
IType type = typeReference.Resolve(context);
IEnumerable<IMember> members;
if (symbolKind == SymbolKind.Accessor) {
members = type.GetAccessors(
m => m.Name == name && !m.IsExplicitInterfaceImplementation,
GetMemberOptions.IgnoreInheritedMembers);
} else if (symbolKind == SymbolKind.Method) {
members = type.GetMethods(
m => m.Name == name && m.SymbolKind == SymbolKind.Method
&& m.TypeParameters.Count == typeParameterCount && !m.IsExplicitInterfaceImplementation,
GetMemberOptions.IgnoreInheritedMembers);
} else {
members = type.GetMembers(
m => m.Name == name && m.SymbolKind == symbolKind && !m.IsExplicitInterfaceImplementation,
GetMemberOptions.IgnoreInheritedMembers);
}
var resolvedParameterTypes = parameterTypes.Resolve(context);
foreach (IMember member in members) {
IParameterizedMember parameterizedMember = member as IParameterizedMember;
if (parameterizedMember == null) {
if (parameterTypes.Count == 0)
return member;
} else if (parameterTypes.Count == parameterizedMember.Parameters.Count) {
bool signatureMatches = true;
for (int i = 0; i < parameterTypes.Count; i++) {
IType type1 = DummyTypeParameter.NormalizeAllTypeParameters(resolvedParameterTypes[i]);
IType type2 = DummyTypeParameter.NormalizeAllTypeParameters(parameterizedMember.Parameters[i].Type);
if (!type1.Equals(type2)) {
signatureMatches = false;
break;
}
}
if (signatureMatches)
return member;
}
}
return null;
}
ISymbol ISymbolReference.Resolve(ITypeResolveContext context)
{
return ((IMemberReference)this).Resolve(context);
}
int ISupportsInterning.GetHashCodeForInterning()
{
return (int)symbolKind ^ typeReference.GetHashCode() ^ name.GetHashCode() ^ parameterTypes.GetHashCode();
}
bool ISupportsInterning.EqualsForInterning(ISupportsInterning other)
{
DefaultMemberReference o = other as DefaultMemberReference;
return o != null && symbolKind == o.symbolKind && typeReference == o.typeReference && name == o.name && parameterTypes == o.parameterTypes;
}
}
}
| 42.008403
| 170
| 0.742348
|
[
"MIT"
] |
nguyenthiennam1992/Decompiler
|
ILSpy-master/ICSharpCode.Decompiler/TypeSystem/Implementation/DefaultMemberReference.cs
| 5,001
|
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.Network.V20190901.Outputs
{
[OutputType]
public sealed class NetworkInterfaceDnsSettingsResponse
{
/// <summary>
/// If the VM that uses this NIC is part of an Availability Set, then this list will have the union of all DNS servers from all NICs that are part of the Availability Set. This property is what is configured on each of those VMs.
/// </summary>
public readonly ImmutableArray<string> AppliedDnsServers;
/// <summary>
/// List of DNS servers IP addresses. Use 'AzureProvidedDNS' to switch to azure provided DNS resolution. 'AzureProvidedDNS' value cannot be combined with other IPs, it must be the only value in dnsServers collection.
/// </summary>
public readonly ImmutableArray<string> DnsServers;
/// <summary>
/// Relative DNS name for this NIC used for internal communications between VMs in the same virtual network.
/// </summary>
public readonly string? InternalDnsNameLabel;
/// <summary>
/// Even if internalDnsNameLabel is not specified, a DNS entry is created for the primary NIC of the VM. This DNS name can be constructed by concatenating the VM name with the value of internalDomainNameSuffix.
/// </summary>
public readonly string InternalDomainNameSuffix;
/// <summary>
/// Fully qualified DNS name supporting internal communications between VMs in the same virtual network.
/// </summary>
public readonly string InternalFqdn;
[OutputConstructor]
private NetworkInterfaceDnsSettingsResponse(
ImmutableArray<string> appliedDnsServers,
ImmutableArray<string> dnsServers,
string? internalDnsNameLabel,
string internalDomainNameSuffix,
string internalFqdn)
{
AppliedDnsServers = appliedDnsServers;
DnsServers = dnsServers;
InternalDnsNameLabel = internalDnsNameLabel;
InternalDomainNameSuffix = internalDomainNameSuffix;
InternalFqdn = internalFqdn;
}
}
}
| 42.877193
| 237
| 0.68617
|
[
"Apache-2.0"
] |
pulumi-bot/pulumi-azure-native
|
sdk/dotnet/Network/V20190901/Outputs/NetworkInterfaceDnsSettingsResponse.cs
| 2,444
|
C#
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
using MailCheck.Common.Messaging.Abstractions;
using MailCheck.Intelligence.IpToAsnParser.Dao;
using MailCheck.Intelligence.IpToAsnParser.Fetchers;
namespace MailCheck.Intelligence.IpToAsnParser
{
public class IpAddressToAsnProcessor : IProcess
{
private readonly IAsnToIpAddressParser _asnToIpAddressParser;
private readonly IAsnToIp6AddressFetcher _asnToIp6AddressFetcher;
private readonly IAsnToIp4AddressFetcher _asnToIp4AddressFetcher;
private readonly IIp6ToAsnDao _ip6ToAsnDao;
private readonly IIp4ToAsnDao _ipIp4ToAsnDao;
public IpAddressToAsnProcessor(IAsnToIpAddressParser asnToIpAddressParser, IAsnToIp6AddressFetcher asnToIp6AddressFetcher, IAsnToIp4AddressFetcher asnToIp4AddressFetcher, IIp6ToAsnDao ip6ToAsnDao, IIp4ToAsnDao ipIp4ToAsnDao)
{
_asnToIpAddressParser = asnToIpAddressParser;
_asnToIp6AddressFetcher = asnToIp6AddressFetcher;
_asnToIp4AddressFetcher = asnToIp4AddressFetcher;
_ip6ToAsnDao = ip6ToAsnDao;
_ipIp4ToAsnDao = ipIp4ToAsnDao;
}
public async Task<ProcessResult> Process()
{
DateTime dateTime = DateTime.UtcNow;
Stream ip6Stream = await _asnToIp6AddressFetcher.Fetch(dateTime);
await _ip6ToAsnDao.Save(await ParseStream(ip6Stream));
Stream ip4Stream = await _asnToIp4AddressFetcher.Fetch(dateTime);
await _ipIp4ToAsnDao.Save(await ParseStream(ip4Stream));
return ProcessResult.Stop;
}
private async Task<List<IpToAsn>> ParseStream(Stream stream)
{
List<IpToAsn> ipToAsns;
using (stream)
{
ipToAsns = await _asnToIpAddressParser.Parse(stream);
}
return ipToAsns;
}
}
}
| 36.584906
| 232
| 0.708613
|
[
"Apache-2.0"
] |
ukncsc/MailCheck.Public.AggregateReport
|
src/MailCheck.Intelligence.IpToAsnParser/IPAddressToAsnProcessor.cs
| 1,939
|
C#
|
namespace BankManagementSystem.Services.DataServices.Implementations
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using AutoMapper;
using BankManagementSystem.Common;
using BankManagementSystem.Common.BindingModels.CreditCard;
using BankManagementSystem.Common.ViewModels.CreditCard;
using BankManagementSystem.Data.Common.Repositories;
using BankManagementSystem.Models;
using Microsoft.AspNetCore.Identity;
class CreditCardService : BaseService<CreditCard>, ICreditCardService
{
public CreditCardService(IRepository<CreditCard> repository,
IMapper mapper,
UserManager<Client> userManager)
: base(repository, mapper, userManager)
{
}
public async Task<int> Create(CreateCreditCardBindingModel model, string username)
{
Validator.ThrowIfNull(model);
var client = await this.GetUserByNamedAsync(username);
var creditCard = this.Mapper.Map<CreditCard>(model);
creditCard.ClientId = client.Id;
creditCard.DateRegistered = DateTime.Now;
await this.Repository.AddAsync(creditCard);
await this.Repository.SaveChangesAsync();
return creditCard.Id;
}
public async Task<IEnumerable<CreditCardViewModel>> GetAllCreditCardsAsync(string id)
{
return this.Mapper.Map<IEnumerable<CreditCardViewModel>>(
this.Repository.All().Where(x => x.ClientId == id));
}
}
}
| 35.042553
| 94
| 0.657559
|
[
"MIT"
] |
evgenirusev/BankManagementSystem
|
src/Services/BankManagementSystem.Services.DataServices/Implementations/CreditCardService.cs
| 1,649
|
C#
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
namespace StoppyMcStopwatchface
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
}
| 22.272727
| 65
| 0.606122
|
[
"MIT"
] |
Ha3ks/StoppyMcStopwatchface
|
Backup/Program.cs
| 492
|
C#
|
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using osu.Game.Rulesets.Objects.Types;
using osuTK;
namespace osu.Game.Rulesets.Objects.Legacy.Osu
{
/// <summary>
/// Legacy osu! Spinner-type, used for parsing Beatmaps.
/// </summary>
internal sealed class ConvertSpinner : HitObject, IHasEndTime, IHasPosition, IHasCombo
{
public double EndTime { get; set; }
public double Duration => EndTime - StartTime;
public Vector2 Position { get; set; }
public float X => Position.X;
public float Y => Position.Y;
protected override HitWindows CreateHitWindows() => null;
public bool NewCombo { get; set; }
public int ComboOffset { get; set; }
}
}
| 28.032258
| 93
| 0.634062
|
[
"MIT"
] |
Dragicafit/osu
|
osu.Game/Rulesets/Objects/Legacy/Osu/ConvertSpinner.cs
| 841
|
C#
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Windows.Media.Media3D;
namespace ThreeDimensionaApplication
{
/// <summary>
/// MaterialsWindow.xaml 的交互逻辑
/// </summary>
public partial class MaterialsWindow : Window
{
public MaterialsWindow()
{
InitializeComponent();
}
private void chk_Click(object sender, RoutedEventArgs e)
{
materialsGroup.Children.Clear();
if (chkBackground.IsChecked == true)
rect.Visibility = Visibility.Visible;
else
rect.Visibility = Visibility.Hidden;
if (chkDiffuse.IsChecked == true)
materialsGroup.Children.Add((Material)FindResource("diffuse"));
if (chkSpecular.IsChecked == true)
materialsGroup.Children.Add((Material)FindResource("specular"));
if (chkEmissive.IsChecked == true)
materialsGroup.Children.Add((Material)FindResource("emissive"));
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
}
}
}
| 26.942308
| 80
| 0.642398
|
[
"MIT"
] |
changweihua/ProjectStudy
|
ThreeDimensionaApplication/MaterialsWindow.xaml.cs
| 1,413
|
C#
|
using System;
using System.Collections.Generic;
namespace Vue2Spa.Models.DB
{
public partial class Types
{
public short TypeId { get; set; }
public short DepId { get; set; }
public string TypeDesc { get; set; }
}
}
| 19.461538
| 44
| 0.624506
|
[
"MIT"
] |
MoeinElwani/Holiday
|
Models/DB/Types.cs
| 255
|
C#
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Follow : MonoBehaviour
{
[SerializeField] bool canvasObject;
[SerializeField] Transform target;
[SerializeField] Vector2 offset;
private void Start()
{
target = FindObjectOfType<MergedPlayerController>().transform;
}
// Update is called once per frame
void FixedUpdate()
{
if (canvasObject)
{
transform.position = Camera.main.WorldToScreenPoint(target.position + (Vector3)offset);
}
else
{
transform.position = target.position + (Vector3)offset;
}
}
}
| 22.566667
| 99
| 0.630724
|
[
"Apache-2.0"
] |
Short1398/BouncyDash
|
Bouncy Dash/Assets/Scripts/Controllers/Follow.cs
| 679
|
C#
|
/*
Copyright 2017 Coin Foundry (coinfoundry.org)
Authors: Oliver Weichhold (oliver@weichhold.com)
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
associated documentation files (the "Software"), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial
portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT
LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
using System;
using System.Collections.Concurrent;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using JetBrains.Annotations;
namespace MiningCore.Contracts
{
public class Contract
{
[ContractAnnotation("predicate:false => halt")]
public static void Requires<TException>(bool predicate, string message = null)
where TException : Exception, new()
{
if (!predicate)
{
var constructor = constructors.GetOrAdd(typeof(TException), CreateConstructor);
throw constructor(new object[] {message});
}
}
[ContractAnnotation("parameter:null => halt")]
public static void RequiresNonNull(object parameter, string paramName)
{
if (parameter == null)
throw new ArgumentNullException(paramName);
}
#region Exception Constructors
private static readonly ConcurrentDictionary<Type, ConstructorDelegate> constructors = new ConcurrentDictionary<Type, ConstructorDelegate>();
private delegate Exception ConstructorDelegate(object[] parameters);
private static ConstructorDelegate CreateConstructor(Type type)
{
// Get the constructor info for these parameters
var parameters = new[] {typeof(string)};
var constructorInfo = type.GetTypeInfo().DeclaredConstructors.First(
x => x.GetParameters().Length == 1 && x.GetParameters().First().ParameterType == typeof(string));
var paramExpr = Expression.Parameter(typeof(object[]));
// To feed the constructor with the right parameters, we need to generate an array
// of parameters that will be read from the initialize object array argument.
var constructorParameters = parameters.Select((paramType, index) =>
// convert the object[index] to the right constructor parameter type.
Expression.Convert(
// read a value from the object[index]
Expression.ArrayAccess(
paramExpr,
Expression.Constant(index)),
paramType)).ToArray();
// just call the constructor.
var body = Expression.New(constructorInfo, constructorParameters);
var constructor = Expression.Lambda<ConstructorDelegate>(body, paramExpr);
return constructor.Compile();
}
#endregion // Exception Constructors
}
}
| 43.788235
| 149
| 0.674369
|
[
"MIT"
] |
AltcoinCoop/PoolMiningEngine
|
src/MiningCore/Contracts/Contract.cs
| 3,724
|
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.Generic;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.CSharp.Extensions
{
internal partial class MemberDeclarationSyntaxExtensions
{
private sealed class DeclarationFinder : CSharpSyntaxWalker
{
private readonly Dictionary<string, List<SyntaxToken>> _map = new Dictionary<string, List<SyntaxToken>>();
private DeclarationFinder()
: base(SyntaxWalkerDepth.Node)
{
}
public static Dictionary<string, List<SyntaxToken>> GetAllDeclarations(SyntaxNode syntax)
{
var finder = new DeclarationFinder();
finder.Visit(syntax);
return finder._map;
}
private void Add(SyntaxToken syntaxToken)
{
if (syntaxToken.Kind() == SyntaxKind.IdentifierToken)
{
var identifier = syntaxToken.ValueText;
if (!_map.TryGetValue(identifier, out var list))
{
list = new List<SyntaxToken>();
_map.Add(identifier, list);
}
list.Add(syntaxToken);
}
}
public override void VisitVariableDeclarator(VariableDeclaratorSyntax node)
{
base.VisitVariableDeclarator(node);
Add(node.Identifier);
}
public override void VisitCatchDeclaration(CatchDeclarationSyntax node)
{
base.VisitCatchDeclaration(node);
Add(node.Identifier);
}
public override void VisitParameter(ParameterSyntax node)
{
base.VisitParameter(node);
Add(node.Identifier);
}
public override void VisitFromClause(FromClauseSyntax node)
{
base.VisitFromClause(node);
Add(node.Identifier);
}
public override void VisitLetClause(LetClauseSyntax node)
{
base.VisitLetClause(node);
Add(node.Identifier);
}
public override void VisitJoinClause(JoinClauseSyntax node)
{
base.VisitJoinClause(node);
Add(node.Identifier);
}
public override void VisitJoinIntoClause(JoinIntoClauseSyntax node)
{
base.VisitJoinIntoClause(node);
Add(node.Identifier);
}
public override void VisitQueryContinuation(QueryContinuationSyntax node)
{
base.VisitQueryContinuation(node);
Add(node.Identifier);
}
}
}
}
| 32.895833
| 118
| 0.560481
|
[
"MIT"
] |
BertanAygun/roslyn
|
src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Extensions/MemberDeclarationSyntaxExtensions.DeclarationFinder.cs
| 3,160
|
C#
|
using Blackboard.Core;
using Blackboard.Core.Data.Caps;
using Blackboard.Core.Inspect;
using Blackboard.Core.Nodes.Inner;
using Blackboard.Core.Nodes.Outer;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using S = System;
namespace BlackboardTests.CoreTests {
[TestClass]
public class Nodes {
[TestMethod]
public void TestAddNodes() {
InputValue<Bool> input1 = new();
InputValue<Bool> input2 = new();
InputValue<Bool> input3 = new();
And and12 = new(input1, input2);
Or or123 = new(and12, input3);
Not not123 = new(or123);
not123.LegitimatizeAll();
not123.UpdateAllParents();
not123.EvaluateAllParents();
and12 .CheckString("And<bool>[false](Input<bool>, Input<bool>)");
not123.CheckString("Not<bool>[true](Or<bool>(And<bool>, Input<bool>))");
and12 .CheckParents("Input<bool>[false], Input<bool>[false]");
or123 .CheckParents("And<bool>[false], Input<bool>[false]");
not123.CheckParents("Or<bool>[false]");
input1.CheckDepth(0);
input2.CheckDepth(0);
input3.CheckDepth(0);
and12 .CheckDepth(1);
or123 .CheckDepth(2);
not123.CheckDepth(3);
}
[TestMethod]
public void TestEvaluateNodes() {
InputValue<Bool> input1 = new();
InputValue<Bool> input2 = new();
InputValue<Bool> input3 = new();
And and12 = new(input1, input2);
Or or123 = new(and12, input3);
Not not123 = new(or123);
not123.LegitimatizeAll();
not123.UpdateAllParents();
not123.EvaluateAllParents();
input1.CheckValue(false);
input2.CheckValue(false);
input3.CheckValue(false);
and12 .CheckValue(false);
or123 .CheckValue(false);
not123.CheckValue(true);
Slate drv = new(addConsts: false);
drv.Global["One"] = input1;
drv.Global["Two"] = input2;
drv.Global["Three"] = input3;
drv.SetBool(true, "One");
drv.SetBool(true, "Three");
drv.CheckEvaluate(
"Start Eval (pending: 2)",
" Evaluated (changed: False, depth: 1, node: And<bool>[false](One, Two), remaining: 1)",
" Evaluated (changed: True, depth: 2, node: Or<bool>[true](And<bool>(One, Two), Three), remaining: 1)",
" Evaluated (changed: True, depth: 3, node: Not<bool>[false](Or<bool>(And<bool>, Three)), remaining: 0)",
"End Eval (provoked: 0)");
input1.CheckValue(true);
input2.CheckValue(false);
input3.CheckValue(true);
and12 .CheckValue(false);
or123 .CheckValue(true);
not123.CheckValue(false);
drv.SetBool(false, "Three");
drv.CheckEvaluate(
"Start Eval (pending: 1)",
" Evaluated (changed: True, depth: 2, node: Or<bool>[false](And<bool>(One, Two), Three), remaining: 1)",
" Evaluated (changed: True, depth: 3, node: Not<bool>[true](Or<bool>(And<bool>, Three)), remaining: 0)",
"End Eval (provoked: 0)");
input1.CheckValue(true);
input2.CheckValue(false);
input3.CheckValue(false);
and12 .CheckValue(false);
or123 .CheckValue(false);
not123.CheckValue(true);
drv.SetBool(true, "Two");
drv.CheckEvaluate(
"Start Eval (pending: 1)",
" Evaluated (changed: True, depth: 1, node: And<bool>[true](One, Two), remaining: 1)",
" Evaluated (changed: True, depth: 2, node: Or<bool>[true](And<bool>(One, Two), Three), remaining: 1)",
" Evaluated (changed: True, depth: 3, node: Not<bool>[false](Or<bool>(And<bool>, Three)), remaining: 0)",
"End Eval (provoked: 0)");
input1.CheckValue(true);
input2.CheckValue(true);
input3.CheckValue(false);
and12 .CheckValue(true);
or123 .CheckValue(true);
not123.CheckValue(false);
}
[TestMethod]
public void TestTriggerNodes() {
Slate drv = new();
InputTrigger inputA = new();
InputTrigger inputB = new();
InputTrigger inputC = new();
drv.Global["TrigA"] = inputA;
drv.Global["TrigB"] = inputB;
drv.Global["TrigC"] = inputC;
Any any = new(inputA, inputB, inputC);
All all = new(inputA, inputB, inputC);
Counter<Int> counter = new(any, null, all);
drv.Global["Count"] = counter;
OnTrue over3 = new(new GreaterThanOrEqual<Int>(counter, Literal.Int(3)));
drv.Global["High"] = over3;
Toggler toggle = new(over3);
drv.Global["Toggle"] = toggle;
bool high;
OutputTrigger outTrig = new(over3);
outTrig.OnProvoked += (object sender, S.EventArgs e) => high = true;
outTrig.LegitimatizeAll();
toggle.LegitimatizeAll();
outTrig.UpdateAllParents();
toggle.UpdateAllParents();
void check(bool triggerA, bool triggerB, bool triggerC,
int expCount, bool expHigh, bool expToggle) {
if (triggerA) drv.Provoke("TrigA");
if (triggerB) drv.Provoke("TrigB");
if (triggerC) drv.Provoke("TrigC");
high = false;
drv.PerformEvaluation();
drv.ResetTriggers();
drv.CheckValue(expCount, "Count");
Assert.AreEqual(expHigh, high, "High flag state");
drv.CheckValue(expToggle, "Toggle");
}
check(true, false, false, 1, false, false);
check(false, true, false, 2, false, false);
check(false, false, true, 3, true, true);
check(true, true, false, 4, false, true);
check(true, true, true, 0, false, true);
check(true, false, true, 1, false, true);
check(false, true, true, 2, false, true);
check(false, false, true, 3, true, false);
}
// TODO: Test for:
// - setting children to parent, legitimize children.
// - setting parents for sum(a, b, c, d) where a & c are legitimate and b & d are illegitimate.
}
}
| 38.994118
| 122
| 0.533715
|
[
"BSD-3-Clause"
] |
Grant-Nelson/BlackboardCSharp
|
BlackboardTests/CoreTests/Nodes.cs
| 6,629
|
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 JetBrains.Annotations;
using Microsoft.EntityFrameworkCore.Infrastructure;
using MaikeBing.EntityFrameworkCore.NoSqLiteDB.Infrastructure.Internal;
namespace MaikeBing.EntityFrameworkCore.NoSqLiteDB.Storage.Internal
{
/// <summary>
/// This API supports the Entity Framework Core infrastructure and is not intended to be used
/// directly from your code. This API may change or be removed in future releases.
/// </summary>
public static class LiteDBStoreCacheExtensions
{
/// <summary>
/// This API supports the Entity Framework Core infrastructure and is not intended to be used
/// directly from your code. This API may change or be removed in future releases.
/// </summary>
public static ILiteDBStore GetStore([NotNull] this ILiteDBStoreCache storeCache, [NotNull] IDbContextOptions options)
=> storeCache.GetStore(options.Extensions.OfType<LiteDBOptionsExtension>().First().StoreName);
}
}
| 47.4
| 125
| 0.731646
|
[
"MIT"
] |
maikebing/EntityFrameworkCore.LiteDB
|
MaikeBing.EntityFrameworkCore.NoSqLiteDB/Storage/Internal/LiteDBStoreCacheExtensions.cs
| 1,185
|
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.Diagnostics;
using Microsoft.Win32.SafeHandles;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
namespace System.Net
{
internal static partial class CertificateValidationPal
{
internal static SslPolicyErrors VerifyCertificateProperties(
SafeDeleteContext securityContext,
X509Chain chain,
X509Certificate2 remoteCertificate,
bool checkCertName,
bool isServer,
string hostName)
{
return CertificateValidation.BuildChainAndVerifyProperties(chain, remoteCertificate, checkCertName, hostName);
}
//
// Extracts a remote certificate upon request.
//
internal static X509Certificate2 GetRemoteCertificate(SafeDeleteContext securityContext)
{
return GetRemoteCertificate(securityContext, null);
}
internal static X509Certificate2 GetRemoteCertificate(
SafeDeleteContext securityContext,
out X509Certificate2Collection remoteCertificateStore)
{
if (securityContext == null)
{
remoteCertificateStore = null;
return null;
}
remoteCertificateStore = new X509Certificate2Collection();
return GetRemoteCertificate(securityContext, remoteCertificateStore);
}
private static X509Certificate2 GetRemoteCertificate(SafeDeleteContext securityContext, X509Certificate2Collection remoteCertificateStore)
{
bool gotReference = false;
if (securityContext == null)
{
return null;
}
if (NetEventSource.IsEnabled) NetEventSource.Enter(securityContext);
X509Certificate2 result = null;
SafeFreeCertContext remoteContext = null;
try
{
int errorCode = QueryContextRemoteCertificate(securityContext, out remoteContext);
if (remoteContext != null && !remoteContext.IsInvalid)
{
remoteContext.DangerousAddRef(ref gotReference);
result = new X509Certificate2(remoteContext.DangerousGetHandle());
}
if (remoteCertificateStore != null)
{
using (SafeSharedX509StackHandle chainStack =
Interop.OpenSsl.GetPeerCertificateChain(((SafeDeleteSslContext)securityContext).SslContext))
{
if (!chainStack.IsInvalid)
{
int count = Interop.Crypto.GetX509StackFieldCount(chainStack);
for (int i = 0; i < count; i++)
{
IntPtr certPtr = Interop.Crypto.GetX509StackField(chainStack, i);
if (certPtr != IntPtr.Zero)
{
// X509Certificate2(IntPtr) calls X509_dup, so the reference is appropriately tracked.
X509Certificate2 chainCert = new X509Certificate2(certPtr);
remoteCertificateStore.Add(chainCert);
}
}
}
}
}
}
catch
{
result?.Dispose();
throw;
}
finally
{
if (remoteContext != null)
{
if (gotReference)
{
remoteContext.DangerousRelease();
}
remoteContext.Dispose();
}
}
if (NetEventSource.IsEnabled)
{
NetEventSource.Log.RemoteCertificate(result);
NetEventSource.Exit(securityContext, result);
}
return result;
}
//
// Used only by client SSL code, never returns null.
//
internal static string[] GetRequestCertificateAuthorities(SafeDeleteContext securityContext)
{
using (SafeSharedX509NameStackHandle names = Interop.Ssl.SslGetClientCAList(((SafeDeleteSslContext)securityContext).SslContext))
{
if (names.IsInvalid)
{
return Array.Empty<string>();
}
int nameCount = Interop.Crypto.GetX509NameStackFieldCount(names);
if (nameCount == 0)
{
return Array.Empty<string>();
}
string[] clientAuthorityNames = new string[nameCount];
for (int i = 0; i < nameCount; i++)
{
using (SafeSharedX509NameHandle nameHandle = Interop.Crypto.GetX509NameStackField(names, i))
{
X500DistinguishedName dn = Interop.Crypto.LoadX500Name(nameHandle);
clientAuthorityNames[i] = dn.Name;
}
}
return clientAuthorityNames;
}
}
static partial void CheckSupportsStore(StoreLocation storeLocation, ref bool hasSupport)
{
// There's not currently a LocalMachine\My store on Unix, so don't bother trying
// and having to deal with the exception.
//
// https://github.com/dotnet/corefx/issues/3690 tracks the lack of this store.
if (storeLocation == StoreLocation.LocalMachine)
hasSupport = false;
}
private static X509Store OpenStore(StoreLocation storeLocation)
{
Debug.Assert(storeLocation == StoreLocation.CurrentUser);
X509Store store = new X509Store(StoreName.My, storeLocation);
store.Open(OpenFlags.ReadOnly);
return store;
}
private static int QueryContextRemoteCertificate(SafeDeleteContext securityContext, out SafeFreeCertContext remoteCertContext)
{
remoteCertContext = null;
try
{
SafeX509Handle remoteCertificate = Interop.OpenSsl.GetPeerCertificate(((SafeDeleteSslContext)securityContext).SslContext);
// Note that cert ownership is transferred to SafeFreeCertContext
remoteCertContext = new SafeFreeCertContext(remoteCertificate);
return 0;
}
catch
{
return -1;
}
}
}
}
| 36.382199
| 146
| 0.543244
|
[
"MIT"
] |
ARhj/corefx
|
src/System.Net.Security/src/System/Net/CertificateValidationPal.Unix.cs
| 6,949
|
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 Microsoft.VisualStudio.Shell.Interop;
namespace Microsoft.CodeAnalysis.ExternalAccess.LegacyCodeAnalysis.Api
{
internal interface ILegacyCodeAnalysisVisualStudioSuppressionFixServiceAccessor
{
bool AddSuppressions(IVsHierarchy projectHierarchyOpt);
bool AddSuppressions(bool selectedErrorListEntriesOnly, bool suppressInSource, IVsHierarchy projectHierarchyOpt);
bool RemoveSuppressions(bool selectedErrorListEntriesOnly, IVsHierarchy projectHierarchyOpt);
}
}
| 47.642857
| 161
| 0.811094
|
[
"Apache-2.0"
] |
20chan/roslyn
|
src/VisualStudio/Core/Def/ExternalAccess/LegacyCodeAnalysis/Api/ILegacyCodeAnalysisVisualStudioSuppressionFixServiceAccessor.cs
| 669
|
C#
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using ServerSimulator.Properties;
namespace ServerSimulator
{
/// <summary>
/// This class validates and stores parameters passed in from the command-line or config file
/// </summary>
internal sealed class Parameters
{
// the number of requests in flight
private int numRequests = 200;
public int NumRequests
{
get { return numRequests; }
set
{
if (value > 0)
{
numRequests = value;
}
else
{
throw new ArgumentOutOfRangeException("value", "NumRequests must be > 0");
}
}
}
// the fraction of requests that are finalizable
private float finalizableRate = 0;
public float FinalizableRate
{
get { return finalizableRate; }
set
{
if ((value >= 0) && (value <= 1))
{
finalizableRate = value;
}
else
{
throw new ArgumentOutOfRangeException(
"value",
"FinalizableRate must be >=0 and <=1"
);
}
}
}
// the replacement rate of the cache for each request
private float cacheReplacementRate = 0.01f;
public float CacheReplacementRate
{
get { return cacheReplacementRate; }
set
{
if ((value > 0) && (value <= 1))
{
cacheReplacementRate = value;
}
else
{
throw new ArgumentOutOfRangeException(
"value",
"CacheReplacementRate must be >0 and <=1"
);
}
}
}
// the fraction that survives for the life of the request
private float survivalRate = 0.9f;
public float SurvivalRate
{
get { return survivalRate; }
set
{
if ((value > 0) && (value <= 1))
{
survivalRate = value;
}
else
{
throw new ArgumentOutOfRangeException(
"value",
"SurvivalRate must be >0 and <=1"
);
}
}
}
// the number of times to loop (-1 for infinite)
private int numPasses = -1;
public int NumPasses
{
get { return numPasses; }
set { numPasses = value; }
}
// the random seed for reproducibility
private int randomSeed = 0;
public int RandomSeed
{
get { return randomSeed; }
set { randomSeed = value; }
}
// the total allocation per request in byte
private int allocationVolume = 100000;
public int AllocationVolume
{
get { return allocationVolume; }
set
{
if (value > 0)
{
allocationVolume = value;
}
else
{
throw new ArgumentOutOfRangeException("value", "AllocationVolume must be >0");
}
}
}
// the cache size in bytes
private int cacheSize = 1024 * 1024 * 100;
public int CacheSize
{
get { return cacheSize; }
set
{
if (value > 0)
{
cacheSize = value;
}
else
{
throw new ArgumentOutOfRangeException("value", "CacheSize must be > 0");
}
}
}
// the number of times requests to executes after steady state is achieved.
// if it took 300 reqs to achieve steady state, then perform 300*steady_state_factor requests
private int steadyStateFactor = 20;
public int SteadyStateFactor
{
get { return steadyStateFactor; }
set
{
if (value > 0)
{
steadyStateFactor = value;
}
else
{
throw new ArgumentOutOfRangeException("value", "SteadyStateFactor must be > 0");
}
}
}
// the amount of non changing static data in MB
private int staticDataVolume = 500;
public int StaticDataVolume
{
get { return staticDataVolume; }
set
{
if (value >= 0)
{
staticDataVolume = value;
}
else
{
throw new ArgumentOutOfRangeException("value", "StaticDataVolume must be >=0");
}
}
}
// use fifo cache replacement strategy instead of random
private bool fifoCache = false;
public bool FifoCache
{
get { return fifoCache; }
set { fifoCache = value; }
}
// pin all requests
private bool pinning = false;
public bool Pinning
{
get { return pinning; }
set { pinning = value; }
}
public Parameters()
{
numRequests = Settings.Default.NumRequests;
finalizableRate = Settings.Default.FinalizableRate;
cacheReplacementRate = Settings.Default.CacheReplacementRate;
survivalRate = Settings.Default.SurvivalRate;
numPasses = Settings.Default.NumPasses;
randomSeed = Settings.Default.RandomSeed;
allocationVolume = Settings.Default.AllocationVolume;
cacheSize = Settings.Default.CacheSize;
steadyStateFactor = Settings.Default.SteadyStateFactor;
staticDataVolume = Settings.Default.StaticDataVolume;
fifoCache = Settings.Default.FifoCache;
pinning = Settings.Default.Pinning;
}
// gets and stores command-line parameters
public bool GetParams(string[] args)
{
try
{
for (int i = 0; i < args.Length; i++)
{
string str = args[i].ToLower();
if (str.StartsWith("/randomseed:"))
{
int randomSeed = 0;
if (!Int32.TryParse(str.Substring("/randomseed:".Length), out randomSeed))
{
Console.WriteLine("Invalid randomseed");
return false;
}
else
{
//Console.WriteLine("randomseed: {0}", randomSeed);
RandomSeed = randomSeed;
}
}
else if (str.StartsWith("/finalizablerate:"))
{
float finalizableRate = 0;
if (
!float.TryParse(
str.Substring("/finalizablerate:".Length),
out finalizableRate
)
)
{
Console.WriteLine("Invalid finalizablerate");
return false;
}
else
{
//Console.WriteLine("finalizablerate: {0}", finalizableRate);
this.finalizableRate = finalizableRate;
}
}
else if (str.StartsWith("/cachereplacementrate:"))
{
float cacheReplacementRate = 0;
if (
!float.TryParse(
str.Substring("/cachereplacementrate:".Length),
out cacheReplacementRate
)
)
{
Console.WriteLine("Invalid cachereplacementrate");
return false;
}
else
{
//Console.WriteLine("cachereplacementrate: {0}", cacheReplacementRate);
this.cacheReplacementRate = cacheReplacementRate;
}
}
else if (str.StartsWith("/survivalrate:"))
{
float survivalRate = 0;
if (
!float.TryParse(
str.Substring("/survivalrate:".Length),
out survivalRate
)
)
{
Console.WriteLine("Invalid survivalrate");
return false;
}
else
{
//Console.WriteLine("survivalrate: {0}", survivalRate);
this.survivalRate = survivalRate;
}
}
else if (str.StartsWith("/numpasses:"))
{
int numPasses = 0;
if (!Int32.TryParse(str.Substring("/numpasses:".Length), out numPasses))
{
Console.WriteLine("Invalid numpasses");
return false;
}
else
{
//Console.WriteLine("numpasses: {0}", numPasses);
this.numPasses = numPasses;
}
}
else if (str.StartsWith("/allocationvolume:"))
{
int allocationVolume = 0;
if (
!Int32.TryParse(
str.Substring("/allocationvolume:".Length),
out allocationVolume
)
)
{
Console.WriteLine("Invalid allocationvolume");
return false;
}
else
{
//Console.WriteLine("allocationvolume: {0}", allocationVolume);
this.allocationVolume = allocationVolume;
}
}
else if (str.StartsWith("/cachesize:"))
{
int cacheSize = 0;
if (!Int32.TryParse(str.Substring("/cachesize:".Length), out cacheSize))
{
Console.WriteLine("Invalid cachesize");
return false;
}
else
{
//Console.WriteLine("cachesize: {0}", cacheSize);
this.cacheSize = cacheSize;
}
}
else if (str.StartsWith("/steadystatefactor:"))
{
int steadyStateFactor = 0;
if (
!Int32.TryParse(
str.Substring("/steadystatefactor:".Length),
out steadyStateFactor
)
)
{
Console.WriteLine("Invalid steadystatefactor");
return false;
}
else
{
//Console.WriteLine("steadystatefactor: {0}", steadyStateFactor);
this.steadyStateFactor = steadyStateFactor;
}
}
else if (str.StartsWith("/numrequests:"))
{
int numRequests = 0;
if (!Int32.TryParse(str.Substring("/numrequests:".Length), out numRequests))
{
Console.WriteLine("Invalid numrequests");
return false;
}
else
{
//Console.WriteLine("numrequests: {0}", numRequests);
this.numRequests = numRequests;
}
}
else if (str.StartsWith("/staticdatavolume:"))
{
int staticDataVolume = 0;
if (
!Int32.TryParse(
str.Substring("/staticdatavolume:".Length),
out staticDataVolume
)
)
{
Console.WriteLine("Invalid staticdatavolume");
return false;
}
else
{
//Console.WriteLine("staticdatavolume: {0}", staticDataVolume);
this.staticDataVolume = staticDataVolume;
}
}
else if (str.StartsWith("/fifocache:"))
{
int fifoCache = 0;
if (!Int32.TryParse(str.Substring("/fifocache:".Length), out fifoCache))
{
Console.WriteLine("Invalid fifocache");
return false;
}
else
{
// Console.WriteLine("fifocache: {0}", fifoCache);
if (fifoCache == 0)
{
this.fifoCache = false;
}
else
{
this.fifoCache = true;
}
}
}
else if (str.StartsWith("/pinning:"))
{
int pinning = 0;
if (!Int32.TryParse(str.Substring("/pinning:".Length), out pinning))
{
Console.WriteLine("Invalid pinning");
return false;
}
else
{
//Console.WriteLine("pinning: {0}", pinning);
if (pinning == 0)
{
this.pinning = false;
}
else
{
this.pinning = true;
}
}
}
else if (str.Equals("/?"))
{
return false;
}
else
{
Console.WriteLine("Invalid parameter");
return false;
}
}
}
catch (ArgumentOutOfRangeException e)
{
Console.WriteLine(e.Message);
return false;
}
return true;
}
}
}
| 36.189956
| 105
| 0.367481
|
[
"MIT"
] |
belav/runtime
|
src/tests/GC/Scenarios/ServerModel/parameters.cs
| 16,575
|
C#
|
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using Couchbase.Linq.QueryGeneration;
using Couchbase.Linq.QueryGeneration.MethodCallTranslators;
using Moq;
using NUnit.Framework;
namespace Couchbase.Linq.UnitTests.QueryGeneration.MethodCallTranslators
{
class N1QlFunctionMethodCallTranslatorTests
{
#region Constructor
[Test]
public void Constructor_NoMethod_ThrowsArgumentNullException()
{
// Act/Assert
// ReSharper disable once ObjectCreationAsStatement
var result = Assert.Throws<ArgumentNullException>(() => new N1QlFunctionMethodCallTranslator(null, new N1QlFunctionAttribute("FUNC")));
Assert.AreEqual("methodInfo", result.ParamName);
}
[Test]
public void Constructor_InstanceMethod_ThrowsArgumentException()
{
// Arrange
var method = typeof (string).GetMethod("Clone");
// Act/Assert
// ReSharper disable once ObjectCreationAsStatement
var result = Assert.Throws<ArgumentException>(() => new N1QlFunctionMethodCallTranslator(method, new N1QlFunctionAttribute("FUNC")));
Assert.AreEqual("methodInfo", result.ParamName);
}
[Test]
public void Constructor_NoAttribute_ThrowsArgumentNullException()
{
// Arrange
var method = typeof(Methods).GetMethod("Method0");
// Act/Assert
// ReSharper disable once ObjectCreationAsStatement
var result = Assert.Throws<ArgumentNullException>(() => new N1QlFunctionMethodCallTranslator(method, null));
Assert.AreEqual("attribute", result.ParamName);
}
#endregion
#region Properties
[Test]
public void SupportedMethods_ReturnsMethodInfoFromConstructor()
{
// Arrange
var method = typeof(Methods).GetMethod("Method0");
var translator = new N1QlFunctionMethodCallTranslator(method, new N1QlFunctionAttribute("FUNC"));
// Act
var result = new List<MethodInfo>(translator.SupportMethods);
// Assert
Assert.Contains(method, result);
}
#endregion
#region Translate
[Test]
public void Translate_NoMethod_ThrowsArgumentNullException()
{
// Arrange
var visitor = new Mock<N1QlExpressionTreeVisitor>(new N1QlQueryGenerationContext())
{
CallBase = true
};
var method = typeof(Methods).GetMethod("Method0");
var transformer = new N1QlFunctionMethodCallTranslator(method, new N1QlFunctionAttribute("FUNC"));
// Act/Assert
var result = Assert.Throws<ArgumentNullException>(() => transformer.Translate(null, visitor.Object));
Assert.AreEqual("methodCallExpression", result.ParamName);
}
[Test]
public void Translate_MismatchedMethod_ThrowsArgumentException()
{
// Arrange
var visitor = new Mock<N1QlExpressionTreeVisitor>(new N1QlQueryGenerationContext())
{
CallBase = true
};
var method = typeof(Methods).GetMethod("Method1");
var expression = Expression.Call(typeof(Methods).GetMethod("Method0"));
var transformer = new N1QlFunctionMethodCallTranslator(method, new N1QlFunctionAttribute("FUNC"));
// Act/Assert
var result = Assert.Throws<ArgumentException>(() => transformer.Translate(expression, visitor.Object));
Assert.AreEqual("methodCallExpression", result.ParamName);
}
[Test]
public void Translate_NoVisitor_ThrowsArgumentNullException()
{
// Arrange
var method = typeof(Methods).GetMethod("Method0");
var expression = Expression.Call(method);
var transformer = new N1QlFunctionMethodCallTranslator(method, new N1QlFunctionAttribute("FUNC"));
// Act/Assert
var result = Assert.Throws<ArgumentNullException>(() => transformer.Translate(expression, null));
Assert.AreEqual("expressionTreeVisitor", result.ParamName);
}
[Test]
public void Translate_NoParameters_RendersCorrectly()
{
// Arrange
var visitor = new Mock<N1QlExpressionTreeVisitor>(new N1QlQueryGenerationContext())
{
CallBase = true
};
var method = typeof (Methods).GetMethod("Method0");
var expression = Expression.Call(method);
var transformer = new N1QlFunctionMethodCallTranslator(method, new N1QlFunctionAttribute("FUNC"));
// Act
transformer.Translate(expression, visitor.Object);
var result = visitor.Object.GetN1QlExpression();
// Assert
Assert.AreEqual("FUNC()", result);
}
[Test]
public void Translate_OneParameter_RendersCorrectly()
{
// Arrange
var visitor = new Mock<N1QlExpressionTreeVisitor>(new N1QlQueryGenerationContext())
{
CallBase = true
};
var method = typeof(Methods).GetMethod("Method1");
var expression = Expression.Call(method,
Expression.Constant("arg1"));
var transformer = new N1QlFunctionMethodCallTranslator(method, new N1QlFunctionAttribute("FUNC"));
// Act
transformer.Translate(expression, visitor.Object);
var result = visitor.Object.GetN1QlExpression();
// Assert
Assert.AreEqual("FUNC('arg1')", result);
}
[Test]
public void Translate_TwoParameters_RendersCorrectly()
{
// Arrange
var visitor = new Mock<N1QlExpressionTreeVisitor>(new N1QlQueryGenerationContext())
{
CallBase = true
};
var method = typeof (Methods).GetMethod("Method2");
var expression = Expression.Call(method,
Expression.Constant("arg1"),
Expression.Constant("arg2"));
var transformer = new N1QlFunctionMethodCallTranslator(method, new N1QlFunctionAttribute("FUNC"));
// Act
transformer.Translate(expression, visitor.Object);
var result = visitor.Object.GetN1QlExpression();
// Assert
Assert.AreEqual("FUNC('arg1', 'arg2')", result);
}
#endregion
#region Helpers
[SuppressMessage("ReSharper", "UnusedMember.Local")]
[SuppressMessage("ReSharper", "UnusedParameter.Local")]
private class Methods
{
public static string Method0()
{
throw new NotImplementedException();
}
public static string Method1(string param1)
{
throw new NotImplementedException();
}
public static string Method2(string param1, string param2)
{
throw new NotImplementedException();
}
}
#endregion
}
}
| 29.559524
| 147
| 0.602497
|
[
"Apache-2.0"
] |
RossMerr/CouchbaseNetLinq
|
Src/src/Couchbase.Linq.UnitTests/QueryGeneration/MethodCallTranslators/N1QlFunctionMethodCallTranslatorTests.cs
| 7,451
|
C#
|
using Microsoft.Dynamics.Framework.UI.Extensibility;
using Microsoft.Dynamics.Framework.UI.Extensibility.WinForms;
using System.Windows.Forms;
using System.Data;
using System;
namespace NAVDataGridView
{
[ControlAddInExport("NAVDataGridView")]
public class NAVDataGrid : WinFormsControlAddInBase
{
private DataGridView dataGridView;
[ApplicationVisible]
public event ControlAddInEventHandler ControlAddIn;
protected override Control CreateControl()
{
dataGridView = new DataGridView();
dataGridView.Dock = DockStyle.Fill;
dataGridView.ReadOnly = true;
ControlAddIn(0, string.Empty);
return dataGridView;
}
[ApplicationVisible]
public void UpdateView(DataTable dataTable)
{
dataGridView.DataSource = dataTable;
}
}
}
| 26.657143
| 62
| 0.636656
|
[
"MIT"
] |
PacktPublishing/Extending-Microsoft-Dynamics-NAV-2016-Cookbook
|
Chapter07/Recipe 8/NAVDataGridView/NAVDataGridView/NAVDataGrid.cs
| 935
|
C#
|
namespace AsterNET.Manager.Action
{
/// <summary>
/// The ZapTransferAction transfers a zap channel.
/// </summary>
public class ZapTransferAction : ManagerAction
{
/// <summary>
/// Get the name of this action, i.e. "ZapTransfer".
/// </summary>
public override string Action
{
get { return "ZapTransfer"; }
}
/// <summary>
/// Get/Set the number of the zap channel to transfer.<br />
/// This property is mandatory.
/// </summary>
public int ZapChannel { get; set; }
}
}
| 27.863636
| 72
| 0.528548
|
[
"MIT"
] |
1stco/AsterNET
|
Asterisk.2013/OldAsterNET/Asterisk.NET/Manager/Action/ZapTransferAction.cs
| 613
|
C#
|
using UnityEngine;
using System.Collections;
using RootMotion.FinalIK;
namespace RootMotion.Demos {
/// <summary>
/// Demo of exploding a viking using FBBIK
/// </summary>
public class ExplosionDemo : MonoBehaviour {
public SimpleLocomotion character; // Reference to the SimpleLocomotion component
public float forceMlp = 1f; // Explosion force
public float upForce = 1f; // Explosion up forve
public float weightFalloffSpeed = 1f; // The speed of explosion falloff
public AnimationCurve weightFalloff; // Explosion weight falloff
public AnimationCurve explosionForceByDistance; // The force of the explosion relative to character distance to the bomb
public AnimationCurve scale; // Scaling the bomb GameObject with the explosion
private float weight = 0f;
private Vector3 defaultScale = Vector3.one;
private Rigidbody r;
private FullBodyBipedIK ik;
void Start() {
// Storing the default scale of the bomb
defaultScale = transform.localScale;
r = character.GetComponent<Rigidbody>();
ik = character.GetComponent<FullBodyBipedIK>();
}
// Update is called once per frame
void Update () {
weight = Mathf.Clamp(weight - Time.deltaTime * weightFalloffSpeed, 0f, 1f);
// Exploding the bomb
if (Input.GetKeyDown(KeyCode.E) && character.isGrounded) {
// Set FBBIK weight to 1
ik.solver.IKPositionWeight = 1f;
// Set limb effector positions to where they are at the momemt
ik.solver.leftHandEffector.position = ik.solver.leftHandEffector.bone.position;
ik.solver.rightHandEffector.position = ik.solver.rightHandEffector.bone.position;
ik.solver.leftFootEffector.position = ik.solver.leftFootEffector.bone.position;
ik.solver.rightFootEffector.position = ik.solver.rightFootEffector.bone.position;
weight = 1f;
// Add explosion force to the character rigidbody
Vector3 direction = r.position - transform.position;
direction.y = 0f;
float explosionForce = explosionForceByDistance.Evaluate(direction.magnitude);
r.velocity = (direction.normalized + (Vector3.up * upForce)) * explosionForce * forceMlp;
}
if (weight < 0.5f && character.isGrounded) {
weight = Mathf.Clamp(weight - Time.deltaTime * 3f, 0f, 1f);
}
// Set effector weights
SetEffectorWeights(weightFalloff.Evaluate(weight));
// Set bomb scale
transform.localScale = scale.Evaluate(weight) * defaultScale;
}
// Set FBBIK limb end-effector weights to value
private void SetEffectorWeights(float w) {
ik.solver.leftHandEffector.positionWeight = w;
ik.solver.rightHandEffector.positionWeight = w;
ik.solver.leftFootEffector.positionWeight = w;
ik.solver.rightFootEffector.positionWeight = w;
}
}
}
| 35.298701
| 122
| 0.738779
|
[
"MIT"
] |
669-Development-Team/Mecha-Fighter-VR
|
Mecha Fighter VR/Assets/Plugins/RootMotion/FinalIK/_DEMOS/FBBIK/Scripts/ExplosionDemo.cs
| 2,720
|
C#
|
using System;
namespace PuertsStaticWrap
{
public static class UnityEngine_ParticleSystem_PlaybackState_Wrap
{
[Puerts.MonoPInvokeCallback(typeof(Puerts.V8ConstructorCallback))]
private static IntPtr Constructor(IntPtr isolate, IntPtr info, int paramLen, long data)
{
try
{
Puerts.PuertsDLL.ThrowException(isolate, "invalid arguments to UnityEngine.ParticleSystem.PlaybackState constructor");
}
catch (Exception e)
{
Puerts.PuertsDLL.ThrowException(isolate, "c# exception:" + e.Message + ",stack:" + e.StackTrace);
}
return IntPtr.Zero;
}
public static Puerts.TypeRegisterInfo GetRegisterInfo()
{
return new Puerts.TypeRegisterInfo()
{
BlittableCopy = false,
Constructor = Constructor,
Methods = new System.Collections.Generic.Dictionary<Puerts.MethodKey, Puerts.V8FunctionCallback>()
{
},
Properties = new System.Collections.Generic.Dictionary<string, Puerts.PropertyRegisterInfo>()
{
}
};
}
}
}
| 30.4
| 134
| 0.524123
|
[
"MIT"
] |
HFX-93/luban_examples
|
Projects/TypeScript_Unity_Puerts_Bin/Assets/Gen/UnityEngine_ParticleSystem_PlaybackState_Wrap.cs
| 1,370
|
C#
|
using System.Threading;
using System.Threading.Tasks;
using Duende.IdentityServer.Models;
using IdOps.IdentityServer.Model;
using IdOps.IdentityServer.Storage;
namespace IdOps.IdentityServer.ResourceUpdate
{
public class ClientMessageConsumer : ResourceMessageConsumer<IdOpsClient>
{
private readonly IClientRepository _repository;
public ClientMessageConsumer(IClientRepository clientRepository)
{
_repository = clientRepository;
}
public override string MessageType => nameof(Client);
public override async Task<UpdateResourceResult> Process(
IdOpsClient data,
CancellationToken cancellationToken) =>
await _repository.UpdateAsync(data, cancellationToken);
}
}
| 29.807692
| 77
| 0.727742
|
[
"MIT"
] |
SwissLife-OSS/IdOps
|
src/IdentityServer/src/IdentityServer.Core/Resources/Client/ClientMessageConsumer.cs
| 775
|
C#
|
/* _BEGIN_TEMPLATE_
{
"id": "TB_TagTeam_ClearBoard",
"name": [
"你的下一个目标来了",
"Your Next Victim Comes"
],
"text": [
"消灭所有随从。吸取所有法力值。获得5点生命值。",
"Destroy all minions. Drain all Mana. Gain 5 Health."
],
"cardClass": "NEUTRAL",
"type": "SPELL",
"cost": 10,
"rarity": null,
"set": "TB",
"collectible": null,
"dbfId": 40999
}
_END_TEMPLATE_ */
namespace HREngine.Bots
{
class Sim_TB_TagTeam_ClearBoard : SimTemplate
{
}
}
| 17.259259
| 57
| 0.60515
|
[
"MIT"
] |
chi-rei-den/Silverfish
|
cards/TB/TB/Sim_TB_TagTeam_ClearBoard.cs
| 528
|
C#
|
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// <auto-generated/>
#nullable disable
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Threading;
using System.Threading.Tasks;
using Azure;
using Azure.Core;
using Azure.Core.Pipeline;
using Azure.ResourceManager;
using Azure.ResourceManager.Core;
namespace Azure.ResourceManager.CosmosDB
{
/// <summary> A Class representing a SqlStoredProcedure along with the instance operations that can be performed on it. </summary>
public partial class SqlStoredProcedure : ArmResource
{
/// <summary> Generate the resource identifier of a <see cref="SqlStoredProcedure"/> instance. </summary>
public static ResourceIdentifier CreateResourceIdentifier(string subscriptionId, string resourceGroupName, string accountName, string databaseName, string containerName, string storedProcedureName)
{
var resourceId = $"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/sqlDatabases/{databaseName}/containers/{containerName}/storedProcedures/{storedProcedureName}";
return new ResourceIdentifier(resourceId);
}
private readonly ClientDiagnostics _sqlStoredProcedureSqlResourcesClientDiagnostics;
private readonly SqlResourcesRestOperations _sqlStoredProcedureSqlResourcesRestClient;
private readonly SqlStoredProcedureData _data;
/// <summary> Initializes a new instance of the <see cref="SqlStoredProcedure"/> class for mocking. </summary>
protected SqlStoredProcedure()
{
}
/// <summary> Initializes a new instance of the <see cref = "SqlStoredProcedure"/> class. </summary>
/// <param name="client"> The client parameters to use in these operations. </param>
/// <param name="data"> The resource that is the target of operations. </param>
internal SqlStoredProcedure(ArmClient client, SqlStoredProcedureData data) : this(client, data.Id)
{
HasData = true;
_data = data;
}
/// <summary> Initializes a new instance of the <see cref="SqlStoredProcedure"/> class. </summary>
/// <param name="client"> The client parameters to use in these operations. </param>
/// <param name="id"> The identifier of the resource that is the target of operations. </param>
internal SqlStoredProcedure(ArmClient client, ResourceIdentifier id) : base(client, id)
{
_sqlStoredProcedureSqlResourcesClientDiagnostics = new ClientDiagnostics("Azure.ResourceManager.CosmosDB", ResourceType.Namespace, DiagnosticOptions);
Client.TryGetApiVersion(ResourceType, out string sqlStoredProcedureSqlResourcesApiVersion);
_sqlStoredProcedureSqlResourcesRestClient = new SqlResourcesRestOperations(_sqlStoredProcedureSqlResourcesClientDiagnostics, Pipeline, DiagnosticOptions.ApplicationId, BaseUri, sqlStoredProcedureSqlResourcesApiVersion);
#if DEBUG
ValidateResourceId(Id);
#endif
}
/// <summary> Gets the resource type for the operations. </summary>
public static readonly ResourceType ResourceType = "Microsoft.DocumentDB/databaseAccounts/sqlDatabases/containers/storedProcedures";
/// <summary> Gets whether or not the current instance has data. </summary>
public virtual bool HasData { get; }
/// <summary> Gets the data representing this Feature. </summary>
/// <exception cref="InvalidOperationException"> Throws if there is no data loaded in the current instance. </exception>
public virtual SqlStoredProcedureData Data
{
get
{
if (!HasData)
throw new InvalidOperationException("The current instance does not have data, you must call Get first.");
return _data;
}
}
internal static void ValidateResourceId(ResourceIdentifier id)
{
if (id.ResourceType != ResourceType)
throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "Invalid resource type {0} expected {1}", id.ResourceType, ResourceType), nameof(id));
}
/// <summary> Gets the SQL storedProcedure under an existing Azure Cosmos DB database account. </summary>
/// <param name="cancellationToken"> The cancellation token to use. </param>
public async virtual Task<Response<SqlStoredProcedure>> GetAsync(CancellationToken cancellationToken = default)
{
using var scope = _sqlStoredProcedureSqlResourcesClientDiagnostics.CreateScope("SqlStoredProcedure.Get");
scope.Start();
try
{
var response = await _sqlStoredProcedureSqlResourcesRestClient.GetSqlStoredProcedureAsync(Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Parent.Parent.Name, Id.Parent.Parent.Name, Id.Parent.Name, Id.Name, cancellationToken).ConfigureAwait(false);
if (response.Value == null)
throw await _sqlStoredProcedureSqlResourcesClientDiagnostics.CreateRequestFailedExceptionAsync(response.GetRawResponse()).ConfigureAwait(false);
return Response.FromValue(new SqlStoredProcedure(Client, response.Value), response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary> Gets the SQL storedProcedure under an existing Azure Cosmos DB database account. </summary>
/// <param name="cancellationToken"> The cancellation token to use. </param>
public virtual Response<SqlStoredProcedure> Get(CancellationToken cancellationToken = default)
{
using var scope = _sqlStoredProcedureSqlResourcesClientDiagnostics.CreateScope("SqlStoredProcedure.Get");
scope.Start();
try
{
var response = _sqlStoredProcedureSqlResourcesRestClient.GetSqlStoredProcedure(Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Parent.Parent.Name, Id.Parent.Parent.Name, Id.Parent.Name, Id.Name, cancellationToken);
if (response.Value == null)
throw _sqlStoredProcedureSqlResourcesClientDiagnostics.CreateRequestFailedException(response.GetRawResponse());
return Response.FromValue(new SqlStoredProcedure(Client, response.Value), response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary> Deletes an existing Azure Cosmos DB SQL storedProcedure. </summary>
/// <param name="waitForCompletion"> Waits for the completion of the long running operations. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
public async virtual Task<ArmOperation> DeleteAsync(bool waitForCompletion, CancellationToken cancellationToken = default)
{
using var scope = _sqlStoredProcedureSqlResourcesClientDiagnostics.CreateScope("SqlStoredProcedure.Delete");
scope.Start();
try
{
var response = await _sqlStoredProcedureSqlResourcesRestClient.DeleteSqlStoredProcedureAsync(Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Parent.Parent.Name, Id.Parent.Parent.Name, Id.Parent.Name, Id.Name, cancellationToken).ConfigureAwait(false);
var operation = new CosmosDBArmOperation(_sqlStoredProcedureSqlResourcesClientDiagnostics, Pipeline, _sqlStoredProcedureSqlResourcesRestClient.CreateDeleteSqlStoredProcedureRequest(Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Parent.Parent.Name, Id.Parent.Parent.Name, Id.Parent.Name, Id.Name).Request, response, OperationFinalStateVia.Location);
if (waitForCompletion)
await operation.WaitForCompletionResponseAsync(cancellationToken).ConfigureAwait(false);
return operation;
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary> Deletes an existing Azure Cosmos DB SQL storedProcedure. </summary>
/// <param name="waitForCompletion"> Waits for the completion of the long running operations. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
public virtual ArmOperation Delete(bool waitForCompletion, CancellationToken cancellationToken = default)
{
using var scope = _sqlStoredProcedureSqlResourcesClientDiagnostics.CreateScope("SqlStoredProcedure.Delete");
scope.Start();
try
{
var response = _sqlStoredProcedureSqlResourcesRestClient.DeleteSqlStoredProcedure(Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Parent.Parent.Name, Id.Parent.Parent.Name, Id.Parent.Name, Id.Name, cancellationToken);
var operation = new CosmosDBArmOperation(_sqlStoredProcedureSqlResourcesClientDiagnostics, Pipeline, _sqlStoredProcedureSqlResourcesRestClient.CreateDeleteSqlStoredProcedureRequest(Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Parent.Parent.Name, Id.Parent.Parent.Name, Id.Parent.Name, Id.Name).Request, response, OperationFinalStateVia.Location);
if (waitForCompletion)
operation.WaitForCompletionResponse(cancellationToken);
return operation;
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary> Add a tag to the current resource. </summary>
/// <param name="key"> The key for the tag. </param>
/// <param name="value"> The value for the tag. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="key"/> or <paramref name="value"/> is null. </exception>
public async virtual Task<Response<SqlStoredProcedure>> AddTagAsync(string key, string value, CancellationToken cancellationToken = default)
{
if (key == null)
{
throw new ArgumentNullException(nameof(key));
}
if (value == null)
{
throw new ArgumentNullException(nameof(value));
}
using var scope = _sqlStoredProcedureSqlResourcesClientDiagnostics.CreateScope("SqlStoredProcedure.AddTag");
scope.Start();
try
{
var originalTags = await TagResource.GetAsync(cancellationToken).ConfigureAwait(false);
originalTags.Value.Data.Properties.TagsValue[key] = value;
await TagResource.CreateOrUpdateAsync(true, originalTags.Value.Data, cancellationToken: cancellationToken).ConfigureAwait(false);
var originalResponse = await _sqlStoredProcedureSqlResourcesRestClient.GetSqlStoredProcedureAsync(Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Parent.Parent.Name, Id.Parent.Parent.Name, Id.Parent.Name, Id.Name, cancellationToken).ConfigureAwait(false);
return Response.FromValue(new SqlStoredProcedure(Client, originalResponse.Value), originalResponse.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary> Add a tag to the current resource. </summary>
/// <param name="key"> The key for the tag. </param>
/// <param name="value"> The value for the tag. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="key"/> or <paramref name="value"/> is null. </exception>
public virtual Response<SqlStoredProcedure> AddTag(string key, string value, CancellationToken cancellationToken = default)
{
if (key == null)
{
throw new ArgumentNullException(nameof(key));
}
if (value == null)
{
throw new ArgumentNullException(nameof(value));
}
using var scope = _sqlStoredProcedureSqlResourcesClientDiagnostics.CreateScope("SqlStoredProcedure.AddTag");
scope.Start();
try
{
var originalTags = TagResource.Get(cancellationToken);
originalTags.Value.Data.Properties.TagsValue[key] = value;
TagResource.CreateOrUpdate(true, originalTags.Value.Data, cancellationToken: cancellationToken);
var originalResponse = _sqlStoredProcedureSqlResourcesRestClient.GetSqlStoredProcedure(Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Parent.Parent.Name, Id.Parent.Parent.Name, Id.Parent.Name, Id.Name, cancellationToken);
return Response.FromValue(new SqlStoredProcedure(Client, originalResponse.Value), originalResponse.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary> Replace the tags on the resource with the given set. </summary>
/// <param name="tags"> The set of tags to use as replacement. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="tags"/> is null. </exception>
public async virtual Task<Response<SqlStoredProcedure>> SetTagsAsync(IDictionary<string, string> tags, CancellationToken cancellationToken = default)
{
if (tags == null)
{
throw new ArgumentNullException(nameof(tags));
}
using var scope = _sqlStoredProcedureSqlResourcesClientDiagnostics.CreateScope("SqlStoredProcedure.SetTags");
scope.Start();
try
{
await TagResource.DeleteAsync(true, cancellationToken: cancellationToken).ConfigureAwait(false);
var originalTags = await TagResource.GetAsync(cancellationToken).ConfigureAwait(false);
originalTags.Value.Data.Properties.TagsValue.ReplaceWith(tags);
await TagResource.CreateOrUpdateAsync(true, originalTags.Value.Data, cancellationToken: cancellationToken).ConfigureAwait(false);
var originalResponse = await _sqlStoredProcedureSqlResourcesRestClient.GetSqlStoredProcedureAsync(Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Parent.Parent.Name, Id.Parent.Parent.Name, Id.Parent.Name, Id.Name, cancellationToken).ConfigureAwait(false);
return Response.FromValue(new SqlStoredProcedure(Client, originalResponse.Value), originalResponse.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary> Replace the tags on the resource with the given set. </summary>
/// <param name="tags"> The set of tags to use as replacement. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="tags"/> is null. </exception>
public virtual Response<SqlStoredProcedure> SetTags(IDictionary<string, string> tags, CancellationToken cancellationToken = default)
{
if (tags == null)
{
throw new ArgumentNullException(nameof(tags));
}
using var scope = _sqlStoredProcedureSqlResourcesClientDiagnostics.CreateScope("SqlStoredProcedure.SetTags");
scope.Start();
try
{
TagResource.Delete(true, cancellationToken: cancellationToken);
var originalTags = TagResource.Get(cancellationToken);
originalTags.Value.Data.Properties.TagsValue.ReplaceWith(tags);
TagResource.CreateOrUpdate(true, originalTags.Value.Data, cancellationToken: cancellationToken);
var originalResponse = _sqlStoredProcedureSqlResourcesRestClient.GetSqlStoredProcedure(Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Parent.Parent.Name, Id.Parent.Parent.Name, Id.Parent.Name, Id.Name, cancellationToken);
return Response.FromValue(new SqlStoredProcedure(Client, originalResponse.Value), originalResponse.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary> Removes a tag by key from the resource. </summary>
/// <param name="key"> The key for the tag. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="key"/> is null. </exception>
public async virtual Task<Response<SqlStoredProcedure>> RemoveTagAsync(string key, CancellationToken cancellationToken = default)
{
if (key == null)
{
throw new ArgumentNullException(nameof(key));
}
using var scope = _sqlStoredProcedureSqlResourcesClientDiagnostics.CreateScope("SqlStoredProcedure.RemoveTag");
scope.Start();
try
{
var originalTags = await TagResource.GetAsync(cancellationToken).ConfigureAwait(false);
originalTags.Value.Data.Properties.TagsValue.Remove(key);
await TagResource.CreateOrUpdateAsync(true, originalTags.Value.Data, cancellationToken: cancellationToken).ConfigureAwait(false);
var originalResponse = await _sqlStoredProcedureSqlResourcesRestClient.GetSqlStoredProcedureAsync(Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Parent.Parent.Name, Id.Parent.Parent.Name, Id.Parent.Name, Id.Name, cancellationToken).ConfigureAwait(false);
return Response.FromValue(new SqlStoredProcedure(Client, originalResponse.Value), originalResponse.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary> Removes a tag by key from the resource. </summary>
/// <param name="key"> The key for the tag. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="key"/> is null. </exception>
public virtual Response<SqlStoredProcedure> RemoveTag(string key, CancellationToken cancellationToken = default)
{
if (key == null)
{
throw new ArgumentNullException(nameof(key));
}
using var scope = _sqlStoredProcedureSqlResourcesClientDiagnostics.CreateScope("SqlStoredProcedure.RemoveTag");
scope.Start();
try
{
var originalTags = TagResource.Get(cancellationToken);
originalTags.Value.Data.Properties.TagsValue.Remove(key);
TagResource.CreateOrUpdate(true, originalTags.Value.Data, cancellationToken: cancellationToken);
var originalResponse = _sqlStoredProcedureSqlResourcesRestClient.GetSqlStoredProcedure(Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Parent.Parent.Name, Id.Parent.Parent.Name, Id.Parent.Name, Id.Name, cancellationToken);
return Response.FromValue(new SqlStoredProcedure(Client, originalResponse.Value), originalResponse.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
}
}
| 56.997151
| 368
| 0.662451
|
[
"MIT"
] |
vidai-msft/azure-sdk-for-net
|
sdk/cosmosdb/Azure.ResourceManager.CosmosDB/src/Generated/SqlStoredProcedure.cs
| 20,006
|
C#
|
using CryptoExchange.Net;
using CryptoExchange.Net.Objects;
using Newtonsoft.Json;
using Okex.Net.Converters;
using Okex.Net.CoreObjects;
using Okex.Net.Enums;
using Okex.Net.Helpers;
using Okex.Net.RestObjects.Funding;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
namespace Okex.Net
{
public partial class OkexClient
{
#region Funding API Endpoints
/// <summary>
/// Retrieve a list of all currencies. Not all currencies can be traded. Currencies that have not been defined in ISO 4217 may use a custom symbol.
/// </summary>
/// <param name="ct">Cancellation Token</param>
/// <returns></returns>
public virtual WebCallResult<IEnumerable<OkexCurrency>> GetCurrencies(CancellationToken ct = default) => GetCurrencies_Async(ct).Result;
/// <summary>
/// Retrieve a list of all currencies. Not all currencies can be traded. Currencies that have not been defined in ISO 4217 may use a custom symbol.
/// </summary>
/// <param name="ct">Cancellation Token</param>
/// <returns></returns>
public virtual async Task<WebCallResult<IEnumerable<OkexCurrency>>> GetCurrencies_Async(CancellationToken ct = default)
{
var result = await SendRequestAsync<OkexRestApiResponse<IEnumerable<OkexCurrency>>>(GetUrl(Endpoints_V5_Asset_Currencies), HttpMethod.Get, ct, null, true).ConfigureAwait(false);
if (!result.Success) return WebCallResult<IEnumerable<OkexCurrency>>.CreateErrorResult(result.ResponseStatusCode, result.ResponseHeaders, result.Error);
if (result.Data.ErrorCode > 0) return WebCallResult<IEnumerable<OkexCurrency>>.CreateErrorResult(result.ResponseStatusCode, result.ResponseHeaders, new ServerError(result.Data.ErrorCode, result.Data.ErrorMessage));
return new WebCallResult<IEnumerable<OkexCurrency>>(result.ResponseStatusCode, result.ResponseHeaders, result.Data.Data, null);
}
/// <summary>
/// Retrieve the balances of all the assets, and the amount that is available or on hold.
/// </summary>
/// <param name="currency">Currency</param>
/// <param name="ct">Cancellation Token</param>
/// <returns></returns>
public virtual WebCallResult<IEnumerable<OkexFundingBalance>> GetFundingBalance(string currency = null, CancellationToken ct = default) => GetFundingBalance_Async(currency, ct).Result;
/// <summary>
/// Retrieve the balances of all the assets, and the amount that is available or on hold.
/// </summary>
/// <param name="currency">Currency</param>
/// <param name="ct">Cancellation Token</param>
/// <returns></returns>
public virtual async Task<WebCallResult<IEnumerable<OkexFundingBalance>>> GetFundingBalance_Async(string currency = null, CancellationToken ct = default)
{
var parameters = new Dictionary<string, object>();
parameters.AddOptionalParameter("ccy", currency);
var result = await SendRequestAsync<OkexRestApiResponse<IEnumerable<OkexFundingBalance>>>(GetUrl(Endpoints_V5_Asset_Balances), HttpMethod.Get, ct, parameters, true).ConfigureAwait(false);
if (!result.Success) return WebCallResult<IEnumerable<OkexFundingBalance>>.CreateErrorResult(result.ResponseStatusCode, result.ResponseHeaders, result.Error);
if (result.Data.ErrorCode > 0) return WebCallResult<IEnumerable<OkexFundingBalance>>.CreateErrorResult(result.ResponseStatusCode, result.ResponseHeaders, new ServerError(result.Data.ErrorCode, result.Data.ErrorMessage));
return new WebCallResult<IEnumerable<OkexFundingBalance>>(result.ResponseStatusCode, result.ResponseHeaders, result.Data.Data, null);
}
/// <summary>
/// This endpoint supports the transfer of funds between your funding account and trading account, and from the master account to sub-accounts. Direct transfers between sub-accounts are not allowed.
/// </summary>
/// <param name="currency">Currency</param>
/// <param name="amount">Amount</param>
/// <param name="type">Transfer type</param>
/// <param name="fromAccount">The remitting account</param>
/// <param name="toAccount">The beneficiary account</param>
/// <param name="subAccountName">Sub Account Name</param>
/// <param name="fromInstrumentId">MARGIN trading pair (e.g. BTC-USDT) or contract underlying (e.g. BTC-USD) to be transferred out.</param>
/// <param name="toInstrumentId">MARGIN trading pair (e.g. BTC-USDT) or contract underlying (e.g. BTC-USD) to be transferred in.</param>
/// <param name="ct">Cancellation Token</param>
/// <returns></returns>
public virtual WebCallResult<OkexTransferResponse> FundTransfer(
string currency,
decimal amount,
OkexTransferType type,
OkexAccount fromAccount,
OkexAccount toAccount,
string subAccountName = null,
string fromInstrumentId = null,
string toInstrumentId = null,
CancellationToken ct = default) => FundTransfer_Async(
currency,
amount,
type,
fromAccount,
toAccount,
subAccountName,
fromInstrumentId,
toInstrumentId,
ct).Result;
/// <summary>
/// This endpoint supports the transfer of funds between your funding account and trading account, and from the master account to sub-accounts. Direct transfers between sub-accounts are not allowed.
/// </summary>
/// <param name="currency">Currency</param>
/// <param name="amount">Amount</param>
/// <param name="type">Transfer type</param>
/// <param name="fromAccount">The remitting account</param>
/// <param name="toAccount">The beneficiary account</param>
/// <param name="subAccountName">Sub Account Name</param>
/// <param name="fromInstrumentId">MARGIN trading pair (e.g. BTC-USDT) or contract underlying (e.g. BTC-USD) to be transferred out.</param>
/// <param name="toInstrumentId">MARGIN trading pair (e.g. BTC-USDT) or contract underlying (e.g. BTC-USD) to be transferred in.</param>
/// <param name="ct">Cancellation Token</param>
/// <returns></returns>
public virtual async Task<WebCallResult<OkexTransferResponse>> FundTransfer_Async(
string currency,
decimal amount,
OkexTransferType type,
OkexAccount fromAccount,
OkexAccount toAccount,
string subAccountName = null,
string fromInstrumentId = null,
string toInstrumentId = null,
CancellationToken ct = default)
{
var parameters = new Dictionary<string, object> {
{ "ccy",currency},
{ "amt",amount.ToString(OkexGlobals.OkexCultureInfo)},
{ "type", JsonConvert.SerializeObject(type, new TransferTypeConverter(false)) },
{ "from", JsonConvert.SerializeObject(fromAccount, new AccountConverter(false)) },
{ "to", JsonConvert.SerializeObject(toAccount, new AccountConverter(false)) },
};
parameters.AddOptionalParameter("subAcct", subAccountName);
parameters.AddOptionalParameter("instId", fromInstrumentId);
parameters.AddOptionalParameter("toInstId", toInstrumentId);
var result = await SendRequestAsync<OkexRestApiResponse<IEnumerable<OkexTransferResponse>>>(GetUrl(Endpoints_V5_Asset_Transfer), HttpMethod.Post, ct, parameters, true).ConfigureAwait(false);
if (!result.Success) return WebCallResult<OkexTransferResponse>.CreateErrorResult(result.ResponseStatusCode, result.ResponseHeaders, result.Error);
if (result.Data.ErrorCode > 0) return WebCallResult<OkexTransferResponse>.CreateErrorResult(result.ResponseStatusCode, result.ResponseHeaders, new ServerError(result.Data.ErrorCode, result.Data.ErrorMessage));
return new WebCallResult<OkexTransferResponse>(result.ResponseStatusCode, result.ResponseHeaders, result.Data.Data.FirstOrDefault(), null);
}
/// <summary>
/// Query the billing record, you can get the latest 1 month historical data
/// </summary>
/// <param name="currency">Currency</param>
/// <param name="type">Bill type</param>
/// <param name="after">Pagination of data to return records earlier than the requested ts, Unix timestamp format in milliseconds, e.g. 1597026383085</param>
/// <param name="before">Pagination of data to return records newer than the requested ts, Unix timestamp format in milliseconds, e.g. 1597026383085</param>
/// <param name="limit">Number of results per request. The maximum is 100; the default is 100.</param>
/// <param name="ct">Cancellation Token</param>
/// <returns></returns>
public virtual WebCallResult<IEnumerable<OkexFundingBill>> GetFundingBillDetails(
string currency = null,
OkexFundingBillType? type = null,
long? after = null,
long? before = null,
int limit = 100,
CancellationToken ct = default) => GetFundingBillDetails_Async(
currency,
type,
after,
before,
limit,
ct).Result;
/// <summary>
/// Query the billing record, you can get the latest 1 month historical data
/// </summary>
/// <param name="currency">Currency</param>
/// <param name="type">Bill type</param>
/// <param name="after">Pagination of data to return records earlier than the requested ts, Unix timestamp format in milliseconds, e.g. 1597026383085</param>
/// <param name="before">Pagination of data to return records newer than the requested ts, Unix timestamp format in milliseconds, e.g. 1597026383085</param>
/// <param name="limit">Number of results per request. The maximum is 100; the default is 100.</param>
/// <param name="ct">Cancellation Token</param>
/// <returns></returns>
public virtual async Task<WebCallResult<IEnumerable<OkexFundingBill>>> GetFundingBillDetails_Async(
string currency = null,
OkexFundingBillType? type = null,
long? after = null,
long? before = null,
int limit = 100,
CancellationToken ct = default)
{
if (limit < 1 || limit > 100)
throw new ArgumentException("Limit can be between 1-100.");
var parameters = new Dictionary<string, object>();
parameters.AddOptionalParameter("ccy", currency);
if (type.HasValue)
parameters.AddOptionalParameter("type", JsonConvert.SerializeObject(type, new FundingBillTypeConverter(false)));
parameters.AddOptionalParameter("after", after?.ToString(OkexGlobals.OkexCultureInfo));
parameters.AddOptionalParameter("before", before?.ToString(OkexGlobals.OkexCultureInfo));
parameters.AddOptionalParameter("limit", limit.ToString(OkexGlobals.OkexCultureInfo));
var result = await SendRequestAsync<OkexRestApiResponse<IEnumerable<OkexFundingBill>>>(GetUrl(Endpoints_V5_Asset_Bills), HttpMethod.Get, ct, parameters, true).ConfigureAwait(false);
if (!result.Success) return WebCallResult<IEnumerable<OkexFundingBill>>.CreateErrorResult(result.ResponseStatusCode, result.ResponseHeaders, result.Error);
if (result.Data.ErrorCode > 0) return WebCallResult<IEnumerable<OkexFundingBill>>.CreateErrorResult(result.ResponseStatusCode, result.ResponseHeaders, new ServerError(result.Data.ErrorCode, result.Data.ErrorMessage));
return new WebCallResult<IEnumerable<OkexFundingBill>>(result.ResponseStatusCode, result.ResponseHeaders, result.Data.Data, null);
}
/// <summary>
/// Retrieve the deposit addresses of currencies, including previously-used addresses.
/// </summary>
/// <param name="currency">Currency</param>
/// <param name="ct">Cancellation Token</param>
/// <returns></returns>
public virtual WebCallResult<IEnumerable<OkexDepositAddress>> GetDepositAddress(string currency = null, CancellationToken ct = default) => GetDepositAddress_Async(currency, ct).Result;
/// <summary>
/// Retrieve the deposit addresses of currencies, including previously-used addresses.
/// </summary>
/// <param name="currency">Currency</param>
/// <param name="ct">Cancellation Token</param>
/// <returns></returns>
public virtual async Task<WebCallResult<IEnumerable<OkexDepositAddress>>> GetDepositAddress_Async(string currency = null, CancellationToken ct = default)
{
var parameters = new Dictionary<string, object> {
{ "ccy", currency },
};
var result = await SendRequestAsync<OkexRestApiResponse<IEnumerable<OkexDepositAddress>>>(GetUrl(Endpoints_V5_Asset_DepositAddress), HttpMethod.Get, ct, parameters, true).ConfigureAwait(false);
if (!result.Success) return WebCallResult<IEnumerable<OkexDepositAddress>>.CreateErrorResult(result.ResponseStatusCode, result.ResponseHeaders, result.Error);
if (result.Data.ErrorCode > 0) return WebCallResult<IEnumerable<OkexDepositAddress>>.CreateErrorResult(result.ResponseStatusCode, result.ResponseHeaders, new ServerError(result.Data.ErrorCode, result.Data.ErrorMessage));
return new WebCallResult<IEnumerable<OkexDepositAddress>>(result.ResponseStatusCode, result.ResponseHeaders, result.Data.Data, null);
}
/// <summary>
/// Retrieve the deposit history of all currencies, up to 100 recent records in a year.
/// </summary>
/// <param name="currency">Currency</param>
/// <param name="transactionId">Transaction ID</param>
/// <param name="state">State</param>
/// <param name="after">Pagination of data to return records earlier than the requested ts, Unix timestamp format in milliseconds, e.g. 1597026383085</param>
/// <param name="before">Pagination of data to return records newer than the requested ts, Unix timestamp format in milliseconds, e.g. 1597026383085</param>
/// <param name="limit">Number of results per request. The maximum is 100; the default is 100.</param>
/// <param name="ct">Cancellation Token</param>
/// <returns></returns>
public virtual WebCallResult<IEnumerable<OkexDepositHistory>> GetDepositHistory(
string currency = null,
string transactionId = null,
OkexDepositState? state = null,
long? after = null,
long? before = null,
int limit = 100,
CancellationToken ct = default) => GetDepositHistory_Async(currency, transactionId, state, after, before, limit, ct).Result;
/// <summary>
/// Retrieve the deposit history of all currencies, up to 100 recent records in a year.
/// </summary>
/// <param name="currency">Currency</param>
/// <param name="transactionId">Transaction ID</param>
/// <param name="state">State</param>
/// <param name="after">Pagination of data to return records earlier than the requested ts, Unix timestamp format in milliseconds, e.g. 1597026383085</param>
/// <param name="before">Pagination of data to return records newer than the requested ts, Unix timestamp format in milliseconds, e.g. 1597026383085</param>
/// <param name="limit">Number of results per request. The maximum is 100; the default is 100.</param>
/// <param name="ct">Cancellation Token</param>
/// <returns></returns>
public virtual async Task<WebCallResult<IEnumerable<OkexDepositHistory>>> GetDepositHistory_Async(
string currency = null,
string transactionId = null,
OkexDepositState? state = null,
long? after = null,
long? before = null,
int limit = 100,
CancellationToken ct = default)
{
if (limit < 1 || limit > 100)
throw new ArgumentException("Limit can be between 1-100.");
var parameters = new Dictionary<string, object>();
parameters.AddOptionalParameter("ccy", currency);
parameters.AddOptionalParameter("txId", transactionId);
if (state.HasValue)
parameters.AddOptionalParameter("state", JsonConvert.SerializeObject(state, new DepositStateConverter(false)));
parameters.AddOptionalParameter("after", after?.ToString(OkexGlobals.OkexCultureInfo));
parameters.AddOptionalParameter("before", before?.ToString(OkexGlobals.OkexCultureInfo));
parameters.AddOptionalParameter("limit", limit.ToString(OkexGlobals.OkexCultureInfo));
var result = await SendRequestAsync<OkexRestApiResponse<IEnumerable<OkexDepositHistory>>>(GetUrl(Endpoints_V5_Asset_DepositHistory), HttpMethod.Get, ct, parameters, true).ConfigureAwait(false);
if (!result.Success) return WebCallResult<IEnumerable<OkexDepositHistory>>.CreateErrorResult(result.ResponseStatusCode, result.ResponseHeaders, result.Error);
if (result.Data.ErrorCode > 0) return WebCallResult<IEnumerable<OkexDepositHistory>>.CreateErrorResult(result.ResponseStatusCode, result.ResponseHeaders, new ServerError(result.Data.ErrorCode, result.Data.ErrorMessage));
return new WebCallResult<IEnumerable<OkexDepositHistory>>(result.ResponseStatusCode, result.ResponseHeaders, result.Data.Data, null);
}
/// <summary>
/// Withdrawal of tokens.
/// </summary>
/// <param name="currency">Currency</param>
/// <param name="amount">Amount</param>
/// <param name="destination">Withdrawal destination address</param>
/// <param name="toAddress">Verified digital currency address, email or mobile number. Some digital currency addresses are formatted as 'address+tag', e.g. 'ARDOR-7JF3-8F2E-QUWZ-CAN7F:123456'</param>
/// <param name="password">Trade password</param>
/// <param name="fee">Transaction fee</param>
/// <param name="chain">Chain name. There are multiple chains under some currencies, such as USDT has USDT-ERC20, USDT-TRC20, and USDT-Omni. If this parameter is not filled in because it is not available, it will default to the main chain.</param>
/// <param name="ct">Cancellation Token</param>
/// <returns></returns>
public virtual WebCallResult<OkexWithdrawalResponse> Withdraw(
string currency,
decimal amount,
OkexWithdrawalDestination destination,
string toAddress,
string password,
decimal fee,
string chain = null,
CancellationToken ct = default) => Withdraw_Async(
currency,
amount,
destination,
toAddress,
password,
fee,
chain,
ct).Result;
/// <summary>
/// Withdrawal of tokens.
/// </summary>
/// <param name="currency">Currency</param>
/// <param name="amount">Amount</param>
/// <param name="destination">Withdrawal destination address</param>
/// <param name="toAddress">Verified digital currency address, email or mobile number. Some digital currency addresses are formatted as 'address+tag', e.g. 'ARDOR-7JF3-8F2E-QUWZ-CAN7F:123456'</param>
/// <param name="password">Trade password</param>
/// <param name="fee">Transaction fee</param>
/// <param name="chain">Chain name. There are multiple chains under some currencies, such as USDT has USDT-ERC20, USDT-TRC20, and USDT-Omni. If this parameter is not filled in because it is not available, it will default to the main chain.</param>
/// <param name="ct">Cancellation Token</param>
/// <returns></returns>
public virtual async Task<WebCallResult<OkexWithdrawalResponse>> Withdraw_Async(
string currency,
decimal amount,
OkexWithdrawalDestination destination,
string toAddress,
string password,
decimal fee,
string chain = null,
CancellationToken ct = default)
{
var parameters = new Dictionary<string, object> {
{ "ccy",currency},
{ "amt",amount.ToString(OkexGlobals.OkexCultureInfo)},
{ "dest", JsonConvert.SerializeObject(destination, new WithdrawalDestinationConverter(false)) },
{ "toAddr",toAddress},
{ "pwd",password},
{ "fee",fee .ToString(OkexGlobals.OkexCultureInfo)},
};
parameters.AddOptionalParameter("chain", chain);
var result = await SendRequestAsync<OkexRestApiResponse<IEnumerable<OkexWithdrawalResponse>>>(GetUrl(Endpoints_V5_Asset_Withdrawal), HttpMethod.Post, ct, parameters, true).ConfigureAwait(false);
if (!result.Success) return WebCallResult<OkexWithdrawalResponse>.CreateErrorResult(result.ResponseStatusCode, result.ResponseHeaders, result.Error);
if (result.Data.ErrorCode > 0) return WebCallResult<OkexWithdrawalResponse>.CreateErrorResult(result.ResponseStatusCode, result.ResponseHeaders, new ServerError(result.Data.ErrorCode, result.Data.ErrorMessage));
return new WebCallResult<OkexWithdrawalResponse>(result.ResponseStatusCode, result.ResponseHeaders, result.Data.Data.FirstOrDefault(), null);
}
/// <summary>
/// Retrieve the withdrawal records according to the currency, withdrawal status, and time range in reverse chronological order. The 100 most recent records are returned by default.
/// </summary>
/// <param name="currency">Currency</param>
/// <param name="transactionId">Transaction ID</param>
/// <param name="state">State</param>
/// <param name="after">Pagination of data to return records earlier than the requested ts, Unix timestamp format in milliseconds, e.g. 1597026383085</param>
/// <param name="before">Pagination of data to return records newer than the requested ts, Unix timestamp format in milliseconds, e.g. 1597026383085</param>
/// <param name="limit">Number of results per request. The maximum is 100; the default is 100.</param>
/// <param name="ct">Cancellation Token</param>
/// <returns></returns>
public virtual WebCallResult<IEnumerable<OkexWithdrawalHistory>> GetWithdrawalHistory(
string currency = null,
string transactionId = null,
OkexWithdrawalState? state = null,
long? after = null,
long? before = null,
int limit = 100,
CancellationToken ct = default) => GetWithdrawalHistory_Async(currency, transactionId, state, after, before, limit, ct).Result;
/// <summary>
/// Retrieve the withdrawal records according to the currency, withdrawal status, and time range in reverse chronological order. The 100 most recent records are returned by default.
/// </summary>
/// <param name="currency">Currency</param>
/// <param name="transactionId">Transaction ID</param>
/// <param name="state">State</param>
/// <param name="after">Pagination of data to return records earlier than the requested ts, Unix timestamp format in milliseconds, e.g. 1597026383085</param>
/// <param name="before">Pagination of data to return records newer than the requested ts, Unix timestamp format in milliseconds, e.g. 1597026383085</param>
/// <param name="limit">Number of results per request. The maximum is 100; the default is 100.</param>
/// <param name="ct">Cancellation Token</param>
/// <returns></returns>
public virtual async Task<WebCallResult<IEnumerable<OkexWithdrawalHistory>>> GetWithdrawalHistory_Async(
string currency = null,
string transactionId = null,
OkexWithdrawalState? state = null,
long? after = null,
long? before = null,
int limit = 100,
CancellationToken ct = default)
{
if (limit < 1 || limit > 100)
throw new ArgumentException("Limit can be between 1-100.");
var parameters = new Dictionary<string, object>();
parameters.AddOptionalParameter("ccy", currency);
parameters.AddOptionalParameter("txId", transactionId);
if (state.HasValue)
parameters.AddOptionalParameter("state", JsonConvert.SerializeObject(state, new WithdrawalStateConverter(false)));
parameters.AddOptionalParameter("after", after?.ToString(OkexGlobals.OkexCultureInfo));
parameters.AddOptionalParameter("before", before?.ToString(OkexGlobals.OkexCultureInfo));
parameters.AddOptionalParameter("limit", limit.ToString(OkexGlobals.OkexCultureInfo));
var result = await SendRequestAsync<OkexRestApiResponse<IEnumerable<OkexWithdrawalHistory>>>(GetUrl(Endpoints_V5_Asset_WithdrawalHistory), HttpMethod.Get, ct, parameters, true).ConfigureAwait(false);
if (!result.Success) return WebCallResult<IEnumerable<OkexWithdrawalHistory>>.CreateErrorResult(result.ResponseStatusCode, result.ResponseHeaders, result.Error);
if (result.Data.ErrorCode > 0) return WebCallResult<IEnumerable<OkexWithdrawalHistory>>.CreateErrorResult(result.ResponseStatusCode, result.ResponseHeaders, new ServerError(result.Data.ErrorCode, result.Data.ErrorMessage));
return new WebCallResult<IEnumerable<OkexWithdrawalHistory>>(result.ResponseStatusCode, result.ResponseHeaders, result.Data.Data, null);
}
/// <summary>
/// PiggyBank Purchase/Redemption
/// </summary>
/// <param name="currency">Currency</param>
/// <param name="amount">Amount</param>
/// <param name="side">Side</param>
/// <param name="ct">Cancellation Token</param>
/// <returns></returns>
public virtual WebCallResult<OkexPiggyBankActionResponse> PiggyBankAction(
string currency,
decimal amount,
OkexPiggyBankActionSide side,
CancellationToken ct = default) => PiggyBankAction_Async(
currency,
amount,
side,
ct).Result;
/// <summary>
/// PiggyBank Purchase/Redemption
/// </summary>
/// <param name="currency">Currency</param>
/// <param name="amount">Amount</param>
/// <param name="side">Side</param>
/// <param name="ct">Cancellation Token</param>
/// <returns></returns>
public virtual async Task<WebCallResult<OkexPiggyBankActionResponse>> PiggyBankAction_Async(
string currency,
decimal amount,
OkexPiggyBankActionSide side,
CancellationToken ct = default)
{
var parameters = new Dictionary<string, object> {
{ "ccy",currency},
{ "amt",amount.ToString(OkexGlobals.OkexCultureInfo)},
{ "side", JsonConvert.SerializeObject(side, new PiggyBankActionSideConverter(false)) },
};
var result = await SendRequestAsync<OkexRestApiResponse<IEnumerable<OkexPiggyBankActionResponse>>>(GetUrl(Endpoints_V5_Asset_PurchaseRedempt), HttpMethod.Post, ct, parameters, true).ConfigureAwait(false);
if (!result.Success) return WebCallResult<OkexPiggyBankActionResponse>.CreateErrorResult(result.ResponseStatusCode, result.ResponseHeaders, result.Error);
if (result.Data.ErrorCode > 0) return WebCallResult<OkexPiggyBankActionResponse>.CreateErrorResult(result.ResponseStatusCode, result.ResponseHeaders, new ServerError(result.Data.ErrorCode, result.Data.ErrorMessage));
return new WebCallResult<OkexPiggyBankActionResponse>(result.ResponseStatusCode, result.ResponseHeaders, result.Data.Data.FirstOrDefault(), null);
}
/// <summary>
/// Get PiggyBank Balance
/// </summary>
/// <param name="currency">Currency</param>
/// <param name="ct">Cancellation Token</param>
/// <returns></returns>
public virtual WebCallResult<IEnumerable<OkexPiggyBankBalance>> PiggyBankBalance(string currency = null, CancellationToken ct = default) => PiggyBankBalance_Async(currency, ct).Result;
/// <summary>
/// Get PiggyBank Balance
/// </summary>
/// <param name="currency">Currency</param>
/// <param name="ct">Cancellation Token</param>
/// <returns></returns>
public virtual async Task<WebCallResult<IEnumerable<OkexPiggyBankBalance>>> PiggyBankBalance_Async(string currency = null, CancellationToken ct = default)
{
var parameters = new Dictionary<string, object>();
parameters.AddOptionalParameter("ccy", currency);
var result = await SendRequestAsync<OkexRestApiResponse<IEnumerable<OkexPiggyBankBalance>>>(GetUrl(Endpoints_V5_Asset_PiggyBalance), HttpMethod.Get, ct, parameters, true).ConfigureAwait(false);
if (!result.Success) return WebCallResult<IEnumerable<OkexPiggyBankBalance>>.CreateErrorResult(result.ResponseStatusCode, result.ResponseHeaders, result.Error);
if (result.Data.ErrorCode > 0) return WebCallResult<IEnumerable<OkexPiggyBankBalance>>.CreateErrorResult(result.ResponseStatusCode, result.ResponseHeaders, new ServerError(result.Data.ErrorCode, result.Data.ErrorMessage));
return new WebCallResult<IEnumerable<OkexPiggyBankBalance>>(result.ResponseStatusCode, result.ResponseHeaders, result.Data.Data, null);
}
/// <summary>
/// only 100 invoices can be generated within a 24 hour period.
/// </summary>
/// <param name="currency">Currency</param>
/// <param name="amount">deposit amount between 0.000001 - 0.1</param>
/// <param name="account">Receiving account</param>
/// <param name="ct">Cancellation Token</param>
/// <returns></returns>
public virtual WebCallResult<IEnumerable<OkexLightningDeposit>> GetLightningDeposits(
string currency,
decimal amount,
OkexLightningDepositAccount? account = null,
CancellationToken ct = default) => GetLightningDeposits_Async(currency, amount, account, ct).Result;
/// <summary>
/// only 100 invoices can be generated within a 24 hour period.
/// </summary>
/// <param name="currency">Currency</param>
/// <param name="amount">deposit amount between 0.000001 - 0.1</param>
/// <param name="account">Receiving account</param>
/// <param name="ct">Cancellation Token</param>
/// <returns></returns>
public virtual async Task<WebCallResult<IEnumerable<OkexLightningDeposit>>> GetLightningDeposits_Async(
string currency,
decimal amount,
OkexLightningDepositAccount? account = null,
CancellationToken ct = default)
{
var parameters = new Dictionary<string, object>
{
{ "ccy", currency },
{ "amt", amount.ToString(OkexGlobals.OkexCultureInfo) },
};
if (account.HasValue)
parameters.AddOptionalParameter("to", JsonConvert.SerializeObject(account, new LightningDepositAccountConverter(false)));
var result = await SendRequestAsync<OkexRestApiResponse<IEnumerable<OkexLightningDeposit>>>(GetUrl(Endpoints_V5_Asset_DepositLightning), HttpMethod.Get, ct, parameters, true).ConfigureAwait(false);
if (!result.Success) return WebCallResult<IEnumerable<OkexLightningDeposit>>.CreateErrorResult(result.ResponseStatusCode, result.ResponseHeaders, result.Error);
if (result.Data.ErrorCode > 0) return WebCallResult<IEnumerable<OkexLightningDeposit>>.CreateErrorResult(result.ResponseStatusCode, result.ResponseHeaders, new ServerError(result.Data.ErrorCode, result.Data.ErrorMessage));
return new WebCallResult<IEnumerable<OkexLightningDeposit>>(result.ResponseStatusCode, result.ResponseHeaders, result.Data.Data, null);
}
/// <summary>
/// Used to make a withdrawal via Lightning. Maximum withdrawal amount is 0.1 BTC, minimum amount is 0.000001 BTC. Rolling 24 hour limit of 1 BTC.
/// </summary>
/// <param name="currency">Currency</param>
/// <param name="invoice">Invoice text</param>
/// <param name="password">fund password</param>
/// <param name="ct">Cancellation Token</param>
/// <returns></returns>
public virtual WebCallResult<OkexLightningWithdrawal> GetLightningWithdrawals(
string currency,
string invoice,
string password,
CancellationToken ct = default) => GetLightningWithdrawals_Async(currency, invoice, password, ct).Result;
/// <summary>
/// Used to make a withdrawal via Lightning. Maximum withdrawal amount is 0.1 BTC, minimum amount is 0.000001 BTC. Rolling 24 hour limit of 1 BTC.
/// </summary>
/// <param name="currency">Currency</param>
/// <param name="invoice">Invoice text</param>
/// <param name="password">fund password</param>
/// <param name="ct">Cancellation Token</param>
/// <returns></returns>
public virtual async Task<WebCallResult<OkexLightningWithdrawal>> GetLightningWithdrawals_Async(
string currency,
string invoice,
string password,
CancellationToken ct = default)
{
var parameters = new Dictionary<string, object>
{
{ "ccy", currency },
{ "invoice", invoice },
{ "pwd", password },
};
var result = await SendRequestAsync<OkexRestApiResponse<IEnumerable<OkexLightningWithdrawal>>>(GetUrl(Endpoints_V5_Asset_WithdrawalLightning), HttpMethod.Get, ct, parameters, true).ConfigureAwait(false);
if (!result.Success) return WebCallResult<OkexLightningWithdrawal>.CreateErrorResult(result.ResponseStatusCode, result.ResponseHeaders, result.Error);
if (result.Data.ErrorCode > 0) return WebCallResult<OkexLightningWithdrawal>.CreateErrorResult(result.ResponseStatusCode, result.ResponseHeaders, new ServerError(result.Data.ErrorCode, result.Data.ErrorMessage));
return new WebCallResult<OkexLightningWithdrawal>(result.ResponseStatusCode, result.ResponseHeaders, result.Data.Data.FirstOrDefault(), null);
}
#endregion
}
}
| 62.471631
| 255
| 0.667906
|
[
"MIT"
] |
EricGarnier/OKEx.Net
|
Okex.Net/OkexClient_Funding.cs
| 35,236
|
C#
|
using System;
using System.Collections.Generic;
using System.Linq;
namespace Xamarin.PropertyEditing.Drawing
{
/// <summary>
/// An abstract description of a gradient brush, composed of gradient stops.
/// </summary>
public abstract class CommonGradientBrush : CommonBrush, IEquatable<CommonGradientBrush>
{
protected CommonGradientBrush (
IEnumerable<CommonGradientStop> stops,
CommonColorInterpolationMode colorInterpolationMode = CommonColorInterpolationMode.SRgbLinearInterpolation,
CommonBrushMappingMode mappingMode = CommonBrushMappingMode.RelativeToBoundingBox,
CommonGradientSpreadMethod spreadMethod = CommonGradientSpreadMethod.Pad,
double opacity = 1.0)
: base(opacity)
{
if (stops == null) {
throw new ArgumentNullException (nameof (stops));
}
GradientStops = stops.ToArray ();
ColorInterpolationMode = colorInterpolationMode;
MappingMode = mappingMode;
SpreadMethod = spreadMethod;
}
/// <summary>
/// The brush's gradient stops.
/// </summary>
public IReadOnlyList<CommonGradientStop> GradientStops { get; }
/// <summary>
/// How the gradient's colors are interpolated.
/// </summary>
public CommonColorInterpolationMode ColorInterpolationMode { get; }
/// <summary>
/// Specifies whether the gradient brush's positioning coordinates are
/// absolute or relative to the output area.
/// </summary>
public CommonBrushMappingMode MappingMode { get; }
/// <summary>
/// Specifies how to draw a gradient that starts or ends inside the
/// bounds of the object to be painted.
/// </summary>
public CommonGradientSpreadMethod SpreadMethod { get; }
public override bool Equals (object obj)
{
var brush = obj as CommonGradientBrush;
if (brush == null) return false;
return Equals (brush);
}
public bool Equals (CommonGradientBrush other)
{
if (other == null) return false;
if (GradientStops.Count != other.GradientStops.Count) return false;
for(var i = 0; i < GradientStops.Count; i++) {
if (GradientStops[i] != other.GradientStops[i]) return false;
}
return base.Equals (other) &&
ColorInterpolationMode == other.ColorInterpolationMode &&
MappingMode == other.MappingMode &&
SpreadMethod == other.SpreadMethod;
}
public override int GetHashCode ()
{
var hashCode = base.GetHashCode ();
unchecked {
foreach(var stop in GradientStops) {
hashCode = hashCode * -1521134295 + stop.GetHashCode();
}
hashCode = hashCode * -1521134295 + ColorInterpolationMode.GetHashCode ();
hashCode = hashCode * -1521134295 + MappingMode.GetHashCode ();
hashCode = hashCode * -1521134295 + SpreadMethod.GetHashCode ();
}
return hashCode;
}
}
}
| 32.47619
| 110
| 0.715543
|
[
"MIT"
] |
Acidburn0zzz/Xamarin.PropertyEditing
|
Xamarin.PropertyEditing/Drawing/CommonGradientBrush.cs
| 2,728
|
C#
|
// <auto-generated />
using DriveSupport.Data;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using System;
namespace DriveSupport.Data.Migrations
{
[DbContext(typeof(ApplicationDbContext))]
[Migration("00000000000000_CreateIdentitySchema")]
partial class CreateIdentitySchema
{
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "3.0.0")
.HasAnnotation("Relational:MaxIdentifierLength", 128)
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRole", b =>
{
b.Property<string>("Id")
.HasColumnType("nvarchar(450)");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken()
.HasColumnType("nvarchar(max)");
b.Property<string>("Name")
.HasColumnType("nvarchar(256)")
.HasMaxLength(256);
b.Property<string>("NormalizedName")
.HasColumnType("nvarchar(256)")
.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()
.HasColumnType("int")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<string>("ClaimType")
.HasColumnType("nvarchar(max)");
b.Property<string>("ClaimValue")
.HasColumnType("nvarchar(max)");
b.Property<string>("RoleId")
.IsRequired()
.HasColumnType("nvarchar(450)");
b.HasKey("Id");
b.HasIndex("RoleId");
b.ToTable("AspNetRoleClaims");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUser", b =>
{
b.Property<string>("Id")
.HasColumnType("nvarchar(450)");
b.Property<int>("AccessFailedCount")
.HasColumnType("int");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken()
.HasColumnType("nvarchar(max)");
b.Property<string>("Email")
.HasColumnType("nvarchar(256)")
.HasMaxLength(256);
b.Property<bool>("EmailConfirmed")
.HasColumnType("bit");
b.Property<bool>("LockoutEnabled")
.HasColumnType("bit");
b.Property<DateTimeOffset?>("LockoutEnd")
.HasColumnType("datetimeoffset");
b.Property<string>("NormalizedEmail")
.HasColumnType("nvarchar(256)")
.HasMaxLength(256);
b.Property<string>("NormalizedUserName")
.HasColumnType("nvarchar(256)")
.HasMaxLength(256);
b.Property<string>("PasswordHash")
.HasColumnType("nvarchar(max)");
b.Property<string>("PhoneNumber")
.HasColumnType("nvarchar(max)");
b.Property<bool>("PhoneNumberConfirmed")
.HasColumnType("bit");
b.Property<string>("SecurityStamp")
.HasColumnType("nvarchar(max)");
b.Property<bool>("TwoFactorEnabled")
.HasColumnType("bit");
b.Property<string>("UserName")
.HasColumnType("nvarchar(256)")
.HasMaxLength(256);
b.HasKey("Id");
b.HasIndex("NormalizedEmail")
.HasName("EmailIndex");
b.HasIndex("NormalizedUserName")
.IsUnique()
.HasName("UserNameIndex")
.HasFilter("[NormalizedUserName] IS NOT NULL");
b.ToTable("AspNetUsers");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<string>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<string>("ClaimType")
.HasColumnType("nvarchar(max)");
b.Property<string>("ClaimValue")
.HasColumnType("nvarchar(max)");
b.Property<string>("UserId")
.IsRequired()
.HasColumnType("nvarchar(450)");
b.HasKey("Id");
b.HasIndex("UserId");
b.ToTable("AspNetUserClaims");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<string>", b =>
{
b.Property<string>("LoginProvider")
.HasColumnType("nvarchar(128)")
.HasMaxLength(128);
b.Property<string>("ProviderKey")
.HasColumnType("nvarchar(128)")
.HasMaxLength(128);
b.Property<string>("ProviderDisplayName")
.HasColumnType("nvarchar(max)");
b.Property<string>("UserId")
.IsRequired()
.HasColumnType("nvarchar(450)");
b.HasKey("LoginProvider", "ProviderKey");
b.HasIndex("UserId");
b.ToTable("AspNetUserLogins");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<string>", b =>
{
b.Property<string>("UserId")
.HasColumnType("nvarchar(450)");
b.Property<string>("RoleId")
.HasColumnType("nvarchar(450)");
b.HasKey("UserId", "RoleId");
b.HasIndex("RoleId");
b.ToTable("AspNetUserRoles");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<string>", b =>
{
b.Property<string>("UserId")
.HasColumnType("nvarchar(450)");
b.Property<string>("LoginProvider")
.HasColumnType("nvarchar(128)")
.HasMaxLength(128);
b.Property<string>("Name")
.HasColumnType("nvarchar(128)")
.HasMaxLength(128);
b.Property<string>("Value")
.HasColumnType("nvarchar(max)");
b.HasKey("UserId", "LoginProvider", "Name");
b.ToTable("AspNetUserTokens");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<string>", b =>
{
b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null)
.WithMany()
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<string>", b =>
{
b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<string>", b =>
{
b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<string>", b =>
{
b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null)
.WithMany()
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<string>", b =>
{
b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
#pragma warning restore 612, 618
}
}
}
| 37.683453
| 125
| 0.471172
|
[
"MIT"
] |
itIsEazy/DriveSupport
|
Data/Migrations/00000000000000_CreateIdentitySchema.Designer.cs
| 10,476
|
C#
|
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Kindle2OneNote")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Kindle2OneNote")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: ComVisible(false)]
| 36.034483
| 84
| 0.742584
|
[
"MIT"
] |
ld0891/Kindle2OneNote
|
Kindle2OneNote/Properties/AssemblyInfo.cs
| 1,048
|
C#
|
/**
* Copyright 2016 IBM Corp. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the “License”);
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an “AS IS” BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace MVC.Models
{
public class ElephantSQLCredentials
{
public string Username { get; set; }
public string Password { get; set; }
public string Database { get; set; }
public string Port { get; set; }
public string Server { get; set; }
}
}
| 33.703704
| 75
| 0.691209
|
[
"Apache-2.0"
] |
hakimnaas/ShowroomerCore
|
src/CoreMVC/Models/ElephantSQLCredentials.cs
| 920
|
C#
|
// <copyright file="StandaloneFileBrowser.cs" company="RedHead">
// Copyright (c) RedHead. All rights reserved.
// </copyright>
using System;
namespace SFB
{
public struct ExtensionFilter
{
public string Name;
public string[] Extensions;
public ExtensionFilter(string filterName, params string[] filterExtensions)
{
Name = filterName;
Extensions = filterExtensions;
}
}
public class StandaloneFileBrowser
{
private static IStandaloneFileBrowser _platformWrapper = null;
static StandaloneFileBrowser()
{
#if UNITY_STANDALONE_OSX
_platformWrapper = new StandaloneFileBrowserMac();
#elif UNITY_STANDALONE_WIN
_platformWrapper = new StandaloneFileBrowserWindows();
#elif UNITY_STANDALONE_LINUX
_platformWrapper = new StandaloneFileBrowserLinux();
#elif UNITY_EDITOR
_platformWrapper = new StandaloneFileBrowserEditor();
#endif
}
/// <summary>
/// Native open file dialog
/// </summary>
/// <param name="title">Dialog title</param>
/// <param name="directory">Root directory</param>
/// <param name="extension">Allowed extension</param>
/// <param name="multiselect">Allow multiple file selection</param>
/// <returns>Returns array of chosen paths. Zero length array when cancelled</returns>
public static string[] OpenFilePanel(string title, string directory, string extension, bool multiselect)
{
var extensions = string.IsNullOrEmpty(extension) ? null : new[] { new ExtensionFilter("", extension) };
return OpenFilePanel(title, directory, extensions, multiselect);
}
/// <summary>
/// Native open file dialog
/// </summary>
/// <param name="title">Dialog title</param>
/// <param name="directory">Root directory</param>
/// <param name="extensions">List of extension filters. Filter Example: new ExtensionFilter("Image Files", "jpg", "png")</param>
/// <param name="multiselect">Allow multiple file selection</param>
/// <returns>Returns array of chosen paths. Zero length array when cancelled</returns>
public static string[] OpenFilePanel(string title, string directory, ExtensionFilter[] extensions, bool multiselect) => _platformWrapper.OpenFilePanel(title, directory, extensions, multiselect);
/// <summary>
/// Native open file dialog async
/// </summary>
/// <param name="title">Dialog title</param>
/// <param name="directory">Root directory</param>
/// <param name="extension">Allowed extension</param>
/// <param name="multiselect">Allow multiple file selection</param>
/// <param name="cb">Callback")</param>
public static void OpenFilePanelAsync(string title, string directory, string extension, bool multiselect, Action<string[]> cb)
{
var extensions = string.IsNullOrEmpty(extension) ? null : new[] { new ExtensionFilter("", extension) };
OpenFilePanelAsync(title, directory, extensions, multiselect, cb);
}
/// <summary>
/// Native open file dialog async
/// </summary>
/// <param name="title">Dialog title</param>
/// <param name="directory">Root directory</param>
/// <param name="extensions">List of extension filters. Filter Example: new ExtensionFilter("Image Files", "jpg", "png")</param>
/// <param name="multiselect">Allow multiple file selection</param>
/// <param name="cb">Callback")</param>
public static void OpenFilePanelAsync(string title, string directory, ExtensionFilter[] extensions, bool multiselect, Action<string[]> cb) => _platformWrapper.OpenFilePanelAsync(title, directory, extensions, multiselect, cb);
/// <summary>
/// Native open folder dialog
/// NOTE: Multiple folder selection doesn't supported on Windows
/// </summary>
/// <param name="title"></param>
/// <param name="directory">Root directory</param>
/// <param name="multiselect"></param>
/// <returns>Returns array of chosen paths. Zero length array when cancelled</returns>
public static string[] OpenFolderPanel(string title, string directory, bool multiselect) => _platformWrapper.OpenFolderPanel(title, directory, multiselect);
/// <summary>
/// Native open folder dialog async
/// NOTE: Multiple folder selection doesn't supported on Windows
/// </summary>
/// <param name="title"></param>
/// <param name="directory">Root directory</param>
/// <param name="multiselect"></param>
/// <param name="cb">Callback")</param>
public static void OpenFolderPanelAsync(string title, string directory, bool multiselect, Action<string[]> cb) => _platformWrapper.OpenFolderPanelAsync(title, directory, multiselect, cb);
/// <summary>
/// Native save file dialog
/// </summary>
/// <param name="title">Dialog title</param>
/// <param name="directory">Root directory</param>
/// <param name="defaultName">Default file name</param>
/// <param name="extension">File extension</param>
/// <returns>Returns chosen path. Empty string when cancelled</returns>
public static string SaveFilePanel(string title, string directory, string defaultName, string extension)
{
var extensions = string.IsNullOrEmpty(extension) ? null : new[] { new ExtensionFilter("", extension) };
return SaveFilePanel(title, directory, defaultName, extensions);
}
/// <summary>
/// Native save file dialog
/// </summary>
/// <param name="title">Dialog title</param>
/// <param name="directory">Root directory</param>
/// <param name="defaultName">Default file name</param>
/// <param name="extensions">List of extension filters. Filter Example: new ExtensionFilter("Image Files", "jpg", "png")</param>
/// <returns>Returns chosen path. Empty string when cancelled</returns>
public static string SaveFilePanel(string title, string directory, string defaultName, ExtensionFilter[] extensions) => _platformWrapper.SaveFilePanel(title, directory, defaultName, extensions);
/// <summary>
/// Native save file dialog async
/// </summary>
/// <param name="title">Dialog title</param>
/// <param name="directory">Root directory</param>
/// <param name="defaultName">Default file name</param>
/// <param name="extension">File extension</param>
/// <param name="cb">Callback")</param>
public static void SaveFilePanelAsync(string title, string directory, string defaultName, string extension, Action<string> cb)
{
var extensions = string.IsNullOrEmpty(extension) ? null : new[] { new ExtensionFilter("", extension) };
SaveFilePanelAsync(title, directory, defaultName, extensions, cb);
}
/// <summary>
/// Native save file dialog async
/// </summary>
/// <param name="title">Dialog title</param>
/// <param name="directory">Root directory</param>
/// <param name="defaultName">Default file name</param>
/// <param name="extensions">List of extension filters. Filter Example: new ExtensionFilter("Image Files", "jpg", "png")</param>
/// <param name="cb">Callback")</param>
public static void SaveFilePanelAsync(string title, string directory, string defaultName, ExtensionFilter[] extensions, Action<string> cb) => _platformWrapper.SaveFilePanelAsync(title, directory, defaultName, extensions, cb);
}
}
| 50.733766
| 233
| 0.644311
|
[
"CC0-1.0"
] |
Chris2918/VibRibbonPlusAlphaPublic
|
Assets/StandaloneFileBrowser/StandaloneFileBrowser.cs
| 7,813
|
C#
|
namespace SampleWpfDataGrid
{
#region #using Directives
using System.Collections.ObjectModel;
#endregion
public partial class TeamView
{
#region Construction
public TeamView()
{
InitializeComponent();
SetupDesignTimeModel();
}
#endregion
#region Setting Up Model for Testing Purposes
private void SetupDesignTimeModel()
{
var playerAges = new ObservableCollection<IPlayerAge>();
var alphaTeam = new PlayerAge(null, "1", true, true, "Alpha Team", 0, 0, string.Empty, 0);
playerAges.Add(alphaTeam);
playerAges.Add(new PlayerAge(alphaTeam, "11", false, true, "John Smith", 32, 3, "Senior", 0.11));
playerAges.Add(new PlayerAge(alphaTeam, "12", false, true, "Jesse Furher", 17, 3, "Junior", 0.11));
playerAges.Add(new PlayerAge(alphaTeam, "13", false, true, "Alfred Morgan", 18, 3, "Junior", 0.11));
playerAges.Add(new PlayerAge(alphaTeam, "14", false, true, "John Mufin", 9, 3, "Mini", 0.11));
playerAges.Add(new PlayerAge(alphaTeam, "15", false, true, "Andrea Pascal", 78, 3, "Veteran", 0.11));
var betaTeam = new PlayerAge(null, "2", true, true, "Beta Team", 0, 0, string.Empty, 0);
playerAges.Add(betaTeam);
playerAges.Add(new PlayerAge(betaTeam, "21", false, true, "Mark Smith", 32, 3, "Senior", 0.11));
playerAges.Add(new PlayerAge(betaTeam, "22", false, true, "Furin Furher", 17, 3, "Junior", 0.11));
playerAges.Add(new PlayerAge(betaTeam, "23", false, true, "Johana Morgan", 18, 3, "Junior", 0.11));
playerAges.Add(new PlayerAge(betaTeam, "24", false, true, "Albert Mufin", 9, 3, "Mini", 0.11));
playerAges.Add(new PlayerAge(betaTeam, "25", false, true, "Snoopy Pascal", 78, 3, "Veteran", 0.11));
DataContext = new TeamModel {PlayerAges = playerAges};
}
#endregion
}
}
| 36.75
| 104
| 0.675737
|
[
"MIT"
] |
smoura/smoura.com-WPFToolkitDatagrid
|
TeamView.xaml.cs
| 1,766
|
C#
|
using System;
using System.ComponentModel;
using EfsTools.Attributes;
using EfsTools.Utils;
using Newtonsoft.Json;
namespace EfsTools.Items.Efs
{
[Serializable]
[EfsFile("/nv/item_files/rfnv/00022235", true, 0xE1FF)]
[Attributes(9)]
public class LteB24TxLimitVsTemp
{
[ElementsCount(8)]
[ElementType("int8")]
[Description("")]
public sbyte[] Value { get; set; }
}
}
| 21.52381
| 60
| 0.612832
|
[
"MIT"
] |
HomerSp/EfsTools
|
EfsTools/Items/Efs/LteB24TxLimitVsTempI.cs
| 452
|
C#
|
// -----------------------------------------------------------------------------
// <copyright file="IrcClient.cs" company="Zack Loveless">
// Copyright (c) Zack Loveless. All rights reserved.
// </copyright>
// -----------------------------------------------------------------------------
namespace Atlantis.Net.Irc
{
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Security;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Collections;
using Collections.Concurrent;
using Linq;
public partial class IrcClient : IDisposable
{
// ReSharper disable FieldCanBeMadeReadOnly.Local
private readonly IQueue<string> messageQueue;
private TcpClient client;
private NetworkStream stream;
private StreamReader reader;
private Task queueRunner;
private CancellationTokenSource tokenSource;
private CancellationToken token;
private bool enableFakeLag;
private List<char> modes;
private bool quitSent;
private Encoding encoding;
// ReSharper restore FieldCanBeMadeReadOnly.Local
public IrcClient()
{
tokenSource = new CancellationTokenSource();
token = tokenSource.Token;
Channels = new HashSet<Channel>();
messageQueue = new ConcurrentQueueAdapter<string>();
Options = ConnectOptions.Default;
QueueInteval = (int)new TimeSpan(0, 0, 0, 0, 500).TotalMilliseconds;
EnableFakeLag = true;
RetryInterval = new TimeSpan(0, 0, 0, 1).TotalMilliseconds;
Timeout = new TimeSpan(0, 0, 10, 0);
modes = new List<char>();
FillListsOnJoin = false;
FillListsDelay = new TimeSpan(0, 0, 30, 0).TotalMilliseconds;
RequestDelay = new TimeSpan(0, 0, 3, 0).TotalMilliseconds;
RawMessageReceivedEvent += RegistrationHandler;
RawMessageReceivedEvent += PingHandler;
RawMessageReceivedEvent += RfcNumericHandler;
RawMessageReceivedEvent += JoinPartHandler;
RawMessageReceivedEvent += MessageNoticeHandler;
RawMessageReceivedEvent += ModeHandler;
RawMessageReceivedEvent += NickHandler;
RawMessageReceivedEvent += QuitHandler;
RfcNumericEvent += ConnectionHandler;
RfcNumericEvent += RfcProtocolHandler;
RfcNumericEvent += RfcNamesHandler;
RfcNumericEvent += NickInUseHandler;
RfcNumericEvent += ListModeHandler;
token.Register(CancellationNoticeHandler);
}
public IrcClient(IrcConfiguration config) : this()
{
Host = config.Host;
Port = config.Port;
Nick = config.Nick;
Ident = config.Ident;
RealName = config.RealName;
Password = config.Password;
}
~IrcClient()
{
RawMessageReceivedEvent = null;
RfcNumericEvent = null;
}
#region Properties
/// <summary>
/// Gets a <see cref="T:System.Boolean" /> value representing whether the <see cref="T:IrcClient" /> has connected to the Host.
/// </summary>
public bool Connected
{
get { return client != null && client.Connected; }
}
public HashSet<Channel> Channels { get; private set; }
public bool EnableFakeLag
{
get { return enableFakeLag; }
set
{
enableFakeLag = value;
if (value)
{
StartQueue();
}
}
}
/// <summary>
/// Gets or sets a value representing what type of encoding to use for encoding messages sent to the Host.
/// </summary>
public IrcEncoding Encoding { get; set; }
public bool FillListsOnJoin { get; set; }
public double FillListsDelay { get; set; }
/// <summary>
/// Gets or sets a <see cref="T:System.String" /> value representing the name of the Host in which the <see cref="T:IrcClient" /> will be connecting.
/// </summary>
public string Host { get; set; }
/// <summary>
/// Gets or sets a <see cref="T:System.String" /> value representing the Ident part for the <see cref="T:IrcClient" />'s user.
/// </summary>
public string Ident { get; set; }
/// <summary>
/// Gets a <see cref="T:System.Boolean" /> value representing whether the <see cref="T:IrcClient" /> has been initialized.
/// </summary>
public bool IsInitialized
{
get
{
var val = true;
if (string.IsNullOrEmpty(Nick)) val = false;
else if (string.IsNullOrEmpty(Host) || Dns.GetHostEntry(Host) == null) val = false;
else if (Port <= 0) val = false;
return val;
}
}
/// <summary>
/// Gets a list of modes that are currently set on the client.
/// </summary>
public ReadOnlyCollection<char> Modes
{
get { return modes.AsReadOnly(); }
}
/// <summary>
/// Gets or sets a <see cref="T:System.String" /> value representing the nickname for the <see cref="T:IrcClient" />
/// </summary>
public string Nick { get; set; }
/// <summary>
/// Gets or sets a bit-mask value representing the options for connecting to the Host.
/// </summary>
public ConnectOptions Options { get; set; }
/// <summary>
/// Gets or sets a <see cref="T:System.String" /> value representing the password to be used for protocol registration.
/// </summary>
public string Password { get; set; }
/// <summary>
/// Gets or sets a <see cref="T:System.Int32" /> value representing the port in which the <see cref="T:IrcClient" /> will be connecting.
/// </summary>
public int Port { get; set; }
/// <summary>
/// Gets or sets a <see cref="T:System.Int32" /> value representing the interval for processing queued messages.
/// </summary>
public int QueueInteval { get; set; }
/// <summary>
/// Gets or sets a <see cref="T:System.String" /> value representing the <see cref="T:IrcClient" />'s real name.
/// </summary>
public string RealName { get; set; }
public double RequestDelay { get; set; }
/// <summary>
/// Gets or sets a <see cref="T:System.Boolean" /> value indicating whether to retry connecting to the IRC server.
/// </summary>
public bool RetryConnect { get; set; }
/// <summary>
/// Gets or sets a <see cref="T:System.Boolean" /> value indicating whether to retry the client's primary nickname.
/// </summary>
public bool RetryNick { get; set; }
/// <summary>
/// Gets or sets a <see cref="T:System.Int32" /> value representing the inteval for retry attempts
/// </summary>
public double RetryInterval { get; set; }
/// <summary>
/// Gets or sets a <see cref="T:System.Boolean" /> value indicating whether to request RPL_NAMEREPLY from the server when someone joins/leaves a channel or changes modes on a channel.
/// </summary>
public bool StrictNames { get; set; }
/// <summary>
/// Gets or sets a value representing the timeout interval for messages being received.
/// </summary>
public TimeSpan Timeout { get; set; }
#endregion
#region Events
/// <summary>
/// Raised when the <see cref="T:IrcClient" /> establishes a connection to the server.
/// It is strongly recommended that you delay any commands processed here if you disable EnableFakeLag.
/// </summary>
public event EventHandler ConnectionEstablishedEvent;
public event EventHandler<JoinPartEventArgs> ChannelJoinEvent;
public event EventHandler<JoinPartEventArgs> ChannelPartEvent;
public event EventHandler<MessageReceivedEventArgs> MessageReceivedEvent;
public event EventHandler<NickChangeEventArgs> NickChangedEvent;
public event EventHandler<MessageReceivedEventArgs> NoticeReceivedEvent;
public event EventHandler PingReceiptEvent;
public event EventHandler<QuitEventArgs> QuitEvent;
public event EventHandler<RawMessageEventArgs> RawMessageReceivedEvent;
public event EventHandler<RfcNumericEventArgs> RfcNumericEvent;
public event EventHandler<MessageReceivedEventArgs> ServerNoticeReceivedEvent;
public event EventHandler<TimeoutEventArgs> TimeoutEvent;
#endregion
#region Methods
private void ChangeNick(string nick)
{
Send("NICK {0}", nick);
}
public void Disconnect(string message = null)
{
if (quitSent)
{
return;
}
// Send QUIT directly to the IRC server, bypassing the queue system.
string quit = String.Format("QUIT{0}", string.IsNullOrEmpty(message) ? "" : " :" + message);
byte[] data = encoding.GetBytes(quit);
quitSent = true;
//Send("QUIT {0}", string.IsNullOrEmpty(message) ? "" : ":" + message);
//Task.Factory.StartNew(async () => await Task.Delay(250)).Wait();
}
public Channel GetChannel(string channelName)
{
if (string.IsNullOrEmpty(channelName))
{
throw new ArgumentNullException("channelName", "The channelName parameter cannot be null or empty.");
}
var c = Channels.SingleOrDefault(x => x.Name.EqualsIgnoreCase(channelName));
if (c == null)
{
c = new Channel(this, channelName);
Channels.Add(c);
}
return c;
}
public void Message(string target, string format, params object[] args)
{
var message = string.Format(format, args);
Send("PRIVMSG {0} :{1}", target, message);
}
public void Notice(string target, string format, params object[] args)
{
var message = string.Format(format, args);
Send("NOTICE {0} :{1}", target, message);
}
private void SetDefaults()
{
if (string.IsNullOrEmpty(Ident)) Ident = Nick.ToLower();
if (string.IsNullOrEmpty(RealName)) RealName = Nick;
}
/// <summary>
/// Starts the <see cref="T:IrcClient" /> process of reading and writing to the Host.
/// </summary>
public void Start()
{
if (!IsInitialized)
{
throw new InvalidOperationException(
string.Format(
"Unable to start the current {0} as it as not been properly initialized. Please refer to the documentation.",
GetType().Name));
}
SetDefaults();
Connect();
}
private async void Connect()
{
try
{
switch (Encoding)
{
default:
encoding = new ASCIIEncoding();
break;
case IrcEncoding.UTF8:
encoding = new UTF8Encoding(false);
break;
}
//client = new TcpClientAsyncAdapter(new TcpClient(), encoding);
client = new TcpClient();
IPHostEntry he = await Dns.GetHostEntryAsync(Host);
if (he.AddressList.Length == 0)
{
throw new SocketException();
}
var connectionEndpoint = new IPEndPoint(he.AddressList[0], Port);
if (Options.HasFlag(ConnectOptions.Secure))
{
// TODO: Actually open a secure connection (using SSL).
client.Connect(connectionEndpoint);
stream = client.GetStream();
reader = new StreamReader(stream, encoding);
}
else
{
client.Connect(connectionEndpoint);
stream = client.GetStream();
reader = new StreamReader(stream, encoding);
}
}
catch (ArgumentNullException)
{
tokenSource.Cancel();
}
catch (SocketException)
{
// poo
}
await
reader.ReadLineAsync().
ContinueWith(OnAsyncRead, this, token, TaskContinuationOptions.LongRunning, TaskScheduler.Current);
StartQueue();
TickTimeout();
}
private void StartQueue()
{
queueRunner = Task.Factory.StartNew(QueueProcessor, token, TaskCreationOptions.LongRunning);
}
private async void Send(string data)
{
var sb = new StringBuilder(data);
sb.AppendLine();
byte[] buf = encoding.GetBytes(sb.ToString());
await stream.WriteAsync(buf, 0, buf.Length, token);
await stream.FlushAsync(token);
}
/// <summary>
/// Enqueues the specified formatted <see cref="T:System.String" /> value to be sent to the Host.
/// </summary>
/// <param name="format"></param>
/// <param name="args"></param>
public void Send(string format, params object[] args)
{
var sb = new StringBuilder();
sb.AppendFormat(format, args);
if (EnableFakeLag)
{
messageQueue.Push(sb.ToString());
}
else Send(sb.ToString());
}
#endregion
#region Implementation of IDisposable
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
/// </summary>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (!disposing) return;
RawMessageReceivedEvent = null;
RfcNumericEvent = null;
if (tokenSource != null && !tokenSource.IsCancellationRequested) tokenSource.Cancel();
}
#endregion
}
}
| 29.52381
| 185
| 0.634716
|
[
"MIT"
] |
Genesis2001/Lantea
|
Code/Atlantis/Atlantis.Net.Irc/IrcClient.cs
| 13,022
|
C#
|
using logviewer.Interfaces;
using logviewer.ViewModel;
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Diagnostics;
using System.Linq;
using System.Windows;
using System.Windows.Markup;
namespace logviewer
{
/// <summary>
/// Interaktionslogik für MainWindow.xaml
/// </summary>
[Export]
public partial class MainWindow : Window
{
[ImportingConstructor]
public MainWindow(MainViewModel viewModel, [ImportMany] IEnumerable<Lazy<IPageView, IPageViewMetadata>> pages)
{
InitializeComponent();
// set the data context as viewmodel
DataContext = viewModel;
// create data templates for the views
foreach (var t in pages.Select(CreateTemplate))
{
TabControl.Resources.Add(t.DataTemplateKey, t);
}
}
protected override void OnStateChanged(EventArgs e)
{
base.OnStateChanged(e);
if (WindowState == WindowState.Maximized)
{
MaximizeBorder.BorderThickness = new Thickness(8);
}
else
{
MaximizeBorder.BorderThickness = new Thickness(0);
}
}
private void MinimizeButton_Click(object sender, RoutedEventArgs e)
{
WindowState = WindowState.Minimized;
}
private void RestoreButton_Click(object sender, RoutedEventArgs e)
{
if (WindowState == WindowState.Normal)
{
WindowState = WindowState.Maximized;
}
else
{
WindowState = WindowState.Normal;
}
}
private void CloseButton_Click(object sender, RoutedEventArgs e)
{
Close();
}
private DataTemplate CreateTemplate(Lazy<IPageView, IPageViewMetadata> arg)
{
const string xamlTemplate = "<DataTemplate DataType=\"{{x:Type vm:{0}}}\"><v:{1} /></DataTemplate>";
var xaml = String.Format(xamlTemplate, arg.Metadata.ViewModel.Name, arg.Metadata.View.Name, arg.Metadata.ViewModel.Namespace, arg.Metadata.View.Namespace);
var context = new ParserContext();
context.XamlTypeMapper = new XamlTypeMapper(new string[0]);
context.XamlTypeMapper.AddMappingProcessingInstruction("vm", arg.Metadata.ViewModel.Namespace, arg.Metadata.ViewModel.Assembly.FullName);
context.XamlTypeMapper.AddMappingProcessingInstruction("v", arg.Metadata.View.Namespace, arg.Metadata.View.Assembly.FullName);
context.XmlnsDictionary.Add("", "http://schemas.microsoft.com/winfx/2006/xaml/presentation");
context.XmlnsDictionary.Add("x", "http://schemas.microsoft.com/winfx/2006/xaml");
context.XmlnsDictionary.Add("vm", "vm");
context.XmlnsDictionary.Add("v", "v");
var template = (DataTemplate)XamlReader.Parse(xaml, context);
return template;
}
private void HyperlinkCommand_Executed(object sender, System.Windows.Input.ExecutedRoutedEventArgs e)
{
if (e.Parameter is string url)
{
Process.Start(url);
}
}
}
}
| 34.081633
| 167
| 0.605988
|
[
"MIT"
] |
sitopmn/logviewer
|
logviewer/MainWindow.xaml.cs
| 3,343
|
C#
|
/*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the secretsmanager-2017-10-17.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using System.Net;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.SecretsManager.Model
{
/// <summary>
/// Container for the parameters to the TagResource operation.
/// Attaches one or more tags, each consisting of a key name and a value, to the specified
/// secret. Tags are part of the secret's overall metadata, and are not associated with
/// any specific version of the secret. This operation only appends tags to the existing
/// list of tags. To remove tags, you must use <a>UntagResource</a>.
///
///
/// <para>
/// The following basic restrictions apply to tags:
/// </para>
/// <ul> <li>
/// <para>
/// Maximum number of tags per secret—50
/// </para>
/// </li> <li>
/// <para>
/// Maximum key length—127 Unicode characters in UTF-8
/// </para>
/// </li> <li>
/// <para>
/// Maximum value length—255 Unicode characters in UTF-8
/// </para>
/// </li> <li>
/// <para>
/// Tag keys and values are case sensitive.
/// </para>
/// </li> <li>
/// <para>
/// Do not use the <code>aws:</code> prefix in your tag names or values because AWS reserves
/// it for AWS use. You can't edit or delete tag names or values with this prefix. Tags
/// with this prefix do not count against your tags per secret limit.
/// </para>
/// </li> <li>
/// <para>
/// If you use your tagging schema across multiple services and resources, remember other
/// services might have restrictions on allowed characters. Generally allowed characters:
/// letters, spaces, and numbers representable in UTF-8, plus the following special characters:
/// + - = . _ : / @.
/// </para>
/// </li> </ul> <important>
/// <para>
/// If you use tags as part of your security strategy, then adding or removing a tag can
/// change permissions. If successfully completing this operation would result in you
/// losing your permissions for this secret, then the operation is blocked and returns
/// an Access Denied error.
/// </para>
/// </important>
/// <para>
/// <b>Minimum permissions</b>
/// </para>
///
/// <para>
/// To run this command, you must have the following permissions:
/// </para>
/// <ul> <li>
/// <para>
/// secretsmanager:TagResource
/// </para>
/// </li> </ul>
/// <para>
/// <b>Related operations</b>
/// </para>
/// <ul> <li>
/// <para>
/// To remove one or more tags from the collection attached to a secret, use <a>UntagResource</a>.
/// </para>
/// </li> <li>
/// <para>
/// To view the list of tags attached to a secret, use <a>DescribeSecret</a>.
/// </para>
/// </li> </ul>
/// </summary>
public partial class TagResourceRequest : AmazonSecretsManagerRequest
{
private string _secretId;
private List<Tag> _tags = new List<Tag>();
/// <summary>
/// Gets and sets the property SecretId.
/// <para>
/// The identifier for the secret that you want to attach tags to. You can specify either
/// the Amazon Resource Name (ARN) or the friendly name of the secret.
/// </para>
/// <note>
/// <para>
/// If you specify an ARN, we generally recommend that you specify a complete ARN. You
/// can specify a partial ARN too—for example, if you don’t include the final hyphen and
/// six random characters that Secrets Manager adds at the end of the ARN when you created
/// the secret. A partial ARN match can work as long as it uniquely matches only one secret.
/// However, if your secret has a name that ends in a hyphen followed by six characters
/// (before Secrets Manager adds the hyphen and six characters to the ARN) and you try
/// to use that as a partial ARN, then those characters cause Secrets Manager to assume
/// that you’re specifying a complete ARN. This confusion can cause unexpected results.
/// To avoid this situation, we recommend that you don’t create secret names ending with
/// a hyphen followed by six characters.
/// </para>
///
/// <para>
/// If you specify an incomplete ARN without the random suffix, and instead provide the
/// 'friendly name', you <i>must</i> not include the random suffix. If you do include
/// the random suffix added by Secrets Manager, you receive either a <i>ResourceNotFoundException</i>
/// or an <i>AccessDeniedException</i> error, depending on your permissions.
/// </para>
/// </note>
/// </summary>
[AWSProperty(Required=true, Min=1, Max=2048)]
public string SecretId
{
get { return this._secretId; }
set { this._secretId = value; }
}
// Check to see if SecretId property is set
internal bool IsSetSecretId()
{
return this._secretId != null;
}
/// <summary>
/// Gets and sets the property Tags.
/// <para>
/// The tags to attach to the secret. Each element in the list consists of a <code>Key</code>
/// and a <code>Value</code>.
/// </para>
///
/// <para>
/// This parameter to the API requires a JSON text string argument. For information on
/// how to format a JSON parameter for the various command line tool environments, see
/// <a href="https://docs.aws.amazon.com/cli/latest/userguide/cli-using-param.html#cli-using-param-json">Using
/// JSON for Parameters</a> in the <i>AWS CLI User Guide</i>. For the AWS CLI, you can
/// also use the syntax: <code>--Tags Key="Key1",Value="Value1",Key="Key2",Value="Value2"[,…]</code>
///
/// </para>
/// </summary>
[AWSProperty(Required=true)]
public List<Tag> Tags
{
get { return this._tags; }
set { this._tags = value; }
}
// Check to see if Tags property is set
internal bool IsSetTags()
{
return this._tags != null && this._tags.Count > 0;
}
}
}
| 39.455556
| 118
| 0.604478
|
[
"Apache-2.0"
] |
PureKrome/aws-sdk-net
|
sdk/src/Services/SecretsManager/Generated/Model/TagResourceRequest.cs
| 7,118
|
C#
|
using Certify.Api.Extensions;
using FluentAssertions;
using System.Threading.Tasks;
using Xunit;
using Xunit.Abstractions;
namespace Certify.Api.Test.ModelTests
{
public class ExpenseTests : CertifyTest
{
public ExpenseTests(ITestOutputHelper iTestOutputHelper) : base(iTestOutputHelper)
{
}
[Fact]
public async Task GetAllAsync_Succeeds()
{
var list = await CertifyClient
.Expenses
.GetAllAsync(
"2019-07-30",
null,
null,
1,
1
)
.ConfigureAwait(false);
list.Should().NotBeNullOrEmpty();
list.Count.Should().BeGreaterThan(0);
}
}
}
| 18.060606
| 84
| 0.701342
|
[
"MIT"
] |
panoramicdata/Certify.Api
|
Certify.Api.Test/ModelTests/ExpenseTests.cs
| 596
|
C#
|
using Microsoft.EntityFrameworkCore.Migrations;
namespace AbpCompanyName.AbpProjectName.Migrations
{
public partial class Upgrade_To_ABP_6_4_rc1 : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateIndex(
name: "IX_AbpUserLogins_ProviderKey_TenantId",
table: "AbpUserLogins",
columns: new[] { "ProviderKey", "TenantId" },
unique: true,
filter: "[TenantId] IS NOT NULL");
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropIndex(
name: "IX_AbpUserLogins_ProviderKey_TenantId",
table: "AbpUserLogins");
}
}
}
| 31.68
| 71
| 0.609848
|
[
"MIT"
] |
EduardoSantanaSeverino/module-zero-core-template
|
aspnet-core/src/AbpCompanyName.AbpProjectName.EntityFrameworkCore/Migrations/20210628103231_Upgrade_To_ABP_6_4_rc1.cs
| 794
|
C#
|
/*
* Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the guardduty-2017-11-28.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
using System.Xml.Serialization;
using Amazon.GuardDuty.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using ThirdParty.Json.LitJson;
namespace Amazon.GuardDuty.Model.Internal.MarshallTransformations
{
/// <summary>
/// DataSourceConfigurations Marshaller
/// </summary>
public class DataSourceConfigurationsMarshaller : IRequestMarshaller<DataSourceConfigurations, JsonMarshallerContext>
{
/// <summary>
/// Unmarshaller the response from the service to the response class.
/// </summary>
/// <param name="requestObject"></param>
/// <param name="context"></param>
/// <returns></returns>
public void Marshall(DataSourceConfigurations requestObject, JsonMarshallerContext context)
{
if(requestObject.IsSetS3Logs())
{
context.Writer.WritePropertyName("s3Logs");
context.Writer.WriteObjectStart();
var marshaller = S3LogsConfigurationMarshaller.Instance;
marshaller.Marshall(requestObject.S3Logs, context);
context.Writer.WriteObjectEnd();
}
}
/// <summary>
/// Singleton Marshaller.
/// </summary>
public readonly static DataSourceConfigurationsMarshaller Instance = new DataSourceConfigurationsMarshaller();
}
}
| 34.029851
| 122
| 0.686842
|
[
"Apache-2.0"
] |
DetlefGolze/aws-sdk-net
|
sdk/src/Services/GuardDuty/Generated/Model/Internal/MarshallTransformations/DataSourceConfigurationsMarshaller.cs
| 2,280
|
C#
|
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("DocListTool")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("DocListTool")]
[assembly: AssemblyCopyright("Copyright © 2020")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("45318d56-91b7-4182-9603-850ff06d9f1d")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 37.567568
| 84
| 0.747482
|
[
"MIT"
] |
darkthread/SharePointDocLibDemo
|
src/DocListTool/Properties/AssemblyInfo.cs
| 1,393
|
C#
|
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Security.Principal;
namespace Loupe.Agent.AspNetCore.Models
{
[SuppressMessage("ReSharper", "CollectionNeverUpdated.Global")]
[SuppressMessage("ReSharper", "ClassNeverInstantiated.Global")]
public class LogRequest
{
public ClientSession? Session { get; set; }
public List<LogMessage>? LogMessages { get; set; }
public IPrincipal? User { get; set; }
}
}
| 28.588235
| 67
| 0.711934
|
[
"MIT"
] |
snakefoot/Loupe.Agent.Core
|
src/AspNetCore2/Models/LogRequest.cs
| 488
|
C#
|
using System;
using System.Collections.Generic;
using System.Net;
namespace Scraper.Services
{
public class SourceResult
{
public HttpStatusCode StatusCode { get; set; }
public string Body { get; set; }
public Exception Error { get; set; }
}
}
| 17.9375
| 54
| 0.644599
|
[
"MIT"
] |
traviswilliams/Scraper
|
Scraper/Scraper.Services/Models/SourceResult.cs
| 289
|
C#
|
// <copyright file="AssemblyInfo.cs" company="Milyli">
// Copyright © 2016 Milyli
// </copyright>
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Milyli.ScriptRunner.Agent")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Milyli.ScriptRunner.Agent")]
[assembly: AssemblyCopyright("Copyright © 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("87d85622-fcc2-4522-bb6b-59e3eeaf7771")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 37
| 84
| 0.74555
|
[
"MIT"
] |
Milyli/RelativityScriptRunner
|
Milyli.ScriptRunner.Agent/Properties/AssemblyInfo.cs
| 1,521
|
C#
|
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
// **NOTE** This file was generated by a tool and any changes will be overwritten.
// Template Source: Templates\CSharp\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 Group Lifecycle Policy.
/// </summary>
[JsonObject(MemberSerialization = MemberSerialization.OptIn)]
public partial class GroupLifecyclePolicy : Entity
{
/// <summary>
/// Gets or sets group lifetime in days.
/// Number of days before a group expires and needs to be renewed. Once renewed, the group expiration is extended by the number of days defined.
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "groupLifetimeInDays", Required = Newtonsoft.Json.Required.Default)]
public Int32? GroupLifetimeInDays { get; set; }
/// <summary>
/// Gets or sets managed group types.
/// The group type for which the expiration policy applies. Possible values are All, Selected or None.
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "managedGroupTypes", Required = Newtonsoft.Json.Required.Default)]
public string ManagedGroupTypes { get; set; }
/// <summary>
/// Gets or sets alternate notification emails.
/// List of email address to send notifications for groups without owners. Multiple email address can be defined by separating email address with a semicolon.
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "alternateNotificationEmails", Required = Newtonsoft.Json.Required.Default)]
public string AlternateNotificationEmails { get; set; }
}
}
| 46.333333
| 166
| 0.643885
|
[
"MIT"
] |
AzureMentor/msgraph-sdk-dotnet
|
src/Microsoft.Graph/Models/Generated/GroupLifecyclePolicy.cs
| 2,224
|
C#
|
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// <auto-generated/>
#nullable disable
namespace Azure.Batch.Models
{
/// <summary> The state of the Job Schedule. </summary>
public enum JobScheduleState
{
/// <summary> The Job Schedule is active and will create Jobs as per its schedule. </summary>
Active,
/// <summary> The Job Schedule has terminated, either by reaching its end time or by the user terminating it explicitly. </summary>
Completed,
/// <summary> The user has disabled the Job Schedule. The scheduler will not initiate any new Jobs will on this schedule, but any existing active Job will continue to run. </summary>
Disabled,
/// <summary> The Job Schedule has no more work to do, or has been explicitly terminated by the user, but the termination operation is still in progress. The scheduler will not initiate any new Jobs for this Job Schedule, nor is any existing Job active. </summary>
Terminating,
/// <summary> The user has requested that the Job Schedule be deleted, but the delete operation is still in progress. The scheduler will not initiate any new Jobs for this Job Schedule, and will delete any existing Jobs and Tasks under the Job Schedule, including any active Job. The Job Schedule will be deleted when all Jobs and Tasks under the Job Schedule have been deleted. </summary>
Deleting
}
}
| 58.84
| 397
| 0.719239
|
[
"MIT"
] |
Petermarcu/azure-sdk-for-net
|
sdk/batch/Microsoft.Azure.Batch/Azure.Batch/src/Generated/Models/JobScheduleState.cs
| 1,471
|
C#
|
// <copyright file="WrapPanel.cs" company="Dark Bond, Inc.">
// Copyright © 2016-2018 - Dark Bond, Inc. All Rights Reserved.
// </copyright>
// <author>Donald Roy Airey</author>
namespace DarkBond.Views.Controls
{
using System;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using Windows.Foundation;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
/// <summary>
/// Positions child elements sequentially from left to right or top to bottom. When elements extend beyond the panel edge, elements are
/// positioned in the next row or column.
/// </summary>
public class WrapPanel : Panel
{
/// <summary>
/// Identifies the <see cref="P:WinRTXamlToolkit.Controls.WrapPanel.ItemHeight" /> DependencyProperty.
/// </summary>
[SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "The field is immutable")]
public static readonly DependencyProperty ItemHeightProperty = DependencyProperty.Register(
"ItemHeight",
typeof(double),
typeof(WrapPanel),
new PropertyMetadata(double.NaN, OnItemHeightOrWidthPropertyChanged));
/// <summary>
/// Identifies the <see cref="P:WinRTXamlToolkit.Controls.WrapPanel.ItemWidth" /> DependencyProperty.
/// </summary>
[SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "The field is immutable")]
public static readonly DependencyProperty ItemWidthProperty = DependencyProperty.Register(
"ItemWidth",
typeof(double),
typeof(WrapPanel),
new PropertyMetadata(double.NaN, OnItemHeightOrWidthPropertyChanged));
/// <summary>
/// Identifies the <see cref="P:WinRTXamlToolkit.Controls.WrapPanel.Orientation" /> DependencyProperty.
/// </summary>
[SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "The field is immutable")]
public static readonly DependencyProperty OrientationProperty = DependencyProperty.Register(
"Orientation",
typeof(Orientation),
typeof(WrapPanel),
new PropertyMetadata(Orientation.Horizontal, OnOrientationPropertyChanged));
/// <summary>
/// A value indicating whether a DependencyProperty change handler should ignore the next change notification. This is used to reset the
/// value of properties without performing any of the actions in their change handlers.
/// </summary>
private bool ignorePropertyChange;
/// <summary>
/// Gets or sets the height of the layout area for each item that is contained in a <see cref="WrapPanel" /> .
/// </summary>
/// <value>
/// The height applied to the layout area of each item that is contained within a <see cref="WrapPanel" /> . The
/// default value is <see cref="double.NaN" /> .
/// </value>
public double ItemHeight
{
get
{
return (double)this.GetValue(WrapPanel.ItemHeightProperty);
}
set
{
this.SetValue(WrapPanel.ItemHeightProperty, value);
}
}
/// <summary>
/// Gets or sets the width of the layout area for each item that is contained in a <see cref="WrapPanel" /> .
/// </summary>
/// <value>
/// The width that applies to the layout area of each item that is contained in a <see cref="WrapPanel" /> . The
/// default value is <see cref="F:System.Double.NaN" /> .
/// </value>
public double ItemWidth
{
get
{
return (double)this.GetValue(WrapPanel.ItemWidthProperty);
}
set
{
this.SetValue(WrapPanel.ItemWidthProperty, value);
}
}
/// <summary>
/// Gets or sets the direction in which child elements are arranged.
/// </summary>
public Orientation Orientation
{
get
{
return (Orientation)this.GetValue(WrapPanel.OrientationProperty);
}
set
{
this.SetValue(WrapPanel.OrientationProperty, value);
}
}
/// <summary>
/// Arranges and sizes the <see cref="WrapPanel" /> control and its child elements.
/// </summary>
/// <param name="finalSize">
/// The area within the parent that the <see cref="WrapPanel" /> should use arrange itself and its children.
/// </param>
/// <returns>The actual size used by the <see cref="WrapPanel" /> .</returns>
protected override Size ArrangeOverride(Size finalSize)
{
// Variables tracking the size of the current line, and the maximum size available to fill. Note that the line might represent a row or
// a column depending on the orientation.
Orientation orientation = this.Orientation;
OrientedSize lineSize = new OrientedSize(orientation);
OrientedSize maximumSize = new OrientedSize(orientation, finalSize.Width, finalSize.Height);
// Determine the constraints for individual items
double itemWidth = this.ItemWidth;
double itemHeight = this.ItemHeight;
bool hasFixedWidth = !double.IsNaN(itemWidth);
bool hasFixedHeight = !double.IsNaN(itemHeight);
double indirectOffset = 0;
double? directDelta = (orientation == Orientation.Horizontal) ?
(hasFixedWidth ? (double?)itemWidth : null) :
(hasFixedHeight ? (double?)itemHeight : null);
// Measure each of the Children. We will process the elements one line at a time, just like during measure, but we will wait until we've
// completed an entire line of elements before arranging them. The lineStart and lineEnd variables track the size of the currently
// arranged line.
UIElementCollection children = this.Children;
int count = children.Count;
int lineStart = 0;
for (int lineEnd = 0; lineEnd < count; lineEnd++)
{
UIElement element = children[lineEnd];
// Get the size of the element
OrientedSize elementSize = new OrientedSize(
orientation,
hasFixedWidth ? itemWidth : element.DesiredSize.Width,
hasFixedHeight ? itemHeight : element.DesiredSize.Height);
// If this element falls of the edge of the line
if (lineSize.Direct + elementSize.Direct > maximumSize.Direct)
{
// Then we just completed a line and we should arrange it
this.ArrangeLine(lineStart, lineEnd, directDelta, indirectOffset, lineSize.Indirect);
// Move the current element to a new line
indirectOffset += lineSize.Indirect;
lineSize = elementSize;
// If the current element is larger than the maximum size
if (elementSize.Direct > maximumSize.Direct)
{
// Arrange the element as a single line
this.ArrangeLine(lineEnd, ++lineEnd, directDelta, indirectOffset, elementSize.Indirect);
// Move to a new line
indirectOffset += lineSize.Indirect;
lineSize = new OrientedSize(orientation);
}
// Advance the start index to a new line after arranging
lineStart = lineEnd;
}
else
{
// Otherwise just add the element to the end of the line
lineSize.Direct += elementSize.Direct;
lineSize.Indirect = Math.Max(lineSize.Indirect, elementSize.Indirect);
}
}
// Arrange any elements on the last line
if (lineStart < count)
{
this.ArrangeLine(lineStart, count, directDelta, indirectOffset, lineSize.Indirect);
}
return finalSize;
}
/// <summary>
/// Measures the child elements of a <see cref="WrapPanel" /> in anticipation of arranging them during the ArrangeOverride pass.
/// </summary>
/// <param name="availableSize">The size available to child elements of the wrap panel.</param>
/// <returns>The size required by the <see cref="WrapPanel" /> and its elements.</returns>
protected override Size MeasureOverride(Size availableSize)
{
// Variables tracking the size of the current line, the total size measured so far, and the maximum size available to fill. Note that
// the line might represent a row or a column depending on the orientation.
Orientation orientation = this.Orientation;
OrientedSize lineSize = new OrientedSize(orientation);
OrientedSize totalSize = new OrientedSize(orientation);
OrientedSize maximumSize = new OrientedSize(orientation, availableSize.Width, availableSize.Height);
// Determine the constraints for individual items
double itemWidth = this.ItemWidth;
double itemHeight = this.ItemHeight;
bool hasFixedWidth = !double.IsNaN(itemWidth);
bool hasFixedHeight = !double.IsNaN(itemHeight);
Size itemSize = new Size(hasFixedWidth ? itemWidth : availableSize.Width, hasFixedHeight ? itemHeight : availableSize.Height);
// Measure each of the Children
foreach (UIElement element in this.Children)
{
// Determine the size of the element
element.Measure(itemSize);
OrientedSize elementSize = new OrientedSize(
orientation,
hasFixedWidth ? itemWidth : element.DesiredSize.Width,
hasFixedHeight ? itemHeight : element.DesiredSize.Height);
// If this element falls of the edge of the line
if (lineSize.Direct + elementSize.Direct > maximumSize.Direct)
{
// Update the total size with the direct and indirect growth
// for the current line
totalSize.Direct = Math.Max(lineSize.Direct, totalSize.Direct);
totalSize.Indirect += lineSize.Indirect;
// Move the element to a new line
lineSize = elementSize;
// If the current element is larger than the maximum size, place it on a line by itself
if (elementSize.Direct > maximumSize.Direct)
{
// Update the total size for the line occupied by this single element
totalSize.Direct = Math.Max(elementSize.Direct, totalSize.Direct);
totalSize.Indirect += elementSize.Indirect;
// Move to a new line
lineSize = new OrientedSize(orientation);
}
}
else
{
// Otherwise just add the element to the end of the line
lineSize.Direct += elementSize.Direct;
lineSize.Indirect = Math.Max(lineSize.Indirect, elementSize.Indirect);
}
}
// Update the total size with the elements on the last line
totalSize.Direct = Math.Max(lineSize.Direct, totalSize.Direct);
totalSize.Indirect += lineSize.Indirect;
// Return the total size required as an un-oriented quantity
return new Size(totalSize.Width, totalSize.Height);
}
/// <summary>
/// Property changed handler for ItemHeight and ItemWidth.
/// </summary>
/// <param name="dependencyObject">WrapPanel that changed its ItemHeight or ItemWidth.</param>
/// <param name="dependencyPropertyChangedEventArgs">Event arguments.</param>
private static void OnItemHeightOrWidthPropertyChanged(
DependencyObject dependencyObject,
DependencyPropertyChangedEventArgs dependencyPropertyChangedEventArgs)
{
WrapPanel source = (WrapPanel)dependencyObject;
double value = (double)dependencyPropertyChangedEventArgs.NewValue;
// Ignore the change if requested
if (source.ignorePropertyChange)
{
source.ignorePropertyChange = false;
return;
}
// Validate the length (which must either be NaN or a positive, or a finite number).
if (!double.IsNaN(value) && ((value <= 0.0) || double.IsPositiveInfinity(value)))
{
// Reset the property to its original state before throwing
source.ignorePropertyChange = true;
source.SetValue(dependencyPropertyChangedEventArgs.Property, (double)dependencyPropertyChangedEventArgs.OldValue);
string message = string.Format(CultureInfo.InvariantCulture, "Invalid width or height value {0}", value);
throw new InvalidOperationException(message);
}
// The length properties affect measuring.
source.InvalidateMeasure();
}
/// <summary>
/// OrientationProperty property changed handler.
/// </summary>
/// <param name="dependencyObject">WrapPanel that changed its Orientation.</param>
/// <param name="dependencyPropertyChangedEventArgs">Event arguments.</param>
private static void OnOrientationPropertyChanged(
DependencyObject dependencyObject,
DependencyPropertyChangedEventArgs dependencyPropertyChangedEventArgs)
{
WrapPanel source = (WrapPanel)dependencyObject;
Orientation value = (Orientation)dependencyPropertyChangedEventArgs.NewValue;
// Ignore the change if requested
if (source.ignorePropertyChange)
{
source.ignorePropertyChange = false;
return;
}
// Validate the Orientation
if (value != Orientation.Horizontal && value != Orientation.Vertical)
{
// Reset the property to its original state before throwing
source.ignorePropertyChange = true;
source.SetValue(WrapPanel.OrientationProperty, (Orientation)dependencyPropertyChangedEventArgs.OldValue);
throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, "Invalid Orientation={0}", value));
}
// Orientation affects measuring.
source.InvalidateMeasure();
}
/// <summary>
/// Arrange a sequence of elements in a single line.
/// </summary>
/// <param name="lineStart">Index of the first element in the sequence to arrange.</param>
/// <param name="lineEnd">Index of the last element in the sequence to arrange.</param>
/// <param name="directDelta">Optional fixed growth in the primary direction.</param>
/// <param name="indirectOffset">Offset of the line in the indirect direction.</param>
/// <param name="indirectGrowth">Shared indirect growth of the elements on this line.</param>
private void ArrangeLine(int lineStart, int lineEnd, double? directDelta, double indirectOffset, double indirectGrowth)
{
double directOffset = 0.0;
Orientation o = this.Orientation;
bool isHorizontal = o == Orientation.Horizontal;
UIElementCollection children = this.Children;
for (int index = lineStart; index < lineEnd; index++)
{
// Get the size of the element
UIElement element = children[index];
OrientedSize elementSize = new OrientedSize(o, element.DesiredSize.Width, element.DesiredSize.Height);
// Determine if we should use the element's desired size or the
// fixed item width or height
double directGrowth = directDelta != null ?
directDelta.Value :
elementSize.Direct;
// Arrange the element
Rect bounds = isHorizontal ?
new Rect(directOffset, indirectOffset, directGrowth, indirectGrowth) :
new Rect(indirectOffset, directOffset, indirectGrowth, directGrowth);
element.Arrange(bounds);
directOffset += directGrowth;
}
}
}
}
| 46.730245
| 149
| 0.59691
|
[
"MIT"
] |
DonaldAirey/dark-bond-main
|
DarkBond.Views.UWP/Controls/WrapPanel.cs
| 17,153
|
C#
|
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityTK;
namespace OsFPS
{
/// <summary>
/// Specialized weapon handler for <see cref="FirstPersonEntity"/> entities.
/// </summary>
[RequireComponent(typeof(FirstPersonEntity))]
public class FirstPersonWeaponHandler : EntityWeaponHandler
{
/// <summary>
/// The transform parent where newly created weapons will be parented to.
/// </summary>
[Header("Config")]
public Transform weaponParent;
/// <summary>
/// The flag determining whether or not the weapon is currently zoomed.
/// </summary>
[Header("Debug")]
public bool isZoomed;
/// <summary>
/// Cached reference getter to the <see cref="FirstPersonEntity"/> of this handler.
/// </summary>
public FirstPersonEntity playerEntity
{
get
{
return this._playerEntity.Get(this);
}
}
private LazyLoadedComponentRef<FirstPersonEntity> _playerEntity = new LazyLoadedComponentRef<FirstPersonEntity>();
public override void OnRegisterEventHandlers()
{
base.OnRegisterEventHandlers();
// Zooming
this.playerEntity.fpModel.zoom.RegisterStartCondition(this.CanZoom);
this.playerEntity.fpModel.zoom.RegisterActivityGetter(this.IsZoomed);
this.playerEntity.fpModel.zoom.onStart += this.OnZoomStart;
this.playerEntity.fpModel.zoom.onStop += this.OnZoomEnd;
// Footsteps
this.playerEntity.fpModel.footstep.handler += this.OnFootstep;
this.entity.model.externalForce.handler += this.OnExternalForce;
}
public void Update()
{
if (this.currentWeapon == null)
{
if (this.IsZoomed())
this.playerEntity.fpModel.zoom.ForceStop();
}
}
/// <summary>
/// Forwards footsteps to <see cref="FirstPersonWeapon.OnFootstep"/>, bound to <see cref="EntityModel.footstep"/>.
/// </summary>
private void OnFootstep(Foot foot)
{
if (this.currentWeapon != null)
{
(this.currentWeapon as FirstPersonWeapon).OnFootstep(foot);
}
}
protected override bool _CreateWeapon(WeaponDefinition definition, out Weapon weaponInstance)
{
// Instantiate
var weaponGo = Instantiate(definition.firstPersonWeapon.gameObject, this.weaponParent);
weaponInstance = weaponGo.GetComponent<FirstPersonWeapon>();
// Setup transform
weaponGo.transform.parent = this.weaponParent;
weaponGo.transform.localPosition = Vector3.zero;
weaponGo.transform.localRotation = Quaternion.identity;
// Register
weaponGo.SetActive(false);
return true;
}
private void OnExternalForce(Vector3 force)
{
if (object.ReferenceEquals(this.currentWeapon, null))
return;
(this.currentWeapon as FirstPersonWeapon).anim.ApplyForce(force);
}
#region Zooming
public bool CanZoom()
{
return this.currentWeapon != null && !this.isZoomed;
}
public bool IsZoomed()
{
return this.isZoomed;
}
private void OnZoomStart()
{
this.isZoomed = true;
}
private void OnZoomEnd()
{
this.isZoomed = false;
}
#endregion
}
}
| 29.903226
| 122
| 0.582794
|
[
"MIT"
] |
kennux/OsFPS
|
Assets/OsFPS/Code/Entity/FirstPerson/FirstPersonWeaponHandler.cs
| 3,710
|
C#
|
//------------------------------------------------------------------------------
// <copyright file="QilDataSource.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// <owner current="true" primary="true">[....]</owner>
//------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Xml.Schema;
using System.Diagnostics;
namespace System.Xml.Xsl.Qil {
/// <summary>
/// View over a Qil DataSource operator.
/// </summary>
/// <remarks>
/// Don't construct QIL nodes directly; instead, use the <see cref="QilFactory">QilFactory</see>.
/// </remarks>
internal class QilDataSource : QilBinary {
//-----------------------------------------------
// Constructor
//-----------------------------------------------
/// <summary>
/// Construct a new node
/// </summary>
public QilDataSource(QilNodeType nodeType, QilNode name, QilNode baseUri) : base(nodeType, name, baseUri) {
}
//-----------------------------------------------
// QilDataSource methods
//-----------------------------------------------
public QilNode Name {
get { return Left; }
set { Left = value; }
}
public QilNode BaseUri {
get { return Right; }
set { Right = value; }
}
}
}
| 30.895833
| 115
| 0.431558
|
[
"Apache-2.0"
] |
295007712/295007712.github.io
|
sourceCode/dotNet4.6/ndp/fx/src/XmlUtils/System/Xml/Xsl/QIL/QilDataSource.cs
| 1,483
|
C#
|
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.AspNetCore.WebUtilities;
using Microsoft.Extensions.Logging;
using Piipan.Dashboard.Api;
using Piipan.Shared.Claims;
#nullable enable
namespace Piipan.Dashboard.Pages
{
public class ParticipantUploadsModel : BasePageModel
{
private readonly IParticipantUploadRequest _participantUploadRequest;
private readonly ILogger<ParticipantUploadsModel> _logger;
public ParticipantUploadsModel(IParticipantUploadRequest participantUploadRequest,
ILogger<ParticipantUploadsModel> logger,
IClaimsProvider claimsProvider)
: base(claimsProvider)
{
_participantUploadRequest = participantUploadRequest;
_logger = logger;
}
public string Title = "Most recent upload from each state";
public List<ParticipantUpload> ParticipantUploadResults { get; private set; } = new List<ParticipantUpload>();
public string? NextPageParams { get; private set; }
public string? PrevPageParams { get; private set; }
public string? StateQuery { get; private set; }
public static int PerPageDefault = 10;
public static string ApiUrlKey = "MetricsApiUri";
public string? MetricsApiBaseUrl = Environment.GetEnvironmentVariable(ApiUrlKey);
public string MetricsApiSearchPath = "/getparticipantuploads";
public string MetricsApiLastUploadPath = "/getlastupload";
private HttpClient httpClient = new HttpClient();
public async Task OnGetAsync()
{
try
{
_logger.LogInformation("Loading initial results");
if (MetricsApiBaseUrl == null)
{
throw new Exception("MetricsApiBaseUrl is null.");
}
var url = MetricsApiBaseUrl + MetricsApiLastUploadPath;
var response = await _participantUploadRequest.Get(url);
ParticipantUploadResults = response.data;
SetPageLinks(response.meta);
}
catch (Exception exception)
{
_logger.LogError(exception, exception.Message);
}
}
public async Task<IActionResult> OnPostAsync()
{
try
{
_logger.LogInformation("Querying uploads via search form");
if (MetricsApiBaseUrl == null)
{
throw new Exception("MetricsApiBaseUrl is null.");
}
StateQuery = Request.Form["state"];
var url = QueryHelpers.AddQueryString(MetricsApiBaseUrl + MetricsApiSearchPath, "state", StateQuery);
url = QueryHelpers.AddQueryString(url, "perPage", PerPageDefault.ToString());
var response = await _participantUploadRequest.Get(url);
ParticipantUploadResults = response.data;
SetPageLinks(response.meta);
}
catch (Exception exception)
{
_logger.LogError(exception, exception.Message);
}
return Page();
}
// adds default pagination to the api url if none is present from request params
private string FormatUrl()
{
if (MetricsApiBaseUrl == null)
{
throw new Exception("MetricsApiBaseUrl is null.");
}
var url = MetricsApiBaseUrl + Request.QueryString;
StateQuery = Request.Query["state"];
if (String.IsNullOrEmpty(Request.Query["perPage"]))
url = QueryHelpers.AddQueryString(url, "perPage", PerPageDefault.ToString());
return url;
}
private void SetPageLinks(ParticipantUploadResponseMeta meta)
{
NextPageParams = meta.nextPage;
PrevPageParams = meta.prevPage;
}
}
}
| 38.824074
| 119
| 0.598855
|
[
"CC0-1.0"
] |
18F/piipan
|
dashboard/src/Piipan.Dashboard/Pages/ParticipantUploads.cshtml.cs
| 4,193
|
C#
|
using System;
using System.CodeDom.Compiler;
using System.ComponentModel;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Xml.Schema;
using System.Xml.Serialization;
namespace Workday.HumanResources
{
[GeneratedCode("System.Xml", "4.6.1590.0"), DesignerCategory("code"), DebuggerStepThrough, XmlType(Namespace = "urn:com.workday/bsvc")]
[Serializable]
public class Disability_GradeObjectIDType : INotifyPropertyChanged
{
private string typeField;
private string valueField;
[method: CompilerGenerated]
[CompilerGenerated]
public event PropertyChangedEventHandler PropertyChanged;
[XmlAttribute(Form = XmlSchemaForm.Qualified)]
public string type
{
get
{
return this.typeField;
}
set
{
this.typeField = value;
this.RaisePropertyChanged("type");
}
}
[XmlText]
public string Value
{
get
{
return this.valueField;
}
set
{
this.valueField = value;
this.RaisePropertyChanged("Value");
}
}
protected void RaisePropertyChanged(string propertyName)
{
PropertyChangedEventHandler propertyChanged = this.PropertyChanged;
if (propertyChanged != null)
{
propertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
}
| 20.737705
| 136
| 0.728063
|
[
"MIT"
] |
matteofabbri/Workday.WebServices
|
Workday.HumanResources/Disability_GradeObjectIDType.cs
| 1,265
|
C#
|
//
// PureMVC C# Multicore
//
// Copyright(c) 2020 Saad Shams <saad.shams@puremvc.org>
// Your reuse is governed by the Creative Commons Attribution 3.0 License
//
using PureMVC.Interfaces;
namespace PureMVC.Patterns.Command
{
/// <summary>
/// A SimpleCommand subclass used by MacroCommandTestCommand.
/// </summary>
/// <seealso cref="MacroCommandTest"/>
/// <seealso cref="MacroCommandTestCommand"/>
/// <seealso cref="MacroCommandTestVO"/>
public class MacroCommandTestSub1Command: SimpleCommand, ICommand
{
/// <summary>
/// Fabricate a result by multiplying the input by 2
/// </summary>
/// <param name="notification">notification the <c>INotification</c> carrying the <c>MacroCommandTestVO</c></param>
public override void Execute(INotification notification)
{
var vo = (MacroCommandTestVO)notification.Body;
// Fabricate a result
vo.Result1 = 2 * vo.Input;
}
}
}
| 30.515152
| 123
| 0.643496
|
[
"BSD-3-Clause"
] |
PureMVC/puremvc-csharp-multicore-framework
|
PureMVCTests/Patterns/Command/MacroCommandTestSub1Command.cs
| 1,009
|
C#
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Runtime.Serialization;
using System.Web.Script.Serialization;
using System.Xml.Serialization;
using XCode;
using XCode.Configuration;
using XCode.DataAccessLayer;
namespace COMCMS.Core
{
/// <summary>数据字典</summary>
[Serializable]
[DataObject]
[Description("数据字典")]
[BindTable("DataDictionary", Description = "数据字典", ConnName = "dbconn", DbType = DatabaseType.SqlServer)]
public partial class DataDictionary
{
#region 属性
private Int32 _Id;
/// <summary>编号</summary>
[DisplayName("编号")]
[Description("编号")]
[DataObjectField(true, true, false, 0)]
[BindColumn("Id", "编号", "")]
public Int32 Id { get => _Id; set { if (OnPropertyChanging("Id", value)) { _Id = value; OnPropertyChanged("Id"); } } }
private String _Key;
/// <summary>字典key</summary>
[DisplayName("字典key")]
[Description("字典key")]
[DataObjectField(false, false, true, 50)]
[BindColumn("Key", "字典key", "")]
public String Key { get => _Key; set { if (OnPropertyChanging("Key", value)) { _Key = value; OnPropertyChanged("Key"); } } }
private String _Description;
/// <summary>字典介绍</summary>
[DisplayName("字典介绍")]
[Description("字典介绍")]
[DataObjectField(false, false, true, 50)]
[BindColumn("Description", "字典介绍", "")]
public String Description { get => _Description; set { if (OnPropertyChanging("Description", value)) { _Description = value; OnPropertyChanged("Description"); } } }
private Int32 _Rank;
/// <summary>排序</summary>
[DisplayName("排序")]
[Description("排序")]
[DataObjectField(false, false, false, 0)]
[BindColumn("Rank", "排序", "")]
public Int32 Rank { get => _Rank; set { if (OnPropertyChanging("Rank", value)) { _Rank = value; OnPropertyChanged("Rank"); } } }
private DateTime _AddTime;
/// <summary>添加时间</summary>
[DisplayName("添加时间")]
[Description("添加时间")]
[DataObjectField(false, false, true, 0)]
[BindColumn("AddTime", "添加时间", "")]
public DateTime AddTime { get => _AddTime; set { if (OnPropertyChanging("AddTime", value)) { _AddTime = value; OnPropertyChanged("AddTime"); } } }
#endregion
#region 获取/设置 字段值
/// <summary>获取/设置 字段值</summary>
/// <param name="name">字段名</param>
/// <returns></returns>
public override Object this[String name]
{
get
{
switch (name)
{
case "Id": return _Id;
case "Key": return _Key;
case "Description": return _Description;
case "Rank": return _Rank;
case "AddTime": return _AddTime;
default: return base[name];
}
}
set
{
switch (name)
{
case "Id": _Id = value.ToInt(); break;
case "Key": _Key = Convert.ToString(value); break;
case "Description": _Description = Convert.ToString(value); break;
case "Rank": _Rank = value.ToInt(); break;
case "AddTime": _AddTime = value.ToDateTime(); break;
default: base[name] = value; break;
}
}
}
#endregion
#region 字段名
/// <summary>取得数据字典字段信息的快捷方式</summary>
public partial class _
{
/// <summary>编号</summary>
public static readonly Field Id = FindByName("Id");
/// <summary>字典key</summary>
public static readonly Field Key = FindByName("Key");
/// <summary>字典介绍</summary>
public static readonly Field Description = FindByName("Description");
/// <summary>排序</summary>
public static readonly Field Rank = FindByName("Rank");
/// <summary>添加时间</summary>
public static readonly Field AddTime = FindByName("AddTime");
static Field FindByName(String name) => Meta.Table.FindByName(name);
}
/// <summary>取得数据字典字段名称的快捷方式</summary>
public partial class __
{
/// <summary>编号</summary>
public const String Id = "Id";
/// <summary>字典key</summary>
public const String Key = "Key";
/// <summary>字典介绍</summary>
public const String Description = "Description";
/// <summary>排序</summary>
public const String Rank = "Rank";
/// <summary>添加时间</summary>
public const String AddTime = "AddTime";
}
#endregion
}
}
| 35.540146
| 172
| 0.542822
|
[
"MIT"
] |
NewLifeX/comcms
|
XCoder/Entity/数据字典.cs
| 5,165
|
C#
|
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="IWithRoomSyntax.cs" company="bbv Software Services AG">
// Copyright (c) 2014 - 2020
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace CleanCode.Testing.Sample.Builder
{
using CleanCode.Testing.Sample.SameImplementation;
public interface IWithRoomSyntax : IWithFloorSyntax
{
IWithWindowSyntax AddRoom();
IWithWindowSyntax WithRoom(Room room);
IBuildHouseSyntax WithRoomHavingWindowsQuantityOf(int numberOfWindowsInRoom);
}
}
| 41.516129
| 119
| 0.589744
|
[
"Apache-2.0"
] |
bbvch-academy/CleanCode.Academy
|
source/Testing.Sample/5 Builder with Syntax Sample/Builder/IWithRoomSyntax.cs
| 1,287
|
C#
|
using OpenTK;
using OpenTK.Graphics;
using OpenTK.Graphics.OpenGL;
using OpenTK.Input;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Threading;
using SharpCraft_Client.block;
using SharpCraft_Client.entity;
using SharpCraft_Client.gui;
using SharpCraft_Client.item;
using SharpCraft_Client.json;
using SharpCraft_Client.model;
using SharpCraft_Client.render;
using SharpCraft_Client.render.shader;
using SharpCraft_Client.sound;
using SharpCraft_Client.texture;
using SharpCraft_Client.util;
using SharpCraft_Client.world;
using Bitmap = System.Drawing.Bitmap;
using Rectangle = System.Drawing.Rectangle;
#pragma warning disable 618
namespace SharpCraft_Client
{
internal class SharpCraft : GameWindow
{
//string _dir = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "/.sharpcraft";
private string _dir = "./SharpCraft_Data";
public string GameFolderDir
{
get
{
if (!Directory.Exists(_dir))
Directory.CreateDirectory(_dir);
return _dir;
}
set
{
_dir = value;
if (!Directory.Exists(_dir))
Directory.CreateDirectory(_dir);
}
}
private readonly List<ModMain> _installedMods = new List<ModMain>();
private ItemRegistry _itemRegistry;
private BlockRegistry _blockRegistry;
private RecipeRegistry _recipeRegistry;
public WorldRenderer WorldRenderer;
public EntityRenderer EntityRenderer;
public ParticleRenderer ParticleRenderer;
public SkyboxRenderer SkyboxRenderer;
public GuiRenderer GuiRenderer;
public FontRenderer FontRenderer;
public KeyboardState KeyboardState;
private FBO _frameBuffer;
//public HashSet<Key> KeysDown = new HashSet<Key>();
public MouseOverObject MouseOverObject;
private MouseOverObject _lastMouseOverObject;
public EntityPlayerSp Player;
public World World;
public ServerHander ServerHandler;
public ConcurrentDictionary<BlockPos, DestroyProgress> DestroyProgresses =
new ConcurrentDictionary<BlockPos, DestroyProgress>();
public Random Random = new Random();
private readonly List<MouseButton> _mouseButtonsDown = new List<MouseButton>();
private readonly ConcurrentQueue<Action> _glContextQueue = new ConcurrentQueue<Action>();
private DateTime _updateTimer = DateTime.Now;
private DateTime _lastFpsDate = DateTime.Now;
private WindowState _lastWindowState;
private readonly Thread _renderThread = Thread.CurrentThread;
public static SharpCraft Instance { get; private set; }
public Camera Camera { get; }
public GuiScreen GuiScreen { get; private set; }
private Point _mouseLast;
private float _mouseWheelLast;
public bool IsPaused { get; private set; }
public long GameTicks { get; private set; }
private bool _takeScreenshot;
private int _fpsCounter;
private int _fpsCounterLast;
private long _interactionTickCounter;
private float _sensitivity = 1;
private float _partialTicks;
private static string _title;
public SharpCraft() : base(680, 480, new GraphicsMode(32, 32, 0, 1), _title, GameWindowFlags.Default, DisplayDevice.Default, 3, 3, GraphicsContextFlags.ForwardCompatible)
{
Instance = this;
Camera = new Camera();
ServerHandler = new ServerHander();
VSync = VSyncMode.Off;
Title = _title = $"SharpCraft Alpha 0.0.4 [GLSL {GL.GetString(StringName.ShadingLanguageVersion)}]";
Console.WriteLine("DEBUG: stitching Textures");
TextureManager.LoadTextures();
Init();
}
private void Init()
{
//TODO - just a test - WORKS!
//_installedMods.Add(new TestMod());
GlSetup();
_itemRegistry = new ItemRegistry();
_blockRegistry = new BlockRegistry();
_recipeRegistry = new RecipeRegistry();
LoadMods();
GameRegistry();
WorldRenderer = new WorldRenderer();
EntityRenderer = new EntityRenderer();
GuiRenderer = new GuiRenderer();
FontRenderer = new FontRenderer();
SettingsManager.Load();
//load settings
Camera.SetTargetFov(SettingsManager.GetFloat("fov"));
_sensitivity = SettingsManager.GetFloat("sensitivity");
WorldRenderer.RenderDistance = SettingsManager.GetInt("renderdistance");
OpenGuiScreen(new GuiScreenMainMenu());
}
private void GlSetup()
{
GL.Enable(EnableCap.DepthTest);
GL.Enable(EnableCap.DepthClamp);
GL.Enable(EnableCap.CullFace);
GL.Enable(EnableCap.Blend);
GL.CullFace(CullFaceMode.Back);
GL.PolygonMode(MaterialFace.FrontAndBack, PolygonMode.Fill);
GL.BlendFunc(BlendingFactor.SrcAlpha, BlendingFactor.OneMinusSrcAlpha);
GL.Enable(EnableCap.Multisample);
GL.ActiveTexture(TextureUnit.Texture0);
_frameBuffer = new FBO(Width, Height, true);
}
private void LoadMods()
{
if (Directory.Exists(_dir + "mods"))
{
string[] modFiles = Directory.GetFiles(_dir + "mods");
foreach (string modFile in modFiles)
{
IEnumerable<Type> modClassType = Assembly.LoadFile(modFile).GetModules()
.SelectMany(t => t.GetTypes())
.Where(t => t.IsSubclassOf(typeof(ModMain)));
if (modClassType.FirstOrDefault() is Type type && Activator.CreateInstance(type) is ModMain mm)
{
if (mm.ModInfo.IsValid)
{
Console.WriteLine("registered mod '" + mm.ModInfo.Name + "'!");
_installedMods.Add(mm);
}
else
{
Console.WriteLine("registering mod '" + mm.ModInfo.Name + "' failed!");
}
}
}
}
}
private void GameRegistry()
{
for (int i = 1; i < 6; i++)
{
//SoundEngine.RegisterSound($"block/grass/walk{i}");
}
//register materails
Material.RegisterMaterial(new Material("air", true));
Material.RegisterMaterial(new Material("tallgrass", true));
Material.RegisterMaterial(new Material("grass", false));
Material.RegisterMaterial(new Material("dirt", false));
Material.RegisterMaterial(new Material("stone", false));
Material.RegisterMaterial(new Material("wood", false));
_blockRegistry.Put(new BlockAir());
_blockRegistry.Put(new BlockStone());
_blockRegistry.Put(new BlockGrass());
_blockRegistry.Put(new BlockDirt());
_blockRegistry.Put(new BlockCobbleStone());
_blockRegistry.Put(new BlockPlanks());
_blockRegistry.Put(new BlockBedrock());
_blockRegistry.Put(new BlockLog());
_blockRegistry.Put(new BlockLeaves());
_blockRegistry.Put(new BlockGlass());
_blockRegistry.Put(new BlockCraftingTable());
_blockRegistry.Put(new BlockFurnace());
//_blockRegistry.Put(new BlockSlab());
_blockRegistry.Put(new BlockRare());
_blockRegistry.Put(new BlockLadder());
_blockRegistry.Put(new BlockTallGrass());
_blockRegistry.Put(new BlockTulipRed());
_blockRegistry.Put(new BlockTulipOrange());
_blockRegistry.Put(new BlockTNT());
//POST - MOD Blocks and Items
foreach (ModMain mod in _installedMods)
{
mod.OnItemsAndBlocksRegistry(new RegistryEventArgs(_blockRegistry, _itemRegistry, _recipeRegistry));
}
foreach (var block in BlockRegistry.AllBlocks())
{
_itemRegistry.Put(new ItemBlock(block));
}
Item stick = new ItemStick();
_itemRegistry.Put(new ItemPickaxe("wood"));
_itemRegistry.Put(new ItemPickaxe("stone"));
_itemRegistry.Put(new ItemPickaxe("rare"));
_itemRegistry.Put(stick);
var log = ItemRegistry.GetItem(BlockRegistry.GetBlock<BlockLog>());
var wood = ItemRegistry.GetItem(BlockRegistry.GetBlock<BlockPlanks>());
var cobble = ItemRegistry.GetItem(BlockRegistry.GetBlock<BlockCobbleStone>());
var rare = ItemRegistry.GetItem(BlockRegistry.GetBlock<BlockRare>());
Item[] recipe =
{
cobble, cobble, cobble,
null, stick, null,
null, stick, null
};
_recipeRegistry.RegisterRecipe(recipe, ItemRegistry.GetItem("sharpcraft", "pick_stone"));
recipe = new[]
{
rare, rare, rare,
null, stick, null,
null, stick, null
};
_recipeRegistry.RegisterRecipe(recipe, ItemRegistry.GetItem("sharpcraft", "pick_rare"));
recipe = new[]
{
wood, wood, wood,
null, stick, null,
null, stick, null
};
_recipeRegistry.RegisterRecipe(recipe, ItemRegistry.GetItem("sharpcraft", "pick_wood"));
recipe = new[]
{
cobble, cobble, cobble,
cobble, null, cobble,
cobble, cobble, cobble
};
_recipeRegistry.RegisterRecipe(recipe, ItemRegistry.GetItem(BlockRegistry.GetBlock<BlockFurnace>()));
recipe = new[]
{
wood, wood, null,
wood, wood, null,
null, null, null
};
_recipeRegistry.RegisterRecipe(recipe, ItemRegistry.GetItem(BlockRegistry.GetBlock<BlockCraftingTable>()));
recipe = new[]
{
log, null, null,
null, null, null,
null, null, null
};
_recipeRegistry.RegisterRecipe(recipe, new ItemStack(wood, 4), true);
recipe = new[]
{
wood, null, null,
wood, null, null,
null, null, null
};
_recipeRegistry.RegisterRecipe(recipe, new ItemStack(stick, 4));
recipe = new[]
{
wood, wood, wood,
null, wood, null,
wood, wood, wood
};
_recipeRegistry.RegisterRecipe(recipe, ItemRegistry.GetItem("sharpcraft", "ladder"));
foreach (ModMain mod in _installedMods)
{
mod.OnRecipeRegistry(new RecipeRegistryEventArgs(_recipeRegistry));
}
Block.SetDefaultShader(new Shader("block", "fogDistance"));
JsonModelLoader loader = new JsonModelLoader(Block.DefaultShader, Block.DefaultShader); //TODO - the second argument is the shader for items, which in this case can be the same as the block shader
_blockRegistry.RegisterBlocksPost(loader);
_itemRegistry.RegisterItemsPost(loader);
LangUtil.LoadLang(SettingsManager.GetString("lang"));//TODO - find a proper placement for this line
}
public void StartGame()
{
LoadWorld("MyWorld");
Player?.OnPickup(ItemRegistry.GetItemStack(BlockRegistry.GetBlock<BlockTNT>().GetState()));
}
public void LoadWorld(string saveName)
{
if (World != null)
return;
ParticleRenderer = new ParticleRenderer();
SkyboxRenderer = new SkyboxRenderer();
World loadedWorld = WorldLoader.LoadWorld(saveName);
if (loadedWorld == null)
{
Console.WriteLine("DEBUG: generating World");
BlockPos playerPos = new BlockPos(0, 10, 0);//MathUtil.NextFloat(-100, 100));
World = new WorldClient("MyWorld", "Tomlow's Fuckaround", SettingsManager.GetString("worldseed"));
Player = new EntityPlayerSp(World, playerPos.ToVec());
World.AddEntity(Player);
Player.SetItemStackInInventory(0, new ItemStack(ItemRegistry.GetItem(BlockRegistry.GetBlock<BlockCraftingTable>())));
}
else
{
World = loadedWorld;
}
ResetMouse();
MouseState state = Mouse.GetState();
_mouseLast = new Point(state.X, state.Y);
}
public bool ConnectToServer(string ip, int port)
{
var b = ServerHandler.Connect(ip, port);
if (b)
{
ParticleRenderer = new ParticleRenderer();
SkyboxRenderer = new SkyboxRenderer();
BlockPos playerPos = new BlockPos(0, 100, 0);//MathUtil.NextFloat(-100, 100));
World = new WorldClientServer();
Player = new EntityPlayerSp(World, playerPos.ToVec());
World.AddEntity(Player);
Player.SetItemStackInInventory(0, new ItemStack(ItemRegistry.GetItem(BlockRegistry.GetBlock<BlockCraftingTable>())));
ResetMouse();
MouseState state = Mouse.GetState();
_mouseLast = new Point(state.X, state.Y);
}
return b;
}
public void Disconnect()
{
ParticleRenderer = null;
SkyboxRenderer = null;
if (World is WorldClient wc)
{
WorldLoader.SaveWorld(wc);
}
var wmp = (WorldClientServer)World;
wmp?.DestroyChunkModels();
Player = null;
wmp?.ChunkData.Cleanup();
wmp?.LoadManager.Cleanup();
World = null;
}
private void GameLoop()
{
if (GuiScreen == null && !Focused)
OpenGuiScreen(new GuiScreenIngameMenu());
if (Player != null)
{
if (GameTicks % 5 == 0)
{
SoundEngine.PlaySound($"block/grass/walk{MathUtil.NextInt(1, 6)}");
}
if (AllowIngameInput())
{
if (World?.GetChunk(new BlockPos(Player.Pos).ChunkPos()) == null)
Player.Motion = Vector3.Zero;
bool lmb = _mouseButtonsDown.Contains(MouseButton.Left);
bool rmb = _mouseButtonsDown.Contains(MouseButton.Right);
if (lmb || rmb)
{
_interactionTickCounter++;
BlockPos lastPos = _lastMouseOverObject.blockPos;
if (lmb && _lastMouseOverObject.hit == HitType.Block)
{
if (Player.GameMode == GameMode.Creative)
{
Player.BreakBlock();
}
else
{
ParticleRenderer.SpawnDiggingParticle(_lastMouseOverObject);
if (_lastMouseOverObject.hit == MouseOverObject.hit &&
lastPos == MouseOverObject.blockPos)
{
if (!DestroyProgresses.TryGetValue(lastPos, out DestroyProgress progress))
{
if (World?.GetBlockState(lastPos).Block.Hardness != -1)
{
DestroyProgresses.TryAdd(lastPos,
progress = new DestroyProgress(lastPos, Player));
progress.Progress = 0;
}
}
else
{
progress.Progress +=
Player.GetEquippedItemStack() is ItemStack st && !st.IsEmpty
? st.Item.GetMiningSpeed(World?.GetBlockState(lastPos).Block.Material)
: 1;
}
if (progress.Destroyed)
DestroyProgresses.TryRemove(progress.Pos, out DestroyProgress removed);
}
else ResetDestroyProgress(Player);
}
}
_lastMouseOverObject = MouseOverObject;
if (_interactionTickCounter % 4 == 0)
{
GetMouseOverObject();
if (rmb)
Player.OnClick(MouseButton.Right);
}
}
else
{
_interactionTickCounter = 0;
ResetDestroyProgress(Player);
}
}
else
ResetDestroyProgress(Player);
World?.Update(Player.Pos, WorldRenderer.RenderDistance);
}
WorldRenderer?.Update();
SkyboxRenderer?.Update();
ParticleRenderer?.TickParticles();
GameTicks++;
}
public void GetMouseOverObject()
{
if (World == null)
return;
float radius = 5.5f;
MouseOverObject final = new MouseOverObject();
float dist = float.MaxValue;
Vector3 camPos = Vector3.One * 0.5f + Camera.Pos;
var air = BlockRegistry.GetBlock<BlockAir>();
for (float z = -radius; z <= radius; z++)
{
for (float y = -radius; y <= radius; y++)
{
for (float x = -radius; x <= radius; x++)
{
Vector3 vec = camPos;
vec.X += x;
vec.Y += y;
vec.Z += z;
float f = (vec - Camera.Pos).LengthFast;
if (f <= radius + 0.5f)
{
BlockPos pos = new BlockPos(vec);
BlockState state = World.GetBlockState(pos);
if (state.Block != air)
{
AxisAlignedBb bb = state.Block.BoundingBox.Offset(pos.ToVec());
bool hitSomething = RayHelper.RayIntersectsBB(Camera.Pos,
Camera.GetLookVec(), bb, out Vector3 hitPos, out Vector3 normal);
if (hitSomething)
{
FaceSides sideHit = FaceSides.Null;
if (normal.X < 0)
sideHit = FaceSides.West;
else if (normal.X > 0)
sideHit = FaceSides.East;
if (normal.Y < 0)
sideHit = FaceSides.Down;
else if (normal.Y > 0)
sideHit = FaceSides.Up;
if (normal.Z < 0)
sideHit = FaceSides.North;
else if (normal.Z > 0)
sideHit = FaceSides.South;
BlockPos p = new BlockPos(hitPos - normal * bb.Size / 2);
if (sideHit == FaceSides.Null)
continue;
float l = Math.Abs((Camera.Pos - (p.ToVec() + bb.Size / 2)).Length);
if (l < dist)
{
dist = l;
final.hit = HitType.Block;
final.hitVec = hitPos;
final.blockPos = p;
final.normal = normal;
final.sideHit = sideHit;
final.boundingBox = bb;
}
}
}
}
}
}
}
MouseOverObject = final;
}
private void ResetDestroyProgress(EntityPlayerSp player)
{
foreach (DestroyProgress progress in DestroyProgresses.Values)
{
if (progress.Player == player)
DestroyProgresses.TryRemove(progress.Pos, out DestroyProgress removed);
}
}
private void ResetMouse()
{
Point middle = PointToScreen(new Point(ClientSize.Width / 2, ClientSize.Height / 2));
Mouse.SetPosition(middle.X, middle.Y);
}
public void RunGlTasks()
{
if (_glContextQueue.Count == 0)
return;
while (_glContextQueue.Count > 0)
{
if (_glContextQueue.TryDequeue(out Action func))
func?.Invoke();
}
GL.Flush();
}
private void HandleMouseMovement()
{
MouseState state = Mouse.GetState();
Point point = new Point(state.X, state.Y);
var wheelValue = (int)Math.Ceiling(Mouse.GetState().WheelPrecise);
if (AllowIngameInput())
{
if (wheelValue < _mouseWheelLast)
Player.SelectNextItem();
else if (wheelValue > _mouseWheelLast)
Player.SelectPreviousItem();
Point delta = new Point(_mouseLast.X - point.X, _mouseLast.Y - point.Y);
Camera.Yaw -= delta.X / 1000f * _sensitivity;
Camera.Pitch -= delta.Y / 1000f * _sensitivity;
//ResetMouse();
}
_mouseWheelLast = wheelValue;
_mouseLast = point;
}
public void RunGlContext(Action a)
{
if (_renderThread.ManagedThreadId == Thread.CurrentThread.ManagedThreadId) a();
else _glContextQueue.Enqueue(a);
}
public bool AllowIngameInput()
{
return GuiScreen == null && !(CursorVisible = !Focused);
}
public void OpenGuiScreen(GuiScreen guiScreen)
{
if (guiScreen == null)
{
CloseGuiScreen();
return;
}
GuiScreen = guiScreen;
if (guiScreen.DoesGuiPauseGame)
IsPaused = true;
Point middle = new Point(ClientRectangle.Width / 2, ClientRectangle.Height / 2);
middle = PointToScreen(middle);
Mouse.SetPosition(middle.X, middle.Y);
}
public void CloseGuiScreen()
{
if (GuiScreen == null)
return;
if (GuiScreen.DoesGuiPauseGame)
IsPaused = false;
GuiScreen.OnClose();
GuiScreen = null;
CursorVisible = false;
}
private void CaptureScreen()
{
Bitmap bmp = new Bitmap(ClientSize.Width, ClientSize.Height,
System.Drawing.Imaging.PixelFormat.Format32bppRgb);
using (bmp)
{
BitmapData bData = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height),
ImageLockMode.ReadWrite, bmp.PixelFormat);
GL.ReadBuffer(ReadBufferMode.Back);
// read the data directly into the bitmap's buffer (bitmap is stored in BGRA)
GL.ReadPixels(0, 0, ClientSize.Width, ClientSize.Height, OpenTK.Graphics.OpenGL.PixelFormat.Bgra,
PixelType.UnsignedByte, bData.Scan0);
bmp.UnlockBits(bData);
bmp.RotateFlip(RotateFlipType.RotateNoneFlipY);
DateTime time = DateTime.UtcNow;
string dir = $"{GameFolderDir}/screenshots";
string file =
$"{dir}/{time.Year}-{time.Month}-{time.Day}_{time.TimeOfDay.Hours}.{time.TimeOfDay.Minutes}.{time.TimeOfDay.Seconds}.png";
if (!Directory.Exists(dir))
Directory.CreateDirectory(dir);
using (FileStream fs = new FileStream(file, FileMode.OpenOrCreate, FileAccess.ReadWrite,
FileShare.ReadWrite))
{
bmp.Save(fs, ImageFormat.Png);
}
}
}
public int GetFps()
{
return _fpsCounterLast;
}
public float GetPartialTicksForRender()
{
return _partialTicks;
}
protected override void OnRenderFrame(FrameEventArgs e)
{
GL.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit);
_frameBuffer.Bind();//TODO
GL.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit);
//gt.updateTimer();
//Console.WriteLine(gt.renderPartialTicks);
DateTime now = DateTime.Now;
_partialTicks = (float)MathHelper.Clamp((now - _updateTimer).TotalSeconds / TargetUpdatePeriod, 0, 1);
if (_ticked)
{
_ticked = false;
//Console.WriteLine(_partialTicks);
_partialTicks %= 1f;
}
if ((now - _lastFpsDate).TotalMilliseconds >= 1000)
{
_fpsCounterLast = _fpsCounter;
_fpsCounter = 0;
_lastFpsDate = now;
}
RunGlTasks();
HandleMouseMovement();
Camera.UpdateViewMatrix();
//RENDER SCREEN
if (World != null)
{
SkyboxRenderer?.Render(_partialTicks);
WorldRenderer?.Render(World, _partialTicks);
ParticleRenderer?.Render(_partialTicks);
EntityRenderer?.Render(_partialTicks);
}
//render other gui
if (Player != null)
{
GuiRenderer?.RenderCrosshair();
GuiRenderer?.RenderHUD();
}
//render gui screen
if (GuiScreen != null)
{
CursorVisible = true;
GuiRenderer?.Render(GuiScreen);
}
if (_takeScreenshot)
{
_takeScreenshot = false;
CaptureScreen();
}
_frameBuffer.BindDefault();
_frameBuffer.CopyToScreen();//TODO
SwapBuffers();
_fpsCounter++;
//_spinner.SpinOnce();
}
private bool _ticked;
protected override void OnUpdateFrame(FrameEventArgs e)
{
_ticked = true;
if (!IsDisposed && Visible)
GetMouseOverObject();
GameLoop();
ServerHandler.Tick();
_updateTimer = DateTime.Now;
}
protected override void OnFocusedChanged(EventArgs e)
{
Console.WriteLine("Focus changed to " + Focused);
if (!Focused)
_mouseButtonsDown.Clear();
}
protected override void OnMouseDown(MouseButtonEventArgs e)
{
base.OnMouseDown(e);
if (e.IsPressed)
{
if (GuiScreen == null)
{
GetMouseOverObject();
//pickBlock
if (e.Button == MouseButton.Middle)
Player?.PickBlock();
//place/interact
if (e.Button == MouseButton.Right || e.Button == MouseButton.Left)
{
_interactionTickCounter = 0;
Player?.OnClick(e.Button);
}
}
else
{
MouseState state = Mouse.GetCursorState();
Point point = PointToClient(new Point(state.X, state.Y));
GuiScreen.OnMouseClick(point.X, point.Y, e.Button);
}
if (!_mouseButtonsDown.Contains(e.Button))
_mouseButtonsDown.Add(e.Button);
}
}
protected override void OnMouseUp(MouseButtonEventArgs e)
{
base.OnMouseUp(e);
_mouseButtonsDown.Remove(e.Button);
if (e.Button == MouseButton.Left && AllowIngameInput())
ResetDestroyProgress(Player);
}
public void CommandTeleport(float x, float y, float z)
{
Player.TeleportTo(new Vector3(x, y, z));
}
public void CommandGive(string itemName, int amount)
{
Item item = ItemRegistry.GetItem(itemName);
if (item == null)
return;
// does it work for max stack??
ItemStack itemStack = new ItemStack(item, amount);
Player.OnPickup(itemStack);
}
protected override void OnKeyPress(KeyPressEventArgs e)
{
// If chat add to text
if (GuiScreen is GuiChat gc)
{
gc.InputText(e.KeyChar, KeyboardState.IsKeyDown(Key.ShiftLeft));
}
}
protected override void OnKeyDown(KeyboardKeyEventArgs e)
{
base.OnKeyDown(e);
switch (e.Key)
{
case Key.Escape:
if (GuiScreen is GuiScreenMainMenu || KeyboardState.IsKeyDown(Key.Escape))
return;
if (GuiScreen != null)
CloseGuiScreen();
else
OpenGuiScreen(new GuiScreenIngameMenu());
break;
case Key.E:
if (KeyboardState.IsKeyDown(Key.E))
return;
if (GuiScreen is GuiScreenInventory)
{
CloseGuiScreen();
return;
}
if (GuiScreen == null)
OpenGuiScreen(new GuiScreenInventory());
break;
case Key.Up:
if (KeyboardState.IsKeyDown(Key.Up))
return;
break;
case Key.Down:
if (KeyboardState.IsKeyDown(Key.Down))
return;
break;
case Key.Enter:
if (KeyboardState.IsKeyDown(Key.Enter))
return;
if (GuiScreen is GuiChat gc)
{
gc.SendMessage();
Instance.CloseGuiScreen();
}
else
OpenGuiScreen(new GuiChat());
break;
case Key.F2:
_takeScreenshot = true;
break;
case Key.F11:
if (WindowState != WindowState.Fullscreen)
{
_lastWindowState = WindowState;
WindowState = WindowState.Fullscreen;
}
else
WindowState = _lastWindowState;
break;
}
if (AllowIngameInput())
{
switch (e.Key)
{
case Key.Q:
if (KeyboardState.IsKeyDown(Key.Q))
return;
if (e.Control)
Player.DropHeldStack();
else
Player?.DropHeldItem();
break;
case Key.R:
if (!e.Control || KeyboardState.IsKeyDown(Key.R))
return;
Shader.ReloadAll();
SettingsManager.Load();
TextureManager.Reload();
SoundEngine.Reload();
LangUtil.Reload();
Camera.SetTargetFov(SettingsManager.GetFloat("fov"));
WorldRenderer.RenderDistance = SettingsManager.GetInt("renderdistance");
_sensitivity = SettingsManager.GetFloat("sensitivity");
if (e.Shift)
{
JsonModelLoader.Reload();
//TODO - World?.DestroyChunkModels();
}
break;
}
if (GuiScreen == null)
{
for (int i = 0; i < 9; i++)
{
if (e.Key == Key.Number1 + i)
{
Player?.SetSelectedSlot(i);
break;
}
}
}
}
if (e.Alt && e.Key == Key.F4)
Exit();
KeyboardState = e.Keyboard;
}
protected override void OnKeyUp(KeyboardKeyEventArgs e)
{
base.OnKeyUp(e);
KeyboardState = e.Keyboard;
}
protected override void OnResize(EventArgs e)
{
if (ClientSize.Width < 640)
ClientSize = new Size(640, ClientSize.Height);
if (ClientSize.Height < 480)
ClientSize = new Size(ClientSize.Width, 480);
_frameBuffer.SetSize(Width, Height);
GL.Viewport(ClientRectangle);
//GL.MatrixMode(MatrixMode.Projection);
//GL.LoadIdentity();
//GL.Ortho(0, ClientRectangle.Width, ClientRectangle.Height, 0, Camera.NearPlane, Camera.FarPlane);
Camera.UpdateProjectionMatrix();
}
protected override void OnClosing(CancelEventArgs e)
{
Shader.DestroyAll();
ModelManager.Cleanup();
TextureManager.Destroy();
SoundEngine.Destroy();
if (World is WorldClient wc)
WorldLoader.SaveWorld(wc);
base.OnClosing(e);
}
}
}
| 33.92968
| 209
| 0.469383
|
[
"MIT"
] |
TominoCZ/SharpCraft
|
SharpCraft/SharpCraft.cs
| 37,155
|
C#
|
using UnityEngine;
public class Touch : Sense
{
void OnTriggerEnter(Collider other)
{
Aspect aspect = other.GetComponent<Aspect>();
if (aspect != null)
{
//Check the aspect
if (aspect.aspectType != aspectName)
{
print("Enemy Touch Detected");
}
}
}
}
| 21.875
| 49
| 0.514286
|
[
"MIT"
] |
StanHaakman/unity-tutorial
|
Assets/Scripts/Touch.cs
| 350
|
C#
|
using System.Collections.Generic;
using Newtonsoft.Json;
namespace SitecoreCognitiveServices.Foundation.IBMSDK.Assistant.Models
{
public class CreateWorkspace
{
[JsonProperty("name", NullValueHandling = NullValueHandling.Ignore)]
public string Name { get; set; }
[JsonProperty("description", NullValueHandling = NullValueHandling.Ignore)]
public string Description { get; set; }
[JsonProperty("language", NullValueHandling = NullValueHandling.Ignore)]
public string Language { get; set; }
[JsonProperty("intents", NullValueHandling = NullValueHandling.Ignore)]
public List<CreateIntent> Intents { get; set; }
[JsonProperty("entities", NullValueHandling = NullValueHandling.Ignore)]
public List<CreateEntity> Entities { get; set; }
[JsonProperty("dialog_nodes", NullValueHandling = NullValueHandling.Ignore)]
public List<CreateDialogNode> DialogNodes { get; set; }
[JsonProperty("counterexamples", NullValueHandling = NullValueHandling.Ignore)]
public List<CreateCounterexample> Counterexamples { get; set; }
[JsonProperty("metadata", NullValueHandling = NullValueHandling.Ignore)]
public object Metadata { get; set; }
[JsonProperty("learning_opt_out", NullValueHandling = NullValueHandling.Ignore)]
public bool? LearningOptOut { get; set; }
}
}
| 50.071429
| 88
| 0.708987
|
[
"MIT"
] |
markstiles/SitecoreCognitiveServices.Core
|
src/Foundation/IBMSDK/code/Assistant/Models/CreateWorkspace.cs
| 1,402
|
C#
|
using System.Collections.Generic;
namespace UB3RB0T
{
public class BotResponseData
{
public List<string> Responses { get; set; } = new List<string>();
public EmbedData Embed;
}
}
| 19
| 73
| 0.645933
|
[
"MIT"
] |
ChaseHollins/Yuudachi-Bot
|
src/Types/BotResponseData.cs
| 211
|
C#
|
// ======================================
// Author: Ebenezer Monney
// Email: info@ebenmonney.com
// Copyright (c) 2017 www.ebenmonney.com
// ======================================
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace medicme.Helpers
{
[AttributeUsage(AttributeTargets.Property)]
public sealed class MinimumCountAttribute : ValidationAttribute
{
private readonly int _minCount;
private readonly bool _allowEmptyStringValues;
private readonly bool _required;
private const string _defaultError = "'{0}' must have at least {1} item.";
public MinimumCountAttribute() : this(1)
{
}
public MinimumCountAttribute(int minCount, bool required = true, bool allowEmptyStringValues = false) : base(_defaultError)
{
_minCount = minCount;
_required = required;
_allowEmptyStringValues = allowEmptyStringValues;
}
public override bool IsValid(object value)
{
if (value == null)
return !_required;
var stringList = value as ICollection<string>;
if (!_allowEmptyStringValues && stringList != null)
return stringList.Count(s => !string.IsNullOrWhiteSpace(s)) >= _minCount;
var list = value as ICollection;
if (list != null)
return list.Count >= _minCount;
return false;
}
public override string FormatErrorMessage(string name)
{
return String.Format(this.ErrorMessageString, name, _minCount);
}
}
}
| 28.111111
| 131
| 0.606437
|
[
"MIT"
] |
zouzou73/medicme
|
src/medicme/Helpers/MinimumCountAttribute.cs
| 1,773
|
C#
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.ComponentModel.Composition.Hosting;
using System.ComponentModel.Composition.Primitives;
using System.Diagnostics.CodeAnalysis;
using System.Linq.Expressions;
using System.Text;
using Microsoft.Internal;
namespace System.ComponentModel.Composition.ReflectionModel
{
internal class PartCreatorMemberImportDefinition : ReflectionMemberImportDefinition, IPartCreatorImportDefinition
{
private readonly ContractBasedImportDefinition _productImportDefinition;
public PartCreatorMemberImportDefinition(
LazyMemberInfo importingLazyMember,
ICompositionElement origin,
ContractBasedImportDefinition productImportDefinition)
: base(importingLazyMember, CompositionConstants.PartCreatorContractName, CompositionConstants.PartCreatorTypeIdentity,
productImportDefinition.RequiredMetadata, productImportDefinition.Cardinality, productImportDefinition.IsRecomposable, false, productImportDefinition.RequiredCreationPolicy, MetadataServices.EmptyMetadata, origin)
{
Assumes.NotNull(productImportDefinition);
_productImportDefinition = productImportDefinition;
}
public ContractBasedImportDefinition ProductImportDefinition { get { return _productImportDefinition; } }
public override bool IsConstraintSatisfiedBy(ExportDefinition exportDefinition)
{
if (!base.IsConstraintSatisfiedBy(exportDefinition))
{
return false;
}
return PartCreatorExportDefinition.IsProductConstraintSatisfiedBy(_productImportDefinition, exportDefinition);
}
public override Expression<Func<ExportDefinition, bool>> Constraint
{
get
{
return ConstraintServices.CreatePartCreatorConstraint(base.Constraint, _productImportDefinition);
}
}
public override string ToString()
{
StringBuilder sb = new StringBuilder();
sb.Append(string.Format("\n\tExportFactory of: {0}", ProductImportDefinition.ToString()));
return sb.ToString();
}
}
}
| 41
| 229
| 0.717652
|
[
"MIT"
] |
crummel/dotnet_corefx
|
src/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/PartCreatorMemberImportDefinition.cs
| 2,419
|
C#
|
/* Poly2Tri
* Copyright (c) 2009-2010, Poly2Tri Contributors
* http://code.google.com/p/poly2tri/
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* * Neither the name of Poly2Tri 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.
*/
/// Changes from the Java version
/// Removed getters
/// Has* turned into attributes
/// Future possibilities
/// Comments!
namespace Assets.Scripts.CityGML2GO.Poly2Tri.Triangulation.Delaunay.Sweep
{
public class AdvancingFrontNode
{
public AdvancingFrontNode Next;
public AdvancingFrontNode Prev;
public double Value;
public TriangulationPoint Point;
public DelaunayTriangle Triangle;
public AdvancingFrontNode(TriangulationPoint point)
{
this.Point = point;
Value = point.X;
}
public bool HasNext { get { return Next != null; } }
public bool HasPrev { get { return Prev != null; } }
}
}
| 40.310345
| 84
| 0.727545
|
[
"MIT"
] |
nromblon/AR-GIS
|
Assets/CityGML2GO/Poly2Tri/Triangulation/Delaunay/Sweep/AdvancingFrontNode.cs
| 2,340
|
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("NtApiDotNet")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Google Inc.")]
[assembly: AssemblyProduct("NtApiDotNet")]
[assembly: AssemblyCopyright("Copyright © Google Inc. 2016-2021")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("6aeb5004-6093-4c23-aeae-911d64cacc58")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.1.33.0")]
[assembly: AssemblyInformationalVersion("1.1.33")]
| 39.833333
| 84
| 0.74477
|
[
"Apache-2.0"
] |
avboy1337/sandbox-attacksurface-analysis-tools
|
NtApiDotNet/Properties/AssemblyInfo.cs
| 1,437
|
C#
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.Extensions.Logging;
namespace signalr_scale_out.Pages
{
public class PrivacyModel : PageModel
{
private readonly ILogger<PrivacyModel> _logger;
public PrivacyModel(ILogger<PrivacyModel> logger)
{
_logger = logger;
}
public void OnGet()
{
}
}
}
| 20.64
| 57
| 0.678295
|
[
"MIT"
] |
cealer/chat_signalr_scale_out
|
signalr_scale_out/Pages/Privacy.cshtml.cs
| 518
|
C#
|
using System;
using System.Threading;
using System.Threading.Tasks;
namespace KPreisser
{
/// <summary>
/// Contains extension methods for <see cref="AsyncReaderWriterLockSlim"/>.
/// </summary>
public static class AsyncReaderWriterLockSlimExtension
{
/// <summary>
/// Enters the lock in read mode.
/// </summary>
/// <param name="lockInstance">The <see cref="AsyncReaderWriterLockSlim"/> instance.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> to observe.</param>
/// <returns>A <see cref="IDisposableLock"/> that will release the lock when disposed.</returns>
/// <exception cref="OperationCanceledException"><paramref name="cancellationToken"/> was canceled.</exception>
/// <exception cref="ObjectDisposedException">The current instance has already been disposed.</exception>
public static IDisposableLock GetReadLock(
this AsyncReaderWriterLockSlim lockInstance,
CancellationToken cancellationToken = default(CancellationToken))
{
lockInstance.EnterReadLock(cancellationToken);
return new ActionDisposableLock(lockInstance.ExitReadLock, lockInstance, false);
}
/// <summary>
/// Asynchronously enters the lock in read mode and returns a <see cref="IDisposableLock"/> that
/// will release the lock when disposed.
/// </summary>
/// <param name="lockInstance">The <see cref="AsyncReaderWriterLockSlim"/> instance.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> to observe.</param>
/// <returns>A task that will complete with a <see cref="IDisposableLock"/> when the lock has been entered,
/// which will release the lock when disposed.</returns>
/// <exception cref="OperationCanceledException"><paramref name="cancellationToken"/> was canceled.</exception>
/// <exception cref="ObjectDisposedException">The current instance has already been disposed.</exception>
public static async Task<IDisposableLock> GetReadLockAsync(
this AsyncReaderWriterLockSlim lockInstance,
CancellationToken cancellationToken = default(CancellationToken))
{
await lockInstance.EnterReadLockAsync(cancellationToken);
return new ActionDisposableLock(lockInstance.ExitReadLock, lockInstance, false);
}
/// <summary>
/// Tries to enter the lock in read mode, with an optional integer time-out.
/// </summary>
/// <param name="lockInstance">The <see cref="AsyncReaderWriterLockSlim"/> instance.</param>
/// <param name="millisecondsTimeout">The number of milliseconds to wait, or -1
/// (<see cref="Timeout.Infinite"/>) to wait indefinitely.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> to observe.</param>
/// <returns>A <see cref="IDisposableLock"/> that will release the lock when disposed if the lock
/// could be entered, or <c>null</c> otherwise.</returns>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="millisecondsTimeout"/> is a negative number
/// other than -1, which represents an infinite time-out.</exception>
/// <exception cref="OperationCanceledException"><paramref name="cancellationToken"/> was canceled.</exception>
/// <exception cref="ObjectDisposedException">The current instance has already been disposed.</exception>
public static IDisposableLock TryGetReadLock(
this AsyncReaderWriterLockSlim lockInstance,
int millisecondsTimeout,
CancellationToken cancellationToken = default(CancellationToken))
{
bool returnValue = lockInstance.TryEnterReadLock(
millisecondsTimeout, cancellationToken);
if (returnValue)
return new ActionDisposableLock(lockInstance.ExitReadLock, lockInstance, false);
else
return null;
}
/// <summary>
/// Tries to asynchronously enter the lock in read mode, with an optional integer time-out.
/// </summary>
/// <param name="lockInstance">The <see cref="AsyncReaderWriterLockSlim"/> instance.</param>
/// <param name="millisecondsTimeout">The number of milliseconds to wait, or -1
/// (<see cref="Timeout.Infinite"/>) to wait indefinitely.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> to observe.</param>
/// <returns>A task that will complete with a <see cref="IDisposableLock"/> that will release the lock
/// when disposed if the lock could be entered, or with <c>null</c> otherwise.</returns>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="millisecondsTimeout"/> is a negative number
/// other than -1, which represents an infinite time-out.</exception>
/// <exception cref="OperationCanceledException"><paramref name="cancellationToken"/> was canceled.</exception>
/// <exception cref="ObjectDisposedException">The current instance has already been disposed.</exception>
public static async Task<IDisposableLock> TryGetReadLockAsync(
this AsyncReaderWriterLockSlim lockInstance,
int millisecondsTimeout,
CancellationToken cancellationToken = default(CancellationToken))
{
bool returnValue = await lockInstance.TryEnterReadLockAsync(
millisecondsTimeout, cancellationToken);
if (returnValue)
return new ActionDisposableLock(lockInstance.ExitReadLock, lockInstance, false);
else
return null;
}
/// <summary>
/// Enters the lock in write mode.
/// </summary>
/// <param name="lockInstance">The <see cref="AsyncReaderWriterLockSlim"/> instance.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> to observe.</param>
/// <returns>A <see cref="IDisposableLock"/> that will release the lock when disposed.</returns>
/// <exception cref="OperationCanceledException"><paramref name="cancellationToken"/> was canceled.</exception>
/// <exception cref="ObjectDisposedException">The current instance has already been disposed.</exception>
public static IDisposableLock GetWriteLock(
this AsyncReaderWriterLockSlim lockInstance,
CancellationToken cancellationToken = default(CancellationToken))
{
lockInstance.EnterWriteLock(cancellationToken);
return new ActionDisposableLock(lockInstance.ExitWriteLock, lockInstance, true);
}
/// <summary>
/// Asynchronously enters the lock in write mode.
/// </summary>
/// <param name="lockInstance">The <see cref="AsyncReaderWriterLockSlim"/> instance.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> to observe.</param>
/// <returns>>A task that will complete with a <see cref="IDisposableLock"/> when the lock has been entered,
/// which will release the lock when disposed.</returns>
/// <exception cref="OperationCanceledException"><paramref name="cancellationToken"/> was canceled.</exception>
/// <exception cref="ObjectDisposedException">The current instance has already been disposed.</exception>
public static async Task<IDisposableLock> GetWriteLockAsync(
this AsyncReaderWriterLockSlim lockInstance,
CancellationToken cancellationToken = default(CancellationToken))
{
await lockInstance.EnterWriteLockAsync(cancellationToken);
return new ActionDisposableLock(lockInstance.ExitWriteLock, lockInstance, true);
}
/// <summary>
/// Tries to enter the lock in write mode, with an optional integer time-out.
/// </summary>
/// <param name="lockInstance">The <see cref="AsyncReaderWriterLockSlim"/> instance.</param>
/// <param name="millisecondsTimeout">The number of milliseconds to wait, or -1
/// (<see cref="Timeout.Infinite"/>) to wait indefinitely.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> to observe.</param>
/// <returns>A <see cref="IDisposableLock"/> that will release the lock when disposed if the lock
/// could be entered, or <c>null</c> otherwise.</returns>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="millisecondsTimeout"/> is a negative number
/// other than -1, which represents an infinite time-out.</exception>
/// <exception cref="OperationCanceledException"><paramref name="cancellationToken"/> was canceled.</exception>
/// <exception cref="ObjectDisposedException">The current instance has already been disposed.</exception>
public static IDisposableLock TryGetWriteLock(
this AsyncReaderWriterLockSlim lockInstance,
int millisecondsTimeout,
CancellationToken cancellationToken = default(CancellationToken))
{
bool returnValue = lockInstance.TryEnterWriteLock(
millisecondsTimeout, cancellationToken);
if (returnValue)
return new ActionDisposableLock(lockInstance.ExitWriteLock, lockInstance, true);
else
return null;
}
/// <summary>
/// Tries to asynchronously enter the lock in write mode, with an optional integer time-out.
/// </summary>
/// <param name="lockInstance">The <see cref="AsyncReaderWriterLockSlim"/> instance.</param>
/// <param name="millisecondsTimeout">The number of milliseconds to wait, or -1
/// (<see cref="Timeout.Infinite"/>) to wait indefinitely.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> to observe.</param>
/// <returns>>A task that will complete with a <see cref="IDisposableLock"/> that will release the lock
/// when disposed if the lock could be entered, or with <c>null</c> otherwise.</returns>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="millisecondsTimeout"/> is a negative number
/// other than -1, which represents an infinite time-out.</exception>
/// <exception cref="OperationCanceledException"><paramref name="cancellationToken"/> was canceled.</exception>
/// <exception cref="ObjectDisposedException">The current instance has already been disposed.</exception>
public static async Task<IDisposableLock> TryGetWriteLockAsync(
this AsyncReaderWriterLockSlim lockInstance,
int millisecondsTimeout,
CancellationToken cancellationToken = default(CancellationToken))
{
bool returnValue = await lockInstance.TryEnterWriteLockAsync(
millisecondsTimeout, cancellationToken);
if (returnValue)
return new ActionDisposableLock(lockInstance.ExitWriteLock, lockInstance, true);
else
return null;
}
/// <summary>
/// Downgrades the lock from write mode to read mode.
/// </summary>
/// <param name="lockInstance">The <see cref="AsyncReaderWriterLockSlim"/> instance.</param>
/// <param name="readLock">The <see cref="IDisposableLock"/> which should be downgraded.</param>
/// <exception cref="ObjectDisposedException">The current instance has already been disposed.</exception>
public static void DowngradeWriteLockToReadLock(
this AsyncReaderWriterLockSlim lockInstance,
IDisposableLock readLock)
{
if (readLock == null)
throw new ArgumentNullException(nameof(readLock));
var myReadLock = readLock as ActionDisposableLock;
if (myReadLock == null || myReadLock.LockOrigin != lockInstance ||
!myReadLock.IsWriteLock || myReadLock.IsDisposed)
throw new ArgumentException();
// Downgrade the lock.
lockInstance.DowngradeWriteLockToReadLock();
// Now mark the lock as being a read lock.
myReadLock.IsWriteLock = false;
}
/// <summary>
///
/// </summary>
public interface IDisposableLock : IDisposable
{
}
private class ActionDisposableLock : IDisposableLock
{
private readonly Action action;
private readonly AsyncReaderWriterLockSlim lockOrigin;
private bool isWriteLock;
private bool isDisposed;
public ActionDisposableLock(
Action action,
AsyncReaderWriterLockSlim lockOrigin,
bool isWriteLock)
{
this.action = action;
this.lockOrigin = lockOrigin;
this.isWriteLock = isWriteLock;
}
~ActionDisposableLock()
{
Dispose(false);
}
public AsyncReaderWriterLockSlim LockOrigin => this.lockOrigin;
public bool IsWriteLock
{
get => this.isWriteLock;
set => this.isWriteLock = value;
}
public bool IsDisposed => this.isDisposed;
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (!this.isDisposed)
{
if (disposing)
{
this.action();
}
this.isDisposed = true;
}
}
}
}
}
| 49.222997
| 119
| 0.634317
|
[
"MIT"
] |
kpreisser/AsyncReaderWriterLockSlim
|
AsyncReaderWriterLockSlim/AsyncReaderWriterLockSlimExtension.cs
| 14,129
|
C#
|
namespace STS.Application.Models
{
public class CulturesDisplayViewModel
{
public string Value { get; set; }
public string Text { get; set; }
public bool Current { get; set; }
}
}
| 21.7
| 41
| 0.608295
|
[
"MIT"
] |
mrgrayhat/CleanMicroserviceArchitecture
|
src/MicroServices/IdentityServer/Core/Application/Models/CulturesDisplayViewModel.cs
| 219
|
C#
|
/*
* Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the waf-regional-2016-11-28.normal.json service model.
*/
using System;
using System.Net;
using Amazon.Runtime;
namespace Amazon.WAFRegional.Model
{
///<summary>
/// WAFRegional exception
/// </summary>
#if !PCL && !CORECLR
[Serializable]
#endif
public class WAFStaleDataException : AmazonWAFRegionalException
{
/// <summary>
/// Constructs a new WAFStaleDataException with the specified error
/// message.
/// </summary>
/// <param name="message">
/// Describes the error encountered.
/// </param>
public WAFStaleDataException(string message)
: base(message) {}
/// <summary>
/// Construct instance of WAFStaleDataException
/// </summary>
/// <param name="message"></param>
/// <param name="innerException"></param>
public WAFStaleDataException(string message, Exception innerException)
: base(message, innerException) {}
/// <summary>
/// Construct instance of WAFStaleDataException
/// </summary>
/// <param name="innerException"></param>
public WAFStaleDataException(Exception innerException)
: base(innerException) {}
/// <summary>
/// Construct instance of WAFStaleDataException
/// </summary>
/// <param name="message"></param>
/// <param name="innerException"></param>
/// <param name="errorType"></param>
/// <param name="errorCode"></param>
/// <param name="requestId"></param>
/// <param name="statusCode"></param>
public WAFStaleDataException(string message, Exception innerException, ErrorType errorType, string errorCode, string requestId, HttpStatusCode statusCode)
: base(message, innerException, errorType, errorCode, requestId, statusCode) {}
/// <summary>
/// Construct instance of WAFStaleDataException
/// </summary>
/// <param name="message"></param>
/// <param name="errorType"></param>
/// <param name="errorCode"></param>
/// <param name="requestId"></param>
/// <param name="statusCode"></param>
public WAFStaleDataException(string message, ErrorType errorType, string errorCode, string requestId, HttpStatusCode statusCode)
: base(message, errorType, errorCode, requestId, statusCode) {}
#if !PCL && !CORECLR
/// <summary>
/// Constructs a new instance of the WAFStaleDataException class with serialized data.
/// </summary>
/// <param name="info">The <see cref="T:System.Runtime.Serialization.SerializationInfo" /> that holds the serialized object data about the exception being thrown.</param>
/// <param name="context">The <see cref="T:System.Runtime.Serialization.StreamingContext" /> that contains contextual information about the source or destination.</param>
/// <exception cref="T:System.ArgumentNullException">The <paramref name="info" /> parameter is null. </exception>
/// <exception cref="T:System.Runtime.Serialization.SerializationException">The class name is null or <see cref="P:System.Exception.HResult" /> is zero (0). </exception>
protected WAFStaleDataException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context)
: base(info, context)
{
}
#endif
}
}
| 42.628866
| 178
| 0.645707
|
[
"Apache-2.0"
] |
Bio2hazard/aws-sdk-net
|
sdk/src/Services/WAFRegional/Generated/Model/WAFStaleDataException.cs
| 4,135
|
C#
|
using System.Collections.Generic;
using Orchard.Environment.Extensions.Models;
using Orchard.Security.Permissions;
namespace Orchard.Roles {
public class Permissions : IPermissionProvider {
public static readonly Permission ManageRoles = new Permission { Description = "Managing Roles", Name = "ManageRoles" };
public static readonly Permission AssignRoles = new Permission { Description = "Assign Roles", Name = "AssignRoles", ImpliedBy = new [] { ManageRoles } };
public virtual Feature Feature { get; set; }
public IEnumerable<Permission> GetPermissions() {
return new[] {
ManageRoles, AssignRoles
};
}
public IEnumerable<PermissionStereotype> GetDefaultStereotypes() {
return new[] {
new PermissionStereotype {
Name = "Administrator",
Permissions = new[] {ManageRoles, AssignRoles}
},
};
}
}
}
| 35.821429
| 162
| 0.614158
|
[
"BSD-3-Clause"
] |
1996dylanriley/Orchard
|
src/Orchard.Web/Modules/Orchard.Roles/Permissions.cs
| 1,005
|
C#
|
namespace Labuladong;
public class FreqStack
{
private int maxFreq = 0;
private Dictionary<int, int> valuefreq = new();
private Dictionary<int, Stack<int>> freqvalue = new();
public FreqStack()
{
}
public void Push(int c)
{
var freq = 1;
if (valuefreq.ContainsKey(c))
{
freq = valuefreq[c] + 1;
valuefreq[c] = freq;
}
else
{
valuefreq.Add(c, 1);
}
if (!freqvalue.ContainsKey(freq))
{
freqvalue.Add(freq, new());
}
freqvalue[freq].Push(c);
maxFreq = Math.Max(maxFreq, freq);
}
public int Pop()
{
if (!freqvalue.ContainsKey(maxFreq))
{
return -1;
}
var stack = freqvalue[maxFreq];
var value = stack.Pop();
var freq = valuefreq[value];
valuefreq[value] = freq - 1;
if (!stack.Any())
{
maxFreq = maxFreq - 1;
}
return value;
}
}
| 20.27451
| 58
| 0.478723
|
[
"Apache-2.0"
] |
futugyou/CodeFragments
|
Algorithm/Labuladong/FreqStack.cs
| 1,034
|
C#
|
#if NET462
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Diagnostics;
using static Chessar.Hooks;
using static Microsoft.VisualStudio.TestTools.UnitTesting.Assert;
namespace Chessar.UnitTests.Hooks
{
partial class HooksTests
{
[TestMethod, Conditional("TRACE")]
public void TraceGetFullPathInternalPatchedError_NullException() =>
IsNull(GetTraceMessage(() => TraceGetFullPathInternalPatchedError(null, null)));
[TestMethod, Conditional("TRACE")]
public void TraceGetFullPathInternalPatchedError_TypeIsTraceListener() =>
IsNull(GetTraceMessage(() => TraceGetFullPathInternalPatchedError(new Exception(), typeof(TestTraceListener))));
[TestMethod, Conditional("TRACE")]
public void TraceGetFullPathInternalPatchedError_ReadTrace()
{
var msg = GetTraceMessage(() => TraceGetFullPathInternalPatchedError(new TestTraceException(), null));
IsNotNull(msg);
IsTrue(msg.Contains(nameof(TestTraceException)));
}
}
}
#endif
| 37.413793
| 124
| 0.716129
|
[
"MIT"
] |
chessar/LongPaths
|
UnitTests/Chessar.LongPaths/Hooks/TraceGetFullPathInternalPatchedError.cs
| 1,087
|
C#
|
namespace Atomiv.Core.Application.Messaging
{
class IRequestBus
{
}
}
| 11.857143
| 44
| 0.662651
|
[
"MIT"
] |
atomiv/atomiv-cs
|
src/Core/Application/Messaging/IRequestBus.cs
| 85
|
C#
|
using System;
namespace PodcastRadio.iOS.Interfaces
{
public interface IXiOSView
{
object ParameterData { get; set; }
bool ShowAsPresentView { get; }
}
}
| 18.3
| 42
| 0.644809
|
[
"MIT"
] |
joaowd/PodcastRadio
|
PodcastRadio.iOS/Interfaces/IXiOSView.cs
| 185
|
C#
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using CoreGraphics;
using Foundation;
using UIKit;
using Xamarin.Forms.Internals;
using RectangleF = CoreGraphics.CGRect;
namespace Xamarin.Forms.Platform.iOS
{
public class Platform : BindableObject, INavigation, IDisposable
{
internal static readonly BindableProperty RendererProperty = BindableProperty.CreateAttached("Renderer", typeof(IVisualElementRenderer), typeof(Platform), default(IVisualElementRenderer),
propertyChanged: (bindable, oldvalue, newvalue) =>
{
var view = bindable as VisualElement;
if (view != null)
view.IsPlatformEnabled = newvalue != null;
});
readonly int _alertPadding = 10;
readonly List<Page> _modals;
readonly PlatformRenderer _renderer;
bool _animateModals = true;
bool _appeared;
bool _disposed;
internal Platform()
{
_renderer = new PlatformRenderer(this);
_modals = new List<Page>();
var busyCount = 0;
MessagingCenter.Subscribe(this, Page.BusySetSignalName, (Page sender, bool enabled) =>
{
if (!PageIsChildOfPlatform(sender))
return;
busyCount = Math.Max(0, enabled ? busyCount + 1 : busyCount - 1);
UIApplication.SharedApplication.NetworkActivityIndicatorVisible = busyCount > 0;
});
MessagingCenter.Subscribe(this, Page.AlertSignalName, (Page sender, AlertArguments arguments) =>
{
if (!PageIsChildOfPlatform(sender))
return;
PresentAlert(arguments);
});
MessagingCenter.Subscribe(this, Page.ActionSheetSignalName, (Page sender, ActionSheetArguments arguments) =>
{
if (!PageIsChildOfPlatform(sender))
return;
PresentActionSheet(arguments);
});
}
internal UIViewController ViewController
{
get { return _renderer; }
}
internal Page Page { get; set; }
void IDisposable.Dispose()
{
if (_disposed)
return;
_disposed = true;
Page.DescendantRemoved -= HandleChildRemoved;
MessagingCenter.Unsubscribe<Page, ActionSheetArguments>(this, Page.ActionSheetSignalName);
MessagingCenter.Unsubscribe<Page, AlertArguments>(this, Page.AlertSignalName);
MessagingCenter.Unsubscribe<Page, bool>(this, Page.BusySetSignalName);
Page.DisposeModalAndChildRenderers();
foreach (var modal in _modals)
modal.DisposeModalAndChildRenderers();
_renderer.Dispose();
}
void INavigation.InsertPageBefore(Page page, Page before)
{
throw new InvalidOperationException("InsertPageBefore is not supported globally on iOS, please use a NavigationPage.");
}
IReadOnlyList<Page> INavigation.ModalStack
{
get { return _modals; }
}
IReadOnlyList<Page> INavigation.NavigationStack
{
get { return new List<Page>(); }
}
Task<Page> INavigation.PopAsync()
{
return ((INavigation)this).PopAsync(true);
}
Task<Page> INavigation.PopAsync(bool animated)
{
throw new InvalidOperationException("PopAsync is not supported globally on iOS, please use a NavigationPage.");
}
Task<Page> INavigation.PopModalAsync()
{
return ((INavigation)this).PopModalAsync(true);
}
async Task<Page> INavigation.PopModalAsync(bool animated)
{
var modal = _modals.Last();
_modals.Remove(modal);
modal.DescendantRemoved -= HandleChildRemoved;
var controller = GetRenderer(modal) as UIViewController;
if (_modals.Count >= 1 && controller != null)
await controller.DismissViewControllerAsync(animated);
else
await _renderer.DismissViewControllerAsync(animated);
modal.DisposeModalAndChildRenderers();
return modal;
}
Task INavigation.PopToRootAsync()
{
return ((INavigation)this).PopToRootAsync(true);
}
Task INavigation.PopToRootAsync(bool animated)
{
throw new InvalidOperationException("PopToRootAsync is not supported globally on iOS, please use a NavigationPage.");
}
Task INavigation.PushAsync(Page root)
{
return ((INavigation)this).PushAsync(root, true);
}
Task INavigation.PushAsync(Page root, bool animated)
{
throw new InvalidOperationException("PushAsync is not supported globally on iOS, please use a NavigationPage.");
}
Task INavigation.PushModalAsync(Page modal)
{
return ((INavigation)this).PushModalAsync(modal, true);
}
Task INavigation.PushModalAsync(Page modal, bool animated)
{
EndEditing();
_modals.Add(modal);
modal.DescendantRemoved += HandleChildRemoved;
if (_appeared)
return PresentModal(modal, _animateModals && animated);
return Task.FromResult<object>(null);
}
void INavigation.RemovePage(Page page)
{
throw new InvalidOperationException("RemovePage is not supported globally on iOS, please use a NavigationPage.");
}
public static SizeRequest GetNativeSize(VisualElement view, double widthConstraint, double heightConstraint)
{
Performance.Start(out string reference);
var renderView = GetRenderer(view);
if (renderView == null || renderView.NativeView == null)
return new SizeRequest(Size.Zero);
Performance.Stop(reference);
return renderView.GetDesiredSize(widthConstraint, heightConstraint);
}
public static IVisualElementRenderer CreateRenderer(VisualElement element)
{
var renderer = Internals.Registrar.Registered.GetHandlerForObject<IVisualElementRenderer>(element) ?? new DefaultRenderer();
renderer.SetElement(element);
return renderer;
}
public static IVisualElementRenderer GetRenderer(VisualElement bindable)
{
return (IVisualElementRenderer)bindable.GetValue(RendererProperty);
}
public static void SetRenderer(VisualElement bindable, IVisualElementRenderer value)
{
bindable.SetValue(RendererProperty, value);
}
protected override void OnBindingContextChanged()
{
SetInheritedBindingContext(Page, BindingContext);
base.OnBindingContextChanged();
}
internal void DidAppear()
{
_animateModals = false;
Application.Current.NavigationProxy.Inner = this;
_animateModals = true;
}
internal void LayoutSubviews()
{
if (Page == null)
return;
var rootRenderer = GetRenderer(Page);
if (rootRenderer == null)
return;
rootRenderer.SetElementSize(new Size(_renderer.View.Bounds.Width, _renderer.View.Bounds.Height));
}
internal void SetPage(Page newRoot)
{
if (newRoot == null)
return;
if (Page != null)
throw new NotImplementedException();
Page = newRoot;
if (_appeared == false)
return;
AddChild(Page);
Page.DescendantRemoved += HandleChildRemoved;
Application.Current.NavigationProxy.Inner = this;
}
internal void WillAppear()
{
if (_appeared)
return;
_renderer.View.BackgroundColor = UIColor.White;
_renderer.View.ContentMode = UIViewContentMode.Redraw;
AddChild(Page);
Page.DescendantRemoved += HandleChildRemoved;
_appeared = true;
}
void AddChild(VisualElement view)
{
if (!Application.IsApplicationOrNull(view.RealParent))
Console.Error.WriteLine("Tried to add parented view to canvas directly");
if (GetRenderer(view) == null)
{
var viewRenderer = CreateRenderer(view);
SetRenderer(view, viewRenderer);
_renderer.View.AddSubview(viewRenderer.NativeView);
if (viewRenderer.ViewController != null)
_renderer.AddChildViewController(viewRenderer.ViewController);
viewRenderer.NativeView.Frame = new RectangleF(0, 0, _renderer.View.Bounds.Width, _renderer.View.Bounds.Height);
viewRenderer.SetElementSize(new Size(_renderer.View.Bounds.Width, _renderer.View.Bounds.Height));
}
else
Console.Error.WriteLine("Potential view double add");
}
static void HandleChildRemoved(object sender, ElementEventArgs e)
{
var view = e.Element;
view?.DisposeModalAndChildRenderers();
}
bool PageIsChildOfPlatform(Page page)
{
while (!Application.IsApplicationOrNull(page.RealParent))
page = (Page)page.RealParent;
return Page == page || _modals.Contains(page);
}
// Creates a UIAlertAction which includes a call to hide the presenting UIWindow at the end
UIAlertAction CreateActionWithWindowHide(string text, UIAlertActionStyle style, Action setResult, UIWindow window)
{
return UIAlertAction.Create(text, style,
a =>
{
window.Hidden = true;
setResult();
});
}
void PresentAlert(AlertArguments arguments)
{
var window = new UIWindow { BackgroundColor = Color.Transparent.ToUIColor() };
var alert = UIAlertController.Create(arguments.Title, arguments.Message, UIAlertControllerStyle.Alert);
var oldFrame = alert.View.Frame;
alert.View.Frame = new RectangleF(oldFrame.X, oldFrame.Y, oldFrame.Width, oldFrame.Height - _alertPadding * 2);
if (arguments.Cancel != null)
{
alert.AddAction(CreateActionWithWindowHide(arguments.Cancel, UIAlertActionStyle.Cancel,
() => arguments.SetResult(false), window));
}
if (arguments.Accept != null)
{
alert.AddAction(CreateActionWithWindowHide(arguments.Accept, UIAlertActionStyle.Default,
() => arguments.SetResult(true), window));
}
PresentPopUp(window, alert);
}
void PresentActionSheet(ActionSheetArguments arguments)
{
var alert = UIAlertController.Create(arguments.Title, null, UIAlertControllerStyle.ActionSheet);
var window = new UIWindow { BackgroundColor = Color.Transparent.ToUIColor() };
// Clicking outside of an ActionSheet is an implicit cancel on iPads. If we don't handle it, it freezes the app.
if (arguments.Cancel != null || UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad)
{
alert.AddAction(CreateActionWithWindowHide(arguments.Cancel ?? "", UIAlertActionStyle.Cancel, () => arguments.SetResult(arguments.Cancel), window));
}
if (arguments.Destruction != null)
{
alert.AddAction(CreateActionWithWindowHide(arguments.Destruction, UIAlertActionStyle.Destructive, () => arguments.SetResult(arguments.Destruction), window));
}
foreach (var label in arguments.Buttons)
{
if (label == null)
continue;
var blabel = label;
alert.AddAction(CreateActionWithWindowHide(blabel, UIAlertActionStyle.Default, () => arguments.SetResult(blabel), window));
}
PresentPopUp(window, alert, arguments);
}
static void PresentPopUp(UIWindow window, UIAlertController alert, ActionSheetArguments arguments = null)
{
window.RootViewController = new UIViewController();
window.RootViewController.View.BackgroundColor = Color.Transparent.ToUIColor();
window.WindowLevel = UIWindowLevel.Alert + 1;
window.MakeKeyAndVisible();
if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad && arguments != null)
{
UIDevice.CurrentDevice.BeginGeneratingDeviceOrientationNotifications();
var observer = NSNotificationCenter.DefaultCenter.AddObserver(UIDevice.OrientationDidChangeNotification,
n => { alert.PopoverPresentationController.SourceRect = window.RootViewController.View.Bounds; });
arguments.Result.Task.ContinueWith(t =>
{
NSNotificationCenter.DefaultCenter.RemoveObserver(observer);
UIDevice.CurrentDevice.EndGeneratingDeviceOrientationNotifications();
}, TaskScheduler.FromCurrentSynchronizationContext());
alert.PopoverPresentationController.SourceView = window.RootViewController.View;
alert.PopoverPresentationController.SourceRect = window.RootViewController.View.Bounds;
alert.PopoverPresentationController.PermittedArrowDirections = 0; // No arrow
}
if(!Forms.IsiOS9OrNewer)
{
// For iOS 8, we need to explicitly set the size of the window
window.Frame = new RectangleF(0, 0, UIScreen.MainScreen.Bounds.Width, UIScreen.MainScreen.Bounds.Height);
}
window.RootViewController.PresentViewController(alert, true, null);
}
async Task PresentModal(Page modal, bool animated)
{
var modalRenderer = GetRenderer(modal);
if (modalRenderer == null)
{
modalRenderer = CreateRenderer(modal);
SetRenderer(modal, modalRenderer);
}
var wrapper = new ModalWrapper(modalRenderer);
if (_modals.Count > 1)
{
var topPage = _modals[_modals.Count - 2];
var controller = GetRenderer(topPage) as UIViewController;
if (controller != null)
{
await controller.PresentViewControllerAsync(wrapper, animated);
await Task.Delay(5);
return;
}
}
// One might wonder why these delays are here... well thats a great question. It turns out iOS will claim the
// presentation is complete before it really is. It does not however inform you when it is really done (and thus
// would be safe to dismiss the VC). Fortunately this is almost never an issue
await _renderer.PresentViewControllerAsync(wrapper, animated);
await Task.Delay(5);
}
void EndEditing()
{
// If any text entry controls have focus, we need to end their editing session
// so that they are not the first responder; if we don't some things (like the activity indicator
// on pull-to-refresh) will not work correctly.
// The topmost modal on the stack will have the Window; we can use that to end any current
// editing that's going on
if (_modals.Count > 0)
{
var uiViewController = GetRenderer(_modals[_modals.Count - 1]) as UIViewController;
uiViewController?.View?.Window?.EndEditing(true);
return;
}
// If there aren't any modals, then the platform renderer will have the Window
_renderer.View?.Window?.EndEditing(true);
}
internal class DefaultRenderer : VisualElementRenderer<VisualElement>
{
public override UIView HitTest(CGPoint point, UIEvent uievent)
{
if (!UserInteractionEnabled)
{
// This view can't interact, and neither can its children
return null;
}
// UIview hit testing ignores objects which have an alpha of less than 0.01
// (see https://developer.apple.com/reference/uikit/uiview/1622469-hittest)
// To prevent layouts with low opacity from being implicitly input transparent,
// we need to temporarily bump their alpha value during the actual hit testing,
// then restore it. If the opacity is high enough or user interaction is disabled,
// we don't have to worry about it.
nfloat old = Alpha;
if (UserInteractionEnabled && old <= 0.01)
{
Alpha = (nfloat)0.011;
}
var result = base.HitTest(point, uievent);
if (UserInteractionEnabled && old <= 0.01)
{
Alpha = old;
}
if (UserInteractionEnabled && Element is Layout layout && !layout.CascadeInputTransparent)
{
// This is a Layout with 'InputTransparent = true' and 'InputTransparentInherited = false'
if (this.Equals(result))
{
// If the hit is on the Layout (and not a child control), then ignore it
return null;
}
}
return result;
}
}
}
}
| 30.06721
| 189
| 0.72702
|
[
"MIT"
] |
Opti-Q/Xamarin.Forms
|
Xamarin.Forms.Platform.iOS/Platform.cs
| 14,763
|
C#
|
/*
* Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the rekognition-2016-06-27.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
using System.Xml.Serialization;
using Amazon.Rekognition.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using ThirdParty.Json.LitJson;
namespace Amazon.Rekognition.Model.Internal.MarshallTransformations
{
/// <summary>
/// DetectFaces Request Marshaller
/// </summary>
public class DetectFacesRequestMarshaller : IMarshaller<IRequest, DetectFacesRequest> , IMarshaller<IRequest,AmazonWebServiceRequest>
{
/// <summary>
/// Marshaller the request object to the HTTP request.
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
public IRequest Marshall(AmazonWebServiceRequest input)
{
return this.Marshall((DetectFacesRequest)input);
}
/// <summary>
/// Marshaller the request object to the HTTP request.
/// </summary>
/// <param name="publicRequest"></param>
/// <returns></returns>
public IRequest Marshall(DetectFacesRequest publicRequest)
{
IRequest request = new DefaultRequest(publicRequest, "Amazon.Rekognition");
string target = "RekognitionService.DetectFaces";
request.Headers["X-Amz-Target"] = target;
request.Headers["Content-Type"] = "application/x-amz-json-1.1";
request.HttpMethod = "POST";
string uriResourcePath = "/";
request.ResourcePath = uriResourcePath;
using (StringWriter stringWriter = new StringWriter(CultureInfo.InvariantCulture))
{
JsonWriter writer = new JsonWriter(stringWriter);
writer.WriteObjectStart();
var context = new JsonMarshallerContext(request, writer);
if(publicRequest.IsSetAttributes())
{
context.Writer.WritePropertyName("Attributes");
context.Writer.WriteArrayStart();
foreach(var publicRequestAttributesListValue in publicRequest.Attributes)
{
context.Writer.Write(publicRequestAttributesListValue);
}
context.Writer.WriteArrayEnd();
}
if(publicRequest.IsSetImage())
{
context.Writer.WritePropertyName("Image");
context.Writer.WriteObjectStart();
var marshaller = ImageMarshaller.Instance;
marshaller.Marshall(publicRequest.Image, context);
context.Writer.WriteObjectEnd();
}
writer.WriteObjectEnd();
string snippet = stringWriter.ToString();
request.Content = System.Text.Encoding.UTF8.GetBytes(snippet);
}
return request;
}
private static DetectFacesRequestMarshaller _instance = new DetectFacesRequestMarshaller();
internal static DetectFacesRequestMarshaller GetInstance()
{
return _instance;
}
/// <summary>
/// Gets the singleton.
/// </summary>
public static DetectFacesRequestMarshaller Instance
{
get
{
return _instance;
}
}
}
}
| 35.3
| 137
| 0.609537
|
[
"Apache-2.0"
] |
DalavanCloud/aws-sdk-net
|
sdk/src/Services/Rekognition/Generated/Model/Internal/MarshallTransformations/DetectFacesRequestMarshaller.cs
| 4,236
|
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.R_kvstore.Model.V20150101;
namespace Aliyun.Acs.R_kvstore.Transform.V20150101
{
public class RemoveSubInstanceResponseUnmarshaller
{
public static RemoveSubInstanceResponse Unmarshall(UnmarshallerContext _ctx)
{
RemoveSubInstanceResponse removeSubInstanceResponse = new RemoveSubInstanceResponse();
removeSubInstanceResponse.HttpResponse = _ctx.HttpResponse;
removeSubInstanceResponse.RequestId = _ctx.StringValue("RemoveSubInstance.RequestId");
return removeSubInstanceResponse;
}
}
}
| 36.45
| 90
| 0.762003
|
[
"Apache-2.0"
] |
aliyun/aliyun-openapi-net-sdk
|
aliyun-net-sdk-r-kvstore/R_kvstore/Transform/V20150101/RemoveSubInstanceResponseUnmarshaller.cs
| 1,458
|
C#
|
// *****************************************************************************
//
// (c) Crownwood Consulting Limited 2002
// All rights reserved. The software and associated documentation
// supplied hereunder are the proprietary information of Crownwood Consulting
// Limited, Haxey, North Lincolnshire, England and are supplied subject to
// licence terms.
//
// IDE Version 1.7 www.dotnetmagic.com
// *****************************************************************************
using System;
using System.IO;
using System.Xml;
using System.Data;
using System.Drawing;
using System.Reflection;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using IDE.Menus;
using IDE.Common;
using IDE.Controls;
using IDE.Collections;
namespace IDE.Controls
{
internal class TabGroupLeaf : TabGroupBase
{
// Class constants
protected const int _imageWidth = 16;
protected const int _imageHeight = 16;
protected const int _imageHorzSplit = 0;
protected const int _imageVertSplit = 1;
// Class state
protected static ImageList _internalImages;
// Instance fields
protected MenuCommand _mcClose;
protected MenuCommand _mcSep1;
protected MenuCommand _mcProm;
protected MenuCommand _mcReba;
protected MenuCommand _mcSep2;
protected MenuCommand _mcPrev;
protected MenuCommand _mcNext;
protected MenuCommand _mcVert;
protected MenuCommand _mcHorz;
protected Cursor _savedCursor;
protected bool _dragEntered;
protected TargetManager _targetManager;
protected Controls.TabControl _tabControl;
static TabGroupLeaf()
{
// Create a strip of images by loading an embedded bitmap resource
_internalImages = ResourceHelper.LoadBitmapStrip(Type.GetType("IDE.Controls.TabbedGroups"),
"IDE.Resources.ImagesTabbedGroups.bmp",
new Size(_imageWidth, _imageHeight),
new Point(0,0));
}
public TabGroupLeaf(TabbedGroups tabbedGroups, TabGroupBase parent)
: base(tabbedGroups, parent)
{
// Create our managed tab control instance
_tabControl = new Controls.TabControl();
// We need page drag to begin when mouse dragged a small distance
_tabControl.DragFromControl = false;
// We need to monitor attempts to drag into the tab control
_dragEntered = false;
_tabControl.AllowDrop = true;
_tabControl.DragDrop += new DragEventHandler(OnControlDragDrop);
_tabControl.DragEnter += new DragEventHandler(OnControlDragEnter);
_tabControl.DragLeave += new EventHandler(OnControlDragLeave);
// Need notification when page drag begins
_tabControl.PageDragStart += new MouseEventHandler(OnPageDragStart);
_tabControl.PageDragMove += new MouseEventHandler(OnPageDragMove);
_tabControl.PageDragEnd += new MouseEventHandler(OnPageDragEnd);
_tabControl.PageDragQuit += new MouseEventHandler(OnPageDragQuit);
// Hook into tab page collection events
_tabControl.TabPages.Cleared += new CollectionClear(OnTabPagesCleared);
_tabControl.TabPages.Inserted += new CollectionChange(OnTabPagesInserted);
_tabControl.TabPages.Removed += new CollectionChange(OnTabPagesRemoved);
// Hook into page level events
_tabControl.GotFocus += new EventHandler(OnGainedFocus);
_tabControl.PageGotFocus += new EventHandler(OnGainedFocus);
_tabControl.ClosePressed += new EventHandler(OnClose);
// Manager only created at start of drag operation
_targetManager = null;
DefinePopupMenuForControl(_tabControl);
// Setup the correct 'HideTabsMode' for the control
Notify(TabGroupBase.NotifyCode.DisplayTabMode);
// Define the default setup of TabControl and allow developer to customize
_tabbedGroups.OnTabControlCreated(_tabControl);
}
protected void DefinePopupMenuForControl(Controls.TabControl tabControl)
{
PopupMenu pm = new PopupMenu();
// Add all the standard menus we manage
_mcClose = new MenuCommand("", new EventHandler(OnClose));
_mcSep1 = new MenuCommand("-");
_mcProm = new MenuCommand("", new EventHandler(OnToggleProminent));
_mcReba = new MenuCommand("", new EventHandler(OnRebalance));
_mcSep2 = new MenuCommand("-");
_mcHorz = new MenuCommand("", _internalImages, _imageHorzSplit, new EventHandler(OnNewVertical));
_mcVert = new MenuCommand("", _internalImages, _imageVertSplit, new EventHandler(OnNewHorizontal));
_mcNext = new MenuCommand("", new EventHandler(OnMoveNext));
_mcPrev = new MenuCommand("", new EventHandler(OnMovePrevious));
// Prominent is a radio checked item
_mcProm.RadioCheck = true;
// Use the provided context menu
tabControl.ContextPopupMenu = pm;
// Update command states when shown
tabControl.PopupMenuDisplay += new CancelEventHandler(OnPopupMenuDisplay);
}
public TabPageCollection TabPages
{
get { return _tabControl.TabPages; }
}
public override void Notify(NotifyCode code)
{
switch(code)
{
case NotifyCode.ImageListChanging:
// Are we using the group level imagelist?
if (_tabbedGroups.ImageList == _tabControl.ImageList)
{
// Then remove its use
_tabControl.ImageList = null;
}
break;
case NotifyCode.ImageListChanged:
// If no imagelist defined
if (_tabControl.ImageList == null)
{
// Then use the group level one
_tabControl.ImageList = _tabbedGroups.ImageList;
}
break;
case NotifyCode.StyleChanged:
// Update tab control with new style
_tabControl.Style = _tabbedGroups.Style;
break;
case NotifyCode.DisplayTabMode:
// Apply the latest mode
switch(_tabbedGroups.DisplayTabMode)
{
case IDE.Controls.TabbedGroups.DisplayTabModes.ShowAll:
_tabControl.HideTabsMode = IDE.Controls.TabControl.HideTabsModes.ShowAlways;
break;
case IDE.Controls.TabbedGroups.DisplayTabModes.HideAll:
_tabControl.HideTabsMode = IDE.Controls.TabControl.HideTabsModes.HideAlways;
break;
case IDE.Controls.TabbedGroups.DisplayTabModes.ShowActiveLeaf:
_tabControl.HideTabsMode = (_tabbedGroups.ActiveLeaf == this ? IDE.Controls.TabControl.HideTabsModes.ShowAlways :
IDE.Controls.TabControl.HideTabsModes.HideAlways);
break;
case IDE.Controls.TabbedGroups.DisplayTabModes.ShowMouseOver:
_tabControl.HideTabsMode = IDE.Controls.TabControl.HideTabsModes.HideWithoutMouse;
break;
case IDE.Controls.TabbedGroups.DisplayTabModes.ShowActiveAndMouseOver:
_tabControl.HideTabsMode = (_tabbedGroups.ActiveLeaf == this ? IDE.Controls.TabControl.HideTabsModes.ShowAlways :
IDE.Controls.TabControl.HideTabsModes.HideWithoutMouse);
break;
}
break;
}
}
public override int Count { get { return _tabControl.TabPages.Count; } }
public override bool IsLeaf { get { return true; } }
public override bool IsSequence { get { return false; } }
public override Control GroupControl { get { return _tabControl; } }
public override bool ContainsProminent(bool recurse)
{
// Cache the currently selected prominent group
TabGroupLeaf prominent = _tabbedGroups.ProminentLeaf;
// Valid value to test against?
if (prominent != null)
return (this == prominent);
else
return false;
}
public override void SaveToXml(XmlTextWriter xmlOut)
{
// Output standard values appropriate for all Sequence instances
xmlOut.WriteStartElement("Leaf");
xmlOut.WriteAttributeString("Count", Count.ToString());
xmlOut.WriteAttributeString("Unique", _unique.ToString());
xmlOut.WriteAttributeString("Space", _space.ToString());
// Output each tab page
foreach(Controls.TabPage tp in _tabControl.TabPages)
{
string controlType = "null";
if (tp.Control != null)
controlType = tp.Control.GetType().AssemblyQualifiedName;
xmlOut.WriteStartElement("Page");
xmlOut.WriteAttributeString("Title", tp.Title);
xmlOut.WriteAttributeString("ImageList", (tp.ImageList != null).ToString());
xmlOut.WriteAttributeString("ImageIndex", tp.ImageIndex.ToString());
xmlOut.WriteAttributeString("Selected", tp.Selected.ToString());
xmlOut.WriteAttributeString("Control", controlType);
// Give handlers chance to reconstruct the page
xmlOut.WriteStartElement("CustomPageData");
_tabbedGroups.OnPageSaving(new TGPageSavingEventArgs(tp, xmlOut));
xmlOut.WriteEndElement();
xmlOut.WriteEndElement();
}
xmlOut.WriteEndElement();
}
public override void LoadFromXml(XmlTextReader xmlIn)
{
// Grab the expected attributes
string rawCount = xmlIn.GetAttribute(0);
string rawUnique = xmlIn.GetAttribute(1);
string rawSpace = xmlIn.GetAttribute(2);
// Convert to correct types
int count = Convert.ToInt32(rawCount);
int unique = Convert.ToInt32(rawUnique);
Decimal space = Convert.ToDecimal(rawSpace);
// Update myself with new values
_unique = unique;
_space = space;
// Load each of the children
for(int i=0; i<count; i++)
{
// Read to the first page element or
if (!xmlIn.Read())
throw new ArgumentException("An element was expected but could not be read in");
// Must always be a page instance
if (xmlIn.Name == "Page")
{
Controls.TabPage tp = new Controls.TabPage();
// Grab the expected attributes
string title = xmlIn.GetAttribute(0);
string rawImageList = xmlIn.GetAttribute(1);
string rawImageIndex = xmlIn.GetAttribute(2);
string rawSelected = xmlIn.GetAttribute(3);
string controlType = xmlIn.GetAttribute(4);
// Convert to correct types
bool imageList = Convert.ToBoolean(rawImageList);
int imageIndex = Convert.ToInt32(rawImageIndex);
bool selected = Convert.ToBoolean(rawSelected);
// Setup new page instance
tp.Title = title;
tp.ImageIndex = imageIndex;
tp.Selected = selected;
if (imageList)
tp.ImageList = _tabbedGroups.ImageList;
// Is there a type description of required control?
if (controlType != "null")
{
try
{
// Get type description, if possible
Type t = Type.GetType(controlType);
// Was a valid, known type?
if (t != null)
{
// Get the assembly this type is defined inside
Assembly a = t.Assembly;
if (a != null)
{
// Create a new instance form the assemnly
object newObj = a.CreateInstance(t.FullName);
Control newControl = newObj as Control;
// Must derive from Control to be of use to us
if (newControl != null)
tp.Control = newControl;
}
}
}
catch
{
// We ignore failure to recreate given control type
}
}
// Read to the custom data element
if (!xmlIn.Read())
throw new ArgumentException("An element was expected but could not be read in");
if (xmlIn.Name != "CustomPageData")
throw new ArgumentException("Expected 'CustomPageData' element was not found");
bool finished = xmlIn.IsEmptyElement;
TGPageLoadingEventArgs e = new TGPageLoadingEventArgs(tp, xmlIn);
// Give handlers chance to reconstruct per-page information
_tabbedGroups.OnPageLoading(e);
// Add into the control unless handler cancelled add operation
if (!e.Cancel)
_tabControl.TabPages.Add(tp);
// Read everything until we get the end of custom data marker
while(!finished)
{
// Check it has the expected name
if (xmlIn.NodeType == XmlNodeType.EndElement)
finished = (xmlIn.Name == "CustomPageData");
if (!finished)
{
if (!xmlIn.Read())
throw new ArgumentException("An element was expected but could not be read in");
}
}
// Read past the end of page element
if (!xmlIn.Read())
throw new ArgumentException("An element was expected but could not be read in");
// Check it has the expected name
if (xmlIn.NodeType != XmlNodeType.EndElement)
throw new ArgumentException("End of 'page' element expected but missing");
}
else
throw new ArgumentException("Unknown element was encountered");
}
}
protected void OnGainedFocus(object sender, EventArgs e)
{
// This tab control has the focus, make it the active leaf
_tabbedGroups.ActiveLeaf = this;
}
protected void OnTabPagesCleared()
{
// All pages removed, do we need to compact?
if (_tabbedGroups.AutoCompact)
_tabbedGroups.Compact();
// Mark layout as dirty
if (_tabbedGroups.AutoCalculateDirty)
_tabbedGroups.Dirty = true;
}
protected void OnTabPagesInserted(int index, object value)
{
// If there is no currently active leaf then make it us
if (_tabbedGroups.ActiveLeaf == null)
_tabbedGroups.ActiveLeaf = this;
// Mark layout as dirty
if (_tabbedGroups.AutoCalculateDirty)
_tabbedGroups.Dirty = true;
}
protected void OnTabPagesRemoved(int index, object value)
{
if (_tabControl.TabPages.Count == 0)
{
// All pages removed, do we need to compact?
if (_tabbedGroups.AutoCompact)
_tabbedGroups.Compact();
}
// Mark layout as dirty
if (_tabbedGroups.AutoCalculateDirty)
_tabbedGroups.Dirty = true;
}
protected void OnPopupMenuDisplay(object sender, CancelEventArgs e)
{
// Remove all existing menu items
_tabControl.ContextPopupMenu.MenuCommands.Clear();
// Add our standard set of menus
_tabControl.ContextPopupMenu.MenuCommands.AddRange(new MenuCommand[]{_mcClose, _mcSep1,
_mcProm, _mcReba,
_mcSep2, _mcHorz,
_mcVert, _mcNext,
_mcPrev});
// Are any pages selected
bool valid = (_tabControl.SelectedIndex != -1);
// Define the latest text string
_mcClose.Text = _tabbedGroups.CloseMenuText;
_mcProm.Text = _tabbedGroups.ProminentMenuText;
_mcReba.Text = _tabbedGroups.RebalanceMenuText;
_mcPrev.Text = _tabbedGroups.MovePreviousMenuText;
_mcNext.Text = _tabbedGroups.MoveNextMenuText;
_mcVert.Text = _tabbedGroups.NewVerticalMenuText;
_mcHorz.Text = _tabbedGroups.NewHorizontalMenuText;
// Only need to close option if the tab has close defined
_mcClose.Visible = _tabControl.ShowClose && valid;
_mcSep1.Visible = _tabControl.ShowClose && valid;
// Update the radio button for prominent
_mcProm.Checked = (_tabbedGroups.ProminentLeaf == this);
// Can only create new group if at least two pages exist
bool split = valid && (_tabControl.TabPages.Count > 1);
bool vertSplit = split;
bool horzSplit = split;
TabGroupSequence tgs = _parent as TabGroupSequence;
// If we are not the only leaf, then can only split in
// the same direction as the group we are in
if (tgs.Count > 1)
{
if (tgs.Direction == Direction.Vertical)
vertSplit = false;
else
horzSplit = false;
}
_mcVert.Visible = vertSplit;
_mcHorz.Visible = horzSplit;
// Can only how movement if group exists in that direction
_mcNext.Visible = valid && (_tabbedGroups.NextLeaf(this) != null);
_mcPrev.Visible = valid && (_tabbedGroups.PreviousLeaf(this) != null);
TGContextMenuEventArgs tge = new TGContextMenuEventArgs(this,
_tabControl,
_tabControl.SelectedTab,
_tabControl.ContextPopupMenu);
// Generate event so handlers can add/remove/cancel menu
_tabbedGroups.OnPageContextMenu(tge);
// Pass back cancel value
e.Cancel = tge.Cancel;
}
internal void OnClose(object sender, EventArgs e)
{
TGCloseRequestEventArgs tge = new TGCloseRequestEventArgs(this, _tabControl, _tabControl.SelectedTab);
// Generate event so handlers can perform appropriate action
_tabbedGroups.OnPageCloseRequested(tge);
// Still want to close the page?
if (!tge.Cancel)
_tabControl.TabPages.Remove(_tabControl.SelectedTab);
}
internal void OnToggleProminent(object sender, EventArgs e)
{
// Toggel the prominent mode
if (_tabbedGroups.ProminentLeaf == this)
_tabbedGroups.ProminentLeaf = null;
else
_tabbedGroups.ProminentLeaf = this;
}
internal void OnRebalance(object sender, EventArgs e)
{
_tabbedGroups.Rebalance();
}
internal void OnMovePrevious(object sender, EventArgs e)
{
// Find the previous leaf node
TabGroupLeaf prev = _tabbedGroups.PreviousLeaf(this);
// Must always be valid!
if (prev != null)
MovePageToLeaf(prev);
}
internal void OnMoveNext(object sender, EventArgs e)
{
// Find the previous leaf node
TabGroupLeaf next = _tabbedGroups.NextLeaf(this);
// Must always be valid!
if (next != null)
MovePageToLeaf(next);
}
internal void OnNewVertical(object sender, EventArgs e)
{
NewVerticalGroup(this, false);
}
protected void OnNewHorizontal(object sender, EventArgs e)
{
NewHorizontalGroup(this, false);
}
internal void NewVerticalGroup(TabGroupLeaf sourceLeaf, bool before)
{
TabGroupSequence tgs = this.Parent as TabGroupSequence;
// We must have a parent sequence!
if (tgs != null)
{
tgs.Direction = Direction.Vertical;
AddGroupToSequence(tgs, sourceLeaf, before);
}
}
internal void NewHorizontalGroup(TabGroupLeaf sourceLeaf, bool before)
{
TabGroupSequence tgs = this.Parent as TabGroupSequence;
// We must have a parent sequence!
if (tgs != null)
{
tgs.Direction = Direction.Horizontal;
AddGroupToSequence(tgs, sourceLeaf, before);
}
}
internal void MovePageToLeaf(TabGroupLeaf leaf)
{
// Remember original auto compact mode
bool autoCompact = _tabbedGroups.AutoCompact;
// Turn mode off as it interferes with reorganisation
_tabbedGroups.AutoCompact = false;
// Get the requested tab page to be moved to new leaf
TabPage tp = _tabControl.SelectedTab;
// Remove page from ourself
_tabControl.TabPages.Remove(tp);
// Add into the new leaf
leaf.TabPages.Add(tp);
// Make new leaf the active one
_tabbedGroups.ActiveLeaf = leaf;
TabControl tc = leaf.GroupControl as Controls.TabControl;
// Select the newly added page
tc.SelectedTab = tp;
// Reset compacting mode as we have updated the structure
_tabbedGroups.AutoCompact = autoCompact;
// Do we need to compact?
if (_tabbedGroups.AutoCompact)
_tabbedGroups.Compact();
}
protected void AddGroupToSequence(TabGroupSequence tgs, TabGroupLeaf sourceLeaf, bool before)
{
// Remember original auto compact mode
bool autoCompact = _tabbedGroups.AutoCompact;
// Turn mode off as it interferes with reorganisation
_tabbedGroups.AutoCompact = false;
// Find our index into parent collection
int pos = tgs.IndexOf(this);
TabGroupLeaf newGroup = null;
// New group inserted before existing one?
if (before)
newGroup = tgs.InsertNewLeaf(pos);
else
{
// No, are we at the end of the collection?
if (pos == (tgs.Count - 1))
newGroup = tgs.AddNewLeaf();
else
newGroup = tgs.InsertNewLeaf(pos + 1);
}
// Get tab control for source leaf
Controls.TabControl tc = sourceLeaf.GroupControl as Controls.TabControl;
TabPage tp = tc.SelectedTab;
// Remove page from ourself
tc.TabPages.Remove(tp);
// Add into the new leaf
newGroup.TabPages.Add(tp);
// Reset compacting mode as we have updated the structure
_tabbedGroups.AutoCompact = autoCompact;
// Do we need to compact?
if (_tabbedGroups.AutoCompact)
_tabbedGroups.Compact();
}
protected void OnPageDragStart(object sender, MouseEventArgs e)
{
// Save the current cursor value
_savedCursor = _tabControl.Cursor;
// Manager will create hot zones and draw dragging rectangle
_targetManager = new TargetManager(_tabbedGroups, this, _tabControl);
}
protected void OnPageDragMove(object sender, MouseEventArgs e)
{
// Convert from Control coordinates to screen coordinates
Point mousePos = _tabControl.PointToScreen(new Point(e.X, e.Y));
// Let manager decide on drawing rectangles and setting cursor
_targetManager.MouseMove(mousePos);
}
protected void OnPageDragEnd(object sender, MouseEventArgs e)
{
// Give manager chance to action request and cleanup
_targetManager.Exit();
// No longer need the manager
_targetManager = null;
// Restore the original cursor
_tabControl.Cursor = _savedCursor;
}
protected void OnPageDragQuit(object sender, MouseEventArgs e)
{
// Give manager chance to cleanup
_targetManager.Quit();
// No longer need the manager
_targetManager = null;
// Restore the original cursor
_tabControl.Cursor = _savedCursor;
}
protected void OnControlDragEnter(object sender, DragEventArgs drgevent)
{
_dragEntered = ValidFormat(drgevent);
// Do we allow the drag to occur?
if (_dragEntered)
{
// Must draw a drag indicator
DrawDragIndicator();
// Update the allowed effects
drgevent.Effect = DragDropEffects.Copy;
}
}
protected void OnControlDragDrop(object sender, DragEventArgs drgevent)
{
// Do we allow the drop to occur?
if (_dragEntered)
{
// Must remove the drag indicator
DrawDragIndicator();
// Generate an event so caller can perform required action
_tabbedGroups.OnExternalDrop(this, _tabControl, GetDragProvider(drgevent));
}
_dragEntered = false;
}
protected void OnControlDragLeave(object sender, EventArgs e)
{
// Do we need to remove the drag indicator?
if (_dragEntered)
DrawDragIndicator();
_dragEntered = false;
}
protected bool ValidFormat(DragEventArgs e)
{
return e.Data.GetDataPresent(typeof(TabbedGroups.DragProvider));
}
protected TabbedGroups.DragProvider GetDragProvider(DragEventArgs e)
{
return (TabbedGroups.DragProvider)e.Data.GetData(typeof(TabbedGroups.DragProvider));
}
protected void DrawDragIndicator()
{
// Create client rectangle
Rectangle clientRect = new Rectangle(new Point(0,0), _tabControl.ClientSize);
// Draw drag indicator around whole control
TargetManager.DrawDragRectangle(_tabControl.RectangleToScreen(clientRect));
}
}
}
| 40.374659
| 147
| 0.525662
|
[
"MIT"
] |
chandusekhar/gViewGisOS
|
gView.GeoProcessing.UI/IDE/Controls/TabbedGroups/TabGroupLeaf.cs
| 29,635
|
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 Microsoft.DotNet.VersionTools.BuildManifest.Model;
using System;
namespace Microsoft.DotNet.Build.Tasks.Feed.Model
{
/**
* The goal of this class is to configure a channel that a build can be promoted to,
* most of the information here is just an extension of the info already present in
* BAR. However, a big difference in relation to BAR Channel is that this class has
* the `PublishingInfraVersion` that describes which version of the publishing infra
* structure the channel configuration is applicable.
*/
public struct TargetChannelConfig
{
/// <summary>
/// Which version of the publishing infra can use this configuration.
/// </summary>
public PublishingInfraVersion PublishingInfraVersion { get; }
/// <summary>
/// BAR Channel ID
/// </summary>
public int Id { get; }
/// <summary>
/// The name that should be used for creating Aka.ms links for this channel.
/// </summary>
public string AkaMSChannelName { get; }
/// <summary>
/// The URL (including the index.json suffix) of the *shipping* feed to be used for this channel.
/// </summary>
public string ShippingFeed { get; }
/// <summary>
/// The URL (including the index.json suffix) of the *transport* feed to be used for this channel.
/// </summary>
public string TransportFeed { get; }
/// <summary>
/// The URL (including the index.json suffix) of the *symbols* feed to be used for this channel.
/// </summary>
public string SymbolsFeed { get; }
/// <summary>
/// The URL (including the index.json suffix) where *checksums* should be published to.
/// </summary>
public string ChecksumsFeed { get; }
/// <summary>
/// The URL (including the index.json suffix) where *installers* should be published to.
/// </summary>
public string InstallersFeed { get; }
public TargetChannelConfig(
int id,
PublishingInfraVersion publishingInfraVersion,
string akaMSChannelName,
string shippingFeed,
string transportFeed,
string symbolsFeed,
string checksumsFeed,
string installersFeed)
{
Id = id;
PublishingInfraVersion = publishingInfraVersion;
AkaMSChannelName = akaMSChannelName;
ShippingFeed = shippingFeed;
TransportFeed = transportFeed;
SymbolsFeed = symbolsFeed;
ChecksumsFeed = checksumsFeed;
InstallersFeed = installersFeed;
}
public override string ToString()
{
return
$"\n Channel ID: '{Id}' " +
$"\n Infra-version: '{PublishingInfraVersion}' " +
$"\n AkaMSChannelName: '{AkaMSChannelName}' " +
$"\n Shipping-feed: '{ShippingFeed}' " +
$"\n Transport-feed: '{TransportFeed}' " +
$"\n Symbols-feed: '{SymbolsFeed}' " +
$"\n Installers-feed: '{InstallersFeed}' " +
$"\n Checksums-feed: '{ChecksumsFeed}' ";
}
public override bool Equals(object other)
{
return other is TargetChannelConfig config &&
PublishingInfraVersion == config.PublishingInfraVersion &&
Id == config.Id &&
AkaMSChannelName.Equals(config.AkaMSChannelName, StringComparison.OrdinalIgnoreCase) &&
ShippingFeed.Equals(config.ShippingFeed, StringComparison.OrdinalIgnoreCase) &&
TransportFeed.Equals(config.TransportFeed, StringComparison.OrdinalIgnoreCase) &&
SymbolsFeed.Equals(config.SymbolsFeed, StringComparison.OrdinalIgnoreCase) &&
ChecksumsFeed.Equals(config.ChecksumsFeed, StringComparison.OrdinalIgnoreCase) &&
InstallersFeed.Equals(config.InstallersFeed, StringComparison.OrdinalIgnoreCase);
}
public override int GetHashCode()
{
return (PublishingInfraVersion,
Id,
AkaMSChannelName,
ShippingFeed,
TransportFeed,
SymbolsFeed,
ChecksumsFeed,
InstallersFeed).GetHashCode();
}
}
}
| 39.542373
| 106
| 0.593656
|
[
"MIT"
] |
0xced/arcade
|
src/Microsoft.DotNet.Build.Tasks.Feed/src/model/TargetChannelConfig.cs
| 4,666
|
C#
|
using Newtonsoft.Json;
using System.Collections.Generic;
namespace TMDb.Client.Api.V3.Models.People
{
public class PeopleTranslationsResponse : TMDbResponse
{
[JsonProperty("id")]
public virtual int Id { get; set; }
[JsonProperty("translations")]
public virtual IEnumerable<PersonTranslation> Translations { get; set; }
}
}
| 26.428571
| 80
| 0.686486
|
[
"MIT"
] |
joshuajones02/TMDb
|
TMDb.Client/API/V3/Models/People/PeopleTranslationsResponse.cs
| 372
|
C#
|
using System;
using Engine.Models;
namespace Engine.Actions
{
public class AttackWithWeapon : BaseAction, IAction
{
private readonly int _maximumDamage;
private readonly int _minimumDamage;
public AttackWithWeapon(GameItem itemInUse, int minimumDamage, int maximumDamage)
: base(itemInUse)
{
if(itemInUse.Category != GameItem.ItemCategory.Weapon)
{
throw new ArgumentException($"{itemInUse.Name} is not a weapon");
}
if(_minimumDamage < 0)
{
throw new ArgumentException("minimumDamage must be 0 or larger");
}
if(_maximumDamage < _minimumDamage)
{
throw new ArgumentException("maximumDamage must be >= minimumDamage");
}
_minimumDamage = minimumDamage;
_maximumDamage = maximumDamage;
}
public void Execute(LivingEntity actor, LivingEntity target)
{
int damage = RandomNumberGenerator.NumberBetween(_minimumDamage, _maximumDamage);
string actorName = (actor is Player) ? "You" : $"The {actor.Name.ToLower()}";
string targetName = (target is Player) ? "you" : $"the {target.Name.ToLower()}";
if(damage == 0)
{
ReportResult($"{actorName} missed {targetName}.");
}
else
{
ReportResult($"{actorName} hit {targetName} for {damage} point{(damage > 1 ? "s" : "")}.");
target.TakeDamage(damage);
}
}
}
}
| 31.346154
| 107
| 0.553374
|
[
"MIT"
] |
Boyce-Bellair/rphOriginalFiles
|
Engine/Actions/AttackWithWeapon.cs
| 1,632
|
C#
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/*S-shaped piece*/
public class TetrisSBlock : TetrisBlock {
private static Material blockMaterial = Resources.Load("Materials/Piece2_Mat", typeof(Material)) as Material;
private Vector3[][] rotationConfigurations;
public TetrisSBlock() : base(2) {
blockModel [0].GetComponent<Renderer> ().material = blockMaterial;
blockModel [1].GetComponent<Renderer> ().material = blockMaterial;
blockModel [2].GetComponent<Renderer> ().material = blockMaterial;
blockModel [3].GetComponent<Renderer> ().material = blockMaterial;
maxRotationStates = 2;
rotationConfigurations = new Vector3[2][];
rotationConfigurations [0] = new Vector3[4];
rotationConfigurations [0][0].Set (0, 0, 0);
rotationConfigurations [0][1].Set (1, 0, 0);
rotationConfigurations [0][2].Set (1, 0, 1);
rotationConfigurations [0][3].Set (2, 0, 1);
rotationConfigurations [1] = new Vector3[4];
rotationConfigurations [1][0].Set (0, 0, 2);
rotationConfigurations [1][1].Set (0, 0, 1);
rotationConfigurations [1][2].Set (1, 0, 1);
rotationConfigurations [1][3].Set (1, 0, 0);
blockConfiguration = rotationConfigurations [0];
}
public override Material getBlockMaterial(){
return(blockMaterial);
}
public override Vector3[] getNextRotationConfiguration(){
return(rotationConfigurations[(rotateState + 1) % maxRotationStates]);
}
public override Vector3[] getPreviousRotationConfiguration(){
return(rotationConfigurations[System.Math.Abs(rotateState - 1) % maxRotationStates]);
}
}
| 33.553191
| 110
| 0.733037
|
[
"MIT"
] |
PuzzleBot/Tetris-Remake
|
Assets/Scripts/Tetris_Blocks/TetrisSBlock.cs
| 1,579
|
C#
|
// ***********************************************************************
// <copyright file="AssemblyInfo.cs" company="Holotrek">
// Copyright © Holotrek 2016
// </copyright>
// ***********************************************************************
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Kore.Providers.Containers.TinyIoC")]
[assembly: AssemblyDescription("An implementation of the Holotrek's Container provider that uses TinyIoC.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Holotrek")]
[assembly: AssemblyProduct("Kore.Providers.Containers.TinyIoC")]
[assembly: AssemblyCopyright("Copyright © Holotrek 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("8042363a-0f1f-45f7-9320-b5c8c475bcc7")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.1.0.*")]
[assembly: AssemblyFileVersion("1.1.0.0")]
| 42.47619
| 108
| 0.68722
|
[
"MIT"
] |
holotrek/kore-asp
|
Kore/Providers/Containers/Kore.Providers.Containers.TinyIoC/Properties/AssemblyInfo.cs
| 1,788
|
C#
|
/*
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
using System;
using System.Net;
using Amazon.ElasticLoadBalancing.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
namespace Amazon.ElasticLoadBalancing.Model.Internal.MarshallTransformations
{
/// <summary>
/// Response Unmarshaller for CreateLoadBalancerListeners operation
/// </summary>
internal class CreateLoadBalancerListenersResponseUnmarshaller : XmlResponseUnmarshaller
{
public override AmazonWebServiceResponse Unmarshall(XmlUnmarshallerContext context)
{
CreateLoadBalancerListenersResponse response = new CreateLoadBalancerListenersResponse();
while (context.Read())
{
if (context.IsStartElement)
{
if(context.TestExpression("CreateLoadBalancerListenersResult", 2))
{
response.CreateLoadBalancerListenersResult = CreateLoadBalancerListenersResultUnmarshaller.GetInstance().Unmarshall(context);
continue;
}
if (context.TestExpression("ResponseMetadata", 2))
{
response.ResponseMetadata = ResponseMetadataUnmarshaller.GetInstance().Unmarshall(context);
}
}
}
return response;
}
public override AmazonServiceException UnmarshallException(XmlUnmarshallerContext context, Exception innerException, HttpStatusCode statusCode)
{
ErrorResponse errorResponse = ErrorResponseUnmarshaller.GetInstance().Unmarshall(context);
if (errorResponse.Code != null && errorResponse.Code.Equals("InvalidConfigurationRequest"))
{
return new InvalidConfigurationRequestException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("DuplicateListener"))
{
return new DuplicateListenerException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("CertificateNotFound"))
{
return new CertificateNotFoundException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("LoadBalancerNotFound"))
{
return new LoadBalancerNotFoundException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode);
}
return new AmazonElasticLoadBalancingException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode);
}
private static CreateLoadBalancerListenersResponseUnmarshaller instance;
public static CreateLoadBalancerListenersResponseUnmarshaller GetInstance()
{
if (instance == null)
{
instance = new CreateLoadBalancerListenersResponseUnmarshaller();
}
return instance;
}
}
}
| 42.628866
| 180
| 0.654414
|
[
"Apache-2.0"
] |
mahanthbeeraka/dataservices-sdk-dotnet
|
AWSSDK/Amazon.ElasticLoadBalancing/Model/Internal/MarshallTransformations/CreateLoadBalancerListenersResponseUnmarshaller.cs
| 4,135
|
C#
|
using System.Linq;
using FluentNHibernate.MappingModel;
using FluentNHibernate.MappingModel.Collections;
using FluentNHibernate.Testing.DomainModel.Mapping;
using NUnit.Framework;
namespace FluentNHibernate.Testing.FluentInterfaceTests
{
[TestFixture]
public class OneToManyMutablePropertyModelGenerationTests : BaseModelFixture
{
[Test]
public void AccessShouldSetModelAccessPropertyToValue()
{
OneToMany<ChildObject>(x => x.BagOfChildren)
.Mapping(m => m.Access.Field())
.ModelShouldMatch(x => x.Access.ShouldEqual("field"));
}
[Test]
public void BatchSizeShouldSetModelBatchSizePropertyToValue()
{
OneToMany<ChildObject>(x => x.BagOfChildren)
.Mapping(m => m.BatchSize(10))
.ModelShouldMatch(x => x.BatchSize.ShouldEqual(10));
}
[Test]
public void CacheShouldSetModelCachePropertyToValue()
{
OneToMany<ChildObject>(x => x.BagOfChildren)
.Mapping(m => m.Cache.ReadOnly())
.ModelShouldMatch(x =>
{
x.Cache.ShouldNotBeNull();
x.Cache.Usage.ShouldEqual("read-only");
});
}
[Test]
public void CascadeShouldSetModelCascadePropertyToValue()
{
OneToMany<ChildObject>(x => x.BagOfChildren)
.Mapping(m => m.Cascade.All())
.ModelShouldMatch(x => x.Cascade.ShouldEqual("all"));
}
[Test]
public void CollectionTypeShouldSetModelCollectionTypePropertyToValue()
{
OneToMany<ChildObject>(x => x.BagOfChildren)
.Mapping(m => m.CollectionType("type"))
.ModelShouldMatch(x => x.CollectionType.ShouldEqual(new TypeReference("type")));
}
[Test]
public void ForeignKeyCascadeOnDeleteShouldSetModelKeyOnDeletePropertyToCascade()
{
OneToMany<ChildObject>(x => x.BagOfChildren)
.Mapping(m => m.ForeignKeyCascadeOnDelete())
.ModelShouldMatch(x => x.Key.OnDelete.ShouldEqual("cascade"));
}
[Test]
public void InverseShouldSetModelInversePropertyToTrue()
{
OneToMany<ChildObject>(x => x.BagOfChildren)
.Mapping(m => m.Inverse())
.ModelShouldMatch(x => x.Inverse.ShouldBeTrue());
}
[Test]
public void NotInverseShouldSetModelInversePropertyToFalse()
{
OneToMany<ChildObject>(x => x.BagOfChildren)
.Mapping(m => m.Not.Inverse())
.ModelShouldMatch(x => x.Inverse.ShouldBeFalse());
}
[Test]
public void KeyColumnNameShouldAddColumnToModelKeyColumnsCollection()
{
OneToMany<ChildObject>(x => x.BagOfChildren)
.Mapping(m => m.KeyColumn("col"))
.ModelShouldMatch(x => x.Key.Columns.Count().ShouldEqual(1));
}
[Test]
public void KeyColumnNamesShouldAddColumnsToModelKeyColumnsCollection()
{
OneToMany<ChildObject>(x => x.BagOfChildren)
.Mapping(m => m.KeyColumns.Add("col1", "col2"))
.ModelShouldMatch(x => x.Key.Columns.Count().ShouldEqual(2));
}
[Test]
public void LazyLoadShouldSetModelLazyPropertyToTrue()
{
OneToMany<ChildObject>(x => x.BagOfChildren)
.Mapping(m => m.LazyLoad())
.ModelShouldMatch(x => x.Lazy.ShouldEqual(true));
}
[Test]
public void NotLazyLoadShouldSetModelLazyPropertyToFalse()
{
OneToMany<ChildObject>(x => x.BagOfChildren)
.Mapping(m => m.Not.LazyLoad())
.ModelShouldMatch(x => x.Lazy.ShouldEqual(false));
}
[Test]
public void NotFoundShouldSetModelRelationshipNotFoundPropertyToValue()
{
OneToMany<ChildObject>(x => x.BagOfChildren)
.Mapping(m => m.NotFound.Ignore())
.ModelShouldMatch(x => ((OneToManyMapping)x.Relationship).NotFound.ShouldEqual("ignore"));
}
[Test]
public void WhereShouldSetModelWherePropertyToValue()
{
OneToMany<ChildObject>(x => x.BagOfChildren)
.Mapping(m => m.Where("x = 1"))
.ModelShouldMatch(x => x.Where.ShouldEqual("x = 1"));
}
[Test]
public void WithForeignKeyConstraintNameShouldSetModelKeyForeignKeyPropertyToValue()
{
OneToMany<ChildObject>(x => x.BagOfChildren)
.Mapping(m => m.ForeignKeyConstraintName("fk"))
.ModelShouldMatch(x => x.Key.ForeignKey.ShouldEqual("fk"));
}
[Test]
public void WithTableNameShouldSetModelTableNamePropertyToValue()
{
OneToMany<ChildObject>(x => x.BagOfChildren)
.Mapping(m => m.Table("t"))
.ModelShouldMatch(x => x.TableName.ShouldEqual("t"));
}
[Test]
public void SchemaIsShouldSetModelSchemaPropertyToValue()
{
OneToMany<ChildObject>(x => x.BagOfChildren)
.Mapping(m => m.Schema("dto"))
.ModelShouldMatch(x => x.Schema.ShouldEqual("dto"));
}
[Test]
public void FetchShouldSetModelFetchPropertyToValue()
{
OneToMany<ChildObject>(x => x.BagOfChildren)
.Mapping(m => m.Fetch.Select())
.ModelShouldMatch(x => x.Fetch.ShouldEqual("select"));
}
[Test]
public void PersisterShouldSetModelPersisterPropertyToAssemblyQualifiedName()
{
OneToMany<ChildObject>(x => x.BagOfChildren)
.Mapping(m => m.Persister<CustomPersister>())
.ModelShouldMatch(x => x.Persister.GetUnderlyingSystemType().ShouldEqual(typeof(CustomPersister)));
}
[Test]
public void CheckShouldSetModelCheckToValue()
{
OneToMany<ChildObject>(x => x.BagOfChildren)
.Mapping(m => m.Check("x > 100"))
.ModelShouldMatch(x => x.Check.ShouldEqual("x > 100"));
}
[Test]
public void OptimisticLockShouldSetModelOptimisticLockToValue()
{
OneToMany<ChildObject>(x => x.BagOfChildren)
.Mapping(m => m.OptimisticLock.All())
.ModelShouldMatch(x => x.OptimisticLock.ShouldEqual("all"));
}
[Test]
public void GenericShouldSetModelGenericToTrue()
{
OneToMany<ChildObject>(x => x.BagOfChildren)
.Mapping(m => m.Generic())
.ModelShouldMatch(x => x.Generic.ShouldBeTrue());
}
[Test]
public void NotGenericShouldSetModelGenericToFalse()
{
OneToMany<ChildObject>(x => x.BagOfChildren)
.Mapping(m => m.Not.Generic())
.ModelShouldMatch(x => x.Generic.ShouldBeFalse());
}
[Test]
public void ReadOnlyShouldSetModelMutableToFalse()
{
OneToMany<ChildObject>(x => x.BagOfChildren)
.Mapping(m => m.ReadOnly())
.ModelShouldMatch(x => x.Mutable.ShouldBeFalse());
}
[Test]
public void NotReadOnlyShouldSetModelMutableToTrue()
{
OneToMany<ChildObject>(x => x.BagOfChildren)
.Mapping(m => m.Not.ReadOnly())
.ModelShouldMatch(x => x.Mutable.ShouldBeTrue());
}
[Test]
public void SubselectShouldSetModelSubselectToValue()
{
OneToMany<ChildObject>(x => x.BagOfChildren)
.Mapping(m => m.Subselect("whee"))
.ModelShouldMatch(x => x.Subselect.ShouldEqual("whee"));
}
}
}
| 36.424107
| 116
| 0.551048
|
[
"BSD-3-Clause"
] |
jbogard/fluent-nhibernate
|
src/FluentNHibernate.Testing/FluentInterfaceTests/OneToManyMutablePropertyModelGenerationTests.cs
| 8,159
|
C#
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
namespace Tinylytics {
[Serializable]
public class AnalyticsTrigger {
// Properties for Lifecycle
[SerializeField]
public TriggerEvent triggerEvent;
//// Delegate for triggering when using properties
//internal delegate void OnTrigger();
//OnTrigger triggerFunction;
//[SerializeField]
//TriggerMethod m_Method;
}
[Serializable]
public enum TriggerEvent {
None = 0,
Awake,
Start,
OnEnable,
OnDisable,
OnDestroy,
CustomTriggerCall
}
}
| 17.735294
| 53
| 0.699834
|
[
"Unlicense"
] |
apetersell/NewThesisRepo
|
RockBand_Game25 copy/Assets/Tinylytics_AnalyticsTool/Backend/AnalyticsTrigger.cs
| 605
|
C#
|
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Text;
namespace MpesaSDK.NET.Dtos.Callbacks
{
public class B2BResult: BaseResult
{
[JsonProperty("ReferenceData")]
public B2BReferenceData ReferenceData { get; set; }
public override string ToString()
{
return JsonConvert.SerializeObject(this);
}
}
}
| 22.277778
| 59
| 0.665835
|
[
"Apache-2.0"
] |
davidmutia47/MpesaSDK.NET
|
MpesaSDK.NET/Dtos/Callbacks/B2BResult.cs
| 403
|
C#
|
// Copyright (C) 2014 dot42
//
// Original filename: Org.Apache.Http.Conn.Ssl.cs
//
// 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.
#pragma warning disable 1717
namespace Org.Apache.Http.Conn.Ssl
{
/// <summary>
/// <para>The Strict HostnameVerifier works the same way as Sun Java 1.4, Sun Java 5, Sun Java 6-rc. It's also pretty close to IE6. This implementation appears to be compliant with RFC 2818 for dealing with wildcards. </para><para>The hostname must match either the first CN, or any of the subject-alts. A wildcard can occur in the CN, and in any of the subject-alts. The one divergence from IE6 is how we only check the first CN. IE6 allows a match against any of the CNs present. We decided to follow in Sun Java 1.4's footsteps and only check the first CN. (If you need to check all the CN's, feel free to write your own implementation!). </para><para>A wildcard such as "*.foo.com" matches only subdomains in the same level, for example "a.foo.com". It does not match deeper subdomains such as "a.b.foo.com".</para><para><para>Julius Davies </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/conn/ssl/StrictHostnameVerifier
/// </java-name>
[Dot42.DexImport("org/apache/http/conn/ssl/StrictHostnameVerifier", AccessFlags = 33)]
public partial class StrictHostnameVerifier : global::Org.Apache.Http.Conn.Ssl.AbstractVerifier
/* scope: __dot42__ */
{
[Dot42.DexImport("<init>", "()V", AccessFlags = 1)]
public StrictHostnameVerifier() /* MethodBuilder.Create */
{
}
/// <java-name>
/// verify
/// </java-name>
[Dot42.DexImport("verify", "(Ljava/lang/String;[Ljava/lang/String;[Ljava/lang/String;)V", AccessFlags = 17)]
public override void Verify(string host, string[] cns, string[] subjectAlts) /* MethodBuilder.Create */
{
}
/// <java-name>
/// toString
/// </java-name>
[Dot42.DexImport("toString", "()Ljava/lang/String;", AccessFlags = 17)]
public override string ToString() /* MethodBuilder.Create */
{
return default(string);
}
}
/// <summary>
/// <para>Layered socket factory for TLS/SSL connections, based on JSSE. </para><para>SSLSocketFactory can be used to validate the identity of the HTTPS server against a list of trusted certificates and to authenticate to the HTTPS server using a private key. </para><para>SSLSocketFactory will enable server authentication when supplied with a truststore file containg one or several trusted certificates. The client secure socket will reject the connection during the SSL session handshake if the target HTTPS server attempts to authenticate itself with a non-trusted certificate. </para><para>Use JDK keytool utility to import a trusted certificate and generate a truststore file: <pre>
/// keytool -import -alias "my server cert" -file server.crt -keystore my.truststore
/// </pre> </para><para>SSLSocketFactory will enable client authentication when supplied with a keystore file containg a private key/public certificate pair. The client secure socket will use the private key to authenticate itself to the target HTTPS server during the SSL session handshake if requested to do so by the server. The target HTTPS server will in its turn verify the certificate presented by the client in order to establish client's authenticity </para><para>Use the following sequence of actions to generate a keystore file </para><para><ul><li><para></para><para>Use JDK keytool utility to generate a new key <pre>keytool -genkey -v -alias "my client key" -validity 365 -keystore my.keystore</pre> For simplicity use the same password for the key as that of the keystore </para><para></para></li><li><para></para><para>Issue a certificate signing request (CSR) <pre>keytool -certreq -alias "my client key" -file mycertreq.csr -keystore my.keystore</pre> </para><para></para></li><li><para></para><para>Send the certificate request to the trusted Certificate Authority for signature. One may choose to act as her own CA and sign the certificate request using a PKI tool, such as OpenSSL. </para><para></para></li><li><para></para><para>Import the trusted CA root certificate <pre>keytool -import -alias "my trusted ca" -file caroot.crt -keystore my.keystore</pre> </para><para></para></li><li><para></para><para>Import the PKCS#7 file containg the complete certificate chain <pre>keytool -import -alias "my client key" -file mycert.p7 -keystore my.keystore</pre> </para><para></para></li><li><para></para><para>Verify the content the resultant keystore file <pre>keytool -list -v -keystore my.keystore</pre> </para><para></para></li></ul><para> </para><simplesectsep></simplesectsep><para>Julius Davies </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/conn/ssl/SSLSocketFactory
/// </java-name>
[Dot42.DexImport("org/apache/http/conn/ssl/SSLSocketFactory", AccessFlags = 33)]
public partial class SSLSocketFactory : global::Org.Apache.Http.Conn.Scheme.ILayeredSocketFactory
/* scope: __dot42__ */
{
/// <java-name>
/// TLS
/// </java-name>
[Dot42.DexImport("TLS", "Ljava/lang/String;", AccessFlags = 25)]
public const string TLS = "TLS";
/// <java-name>
/// SSL
/// </java-name>
[Dot42.DexImport("SSL", "Ljava/lang/String;", AccessFlags = 25)]
public const string SSL = "SSL";
/// <java-name>
/// SSLV2
/// </java-name>
[Dot42.DexImport("SSLV2", "Ljava/lang/String;", AccessFlags = 25)]
public const string SSLV2 = "SSLv2";
/// <java-name>
/// ALLOW_ALL_HOSTNAME_VERIFIER
/// </java-name>
[Dot42.DexImport("ALLOW_ALL_HOSTNAME_VERIFIER", "Lorg/apache/http/conn/ssl/X509HostnameVerifier;", AccessFlags = 25)]
public static readonly global::Org.Apache.Http.Conn.Ssl.IX509HostnameVerifier ALLOW_ALL_HOSTNAME_VERIFIER;
/// <java-name>
/// BROWSER_COMPATIBLE_HOSTNAME_VERIFIER
/// </java-name>
[Dot42.DexImport("BROWSER_COMPATIBLE_HOSTNAME_VERIFIER", "Lorg/apache/http/conn/ssl/X509HostnameVerifier;", AccessFlags = 25)]
public static readonly global::Org.Apache.Http.Conn.Ssl.IX509HostnameVerifier BROWSER_COMPATIBLE_HOSTNAME_VERIFIER;
/// <java-name>
/// STRICT_HOSTNAME_VERIFIER
/// </java-name>
[Dot42.DexImport("STRICT_HOSTNAME_VERIFIER", "Lorg/apache/http/conn/ssl/X509HostnameVerifier;", AccessFlags = 25)]
public static readonly global::Org.Apache.Http.Conn.Ssl.IX509HostnameVerifier STRICT_HOSTNAME_VERIFIER;
[Dot42.DexImport("<init>", "(Ljava/lang/String;Ljava/security/KeyStore;Ljava/lang/String;Ljava/security/KeySt" +
"ore;Ljava/security/SecureRandom;Lorg/apache/http/conn/scheme/HostNameResolver;)V" +
"", AccessFlags = 1)]
public SSLSocketFactory(string algorithm, global::Java.Security.KeyStore keystore, string keystorePassword, global::Java.Security.KeyStore truststore, global::Java.Security.SecureRandom random, global::Org.Apache.Http.Conn.Scheme.IHostNameResolver nameResolver) /* MethodBuilder.Create */
{
}
[Dot42.DexImport("<init>", "(Ljava/security/KeyStore;Ljava/lang/String;Ljava/security/KeyStore;)V", AccessFlags = 1)]
public SSLSocketFactory(global::Java.Security.KeyStore keystore, string keystorePassword, global::Java.Security.KeyStore truststore) /* MethodBuilder.Create */
{
}
[Dot42.DexImport("<init>", "(Ljava/security/KeyStore;Ljava/lang/String;)V", AccessFlags = 1)]
public SSLSocketFactory(global::Java.Security.KeyStore keystore, string keystorePassword) /* MethodBuilder.Create */
{
}
[Dot42.DexImport("<init>", "(Ljava/security/KeyStore;)V", AccessFlags = 1)]
public SSLSocketFactory(global::Java.Security.KeyStore truststore) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Gets an singleton instance of the SSLProtocolSocketFactory. </para>
/// </summary>
/// <returns>
/// <para>a SSLProtocolSocketFactory </para>
/// </returns>
/// <java-name>
/// getSocketFactory
/// </java-name>
[Dot42.DexImport("getSocketFactory", "()Lorg/apache/http/conn/ssl/SSLSocketFactory;", AccessFlags = 9)]
public static global::Org.Apache.Http.Conn.Ssl.SSLSocketFactory GetSocketFactory() /* MethodBuilder.Create */
{
return default(global::Org.Apache.Http.Conn.Ssl.SSLSocketFactory);
}
/// <summary>
/// <para>Creates a new, unconnected socket. The socket should subsequently be passed to connectSocket.</para><para></para>
/// </summary>
/// <returns>
/// <para>a new socket</para>
/// </returns>
/// <java-name>
/// createSocket
/// </java-name>
[Dot42.DexImport("createSocket", "()Ljava/net/Socket;", AccessFlags = 1)]
public virtual global::Java.Net.Socket CreateSocket() /* MethodBuilder.Create */
{
return default(global::Java.Net.Socket);
}
/// <java-name>
/// connectSocket
/// </java-name>
[Dot42.DexImport("connectSocket", "(Ljava/net/Socket;Ljava/lang/String;ILjava/net/InetAddress;ILorg/apache/http/para" +
"ms/HttpParams;)Ljava/net/Socket;", AccessFlags = 1)]
public virtual global::Java.Net.Socket ConnectSocket(global::Java.Net.Socket sock, string host, int port, global::Java.Net.InetAddress localAddress, int localPort, global::Org.Apache.Http.Params.IHttpParams @params) /* MethodBuilder.Create */
{
return default(global::Java.Net.Socket);
}
/// <summary>
/// <para>Checks whether a socket connection is secure. This factory creates TLS/SSL socket connections which, by default, are considered secure. <br></br> Derived classes may override this method to perform runtime checks, for example based on the cypher suite.</para><para></para>
/// </summary>
/// <returns>
/// <para><code>true</code></para>
/// </returns>
/// <java-name>
/// isSecure
/// </java-name>
[Dot42.DexImport("isSecure", "(Ljava/net/Socket;)Z", AccessFlags = 1)]
public virtual bool IsSecure(global::Java.Net.Socket sock) /* MethodBuilder.Create */
{
return default(bool);
}
/// <java-name>
/// createSocket
/// </java-name>
[Dot42.DexImport("createSocket", "(Ljava/net/Socket;Ljava/lang/String;IZ)Ljava/net/Socket;", AccessFlags = 1)]
public virtual global::Java.Net.Socket CreateSocket(global::Java.Net.Socket socket, string host, int port, bool autoClose) /* MethodBuilder.Create */
{
return default(global::Java.Net.Socket);
}
/// <java-name>
/// setHostnameVerifier
/// </java-name>
[Dot42.DexImport("setHostnameVerifier", "(Lorg/apache/http/conn/ssl/X509HostnameVerifier;)V", AccessFlags = 1)]
public virtual void SetHostnameVerifier(global::Org.Apache.Http.Conn.Ssl.IX509HostnameVerifier hostnameVerifier) /* MethodBuilder.Create */
{
}
/// <java-name>
/// getHostnameVerifier
/// </java-name>
[Dot42.DexImport("getHostnameVerifier", "()Lorg/apache/http/conn/ssl/X509HostnameVerifier;", AccessFlags = 1)]
public virtual global::Org.Apache.Http.Conn.Ssl.IX509HostnameVerifier GetHostnameVerifier() /* MethodBuilder.Create */
{
return default(global::Org.Apache.Http.Conn.Ssl.IX509HostnameVerifier);
}
[global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)]
internal SSLSocketFactory() /* TypeBuilder.AddDefaultConstructor */
{
}
/// <summary>
/// <para>Gets an singleton instance of the SSLProtocolSocketFactory. </para>
/// </summary>
/// <returns>
/// <para>a SSLProtocolSocketFactory </para>
/// </returns>
/// <java-name>
/// getSocketFactory
/// </java-name>
public static global::Org.Apache.Http.Conn.Ssl.SSLSocketFactory SocketFactory
{
[Dot42.DexImport("getSocketFactory", "()Lorg/apache/http/conn/ssl/SSLSocketFactory;", AccessFlags = 9)]
get{ return GetSocketFactory(); }
}
/// <java-name>
/// getHostnameVerifier
/// </java-name>
public global::Org.Apache.Http.Conn.Ssl.IX509HostnameVerifier HostnameVerifier
{
[Dot42.DexImport("getHostnameVerifier", "()Lorg/apache/http/conn/ssl/X509HostnameVerifier;", AccessFlags = 1)]
get{ return GetHostnameVerifier(); }
[Dot42.DexImport("setHostnameVerifier", "(Lorg/apache/http/conn/ssl/X509HostnameVerifier;)V", AccessFlags = 1)]
set{ SetHostnameVerifier(value); }
}
}
/// <summary>
/// <para>The HostnameVerifier that works the same way as Curl and Firefox. </para><para>The hostname must match either the first CN, or any of the subject-alts. A wildcard can occur in the CN, and in any of the subject-alts. </para><para>The only difference between BROWSER_COMPATIBLE and STRICT is that a wildcard (such as "*.foo.com") with BROWSER_COMPATIBLE matches all subdomains, including "a.b.foo.com".</para><para><para>Julius Davies </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/conn/ssl/BrowserCompatHostnameVerifier
/// </java-name>
[Dot42.DexImport("org/apache/http/conn/ssl/BrowserCompatHostnameVerifier", AccessFlags = 33)]
public partial class BrowserCompatHostnameVerifier : global::Org.Apache.Http.Conn.Ssl.AbstractVerifier
/* scope: __dot42__ */
{
[Dot42.DexImport("<init>", "()V", AccessFlags = 1)]
public BrowserCompatHostnameVerifier() /* MethodBuilder.Create */
{
}
/// <java-name>
/// verify
/// </java-name>
[Dot42.DexImport("verify", "(Ljava/lang/String;[Ljava/lang/String;[Ljava/lang/String;)V", AccessFlags = 17)]
public override void Verify(string host, string[] cns, string[] subjectAlts) /* MethodBuilder.Create */
{
}
/// <java-name>
/// toString
/// </java-name>
[Dot42.DexImport("toString", "()Ljava/lang/String;", AccessFlags = 17)]
public override string ToString() /* MethodBuilder.Create */
{
return default(string);
}
}
/// <summary>
/// <para>The ALLOW_ALL HostnameVerifier essentially turns hostname verification off. This implementation is a no-op, and never throws the SSLException.</para><para><para>Julius Davies </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/conn/ssl/AllowAllHostnameVerifier
/// </java-name>
[Dot42.DexImport("org/apache/http/conn/ssl/AllowAllHostnameVerifier", AccessFlags = 33)]
public partial class AllowAllHostnameVerifier : global::Org.Apache.Http.Conn.Ssl.AbstractVerifier
/* scope: __dot42__ */
{
[Dot42.DexImport("<init>", "()V", AccessFlags = 1)]
public AllowAllHostnameVerifier() /* MethodBuilder.Create */
{
}
/// <java-name>
/// verify
/// </java-name>
[Dot42.DexImport("verify", "(Ljava/lang/String;[Ljava/lang/String;[Ljava/lang/String;)V", AccessFlags = 17)]
public override void Verify(string host, string[] cns, string[] subjectAlts) /* MethodBuilder.Create */
{
}
/// <java-name>
/// toString
/// </java-name>
[Dot42.DexImport("toString", "()Ljava/lang/String;", AccessFlags = 17)]
public override string ToString() /* MethodBuilder.Create */
{
return default(string);
}
}
/// <summary>
/// <para>Interface for checking if a hostname matches the names stored inside the server's X.509 certificate. Implements javax.net.ssl.HostnameVerifier, but we don't actually use that interface. Instead we added some methods that take String parameters (instead of javax.net.ssl.HostnameVerifier's SSLSession). JUnit is a lot easier this way! :-) </para><para>We provide the HostnameVerifier.DEFAULT, HostnameVerifier.STRICT, and HostnameVerifier.ALLOW_ALL implementations. But feel free to define your own implementation! </para><para>Inspired by Sebastian Hauer's original StrictSSLProtocolSocketFactory in the HttpClient "contrib" repository.</para><para><para>Julius Davies </para><simplesectsep></simplesectsep><para></para><para>4.0 (8-Dec-2006) </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/conn/ssl/X509HostnameVerifier
/// </java-name>
[Dot42.DexImport("org/apache/http/conn/ssl/X509HostnameVerifier", AccessFlags = 1537)]
public partial interface IX509HostnameVerifier : global::Javax.Net.Ssl.IHostnameVerifier
/* scope: __dot42__ */
{
/// <java-name>
/// verify
/// </java-name>
[Dot42.DexImport("verify", "(Ljava/lang/String;Ljavax/net/ssl/SSLSession;)Z", AccessFlags = 1025)]
bool Verify(string @string, global::Javax.Net.Ssl.ISSLSession sSLSession) /* MethodBuilder.Create */ ;
/// <java-name>
/// verify
/// </java-name>
[Dot42.DexImport("verify", "(Ljava/lang/String;Ljavax/net/ssl/SSLSocket;)V", AccessFlags = 1025)]
void Verify(string @string, global::Javax.Net.Ssl.SSLSocket sSLSocket) /* MethodBuilder.Create */ ;
/// <java-name>
/// verify
/// </java-name>
[Dot42.DexImport("verify", "(Ljava/lang/String;Ljava/security/cert/X509Certificate;)V", AccessFlags = 1025)]
void Verify(string @string, global::Java.Security.Cert.X509Certificate x509Certificate) /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Checks to see if the supplied hostname matches any of the supplied CNs or "DNS" Subject-Alts. Most implementations only look at the first CN, and ignore any additional CNs. Most implementations do look at all of the "DNS" Subject-Alts. The CNs or Subject-Alts may contain wildcards according to RFC 2818.</para><para></para>
/// </summary>
/// <java-name>
/// verify
/// </java-name>
[Dot42.DexImport("verify", "(Ljava/lang/String;[Ljava/lang/String;[Ljava/lang/String;)V", AccessFlags = 1025)]
void Verify(string host, string[] cns, string[] subjectAlts) /* MethodBuilder.Create */ ;
}
/// <summary>
/// <para>Abstract base class for all standard X509HostnameVerifier implementations.</para><para><para>Julius Davies </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/conn/ssl/AbstractVerifier
/// </java-name>
[Dot42.DexImport("org/apache/http/conn/ssl/AbstractVerifier", AccessFlags = 1057)]
public abstract partial class AbstractVerifier : global::Org.Apache.Http.Conn.Ssl.IX509HostnameVerifier
/* scope: __dot42__ */
{
[Dot42.DexImport("<init>", "()V", AccessFlags = 1)]
public AbstractVerifier() /* MethodBuilder.Create */
{
}
/// <java-name>
/// verify
/// </java-name>
[Dot42.DexImport("verify", "(Ljava/lang/String;Ljavax/net/ssl/SSLSocket;)V", AccessFlags = 17)]
public void Verify(string @string, global::Javax.Net.Ssl.SSLSocket sSLSocket) /* MethodBuilder.Create */
{
}
/// <java-name>
/// verify
/// </java-name>
[Dot42.DexImport("verify", "(Ljava/lang/String;Ljavax/net/ssl/SSLSession;)Z", AccessFlags = 17)]
public bool Verify(string @string, global::Javax.Net.Ssl.ISSLSession sSLSession) /* MethodBuilder.Create */
{
return default(bool);
}
/// <java-name>
/// verify
/// </java-name>
[Dot42.DexImport("verify", "(Ljava/lang/String;Ljava/security/cert/X509Certificate;)V", AccessFlags = 17)]
public void Verify(string @string, global::Java.Security.Cert.X509Certificate x509Certificate) /* MethodBuilder.Create */
{
}
/// <java-name>
/// verify
/// </java-name>
[Dot42.DexImport("verify", "(Ljava/lang/String;[Ljava/lang/String;[Ljava/lang/String;Z)V", AccessFlags = 17)]
public void Verify(string host, string[] cns, string[] subjectAlts, bool strictWithSubDomains) /* MethodBuilder.Create */
{
}
/// <java-name>
/// acceptableCountryWildcard
/// </java-name>
[Dot42.DexImport("acceptableCountryWildcard", "(Ljava/lang/String;)Z", AccessFlags = 9)]
public static bool AcceptableCountryWildcard(string cn) /* MethodBuilder.Create */
{
return default(bool);
}
/// <java-name>
/// getCNs
/// </java-name>
[Dot42.DexImport("getCNs", "(Ljava/security/cert/X509Certificate;)[Ljava/lang/String;", AccessFlags = 9)]
public static string[] GetCNs(global::Java.Security.Cert.X509Certificate cert) /* MethodBuilder.Create */
{
return default(string[]);
}
/// <summary>
/// <para>Extracts the array of SubjectAlt DNS names from an X509Certificate. Returns null if there aren't any. </para><para>Note: Java doesn't appear able to extract international characters from the SubjectAlts. It can only extract international characters from the CN field. </para><para>(Or maybe the version of OpenSSL I'm using to test isn't storing the international characters correctly in the SubjectAlts?).</para><para></para>
/// </summary>
/// <returns>
/// <para>Array of SubjectALT DNS names stored in the certificate. </para>
/// </returns>
/// <java-name>
/// getDNSSubjectAlts
/// </java-name>
[Dot42.DexImport("getDNSSubjectAlts", "(Ljava/security/cert/X509Certificate;)[Ljava/lang/String;", AccessFlags = 9)]
public static string[] GetDNSSubjectAlts(global::Java.Security.Cert.X509Certificate cert) /* MethodBuilder.Create */
{
return default(string[]);
}
/// <summary>
/// <para>Counts the number of dots "." in a string. </para>
/// </summary>
/// <returns>
/// <para>number of dots </para>
/// </returns>
/// <java-name>
/// countDots
/// </java-name>
[Dot42.DexImport("countDots", "(Ljava/lang/String;)I", AccessFlags = 9)]
public static int CountDots(string s) /* MethodBuilder.Create */
{
return default(int);
}
[Dot42.DexImport("org/apache/http/conn/ssl/X509HostnameVerifier", "verify", "(Ljava/lang/String;[Ljava/lang/String;[Ljava/lang/String;)V", AccessFlags = 1025)]
public virtual void Verify(string host, string[] cns, string[] subjectAlts) /* TypeBuilder.AddAbstractInterfaceMethods */
{
}
}
}
| 50.369369
| 1,844
| 0.686773
|
[
"Apache-2.0"
] |
Dot42Xna/master
|
Generated/v4.0.3/Org.Apache.Http.Conn.Ssl.cs
| 22,364
|
C#
|
//---------------------------------------------------------------------
// <copyright file="FacetDescriptionElement.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//
// @owner [....]
// @backupOwner [....]
//---------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Text;
using System.Data.Metadata.Edm;
using System.Xml;
using System.Diagnostics;
namespace System.Data.EntityModel.SchemaObjectModel
{
internal abstract class FacetDescriptionElement : SchemaElement
{
int? _minValue;
int? _maxValue;
object _defaultValue;
bool _isConstant;
// won't be populated till you call CreateAndValidate
FacetDescription _facetDescription;
public FacetDescriptionElement(TypeElement type, string name)
: base(type, name)
{
}
protected override bool ProhibitAttribute(string namespaceUri, string localName)
{
if (base.ProhibitAttribute(namespaceUri, localName))
{
return true;
}
if (namespaceUri == null && localName == XmlConstants.Name)
{
return false;
}
return false;
}
protected override bool HandleAttribute(XmlReader reader)
{
if (base.HandleAttribute(reader))
{
return true;
}
else if (CanHandleAttribute(reader, XmlConstants.MinimumAttribute))
{
HandleMinimumAttribute(reader);
return true;
}
else if (CanHandleAttribute(reader, XmlConstants.MaximumAttribute))
{
HandleMaximumAttribute(reader);
return true;
}
else if (CanHandleAttribute(reader, XmlConstants.DefaultValueAttribute))
{
HandleDefaultAttribute(reader);
return true;
}
else if (CanHandleAttribute(reader, XmlConstants.ConstantAttribute))
{
HandleConstantAttribute(reader);
return true;
}
return false;
}
/////////////////////////////////////////////////////////////////////
// Attribute Handlers
/// <summary>
/// Handler for the Minimum attribute
/// </summary>
/// <param name="reader">xml reader currently positioned at Minimum attribute</param>
protected void HandleMinimumAttribute(XmlReader reader)
{
int value = -1;
if (HandleIntAttribute(reader, ref value))
{
_minValue = value;
}
}
/// <summary>
/// Handler for the Maximum attribute
/// </summary>
/// <param name="reader">xml reader currently positioned at Maximum attribute</param>
protected void HandleMaximumAttribute(XmlReader reader)
{
int value = -1;
if (HandleIntAttribute(reader, ref value))
{
_maxValue = value;
}
}
/// <summary>
/// Handler for the Default attribute
/// </summary>
/// <param name="reader">xml reader currently positioned at Default attribute</param>
protected abstract void HandleDefaultAttribute(XmlReader reader);
/// <summary>
/// Handler for the Constant attribute
/// </summary>
/// <param name="reader">xml reader currently positioned at Constant attribute</param>
protected void HandleConstantAttribute(XmlReader reader)
{
bool value = false;
if (HandleBoolAttribute(reader, ref value))
{
_isConstant = value;
}
}
public abstract EdmType FacetType{ get; }
public int? MinValue
{
get { return _minValue; }
}
public int? MaxValue
{
get { return _maxValue; }
}
public object DefaultValue
{
get { return _defaultValue; }
set { _defaultValue = value; }
}
public FacetDescription FacetDescription
{
get
{
Debug.Assert(_facetDescription != null, "Did you forget to call CreateAndValidate first?");
return _facetDescription;
}
}
internal void CreateAndValidateFacetDescription(string declaringTypeName)
{
_facetDescription = new FacetDescription(Name, FacetType, MinValue, MaxValue, DefaultValue, _isConstant, declaringTypeName);
}
}
}
| 30.389937
| 136
| 0.527525
|
[
"Apache-2.0"
] |
295007712/295007712.github.io
|
sourceCode/dotNet4.6/ndp/fx/src/DataEntity/System/Data/EntityModel/SchemaObjectModel/FacetDescriptionElement.cs
| 4,832
|
C#
|
using Hoteles.Modelos;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Hoteles.BL
{
public class ClientesBL
{
public List<Cliente> ListaDeClientes { get; set; }
public ClientesBL()
{
ListaDeClientes = new List<Cliente>();
CrearDatosDePrueba();
}
private void CrearDatosDePrueba()
{
//llenar id nobre telefono
var clienteDatosHistorial = new DatosDelCliente(1, "Clientes"); // CREAR CLASE-->
var cliente1 = new Cliente(1, "Pedro", 89941908, clienteDatosHistorial);
var cliente2 = new Cliente(2, "Juan", 95689900, clienteDatosHistorial);
var cliente3 = new Cliente(3, "Jessica", 89128921, clienteDatosHistorial);
ListaDeClientes.Add(cliente1);
ListaDeClientes.Add(cliente2);
ListaDeClientes.Add(cliente3);
}
}
}
| 20.770833
| 93
| 0.613842
|
[
"MIT"
] |
yosephf02f/hotel
|
Hoteles/Hoteles/BL/ClientesBL.cs
| 999
|
C#
|
using Pims.Dal;
using Entity = Pims.Dal.Entities;
namespace Pims.Core.Test
{
/// <summary>
/// EntityHelper static class, provides helper methods to create test entities.
/// </summary>
public static partial class EntityHelper
{
/// <summary>
/// Create a new instance of an Person.
/// </summary>
/// <param name="id"></param>
/// <param name="surname"></param>
/// <param name="firstName"></param>
/// <param name="address"></param>
/// <returns></returns>
public static Entity.PimsPerson CreatePerson(long id, string surname, string firstName, Entity.PimsAddress address = null)
{
return new Entity.PimsPerson(surname, firstName, address ?? EntityHelper.CreateAddress(id))
{
PersonId = id,
AppCreateUserDirectory = "",
AppCreateUserid = "",
AppLastUpdateUserDirectory = "",
AppLastUpdateUserid = "",
DbCreateUserid = "",
DbLastUpdateUserid = "",
IsDisabled = false,
ConcurrencyControlNumber = 1
};
}
/// <summary>
/// Create a new instance of an Person.
/// </summary>
/// <param name="id"></param>
/// <param name="surname"></param>
/// <param name="firstName"></param>
/// <param name="address"></param>
/// <returns></returns>
public static Entity.PimsPerson CreatePerson(this PimsContext context, long id, string surname, string firstName, Entity.PimsAddress address = null)
{
address ??= EntityHelper.CreateAddress(context, id, "1234 St");
return new Entity.PimsPerson(surname, firstName, address)
{
PersonId = id,
ConcurrencyControlNumber = 1,
AppCreateUserDirectory = "",
AppCreateUserid = "",
AppLastUpdateUserDirectory = "",
AppLastUpdateUserid = "",
DbCreateUserid = "",
DbLastUpdateUserid = "",
IsDisabled = false
};
}
}
}
| 35.677419
| 156
| 0.529385
|
[
"Apache-2.0"
] |
FuriousLlama/PSP
|
backend/tests/core/Entities/PersonHelper.cs
| 2,212
|
C#
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
namespace Microsoft.Extensions.Hosting.Internal
{
internal class Host : IHost, IAsyncDisposable
{
private readonly ILogger<Host> _logger;
private readonly IHostLifetime _hostLifetime;
private readonly ApplicationLifetime _applicationLifetime;
private readonly HostOptions _options;
private IEnumerable<IHostedService> _hostedServices;
public Host(IServiceProvider services, IHostApplicationLifetime applicationLifetime, ILogger<Host> logger,
IHostLifetime hostLifetime, IOptions<HostOptions> options)
{
Services = services ?? throw new ArgumentNullException(nameof(services));
_applicationLifetime = (applicationLifetime ?? throw new ArgumentNullException(nameof(applicationLifetime))) as ApplicationLifetime;
if (_applicationLifetime is null)
{
throw new ArgumentException("Replacing IHostApplicationLifetime is not supported.", nameof(applicationLifetime));
}
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
_hostLifetime = hostLifetime ?? throw new ArgumentNullException(nameof(hostLifetime));
_options = options?.Value ?? throw new ArgumentNullException(nameof(options));
}
public IServiceProvider Services { get; }
public async Task StartAsync(CancellationToken cancellationToken = default)
{
_logger.Starting();
using var combinedCancellationTokenSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, _applicationLifetime.ApplicationStopping);
var combinedCancellationToken = combinedCancellationTokenSource.Token;
await _hostLifetime.WaitForStartAsync(combinedCancellationToken);
combinedCancellationToken.ThrowIfCancellationRequested();
_hostedServices = Services.GetService<IEnumerable<IHostedService>>();
foreach (var hostedService in _hostedServices)
{
// Fire IHostedService.Start
await hostedService.StartAsync(combinedCancellationToken).ConfigureAwait(false);
}
// Fire IHostApplicationLifetime.Started
_applicationLifetime.NotifyStarted();
_logger.Started();
}
public async Task StopAsync(CancellationToken cancellationToken = default)
{
_logger.Stopping();
using (var cts = new CancellationTokenSource(_options.ShutdownTimeout))
using (var linkedCts = CancellationTokenSource.CreateLinkedTokenSource(cts.Token, cancellationToken))
{
var token = linkedCts.Token;
// Trigger IHostApplicationLifetime.ApplicationStopping
_applicationLifetime.StopApplication();
IList<Exception> exceptions = new List<Exception>();
if (_hostedServices != null) // Started?
{
foreach (var hostedService in _hostedServices.Reverse())
{
token.ThrowIfCancellationRequested();
try
{
await hostedService.StopAsync(token).ConfigureAwait(false);
}
catch (Exception ex)
{
exceptions.Add(ex);
}
}
}
token.ThrowIfCancellationRequested();
await _hostLifetime.StopAsync(token);
// Fire IHostApplicationLifetime.Stopped
_applicationLifetime.NotifyStopped();
if (exceptions.Count > 0)
{
var ex = new AggregateException("One or more hosted services failed to stop.", exceptions);
_logger.StoppedWithException(ex);
throw ex;
}
}
_logger.Stopped();
}
public void Dispose() => DisposeAsync().GetAwaiter().GetResult();
public async ValueTask DisposeAsync()
{
switch (Services)
{
case IAsyncDisposable asyncDisposable:
await asyncDisposable.DisposeAsync();
break;
case IDisposable disposable:
disposable.Dispose();
break;
}
}
}
}
| 39.704
| 165
| 0.612936
|
[
"MIT"
] |
ARhj/runtime
|
src/libraries/Microsoft.Extensions.Hosting/src/Internal/Host.cs
| 4,963
|
C#
|
using ISAAR.MSolve.LinearAlgebra.Commons;
using ISAAR.MSolve.LinearAlgebra.Matrices;
using ISAAR.MSolve.LinearAlgebra.Tests.TestData;
using ISAAR.MSolve.LinearAlgebra.Tests.Utilities;
using ISAAR.MSolve.LinearAlgebra.Vectors;
using Xunit;
namespace ISAAR.MSolve.LinearAlgebra.Tests.Matrices
{
/// <summary>
/// Tests for <see cref="CscMatrix"/>.
/// Authors: Serafeim Bakalakos
/// </summary>
public static class CscMatrixTests
{
private static readonly MatrixComparer comparer = new MatrixComparer(1E-13);
[Fact]
private static void TestClear()
{
var zero = Matrix.CreateZero(SparseRectangular10by5.NumRows, SparseRectangular10by5.NumCols);
var csc = CscMatrix.CreateFromArrays(SparseRectangular10by5.NumRows, SparseRectangular10by5.NumCols,
SparseRectangular10by5.CscValues, SparseRectangular10by5.CscRowIndices, SparseRectangular10by5.CscColOffsets,
true);
csc.Clear();
comparer.AssertEqual(zero, csc);
}
[Fact]
private static void TestEquality()
{
var full = Matrix.CreateFromArray(SparseRectangular10by5.Matrix);
var csc = CscMatrix.CreateFromArrays(SparseRectangular10by5.NumRows, SparseRectangular10by5.NumCols,
SparseRectangular10by5.CscValues, SparseRectangular10by5.CscRowIndices, SparseRectangular10by5.CscColOffsets,
true);
Assert.True(csc.Equals(full));
}
[Fact]
private static void TestGetColumn()
{
var matrix = CscMatrix.CreateFromArrays(SparseRectangular10by5.NumRows, SparseRectangular10by5.NumCols,
SparseRectangular10by5.CscValues, SparseRectangular10by5.CscRowIndices, SparseRectangular10by5.CscColOffsets,
true);
for (int j = 0; j < SparseRectangular10by5.NumCols; ++j)
{
Vector colExpected = DenseStrategies.GetColumn(matrix, j);
Vector colComputed = matrix.GetColumn(j);
comparer.AssertEqual(colExpected, colComputed);
}
}
[Fact]
private static void TestGetRow()
{
var matrix = CscMatrix.CreateFromArrays(SparseRectangular10by5.NumRows, SparseRectangular10by5.NumCols,
SparseRectangular10by5.CscValues, SparseRectangular10by5.CscRowIndices, SparseRectangular10by5.CscColOffsets,
true);
for (int i = 0; i < SparseRectangular10by5.NumRows; ++i)
{
Vector rowExpected = DenseStrategies.GetRow(matrix, i);
Vector rowComputed = matrix.GetRow(i);
comparer.AssertEqual(rowExpected, rowComputed);
}
}
[Fact]
private static void TestMatrixCopy()
{
var full = Matrix.CreateFromArray(SparseRectangular10by5.Matrix);
var csc = CscMatrix.CreateFromArrays(SparseRectangular10by5.NumRows, SparseRectangular10by5.NumCols,
SparseRectangular10by5.CscValues, SparseRectangular10by5.CscRowIndices, SparseRectangular10by5.CscColOffsets,
true);
comparer.AssertEqual(full, csc.CopyToFullMatrix());
}
[Theory]
[MemberData(nameof(TestSettings.ProvidersToTest), MemberType = typeof(TestSettings))]
private static void TestMatrixMatrixMultiplication(LinearAlgebraProviderChoice providers)
{
TestSettings.RunMultiproviderTest(providers, delegate ()
{
var matrix5x5 = Matrix.CreateFromArray(SquareInvertible10by10.Matrix).GetSubmatrix(0, 5, 0, 5); //TODO: add a 5x5 matrix and its products
var matrix10x10 = Matrix.CreateFromArray(SquareInvertible10by10.Matrix);
var ATimesMatrix5x5 = Matrix.CreateFromArray(
MatrixOperations.MatrixTimesMatrix(SparseRectangular10by5.Matrix, matrix5x5.CopyToArray2D()));
var ATimesTransposeMatrix5x5 = Matrix.CreateFromArray(
MatrixOperations.MatrixTimesMatrix(SparseRectangular10by5.Matrix, matrix5x5.Transpose().CopyToArray2D()));
var transposeATimesMatrix10x10 = Matrix.CreateFromArray(MatrixOperations.MatrixTimesMatrix(
MatrixOperations.Transpose(SparseRectangular10by5.Matrix), matrix10x10.CopyToArray2D()));
var transposeATimesTransposeMatrix10x10 = Matrix.CreateFromArray(MatrixOperations.MatrixTimesMatrix(
MatrixOperations.Transpose(SparseRectangular10by5.Matrix), matrix10x10.Transpose().CopyToArray2D()));
var matrix10x10TimesA = Matrix.CreateFromArray(
MatrixOperations.MatrixTimesMatrix(matrix10x10.CopyToArray2D(), SparseRectangular10by5.Matrix));
var transposeMatrix10x10TimesA = Matrix.CreateFromArray(
MatrixOperations.MatrixTimesMatrix(matrix10x10.Transpose().CopyToArray2D(), SparseRectangular10by5.Matrix));
var matrix5x5TimesTransposeA = Matrix.CreateFromArray(
MatrixOperations.MatrixTimesMatrix(matrix5x5.CopyToArray2D(),
MatrixOperations.Transpose(SparseRectangular10by5.Matrix)));
var transposeMatrix5x5TimesTransposeA = Matrix.CreateFromArray(
MatrixOperations.MatrixTimesMatrix(matrix5x5.Transpose().CopyToArray2D(),
MatrixOperations.Transpose(SparseRectangular10by5.Matrix)));
var A = CscMatrix.CreateFromArrays(SparseRectangular10by5.NumRows, SparseRectangular10by5.NumCols,
SparseRectangular10by5.CscValues, SparseRectangular10by5.CscRowIndices, SparseRectangular10by5.CscColOffsets,
true);
// MultiplyRight()
comparer.AssertEqual(ATimesMatrix5x5, A.MultiplyRight(matrix5x5, false, false));
comparer.AssertEqual(ATimesTransposeMatrix5x5, A.MultiplyRight(matrix5x5, false, true));
comparer.AssertEqual(transposeATimesMatrix10x10, A.MultiplyRight(matrix10x10, true, false));
comparer.AssertEqual(transposeATimesTransposeMatrix10x10, A.MultiplyRight(matrix10x10, true, true));
// MultiplyLeft()
comparer.AssertEqual(matrix10x10TimesA, A.MultiplyLeft(matrix10x10, false, false));
comparer.AssertEqual(transposeMatrix10x10TimesA, A.MultiplyLeft(matrix10x10, false, true));
comparer.AssertEqual(matrix5x5TimesTransposeA, A.MultiplyLeft(matrix5x5, true, false));
comparer.AssertEqual(transposeMatrix5x5TimesTransposeA, A.MultiplyLeft(matrix5x5, true, true));
});
}
[Theory]
[MemberData(nameof(TestSettings.ProvidersToTest), MemberType = typeof(TestSettings))]
private static void TestMatrixVectorMultiplication(LinearAlgebraProviderChoice providers)
{
TestSettings.RunMultiproviderTest(providers, delegate ()
{
// MultiplyRight() - untransposed
var A = CscMatrix.CreateFromArrays(SparseRectangular10by5.NumRows, SparseRectangular10by5.NumCols,
SparseRectangular10by5.CscValues, SparseRectangular10by5.CscRowIndices, SparseRectangular10by5.CscColOffsets,
true);
var x5 = Vector.CreateFromArray(SparseRectangular10by5.Lhs5);
var b10Expected = Vector.CreateFromArray(SparseRectangular10by5.Rhs10);
Vector b10Computed = A.Multiply(x5, false);
comparer.AssertEqual(b10Expected, b10Computed);
// MultiplyRight() - transposed
var x10 = Vector.CreateFromArray(SparseRectangular10by5.Lhs10);
var b5Expected = Vector.CreateFromArray(SparseRectangular10by5.Rhs5);
Vector b5Computed = A.Multiply(x10, true);
comparer.AssertEqual(b5Expected, b5Computed);
});
}
[Theory]
[MemberData(nameof(TestSettings.ProvidersToTest), MemberType = typeof(TestSettings))]
private static void TestMatrixVectorMultiplicationIntoResult(LinearAlgebraProviderChoice providers)
{
TestSettings.RunMultiproviderTest(providers, delegate ()
{
// The result vectors will first be set to some non zero values to make sure that the result overwrites
// them instead of being added to them.
// MultiplyIntoResult() - untransposed
var A = CscMatrix.CreateFromArrays(SparseRectangular10by5.NumRows, SparseRectangular10by5.NumCols,
SparseRectangular10by5.CscValues, SparseRectangular10by5.CscRowIndices, SparseRectangular10by5.CscColOffsets,
true);
var x5 = Vector.CreateFromArray(SparseRectangular10by5.Lhs5);
var b10Expected = Vector.CreateFromArray(SparseRectangular10by5.Rhs10);
Vector b10Computed = Vector.CreateWithValue(SparseRectangular10by5.NumRows, 1.0);
//Vector bComputed = Vector.CreateZero(SparseRectangular10by5.NumRows);
A.MultiplyIntoResult(x5, b10Computed, false);
comparer.AssertEqual(b10Expected, b10Computed);
// MultiplyIntoResult() - transposed
var x10 = Vector.CreateFromArray(SparseRectangular10by5.Lhs10);
var b5Expected = Vector.CreateFromArray(SparseRectangular10by5.Rhs5);
Vector b5Computed = Vector.CreateWithValue(SparseRectangular10by5.NumCols, 1.0);
A.MultiplyIntoResult(x10, b5Computed, true);
comparer.AssertEqual(b5Expected, b5Computed);
});
}
[Fact] //TODO: If the explicit transposition becomes abstracted behind a provider, then this should also be a Theory
private static void TestTransposition()
{
var matrix = CscMatrix.CreateFromArrays(SparseRectangular10by5.NumRows, SparseRectangular10by5.NumCols,
SparseRectangular10by5.CscValues, SparseRectangular10by5.CscRowIndices, SparseRectangular10by5.CscColOffsets,
true);
var transposeExpected = Matrix.CreateFromArray(MatrixOperations.Transpose(SparseRectangular10by5.Matrix));
// TransposeToCSC()
CscMatrix transposeCsc = matrix.TransposeToCSC();
comparer.AssertEqual(transposeExpected, transposeCsc);
// TransposeToCSR()
CsrMatrix transposeCsr = matrix.TransposeToCSR(true);
comparer.AssertEqual(transposeExpected, transposeCsr);
}
}
}
| 55.71875
| 153
| 0.670312
|
[
"Apache-2.0"
] |
TheoChristo/MSolve.Bio
|
ISAAR.MSolve.LinearAlgebra.Tests/Matrices/CscMatrixTests.cs
| 10,700
|
C#
|
namespace SyncTrayzor.Pages.BarAlerts
{
public interface IBarAlert
{
AlertSeverity Severity { get; }
}
}
| 16.625
| 40
| 0.616541
|
[
"MIT"
] |
Bararie/SyncTrayzor
|
src/SyncTrayzor/Pages/BarAlerts/IBarAlert.cs
| 128
|
C#
|
using System;
using System.Xml.Serialization;
using System.ComponentModel.DataAnnotations;
using BroadWorksConnector.Ocip.Validation;
using System.Collections.Generic;
namespace BroadWorksConnector.Ocip.Models
{
/// <summary>
/// Request to get a sip device type.
/// See Also: SystemDeviceTypeGetRequest
/// The response is either SystemSIPDeviceTypeGetResponse23V7 or ErrorResponse.
///
/// Replaced by SystemSIPDeviceTypeGetResquest23V8
/// <see cref="SystemDeviceTypeGetRequest"/>
/// <see cref="SystemSIPDeviceTypeGetResponse23V7"/>
/// <see cref="ErrorResponse"/>
/// </summary>
[Serializable]
[XmlRoot(Namespace = "")]
[Groups(@"[{""__type"":""Sequence:#BroadWorksConnector.Ocip.Validation"",""id"":""de4d76f01f337fe4694212ec9f771753:10395""}]")]
public class SystemSIPDeviceTypeGetRequest23V7 : BroadWorksConnector.Ocip.Models.C.OCIRequest
{
private string _deviceType;
[XmlElement(ElementName = "deviceType", IsNullable = false, Namespace = "")]
[Group(@"de4d76f01f337fe4694212ec9f771753:10395")]
[MinLength(1)]
[MaxLength(40)]
public string DeviceType
{
get => _deviceType;
set
{
DeviceTypeSpecified = true;
_deviceType = value;
}
}
[XmlIgnore]
protected bool DeviceTypeSpecified { get; set; }
}
}
| 30.617021
| 131
| 0.648367
|
[
"MIT"
] |
Rogn/broadworks-connector-net
|
BroadworksConnector/Ocip/Models/SystemSIPDeviceTypeGetRequest23V7.cs
| 1,439
|
C#
|
using System;
using System.ComponentModel.DataAnnotations.Schema;
using Yuebon.Commons.Models;
namespace Yuebon.DataProcess.Models
{
/// <summary>
/// 使用插件的配置信息
/// </summary>
[Table("dp_plug_confdetail")]
[Serializable]
public class Plug_ConfDetail : BaseEntity<string>
{
/// <summary>
/// 设置或获取主项ID
/// </summary>
public string Obj_Id { get; set; }
/// <summary>
/// 设置或获取配置类型
/// </summary>
public int? ConfType { get; set; }
/// <summary>
/// 设置或获取配置字符串
/// </summary>
public string ConfJson { get; set; }
}
}
| 22.166667
| 54
| 0.535338
|
[
"MIT"
] |
JonasChan2020/DataProcess
|
Yuebon.DataProcess.Core/Models/Plug_ConfDetail.cs
| 735
|
C#
|
using Fumbbl.Model.Types;
using System.Collections.Generic;
namespace Fumbbl.UI.LogText
{
public class Pushback : LogTextGenerator<Ffb.Dto.Reports.Pushback>
{
public override IEnumerable<LogRecord> Convert(Ffb.Dto.Reports.Pushback report)
{
Player attacker = FFB.Instance.Model.GetPlayer(FFB.Instance.Model.ActingPlayer.PlayerId);
Player defender = FFB.Instance.Model.GetPlayer(report.defenderId);
switch (report.pushbackMode)
{
case "regular":
break;
case "grab":
yield return new LogRecord($"{attacker.FormattedName} uses Grab to place {attacker.Gender.Genetive} opponent.", 1);
break;
case "sideStep":
yield return new LogRecord($"{defender.FormattedName} uses Side Step to avoid being pushed.", 1);
break;
}
}
}
}
| 37.076923
| 135
| 0.584025
|
[
"MIT",
"Unlicense"
] |
christerk/FFBUnity
|
Assets/Scripts/UI/LogText/Pushback.cs
| 966
|
C#
|
using System;
using System.ComponentModel.DataAnnotations;
namespace PartsUnlimited.Models
{
public class CartItem : ILineItem
{
// second change
[Key]
public int CartItemId { get; set; }
[Required]
public string CartId { get; set; }
public int ProductId { get; set; }
public int Count { get; set; }
[DataType(DataType.DateTime)]
public DateTime DateCreated { get; set; }
public virtual Product Product { get; set; }
}
}
| 23.5
| 52
| 0.603482
|
[
"MIT"
] |
mhubert-pmn/PartsUnlimitedE2E
|
PartsUnlimited-aspnet45/src/PartsUnlimitedWebsite/Models/CartItem.cs
| 519
|
C#
|
#region Copyright
//
// DotNetNuke® - https://www.dnnsoftware.com
// Copyright (c) 2002-2018
// by DotNetNuke Corporation
//
// 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.
//Based on the work of:
// Base oAuth Class for Twitter and LinkedIn
// Author: Eran Sandler
// Code Url: http://oauth.net/code/
// Author Url: http://eran.sandler.co.il/
//
// Some modifications by Shannon Whitley
// Author Url: http://voiceoftech.com/
//
// Additional modifications by Evan Smith (DNN-4143 & DNN-6265)
// Author Url: http://skydnn.com
#endregion
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Globalization;
using System.IO;
using System.Net;
using System.Security.Cryptography;
using System.Text;
using System.Web;
using DotNetNuke.Common;
using DotNetNuke.Common.Utilities;
using DotNetNuke.Data;
using DotNetNuke.Entities.Users;
using DotNetNuke.Security.Membership;
using DotNetNuke.Instrumentation;
using DotNetNuke.Entities.Portals;
using DotNetNuke.Services.Localization;
namespace DotNetNuke.Services.Authentication.OAuth
{
public abstract class OAuthClientBase
{
#region Private Members
private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(OAuthClientBase));
private const string HMACSHA1SignatureType = "HMAC-SHA1";
//oAuth 1
private const string OAuthParameterPrefix = "oauth_";
private const string OAuthConsumerKeyKey = "oauth_consumer_key";
private const string OAuthCallbackKey = "oauth_callback";
private const string OAuthVersionKey = "oauth_version";
private const string OAuthSignatureKey = "oauth_signature";
private const string OAuthSignatureMethodKey = "oauth_signature_method";
private const string OAuthTimestampKey = "oauth_timestamp";
private const string OAuthNonceKey = "oauth_nonce";
private const string OAuthTokenSecretKey = "oauth_token_secret";
private const string OAuthVerifierKey = "oauth_verifier";
private const string OAuthCallbackConfirmedKey = "oauth_callback_confirmed";
//oAuth 2
private const string OAuthClientIdKey = "client_id";
private const string OAuthClientSecretKey = "client_secret";
private const string OAuthRedirectUriKey = "redirect_uri";
private const string OAuthGrantTyepKey = "grant_type";
private const string OAuthCodeKey = "code";
private readonly Random random = new Random();
private const string UnreservedChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_.~";
//DNN-6265 - Support OAuth V2 optional parameter resource, which is required by Microsoft Azure Active
//Directory implementation of OAuth V2
private const string OAuthResourceKey = "resource";
#endregion
protected OAuthClientBase(int portalId, AuthMode mode, string service)
{
//Set default Expiry to 14 days
//oAuth v1 tokens do not expire
//oAuth v2 tokens have an expiry
AuthTokenExpiry = new TimeSpan(14, 0, 0, 0);
Service = service;
APIKey = OAuthConfigBase.GetConfig(Service, portalId).APIKey;
APISecret = OAuthConfigBase.GetConfig(Service, portalId).APISecret;
Mode = mode;
CallbackUri = Mode == AuthMode.Login
? new Uri(Globals.LoginURL(String.Empty, false))
: new Uri(Globals.RegisterURL(String.Empty, String.Empty));
}
#region Protected Properties
protected const string OAuthTokenKey = "oauth_token";
protected virtual string UserGuidKey
{
get { return String.Empty; }
}
protected string APIKey { get; set; }
protected string APISecret { get; set; }
protected AuthMode Mode { get; set; }
protected string OAuthVersion { get; set; }
protected HttpMethod TokenMethod { get; set; }
//oAuth 1
protected string OAuthVerifier
{
get { return HttpContext.Current.Request.Params[OAuthVerifierKey]; }
}
protected Uri RequestTokenEndpoint { get; set; }
protected HttpMethod RequestTokenMethod { get; set; }
protected string TokenSecret { get; set; }
protected string UserGuid { get; set; }
//oAuth 1 and 2
protected Uri AuthorizationEndpoint { get; set; }
protected string AuthToken { get; set; }
protected TimeSpan AuthTokenExpiry { get; set; }
protected Uri MeGraphEndpoint { get; set; }
protected Uri TokenEndpoint { get; set; }
protected string OAuthHeaderCode { get; set; }
//oAuth 2
protected string AuthTokenName { get; set; }
protected string Scope { get; set; }
protected string AccessToken { get; set; }
protected string VerificationCode
{
get { return HttpContext.Current.Request.Params[OAuthCodeKey]; }
}
//DNN-6265 Support "Optional" Resource Parameter required by Azure AD Oauth V2 Solution
protected string APIResource { get; set; }
#endregion
#region Public Properties
public Uri CallbackUri { get; set; }
public string Service { get; set; }
public virtual bool PrefixServiceToUserName
{
get { return true; }
}
public virtual bool AutoMatchExistingUsers
{
get { return false; }
}
#endregion
#region Private Methods
private AuthorisationResult AuthorizeV1()
{
if (!IsCurrentUserAuthorized())
{
if (!HaveVerificationCode())
{
string ret = null;
string response = RequestToken();
if (!string.IsNullOrWhiteSpace(response))
{
//response contains token and token secret. We only need the token.
NameValueCollection qs = HttpUtility.ParseQueryString(response);
if (qs[OAuthCallbackConfirmedKey] != null)
{
if (qs[OAuthCallbackConfirmedKey] != "true")
{
throw new Exception("OAuth callback not confirmed.");
}
}
if (qs[OAuthTokenKey] != null)
{
ret = AuthorizationEndpoint + "?" + OAuthTokenKey + "=" + qs[OAuthTokenKey];
AuthToken = qs[OAuthTokenKey];
TokenSecret = qs[OAuthTokenSecretKey];
SaveTokenCookie("_request");
}
}
if (ret != null)
{
HttpContext.Current.Response.Redirect(ret, true);
}
return AuthorisationResult.RequestingCode;
}
ExchangeRequestTokenForToken();
}
return AuthorisationResult.Authorized;
}
private AuthorisationResult AuthorizeV2()
{
string errorReason = HttpContext.Current.Request.Params["error_reason"];
bool userDenied = (errorReason != null);
if (userDenied)
{
return AuthorisationResult.Denied;
}
if (!HaveVerificationCode())
{
var parameters = new List<QueryParameter>
{
new QueryParameter("scope", Scope),
new QueryParameter(OAuthClientIdKey, APIKey),
new QueryParameter(OAuthRedirectUriKey, HttpContext.Current.Server.UrlEncode(CallbackUri.ToString())),
new QueryParameter("state", Service),
new QueryParameter("response_type", "code")
};
HttpContext.Current.Response.Redirect(AuthorizationEndpoint + "?" + parameters.ToNormalizedString(), false);
return AuthorisationResult.RequestingCode;
}
ExchangeCodeForToken();
return String.IsNullOrEmpty(AuthToken) ? AuthorisationResult.Denied : AuthorisationResult.Authorized;
}
private string ComputeHash(HashAlgorithm hashAlgorithm, string data)
{
if (hashAlgorithm == null)
{
throw new ArgumentNullException("hashAlgorithm");
}
if (string.IsNullOrEmpty(data))
{
throw new ArgumentNullException("data");
}
byte[] dataBuffer = Encoding.ASCII.GetBytes(data);
byte[] hashBytes = hashAlgorithm.ComputeHash(dataBuffer);
return Convert.ToBase64String(hashBytes);
}
private void ExchangeCodeForToken()
{
IList<QueryParameter> parameters = new List<QueryParameter>();
parameters.Add(new QueryParameter(OAuthClientIdKey, APIKey));
parameters.Add(new QueryParameter(OAuthRedirectUriKey, HttpContext.Current.Server.UrlEncode(CallbackUri.ToString())));
//DNN-6265 Support for OAuth V2 Secrets which are not URL Friendly
parameters.Add(new QueryParameter(OAuthClientSecretKey, HttpContext.Current.Server.UrlEncode(APISecret.ToString())));
parameters.Add(new QueryParameter(OAuthGrantTyepKey, "authorization_code"));
parameters.Add(new QueryParameter(OAuthCodeKey, VerificationCode));
//DNN-6265 Support for OAuth V2 optional parameter
if (!String.IsNullOrEmpty(APIResource))
{
parameters.Add(new QueryParameter("resource", APIResource));
}
string responseText = ExecuteWebRequest(TokenMethod, TokenEndpoint, parameters.ToNormalizedString(), String.Empty);
AuthToken = GetToken(responseText);
AuthTokenExpiry = GetExpiry(responseText);
}
private void ExchangeRequestTokenForToken()
{
LoadTokenCookie("_request");
string response = ExecuteAuthorizedRequest(HttpMethod.POST, TokenEndpoint);
if (response.Length > 0)
{
//Store the Token and Token Secret
NameValueCollection qs = HttpUtility.ParseQueryString(response);
if (qs[OAuthTokenKey] != null)
{
AuthToken = qs[OAuthTokenKey];
}
if (qs[OAuthTokenSecretKey] != null)
{
TokenSecret = qs[OAuthTokenSecretKey];
}
if (qs[UserGuidKey] != null)
{
UserGuid = qs[UserGuidKey];
}
}
}
private string ExecuteAuthorizedRequest(HttpMethod method, Uri uri)
{
string outUrl;
List<QueryParameter> requestParameters;
string nonce = GenerateNonce();
string timeStamp = GenerateTimeStamp();
string verifier = (uri == TokenEndpoint) ? OAuthVerifier: String.Empty;
//Generate Signature
string sig = GenerateSignature(uri,
AuthToken,
TokenSecret,
String.Empty,
verifier,
method.ToString(),
timeStamp,
nonce,
out outUrl,
out requestParameters);
var headerParameters = new List<QueryParameter>
{
new QueryParameter(OAuthConsumerKeyKey, APIKey),
new QueryParameter(OAuthNonceKey, nonce),
new QueryParameter(OAuthSignatureKey, sig),
new QueryParameter(OAuthSignatureMethodKey, HMACSHA1SignatureType),
new QueryParameter(OAuthTimestampKey, timeStamp),
new QueryParameter(OAuthTokenKey, AuthToken),
new QueryParameter(OAuthVersionKey, OAuthVersion)
};
if (uri == TokenEndpoint)
{
headerParameters.Add(new QueryParameter(OAuthVerifierKey, OAuthVerifier));
}
string ret = ExecuteWebRequest(method, uri, String.Empty, headerParameters.ToAuthorizationString());
return ret;
}
private string ExecuteWebRequest(HttpMethod method, Uri uri, string parameters, string authHeader)
{
WebRequest request;
if (method == HttpMethod.POST)
{
byte[] byteArray = Encoding.UTF8.GetBytes(parameters);
request = WebRequest.CreateDefault(uri);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
//request.ContentType = "text/xml";
request.ContentLength = byteArray.Length;
if (!String.IsNullOrEmpty(OAuthHeaderCode))
{
byte[] API64 = Encoding.UTF8.GetBytes(APIKey + ":" + APISecret);
string Api64Encoded = System.Convert.ToBase64String(API64);
//Authentication providers needing an "Authorization: Basic/bearer base64(clientID:clientSecret)" header. OAuthHeaderCode might be: Basic/Bearer/empty.
request.Headers.Add("Authorization: " + OAuthHeaderCode + " " + Api64Encoded);
}
if (!String.IsNullOrEmpty(parameters))
{
Stream dataStream = request.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
}
}
else
{
request = WebRequest.CreateDefault(GenerateRequestUri(uri.ToString(), parameters));
}
//Add Headers
if (!String.IsNullOrEmpty(authHeader))
{
request.Headers.Add(HttpRequestHeader.Authorization, authHeader);
}
try
{
using (WebResponse response = request.GetResponse())
{
using (Stream responseStream = response.GetResponseStream())
{
if (responseStream != null)
{
using (var responseReader = new StreamReader(responseStream))
{
return responseReader.ReadToEnd();
}
}
}
}
}
catch (WebException ex)
{
using (Stream responseStream = ex.Response.GetResponseStream())
{
if (responseStream != null)
{
using (var responseReader = new StreamReader(responseStream))
{
Logger.ErrorFormat("WebResponse exception: {0}", responseReader.ReadToEnd());
}
}
}
}
return null;
}
private string GenerateSignatureBase(Uri url, string token, string callbackurl, string oauthVerifier, string httpMethod, string timeStamp, string nonce, out string normalizedUrl, out List<QueryParameter> requestParameters)
{
if (token == null)
{
token = string.Empty;
}
if (string.IsNullOrEmpty(httpMethod))
{
throw new ArgumentNullException("httpMethod");
}
requestParameters = GetQueryParameters(url.Query);
requestParameters.Add(new QueryParameter(OAuthVersionKey, OAuthVersion));
requestParameters.Add(new QueryParameter(OAuthNonceKey, nonce));
requestParameters.Add(new QueryParameter(OAuthTimestampKey, timeStamp));
requestParameters.Add(new QueryParameter(OAuthSignatureMethodKey, HMACSHA1SignatureType));
requestParameters.Add(new QueryParameter(OAuthConsumerKeyKey, APIKey));
if (!string.IsNullOrEmpty(callbackurl))
{
requestParameters.Add(new QueryParameter(OAuthCallbackKey, UrlEncode(callbackurl)));
}
if (!string.IsNullOrEmpty(oauthVerifier))
{
requestParameters.Add(new QueryParameter(OAuthVerifierKey, oauthVerifier));
}
if (!string.IsNullOrEmpty(token))
{
requestParameters.Add(new QueryParameter(OAuthTokenKey, token));
}
requestParameters.Sort(new QueryParameterComparer());
normalizedUrl = string.Format("{0}://{1}", url.Scheme, url.Host);
if (!((url.Scheme == "http" && url.Port == 80) || (url.Scheme == "https" && url.Port == 443)))
{
normalizedUrl += ":" + url.Port;
}
normalizedUrl += url.AbsolutePath;
string normalizedRequestParameters = requestParameters.ToNormalizedString();
var signatureBase = new StringBuilder();
signatureBase.AppendFormat("{0}&", httpMethod.ToUpper());
signatureBase.AppendFormat("{0}&", UrlEncode(normalizedUrl));
signatureBase.AppendFormat("{0}", UrlEncode(normalizedRequestParameters));
return signatureBase.ToString();
}
private string GenerateSignatureUsingHash(string signatureBase, HashAlgorithm hash)
{
return ComputeHash(hash, signatureBase);
}
private List<QueryParameter> GetQueryParameters(string parameters)
{
if (parameters.StartsWith("?"))
{
parameters = parameters.Remove(0, 1);
}
var result = new List<QueryParameter>();
if (!string.IsNullOrEmpty(parameters))
{
string[] p = parameters.Split('&');
foreach (string s in p)
{
if (!string.IsNullOrEmpty(s) && !s.StartsWith(OAuthParameterPrefix))
{
if (s.IndexOf('=') > -1)
{
string[] temp = s.Split('=');
result.Add(new QueryParameter(temp[0], temp[1]));
}
else
{
result.Add(new QueryParameter(s, string.Empty));
}
}
}
}
return result;
}
private string RequestToken()
{
string outUrl;
List<QueryParameter> requestParameters;
string nonce = GenerateNonce();
string timeStamp = GenerateTimeStamp();
string sig = GenerateSignature(RequestTokenEndpoint,
String.Empty,
String.Empty,
CallbackUri.OriginalString,
String.Empty,
RequestTokenMethod.ToString(),
timeStamp,
nonce,
out outUrl,
out requestParameters);
var headerParameters = new List<QueryParameter>
{
new QueryParameter(OAuthCallbackKey, CallbackUri.OriginalString),
new QueryParameter(OAuthConsumerKeyKey, APIKey),
new QueryParameter(OAuthNonceKey, nonce),
new QueryParameter(OAuthSignatureKey, sig),
new QueryParameter(OAuthSignatureMethodKey, HMACSHA1SignatureType),
new QueryParameter(OAuthTimestampKey, timeStamp),
new QueryParameter(OAuthVersionKey, OAuthVersion)
};
string ret = ExecuteWebRequest(RequestTokenMethod, new Uri(outUrl), String.Empty, headerParameters.ToAuthorizationString());
return ret;
}
private void SaveTokenCookie(string suffix)
{
var authTokenCookie = new HttpCookie(AuthTokenName + suffix) { Path = (!string.IsNullOrEmpty(Globals.ApplicationPath) ? Globals.ApplicationPath : "/") };
authTokenCookie.Values[OAuthTokenKey] = AuthToken;
authTokenCookie.Values[OAuthTokenSecretKey] = TokenSecret;
authTokenCookie.Values[UserGuidKey] = UserGuid;
authTokenCookie.Expires = DateTime.Now.Add(AuthTokenExpiry);
HttpContext.Current.Response.SetCookie(authTokenCookie);
}
private Uri GenerateRequestUri(string url, string parameters)
{
if (string.IsNullOrEmpty(parameters))
{
return new Uri(url);
}
return new Uri(string.Format("{0}{1}{2}", url, url.Contains("?") ? "&" : "?", parameters));
}
#endregion
#region Protected Methods
/// <summary>
/// Generate the timestamp for the signature
/// </summary>
/// <returns></returns>
protected virtual string GenerateTimeStamp()
{
// Default implementation of UNIX time of the current UTC time
TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
return Convert.ToInt64(ts.TotalSeconds).ToString(CultureInfo.InvariantCulture);
}
/// <summary>
/// Generate a nonce
/// </summary>
/// <returns></returns>
protected virtual string GenerateNonce()
{
// Just a simple implementation of a random number between 123400 and 9999999
return random.Next(123400, 9999999).ToString(CultureInfo.InvariantCulture);
}
protected virtual TimeSpan GetExpiry(string responseText)
{
return TimeSpan.MinValue;
}
protected virtual string GetToken(string responseText)
{
return responseText;
}
protected void LoadTokenCookie(string suffix)
{
HttpCookie authTokenCookie = HttpContext.Current.Request.Cookies[AuthTokenName + suffix];
if (authTokenCookie != null)
{
if (authTokenCookie.HasKeys)
{
AuthToken = authTokenCookie.Values[OAuthTokenKey];
TokenSecret = authTokenCookie.Values[OAuthTokenSecretKey];
UserGuid = authTokenCookie.Values[UserGuidKey];
}
}
}
#endregion
public virtual void AuthenticateUser(UserData user, PortalSettings settings, string IPAddress, Action<NameValueCollection> addCustomProperties, Action<UserAuthenticatedEventArgs> onAuthenticated)
{
var loginStatus = UserLoginStatus.LOGIN_FAILURE;
string userName = PrefixServiceToUserName ? Service + "-" + user.Id : user.Id;
string token = Service + "-" + user.Id;
UserInfo objUserInfo;
if (AutoMatchExistingUsers)
{
objUserInfo = MembershipProvider.Instance().GetUserByUserName(settings.PortalId, userName);
if (objUserInfo != null)
{
//user already exists... lets check for a token next...
var dnnAuthToken = MembershipProvider.Instance().GetUserByAuthToken(settings.PortalId, token, Service);
if (dnnAuthToken == null)
{
DataProvider.Instance().AddUserAuthentication(objUserInfo.UserID, Service, token, objUserInfo.UserID);
}
}
}
objUserInfo = UserController.ValidateUser(settings.PortalId, userName, "",
Service, token,
settings.PortalName, IPAddress,
ref loginStatus);
//Raise UserAuthenticated Event
var eventArgs = new UserAuthenticatedEventArgs(objUserInfo, token, loginStatus, Service)
{
AutoRegister = true,
UserName = userName,
};
var profileProperties = new NameValueCollection();
if (objUserInfo == null || (string.IsNullOrEmpty(objUserInfo.FirstName) && !string.IsNullOrEmpty(user.FirstName)))
{
profileProperties.Add("FirstName", user.FirstName);
}
if (objUserInfo == null || (string.IsNullOrEmpty(objUserInfo.LastName) && !string.IsNullOrEmpty(user.LastName)))
{
profileProperties.Add("LastName", user.LastName);
}
if (objUserInfo == null || (string.IsNullOrEmpty(objUserInfo.Email) && !string.IsNullOrEmpty(user.Email)))
{
profileProperties.Add("Email", user.PreferredEmail);
}
if (objUserInfo == null || (string.IsNullOrEmpty(objUserInfo.DisplayName) && !string.IsNullOrEmpty(user.DisplayName)))
{
profileProperties.Add("DisplayName", user.DisplayName);
}
if (objUserInfo == null || (string.IsNullOrEmpty(objUserInfo.Profile.GetPropertyValue("ProfileImage")) && !string.IsNullOrEmpty(user.ProfileImage)))
{
profileProperties.Add("ProfileImage", user.ProfileImage);
}
if (objUserInfo == null || (string.IsNullOrEmpty(objUserInfo.Profile.GetPropertyValue("Website")) && !string.IsNullOrEmpty(user.Website)))
{
profileProperties.Add("Website", user.Website);
}
if ((objUserInfo == null || (string.IsNullOrEmpty(objUserInfo.Profile.GetPropertyValue("PreferredLocale")))) && !string.IsNullOrEmpty(user.Locale))
{
if (LocaleController.IsValidCultureName(user.Locale.Replace('_', '-')))
{
profileProperties.Add("PreferredLocale", user.Locale.Replace('_', '-'));
}
else
{
profileProperties.Add("PreferredLocale", settings.CultureCode);
}
}
if (objUserInfo == null || (string.IsNullOrEmpty(objUserInfo.Profile.GetPropertyValue("PreferredTimeZone"))))
{
if (String.IsNullOrEmpty(user.TimeZoneInfo))
{
int timeZone;
if (Int32.TryParse(user.Timezone, out timeZone))
{
var timeZoneInfo = Localization.Localization.ConvertLegacyTimeZoneOffsetToTimeZoneInfo(timeZone);
profileProperties.Add("PreferredTimeZone", timeZoneInfo.Id);
}
}
else
{
profileProperties.Add("PreferredTimeZone", user.TimeZoneInfo);
}
}
addCustomProperties(profileProperties);
eventArgs.Profile = profileProperties;
if (Mode == AuthMode.Login)
{
SaveTokenCookie(String.Empty);
}
onAuthenticated(eventArgs);
}
public virtual AuthorisationResult Authorize()
{
if (OAuthVersion == "1.0")
{
return AuthorizeV1();
}
return AuthorizeV2();
}
/// <summary>
/// Generates a signature using the HMAC-SHA1 algorithm
/// </summary>
/// <param name="url">The full url that needs to be signed including its non OAuth url parameters</param>
/// <param name="token">The token, if available. If not available pass null or an empty string</param>
/// <param name="tokenSecret">The token secret, if available. If not available pass null or an empty string</param>
/// <param name="callbackurl"> </param>
/// <param name="oauthVerifier">This value MUST be included when exchanging Request Tokens for Access Tokens. Otherwise pass a null or an empty string</param>
/// <param name="httpMethod">The http method used. Must be a valid HTTP method verb (POST,GET,PUT, etc)</param>
/// <param name="timeStamp"> </param>
/// <param name="nonce"> </param>
/// <param name="normalizedUrl"> </param>
/// <param name="requestParameters"> </param>
/// <returns>A base64 string of the hash value</returns>
public string GenerateSignature(Uri url, string token, string tokenSecret, string callbackurl, string oauthVerifier, string httpMethod, string timeStamp, string nonce, out string normalizedUrl, out List<QueryParameter> requestParameters)
{
string signatureBase = GenerateSignatureBase(url, token, callbackurl, oauthVerifier, httpMethod, timeStamp, nonce, out normalizedUrl, out requestParameters);
var hmacsha1 = new HMACSHA1
{
Key = Encoding.ASCII.GetBytes(string.Format("{0}&{1}", UrlEncode(APISecret),
string.IsNullOrEmpty(tokenSecret)
? ""
: UrlEncode(tokenSecret)))
};
return GenerateSignatureUsingHash(signatureBase, hmacsha1);
}
public virtual TUserData GetCurrentUser<TUserData>() where TUserData : UserData
{
LoadTokenCookie(String.Empty);
if (!IsCurrentUserAuthorized())
{
return null;
}
var accessToken = string.IsNullOrEmpty(AccessToken) ? "access_token=" + AuthToken : AccessToken + "=" + AuthToken;
string responseText = (OAuthVersion == "1.0")
? ExecuteAuthorizedRequest(HttpMethod.GET, MeGraphEndpoint)
: ExecuteWebRequest(HttpMethod.GET, GenerateRequestUri(MeGraphEndpoint.ToString(), accessToken), null, String.Empty);
var user = Json.Deserialize<TUserData>(responseText);
return user;
}
public bool HaveVerificationCode()
{
return (OAuthVersion == "1.0") ? (OAuthVerifier != null) : (VerificationCode != null);
}
public bool IsCurrentService()
{
string service = HttpContext.Current.Request.Params["state"];
return !String.IsNullOrEmpty(service) && service == Service;
}
public Boolean IsCurrentUserAuthorized()
{
return !String.IsNullOrEmpty(AuthToken);
}
public void RemoveToken()
{
var authTokenCookie = new HttpCookie(AuthTokenName)
{
Expires = DateTime.Now.AddDays(-30),
Path = (!string.IsNullOrEmpty(Globals.ApplicationPath) ? Globals.ApplicationPath : "/")
};
HttpContext.Current.Response.SetCookie(authTokenCookie);
}
/// <summary>
/// This is a different Url Encode implementation since the default .NET one outputs the percent encoding in lower case.
/// While this is not a problem with the percent encoding spec, it is used in upper case throughout OAuth
/// </summary>
/// <param name="value">The value to Url encode</param>
/// <returns>Returns a Url encoded string</returns>
public static string UrlEncode(string value)
{
var result = new StringBuilder();
foreach (char symbol in value)
{
if (UnreservedChars.IndexOf(symbol) != -1)
{
result.Append(symbol);
}
else
{
result.Append('%' + String.Format("{0:X2}", (int)symbol));
}
}
return result.ToString();
}
}
}
| 41.332539
| 245
| 0.546946
|
[
"MIT"
] |
Mhtshum/Dnn.Platform
|
DNN Platform/Library/Services/Authentication/OAuth/OAuthClientBase.cs
| 34,681
|
C#
|
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a T4 template.
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
using System.Windows;
namespace Accelerider.Windows.Modules.Group.I18nResources
{
public static class ResKeys
{
private class TypeInTargetAssembly { }
}
}
| 26.4
| 81
| 0.496212
|
[
"MIT"
] |
Accelerider/Accelerider.Windows
|
Source/Accelerider.Windows.Modules.Group/I18nResources/ResKeys.cs
| 530
|
C#
|
// <auto-generated />
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using Passenger.Data;
#nullable disable
namespace Passenger.Data.Migrations
{
[DbContext(typeof(PassengerDbContext))]
[Migration("20220309230648_initial")]
partial class initial
{
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "6.0.1")
.HasAnnotation("Relational:MaxIdentifierLength", 128);
SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder, 1L, 1);
modelBuilder.Entity("BuildingBlocks.Outbox.OutboxMessage", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uniqueidentifier");
b.Property<Guid?>("CorrelationId")
.HasColumnType("uniqueidentifier");
b.Property<string>("Data")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("EventType")
.IsRequired()
.HasMaxLength(50)
.IsUnicode(false)
.HasColumnType("varchar(50)");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<DateTime>("OccurredOn")
.HasColumnType("datetime2");
b.Property<DateTime?>("ProcessedOn")
.HasColumnType("datetime2");
b.Property<string>("Type")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.HasKey("Id");
b.ToTable("OutboxMessages", (string)null);
});
modelBuilder.Entity("Passenger.Passenger.Models.Passenger", b =>
{
b.Property<long>("Id")
.HasColumnType("bigint");
b.Property<int>("Age")
.HasColumnType("int");
b.Property<bool>("IsDeleted")
.HasColumnType("bit");
b.Property<DateTime>("LastModified")
.HasColumnType("datetime2");
b.Property<int?>("ModifiedBy")
.HasColumnType("int");
b.Property<string>("Name")
.HasColumnType("nvarchar(max)");
b.Property<int>("PassengerType")
.HasColumnType("int");
b.Property<string>("PassportNumber")
.HasColumnType("nvarchar(max)");
b.HasKey("Id");
b.ToTable("Passenger", "dbo");
});
#pragma warning restore 612, 618
}
}
}
| 33.010101
| 84
| 0.495104
|
[
"MIT"
] |
bagalaty/Airline-Microservices
|
src/Services/Airline.Passenger/src/Passenger/Data/Migrations/20220309230648_initial.Designer.cs
| 3,270
|
C#
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.