content stringlengths 5 1.04M | avg_line_length float64 1.75 12.9k | max_line_length int64 2 244k | alphanum_fraction float64 0 0.98 | licenses list | repository_name stringlengths 7 92 | path stringlengths 3 249 | size int64 5 1.04M | lang stringclasses 2
values |
|---|---|---|---|---|---|---|---|---|
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Threading;
namespace Tasks
{
/*Реализовать класс логгера. Конструктор логгера принимает на вход путь
к файлу, в который будут записываться логи с различными уровнями
жёсткости (severity; от наименее к наиболее жёсткому: trace, debug,
information, warning, error, critical; severity описан в виде enum). Метод Log
позволяет залоггировать в файл переданную строку data с переданным
severity в следующем формате:
[<Date> <Time>] [<severity>]: <data>
В классе реализовать необходимые интерфейсы.*/
public sealed class Logger :IDisposable
{
private ReaderWriterLockSlim _cacheLock = new ReaderWriterLockSlim();
private StreamWriter _fs;
public enum Severity
{
race, debug,
information,
warning, error, critical
}
public Logger(string filepath) =>
_fs = new StreamWriter(filepath, true);
public void Set_file(string filepath)
{
Dispose();
_fs = new StreamWriter(filepath, true);
return;
}
public int Log(string data, Severity severity)
{
_cacheLock.EnterWriteLock();
//DNC Double not
try {
_fs.Write($"{Environment.NewLine}[{DateTime.Now.Day}.{DateTime.Now.Month}.{DateTime.Now.Year}] " +
$"[{DateTime.Now.Hour}:{DateTime.Now.Minute}:{DateTime.Now.Second}] [{severity}]: {data}");
return 0;
}
catch(Exception e)
{
throw e;
}
finally
{
_cacheLock.ExitWriteLock();
}
}
~Logger()=>
_fs.Dispose();
public void Dispose()//ToDO ;_cacheLock clear
{
_fs.Flush();
_fs.Close();
_fs.Dispose();
GC.SuppressFinalize(this);
}
}
class Pragma
{
delegate void Message();
Message _mes;
private struct syslog
{
public string data { get; set; }
public Logger.Severity severity { get; set; }
}
syslog _syslog;
static Random _random = new Random();
static Array _values = Enum.GetValues(typeof(Logger.Severity));
public Logger Logger { get; }
public Pragma(string path)
=> Logger = new Logger(path);
private void DeployMorning()
{
_syslog.data = "Morning Deploy";
_syslog.severity = (Logger.Severity)_values.GetValue(_random.Next(_values.Length));
}
private void DeployEvening()
{
_syslog.data= "Evening Deploy" ;
_syslog.severity = (Logger.Severity) _values.GetValue(_random.Next(_values.Length));
}
public int DoSmth()
{
try {
if (Logger==null) throw new DirectoryNotFoundException( "Logger or filepath can be equal null pls relaunch Pragma");
if (DateTime.Now.Hour < 12)
_mes = DeployMorning;
else
_mes = DeployEvening;
_mes();
Logger.Log(_syslog.data,_syslog.severity);
return 0;
}
catch(Exception e)
{
throw e;
}
}
public void Dispose()
=> Logger.Dispose();
}
}
| 28.076923 | 132 | 0.52411 | [
"MIT"
] | DeoEsor/Practice_2_Grade | CSharp_Practice/Tasks/Task_2.cs | 3,928 | C# |
namespace Sentry.Extensibility
{
/// <summary>
/// Base type for payload extraction.
/// </summary>
public abstract class BaseRequestPayloadExtractor : IRequestPayloadExtractor
{
/// <summary>
/// Extract the payload of the <see cref="IHttpRequest"/>
/// </summary>
/// <param name="request"></param>
/// <returns></returns>
public object ExtractPayload(IHttpRequest request)
{
if (!request.Body.CanSeek
|| !request.Body.CanRead
|| !IsSupported(request))
{
return null;
}
var originalPosition = request.Body.Position;
try
{
request.Body.Position = 0;
return DoExtractPayLoad(request);
}
finally
{
request.Body.Position = originalPosition;
}
}
/// <summary>
/// Whether this implementation supports the <see cref="IHttpRequest"/>
/// </summary>
/// <param name="request"></param>
/// <returns></returns>
protected abstract bool IsSupported(IHttpRequest request);
/// <summary>
/// The extraction that gets called in case <see cref="IsSupported"/> is true.
/// </summary>
/// <param name="request"></param>
/// <returns></returns>
protected abstract object DoExtractPayLoad(IHttpRequest request);
}
}
| 30.06 | 86 | 0.526946 | [
"MIT"
] | CADbloke/sentry-dotnet | src/Sentry/Extensibility/BaseRequestPayloadExtractor.cs | 1,503 | C# |
namespace java.sql
{
[global::MonoJavaBridge.JavaInterface(typeof(global::java.sql.Array_))]
public partial interface Array : global::MonoJavaBridge.IJavaObject
{
global::java.lang.Object getArray(long arg0, int arg1);
global::java.lang.Object getArray(long arg0, int arg1, java.util.Map arg2);
global::java.lang.Object getArray();
global::java.lang.Object getArray(java.util.Map arg0);
global::java.lang.String getBaseTypeName();
int getBaseType();
global::java.sql.ResultSet getResultSet();
global::java.sql.ResultSet getResultSet(java.util.Map arg0);
global::java.sql.ResultSet getResultSet(long arg0, int arg1);
global::java.sql.ResultSet getResultSet(long arg0, int arg1, java.util.Map arg2);
void free();
}
[global::MonoJavaBridge.JavaProxy(typeof(global::java.sql.Array))]
internal sealed partial class Array_ : java.lang.Object, Array
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
internal Array_(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
private static global::MonoJavaBridge.MethodId _m0;
global::java.lang.Object java.sql.Array.getArray(long arg0, int arg1)
{
return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::java.sql.Array_.staticClass, "getArray", "(JI)Ljava/lang/Object;", ref global::java.sql.Array_._m0, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)) as java.lang.Object;
}
private static global::MonoJavaBridge.MethodId _m1;
global::java.lang.Object java.sql.Array.getArray(long arg0, int arg1, java.util.Map arg2)
{
return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::java.sql.Array_.staticClass, "getArray", "(JILjava/util/Map;)Ljava/lang/Object;", ref global::java.sql.Array_._m1, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)) as java.lang.Object;
}
private static global::MonoJavaBridge.MethodId _m2;
global::java.lang.Object java.sql.Array.getArray()
{
return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::java.sql.Array_.staticClass, "getArray", "()Ljava/lang/Object;", ref global::java.sql.Array_._m2) as java.lang.Object;
}
private static global::MonoJavaBridge.MethodId _m3;
global::java.lang.Object java.sql.Array.getArray(java.util.Map arg0)
{
return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::java.sql.Array_.staticClass, "getArray", "(Ljava/util/Map;)Ljava/lang/Object;", ref global::java.sql.Array_._m3, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)) as java.lang.Object;
}
private static global::MonoJavaBridge.MethodId _m4;
global::java.lang.String java.sql.Array.getBaseTypeName()
{
return global::MonoJavaBridge.JavaBridge.CallSealedClassObjectMethod<java.lang.String>(this, global::java.sql.Array_.staticClass, "getBaseTypeName", "()Ljava/lang/String;", ref global::java.sql.Array_._m4) as java.lang.String;
}
private static global::MonoJavaBridge.MethodId _m5;
int java.sql.Array.getBaseType()
{
return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::java.sql.Array_.staticClass, "getBaseType", "()I", ref global::java.sql.Array_._m5);
}
private static global::MonoJavaBridge.MethodId _m6;
global::java.sql.ResultSet java.sql.Array.getResultSet()
{
return global::MonoJavaBridge.JavaBridge.CallIJavaObjectMethod<java.sql.ResultSet>(this, global::java.sql.Array_.staticClass, "getResultSet", "()Ljava/sql/ResultSet;", ref global::java.sql.Array_._m6) as java.sql.ResultSet;
}
private static global::MonoJavaBridge.MethodId _m7;
global::java.sql.ResultSet java.sql.Array.getResultSet(java.util.Map arg0)
{
return global::MonoJavaBridge.JavaBridge.CallIJavaObjectMethod<java.sql.ResultSet>(this, global::java.sql.Array_.staticClass, "getResultSet", "(Ljava/util/Map;)Ljava/sql/ResultSet;", ref global::java.sql.Array_._m7, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)) as java.sql.ResultSet;
}
private static global::MonoJavaBridge.MethodId _m8;
global::java.sql.ResultSet java.sql.Array.getResultSet(long arg0, int arg1)
{
return global::MonoJavaBridge.JavaBridge.CallIJavaObjectMethod<java.sql.ResultSet>(this, global::java.sql.Array_.staticClass, "getResultSet", "(JI)Ljava/sql/ResultSet;", ref global::java.sql.Array_._m8, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)) as java.sql.ResultSet;
}
private static global::MonoJavaBridge.MethodId _m9;
global::java.sql.ResultSet java.sql.Array.getResultSet(long arg0, int arg1, java.util.Map arg2)
{
return global::MonoJavaBridge.JavaBridge.CallIJavaObjectMethod<java.sql.ResultSet>(this, global::java.sql.Array_.staticClass, "getResultSet", "(JILjava/util/Map;)Ljava/sql/ResultSet;", ref global::java.sql.Array_._m9, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)) as java.sql.ResultSet;
}
private static global::MonoJavaBridge.MethodId _m10;
void java.sql.Array.free()
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.sql.Array_.staticClass, "free", "()V", ref global::java.sql.Array_._m10);
}
static Array_()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::java.sql.Array_.staticClass = @__env.NewGlobalRef(@__env.FindClass("java/sql/Array"));
}
}
}
| 63.693182 | 411 | 0.772525 | [
"MIT"
] | JeroMiya/androidmono | MonoJavaBridge/android/generated/java/sql/Array.cs | 5,605 | C# |
// Copyright (c) Andrew Arnott. All rights reserved.
// Licensed under the Microsoft Public License (Ms-PL). See LICENSE.txt file in the project root for full license information.
namespace Xunit
{
/// <summary>
/// Static methods for dynamically skipping tests identified with
/// the <see cref="SkippableFactAttribute"/>.
/// </summary>
public static class Skip
{
/// <summary>
/// Throws an exception that results in a "Skipped" result for the test.
/// </summary>
/// <param name="condition">The condition that must evaluate to <c>true</c> for the test to be skipped.</param>
/// <param name="reason">The explanation for why the test is skipped.</param>
public static void If(bool condition, string reason = null)
{
if (condition)
{
throw new SkipException(reason);
}
}
/// <summary>
/// Throws an exception that results in a "Skipped" result for the test.
/// </summary>
/// <param name="condition">The condition that must evaluate to <c>false</c> for the test to be skipped.</param>
/// <param name="reason">The explanation for why the test is skipped.</param>
public static void IfNot(bool condition, string reason = null)
{
Skip.If(!condition, reason);
}
}
} | 39.685714 | 126 | 0.604032 | [
"MIT"
] | jhgbrt/yadal | Net.Code.ADONet.Tests.Integration/Xunit/Skip.cs | 1,391 | C# |
using AppModelv2_WebApp_OpenIDConnect_DotNet.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace AppModelv2_WebApp_OpenIDConnect_DotNet.Controllers
{
public class DashboardController : BaseController
{
public DateTime StartDate { get; set; }
public DateTime EndDate { get; set; }
private const string ClientId = "clientId";
private const string ClientSecret = "clientSecret";
private const string AntiforgeryToken = "state";
// GET: Dashboard
public ActionResult Index(string filterWeek, string filterMonth, string filterYear, string filterMode)
{
filterDates fd;
switch (filterMode)
{
case "week":
fd = getDatesFromFilter(filterWeek, filterMode);
ViewData["filterMode"] = "week";
break;
case "month":
fd = getDatesFromFilter(filterMonth, filterMode);
ViewData["filterMode"] = "month";
break;
case "year":
fd = getDatesFromFilter(filterYear, filterMode);
ViewData["filterMode"] = "year";
break;
default:
fd = getDatesFromFilter(DateTime.Now.ToString(), "week");
ViewData["filterMode"] = "week";
filterMode = "week";
break;
}
StartDate = fd.StartDate;
EndDate = fd.EndDate;
ViewData["Title"] = "Dashboard";//YSA-DO Add Resources Resources.Resources.Dashboard;
//On récupère et on applique les paramètres utilisateurs
UserParameters parameters = UserParametersDataContext.GetUserParameters(true);
ViewData["SerieColor1"] = parameters.Color_Serie_1;
ViewData["SerieColor2"] = parameters.Color_Serie_2;
ViewData["SerieColor3"] = parameters.Color_Serie_3;
ViewData["SerieColor4"] = parameters.Color_Serie_4;
ViewData["SerieColor5"] = parameters.Color_Serie_5;
ViewData["SerieColor6"] = parameters.Color_Serie_6;
//ViewData["NavisionUserName"] = parameters.NavisionUserName;//Add
ViewData["UsernameLogin"] = System.Web.HttpContext.Current.Session["Username"]; //YSA Nav User
ViewData["ShowWebPortalSetup"] = parameters.Can_Read_Web_Portal_Setup;
ViewData["ShowExpenseSheet"] = parameters.Can_Read_ExpenseSheet;
ViewData["ShowTimeSheet"] = parameters.Can_Read_TimeSheet;
ViewData["CanReadGaugeChart"] = parameters.Can_Read_Gauge_Chart; //Audrey
ViewData["CanReadGaugeChartHour"] = parameters.Can_Read_Gauge_Chart_Hour; // YSA Gauge Chart
ViewData["CanReadHoursDistribution"] = parameters.Can_Read_Hours_Distribution;
ViewData["CanReadTotalHours"] = parameters.Can_Read_Total_Hours_Chart;
ViewData["CanReadSynthesis"] = parameters.Can_Read_TimeSheet_Synt;
ViewData["TimerValidation"] = parameters.Timer_Validation;
//On fournit via le viewBag les dates de filtres par défaut (semaine en cours)
//C'est moche à cause des américains qui savent pas écrire les dates correctement
ViewBag.startDate = StartDate.ToShortDateString();
ViewBag.endDate = EndDate.ToShortDateString();
ViewBag.start = StartDate;
return View();
}
public filterDates getDatesFromFilter(string filterDate, string filterMode)
{
filterDates dates = new filterDates();
switch (filterMode)
{
case "week":
int daysToRemove = (int)(Convert.ToDateTime(filterDate).DayOfWeek) == 0 ? 7 : (int)(Convert.ToDateTime(filterDate).DayOfWeek);
dates.StartDate = Convert.ToDateTime(filterDate).AddDays(1 - daysToRemove).Date;
dates.EndDate = dates.StartDate.AddDays(6);
break;
case "month":
dates.StartDate = Convert.ToDateTime(filterDate);
dates.EndDate = dates.StartDate.AddDays(DateTime.DaysInMonth(dates.StartDate.Year, dates.StartDate.Month) - 1);
break;
case "year":
dates.StartDate = new DateTime().AddYears(Convert.ToInt32(filterDate) - 1);
dates.EndDate = dates.StartDate.AddYears(1).AddDays(-1);
break;
}
return dates;
}
//private void ClearSession()
//{
// Session[ClientId] = null;
// Session[ClientSecret] = null;
// Session[AntiforgeryToken] = null;
//}
//private ViewResult Error(string error, string description)
//{
// ClearSession();
// return View("Error", new ErrorModel { Message = error, Description = description ?? "(none)" });
//}
}
public struct filterDates
{
public DateTime StartDate { get; set; }
public DateTime EndDate { get; set; }
}
} | 44.151261 | 146 | 0.593643 | [
"Apache-2.0"
] | SBYSA/SinglePageOauthBCASPNET-main | AppModelv2-WebApp-OpenIDConnect-DotNet/Controllers/DashboardController.cs | 5,263 | C# |
namespace DncZeus.Api.Entities
{
public abstract class Entity<T>
{
public T Id { get; set; }
}
}
| 14.75 | 35 | 0.576271 | [
"MIT"
] | SkyGrass/ttxy | DncZeus.Api/Entities/Entity.cs | 120 | C# |
namespace Gecko.WebIDL
{
using System;
internal class MozNetworkStats : WebIDLBase
{
public MozNetworkStats(nsIDOMWindow globalWindow, nsISupports thisObject) :
base(globalWindow, thisObject)
{
}
public string AppManifestURL
{
get
{
return this.GetProperty<string>("appManifestURL");
}
}
public bool BrowsingTrafficOnly
{
get
{
return this.GetProperty<bool>("browsingTrafficOnly");
}
}
public string ServiceType
{
get
{
return this.GetProperty<string>("serviceType");
}
}
public nsISupports Network
{
get
{
return this.GetProperty<nsISupports>("network");
}
}
public nsISupports[] Data
{
get
{
return this.GetProperty<nsISupports[]>("data");
}
}
public object Start
{
get
{
return this.GetProperty<object>("start");
}
}
public object End
{
get
{
return this.GetProperty<object>("end");
}
}
}
}
| 20.633803 | 84 | 0.407509 | [
"MIT"
] | haga-rak/Freezer | Freezer/GeckoFX/__Core/WebIDL/Generated/MozNetworkStats.cs | 1,465 | C# |
// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information.
// Ported from um/winnt.h in the Windows SDK for Windows 10.0.19041.0
// Original source is Copyright © Microsoft. All rights reserved.
using NUnit.Framework;
using System.Runtime.InteropServices;
namespace TerraFX.Interop.UnitTests
{
/// <summary>Provides validation of the <see cref="ACCESS_DENIED_ACE" /> struct.</summary>
public static unsafe class ACCESS_DENIED_ACETests
{
/// <summary>Validates that the <see cref="ACCESS_DENIED_ACE" /> struct is blittable.</summary>
[Test]
public static void IsBlittableTest()
{
Assert.That(Marshal.SizeOf<ACCESS_DENIED_ACE>(), Is.EqualTo(sizeof(ACCESS_DENIED_ACE)));
}
/// <summary>Validates that the <see cref="ACCESS_DENIED_ACE" /> struct has the right <see cref="LayoutKind" />.</summary>
[Test]
public static void IsLayoutSequentialTest()
{
Assert.That(typeof(ACCESS_DENIED_ACE).IsLayoutSequential, Is.True);
}
/// <summary>Validates that the <see cref="ACCESS_DENIED_ACE" /> struct has the correct size.</summary>
[Test]
public static void SizeOfTest()
{
Assert.That(sizeof(ACCESS_DENIED_ACE), Is.EqualTo(12));
}
}
}
| 38.527778 | 145 | 0.670512 | [
"MIT"
] | Ethereal77/terrafx.interop.windows | tests/Interop/Windows/um/winnt/ACCESS_DENIED_ACETests.cs | 1,389 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
namespace Microsoft.Azure.PowerShell.Cmdlets.Resources.Authorization.Models.Api20201001Preview
{
using Microsoft.Azure.PowerShell.Cmdlets.Resources.Authorization.Runtime.PowerShell;
/// <summary>The role management policy rule target.</summary>
[System.ComponentModel.TypeConverter(typeof(RoleManagementPolicyRuleTargetTypeConverter))]
public partial class RoleManagementPolicyRuleTarget
{
/// <summary>
/// <c>AfterDeserializeDictionary</c> will be called after the deserialization has finished, allowing customization of the
/// object before it is returned. Implement this method in a partial class to enable this behavior
/// </summary>
/// <param name="content">The global::System.Collections.IDictionary content that should be used.</param>
partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content);
/// <summary>
/// <c>AfterDeserializePSObject</c> will be called after the deserialization has finished, allowing customization of the object
/// before it is returned. Implement this method in a partial class to enable this behavior
/// </summary>
/// <param name="content">The global::System.Management.Automation.PSObject content that should be used.</param>
partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content);
/// <summary>
/// <c>BeforeDeserializeDictionary</c> will be called before the deserialization has commenced, allowing complete customization
/// of the object before it is deserialized.
/// If you wish to disable the default deserialization entirely, return <c>true</c> in the <see "returnNow" /> output parameter.
/// Implement this method in a partial class to enable this behavior.
/// </summary>
/// <param name="content">The global::System.Collections.IDictionary content that should be used.</param>
/// <param name="returnNow">Determines if the rest of the serialization should be processed, or if the method should return
/// instantly.</param>
partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow);
/// <summary>
/// <c>BeforeDeserializePSObject</c> will be called before the deserialization has commenced, allowing complete customization
/// of the object before it is deserialized.
/// If you wish to disable the default deserialization entirely, return <c>true</c> in the <see "returnNow" /> output parameter.
/// Implement this method in a partial class to enable this behavior.
/// </summary>
/// <param name="content">The global::System.Management.Automation.PSObject content that should be used.</param>
/// <param name="returnNow">Determines if the rest of the serialization should be processed, or if the method should return
/// instantly.</param>
partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow);
/// <summary>
/// Deserializes a <see cref="global::System.Collections.IDictionary" /> into an instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.Resources.Authorization.Models.Api20201001Preview.RoleManagementPolicyRuleTarget"
/// />.
/// </summary>
/// <param name="content">The global::System.Collections.IDictionary content that should be used.</param>
/// <returns>
/// an instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.Resources.Authorization.Models.Api20201001Preview.IRoleManagementPolicyRuleTarget"
/// />.
/// </returns>
public static Microsoft.Azure.PowerShell.Cmdlets.Resources.Authorization.Models.Api20201001Preview.IRoleManagementPolicyRuleTarget DeserializeFromDictionary(global::System.Collections.IDictionary content)
{
return new RoleManagementPolicyRuleTarget(content);
}
/// <summary>
/// Deserializes a <see cref="global::System.Management.Automation.PSObject" /> into an instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.Resources.Authorization.Models.Api20201001Preview.RoleManagementPolicyRuleTarget"
/// />.
/// </summary>
/// <param name="content">The global::System.Management.Automation.PSObject content that should be used.</param>
/// <returns>
/// an instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.Resources.Authorization.Models.Api20201001Preview.IRoleManagementPolicyRuleTarget"
/// />.
/// </returns>
public static Microsoft.Azure.PowerShell.Cmdlets.Resources.Authorization.Models.Api20201001Preview.IRoleManagementPolicyRuleTarget DeserializeFromPSObject(global::System.Management.Automation.PSObject content)
{
return new RoleManagementPolicyRuleTarget(content);
}
/// <summary>
/// Creates a new instance of <see cref="RoleManagementPolicyRuleTarget" />, deserializing the content from a json string.
/// </summary>
/// <param name="jsonText">a string containing a JSON serialized instance of this model.</param>
/// <returns>an instance of the <see cref="className" /> model class.</returns>
public static Microsoft.Azure.PowerShell.Cmdlets.Resources.Authorization.Models.Api20201001Preview.IRoleManagementPolicyRuleTarget FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.Resources.Authorization.Runtime.Json.JsonNode.Parse(jsonText));
/// <summary>
/// Deserializes a <see cref="global::System.Collections.IDictionary" /> into a new instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.Resources.Authorization.Models.Api20201001Preview.RoleManagementPolicyRuleTarget"
/// />.
/// </summary>
/// <param name="content">The global::System.Collections.IDictionary content that should be used.</param>
internal RoleManagementPolicyRuleTarget(global::System.Collections.IDictionary content)
{
bool returnNow = false;
BeforeDeserializeDictionary(content, ref returnNow);
if (returnNow)
{
return;
}
// actually deserialize
if (content.Contains("Caller"))
{
((Microsoft.Azure.PowerShell.Cmdlets.Resources.Authorization.Models.Api20201001Preview.IRoleManagementPolicyRuleTargetInternal)this).Caller = (string) content.GetValueForProperty("Caller",((Microsoft.Azure.PowerShell.Cmdlets.Resources.Authorization.Models.Api20201001Preview.IRoleManagementPolicyRuleTargetInternal)this).Caller, global::System.Convert.ToString);
}
if (content.Contains("Operation"))
{
((Microsoft.Azure.PowerShell.Cmdlets.Resources.Authorization.Models.Api20201001Preview.IRoleManagementPolicyRuleTargetInternal)this).Operation = (string[]) content.GetValueForProperty("Operation",((Microsoft.Azure.PowerShell.Cmdlets.Resources.Authorization.Models.Api20201001Preview.IRoleManagementPolicyRuleTargetInternal)this).Operation, __y => TypeConverterExtensions.SelectToArray<string>(__y, global::System.Convert.ToString));
}
if (content.Contains("Level"))
{
((Microsoft.Azure.PowerShell.Cmdlets.Resources.Authorization.Models.Api20201001Preview.IRoleManagementPolicyRuleTargetInternal)this).Level = (string) content.GetValueForProperty("Level",((Microsoft.Azure.PowerShell.Cmdlets.Resources.Authorization.Models.Api20201001Preview.IRoleManagementPolicyRuleTargetInternal)this).Level, global::System.Convert.ToString);
}
if (content.Contains("TargetObject"))
{
((Microsoft.Azure.PowerShell.Cmdlets.Resources.Authorization.Models.Api20201001Preview.IRoleManagementPolicyRuleTargetInternal)this).TargetObject = (string[]) content.GetValueForProperty("TargetObject",((Microsoft.Azure.PowerShell.Cmdlets.Resources.Authorization.Models.Api20201001Preview.IRoleManagementPolicyRuleTargetInternal)this).TargetObject, __y => TypeConverterExtensions.SelectToArray<string>(__y, global::System.Convert.ToString));
}
if (content.Contains("InheritableSetting"))
{
((Microsoft.Azure.PowerShell.Cmdlets.Resources.Authorization.Models.Api20201001Preview.IRoleManagementPolicyRuleTargetInternal)this).InheritableSetting = (string[]) content.GetValueForProperty("InheritableSetting",((Microsoft.Azure.PowerShell.Cmdlets.Resources.Authorization.Models.Api20201001Preview.IRoleManagementPolicyRuleTargetInternal)this).InheritableSetting, __y => TypeConverterExtensions.SelectToArray<string>(__y, global::System.Convert.ToString));
}
if (content.Contains("EnforcedSetting"))
{
((Microsoft.Azure.PowerShell.Cmdlets.Resources.Authorization.Models.Api20201001Preview.IRoleManagementPolicyRuleTargetInternal)this).EnforcedSetting = (string[]) content.GetValueForProperty("EnforcedSetting",((Microsoft.Azure.PowerShell.Cmdlets.Resources.Authorization.Models.Api20201001Preview.IRoleManagementPolicyRuleTargetInternal)this).EnforcedSetting, __y => TypeConverterExtensions.SelectToArray<string>(__y, global::System.Convert.ToString));
}
AfterDeserializeDictionary(content);
}
/// <summary>
/// Deserializes a <see cref="global::System.Management.Automation.PSObject" /> into a new instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.Resources.Authorization.Models.Api20201001Preview.RoleManagementPolicyRuleTarget"
/// />.
/// </summary>
/// <param name="content">The global::System.Management.Automation.PSObject content that should be used.</param>
internal RoleManagementPolicyRuleTarget(global::System.Management.Automation.PSObject content)
{
bool returnNow = false;
BeforeDeserializePSObject(content, ref returnNow);
if (returnNow)
{
return;
}
// actually deserialize
if (content.Contains("Caller"))
{
((Microsoft.Azure.PowerShell.Cmdlets.Resources.Authorization.Models.Api20201001Preview.IRoleManagementPolicyRuleTargetInternal)this).Caller = (string) content.GetValueForProperty("Caller",((Microsoft.Azure.PowerShell.Cmdlets.Resources.Authorization.Models.Api20201001Preview.IRoleManagementPolicyRuleTargetInternal)this).Caller, global::System.Convert.ToString);
}
if (content.Contains("Operation"))
{
((Microsoft.Azure.PowerShell.Cmdlets.Resources.Authorization.Models.Api20201001Preview.IRoleManagementPolicyRuleTargetInternal)this).Operation = (string[]) content.GetValueForProperty("Operation",((Microsoft.Azure.PowerShell.Cmdlets.Resources.Authorization.Models.Api20201001Preview.IRoleManagementPolicyRuleTargetInternal)this).Operation, __y => TypeConverterExtensions.SelectToArray<string>(__y, global::System.Convert.ToString));
}
if (content.Contains("Level"))
{
((Microsoft.Azure.PowerShell.Cmdlets.Resources.Authorization.Models.Api20201001Preview.IRoleManagementPolicyRuleTargetInternal)this).Level = (string) content.GetValueForProperty("Level",((Microsoft.Azure.PowerShell.Cmdlets.Resources.Authorization.Models.Api20201001Preview.IRoleManagementPolicyRuleTargetInternal)this).Level, global::System.Convert.ToString);
}
if (content.Contains("TargetObject"))
{
((Microsoft.Azure.PowerShell.Cmdlets.Resources.Authorization.Models.Api20201001Preview.IRoleManagementPolicyRuleTargetInternal)this).TargetObject = (string[]) content.GetValueForProperty("TargetObject",((Microsoft.Azure.PowerShell.Cmdlets.Resources.Authorization.Models.Api20201001Preview.IRoleManagementPolicyRuleTargetInternal)this).TargetObject, __y => TypeConverterExtensions.SelectToArray<string>(__y, global::System.Convert.ToString));
}
if (content.Contains("InheritableSetting"))
{
((Microsoft.Azure.PowerShell.Cmdlets.Resources.Authorization.Models.Api20201001Preview.IRoleManagementPolicyRuleTargetInternal)this).InheritableSetting = (string[]) content.GetValueForProperty("InheritableSetting",((Microsoft.Azure.PowerShell.Cmdlets.Resources.Authorization.Models.Api20201001Preview.IRoleManagementPolicyRuleTargetInternal)this).InheritableSetting, __y => TypeConverterExtensions.SelectToArray<string>(__y, global::System.Convert.ToString));
}
if (content.Contains("EnforcedSetting"))
{
((Microsoft.Azure.PowerShell.Cmdlets.Resources.Authorization.Models.Api20201001Preview.IRoleManagementPolicyRuleTargetInternal)this).EnforcedSetting = (string[]) content.GetValueForProperty("EnforcedSetting",((Microsoft.Azure.PowerShell.Cmdlets.Resources.Authorization.Models.Api20201001Preview.IRoleManagementPolicyRuleTargetInternal)this).EnforcedSetting, __y => TypeConverterExtensions.SelectToArray<string>(__y, global::System.Convert.ToString));
}
AfterDeserializePSObject(content);
}
/// <summary>Serializes this instance to a json string.</summary>
/// <returns>a <see cref="System.String" /> containing this model serialized to JSON text.</returns>
public string ToJsonString() => ToJson(null, Microsoft.Azure.PowerShell.Cmdlets.Resources.Authorization.Runtime.SerializationMode.IncludeAll)?.ToString();
}
/// The role management policy rule target.
[System.ComponentModel.TypeConverter(typeof(RoleManagementPolicyRuleTargetTypeConverter))]
public partial interface IRoleManagementPolicyRuleTarget
{
}
} | 78.315217 | 476 | 0.720611 | [
"MIT"
] | Agazoth/azure-powershell | src/Resources/Authorization.Autorest/generated/api/Models/Api20201001Preview/RoleManagementPolicyRuleTarget.PowerShell.cs | 14,227 | C# |
using ApiTaskSchedule.DB;
using ApiTaskSchedule.Enum;
using ApiTaskSchedule.Hubs;
using ApiTaskSchedule.Models;
using ApiTaskSchedule.Services;
using Microsoft.AspNetCore.SignalR;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace ApiTaskSchedule.Jobs
{
public interface IJob<T> where T : IJobData, new()
{
Guid JobId { get; set; }
JobType Type { get; set; }
Task Run(T input);
Task<JobBase<T>> Build(T input);
Task BuildAndRun(T input);
}
public interface IJobData
{
string Name { get; set; }
string Description { get; set; }
Guid OwnerId { get; set; }
}
public abstract class JobBase<T> : IJob<T> where T : IJobData, new()
{
public Guid JobId { get; set; }
public JobType Type { get; set; } = JobType.Default;
private IJobPersister _jobPersister;
public JobBase(IJobPersister jobPersister)
{
_jobPersister = jobPersister;
}
protected async Task AddOuput(string content)
{
await _jobPersister.AddOuput(this.JobId, content);
}
protected async Task SetStatus(JobStatus status)
{
await _jobPersister.SetStatus(this.JobId, status);
}
protected async Task SetPercent(int percent)
{
await _jobPersister.SetPercent(this.JobId, percent);
}
public async Task<JobBase<T>> Build(T input)
{
var job = await _jobPersister.CreateJob(Type,input.OwnerId, input.Name, input.Description, DateTime.UtcNow);
this.JobId = job.Id;
return this;
}
public abstract Task Run(T input);
public async Task BuildAndRun(T input)
{
var job = await this.Build(input);
await job.Run(input);
await _jobPersister.SetEnd(JobId, DateTime.UtcNow);
}
}
}
| 28.342857 | 120 | 0.608367 | [
"MIT"
] | nertilpoci/AspnetCoreApi.LongRunningJobs | ApiTaskSchedule/ApiTaskSchedule/Jobs/JobBase.cs | 1,986 | C# |
using System;
using System.Threading;
namespace Stethoscope.Collections
{
/// <summary>
/// Track an index within a <see cref="IBaseListCollection{T}"/>.
/// </summary>
/// <typeparam name="T">The type of element in the collection.</typeparam>
public class ListCollectionIndexOffsetTracker<T>
{
// Would prefer to use atomics instead of locks...
private readonly object locker = new object();
private bool isLockContextInUse = false;
/// <summary>
/// Get or set the original index to track.
/// </summary>
/// <seealso cref="ApplyContextLock(Action{ListCollectionIndexOffsetTracker{T}})"/>
public int OriginalIndex { get; set; }
/// <summary>
/// Get the current index after events.
/// </summary>
public int CurrentIndex { get; private set; }
/// <summary>
/// Get the offset between the <see cref="CurrentIndex"/> and <see cref="OriginalIndex"/>.
/// </summary>
public int Offset
{
get
{
lock (locker)
{
return CurrentIndex - OriginalIndex;
}
}
}
/// <summary>
/// Reset <see cref="CurrentIndex"/> to <see cref="OriginalIndex"/> so <see cref="Offset"/> is zero.
/// </summary>
/// <seealso cref="ApplyContextLock(Action{ListCollectionIndexOffsetTracker{T}})"/>
public void ResetCurrentIndex()
{
lock (locker)
{
CurrentIndex = OriginalIndex;
}
}
/// <summary>
/// Set <see cref="OriginalIndex"/> and reset <see cref="CurrentIndex"/>.
/// </summary>
/// <param name="index">The new original index.</param>
/// <seealso cref="ApplyContextLock(Action{ListCollectionIndexOffsetTracker{T}})"/>
public void SetOriginalIndexAndResetCurrent(int index)
{
lock (locker)
{
CurrentIndex = OriginalIndex = index;
}
}
/// <summary>
/// Do an action involving the tracker without any events or outside actions influencing it.
/// </summary>
/// <param name="lockedContext">The action to take place. Should not be long running.</param>
/// <exception cref="InvalidOperationException">If <see cref="ApplyContextLock(Action{ListCollectionIndexOffsetTracker{T}})"/> is recursivly invoked.</exception>
public void ApplyContextLock(Action<ListCollectionIndexOffsetTracker<T>> lockedContext)
{
if (lockedContext == null)
{
throw new ArgumentNullException(nameof(lockedContext));
}
// Logic is to prevent throwing an exception inside a "lock" to maintain state, AKA, the lockDepth value (https://stackoverflow.com/a/15860936/492347)
// Reason for caring about lock depth is it would eventually cause holding the lock for longer then we want, and it implies complexity that would better require a workaround on the dev's part then the framework
Exception lateException = null;
lock (locker)
{
if (isLockContextInUse)
{
lateException = new InvalidOperationException("Lock has already been invoked and cannot be invoked additional times");
}
else
{
// "Oh no, what if multiple threads try to use this at the same time? This state will be wrong!" Nope. Other threads will hit the outer lock and, well, be locked.
// Meanwhile the thread that holds the lock will have access to the state, and the exception handling we do will ensure the state gets reset before the final lock gets released.
isLockContextInUse = true;
try
{
lockedContext(this);
}
catch (Exception e)
{
lateException = e;
}
isLockContextInUse = false;
}
}
if (lateException != null)
{
throw lateException;
}
}
/// <summary>
/// Handle events that change the index.
/// </summary>
/// <param name="sender">The sender of the events.</param>
/// <param name="e">The event args.</param>
public void HandleEvent(object sender, ListCollectionEventArgs<T> e)
{
if (e != null)
{
if (e.Type == ListCollectionEventType.Clear)
{
lock (locker)
{
OriginalIndex = 0;
CurrentIndex = 0;
}
}
else if (e.Type == ListCollectionEventType.Insert)
{
lock (locker)
{
if (e.Index <= CurrentIndex)
{
CurrentIndex++;
}
}
}
}
}
}
}
| 37.765957 | 222 | 0.515869 | [
"MIT"
] | rcmaniac25/stethoscope | stethoscope/StethoscopeLib/Sources/Collections/ListCollectionIndexOffsetTracker.cs | 5,327 | C# |
using System;
namespace UnlockAllWondersAndLandmarks.OptionsFramework.Attibutes
{
[AttributeUsage(AttributeTargets.Property)]
public class TextfieldAttribute : AbstractOptionsAttribute
{
public TextfieldAttribute(string description, string group = null, string actionClass = null,
string actionMethod = null) : base(description, group, actionClass, actionMethod)
{
}
}
} | 32.615385 | 101 | 0.721698 | [
"MIT"
] | bloodypenguin/Skylines-UnlockAllWondersAndLandmarks | src/OptionsFramework/Attibutes/TextFieldAttribute.cs | 426 | C# |
namespace Employees.App.Command
{
using Employees.Services;
public class SetManagerCommand : ICommand
{
private readonly EmployeeService employeeService;
public SetManagerCommand(EmployeeService employeeService)
{
this.employeeService = employeeService;
}
// <employeeId> <managerId>
public string Execute(params string[] args)
{
int employeeId = int.Parse(args[0]);
int managerId = int.Parse(args[1]);
string names = this.employeeService.SetManager(employeeId, managerId);
string[] tokens = names.Split();
string emplName = $"{tokens[0]} {tokens[1]}";
string manName = $"{tokens[2]} {tokens[3]}";
return $"{manName} successfully appointed as {emplName}'s manager.";
}
}
}
| 28.566667 | 82 | 0.596266 | [
"MIT"
] | Pazzobg/03.01.CSharp-DB-Advanced-Entity-Framework | 11. EF Core AutoMapping Objects/P01_EmployeesMappingUsingServices/Employees.App/Command/SetManagerCommand.cs | 859 | C# |
using System.IO;
using eilang.Interpreting;
using eilang.Values;
namespace eilang.OperationCodes
{
public class FileEof : IOperationCode
{
public void Execute(State state)
{
var file = state.Scopes.Peek().GetVariable(SpecialVariables.FileRead).As<AnyValue>();
var reader = file.Get<StreamReader>();
state.Stack.Push(state.ValueFactory.Bool(reader.EndOfStream));
}
}
} | 27.5625 | 97 | 0.653061 | [
"MIT"
] | Szune/eilang | eilang/OperationCodes/FileEOF.cs | 443 | C# |
// Copyright (c) Josef Pihrt and Contributors. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
namespace Roslynator.Documentation
{
//TODO: ClassHierarchy
internal enum SymbolDefinitionListLayout
{
NamespaceList = 0,
NamespaceHierarchy = 1,
TypeHierarchy = 2,
}
}
| 28.230769 | 156 | 0.702997 | [
"Apache-2.0"
] | ProphetLamb-Organistion/Roslynator | src/Documentation/SymbolDefinitionListLayout.cs | 369 | C# |
// <auto-generated>
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// </auto-generated>
namespace Microsoft.Azure.Management.Batch.Fluent.Models
{
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
/// <summary>
/// A task which is run when a compute node joins a pool in the Azure Batch
/// service, or when the compute node is rebooted or reimaged.
/// </summary>
public partial class StartTask
{
/// <summary>
/// Initializes a new instance of the StartTask class.
/// </summary>
public StartTask()
{
CustomInit();
}
/// <summary>
/// Initializes a new instance of the StartTask class.
/// </summary>
/// <param name="commandLine">The command line of the start
/// task.</param>
/// <param name="resourceFiles">A list of files that the Batch service
/// will download to the compute node before running the command
/// line.</param>
/// <param name="environmentSettings">A list of environment variable
/// settings for the start task.</param>
/// <param name="userIdentity">The user identity under which the start
/// task runs.</param>
/// <param name="maxTaskRetryCount">The maximum number of times the
/// task may be retried.</param>
/// <param name="waitForSuccess">Whether the Batch service should wait
/// for the start task to complete successfully (that is, to exit with
/// exit code 0) before scheduling any tasks on the compute
/// node.</param>
public StartTask(string commandLine = default(string), IList<ResourceFile> resourceFiles = default(IList<ResourceFile>), IList<EnvironmentSetting> environmentSettings = default(IList<EnvironmentSetting>), UserIdentity userIdentity = default(UserIdentity), int? maxTaskRetryCount = default(int?), bool? waitForSuccess = default(bool?))
{
CommandLine = commandLine;
ResourceFiles = resourceFiles;
EnvironmentSettings = environmentSettings;
UserIdentity = userIdentity;
MaxTaskRetryCount = maxTaskRetryCount;
WaitForSuccess = waitForSuccess;
CustomInit();
}
/// <summary>
/// An initialization method that performs custom operations like setting defaults
/// </summary>
partial void CustomInit();
/// <summary>
/// Gets or sets the command line of the start task.
/// </summary>
/// <remarks>
/// The command line does not run under a shell, and therefore cannot
/// take advantage of shell features such as environment variable
/// expansion. If you want to take advantage of such features, you
/// should invoke the shell in the command line, for example using "cmd
/// /c MyCommand" in Windows or "/bin/sh -c MyCommand" in Linux.
/// Required if any other properties of the startTask are specified.
/// </remarks>
[JsonProperty(PropertyName = "commandLine")]
public string CommandLine { get; set; }
/// <summary>
/// Gets or sets a list of files that the Batch service will download
/// to the compute node before running the command line.
/// </summary>
[JsonProperty(PropertyName = "resourceFiles")]
public IList<ResourceFile> ResourceFiles { get; set; }
/// <summary>
/// Gets or sets a list of environment variable settings for the start
/// task.
/// </summary>
[JsonProperty(PropertyName = "environmentSettings")]
public IList<EnvironmentSetting> EnvironmentSettings { get; set; }
/// <summary>
/// Gets or sets the user identity under which the start task runs.
/// </summary>
/// <remarks>
/// If omitted, the task runs as a non-administrative user unique to
/// the task.
/// </remarks>
[JsonProperty(PropertyName = "userIdentity")]
public UserIdentity UserIdentity { get; set; }
/// <summary>
/// Gets or sets the maximum number of times the task may be retried.
/// </summary>
/// <remarks>
/// The Batch service retries a task if its exit code is nonzero. Note
/// that this value specifically controls the number of retries. The
/// Batch service will try the task once, and may then retry up to this
/// limit. For example, if the maximum retry count is 3, Batch tries
/// the task up to 4 times (one initial try and 3 retries). If the
/// maximum retry count is 0, the Batch service does not retry the
/// task. If the maximum retry count is -1, the Batch service retries
/// the task without limit.
/// </remarks>
[JsonProperty(PropertyName = "maxTaskRetryCount")]
public int? MaxTaskRetryCount { get; set; }
/// <summary>
/// Gets or sets whether the Batch service should wait for the start
/// task to complete successfully (that is, to exit with exit code 0)
/// before scheduling any tasks on the compute node.
/// </summary>
/// <remarks>
/// If true and the start task fails on a compute node, the Batch
/// service retries the start task up to its maximum retry count
/// (maxTaskRetryCount). If the task has still not completed
/// successfully after all retries, then the Batch service marks the
/// compute node unusable, and will not schedule tasks to it. This
/// condition can be detected via the node state and scheduling error
/// detail. If false, the Batch service will not wait for the start
/// task to complete. In this case, other tasks can start executing on
/// the compute node while the start task is still running; and even if
/// the start task fails, new tasks will continue to be scheduled on
/// the node. The default is false.
/// </remarks>
[JsonProperty(PropertyName = "waitForSuccess")]
public bool? WaitForSuccess { get; set; }
}
}
| 45.546099 | 342 | 0.627686 | [
"MIT"
] | AntoineGa/azure-libraries-for-net | src/ResourceManagement/Batch/Generated/Models/StartTask.cs | 6,422 | C# |
using HabitRPG.Client.Model;
using System.Collections.Generic;
using System.Threading.Tasks;
using Task = System.Threading.Tasks.Task;
namespace HabitRPG.Client
{
public interface IGroupsClient
{
/// <summary>
/// GET /groups Get a list of groups
/// </summary>
/// <param name="types"></param>
/// <returns></returns>
Task<List<Group>> GetGroupsAsync(string types);
// todo: implement POST /groups Create a group
/// <summary>
/// GET /groups/{gid}
///
/// Get a group. The party the user currently is in can be accessed with the gid 'party'.
/// </summary>
/// <param name="groupId"></param>
/// <returns></returns>
Task<Group> GetGroupAsync(string groupId);
// todo: implement POST /groups/{gid} Edit a group
// todo: implement POST /groups/{gid}/join Join a group
// todo: implement POST /groups/{gid}/leave Leave a group
// todo: implement POST /groups/{gid}/invite Invite a user to a group
// todo: implement POST /groups/{gid}/removeMember Remove / boot a member from a group
// todo: implement POST /groups/{gid}/questAccept Accept a quest invitation
// todo: implement POST /groups/{gid}/questReject Reject quest invitation
// todo: implement POST /groups/{gid}/questAbort Abort quest
/// <summary>
/// GET /groups/{gid}/chat
/// Get all chat messages
/// </summary>
/// <param name="groupId"></param>
/// <returns></returns>
Task<List<ChatMessage>> GetGroupChatAsync(string groupId);
/// <summary>
/// POST /groups/{gid}/chat
///
/// Send a chat message
/// </summary>
/// <param name="groupId"></param>
/// <param name="message"></param>
/// <returns></returns>
Task<ChatMessage> SendChatMessageAsync(string groupId, string message);
// todo: implement POST /groups/{gid}/chat/seen Flag chat messages for a particular group as seen
/// <summary>
/// DELETE /groups/{gid}/chat/{messageId} Delete a chat message in a given group
/// </summary>
/// <param name="groupId"></param>
/// <param name="messageId"></param>
/// <returns></returns>
Task DeleteChatMessageAsync(string groupId, string messageId);
/// <summary>
/// POST /groups/{gid}/chat/{mid}/like
///
/// Like a chat message
/// </summary>
/// <param name="groupId"></param>
/// <param name="messageId"></param>
/// <returns></returns>
Task LikeChatMessageAsync(string groupId, string messageId);
}
} | 36.64 | 105 | 0.576783 | [
"Apache-2.0"
] | marska/habitrpg-api-dotnet-client | src/HabitRPG.Client/Interfaces/IGroupsClient.cs | 2,750 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
namespace Microsoft.Azure.PowerShell.Cmdlets.CloudService.Models.Api20210301
{
using static Microsoft.Azure.PowerShell.Cmdlets.CloudService.Runtime.Extensions;
/// <summary>Network security rule.</summary>
public partial class SecurityRule :
Microsoft.Azure.PowerShell.Cmdlets.CloudService.Models.Api20210301.ISecurityRule,
Microsoft.Azure.PowerShell.Cmdlets.CloudService.Models.Api20210301.ISecurityRuleInternal,
Microsoft.Azure.PowerShell.Cmdlets.CloudService.Runtime.IValidates
{
/// <summary>
/// Backing field for Inherited model <see cref= "Microsoft.Azure.PowerShell.Cmdlets.CloudService.Models.Api20210301.ISubResourceAutoGenerated"
/// />
/// </summary>
private Microsoft.Azure.PowerShell.Cmdlets.CloudService.Models.Api20210301.ISubResourceAutoGenerated __subResourceAutoGenerated = new Microsoft.Azure.PowerShell.Cmdlets.CloudService.Models.Api20210301.SubResourceAutoGenerated();
/// <summary>The network traffic is allowed or denied.</summary>
[Microsoft.Azure.PowerShell.Cmdlets.CloudService.Origin(Microsoft.Azure.PowerShell.Cmdlets.CloudService.PropertyOrigin.Inlined)]
public Microsoft.Azure.PowerShell.Cmdlets.CloudService.Support.SecurityRuleAccess? Access { get => ((Microsoft.Azure.PowerShell.Cmdlets.CloudService.Models.Api20210301.ISecurityRulePropertiesFormatInternal)Property).Access; set => ((Microsoft.Azure.PowerShell.Cmdlets.CloudService.Models.Api20210301.ISecurityRulePropertiesFormatInternal)Property).Access = value ?? ((Microsoft.Azure.PowerShell.Cmdlets.CloudService.Support.SecurityRuleAccess)""); }
/// <summary>A description for this rule. Restricted to 140 chars.</summary>
[Microsoft.Azure.PowerShell.Cmdlets.CloudService.Origin(Microsoft.Azure.PowerShell.Cmdlets.CloudService.PropertyOrigin.Inlined)]
public string Description { get => ((Microsoft.Azure.PowerShell.Cmdlets.CloudService.Models.Api20210301.ISecurityRulePropertiesFormatInternal)Property).Description; set => ((Microsoft.Azure.PowerShell.Cmdlets.CloudService.Models.Api20210301.ISecurityRulePropertiesFormatInternal)Property).Description = value ?? null; }
/// <summary>
/// The destination address prefix. CIDR or destination IP range. Asterisk '*' can also be used to match all source IPs. Default
/// tags such as 'VirtualNetwork', 'AzureLoadBalancer' and 'Internet' can also be used.
/// </summary>
[Microsoft.Azure.PowerShell.Cmdlets.CloudService.Origin(Microsoft.Azure.PowerShell.Cmdlets.CloudService.PropertyOrigin.Inlined)]
public string DestinationAddressPrefix { get => ((Microsoft.Azure.PowerShell.Cmdlets.CloudService.Models.Api20210301.ISecurityRulePropertiesFormatInternal)Property).DestinationAddressPrefix; set => ((Microsoft.Azure.PowerShell.Cmdlets.CloudService.Models.Api20210301.ISecurityRulePropertiesFormatInternal)Property).DestinationAddressPrefix = value ?? null; }
/// <summary>The application security group specified as destination.</summary>
[Microsoft.Azure.PowerShell.Cmdlets.CloudService.Origin(Microsoft.Azure.PowerShell.Cmdlets.CloudService.PropertyOrigin.Inlined)]
public Microsoft.Azure.PowerShell.Cmdlets.CloudService.Models.Api20210301.IApplicationSecurityGroup[] DestinationApplicationSecurityGroup { get => ((Microsoft.Azure.PowerShell.Cmdlets.CloudService.Models.Api20210301.ISecurityRulePropertiesFormatInternal)Property).DestinationApplicationSecurityGroup; set => ((Microsoft.Azure.PowerShell.Cmdlets.CloudService.Models.Api20210301.ISecurityRulePropertiesFormatInternal)Property).DestinationApplicationSecurityGroup = value ?? null /* arrayOf */; }
/// <summary>
/// The destination port or range. Integer or range between 0 and 65535. Asterisk '*' can also be used to match all ports.
/// </summary>
[Microsoft.Azure.PowerShell.Cmdlets.CloudService.Origin(Microsoft.Azure.PowerShell.Cmdlets.CloudService.PropertyOrigin.Inlined)]
public string DestinationPortRange { get => ((Microsoft.Azure.PowerShell.Cmdlets.CloudService.Models.Api20210301.ISecurityRulePropertiesFormatInternal)Property).DestinationPortRange; set => ((Microsoft.Azure.PowerShell.Cmdlets.CloudService.Models.Api20210301.ISecurityRulePropertiesFormatInternal)Property).DestinationPortRange = value ?? null; }
/// <summary>
/// The direction of the rule. The direction specifies if rule will be evaluated on incoming or outgoing traffic.
/// </summary>
[Microsoft.Azure.PowerShell.Cmdlets.CloudService.Origin(Microsoft.Azure.PowerShell.Cmdlets.CloudService.PropertyOrigin.Inlined)]
public Microsoft.Azure.PowerShell.Cmdlets.CloudService.Support.SecurityRuleDirection? Direction { get => ((Microsoft.Azure.PowerShell.Cmdlets.CloudService.Models.Api20210301.ISecurityRulePropertiesFormatInternal)Property).Direction; set => ((Microsoft.Azure.PowerShell.Cmdlets.CloudService.Models.Api20210301.ISecurityRulePropertiesFormatInternal)Property).Direction = value ?? ((Microsoft.Azure.PowerShell.Cmdlets.CloudService.Support.SecurityRuleDirection)""); }
/// <summary>Backing field for <see cref="Etag" /> property.</summary>
private string _etag;
/// <summary>A unique read-only string that changes whenever the resource is updated.</summary>
[Microsoft.Azure.PowerShell.Cmdlets.CloudService.Origin(Microsoft.Azure.PowerShell.Cmdlets.CloudService.PropertyOrigin.Owned)]
public string Etag { get => this._etag; }
/// <summary>Resource ID.</summary>
[Microsoft.Azure.PowerShell.Cmdlets.CloudService.Origin(Microsoft.Azure.PowerShell.Cmdlets.CloudService.PropertyOrigin.Inherited)]
public string Id { get => ((Microsoft.Azure.PowerShell.Cmdlets.CloudService.Models.Api20210301.ISubResourceAutoGeneratedInternal)__subResourceAutoGenerated).Id; set => ((Microsoft.Azure.PowerShell.Cmdlets.CloudService.Models.Api20210301.ISubResourceAutoGeneratedInternal)__subResourceAutoGenerated).Id = value ?? null; }
/// <summary>Internal Acessors for Etag</summary>
string Microsoft.Azure.PowerShell.Cmdlets.CloudService.Models.Api20210301.ISecurityRuleInternal.Etag { get => this._etag; set { {_etag = value;} } }
/// <summary>Internal Acessors for Property</summary>
Microsoft.Azure.PowerShell.Cmdlets.CloudService.Models.Api20210301.ISecurityRulePropertiesFormat Microsoft.Azure.PowerShell.Cmdlets.CloudService.Models.Api20210301.ISecurityRuleInternal.Property { get => (this._property = this._property ?? new Microsoft.Azure.PowerShell.Cmdlets.CloudService.Models.Api20210301.SecurityRulePropertiesFormat()); set { {_property = value;} } }
/// <summary>Internal Acessors for ProvisioningState</summary>
Microsoft.Azure.PowerShell.Cmdlets.CloudService.Support.ProvisioningState? Microsoft.Azure.PowerShell.Cmdlets.CloudService.Models.Api20210301.ISecurityRuleInternal.ProvisioningState { get => ((Microsoft.Azure.PowerShell.Cmdlets.CloudService.Models.Api20210301.ISecurityRulePropertiesFormatInternal)Property).ProvisioningState; set => ((Microsoft.Azure.PowerShell.Cmdlets.CloudService.Models.Api20210301.ISecurityRulePropertiesFormatInternal)Property).ProvisioningState = value; }
/// <summary>Backing field for <see cref="Name" /> property.</summary>
private string _name;
/// <summary>
/// The name of the resource that is unique within a resource group. This name can be used to access the resource.
/// </summary>
[Microsoft.Azure.PowerShell.Cmdlets.CloudService.Origin(Microsoft.Azure.PowerShell.Cmdlets.CloudService.PropertyOrigin.Owned)]
public string Name { get => this._name; set => this._name = value; }
/// <summary>
/// The priority of the rule. The value can be between 100 and 4096. The priority number must be unique for each rule in the
/// collection. The lower the priority number, the higher the priority of the rule.
/// </summary>
[Microsoft.Azure.PowerShell.Cmdlets.CloudService.Origin(Microsoft.Azure.PowerShell.Cmdlets.CloudService.PropertyOrigin.Inlined)]
public int? Priority { get => ((Microsoft.Azure.PowerShell.Cmdlets.CloudService.Models.Api20210301.ISecurityRulePropertiesFormatInternal)Property).Priority; set => ((Microsoft.Azure.PowerShell.Cmdlets.CloudService.Models.Api20210301.ISecurityRulePropertiesFormatInternal)Property).Priority = value ?? default(int); }
/// <summary>The destination address prefixes. CIDR or destination IP ranges.</summary>
[Microsoft.Azure.PowerShell.Cmdlets.CloudService.Origin(Microsoft.Azure.PowerShell.Cmdlets.CloudService.PropertyOrigin.Inlined)]
public string[] PropertiesDestinationAddressPrefixes { get => ((Microsoft.Azure.PowerShell.Cmdlets.CloudService.Models.Api20210301.ISecurityRulePropertiesFormatInternal)Property).DestinationAddressPrefixes; set => ((Microsoft.Azure.PowerShell.Cmdlets.CloudService.Models.Api20210301.ISecurityRulePropertiesFormatInternal)Property).DestinationAddressPrefixes = value ?? null /* arrayOf */; }
/// <summary>The destination port ranges.</summary>
[Microsoft.Azure.PowerShell.Cmdlets.CloudService.Origin(Microsoft.Azure.PowerShell.Cmdlets.CloudService.PropertyOrigin.Inlined)]
public string[] PropertiesDestinationPortRanges { get => ((Microsoft.Azure.PowerShell.Cmdlets.CloudService.Models.Api20210301.ISecurityRulePropertiesFormatInternal)Property).DestinationPortRanges; set => ((Microsoft.Azure.PowerShell.Cmdlets.CloudService.Models.Api20210301.ISecurityRulePropertiesFormatInternal)Property).DestinationPortRanges = value ?? null /* arrayOf */; }
/// <summary>The CIDR or source IP ranges.</summary>
[Microsoft.Azure.PowerShell.Cmdlets.CloudService.Origin(Microsoft.Azure.PowerShell.Cmdlets.CloudService.PropertyOrigin.Inlined)]
public string[] PropertiesSourceAddressPrefixes { get => ((Microsoft.Azure.PowerShell.Cmdlets.CloudService.Models.Api20210301.ISecurityRulePropertiesFormatInternal)Property).SourceAddressPrefixes; set => ((Microsoft.Azure.PowerShell.Cmdlets.CloudService.Models.Api20210301.ISecurityRulePropertiesFormatInternal)Property).SourceAddressPrefixes = value ?? null /* arrayOf */; }
/// <summary>The source port ranges.</summary>
[Microsoft.Azure.PowerShell.Cmdlets.CloudService.Origin(Microsoft.Azure.PowerShell.Cmdlets.CloudService.PropertyOrigin.Inlined)]
public string[] PropertiesSourcePortRanges { get => ((Microsoft.Azure.PowerShell.Cmdlets.CloudService.Models.Api20210301.ISecurityRulePropertiesFormatInternal)Property).SourcePortRanges; set => ((Microsoft.Azure.PowerShell.Cmdlets.CloudService.Models.Api20210301.ISecurityRulePropertiesFormatInternal)Property).SourcePortRanges = value ?? null /* arrayOf */; }
/// <summary>Backing field for <see cref="Property" /> property.</summary>
private Microsoft.Azure.PowerShell.Cmdlets.CloudService.Models.Api20210301.ISecurityRulePropertiesFormat _property;
/// <summary>Properties of the security rule.</summary>
[Microsoft.Azure.PowerShell.Cmdlets.CloudService.Origin(Microsoft.Azure.PowerShell.Cmdlets.CloudService.PropertyOrigin.Owned)]
internal Microsoft.Azure.PowerShell.Cmdlets.CloudService.Models.Api20210301.ISecurityRulePropertiesFormat Property { get => (this._property = this._property ?? new Microsoft.Azure.PowerShell.Cmdlets.CloudService.Models.Api20210301.SecurityRulePropertiesFormat()); set => this._property = value; }
/// <summary>Network protocol this rule applies to.</summary>
[Microsoft.Azure.PowerShell.Cmdlets.CloudService.Origin(Microsoft.Azure.PowerShell.Cmdlets.CloudService.PropertyOrigin.Inlined)]
public Microsoft.Azure.PowerShell.Cmdlets.CloudService.Support.SecurityRuleProtocol? Protocol { get => ((Microsoft.Azure.PowerShell.Cmdlets.CloudService.Models.Api20210301.ISecurityRulePropertiesFormatInternal)Property).Protocol; set => ((Microsoft.Azure.PowerShell.Cmdlets.CloudService.Models.Api20210301.ISecurityRulePropertiesFormatInternal)Property).Protocol = value ?? ((Microsoft.Azure.PowerShell.Cmdlets.CloudService.Support.SecurityRuleProtocol)""); }
/// <summary>The provisioning state of the security rule resource.</summary>
[Microsoft.Azure.PowerShell.Cmdlets.CloudService.Origin(Microsoft.Azure.PowerShell.Cmdlets.CloudService.PropertyOrigin.Inlined)]
public Microsoft.Azure.PowerShell.Cmdlets.CloudService.Support.ProvisioningState? ProvisioningState { get => ((Microsoft.Azure.PowerShell.Cmdlets.CloudService.Models.Api20210301.ISecurityRulePropertiesFormatInternal)Property).ProvisioningState; }
/// <summary>
/// The CIDR or source IP range. Asterisk '*' can also be used to match all source IPs. Default tags such as 'VirtualNetwork',
/// 'AzureLoadBalancer' and 'Internet' can also be used. If this is an ingress rule, specifies where network traffic originates
/// from.
/// </summary>
[Microsoft.Azure.PowerShell.Cmdlets.CloudService.Origin(Microsoft.Azure.PowerShell.Cmdlets.CloudService.PropertyOrigin.Inlined)]
public string SourceAddressPrefix { get => ((Microsoft.Azure.PowerShell.Cmdlets.CloudService.Models.Api20210301.ISecurityRulePropertiesFormatInternal)Property).SourceAddressPrefix; set => ((Microsoft.Azure.PowerShell.Cmdlets.CloudService.Models.Api20210301.ISecurityRulePropertiesFormatInternal)Property).SourceAddressPrefix = value ?? null; }
/// <summary>The application security group specified as source.</summary>
[Microsoft.Azure.PowerShell.Cmdlets.CloudService.Origin(Microsoft.Azure.PowerShell.Cmdlets.CloudService.PropertyOrigin.Inlined)]
public Microsoft.Azure.PowerShell.Cmdlets.CloudService.Models.Api20210301.IApplicationSecurityGroup[] SourceApplicationSecurityGroup { get => ((Microsoft.Azure.PowerShell.Cmdlets.CloudService.Models.Api20210301.ISecurityRulePropertiesFormatInternal)Property).SourceApplicationSecurityGroup; set => ((Microsoft.Azure.PowerShell.Cmdlets.CloudService.Models.Api20210301.ISecurityRulePropertiesFormatInternal)Property).SourceApplicationSecurityGroup = value ?? null /* arrayOf */; }
/// <summary>
/// The source port or range. Integer or range between 0 and 65535. Asterisk '*' can also be used to match all ports.
/// </summary>
[Microsoft.Azure.PowerShell.Cmdlets.CloudService.Origin(Microsoft.Azure.PowerShell.Cmdlets.CloudService.PropertyOrigin.Inlined)]
public string SourcePortRange { get => ((Microsoft.Azure.PowerShell.Cmdlets.CloudService.Models.Api20210301.ISecurityRulePropertiesFormatInternal)Property).SourcePortRange; set => ((Microsoft.Azure.PowerShell.Cmdlets.CloudService.Models.Api20210301.ISecurityRulePropertiesFormatInternal)Property).SourcePortRange = value ?? null; }
/// <summary>Backing field for <see cref="Type" /> property.</summary>
private string _type;
/// <summary>The type of the resource.</summary>
[Microsoft.Azure.PowerShell.Cmdlets.CloudService.Origin(Microsoft.Azure.PowerShell.Cmdlets.CloudService.PropertyOrigin.Owned)]
public string Type { get => this._type; set => this._type = value; }
/// <summary>Creates an new <see cref="SecurityRule" /> instance.</summary>
public SecurityRule()
{
}
/// <summary>Validates that this object meets the validation criteria.</summary>
/// <param name="eventListener">an <see cref="Microsoft.Azure.PowerShell.Cmdlets.CloudService.Runtime.IEventListener" /> instance that will receive validation
/// events.</param>
/// <returns>
/// A < see cref = "global::System.Threading.Tasks.Task" /> that will be complete when validation is completed.
/// </returns>
public async global::System.Threading.Tasks.Task Validate(Microsoft.Azure.PowerShell.Cmdlets.CloudService.Runtime.IEventListener eventListener)
{
await eventListener.AssertNotNull(nameof(__subResourceAutoGenerated), __subResourceAutoGenerated);
await eventListener.AssertObjectIsValid(nameof(__subResourceAutoGenerated), __subResourceAutoGenerated);
}
}
/// Network security rule.
public partial interface ISecurityRule :
Microsoft.Azure.PowerShell.Cmdlets.CloudService.Runtime.IJsonSerializable,
Microsoft.Azure.PowerShell.Cmdlets.CloudService.Models.Api20210301.ISubResourceAutoGenerated
{
/// <summary>The network traffic is allowed or denied.</summary>
[Microsoft.Azure.PowerShell.Cmdlets.CloudService.Runtime.Info(
Required = false,
ReadOnly = false,
Description = @"The network traffic is allowed or denied.",
SerializedName = @"access",
PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.CloudService.Support.SecurityRuleAccess) })]
Microsoft.Azure.PowerShell.Cmdlets.CloudService.Support.SecurityRuleAccess? Access { get; set; }
/// <summary>A description for this rule. Restricted to 140 chars.</summary>
[Microsoft.Azure.PowerShell.Cmdlets.CloudService.Runtime.Info(
Required = false,
ReadOnly = false,
Description = @"A description for this rule. Restricted to 140 chars.",
SerializedName = @"description",
PossibleTypes = new [] { typeof(string) })]
string Description { get; set; }
/// <summary>
/// The destination address prefix. CIDR or destination IP range. Asterisk '*' can also be used to match all source IPs. Default
/// tags such as 'VirtualNetwork', 'AzureLoadBalancer' and 'Internet' can also be used.
/// </summary>
[Microsoft.Azure.PowerShell.Cmdlets.CloudService.Runtime.Info(
Required = false,
ReadOnly = false,
Description = @"The destination address prefix. CIDR or destination IP range. Asterisk '*' can also be used to match all source IPs. Default tags such as 'VirtualNetwork', 'AzureLoadBalancer' and 'Internet' can also be used.",
SerializedName = @"destinationAddressPrefix",
PossibleTypes = new [] { typeof(string) })]
string DestinationAddressPrefix { get; set; }
/// <summary>The application security group specified as destination.</summary>
[Microsoft.Azure.PowerShell.Cmdlets.CloudService.Runtime.Info(
Required = false,
ReadOnly = false,
Description = @"The application security group specified as destination.",
SerializedName = @"destinationApplicationSecurityGroups",
PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.CloudService.Models.Api20210301.IApplicationSecurityGroup) })]
Microsoft.Azure.PowerShell.Cmdlets.CloudService.Models.Api20210301.IApplicationSecurityGroup[] DestinationApplicationSecurityGroup { get; set; }
/// <summary>
/// The destination port or range. Integer or range between 0 and 65535. Asterisk '*' can also be used to match all ports.
/// </summary>
[Microsoft.Azure.PowerShell.Cmdlets.CloudService.Runtime.Info(
Required = false,
ReadOnly = false,
Description = @"The destination port or range. Integer or range between 0 and 65535. Asterisk '*' can also be used to match all ports.",
SerializedName = @"destinationPortRange",
PossibleTypes = new [] { typeof(string) })]
string DestinationPortRange { get; set; }
/// <summary>
/// The direction of the rule. The direction specifies if rule will be evaluated on incoming or outgoing traffic.
/// </summary>
[Microsoft.Azure.PowerShell.Cmdlets.CloudService.Runtime.Info(
Required = false,
ReadOnly = false,
Description = @"The direction of the rule. The direction specifies if rule will be evaluated on incoming or outgoing traffic.",
SerializedName = @"direction",
PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.CloudService.Support.SecurityRuleDirection) })]
Microsoft.Azure.PowerShell.Cmdlets.CloudService.Support.SecurityRuleDirection? Direction { get; set; }
/// <summary>A unique read-only string that changes whenever the resource is updated.</summary>
[Microsoft.Azure.PowerShell.Cmdlets.CloudService.Runtime.Info(
Required = false,
ReadOnly = true,
Description = @"A unique read-only string that changes whenever the resource is updated.",
SerializedName = @"etag",
PossibleTypes = new [] { typeof(string) })]
string Etag { get; }
/// <summary>
/// The name of the resource that is unique within a resource group. This name can be used to access the resource.
/// </summary>
[Microsoft.Azure.PowerShell.Cmdlets.CloudService.Runtime.Info(
Required = false,
ReadOnly = false,
Description = @"The name of the resource that is unique within a resource group. This name can be used to access the resource.",
SerializedName = @"name",
PossibleTypes = new [] { typeof(string) })]
string Name { get; set; }
/// <summary>
/// The priority of the rule. The value can be between 100 and 4096. The priority number must be unique for each rule in the
/// collection. The lower the priority number, the higher the priority of the rule.
/// </summary>
[Microsoft.Azure.PowerShell.Cmdlets.CloudService.Runtime.Info(
Required = false,
ReadOnly = false,
Description = @"The priority of the rule. The value can be between 100 and 4096. The priority number must be unique for each rule in the collection. The lower the priority number, the higher the priority of the rule.",
SerializedName = @"priority",
PossibleTypes = new [] { typeof(int) })]
int? Priority { get; set; }
/// <summary>The destination address prefixes. CIDR or destination IP ranges.</summary>
[Microsoft.Azure.PowerShell.Cmdlets.CloudService.Runtime.Info(
Required = false,
ReadOnly = false,
Description = @"The destination address prefixes. CIDR or destination IP ranges.",
SerializedName = @"destinationAddressPrefixes",
PossibleTypes = new [] { typeof(string) })]
string[] PropertiesDestinationAddressPrefixes { get; set; }
/// <summary>The destination port ranges.</summary>
[Microsoft.Azure.PowerShell.Cmdlets.CloudService.Runtime.Info(
Required = false,
ReadOnly = false,
Description = @"The destination port ranges.",
SerializedName = @"destinationPortRanges",
PossibleTypes = new [] { typeof(string) })]
string[] PropertiesDestinationPortRanges { get; set; }
/// <summary>The CIDR or source IP ranges.</summary>
[Microsoft.Azure.PowerShell.Cmdlets.CloudService.Runtime.Info(
Required = false,
ReadOnly = false,
Description = @"The CIDR or source IP ranges.",
SerializedName = @"sourceAddressPrefixes",
PossibleTypes = new [] { typeof(string) })]
string[] PropertiesSourceAddressPrefixes { get; set; }
/// <summary>The source port ranges.</summary>
[Microsoft.Azure.PowerShell.Cmdlets.CloudService.Runtime.Info(
Required = false,
ReadOnly = false,
Description = @"The source port ranges.",
SerializedName = @"sourcePortRanges",
PossibleTypes = new [] { typeof(string) })]
string[] PropertiesSourcePortRanges { get; set; }
/// <summary>Network protocol this rule applies to.</summary>
[Microsoft.Azure.PowerShell.Cmdlets.CloudService.Runtime.Info(
Required = false,
ReadOnly = false,
Description = @"Network protocol this rule applies to.",
SerializedName = @"protocol",
PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.CloudService.Support.SecurityRuleProtocol) })]
Microsoft.Azure.PowerShell.Cmdlets.CloudService.Support.SecurityRuleProtocol? Protocol { get; set; }
/// <summary>The provisioning state of the security rule resource.</summary>
[Microsoft.Azure.PowerShell.Cmdlets.CloudService.Runtime.Info(
Required = false,
ReadOnly = true,
Description = @"The provisioning state of the security rule resource.",
SerializedName = @"provisioningState",
PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.CloudService.Support.ProvisioningState) })]
Microsoft.Azure.PowerShell.Cmdlets.CloudService.Support.ProvisioningState? ProvisioningState { get; }
/// <summary>
/// The CIDR or source IP range. Asterisk '*' can also be used to match all source IPs. Default tags such as 'VirtualNetwork',
/// 'AzureLoadBalancer' and 'Internet' can also be used. If this is an ingress rule, specifies where network traffic originates
/// from.
/// </summary>
[Microsoft.Azure.PowerShell.Cmdlets.CloudService.Runtime.Info(
Required = false,
ReadOnly = false,
Description = @"The CIDR or source IP range. Asterisk '*' can also be used to match all source IPs. Default tags such as 'VirtualNetwork', 'AzureLoadBalancer' and 'Internet' can also be used. If this is an ingress rule, specifies where network traffic originates from.",
SerializedName = @"sourceAddressPrefix",
PossibleTypes = new [] { typeof(string) })]
string SourceAddressPrefix { get; set; }
/// <summary>The application security group specified as source.</summary>
[Microsoft.Azure.PowerShell.Cmdlets.CloudService.Runtime.Info(
Required = false,
ReadOnly = false,
Description = @"The application security group specified as source.",
SerializedName = @"sourceApplicationSecurityGroups",
PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.CloudService.Models.Api20210301.IApplicationSecurityGroup) })]
Microsoft.Azure.PowerShell.Cmdlets.CloudService.Models.Api20210301.IApplicationSecurityGroup[] SourceApplicationSecurityGroup { get; set; }
/// <summary>
/// The source port or range. Integer or range between 0 and 65535. Asterisk '*' can also be used to match all ports.
/// </summary>
[Microsoft.Azure.PowerShell.Cmdlets.CloudService.Runtime.Info(
Required = false,
ReadOnly = false,
Description = @"The source port or range. Integer or range between 0 and 65535. Asterisk '*' can also be used to match all ports.",
SerializedName = @"sourcePortRange",
PossibleTypes = new [] { typeof(string) })]
string SourcePortRange { get; set; }
/// <summary>The type of the resource.</summary>
[Microsoft.Azure.PowerShell.Cmdlets.CloudService.Runtime.Info(
Required = false,
ReadOnly = false,
Description = @"The type of the resource.",
SerializedName = @"type",
PossibleTypes = new [] { typeof(string) })]
string Type { get; set; }
}
/// Network security rule.
internal partial interface ISecurityRuleInternal :
Microsoft.Azure.PowerShell.Cmdlets.CloudService.Models.Api20210301.ISubResourceAutoGeneratedInternal
{
/// <summary>The network traffic is allowed or denied.</summary>
Microsoft.Azure.PowerShell.Cmdlets.CloudService.Support.SecurityRuleAccess? Access { get; set; }
/// <summary>A description for this rule. Restricted to 140 chars.</summary>
string Description { get; set; }
/// <summary>
/// The destination address prefix. CIDR or destination IP range. Asterisk '*' can also be used to match all source IPs. Default
/// tags such as 'VirtualNetwork', 'AzureLoadBalancer' and 'Internet' can also be used.
/// </summary>
string DestinationAddressPrefix { get; set; }
/// <summary>The application security group specified as destination.</summary>
Microsoft.Azure.PowerShell.Cmdlets.CloudService.Models.Api20210301.IApplicationSecurityGroup[] DestinationApplicationSecurityGroup { get; set; }
/// <summary>
/// The destination port or range. Integer or range between 0 and 65535. Asterisk '*' can also be used to match all ports.
/// </summary>
string DestinationPortRange { get; set; }
/// <summary>
/// The direction of the rule. The direction specifies if rule will be evaluated on incoming or outgoing traffic.
/// </summary>
Microsoft.Azure.PowerShell.Cmdlets.CloudService.Support.SecurityRuleDirection? Direction { get; set; }
/// <summary>A unique read-only string that changes whenever the resource is updated.</summary>
string Etag { get; set; }
/// <summary>
/// The name of the resource that is unique within a resource group. This name can be used to access the resource.
/// </summary>
string Name { get; set; }
/// <summary>
/// The priority of the rule. The value can be between 100 and 4096. The priority number must be unique for each rule in the
/// collection. The lower the priority number, the higher the priority of the rule.
/// </summary>
int? Priority { get; set; }
/// <summary>The destination address prefixes. CIDR or destination IP ranges.</summary>
string[] PropertiesDestinationAddressPrefixes { get; set; }
/// <summary>The destination port ranges.</summary>
string[] PropertiesDestinationPortRanges { get; set; }
/// <summary>The CIDR or source IP ranges.</summary>
string[] PropertiesSourceAddressPrefixes { get; set; }
/// <summary>The source port ranges.</summary>
string[] PropertiesSourcePortRanges { get; set; }
/// <summary>Properties of the security rule.</summary>
Microsoft.Azure.PowerShell.Cmdlets.CloudService.Models.Api20210301.ISecurityRulePropertiesFormat Property { get; set; }
/// <summary>Network protocol this rule applies to.</summary>
Microsoft.Azure.PowerShell.Cmdlets.CloudService.Support.SecurityRuleProtocol? Protocol { get; set; }
/// <summary>The provisioning state of the security rule resource.</summary>
Microsoft.Azure.PowerShell.Cmdlets.CloudService.Support.ProvisioningState? ProvisioningState { get; set; }
/// <summary>
/// The CIDR or source IP range. Asterisk '*' can also be used to match all source IPs. Default tags such as 'VirtualNetwork',
/// 'AzureLoadBalancer' and 'Internet' can also be used. If this is an ingress rule, specifies where network traffic originates
/// from.
/// </summary>
string SourceAddressPrefix { get; set; }
/// <summary>The application security group specified as source.</summary>
Microsoft.Azure.PowerShell.Cmdlets.CloudService.Models.Api20210301.IApplicationSecurityGroup[] SourceApplicationSecurityGroup { get; set; }
/// <summary>
/// The source port or range. Integer or range between 0 and 65535. Asterisk '*' can also be used to match all ports.
/// </summary>
string SourcePortRange { get; set; }
/// <summary>The type of the resource.</summary>
string Type { get; set; }
}
} | 79.59901 | 502 | 0.716494 | [
"MIT"
] | Agazoth/azure-powershell | src/CloudService/generated/api/Models/Api20210301/SecurityRule.cs | 31,755 | C# |
// Copyright (c) The Vignette Authors
// Licensed under BSD 3-Clause License. See LICENSE for details.
using Oxide.Graphics;
using Oxide.Graphics.Fonts;
namespace Oxide
{
public unsafe sealed class Config : DisposableObject
{
private string cachePath;
/// <summary>
/// Set the file path to a writable directory that will be used to store
/// cookies, cached resources, and other persistent data.
/// </summary>
public string CachePath
{
get => cachePath;
set => Ultralight.ulConfigSetCachePath(Handle, cachePath = value);
}
private FaceWinding faceWinding;
/// <summary>
/// The winding order for front-facing triangles.
/// </summary>
/// <remarks>
/// This is only used with custom GPUDrivers
/// </remarks>
public FaceWinding FaceWinding
{
get => faceWinding;
set => Ultralight.ulConfigSetFaceWinding(Handle, faceWinding = value);
}
private FontHinting fontHinting;
/// <summary>
/// The hinting algorithm to use when rendering fonts.
/// </summary>
public FontHinting FontHinting
{
get => fontHinting;
set => Ultralight.ulConfigSetFontHinting(Handle, fontHinting = value);
}
private double fontGamma;
/// <summary>
/// The gamma to use when compositing font glyphs, change this value to
/// adjust contrast (Adobe and Apple prefer 1.8, others may prefer 2.2).
/// <br/>
/// (Default = 1.8)
/// </summary>
public double FontGamma
{
get => fontGamma;
set => Ultralight.ulConfigSetFontGamma(Handle, fontGamma = value);
}
private string userStylesheet;
/// <summary>
/// Set user stylesheet (CSS).
/// <br/>
/// (Default = Empty)
/// </summary>
public string UserStylesheet
{
get => userStylesheet;
set => Ultralight.ulConfigSetUserStyleSheet(Handle, userStylesheet = value);
}
private bool forceRepaint;
/// <summary>
/// Set whether or not we should continuously repaint any Views or compositor
/// layers, regardless if they are dirty or not. This is mainly used to
/// diagnose painting/shader issues.
/// <br/>
/// (Default = False)
/// </summary>
public bool ForceRepaint
{
get => forceRepaint;
set => Ultralight.ulConfigSetForceRepaint(Handle, forceRepaint = value);
}
private double animationTimerDelay;
/// <summary>
/// Set the amount of time to wait before triggering another repaint when a
/// CSS animation is active.
/// <br/>
/// (Default = 1.0 / 60.0)
/// </summary>
public double AnimationTimerDelay
{
get => animationTimerDelay;
set => Ultralight.ulConfigSetAnimationTimerDelay(Handle, animationTimerDelay = value);
}
private double scrollTimerDelay;
/// <summary>
/// When a smooth scroll animation is active, the amount of time (in seconds)
/// to wait before triggering another repaint.
/// <br/>
/// (Default = 60 Hz)
/// </summary>
public double ScrollTimerDelay
{
get => scrollTimerDelay;
set => Ultralight.ulConfigSetScrollTimerDelay(Handle, scrollTimerDelay = value);
}
private double recycleDelay;
/// <summary>
/// The amount of time (in seconds) to wait before running the recycler (will
/// attempt to return excess memory back to the system).
/// <br/>
/// (Default = 4.0)
/// </summary>
public double RecycleDelay
{
get => recycleDelay;
set => Ultralight.ulConfigSetRecycleDelay(Handle, recycleDelay = value);
}
private uint memoryCacheSize;
/// <summary>
/// Set the size of WebCore's memory cache for decoded images, scripts, and
/// other assets in bytes.
/// <br/>
/// (Default = 64 * 1024 * 1024)
/// </summary>
public uint MemoryCacheSize
{
get => memoryCacheSize;
set => Ultralight.ulConfigSetMemoryCacheSize(Handle, memoryCacheSize = value);
}
private uint pageCacheSize;
/// <summary>
/// Set the number of pages to keep in the cache.
/// <br/>
/// (Default = 0)
/// </summary>
public uint PageCacheSize
{
get => pageCacheSize;
set => Ultralight.ulConfigSetPageCacheSize(Handle, pageCacheSize = value);
}
private uint overrideRAMSize;
/// <summary>
/// JavascriptCore tries to detect the system's physical RAM size to set
/// reasonable allocation limits. Set this to anything other than 0 to
/// override the detected value. Size is in bytes.
/// <br/>
/// This can be used to force JavascriptCore to be more conservative with
/// its allocation strategy (at the cost of some performance).
/// </summary>
public uint OverrideRAMSize
{
get => overrideRAMSize;
set => Ultralight.ulConfigSetOverrideRAMSize(Handle, overrideRAMSize = value);
}
private uint minLargeHeapSize;
/// <summary>
/// The minimum size of large VM heaps in JavascriptCore. Set this to a
/// lower value to make these heaps start with a smaller initial value.
/// </summary>
public uint MinLargeHeapSize
{
get => minLargeHeapSize;
set => Ultralight.ulConfigSetMinLargeHeapSize(Handle, minLargeHeapSize = value);
}
private uint minSmallHeapSize;
/// <summary>
/// The minimum size of small VM heaps in JavascriptCore. Set this to a
/// lower value to make these heaps start with a smaller initial value.
/// </summary>
public uint MinSmallHeapSize
{
get => minSmallHeapSize;
set => Ultralight.ulConfigSetMinSmallHeapSize(Handle, minSmallHeapSize = value);
}
/// <summary>
/// Create config with default values.
/// </summary>
public Config()
: base(Ultralight.ulCreateConfig())
{
}
protected override void DisposeUnmanaged()
=> Ultralight.ulDestroyConfig(Handle);
}
}
| 31.725118 | 98 | 0.568121 | [
"BSD-3-Clause"
] | vignetteapp/Mikomi | src/Oxide/Config.cs | 6,694 | C# |
using ServiceStack;
using System.Collections.Generic;
using System.Runtime.Serialization;
namespace JARS.SS.DTOs
{
/// <summary>
/// This response is gets returned from when a single default appointment records needs updating
/// </summary>
[DataContract]
public class JarsDefaultAppointmentResponse
{
[DataMember]
public JarsDefaultAppointmentDto Appointment { get; set; }
[DataMember]
public ResponseStatus ResponseStatus { get; set; } // inject structured errors
}
/// <summary>
/// This response is gets returned from when multiple default appointment records needs updating
/// </summary>
[DataContract]
public class JarsDefaultAppointmentsResponse
{
[DataMember]
public List<JarsDefaultAppointmentDto> Appointments { get; set; }
[DataMember]
public ResponseStatus ResponseStatus { get; set; } // inject structured errors
}
}
| 29.454545 | 100 | 0.673868 | [
"MIT"
] | CobyC/JaRS | Source/JARS.SS.DTOs/Responses/JarsDefaultsAppointmentResponse.cs | 974 | 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 iotsitewise-2019-12-02.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.IoTSiteWise.Model
{
/// <summary>
/// This is the response object from the DisassociateAssets operation.
/// </summary>
public partial class DisassociateAssetsResponse : AmazonWebServiceResponse
{
}
} | 30.243243 | 109 | 0.736372 | [
"Apache-2.0"
] | NGL321/aws-sdk-net | sdk/src/Services/IoTSiteWise/Generated/Model/DisassociateAssetsResponse.cs | 1,119 | C# |
// ==========================================================================
// Squidex Headless CMS
// ==========================================================================
// Copyright (c) Squidex UG (haftungsbeschraenkt)
// All rights reserved. Licensed under the MIT license.
// ==========================================================================
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using NodaTime;
using Squidex.Domain.Apps.Core.Apps;
using Squidex.Domain.Apps.Entities.Apps.Commands;
using Squidex.Domain.Apps.Entities.Backup.State;
using Squidex.Domain.Apps.Events;
using Squidex.Domain.Apps.Events.Apps;
using Squidex.Infrastructure;
using Squidex.Infrastructure.Commands;
using Squidex.Infrastructure.EventSourcing;
using Squidex.Infrastructure.Json.Objects;
using Squidex.Infrastructure.Log;
using Squidex.Infrastructure.Orleans;
using Squidex.Infrastructure.States;
using Squidex.Infrastructure.Tasks;
using Squidex.Infrastructure.Translations;
using Squidex.Shared.Users;
namespace Squidex.Domain.Apps.Entities.Backup
{
public sealed class RestoreGrain : GrainOfString, IRestoreGrain
{
private readonly IBackupArchiveLocation backupArchiveLocation;
private readonly IClock clock;
private readonly ICommandBus commandBus;
private readonly IEventStore eventStore;
private readonly IEventDataFormatter eventDataFormatter;
private readonly ISemanticLog log;
private readonly IServiceProvider serviceProvider;
private readonly IStreamNameResolver streamNameResolver;
private readonly IUserResolver userResolver;
private readonly IGrainState<BackupRestoreState> state;
private RestoreContext restoreContext;
private RestoreJob CurrentJob
{
get { return state.Value.Job; }
}
public RestoreGrain(
IBackupArchiveLocation backupArchiveLocation,
IClock clock,
ICommandBus commandBus,
IEventDataFormatter eventDataFormatter,
IEventStore eventStore,
IGrainState<BackupRestoreState> state,
IServiceProvider serviceProvider,
IStreamNameResolver streamNameResolver,
IUserResolver userResolver,
ISemanticLog log)
{
Guard.NotNull(backupArchiveLocation, nameof(backupArchiveLocation));
Guard.NotNull(clock, nameof(clock));
Guard.NotNull(commandBus, nameof(commandBus));
Guard.NotNull(eventDataFormatter, nameof(eventDataFormatter));
Guard.NotNull(eventStore, nameof(eventStore));
Guard.NotNull(serviceProvider, nameof(serviceProvider));
Guard.NotNull(state, nameof(state));
Guard.NotNull(streamNameResolver, nameof(streamNameResolver));
Guard.NotNull(userResolver, nameof(userResolver));
Guard.NotNull(log, nameof(log));
this.backupArchiveLocation = backupArchiveLocation;
this.clock = clock;
this.commandBus = commandBus;
this.eventDataFormatter = eventDataFormatter;
this.eventStore = eventStore;
this.serviceProvider = serviceProvider;
this.state = state;
this.streamNameResolver = streamNameResolver;
this.userResolver = userResolver;
this.log = log;
}
protected override Task OnActivateAsync(string key)
{
RecoverAfterRestartAsync().Forget();
return Task.CompletedTask;
}
private async Task RecoverAfterRestartAsync()
{
if (CurrentJob?.Status == JobStatus.Started)
{
Log("Failed due application restart");
CurrentJob.Status = JobStatus.Failed;
await state.WriteAsync();
}
}
public async Task RestoreAsync(Uri url, RefToken actor, string? newAppName)
{
Guard.NotNull(url, nameof(url));
Guard.NotNull(actor, nameof(actor));
if (!string.IsNullOrWhiteSpace(newAppName))
{
Guard.ValidSlug(newAppName, nameof(newAppName));
}
if (CurrentJob?.Status == JobStatus.Started)
{
throw new DomainException(T.Get("backups.restoreRunning"));
}
state.Value.Job = new RestoreJob
{
Id = DomainId.NewGuid(),
NewAppName = newAppName,
Actor = actor,
Started = clock.GetCurrentInstant(),
Status = JobStatus.Started,
Url = url
};
await state.WriteAsync();
Process();
}
private void Process()
{
ProcessAsync().Forget();
}
private async Task ProcessAsync()
{
var handlers = CreateHandlers();
var logContext = (jobId: CurrentJob.Id.ToString(), jobUrl: CurrentJob.Url.ToString());
using (Profiler.StartSession())
{
try
{
Log("Started. The restore process has the following steps:");
Log(" * Download backup");
Log(" * Restore events and attachments.");
Log(" * Restore all objects like app, schemas and contents");
Log(" * Complete the restore operation for all objects");
log.LogInformation(logContext, (ctx, w) => w
.WriteProperty("action", "restore")
.WriteProperty("status", "started")
.WriteProperty("operationId", ctx.jobId)
.WriteProperty("url", ctx.jobUrl));
using (var reader = await DownloadAsync())
{
await reader.CheckCompatibilityAsync();
using (Profiler.Trace("ReadEvents"))
{
await ReadEventsAsync(reader, handlers);
}
foreach (var handler in handlers)
{
using (Profiler.TraceMethod(handler.GetType(), nameof(IBackupHandler.RestoreAsync)))
{
await handler.RestoreAsync(restoreContext);
}
Log($"Restored {handler.Name}");
}
foreach (var handler in handlers)
{
using (Profiler.TraceMethod(handler.GetType(), nameof(IBackupHandler.CompleteRestoreAsync)))
{
await handler.CompleteRestoreAsync(restoreContext);
}
Log($"Completed {handler.Name}");
}
}
await AssignContributorAsync();
CurrentJob.Status = JobStatus.Completed;
Log("Completed, Yeah!");
log.LogInformation(logContext, (ctx, w) =>
{
w.WriteProperty("action", "restore");
w.WriteProperty("status", "completed");
w.WriteProperty("operationId", ctx.jobId);
w.WriteProperty("url", ctx.jobUrl);
Profiler.Session?.Write(w);
});
}
catch (Exception ex)
{
switch (ex)
{
case BackupRestoreException backupException:
Log(backupException.Message);
break;
case FileNotFoundException fileNotFoundException:
Log(fileNotFoundException.Message);
break;
default:
Log("Failed with internal error");
break;
}
await CleanupAsync(handlers);
CurrentJob.Status = JobStatus.Failed;
log.LogError(ex, logContext, (ctx, w) =>
{
w.WriteProperty("action", "restore");
w.WriteProperty("status", "failed");
w.WriteProperty("operationId", ctx.jobId);
w.WriteProperty("url", ctx.jobUrl);
Profiler.Session?.Write(w);
});
}
finally
{
CurrentJob.Stopped = clock.GetCurrentInstant();
await state.WriteAsync();
}
}
}
private async Task AssignContributorAsync()
{
var actor = CurrentJob.Actor;
if (actor?.IsSubject == true)
{
try
{
await commandBus.PublishAsync(new AssignContributor
{
Actor = actor,
AppId = CurrentJob.AppId,
ContributorId = actor.Identifier,
Restoring = true,
Role = Role.Owner
});
Log("Assigned current user.");
}
catch (DomainException ex)
{
Log($"Failed to assign contributor: {ex.Message}");
}
}
else
{
Log("Current user not assigned because restore was triggered by client.");
}
}
private async Task CleanupAsync(IEnumerable<IBackupHandler> handlers)
{
if (CurrentJob.AppId != null)
{
var appId = CurrentJob.AppId.Id;
foreach (var handler in handlers)
{
try
{
await handler.CleanupRestoreErrorAsync(appId);
}
catch (Exception ex)
{
log.LogError(ex, appId.ToString(), (logOperationId, w) => w
.WriteProperty("action", "cleanupRestore")
.WriteProperty("status", "failed")
.WriteProperty("operationId", logOperationId));
}
}
}
}
private async Task<IBackupReader> DownloadAsync()
{
using (Profiler.Trace("Download"))
{
Log("Downloading Backup");
var reader = await backupArchiveLocation.OpenReaderAsync(CurrentJob.Url, CurrentJob.Id);
Log("Downloaded Backup");
return reader;
}
}
private async Task ReadEventsAsync(IBackupReader reader, IEnumerable<IBackupHandler> handlers)
{
await reader.ReadEventsAsync(streamNameResolver, eventDataFormatter, async storedEvent =>
{
await HandleEventAsync(reader, handlers, storedEvent.Stream, storedEvent.Event);
});
Log($"Reading {reader.ReadEvents} events and {reader.ReadAttachments} attachments completed.", true);
}
private async Task HandleEventAsync(IBackupReader reader, IEnumerable<IBackupHandler> handlers, string stream, Envelope<IEvent> @event)
{
if (@event.Payload is AppCreated appCreated)
{
var previousAppId = appCreated.AppId.Id;
if (!string.IsNullOrWhiteSpace(CurrentJob.NewAppName))
{
appCreated.Name = CurrentJob.NewAppName;
CurrentJob.AppId = NamedId.Of(DomainId.NewGuid(), CurrentJob.NewAppName);
}
else
{
CurrentJob.AppId = NamedId.Of(DomainId.NewGuid(), appCreated.Name);
}
await CreateContextAsync(reader, previousAppId);
}
stream = stream.Replace(
restoreContext.PreviousAppId.ToString(),
restoreContext.AppId.ToString());
if (@event.Payload is SquidexEvent squidexEvent && squidexEvent.Actor != null)
{
if (restoreContext.UserMapping.TryMap(squidexEvent.Actor, out var newUser))
{
squidexEvent.Actor = newUser;
}
}
if (@event.Payload is AppEvent appEvent)
{
appEvent.AppId = CurrentJob.AppId;
}
if (@event.Headers.TryGet(CommonHeaders.AggregateId, out var aggregateId) && aggregateId is JsonString s)
{
var id = s.Value.Replace(
restoreContext.PreviousAppId.ToString(),
restoreContext.AppId.ToString());
var domainId = DomainId.Create(id);
@event.SetAggregateId(domainId);
}
foreach (var handler in handlers)
{
if (!await handler.RestoreEventAsync(@event, restoreContext))
{
return;
}
}
var eventData = eventDataFormatter.ToEventData(@event, @event.Headers.CommitId());
var eventCommit = new List<EventData>
{
eventData
};
await eventStore.AppendAsync(Guid.NewGuid(), stream, eventCommit);
Log($"Read {reader.ReadEvents} events and {reader.ReadAttachments} attachments.", true);
}
private async Task CreateContextAsync(IBackupReader reader, DomainId previousAppId)
{
var userMapping = new UserMapping(CurrentJob.Actor);
using (Profiler.Trace("CreateUsers"))
{
Log("Creating Users");
await userMapping.RestoreAsync(reader, userResolver);
Log("Created Users");
}
restoreContext = new RestoreContext(CurrentJob.AppId.Id, userMapping, reader, previousAppId);
}
private void Log(string message, bool replace = false)
{
if (replace && CurrentJob.Log.Count > 0)
{
CurrentJob.Log[^1] = $"{clock.GetCurrentInstant()}: {message}";
}
else
{
CurrentJob.Log.Add($"{clock.GetCurrentInstant()}: {message}");
}
}
private IEnumerable<IBackupHandler> CreateHandlers()
{
return serviceProvider.GetRequiredService<IEnumerable<IBackupHandler>>();
}
public Task<J<IRestoreJob>> GetStateAsync()
{
return Task.FromResult<J<IRestoreJob>>(CurrentJob);
}
}
}
| 35.393023 | 143 | 0.511532 | [
"MIT"
] | Smilefounder/squidex | backend/src/Squidex.Domain.Apps.Entities/Backup/RestoreGrain.cs | 15,219 | C# |
// MIT License - Copyright (c) Callum McGing
// This file is subject to the terms and conditions defined in
// LICENSE, which is part of this source code package
namespace LibreLancer.Data.Equipment
{
public class RepairKit: AbstractEquipment
{
}
} | 26.9 | 62 | 0.713755 | [
"MIT"
] | HaydnTrigg/Librelancer | src/LibreLancer.Data/Equipment/RepairKit.cs | 269 | C# |
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Linq;
using osu.Framework.Extensions;
using osu.Framework.Graphics;
using osu.Game.Rulesets.Judgements;
using osu.Game.Rulesets.Mania.UI;
using osu.Game.Rulesets.Objects;
using osu.Game.Rulesets.Scoring;
namespace osu.Game.Rulesets.Mania.Tests.Skinning
{
public class TestSceneDrawableJudgement : ManiaSkinnableTestScene
{
public TestSceneDrawableJudgement()
{
foreach (HitResult result in Enum.GetValues(typeof(HitResult)).OfType<HitResult>().Skip(1))
{
AddStep("Show " + result.GetDescription(), () => SetContents(() =>
new DrawableManiaJudgement(new JudgementResult(new HitObject(), new Judgement()) { Type = result }, null)
{
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
}));
}
}
}
}
| 35.322581 | 126 | 0.607306 | [
"MIT"
] | BananeVolante/osu | osu.Game.Rulesets.Mania.Tests/Skinning/TestSceneDrawableJudgement.cs | 1,065 | C# |
using System;
using System.Linq;
using System.Collections.Generic;
using UnityEngine;
namespace UnityExtensions.Memo {
[Serializable]
internal class MemoExport {
public MemoCategory[] category;
public MemoExport( List<MemoCategory> c ) {
category = c.ToArray();
}
}
} | 17.894737 | 52 | 0.614706 | [
"MIT"
] | 654306663/UnityExtensions | Extensions/Memo/Editor/Scripts/Data/MemoExport.cs | 342 | C# |
// <copyright file="IIxMultiplicityConfig.cs" company="ClrCoder project">
// Copyright (c) ClrCoder project. All rights reserved.
// Licensed under the Apache 2.0 license. See LICENSE file in the project root for full license information.
// </copyright>
namespace ClrCoder.ComponentModel.IndirectX
{
/// <summary>
/// Allowed instance multiplicity inside a scope. Possibly Singleton, Unlimited, Pool etc.
/// </summary>
public interface IIxMultiplicityConfig
{
}
} | 35.071429 | 108 | 0.727088 | [
"Apache-2.0"
] | dmitriyse/ClrCoder | src/ClrCoder/ComponentModel/IndirectX/Config/IIxMultiplicityConfig.cs | 493 | C# |
// 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.
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by google-apis-code-generator 1.5.1
// C# generator version: 1.27.1
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
/**
* \brief
* Ad Exchange Seller API Version v2.0
*
* \section ApiInfo API Version Information
* <table>
* <tr><th>API
* <td><a href='https://developers.google.com/ad-exchange/seller-rest/'>Ad Exchange Seller API</a>
* <tr><th>API Version<td>v2.0
* <tr><th>API Rev<td>20160805 (582)
* <tr><th>API Docs
* <td><a href='https://developers.google.com/ad-exchange/seller-rest/'>
* https://developers.google.com/ad-exchange/seller-rest/</a>
* <tr><th>Discovery Name<td>adexchangeseller
* </table>
*
* \section ForMoreInfo For More Information
*
* The complete API documentation for using Ad Exchange Seller API can be found at
* <a href='https://developers.google.com/ad-exchange/seller-rest/'>https://developers.google.com/ad-exchange/seller-rest/</a>.
*
* For more information about the Google APIs Client Library for .NET, see
* <a href='https://developers.google.com/api-client-library/dotnet/get_started'>
* https://developers.google.com/api-client-library/dotnet/get_started</a>
*/
namespace Google.Apis.AdExchangeSeller.v2_0
{
/// <summary>The AdExchangeSeller Service.</summary>
public class AdExchangeSellerService : Google.Apis.Services.BaseClientService
{
/// <summary>The API version.</summary>
public const string Version = "v2.0";
/// <summary>The discovery version used to generate this service.</summary>
public static Google.Apis.Discovery.DiscoveryVersion DiscoveryVersionUsed =
Google.Apis.Discovery.DiscoveryVersion.Version_1_0;
/// <summary>Constructs a new service.</summary>
public AdExchangeSellerService() :
this(new Google.Apis.Services.BaseClientService.Initializer()) {}
/// <summary>Constructs a new service.</summary>
/// <param name="initializer">The service initializer.</param>
public AdExchangeSellerService(Google.Apis.Services.BaseClientService.Initializer initializer)
: base(initializer)
{
accounts = new AccountsResource(this);
}
/// <summary>Gets the service supported features.</summary>
public override System.Collections.Generic.IList<string> Features
{
get { return new string[0]; }
}
/// <summary>Gets the service name.</summary>
public override string Name
{
get { return "adexchangeseller"; }
}
/// <summary>Gets the service base URI.</summary>
public override string BaseUri
{
get { return "https://www.googleapis.com/adexchangeseller/v2.0/"; }
}
/// <summary>Gets the service base path.</summary>
public override string BasePath
{
get { return "adexchangeseller/v2.0/"; }
}
#if !NET40
/// <summary>Gets the batch base URI; <c>null</c> if unspecified.</summary>
public override string BatchUri
{
get { return "https://www.googleapis.com/batch"; }
}
/// <summary>Gets the batch base path; <c>null</c> if unspecified.</summary>
public override string BatchPath
{
get { return "batch"; }
}
#endif
/// <summary>Available OAuth 2.0 scopes for use with the Ad Exchange Seller API.</summary>
public class Scope
{
/// <summary>View and manage your Ad Exchange data</summary>
public static string AdexchangeSeller = "https://www.googleapis.com/auth/adexchange.seller";
/// <summary>View your Ad Exchange data</summary>
public static string AdexchangeSellerReadonly = "https://www.googleapis.com/auth/adexchange.seller.readonly";
}
private readonly AccountsResource accounts;
/// <summary>Gets the Accounts resource.</summary>
public virtual AccountsResource Accounts
{
get { return accounts; }
}
}
///<summary>A base abstract class for AdExchangeSeller requests.</summary>
public abstract class AdExchangeSellerBaseServiceRequest<TResponse> : Google.Apis.Requests.ClientServiceRequest<TResponse>
{
///<summary>Constructs a new AdExchangeSellerBaseServiceRequest instance.</summary>
protected AdExchangeSellerBaseServiceRequest(Google.Apis.Services.IClientService service)
: base(service)
{
}
/// <summary>Data format for the response.</summary>
/// [default: json]
[Google.Apis.Util.RequestParameterAttribute("alt", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<AltEnum> Alt { get; set; }
/// <summary>Data format for the response.</summary>
public enum AltEnum
{
/// <summary>Responses with Content-Type of text/csv</summary>
[Google.Apis.Util.StringValueAttribute("csv")]
Csv,
/// <summary>Responses with Content-Type of application/json</summary>
[Google.Apis.Util.StringValueAttribute("json")]
Json,
}
/// <summary>Selector specifying which fields to include in a partial response.</summary>
[Google.Apis.Util.RequestParameterAttribute("fields", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Fields { get; set; }
/// <summary>API key. Your API key identifies your project and provides you with API access, quota, and reports.
/// Required unless you provide an OAuth 2.0 token.</summary>
[Google.Apis.Util.RequestParameterAttribute("key", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Key { get; set; }
/// <summary>OAuth 2.0 token for the current user.</summary>
[Google.Apis.Util.RequestParameterAttribute("oauth_token", Google.Apis.Util.RequestParameterType.Query)]
public virtual string OauthToken { get; set; }
/// <summary>Returns response with indentations and line breaks.</summary>
/// [default: true]
[Google.Apis.Util.RequestParameterAttribute("prettyPrint", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<bool> PrettyPrint { get; set; }
/// <summary>Available to use for quota purposes for server-side applications. Can be any arbitrary string
/// assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided.</summary>
[Google.Apis.Util.RequestParameterAttribute("quotaUser", Google.Apis.Util.RequestParameterType.Query)]
public virtual string QuotaUser { get; set; }
/// <summary>IP address of the site where the request originates. Use this if you want to enforce per-user
/// limits.</summary>
[Google.Apis.Util.RequestParameterAttribute("userIp", Google.Apis.Util.RequestParameterType.Query)]
public virtual string UserIp { get; set; }
/// <summary>Initializes AdExchangeSeller parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add(
"alt", new Google.Apis.Discovery.Parameter
{
Name = "alt",
IsRequired = false,
ParameterType = "query",
DefaultValue = "json",
Pattern = null,
});
RequestParameters.Add(
"fields", new Google.Apis.Discovery.Parameter
{
Name = "fields",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"key", new Google.Apis.Discovery.Parameter
{
Name = "key",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"oauth_token", new Google.Apis.Discovery.Parameter
{
Name = "oauth_token",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"prettyPrint", new Google.Apis.Discovery.Parameter
{
Name = "prettyPrint",
IsRequired = false,
ParameterType = "query",
DefaultValue = "true",
Pattern = null,
});
RequestParameters.Add(
"quotaUser", new Google.Apis.Discovery.Parameter
{
Name = "quotaUser",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"userIp", new Google.Apis.Discovery.Parameter
{
Name = "userIp",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
/// <summary>The "accounts" collection of methods.</summary>
public class AccountsResource
{
private const string Resource = "accounts";
/// <summary>The service which this resource belongs to.</summary>
private readonly Google.Apis.Services.IClientService service;
/// <summary>Constructs a new resource.</summary>
public AccountsResource(Google.Apis.Services.IClientService service)
{
this.service = service;
adclients = new AdclientsResource(service);
alerts = new AlertsResource(service);
customchannels = new CustomchannelsResource(service);
metadata = new MetadataResource(service);
preferreddeals = new PreferreddealsResource(service);
reports = new ReportsResource(service);
urlchannels = new UrlchannelsResource(service);
}
private readonly AdclientsResource adclients;
/// <summary>Gets the Adclients resource.</summary>
public virtual AdclientsResource Adclients
{
get { return adclients; }
}
/// <summary>The "adclients" collection of methods.</summary>
public class AdclientsResource
{
private const string Resource = "adclients";
/// <summary>The service which this resource belongs to.</summary>
private readonly Google.Apis.Services.IClientService service;
/// <summary>Constructs a new resource.</summary>
public AdclientsResource(Google.Apis.Services.IClientService service)
{
this.service = service;
}
/// <summary>List all ad clients in this Ad Exchange account.</summary>
/// <param name="accountId">Account to which the ad client belongs.</param>
public virtual ListRequest List(string accountId)
{
return new ListRequest(service, accountId);
}
/// <summary>List all ad clients in this Ad Exchange account.</summary>
public class ListRequest : AdExchangeSellerBaseServiceRequest<Google.Apis.AdExchangeSeller.v2_0.Data.AdClients>
{
/// <summary>Constructs a new List request.</summary>
public ListRequest(Google.Apis.Services.IClientService service, string accountId)
: base(service)
{
AccountId = accountId;
InitParameters();
}
/// <summary>Account to which the ad client belongs.</summary>
[Google.Apis.Util.RequestParameterAttribute("accountId", Google.Apis.Util.RequestParameterType.Path)]
public virtual string AccountId { get; private set; }
/// <summary>The maximum number of ad clients to include in the response, used for paging.</summary>
/// [minimum: 0]
/// [maximum: 10000]
[Google.Apis.Util.RequestParameterAttribute("maxResults", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<long> MaxResults { get; set; }
/// <summary>A continuation token, used to page through ad clients. To retrieve the next page, set this
/// parameter to the value of "nextPageToken" from the previous response.</summary>
[Google.Apis.Util.RequestParameterAttribute("pageToken", Google.Apis.Util.RequestParameterType.Query)]
public virtual string PageToken { get; set; }
///<summary>Gets the method name.</summary>
public override string MethodName
{
get { return "list"; }
}
///<summary>Gets the HTTP method.</summary>
public override string HttpMethod
{
get { return "GET"; }
}
///<summary>Gets the REST path.</summary>
public override string RestPath
{
get { return "accounts/{accountId}/adclients"; }
}
/// <summary>Initializes List parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add(
"accountId", new Google.Apis.Discovery.Parameter
{
Name = "accountId",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"maxResults", new Google.Apis.Discovery.Parameter
{
Name = "maxResults",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"pageToken", new Google.Apis.Discovery.Parameter
{
Name = "pageToken",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
}
private readonly AlertsResource alerts;
/// <summary>Gets the Alerts resource.</summary>
public virtual AlertsResource Alerts
{
get { return alerts; }
}
/// <summary>The "alerts" collection of methods.</summary>
public class AlertsResource
{
private const string Resource = "alerts";
/// <summary>The service which this resource belongs to.</summary>
private readonly Google.Apis.Services.IClientService service;
/// <summary>Constructs a new resource.</summary>
public AlertsResource(Google.Apis.Services.IClientService service)
{
this.service = service;
}
/// <summary>List the alerts for this Ad Exchange account.</summary>
/// <param name="accountId">Account owning the alerts.</param>
public virtual ListRequest List(string accountId)
{
return new ListRequest(service, accountId);
}
/// <summary>List the alerts for this Ad Exchange account.</summary>
public class ListRequest : AdExchangeSellerBaseServiceRequest<Google.Apis.AdExchangeSeller.v2_0.Data.Alerts>
{
/// <summary>Constructs a new List request.</summary>
public ListRequest(Google.Apis.Services.IClientService service, string accountId)
: base(service)
{
AccountId = accountId;
InitParameters();
}
/// <summary>Account owning the alerts.</summary>
[Google.Apis.Util.RequestParameterAttribute("accountId", Google.Apis.Util.RequestParameterType.Path)]
public virtual string AccountId { get; private set; }
/// <summary>The locale to use for translating alert messages. The account locale will be used if this
/// is not supplied. The AdSense default (English) will be used if the supplied locale is invalid or
/// unsupported.</summary>
[Google.Apis.Util.RequestParameterAttribute("locale", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Locale { get; set; }
///<summary>Gets the method name.</summary>
public override string MethodName
{
get { return "list"; }
}
///<summary>Gets the HTTP method.</summary>
public override string HttpMethod
{
get { return "GET"; }
}
///<summary>Gets the REST path.</summary>
public override string RestPath
{
get { return "accounts/{accountId}/alerts"; }
}
/// <summary>Initializes List parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add(
"accountId", new Google.Apis.Discovery.Parameter
{
Name = "accountId",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"locale", new Google.Apis.Discovery.Parameter
{
Name = "locale",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
}
private readonly CustomchannelsResource customchannels;
/// <summary>Gets the Customchannels resource.</summary>
public virtual CustomchannelsResource Customchannels
{
get { return customchannels; }
}
/// <summary>The "customchannels" collection of methods.</summary>
public class CustomchannelsResource
{
private const string Resource = "customchannels";
/// <summary>The service which this resource belongs to.</summary>
private readonly Google.Apis.Services.IClientService service;
/// <summary>Constructs a new resource.</summary>
public CustomchannelsResource(Google.Apis.Services.IClientService service)
{
this.service = service;
}
/// <summary>Get the specified custom channel from the specified ad client.</summary>
/// <param name="accountId">Account to which the ad client belongs.</param>
/// <param name="adClientId">Ad client
/// which contains the custom channel.</param>
/// <param name="customChannelId">Custom channel to
/// retrieve.</param>
public virtual GetRequest Get(string accountId, string adClientId, string customChannelId)
{
return new GetRequest(service, accountId, adClientId, customChannelId);
}
/// <summary>Get the specified custom channel from the specified ad client.</summary>
public class GetRequest : AdExchangeSellerBaseServiceRequest<Google.Apis.AdExchangeSeller.v2_0.Data.CustomChannel>
{
/// <summary>Constructs a new Get request.</summary>
public GetRequest(Google.Apis.Services.IClientService service, string accountId, string adClientId, string customChannelId)
: base(service)
{
AccountId = accountId;
AdClientId = adClientId;
CustomChannelId = customChannelId;
InitParameters();
}
/// <summary>Account to which the ad client belongs.</summary>
[Google.Apis.Util.RequestParameterAttribute("accountId", Google.Apis.Util.RequestParameterType.Path)]
public virtual string AccountId { get; private set; }
/// <summary>Ad client which contains the custom channel.</summary>
[Google.Apis.Util.RequestParameterAttribute("adClientId", Google.Apis.Util.RequestParameterType.Path)]
public virtual string AdClientId { get; private set; }
/// <summary>Custom channel to retrieve.</summary>
[Google.Apis.Util.RequestParameterAttribute("customChannelId", Google.Apis.Util.RequestParameterType.Path)]
public virtual string CustomChannelId { get; private set; }
///<summary>Gets the method name.</summary>
public override string MethodName
{
get { return "get"; }
}
///<summary>Gets the HTTP method.</summary>
public override string HttpMethod
{
get { return "GET"; }
}
///<summary>Gets the REST path.</summary>
public override string RestPath
{
get { return "accounts/{accountId}/adclients/{adClientId}/customchannels/{customChannelId}"; }
}
/// <summary>Initializes Get parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add(
"accountId", new Google.Apis.Discovery.Parameter
{
Name = "accountId",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"adClientId", new Google.Apis.Discovery.Parameter
{
Name = "adClientId",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"customChannelId", new Google.Apis.Discovery.Parameter
{
Name = "customChannelId",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = null,
});
}
}
/// <summary>List all custom channels in the specified ad client for this Ad Exchange account.</summary>
/// <param name="accountId">Account to which the ad client belongs.</param>
/// <param name="adClientId">Ad client
/// for which to list custom channels.</param>
public virtual ListRequest List(string accountId, string adClientId)
{
return new ListRequest(service, accountId, adClientId);
}
/// <summary>List all custom channels in the specified ad client for this Ad Exchange account.</summary>
public class ListRequest : AdExchangeSellerBaseServiceRequest<Google.Apis.AdExchangeSeller.v2_0.Data.CustomChannels>
{
/// <summary>Constructs a new List request.</summary>
public ListRequest(Google.Apis.Services.IClientService service, string accountId, string adClientId)
: base(service)
{
AccountId = accountId;
AdClientId = adClientId;
InitParameters();
}
/// <summary>Account to which the ad client belongs.</summary>
[Google.Apis.Util.RequestParameterAttribute("accountId", Google.Apis.Util.RequestParameterType.Path)]
public virtual string AccountId { get; private set; }
/// <summary>Ad client for which to list custom channels.</summary>
[Google.Apis.Util.RequestParameterAttribute("adClientId", Google.Apis.Util.RequestParameterType.Path)]
public virtual string AdClientId { get; private set; }
/// <summary>The maximum number of custom channels to include in the response, used for
/// paging.</summary>
/// [minimum: 0]
/// [maximum: 10000]
[Google.Apis.Util.RequestParameterAttribute("maxResults", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<long> MaxResults { get; set; }
/// <summary>A continuation token, used to page through custom channels. To retrieve the next page, set
/// this parameter to the value of "nextPageToken" from the previous response.</summary>
[Google.Apis.Util.RequestParameterAttribute("pageToken", Google.Apis.Util.RequestParameterType.Query)]
public virtual string PageToken { get; set; }
///<summary>Gets the method name.</summary>
public override string MethodName
{
get { return "list"; }
}
///<summary>Gets the HTTP method.</summary>
public override string HttpMethod
{
get { return "GET"; }
}
///<summary>Gets the REST path.</summary>
public override string RestPath
{
get { return "accounts/{accountId}/adclients/{adClientId}/customchannels"; }
}
/// <summary>Initializes List parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add(
"accountId", new Google.Apis.Discovery.Parameter
{
Name = "accountId",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"adClientId", new Google.Apis.Discovery.Parameter
{
Name = "adClientId",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"maxResults", new Google.Apis.Discovery.Parameter
{
Name = "maxResults",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"pageToken", new Google.Apis.Discovery.Parameter
{
Name = "pageToken",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
}
private readonly MetadataResource metadata;
/// <summary>Gets the Metadata resource.</summary>
public virtual MetadataResource Metadata
{
get { return metadata; }
}
/// <summary>The "metadata" collection of methods.</summary>
public class MetadataResource
{
private const string Resource = "metadata";
/// <summary>The service which this resource belongs to.</summary>
private readonly Google.Apis.Services.IClientService service;
/// <summary>Constructs a new resource.</summary>
public MetadataResource(Google.Apis.Services.IClientService service)
{
this.service = service;
dimensions = new DimensionsResource(service);
metrics = new MetricsResource(service);
}
private readonly DimensionsResource dimensions;
/// <summary>Gets the Dimensions resource.</summary>
public virtual DimensionsResource Dimensions
{
get { return dimensions; }
}
/// <summary>The "dimensions" collection of methods.</summary>
public class DimensionsResource
{
private const string Resource = "dimensions";
/// <summary>The service which this resource belongs to.</summary>
private readonly Google.Apis.Services.IClientService service;
/// <summary>Constructs a new resource.</summary>
public DimensionsResource(Google.Apis.Services.IClientService service)
{
this.service = service;
}
/// <summary>List the metadata for the dimensions available to this AdExchange account.</summary>
/// <param name="accountId">Account with visibility to the dimensions.</param>
public virtual ListRequest List(string accountId)
{
return new ListRequest(service, accountId);
}
/// <summary>List the metadata for the dimensions available to this AdExchange account.</summary>
public class ListRequest : AdExchangeSellerBaseServiceRequest<Google.Apis.AdExchangeSeller.v2_0.Data.Metadata>
{
/// <summary>Constructs a new List request.</summary>
public ListRequest(Google.Apis.Services.IClientService service, string accountId)
: base(service)
{
AccountId = accountId;
InitParameters();
}
/// <summary>Account with visibility to the dimensions.</summary>
[Google.Apis.Util.RequestParameterAttribute("accountId", Google.Apis.Util.RequestParameterType.Path)]
public virtual string AccountId { get; private set; }
///<summary>Gets the method name.</summary>
public override string MethodName
{
get { return "list"; }
}
///<summary>Gets the HTTP method.</summary>
public override string HttpMethod
{
get { return "GET"; }
}
///<summary>Gets the REST path.</summary>
public override string RestPath
{
get { return "accounts/{accountId}/metadata/dimensions"; }
}
/// <summary>Initializes List parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add(
"accountId", new Google.Apis.Discovery.Parameter
{
Name = "accountId",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = null,
});
}
}
}
private readonly MetricsResource metrics;
/// <summary>Gets the Metrics resource.</summary>
public virtual MetricsResource Metrics
{
get { return metrics; }
}
/// <summary>The "metrics" collection of methods.</summary>
public class MetricsResource
{
private const string Resource = "metrics";
/// <summary>The service which this resource belongs to.</summary>
private readonly Google.Apis.Services.IClientService service;
/// <summary>Constructs a new resource.</summary>
public MetricsResource(Google.Apis.Services.IClientService service)
{
this.service = service;
}
/// <summary>List the metadata for the metrics available to this AdExchange account.</summary>
/// <param name="accountId">Account with visibility to the metrics.</param>
public virtual ListRequest List(string accountId)
{
return new ListRequest(service, accountId);
}
/// <summary>List the metadata for the metrics available to this AdExchange account.</summary>
public class ListRequest : AdExchangeSellerBaseServiceRequest<Google.Apis.AdExchangeSeller.v2_0.Data.Metadata>
{
/// <summary>Constructs a new List request.</summary>
public ListRequest(Google.Apis.Services.IClientService service, string accountId)
: base(service)
{
AccountId = accountId;
InitParameters();
}
/// <summary>Account with visibility to the metrics.</summary>
[Google.Apis.Util.RequestParameterAttribute("accountId", Google.Apis.Util.RequestParameterType.Path)]
public virtual string AccountId { get; private set; }
///<summary>Gets the method name.</summary>
public override string MethodName
{
get { return "list"; }
}
///<summary>Gets the HTTP method.</summary>
public override string HttpMethod
{
get { return "GET"; }
}
///<summary>Gets the REST path.</summary>
public override string RestPath
{
get { return "accounts/{accountId}/metadata/metrics"; }
}
/// <summary>Initializes List parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add(
"accountId", new Google.Apis.Discovery.Parameter
{
Name = "accountId",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = null,
});
}
}
}
}
private readonly PreferreddealsResource preferreddeals;
/// <summary>Gets the Preferreddeals resource.</summary>
public virtual PreferreddealsResource Preferreddeals
{
get { return preferreddeals; }
}
/// <summary>The "preferreddeals" collection of methods.</summary>
public class PreferreddealsResource
{
private const string Resource = "preferreddeals";
/// <summary>The service which this resource belongs to.</summary>
private readonly Google.Apis.Services.IClientService service;
/// <summary>Constructs a new resource.</summary>
public PreferreddealsResource(Google.Apis.Services.IClientService service)
{
this.service = service;
}
/// <summary>Get information about the selected Ad Exchange Preferred Deal.</summary>
/// <param name="accountId">Account owning the deal.</param>
/// <param name="dealId">Preferred deal to get
/// information about.</param>
public virtual GetRequest Get(string accountId, string dealId)
{
return new GetRequest(service, accountId, dealId);
}
/// <summary>Get information about the selected Ad Exchange Preferred Deal.</summary>
public class GetRequest : AdExchangeSellerBaseServiceRequest<Google.Apis.AdExchangeSeller.v2_0.Data.PreferredDeal>
{
/// <summary>Constructs a new Get request.</summary>
public GetRequest(Google.Apis.Services.IClientService service, string accountId, string dealId)
: base(service)
{
AccountId = accountId;
DealId = dealId;
InitParameters();
}
/// <summary>Account owning the deal.</summary>
[Google.Apis.Util.RequestParameterAttribute("accountId", Google.Apis.Util.RequestParameterType.Path)]
public virtual string AccountId { get; private set; }
/// <summary>Preferred deal to get information about.</summary>
[Google.Apis.Util.RequestParameterAttribute("dealId", Google.Apis.Util.RequestParameterType.Path)]
public virtual string DealId { get; private set; }
///<summary>Gets the method name.</summary>
public override string MethodName
{
get { return "get"; }
}
///<summary>Gets the HTTP method.</summary>
public override string HttpMethod
{
get { return "GET"; }
}
///<summary>Gets the REST path.</summary>
public override string RestPath
{
get { return "accounts/{accountId}/preferreddeals/{dealId}"; }
}
/// <summary>Initializes Get parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add(
"accountId", new Google.Apis.Discovery.Parameter
{
Name = "accountId",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"dealId", new Google.Apis.Discovery.Parameter
{
Name = "dealId",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = null,
});
}
}
/// <summary>List the preferred deals for this Ad Exchange account.</summary>
/// <param name="accountId">Account owning the deals.</param>
public virtual ListRequest List(string accountId)
{
return new ListRequest(service, accountId);
}
/// <summary>List the preferred deals for this Ad Exchange account.</summary>
public class ListRequest : AdExchangeSellerBaseServiceRequest<Google.Apis.AdExchangeSeller.v2_0.Data.PreferredDeals>
{
/// <summary>Constructs a new List request.</summary>
public ListRequest(Google.Apis.Services.IClientService service, string accountId)
: base(service)
{
AccountId = accountId;
InitParameters();
}
/// <summary>Account owning the deals.</summary>
[Google.Apis.Util.RequestParameterAttribute("accountId", Google.Apis.Util.RequestParameterType.Path)]
public virtual string AccountId { get; private set; }
///<summary>Gets the method name.</summary>
public override string MethodName
{
get { return "list"; }
}
///<summary>Gets the HTTP method.</summary>
public override string HttpMethod
{
get { return "GET"; }
}
///<summary>Gets the REST path.</summary>
public override string RestPath
{
get { return "accounts/{accountId}/preferreddeals"; }
}
/// <summary>Initializes List parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add(
"accountId", new Google.Apis.Discovery.Parameter
{
Name = "accountId",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = null,
});
}
}
}
private readonly ReportsResource reports;
/// <summary>Gets the Reports resource.</summary>
public virtual ReportsResource Reports
{
get { return reports; }
}
/// <summary>The "reports" collection of methods.</summary>
public class ReportsResource
{
private const string Resource = "reports";
/// <summary>The service which this resource belongs to.</summary>
private readonly Google.Apis.Services.IClientService service;
/// <summary>Constructs a new resource.</summary>
public ReportsResource(Google.Apis.Services.IClientService service)
{
this.service = service;
saved = new SavedResource(service);
}
private readonly SavedResource saved;
/// <summary>Gets the Saved resource.</summary>
public virtual SavedResource Saved
{
get { return saved; }
}
/// <summary>The "saved" collection of methods.</summary>
public class SavedResource
{
private const string Resource = "saved";
/// <summary>The service which this resource belongs to.</summary>
private readonly Google.Apis.Services.IClientService service;
/// <summary>Constructs a new resource.</summary>
public SavedResource(Google.Apis.Services.IClientService service)
{
this.service = service;
}
/// <summary>Generate an Ad Exchange report based on the saved report ID sent in the query
/// parameters.</summary>
/// <param name="accountId">Account owning the saved report.</param>
/// <param name="savedReportId">The saved
/// report to retrieve.</param>
public virtual GenerateRequest Generate(string accountId, string savedReportId)
{
return new GenerateRequest(service, accountId, savedReportId);
}
/// <summary>Generate an Ad Exchange report based on the saved report ID sent in the query
/// parameters.</summary>
public class GenerateRequest : AdExchangeSellerBaseServiceRequest<Google.Apis.AdExchangeSeller.v2_0.Data.Report>
{
/// <summary>Constructs a new Generate request.</summary>
public GenerateRequest(Google.Apis.Services.IClientService service, string accountId, string savedReportId)
: base(service)
{
AccountId = accountId;
SavedReportId = savedReportId;
InitParameters();
}
/// <summary>Account owning the saved report.</summary>
[Google.Apis.Util.RequestParameterAttribute("accountId", Google.Apis.Util.RequestParameterType.Path)]
public virtual string AccountId { get; private set; }
/// <summary>The saved report to retrieve.</summary>
[Google.Apis.Util.RequestParameterAttribute("savedReportId", Google.Apis.Util.RequestParameterType.Path)]
public virtual string SavedReportId { get; private set; }
/// <summary>Optional locale to use for translating report output to a local language. Defaults to
/// "en_US" if not specified.</summary>
[Google.Apis.Util.RequestParameterAttribute("locale", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Locale { get; set; }
/// <summary>The maximum number of rows of report data to return.</summary>
/// [minimum: 0]
/// [maximum: 50000]
[Google.Apis.Util.RequestParameterAttribute("maxResults", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<int> MaxResults { get; set; }
/// <summary>Index of the first row of report data to return.</summary>
/// [minimum: 0]
/// [maximum: 5000]
[Google.Apis.Util.RequestParameterAttribute("startIndex", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<int> StartIndex { get; set; }
///<summary>Gets the method name.</summary>
public override string MethodName
{
get { return "generate"; }
}
///<summary>Gets the HTTP method.</summary>
public override string HttpMethod
{
get { return "GET"; }
}
///<summary>Gets the REST path.</summary>
public override string RestPath
{
get { return "accounts/{accountId}/reports/{savedReportId}"; }
}
/// <summary>Initializes Generate parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add(
"accountId", new Google.Apis.Discovery.Parameter
{
Name = "accountId",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"savedReportId", new Google.Apis.Discovery.Parameter
{
Name = "savedReportId",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"locale", new Google.Apis.Discovery.Parameter
{
Name = "locale",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = @"[a-zA-Z_]+",
});
RequestParameters.Add(
"maxResults", new Google.Apis.Discovery.Parameter
{
Name = "maxResults",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"startIndex", new Google.Apis.Discovery.Parameter
{
Name = "startIndex",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
/// <summary>List all saved reports in this Ad Exchange account.</summary>
/// <param name="accountId">Account owning the saved reports.</param>
public virtual ListRequest List(string accountId)
{
return new ListRequest(service, accountId);
}
/// <summary>List all saved reports in this Ad Exchange account.</summary>
public class ListRequest : AdExchangeSellerBaseServiceRequest<Google.Apis.AdExchangeSeller.v2_0.Data.SavedReports>
{
/// <summary>Constructs a new List request.</summary>
public ListRequest(Google.Apis.Services.IClientService service, string accountId)
: base(service)
{
AccountId = accountId;
InitParameters();
}
/// <summary>Account owning the saved reports.</summary>
[Google.Apis.Util.RequestParameterAttribute("accountId", Google.Apis.Util.RequestParameterType.Path)]
public virtual string AccountId { get; private set; }
/// <summary>The maximum number of saved reports to include in the response, used for
/// paging.</summary>
/// [minimum: 0]
/// [maximum: 100]
[Google.Apis.Util.RequestParameterAttribute("maxResults", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<int> MaxResults { get; set; }
/// <summary>A continuation token, used to page through saved reports. To retrieve the next page,
/// set this parameter to the value of "nextPageToken" from the previous response.</summary>
[Google.Apis.Util.RequestParameterAttribute("pageToken", Google.Apis.Util.RequestParameterType.Query)]
public virtual string PageToken { get; set; }
///<summary>Gets the method name.</summary>
public override string MethodName
{
get { return "list"; }
}
///<summary>Gets the HTTP method.</summary>
public override string HttpMethod
{
get { return "GET"; }
}
///<summary>Gets the REST path.</summary>
public override string RestPath
{
get { return "accounts/{accountId}/reports/saved"; }
}
/// <summary>Initializes List parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add(
"accountId", new Google.Apis.Discovery.Parameter
{
Name = "accountId",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"maxResults", new Google.Apis.Discovery.Parameter
{
Name = "maxResults",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"pageToken", new Google.Apis.Discovery.Parameter
{
Name = "pageToken",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
}
/// <summary>Generate an Ad Exchange report based on the report request sent in the query parameters.
/// Returns the result as JSON; to retrieve output in CSV format specify "alt=csv" as a query
/// parameter.</summary>
/// <param name="accountId">Account which owns the generated report.</param>
/// <param name="startDate">Start of
/// the date range to report on in "YYYY-MM-DD" format, inclusive.</param>
/// <param name="endDate">End of the date
/// range to report on in "YYYY-MM-DD" format, inclusive.</param>
public virtual GenerateRequest Generate(string accountId, string startDate, string endDate)
{
return new GenerateRequest(service, accountId, startDate, endDate);
}
/// <summary>Generate an Ad Exchange report based on the report request sent in the query parameters.
/// Returns the result as JSON; to retrieve output in CSV format specify "alt=csv" as a query
/// parameter.</summary>
public class GenerateRequest : AdExchangeSellerBaseServiceRequest<Google.Apis.AdExchangeSeller.v2_0.Data.Report>
{
/// <summary>Constructs a new Generate request.</summary>
public GenerateRequest(Google.Apis.Services.IClientService service, string accountId, string startDate, string endDate)
: base(service)
{
AccountId = accountId;
StartDate = startDate;
EndDate = endDate;
MediaDownloader = new Google.Apis.Download.MediaDownloader(service);
InitParameters();
}
/// <summary>Account which owns the generated report.</summary>
[Google.Apis.Util.RequestParameterAttribute("accountId", Google.Apis.Util.RequestParameterType.Path)]
public virtual string AccountId { get; private set; }
/// <summary>Start of the date range to report on in "YYYY-MM-DD" format, inclusive.</summary>
[Google.Apis.Util.RequestParameterAttribute("startDate", Google.Apis.Util.RequestParameterType.Query)]
public virtual string StartDate { get; private set; }
/// <summary>End of the date range to report on in "YYYY-MM-DD" format, inclusive.</summary>
[Google.Apis.Util.RequestParameterAttribute("endDate", Google.Apis.Util.RequestParameterType.Query)]
public virtual string EndDate { get; private set; }
/// <summary>Dimensions to base the report on.</summary>
[Google.Apis.Util.RequestParameterAttribute("dimension", Google.Apis.Util.RequestParameterType.Query)]
public virtual Google.Apis.Util.Repeatable<string> Dimension { get; set; }
/// <summary>Filters to be run on the report.</summary>
[Google.Apis.Util.RequestParameterAttribute("filter", Google.Apis.Util.RequestParameterType.Query)]
public virtual Google.Apis.Util.Repeatable<string> Filter { get; set; }
/// <summary>Optional locale to use for translating report output to a local language. Defaults to
/// "en_US" if not specified.</summary>
[Google.Apis.Util.RequestParameterAttribute("locale", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Locale { get; set; }
/// <summary>The maximum number of rows of report data to return.</summary>
/// [minimum: 0]
/// [maximum: 50000]
[Google.Apis.Util.RequestParameterAttribute("maxResults", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<long> MaxResults { get; set; }
/// <summary>Numeric columns to include in the report.</summary>
[Google.Apis.Util.RequestParameterAttribute("metric", Google.Apis.Util.RequestParameterType.Query)]
public virtual Google.Apis.Util.Repeatable<string> Metric { get; set; }
/// <summary>The name of a dimension or metric to sort the resulting report on, optionally prefixed with
/// "+" to sort ascending or "-" to sort descending. If no prefix is specified, the column is sorted
/// ascending.</summary>
[Google.Apis.Util.RequestParameterAttribute("sort", Google.Apis.Util.RequestParameterType.Query)]
public virtual Google.Apis.Util.Repeatable<string> Sort { get; set; }
/// <summary>Index of the first row of report data to return.</summary>
/// [minimum: 0]
/// [maximum: 5000]
[Google.Apis.Util.RequestParameterAttribute("startIndex", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<long> StartIndex { get; set; }
///<summary>Gets the method name.</summary>
public override string MethodName
{
get { return "generate"; }
}
///<summary>Gets the HTTP method.</summary>
public override string HttpMethod
{
get { return "GET"; }
}
///<summary>Gets the REST path.</summary>
public override string RestPath
{
get { return "accounts/{accountId}/reports"; }
}
/// <summary>Initializes Generate parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add(
"accountId", new Google.Apis.Discovery.Parameter
{
Name = "accountId",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"startDate", new Google.Apis.Discovery.Parameter
{
Name = "startDate",
IsRequired = true,
ParameterType = "query",
DefaultValue = null,
Pattern = @"\d{4}-\d{2}-\d{2}|(today|startOfMonth|startOfYear)(([\-\+]\d+[dwmy]){0,3}?)",
});
RequestParameters.Add(
"endDate", new Google.Apis.Discovery.Parameter
{
Name = "endDate",
IsRequired = true,
ParameterType = "query",
DefaultValue = null,
Pattern = @"\d{4}-\d{2}-\d{2}|(today|startOfMonth|startOfYear)(([\-\+]\d+[dwmy]){0,3}?)",
});
RequestParameters.Add(
"dimension", new Google.Apis.Discovery.Parameter
{
Name = "dimension",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = @"[a-zA-Z_]+",
});
RequestParameters.Add(
"filter", new Google.Apis.Discovery.Parameter
{
Name = "filter",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = @"[a-zA-Z_]+(==|=@).+",
});
RequestParameters.Add(
"locale", new Google.Apis.Discovery.Parameter
{
Name = "locale",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = @"[a-zA-Z_]+",
});
RequestParameters.Add(
"maxResults", new Google.Apis.Discovery.Parameter
{
Name = "maxResults",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"metric", new Google.Apis.Discovery.Parameter
{
Name = "metric",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = @"[a-zA-Z_]+",
});
RequestParameters.Add(
"sort", new Google.Apis.Discovery.Parameter
{
Name = "sort",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = @"(\+|-)?[a-zA-Z_]+",
});
RequestParameters.Add(
"startIndex", new Google.Apis.Discovery.Parameter
{
Name = "startIndex",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
/// <summary>Gets the media downloader.</summary>
public Google.Apis.Download.IMediaDownloader MediaDownloader { get; private set; }
/// <summary>
/// <para>Synchronously download the media into the given stream.</para>
/// <para>Warning: This method hides download errors; use <see cref="DownloadWithStatus"/> instead.</para>
/// </summary>
public virtual void Download(System.IO.Stream stream)
{
MediaDownloader.Download(this.GenerateRequestUri(), stream);
}
/// <summary>Synchronously download the media into the given stream.</summary>
/// <returns>The final status of the download; including whether the download succeeded or failed.</returns>
public virtual Google.Apis.Download.IDownloadProgress DownloadWithStatus(System.IO.Stream stream)
{
return MediaDownloader.Download(this.GenerateRequestUri(), stream);
}
/// <summary>Asynchronously download the media into the given stream.</summary>
public virtual System.Threading.Tasks.Task<Google.Apis.Download.IDownloadProgress> DownloadAsync(System.IO.Stream stream)
{
return MediaDownloader.DownloadAsync(this.GenerateRequestUri(), stream);
}
/// <summary>Asynchronously download the media into the given stream.</summary>
public virtual System.Threading.Tasks.Task<Google.Apis.Download.IDownloadProgress> DownloadAsync(System.IO.Stream stream,
System.Threading.CancellationToken cancellationToken)
{
return MediaDownloader.DownloadAsync(this.GenerateRequestUri(), stream, cancellationToken);
}
#if !NET40
/// <summary>Synchronously download a range of the media into the given stream.</summary>
public virtual Google.Apis.Download.IDownloadProgress DownloadRange(System.IO.Stream stream, System.Net.Http.Headers.RangeHeaderValue range)
{
var mediaDownloader = new Google.Apis.Download.MediaDownloader(Service);
mediaDownloader.Range = range;
return mediaDownloader.Download(this.GenerateRequestUri(), stream);
}
/// <summary>Asynchronously download a range of the media into the given stream.</summary>
public virtual System.Threading.Tasks.Task<Google.Apis.Download.IDownloadProgress> DownloadRangeAsync(System.IO.Stream stream,
System.Net.Http.Headers.RangeHeaderValue range,
System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
var mediaDownloader = new Google.Apis.Download.MediaDownloader(Service);
mediaDownloader.Range = range;
return mediaDownloader.DownloadAsync(this.GenerateRequestUri(), stream, cancellationToken);
}
#endif
}
}
private readonly UrlchannelsResource urlchannels;
/// <summary>Gets the Urlchannels resource.</summary>
public virtual UrlchannelsResource Urlchannels
{
get { return urlchannels; }
}
/// <summary>The "urlchannels" collection of methods.</summary>
public class UrlchannelsResource
{
private const string Resource = "urlchannels";
/// <summary>The service which this resource belongs to.</summary>
private readonly Google.Apis.Services.IClientService service;
/// <summary>Constructs a new resource.</summary>
public UrlchannelsResource(Google.Apis.Services.IClientService service)
{
this.service = service;
}
/// <summary>List all URL channels in the specified ad client for this Ad Exchange account.</summary>
/// <param name="accountId">Account to which the ad client belongs.</param>
/// <param name="adClientId">Ad client
/// for which to list URL channels.</param>
public virtual ListRequest List(string accountId, string adClientId)
{
return new ListRequest(service, accountId, adClientId);
}
/// <summary>List all URL channels in the specified ad client for this Ad Exchange account.</summary>
public class ListRequest : AdExchangeSellerBaseServiceRequest<Google.Apis.AdExchangeSeller.v2_0.Data.UrlChannels>
{
/// <summary>Constructs a new List request.</summary>
public ListRequest(Google.Apis.Services.IClientService service, string accountId, string adClientId)
: base(service)
{
AccountId = accountId;
AdClientId = adClientId;
InitParameters();
}
/// <summary>Account to which the ad client belongs.</summary>
[Google.Apis.Util.RequestParameterAttribute("accountId", Google.Apis.Util.RequestParameterType.Path)]
public virtual string AccountId { get; private set; }
/// <summary>Ad client for which to list URL channels.</summary>
[Google.Apis.Util.RequestParameterAttribute("adClientId", Google.Apis.Util.RequestParameterType.Path)]
public virtual string AdClientId { get; private set; }
/// <summary>The maximum number of URL channels to include in the response, used for paging.</summary>
/// [minimum: 0]
/// [maximum: 10000]
[Google.Apis.Util.RequestParameterAttribute("maxResults", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<long> MaxResults { get; set; }
/// <summary>A continuation token, used to page through URL channels. To retrieve the next page, set
/// this parameter to the value of "nextPageToken" from the previous response.</summary>
[Google.Apis.Util.RequestParameterAttribute("pageToken", Google.Apis.Util.RequestParameterType.Query)]
public virtual string PageToken { get; set; }
///<summary>Gets the method name.</summary>
public override string MethodName
{
get { return "list"; }
}
///<summary>Gets the HTTP method.</summary>
public override string HttpMethod
{
get { return "GET"; }
}
///<summary>Gets the REST path.</summary>
public override string RestPath
{
get { return "accounts/{accountId}/adclients/{adClientId}/urlchannels"; }
}
/// <summary>Initializes List parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add(
"accountId", new Google.Apis.Discovery.Parameter
{
Name = "accountId",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"adClientId", new Google.Apis.Discovery.Parameter
{
Name = "adClientId",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"maxResults", new Google.Apis.Discovery.Parameter
{
Name = "maxResults",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"pageToken", new Google.Apis.Discovery.Parameter
{
Name = "pageToken",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
}
/// <summary>Get information about the selected Ad Exchange account.</summary>
/// <param name="accountId">Account to get information about. Tip: 'myaccount' is a valid ID.</param>
public virtual GetRequest Get(string accountId)
{
return new GetRequest(service, accountId);
}
/// <summary>Get information about the selected Ad Exchange account.</summary>
public class GetRequest : AdExchangeSellerBaseServiceRequest<Google.Apis.AdExchangeSeller.v2_0.Data.Account>
{
/// <summary>Constructs a new Get request.</summary>
public GetRequest(Google.Apis.Services.IClientService service, string accountId)
: base(service)
{
AccountId = accountId;
InitParameters();
}
/// <summary>Account to get information about. Tip: 'myaccount' is a valid ID.</summary>
[Google.Apis.Util.RequestParameterAttribute("accountId", Google.Apis.Util.RequestParameterType.Path)]
public virtual string AccountId { get; private set; }
///<summary>Gets the method name.</summary>
public override string MethodName
{
get { return "get"; }
}
///<summary>Gets the HTTP method.</summary>
public override string HttpMethod
{
get { return "GET"; }
}
///<summary>Gets the REST path.</summary>
public override string RestPath
{
get { return "accounts/{accountId}"; }
}
/// <summary>Initializes Get parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add(
"accountId", new Google.Apis.Discovery.Parameter
{
Name = "accountId",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = null,
});
}
}
/// <summary>List all accounts available to this Ad Exchange account.</summary>
public virtual ListRequest List()
{
return new ListRequest(service);
}
/// <summary>List all accounts available to this Ad Exchange account.</summary>
public class ListRequest : AdExchangeSellerBaseServiceRequest<Google.Apis.AdExchangeSeller.v2_0.Data.Accounts>
{
/// <summary>Constructs a new List request.</summary>
public ListRequest(Google.Apis.Services.IClientService service)
: base(service)
{
InitParameters();
}
/// <summary>The maximum number of accounts to include in the response, used for paging.</summary>
/// [minimum: 0]
/// [maximum: 10000]
[Google.Apis.Util.RequestParameterAttribute("maxResults", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<int> MaxResults { get; set; }
/// <summary>A continuation token, used to page through accounts. To retrieve the next page, set this
/// parameter to the value of "nextPageToken" from the previous response.</summary>
[Google.Apis.Util.RequestParameterAttribute("pageToken", Google.Apis.Util.RequestParameterType.Query)]
public virtual string PageToken { get; set; }
///<summary>Gets the method name.</summary>
public override string MethodName
{
get { return "list"; }
}
///<summary>Gets the HTTP method.</summary>
public override string HttpMethod
{
get { return "GET"; }
}
///<summary>Gets the REST path.</summary>
public override string RestPath
{
get { return "accounts"; }
}
/// <summary>Initializes List parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add(
"maxResults", new Google.Apis.Discovery.Parameter
{
Name = "maxResults",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"pageToken", new Google.Apis.Discovery.Parameter
{
Name = "pageToken",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
}
}
namespace Google.Apis.AdExchangeSeller.v2_0.Data
{
public class Account : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Unique identifier of this account.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("id")]
public virtual string Id { get; set; }
/// <summary>Kind of resource this is, in this case adexchangeseller#account.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("kind")]
public virtual string Kind { get; set; }
/// <summary>Name of this account.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("name")]
public virtual string Name { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
public class Accounts : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>ETag of this response for caching purposes.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("etag")]
public virtual string ETag { get; set; }
/// <summary>The accounts returned in this list response.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("items")]
public virtual System.Collections.Generic.IList<Account> Items { get; set; }
/// <summary>Kind of list this is, in this case adexchangeseller#accounts.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("kind")]
public virtual string Kind { get; set; }
/// <summary>Continuation token used to page through accounts. To retrieve the next page of results, set the
/// next request's "pageToken" value to this.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("nextPageToken")]
public virtual string NextPageToken { get; set; }
}
public class AdClient : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Whether this ad client is opted in to ARC.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("arcOptIn")]
public virtual System.Nullable<bool> ArcOptIn { get; set; }
/// <summary>Unique identifier of this ad client.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("id")]
public virtual string Id { get; set; }
/// <summary>Kind of resource this is, in this case adexchangeseller#adClient.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("kind")]
public virtual string Kind { get; set; }
/// <summary>This ad client's product code, which corresponds to the PRODUCT_CODE report dimension.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("productCode")]
public virtual string ProductCode { get; set; }
/// <summary>Whether this ad client supports being reported on.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("supportsReporting")]
public virtual System.Nullable<bool> SupportsReporting { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
public class AdClients : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>ETag of this response for caching purposes.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("etag")]
public virtual string ETag { get; set; }
/// <summary>The ad clients returned in this list response.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("items")]
public virtual System.Collections.Generic.IList<AdClient> Items { get; set; }
/// <summary>Kind of list this is, in this case adexchangeseller#adClients.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("kind")]
public virtual string Kind { get; set; }
/// <summary>Continuation token used to page through ad clients. To retrieve the next page of results, set the
/// next request's "pageToken" value to this.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("nextPageToken")]
public virtual string NextPageToken { get; set; }
}
public class Alert : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Unique identifier of this alert. This should be considered an opaque identifier; it is not safe to
/// rely on it being in any particular format.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("id")]
public virtual string Id { get; set; }
/// <summary>Kind of resource this is, in this case adexchangeseller#alert.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("kind")]
public virtual string Kind { get; set; }
/// <summary>The localized alert message.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("message")]
public virtual string Message { get; set; }
/// <summary>Severity of this alert. Possible values: INFO, WARNING, SEVERE.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("severity")]
public virtual string Severity { get; set; }
/// <summary>Type of this alert. Possible values: SELF_HOLD, MIGRATED_TO_BILLING3, ADDRESS_PIN_VERIFICATION,
/// PHONE_PIN_VERIFICATION, CORPORATE_ENTITY, GRAYLISTED_PUBLISHER, API_HOLD.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("type")]
public virtual string Type { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
public class Alerts : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The alerts returned in this list response.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("items")]
public virtual System.Collections.Generic.IList<Alert> Items { get; set; }
/// <summary>Kind of list this is, in this case adexchangeseller#alerts.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("kind")]
public virtual string Kind { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
public class CustomChannel : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Code of this custom channel, not necessarily unique across ad clients.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("code")]
public virtual string Code { get; set; }
/// <summary>Unique identifier of this custom channel. This should be considered an opaque identifier; it is not
/// safe to rely on it being in any particular format.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("id")]
public virtual string Id { get; set; }
/// <summary>Kind of resource this is, in this case adexchangeseller#customChannel.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("kind")]
public virtual string Kind { get; set; }
/// <summary>Name of this custom channel.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("name")]
public virtual string Name { get; set; }
/// <summary>The targeting information of this custom channel, if activated.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("targetingInfo")]
public virtual CustomChannel.TargetingInfoData TargetingInfo { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
/// <summary>The targeting information of this custom channel, if activated.</summary>
public class TargetingInfoData
{
/// <summary>The name used to describe this channel externally.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("adsAppearOn")]
public virtual string AdsAppearOn { get; set; }
/// <summary>The external description of the channel.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("description")]
public virtual string Description { get; set; }
/// <summary>The locations in which ads appear. (Only valid for content and mobile content ads). Acceptable
/// values for content ads are: TOP_LEFT, TOP_CENTER, TOP_RIGHT, MIDDLE_LEFT, MIDDLE_CENTER, MIDDLE_RIGHT,
/// BOTTOM_LEFT, BOTTOM_CENTER, BOTTOM_RIGHT, MULTIPLE_LOCATIONS. Acceptable values for mobile content ads
/// are: TOP, MIDDLE, BOTTOM, MULTIPLE_LOCATIONS.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("location")]
public virtual string Location { get; set; }
/// <summary>The language of the sites ads will be displayed on.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("siteLanguage")]
public virtual string SiteLanguage { get; set; }
}
}
public class CustomChannels : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>ETag of this response for caching purposes.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("etag")]
public virtual string ETag { get; set; }
/// <summary>The custom channels returned in this list response.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("items")]
public virtual System.Collections.Generic.IList<CustomChannel> Items { get; set; }
/// <summary>Kind of list this is, in this case adexchangeseller#customChannels.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("kind")]
public virtual string Kind { get; set; }
/// <summary>Continuation token used to page through custom channels. To retrieve the next page of results, set
/// the next request's "pageToken" value to this.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("nextPageToken")]
public virtual string NextPageToken { get; set; }
}
public class Metadata : Google.Apis.Requests.IDirectResponseSchema
{
[Newtonsoft.Json.JsonPropertyAttribute("items")]
public virtual System.Collections.Generic.IList<ReportingMetadataEntry> Items { get; set; }
/// <summary>Kind of list this is, in this case adexchangeseller#metadata.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("kind")]
public virtual string Kind { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
public class PreferredDeal : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The name of the advertiser this deal is for.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("advertiserName")]
public virtual string AdvertiserName { get; set; }
/// <summary>The name of the buyer network this deal is for.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("buyerNetworkName")]
public virtual string BuyerNetworkName { get; set; }
/// <summary>The currency code that applies to the fixed_cpm value. If not set then assumed to be USD.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("currencyCode")]
public virtual string CurrencyCode { get; set; }
/// <summary>Time when this deal stops being active in seconds since the epoch (GMT). If not set then this deal
/// is valid until manually disabled by the publisher.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("endTime")]
public virtual System.Nullable<ulong> EndTime { get; set; }
/// <summary>The fixed price for this preferred deal. In cpm micros of currency according to currencyCode. If
/// set, then this preferred deal is eligible for the fixed price tier of buying (highest priority, pay exactly
/// the configured fixed price).</summary>
[Newtonsoft.Json.JsonPropertyAttribute("fixedCpm")]
public virtual System.Nullable<long> FixedCpm { get; set; }
/// <summary>Unique identifier of this preferred deal.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("id")]
public virtual System.Nullable<long> Id { get; set; }
/// <summary>Kind of resource this is, in this case adexchangeseller#preferredDeal.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("kind")]
public virtual string Kind { get; set; }
/// <summary>Time when this deal becomes active in seconds since the epoch (GMT). If not set then this deal is
/// active immediately upon creation.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("startTime")]
public virtual System.Nullable<ulong> StartTime { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
public class PreferredDeals : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The preferred deals returned in this list response.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("items")]
public virtual System.Collections.Generic.IList<PreferredDeal> Items { get; set; }
/// <summary>Kind of list this is, in this case adexchangeseller#preferredDeals.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("kind")]
public virtual string Kind { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
public class Report : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The averages of the report. This is the same length as any other row in the report; cells
/// corresponding to dimension columns are empty.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("averages")]
public virtual System.Collections.Generic.IList<string> Averages { get; set; }
/// <summary>The header information of the columns requested in the report. This is a list of headers; one for
/// each dimension in the request, followed by one for each metric in the request.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("headers")]
public virtual System.Collections.Generic.IList<Report.HeadersData> Headers { get; set; }
/// <summary>Kind this is, in this case adexchangeseller#report.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("kind")]
public virtual string Kind { get; set; }
/// <summary>The output rows of the report. Each row is a list of cells; one for each dimension in the request,
/// followed by one for each metric in the request. The dimension cells contain strings, and the metric cells
/// contain numbers.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("rows")]
public virtual System.Collections.Generic.IList<System.Collections.Generic.IList<string>> Rows { get; set; }
/// <summary>The total number of rows matched by the report request. Fewer rows may be returned in the response
/// due to being limited by the row count requested or the report row limit.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("totalMatchedRows")]
public virtual System.Nullable<long> TotalMatchedRows { get; set; }
/// <summary>The totals of the report. This is the same length as any other row in the report; cells
/// corresponding to dimension columns are empty.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("totals")]
public virtual System.Collections.Generic.IList<string> Totals { get; set; }
/// <summary>Any warnings associated with generation of the report.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("warnings")]
public virtual System.Collections.Generic.IList<string> Warnings { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
public class HeadersData
{
/// <summary>The currency of this column. Only present if the header type is METRIC_CURRENCY.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("currency")]
public virtual string Currency { get; set; }
/// <summary>The name of the header.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("name")]
public virtual string Name { get; set; }
/// <summary>The type of the header; one of DIMENSION, METRIC_TALLY, METRIC_RATIO, or
/// METRIC_CURRENCY.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("type")]
public virtual string Type { get; set; }
}
}
public class ReportingMetadataEntry : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>For metrics this is a list of dimension IDs which the metric is compatible with, for dimensions it
/// is a list of compatibility groups the dimension belongs to.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("compatibleDimensions")]
public virtual System.Collections.Generic.IList<string> CompatibleDimensions { get; set; }
/// <summary>The names of the metrics the dimension or metric this reporting metadata entry describes is
/// compatible with.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("compatibleMetrics")]
public virtual System.Collections.Generic.IList<string> CompatibleMetrics { get; set; }
/// <summary>Unique identifier of this reporting metadata entry, corresponding to the name of the appropriate
/// dimension or metric.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("id")]
public virtual string Id { get; set; }
/// <summary>Kind of resource this is, in this case adexchangeseller#reportingMetadataEntry.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("kind")]
public virtual string Kind { get; set; }
/// <summary>The names of the dimensions which the dimension or metric this reporting metadata entry describes
/// requires to also be present in order for the report to be valid. Omitting these will not cause an error or
/// warning, but may result in data which cannot be correctly interpreted.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("requiredDimensions")]
public virtual System.Collections.Generic.IList<string> RequiredDimensions { get; set; }
/// <summary>The names of the metrics which the dimension or metric this reporting metadata entry describes
/// requires to also be present in order for the report to be valid. Omitting these will not cause an error or
/// warning, but may result in data which cannot be correctly interpreted.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("requiredMetrics")]
public virtual System.Collections.Generic.IList<string> RequiredMetrics { get; set; }
/// <summary>The codes of the projects supported by the dimension or metric this reporting metadata entry
/// describes.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("supportedProducts")]
public virtual System.Collections.Generic.IList<string> SupportedProducts { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
public class SavedReport : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Unique identifier of this saved report.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("id")]
public virtual string Id { get; set; }
/// <summary>Kind of resource this is, in this case adexchangeseller#savedReport.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("kind")]
public virtual string Kind { get; set; }
/// <summary>This saved report's name.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("name")]
public virtual string Name { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
public class SavedReports : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>ETag of this response for caching purposes.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("etag")]
public virtual string ETag { get; set; }
/// <summary>The saved reports returned in this list response.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("items")]
public virtual System.Collections.Generic.IList<SavedReport> Items { get; set; }
/// <summary>Kind of list this is, in this case adexchangeseller#savedReports.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("kind")]
public virtual string Kind { get; set; }
/// <summary>Continuation token used to page through saved reports. To retrieve the next page of results, set
/// the next request's "pageToken" value to this.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("nextPageToken")]
public virtual string NextPageToken { get; set; }
}
public class UrlChannel : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Unique identifier of this URL channel. This should be considered an opaque identifier; it is not
/// safe to rely on it being in any particular format.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("id")]
public virtual string Id { get; set; }
/// <summary>Kind of resource this is, in this case adexchangeseller#urlChannel.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("kind")]
public virtual string Kind { get; set; }
/// <summary>URL Pattern of this URL channel. Does not include "http://" or "https://". Example:
/// www.example.com/home</summary>
[Newtonsoft.Json.JsonPropertyAttribute("urlPattern")]
public virtual string UrlPattern { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
public class UrlChannels : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>ETag of this response for caching purposes.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("etag")]
public virtual string ETag { get; set; }
/// <summary>The URL channels returned in this list response.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("items")]
public virtual System.Collections.Generic.IList<UrlChannel> Items { get; set; }
/// <summary>Kind of list this is, in this case adexchangeseller#urlChannels.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("kind")]
public virtual string Kind { get; set; }
/// <summary>Continuation token used to page through URL channels. To retrieve the next page of results, set the
/// next request's "pageToken" value to this.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("nextPageToken")]
public virtual string NextPageToken { get; set; }
}
}
| 45.134439 | 156 | 0.543089 | [
"Apache-2.0"
] | chrisdunelm/google-api-dotnet-client | Src/Generated/Google.Apis.AdExchangeSeller.v2_0/Google.Apis.AdExchangeSeller.v2_0.cs | 103,403 | 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("Extract Bit from Integer")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Extract Bit from Integer")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("da8f1d2b-9c8b-46aa-92c7-79549462677e")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 38.405405 | 84 | 0.74525 | [
"MIT"
] | milkokochev/Telerik | C#1/HomeWorks/03. Operators and Expressions/Extract Bit from Integer/Properties/AssemblyInfo.cs | 1,424 | C# |
/*
* MIT License
*
* Copyright(c) 2017 Jann Westermann
*
* 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.Collections.Generic;
namespace QuickIEnumerableToExcelExporter
{
/// <summary>
/// Describes the properties and functions of an Exporter which can be used to write data from
/// intermediate format to any target.
/// </summary>
internal interface IExporter
{
/// <summary>
/// Path to the result file
/// </summary>
string TargetPath { get; set; }
/// <summary>
/// The values to be exported (intermediate format)
/// </summary>
IEnumerable<ExportRow> Rows { get; set; }
/// <summary>
/// Writes the data to the target
/// </summary>
void Export();
}
} | 35.960784 | 98 | 0.688659 | [
"MIT"
] | chefarbeiter/QuickIEnumerableToExcelExporter | src/QuickIEnumerableToExcelExporter/IExporter.cs | 1,836 | C# |
#if UNITY_EDITOR
using UnityEngine;
using System.Collections.Generic;
namespace O3DWB
{
public static class Mirroring
{
#region Public Static Functions
public static Vector3 MirrorPosition(Plane mirrorPlane, Vector3 position)
{
float planeDistanceToPoint = mirrorPlane.GetDistanceToPoint(position);
return mirrorPlane.ProjectPoint(position) - planeDistanceToPoint * mirrorPlane.normal;
}
public static Vector3 MirrorNormal(Plane mirrorPlane, Vector3 normal)
{
Plane mirrorPlaneAtOrigin = new Plane(mirrorPlane.normal, 0.0f);
Vector3 mirroredNormal = MirrorPosition(mirrorPlaneAtOrigin, normal);
mirroredNormal.Normalize();
return mirroredNormal;
}
public static Vector3 MirrorVector(Plane mirrorPlane, Vector3 vector)
{
Plane mirrorPlaneAtOrigin = new Plane(mirrorPlane.normal, 0.0f);
Vector3 mirroredVector = MirrorPosition(mirrorPlaneAtOrigin, vector);
return mirroredVector;
}
public static OrientedBox MirrorOrientedBox(Plane mirrorPlane, OrientedBox orientedBox, bool mirrorRotation)
{
OrientedBox mirroredBox = new OrientedBox(orientedBox);
mirroredBox.AllowNegativeScale = true;
mirroredBox.Center = MirrorPosition(mirrorPlane, mirroredBox.Center);
if (mirrorRotation)
{
MirroredRotation mirroredRotation = MirrorMatrixRotation(mirrorPlane, mirroredBox.TransformMatrix);
mirroredBox.Rotation = mirroredRotation.Rotation;
mirroredBox.Scale = mirroredRotation.AxesScale;
}
return mirroredBox;
}
public static MirroredRotation MirrorMatrixRotation(Plane mirrorPlane, TransformMatrix rotationMatrix)
{
Vector3 axesScale = rotationMatrix.Scale;
Vector3 rightAxis = rotationMatrix.GetNormalizedRightAxisNoScaleSign();
Vector3 upAxis = rotationMatrix.GetNormalizedUpAxisNoScaleSign();
Vector3 lookAxis = rotationMatrix.GetNormalizedLookAxisNoScaleSign();
rightAxis = MirrorNormal(mirrorPlane, rightAxis);
upAxis = MirrorNormal(mirrorPlane, upAxis);
lookAxis = MirrorNormal(mirrorPlane, lookAxis);
Quaternion newRotation = Quaternion.LookRotation(lookAxis, upAxis);
Vector3 resultRightAxis = Vector3.Cross(upAxis, lookAxis);
bool pointsInSameDirection = resultRightAxis.IsPointingInSameGeneralDirection(rightAxis);
if (!pointsInSameDirection) axesScale[0] *= -1.0f;
return new MirroredRotation(newRotation, axesScale);
}
public static void MirrorTransformRotation(Plane mirrorPlane, Transform transform)
{
MirroredRotation mirroredRotation = MirrorMatrixRotation(mirrorPlane, transform.GetWorldMatrix());
transform.rotation = mirroredRotation.Rotation;
transform.SetWorldScale(mirroredRotation.AxesScale);
}
public static void MirrorObjectHierarchyTransform(Plane mirrorPlane, GameObject root, bool mirrorRotation)
{
Transform rootTransform = root.transform;
OrientedBox hierarchyWorldOrientedBox = root.GetHierarchyWorldOrientedBox();
if (!hierarchyWorldOrientedBox.IsValid()) return;
if (mirrorRotation) MirrorTransformRotation(mirrorPlane, rootTransform);
Vector3 mirroredCenter = MirrorPosition(mirrorPlane, hierarchyWorldOrientedBox.Center);
rootTransform.position = ObjectPositionCalculator.CalculateObjectHierarchyPosition(root, mirroredCenter, rootTransform.lossyScale, rootTransform.rotation);
}
#endregion
}
}
#endif | 42.285714 | 167 | 0.68659 | [
"MIT"
] | AestheticalZ/Faithful-SCP-Unity | Assets/Octave3D World Builder/Scripts/Math/Mirroring/Mirroring.cs | 3,850 | C# |
using System;
using System.IO;
namespace BinaryReaderDemo
{
class Program
{
static void Main(string[] args)
{
}
}
}
| 11.928571 | 39 | 0.508982 | [
"MIT"
] | StelaKaneva/Csharp-Advanced-Repository | Streams,FilesAndDirectoriesLab/BinaryReaderDemo/Program.cs | 169 | C# |
/*
The MIT License (MIT)
Copyright (c) 2007 - 2021 Microting A/S
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.
*/
namespace Inventory.Pn.Services.InventoryItemGroupService
{
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Infrastructure.Models.ItemGroup;
using InventoryLocalizationService;
using Microsoft.EntityFrameworkCore;
using Microting.eForm.Infrastructure.Constants;
using Microting.eFormApi.BasePn.Abstractions;
using Microting.eFormApi.BasePn.Infrastructure.Extensions;
using Microting.eFormApi.BasePn.Infrastructure.Helpers;
using Microting.eFormApi.BasePn.Infrastructure.Models.API;
using Microting.eFormApi.BasePn.Infrastructure.Models.Common;
using Microting.eFormInventoryBase.Infrastructure.Data;
using Microting.eFormInventoryBase.Infrastructure.Data.Entities;
public class InventoryItemGroupService: IInventoryItemGroupService
{
private readonly InventoryPnDbContext _dbContext;
private readonly IInventoryLocalizationService _inventoryLocalizationService;
private readonly IUserService _userService;
//private readonly IEFormCoreService _coreService;
public InventoryItemGroupService(
InventoryPnDbContext dbContext,
IInventoryLocalizationService inventoryLocalizationService,
IUserService userService/*,
IEFormCoreService coreService*/)
{
_userService = userService;
_inventoryLocalizationService = inventoryLocalizationService;
//_coreService = coreService;
_dbContext = dbContext;
}
public async Task<OperationDataResult<Paged<ItemGroupModel>>> GetItemGroups(ItemGroupRequestModel itemGroupRequestModel)
{
try
{
var inventoryItemGroupQuery = _dbContext.ItemGroups
.AsQueryable();
// sort
var excludeSort = new List<string> {"ParentGroup"};
inventoryItemGroupQuery = QueryHelper.AddSortToQuery(inventoryItemGroupQuery,
itemGroupRequestModel.Sort, itemGroupRequestModel.IsSortDsc, excludeSort);
// filter by name
if (!string.IsNullOrEmpty(itemGroupRequestModel.NameFilter))
{
inventoryItemGroupQuery = inventoryItemGroupQuery
.Where(x => x.Name.Contains(itemGroupRequestModel.NameFilter));
}
inventoryItemGroupQuery = inventoryItemGroupQuery
.Where(x => x.WorkflowState != Constants.WorkflowStates.Removed);
// calculate total before pagination
var total = await inventoryItemGroupQuery.Select(x => x.Id).CountAsync();
var inventoryItemGroupQueryMapped = AddSelectToItemGroupQuery(inventoryItemGroupQuery);
if (itemGroupRequestModel.Sort == "ParentGroup")
{
if (itemGroupRequestModel.IsSortDsc)
{
inventoryItemGroupQueryMapped = inventoryItemGroupQueryMapped
.OrderByDescending(x => x.Parent.Name);
}
else
{
inventoryItemGroupQueryMapped = inventoryItemGroupQueryMapped
.OrderBy(x => x.Parent.Name);
}
}
// pagination
inventoryItemGroupQueryMapped
= inventoryItemGroupQueryMapped
.Skip(itemGroupRequestModel.Offset)
.Take(itemGroupRequestModel.PageSize);
// add select and take objects from db
var inventoryItemGroupsFromDb = await inventoryItemGroupQueryMapped.ToListAsync();
var returnValue = new Paged<ItemGroupModel>
{
Entities = inventoryItemGroupsFromDb,
Total = total,
};
return new OperationDataResult<Paged<ItemGroupModel>>(true, returnValue);
}
catch (Exception e)
{
Trace.TraceError(e.Message);
return new OperationDataResult<Paged<ItemGroupModel>>(false,
_inventoryLocalizationService.GetString("ErrorObtainingItemGroups"));
}
}
public async Task<OperationDataResult<ItemGroupModel>> GetItemGroupById(int itemGroupId)
{
try
{
var itemGroupQuery = _dbContext.ItemGroups
.Where(x => x.Id == itemGroupId)
.Where(x => x.WorkflowState != Constants.WorkflowStates.Removed)
.AsQueryable();
var itemGroup = await AddSelectToItemGroupQuery(itemGroupQuery)
.FirstOrDefaultAsync();
if (itemGroup == null)
{
return new OperationDataResult<ItemGroupModel>(false,
_inventoryLocalizationService.GetString("ItemGroupNotFound"));
}
return new OperationDataResult<ItemGroupModel>(true, itemGroup);
}
catch (Exception e)
{
Trace.TraceError(e.Message);
return new OperationDataResult<ItemGroupModel>(false,
_inventoryLocalizationService.GetString("ErrorWhileGetItemGroup"));
}
}
public async Task<OperationResult> UpdateItemGroup(ItemGroupUpdateModel model)
{
try
{
var itemGroup = await _dbContext.ItemGroups
.Where(x => x.Id == model.Id)
.Where(x => x.WorkflowState != Constants.WorkflowStates.Removed)
.FirstOrDefaultAsync();
if (itemGroup == null)
{
return new OperationResult(false,
_inventoryLocalizationService.GetString("ItemGroupNotFound"));
}
itemGroup.Description = model.Description;
itemGroup.Code = model.Code;
itemGroup.Name = model.Name;
itemGroup.ParentId = model.ParentId;
itemGroup.UpdatedByUserId = _userService.UserId;
await itemGroup.Update(_dbContext);
return new OperationResult(true,
_inventoryLocalizationService.GetString("ItemGroupUpdatedSuccessfully"));
}
catch (Exception e)
{
Trace.TraceError(e.Message);
return new OperationResult(false,
_inventoryLocalizationService.GetString("ErrorWhileUpdateItemGroup"));
}
}
public async Task<OperationResult> CreateItemGroup(ItemGroupCreateModel itemGroupCreateModel)
{
try
{
var itemGroup = new ItemGroup
{
Description = itemGroupCreateModel.Description,
ParentId = itemGroupCreateModel.ParentId,
CreatedByUserId = _userService.UserId,
UpdatedByUserId = _userService.UserId,
Name = itemGroupCreateModel.Name,
Code = itemGroupCreateModel.Code,
};
await itemGroup.Create(_dbContext);
return new OperationResult(true,
_inventoryLocalizationService.GetString("ItemGroupCreatedSuccessfully"));
}
catch (Exception e)
{
Trace.TraceError(e.Message);
return new OperationResult(false,
_inventoryLocalizationService.GetString("ErrorWhileCreatingItemGroup"));
}
}
public async Task<OperationResult> DeleteItemGroupById(int itemGroupId)
{
try
{
var itemGroup = await _dbContext.ItemGroups
.Where(x => x.Id == itemGroupId)
.Where(x => x.WorkflowState != Constants.WorkflowStates.Removed)
.FirstOrDefaultAsync();
if (itemGroup == null)
{
return new OperationResult(false,
_inventoryLocalizationService.GetString("ItemGroupNotFound"));
}
var itemGroups = await _dbContext.ItemGroups
.Where(x => x.ParentId == itemGroup.Id)
.Where(x => x.WorkflowState != Constants.WorkflowStates.Removed)
.ToListAsync();
foreach (var itemGroupLocal in itemGroups)
{
itemGroupLocal.ParentId = null;
itemGroupLocal.UpdatedByUserId = _userService.UserId;
await itemGroupLocal.Update(_dbContext);
}
var itemTypes = await _dbContext.ItemTypes
.Where(x => x.ItemGroupId == itemGroup.Id)
.Where(x => x.WorkflowState != Constants.WorkflowStates.Removed)
.ToListAsync();
foreach (var itemType in itemTypes)
{
itemType.ItemGroupId = null;
itemType.UpdatedByUserId = _userService.UserId;
await itemType.Update(_dbContext);
}
itemGroup.UpdatedByUserId = _userService.UserId;
await itemGroup.Delete(_dbContext);
return new OperationResult(true,
_inventoryLocalizationService.GetString("ItemGroupDeletedSuccessfully"));
}
catch (Exception e)
{
Trace.TraceError(e.Message);
return new OperationResult(false,
_inventoryLocalizationService.GetString("ErrorWhileDeleteItemGroup"));
}
}
public async Task<OperationDataResult<List<CommonDictionaryModel>>> GetItemGroupsDictionary()
{
try
{
var inventoryItemGroups = await _dbContext.ItemGroups
.Where(x => x.WorkflowState != Constants.WorkflowStates.Removed)
.Select(x => new CommonDictionaryModel
{
Description = x.Description,
Name = x.Name,
Id = x.Id,
})
.ToListAsync();
return new OperationDataResult<List<CommonDictionaryModel>>(true, inventoryItemGroups);
}
catch (Exception e)
{
Trace.TraceError(e.Message);
return new OperationDataResult<List<CommonDictionaryModel>>(false,
_inventoryLocalizationService.GetString("ErrorObtainingItemGroups"));
}
}
private static IQueryable<ItemGroupModel> AddSelectToItemGroupQuery(IQueryable<ItemGroup> inventoryItemGroupQuery)
{
return inventoryItemGroupQuery
.Select(x => new ItemGroupModel
{
Description = x.Description,
Name = x.Name,
Code = x.Code,
Id = x.Id,
Parent = x.ParentId != null ? new ItemGroupDependencyItemGroup
{
Name = x.Parent.Name,
Id = x.Parent.Id
} : null
});
}
}
} | 41.357143 | 128 | 0.577014 | [
"MIT"
] | Gid733/eform-angular-inventory-plugin | eFormAPI/Plugins/Inventory.Pn/Inventory.Pn/Services/InventoryItemGroupService/InventoryItemGroupService.cs | 12,738 | C# |
using MongoDB.Driver;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Universalis.DbAccess.Queries.Uploads;
using Universalis.DbAccess.Uploads;
using Universalis.Entities.Uploads;
using Xunit;
namespace Universalis.DbAccess.Tests.Uploads;
public class UploadCountHistoryDbAccessTests : IDisposable
{
private static readonly string Database = CollectionUtils.GetDatabaseName(nameof(UploadCountHistoryDbAccessTests));
private readonly IMongoClient _client;
public UploadCountHistoryDbAccessTests()
{
_client = new MongoClient("mongodb://localhost:27017");
_client.DropDatabase(Database);
}
public void Dispose()
{
_client.DropDatabase(Database);
GC.SuppressFinalize(this);
}
[Fact]
public async Task Create_DoesNotThrow()
{
var db = new UploadCountHistoryDbAccess(_client, Database);
await db.Create(new UploadCountHistory
{
LastPush = (uint)DateTimeOffset.Now.ToUnixTimeMilliseconds(),
UploadCountByDay = new List<double> { 1 },
});
}
[Fact]
public async Task Retrieve_DoesNotThrow()
{
var db = new UploadCountHistoryDbAccess(_client, Database);
var output = await db.Retrieve(new UploadCountHistoryQuery());
Assert.Null(output);
}
[Fact]
public async Task Update_DoesNotThrow()
{
var db = new UploadCountHistoryDbAccess(_client, Database);
await db.Update(new UploadCountHistory
{
LastPush = DateTimeOffset.Now.ToUnixTimeMilliseconds(),
UploadCountByDay = new List<double> { 1 },
}, new UploadCountHistoryQuery());
}
[Fact]
public async Task Create_DoesInsert()
{
var db = new UploadCountHistoryDbAccess(_client, Database);
var document = new UploadCountHistory
{
LastPush = DateTimeOffset.Now.ToUnixTimeMilliseconds(),
UploadCountByDay = new List<double> { 1 },
};
await db.Create(document);
var output = await db.Retrieve(new UploadCountHistoryQuery());
Assert.NotNull(output);
Assert.Equal(document.LastPush, output.LastPush);
Assert.Equal(document.UploadCountByDay, output.UploadCountByDay);
}
} | 30.447368 | 119 | 0.672861 | [
"MIT"
] | karashiiro/Universalis | src/Universalis.DbAccess.Tests/Uploads/UploadCountHistoryDbAccessTests.cs | 2,316 | C# |
// Created by Ron 'Maxwolf' McDowell (ron.mcdowell@gmail.com)
// Timestamp 01/03/2016@1:50 AM
using System;
using System.Collections.Generic;
namespace OregonTrail
{
/// <summary>
/// Base interface for all entities in the simulation, this is used as a constraint for generics in event system.
/// </summary>
public interface IEntity : IComparer<IEntity>, IComparable<IEntity>, IEquatable<IEntity>, IEqualityComparer<IEntity>,
ITick
{
/// <summary>
/// Name of the entity as it should be known in the simulation.
/// </summary>
string Name { get; }
}
} | 31.4 | 121 | 0.648089 | [
"MIT"
] | Maxwolf/OregonTrailBot | src/OregonTrail/Entity/IEntity.cs | 630 | C# |
#region MigraDoc - Creating Documents on the Fly
//
// Authors:
// Stefan Lange (mailto:Stefan.Lange@PdfSharpCore.com)
// Klaus Potzesny (mailto:Klaus.Potzesny@PdfSharpCore.com)
// David Stephensen (mailto:David.Stephensen@PdfSharpCore.com)
//
// Copyright (c) 2001-2009 empira Software GmbH, Cologne (Germany)
//
// http://www.PdfSharpCore.com
// http://www.migradoc.com
// http://sourceforge.net/projects/pdfsharp
//
// 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.
#endregion
using System;
using System.Collections;
using System.Collections.Generic;
using MigraDocCore.DocumentObjectModel.IO;
using MigraDocCore.DocumentObjectModel.Tables;
using MigraDocCore.DocumentObjectModel.Visitors;
using MigraDocCore.DocumentObjectModel.Internals;
namespace MigraDocCore.DocumentObjectModel.Visitors
{
/// <summary>
/// Represents a merged list of cells of a table.
/// </summary>
public class MergedCellList : List<Cell>
{
/// <summary>
/// Enumeration of neighbor positions of cells in a table.
/// </summary>
private enum NeighborPosition
{
Top,
Left,
Right,
Bottom
}
/// <summary>
/// Initializes a new instance of the MergedCellList class.
/// </summary>
public MergedCellList(Table table)
{
Init(table);
}
/// <summary>
/// Initializes this instance from a table.
/// </summary>
private void Init(Table table)
{
for (int rwIdx = 0; rwIdx < table.Rows.Count; ++rwIdx)
{
for (int clmIdx = 0; clmIdx < table.Columns.Count; ++clmIdx)
{
Cell cell = table[rwIdx, clmIdx];
if (!IsAlreadyCovered(cell))
this.Add(cell);
}
}
}
/// <summary>
/// Returns whether the given cell is already covered by a preceding cell in this instance.
/// </summary>
/// <remarks>
/// Help function for Init().
/// </remarks>
private bool IsAlreadyCovered(Cell cell)
{
for (int index = this.Count - 1; index >= 0; --index)
{
Cell currentCell = this[index];
if (currentCell.Column.Index <= cell.Column.Index && currentCell.Column.Index + currentCell.MergeRight >= cell.Column.Index)
{
if (currentCell.Row.Index <= cell.Row.Index && currentCell.Row.Index + currentCell.MergeDown >= cell.Row.Index)
return true;
else if (currentCell.Row.Index + currentCell.MergeDown == cell.Row.Index - 1)
return false;
}
}
return false;
}
/// <summary>
/// Gets the cell at the specified position.
/// </summary>
public new Cell this[int index]
{
get
{
return base[index] as Cell;
}
}
/// <summary>
/// Gets a borders object that should be used for rendering.
/// </summary>
/// <exception cref="System.ArgumentException">
/// Thrown when the cell is not in this list.
/// This situation occurs if the given cell is merged "away" by a previous one.
/// </exception>
public Borders GetEffectiveBorders(Cell cell)
{
Borders borders = cell.GetValue("Borders", GV.ReadOnly) as Borders;
if (borders != null)
{
Document doc = borders.Document;
borders = borders.Clone();
borders.parent = cell;
doc = borders.Document;
}
else
borders = new Borders(cell.parent);
int cellIdx = this.BinarySearch(cell, new CellComparer());
if (!(cellIdx >= 0 && cellIdx < this.Count))
throw new ArgumentException("cell is not a relevant cell", "cell");
if (cell.mergeRight > 0)
{
Cell rightBorderCell = cell.Table[cell.Row.Index, cell.Column.Index + (cell.mergeRight ?? 0)];
if (rightBorderCell.borders != null && rightBorderCell.borders.right != null)
borders.Right = rightBorderCell.borders.right.Clone();
else
borders.right = null;
}
if (cell.mergeDown > 0)
{
Cell bottomBorderCell = cell.Table[cell.Row.Index + (cell.mergeDown ?? 0), cell.Column.Index];
if (bottomBorderCell.borders != null && bottomBorderCell.borders.bottom != null)
borders.Bottom = bottomBorderCell.borders.bottom.Clone();
else
borders.bottom = null;
}
Cell leftNeighbor = GetNeighbor(cellIdx, NeighborPosition.Left);
Cell rightNeighbor = GetNeighbor(cellIdx, NeighborPosition.Right);
Cell topNeighbor = GetNeighbor(cellIdx, NeighborPosition.Top);
Cell bottomNeighbor = GetNeighbor(cellIdx, NeighborPosition.Bottom);
if (leftNeighbor != null)
{
Borders nbrBrdrs = leftNeighbor.GetValue("Borders", GV.ReadWrite) as Borders;
if (nbrBrdrs != null && GetEffectiveBorderWidth(nbrBrdrs, BorderType.Right) >= GetEffectiveBorderWidth(borders, BorderType.Left))
borders.SetValue("Left", GetBorderFromBorders(nbrBrdrs, BorderType.Right));
}
if (rightNeighbor != null)
{
Borders nbrBrdrs = rightNeighbor.GetValue("Borders", GV.ReadWrite) as Borders;
if (nbrBrdrs != null && GetEffectiveBorderWidth(nbrBrdrs, BorderType.Left) > GetEffectiveBorderWidth(borders, BorderType.Right))
borders.SetValue("Right", GetBorderFromBorders(nbrBrdrs, BorderType.Left));
}
if (topNeighbor != null)
{
Borders nbrBrdrs = topNeighbor.GetValue("Borders", GV.ReadWrite) as Borders;
if (nbrBrdrs != null && GetEffectiveBorderWidth(nbrBrdrs, BorderType.Bottom) >= GetEffectiveBorderWidth(borders, BorderType.Top))
borders.SetValue("Top", GetBorderFromBorders(nbrBrdrs, BorderType.Bottom));
}
if (bottomNeighbor != null)
{
Borders nbrBrdrs = bottomNeighbor.GetValue("Borders", GV.ReadWrite) as Borders;
if (nbrBrdrs != null && GetEffectiveBorderWidth(nbrBrdrs, BorderType.Top) > GetEffectiveBorderWidth(borders, BorderType.Bottom))
borders.SetValue("Bottom", GetBorderFromBorders(nbrBrdrs, BorderType.Top));
}
return borders;
}
/// <summary>
/// Gets the cell that covers the given cell by merging. Usually the cell itself if not merged.
/// </summary>
public Cell GetCoveringCell(Cell cell)
{
int cellIdx = this.BinarySearch(cell, new CellComparer());
if (cellIdx >= 0 && cellIdx < this.Count)
return this[cellIdx];
else //Binary Search returns the complement of the next value, therefore, "~cellIdx - 1" is the previous cell.
cellIdx = ~cellIdx - 1;
for (int index = cellIdx; index >= 0; --index)
{
Cell currCell = this[index];
if (currCell.Column.Index <= cell.Column.Index &&
currCell.Column.Index + currCell.MergeRight >= cell.Column.Index &&
currCell.Row.Index <= cell.Row.Index &&
currCell.Row.Index + currCell.MergeDown >= cell.Row.Index)
return currCell;
}
return null;
}
/// <summary>
/// Returns the border of the given borders-object of the specified type (top, bottom, ...).
/// If that border doesn't exist, it returns a new border object that inherits all properties from the given borders object
/// </summary>
private Border GetBorderFromBorders(Borders borders, BorderType type)
{
Border returnBorder = borders.GetValue(type.ToString(), GV.ReadOnly) as Border;
if (returnBorder == null)
{
returnBorder = new Border();
returnBorder.style = borders.style;
returnBorder.width = borders.width;
returnBorder.color = borders.color;
returnBorder.visible = borders.visible;
}
return returnBorder;
}
/// <summary>
/// Returns the width of the border at the specified position.
/// </summary>
private Unit GetEffectiveBorderWidth(Borders borders, BorderType type)
{
if (borders == null)
return 0;
Border border = borders.GetValue(type.ToString(), GV.GetNull) as Border;
DocumentObject relevantDocObj = border;
if (relevantDocObj == null || relevantDocObj.IsNull("Width"))
relevantDocObj = borders;
object visible = relevantDocObj.GetValue("visible", GV.GetNull);
object style = relevantDocObj.GetValue("style", GV.GetNull);
object width = relevantDocObj.GetValue("width", GV.GetNull);
object color = relevantDocObj.GetValue("color", GV.GetNull);
if (visible != null || style != null || width != null || color != null)
{
if (visible != null && !(bool)visible)
return 0;
if (width != null)
return (Unit)width;
return 0.5;
}
return 0;
}
/// <summary>
/// Gets the specified cell's uppermost neighbor at the specified position.
/// </summary>
private Cell GetNeighbor(int cellIdx, NeighborPosition position)
{
Cell cell = this[cellIdx];
if (cell.Column.Index == 0 && position == NeighborPosition.Left ||
cell.Row.Index == 0 && position == NeighborPosition.Top ||
cell.Row.Index + cell.MergeDown == cell.Table.Rows.Count - 1 && position == NeighborPosition.Bottom ||
cell.Column.Index + cell.MergeRight == cell.Table.Columns.Count - 1 && position == NeighborPosition.Right)
return null;
switch (position)
{
case NeighborPosition.Top:
case NeighborPosition.Left:
for (int index = cellIdx - 1; index >= 0; --index)
{
Cell currCell = this[index];
if (IsNeighbor(cell, currCell, position))
return currCell;
}
break;
case NeighborPosition.Right:
if (cellIdx + 1 < this.Count)
{
Cell cell2 = this[cellIdx + 1];
if (cell2.Row.Index == cell.Row.Index)
return cell2;
}
for (int index = cellIdx - 1; index >= 0; --index)
{
Cell currCell = this[index];
if (IsNeighbor(cell, currCell, position))
return currCell;
}
break;
case NeighborPosition.Bottom:
for (int index = cellIdx + 1; index < this.Count; ++index)
{
Cell currCell = this[index];
if (IsNeighbor(cell, currCell, position))
return currCell;
}
break;
}
return null;
}
/// <summary>
/// Returns whether cell2 is a neighbor of cell1 at the specified position.
/// </summary>
private bool IsNeighbor(Cell cell1, Cell cell2, NeighborPosition position)
{
bool isNeighbor = false;
switch (position)
{
case NeighborPosition.Bottom:
int bottomRowIdx = cell1.Row.Index + cell1.MergeDown + 1;
isNeighbor = cell2.Row.Index == bottomRowIdx &&
cell2.Column.Index <= cell1.Column.Index &&
cell2.Column.Index + cell2.MergeRight >= cell1.Column.Index;
break;
case NeighborPosition.Left:
int leftClmIdx = cell1.Column.Index - 1;
isNeighbor = cell2.Row.Index <= cell1.Row.Index &&
cell2.Row.Index + cell2.MergeDown >= cell1.Row.Index &&
cell2.Column.Index + cell2.MergeRight == leftClmIdx;
break;
case NeighborPosition.Right:
int rightClmIdx = cell1.Column.Index + cell1.MergeRight + 1;
isNeighbor = cell2.Row.Index <= cell1.Row.Index &&
cell2.Row.Index + cell2.MergeDown >= cell1.Row.Index &&
cell2.Column.Index == rightClmIdx;
break;
case NeighborPosition.Top:
int topRowIdx = cell1.Row.Index - 1;
isNeighbor = cell2.Row.Index + cell2.MergeDown == topRowIdx &&
cell2.Column.Index + cell2.MergeRight >= cell1.Column.Index &&
cell2.Column.Index <= cell1.Column.Index;
break;
}
return isNeighbor;
}
}
}
| 36.592068 | 137 | 0.628784 | [
"MIT"
] | 929496959/PdfSharpCore | MigraDocCore.DocumentObjectModel/MigraDoc.DocumentObjectModel.Visitors/MergedCellList.cs | 12,917 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading;
using System.Threading.Tasks;
namespace Azure.Core.Pipeline
{
public class HttpClientTransport : HttpPipelineTransport
{
static readonly HttpClient s_defaultClient = new HttpClient();
readonly HttpClient _client;
public HttpClientTransport(HttpClient client = null)
=> _client = client == null ? s_defaultClient : client;
public readonly static HttpClientTransport Shared = new HttpClientTransport();
public sealed override Request CreateRequest(IServiceProvider services)
=> new PipelineRequest();
public sealed override async Task ProcessAsync(HttpPipelineMessage message)
{
var pipelineRequest = message.Request as PipelineRequest;
if (pipelineRequest == null)
throw new InvalidOperationException("the request is not compatible with the transport");
using (HttpRequestMessage httpRequest = pipelineRequest.BuildRequestMessage(message.Cancellation))
{
HttpResponseMessage responseMessage = await ProcessCoreAsync(message.Cancellation, httpRequest).ConfigureAwait(false);
message.Response = new PipelineResponse(message.Request.RequestId, responseMessage);
}
}
protected virtual async Task<HttpResponseMessage> ProcessCoreAsync(CancellationToken cancellation, HttpRequestMessage httpRequest)
=> await _client.SendAsync(httpRequest, HttpCompletionOption.ResponseHeadersRead, cancellation).ConfigureAwait(false);
internal static bool TryGetHeader(HttpHeaders headers, HttpContent content, string name, out string value)
{
if (TryGetHeader(headers, content, name, out IEnumerable<string> values))
{
value = JoinHeaderValues(values);
return true;
}
value = null;
return false;
}
internal static bool TryGetHeader(HttpHeaders headers, HttpContent content, string name, out IEnumerable<string> values)
{
return headers.TryGetValues(name, out values) || content?.Headers.TryGetValues(name, out values) == true;
}
internal static IEnumerable<HttpHeader> GetHeaders(HttpHeaders headers, HttpContent content)
{
foreach (var header in headers)
{
yield return new HttpHeader(header.Key, JoinHeaderValues(header.Value));
}
if (content != null)
{
foreach (var header in content.Headers)
{
yield return new HttpHeader(header.Key, JoinHeaderValues(header.Value));
}
}
}
internal static bool RemoveHeader(HttpHeaders headers, HttpContent content, string name)
{
// .Remove throws on invalid header name so use TryGet here to check
if (headers.TryGetValues(name, out _ ) && headers.Remove(name))
{
return true;
}
return content?.Headers.TryGetValues(name, out _ ) == true && content.Headers.Remove(name);
}
internal static bool ContainsHeader(HttpHeaders headers, HttpContent content, string name)
{
// .Contains throws on invalid header name so use TryGet here
if (headers.TryGetValues(name, out _))
{
return true;
}
return content?.Headers.TryGetValues(name, out _) == true;
}
internal static void CopyHeaders(HttpHeaders from, HttpHeaders to)
{
foreach (var header in from)
{
if (!to.TryAddWithoutValidation(header.Key, header.Value))
{
throw new InvalidOperationException($"Unable to add header {header} to header collection.");
}
}
}
private static string JoinHeaderValues(IEnumerable<string> values)
{
return string.Join(",", values);
}
sealed class PipelineRequest : Request
{
private bool _wasSent = false;
private readonly HttpRequestMessage _requestMessage;
private PipelineContentAdapter _requestContent;
public PipelineRequest()
{
_requestMessage = new HttpRequestMessage();
RequestId = Guid.NewGuid().ToString();
}
public override HttpPipelineMethod Method
{
get => HttpPipelineMethodConverter.Parse(_requestMessage.Method.Method);
set => _requestMessage.Method = ToHttpClientMethod(value);
}
public override HttpPipelineRequestContent Content
{
get => _requestContent?.PipelineContent;
set
{
EnsureContentInitialized();
_requestContent.PipelineContent = value;
}
}
public override string RequestId { get; set; }
protected internal override void AddHeader(string name, string value)
{
if (_requestMessage.Headers.TryAddWithoutValidation(name, value))
{
return;
}
EnsureContentInitialized();
if (!_requestContent.Headers.TryAddWithoutValidation(name, value))
{
throw new InvalidOperationException("Unable to add header to request or content");
}
}
protected internal override bool TryGetHeader(string name, out string value) => HttpClientTransport.TryGetHeader(_requestMessage.Headers, _requestContent, name, out value);
protected internal override bool TryGetHeaderValues(string name, out IEnumerable<string> values) => HttpClientTransport.TryGetHeader(_requestMessage.Headers, _requestContent, name, out values);
protected internal override bool ContainsHeader(string name) => HttpClientTransport.ContainsHeader(_requestMessage.Headers, _requestContent, name);
protected internal override bool RemoveHeader(string name) => HttpClientTransport.RemoveHeader(_requestMessage.Headers, _requestContent, name);
protected internal override IEnumerable<HttpHeader> EnumerateHeaders() => HttpClientTransport.GetHeaders(_requestMessage.Headers, _requestContent);
public HttpRequestMessage BuildRequestMessage(CancellationToken cancellation)
{
HttpRequestMessage currentRequest;
if (_wasSent)
{
// A copy of a message needs to be made because HttpClient does not allow sending the same message twice,
// and so the retry logic fails.
currentRequest = new HttpRequestMessage(_requestMessage.Method, UriBuilder.Uri);
CopyHeaders(_requestMessage.Headers, currentRequest.Headers);
}
else
{
currentRequest = _requestMessage;
_wasSent = true;
}
currentRequest.RequestUri = UriBuilder.Uri;
if (_requestContent?.PipelineContent != null)
{
currentRequest.Content = new PipelineContentAdapter()
{
CancellationToken = cancellation,
PipelineContent = _requestContent.PipelineContent
};
CopyHeaders(_requestContent.Headers, currentRequest.Content.Headers);
}
return currentRequest;
}
public override void Dispose()
{
_requestMessage.Dispose();
}
public override string ToString() => _requestMessage.ToString();
readonly static HttpMethod s_patch = new HttpMethod("PATCH");
public static HttpMethod ToHttpClientMethod(HttpPipelineMethod method)
{
switch (method)
{
case HttpPipelineMethod.Get:
return HttpMethod.Get;
case HttpPipelineMethod.Post:
return HttpMethod.Post;
case HttpPipelineMethod.Put:
return HttpMethod.Put;
case HttpPipelineMethod.Delete:
return HttpMethod.Delete;
case HttpPipelineMethod.Patch:
return s_patch;
case HttpPipelineMethod.Head:
return HttpMethod.Head;
default:
throw new NotImplementedException();
}
}
private void EnsureContentInitialized()
{
if (_requestContent == null)
{
_requestContent = new PipelineContentAdapter();
}
}
sealed class PipelineContentAdapter : HttpContent
{
public HttpPipelineRequestContent PipelineContent { get; set; }
public CancellationToken CancellationToken { get; set; }
protected override async Task SerializeToStreamAsync(Stream stream, TransportContext context)
{
Debug.Assert(PipelineContent != null);
await PipelineContent.WriteTo(stream, CancellationToken).ConfigureAwait(false);
}
protected override bool TryComputeLength(out long length)
{
Debug.Assert(PipelineContent != null);
return PipelineContent.TryComputeLength(out length);
}
protected override void Dispose(bool disposing)
{
PipelineContent?.Dispose();
base.Dispose(disposing);
}
}
}
sealed class PipelineResponse : Response
{
private readonly HttpResponseMessage _responseMessage;
private Stream _contentStream;
public PipelineResponse(string requestId, HttpResponseMessage responseMessage)
{
RequestId = requestId ?? throw new ArgumentNullException(nameof(requestId));
_responseMessage = responseMessage ?? throw new ArgumentNullException(nameof(responseMessage));
}
public override int Status => (int)_responseMessage.StatusCode;
public override Stream ContentStream
{
get
{
if (_contentStream != null)
{
return _contentStream;
}
if (_responseMessage.Content == null)
{
return null;
}
Task<Stream> contentTask = _responseMessage.Content.ReadAsStreamAsync();
if (contentTask.IsCompleted)
{
_contentStream = contentTask.GetAwaiter().GetResult();
}
else
{
_contentStream = new ContentStream(contentTask);
}
return _contentStream;
}
set
{
_contentStream = value;
}
}
public override string RequestId { get; set; }
protected internal override bool TryGetHeader(string name, out string value) => HttpClientTransport.TryGetHeader(_responseMessage.Headers, _responseMessage.Content, name, out value);
protected internal override bool TryGetHeaderValues(string name, out IEnumerable<string> values) => HttpClientTransport.TryGetHeader(_responseMessage.Headers, _responseMessage.Content, name, out values);
protected internal override bool ContainsHeader(string name) => HttpClientTransport.ContainsHeader(_responseMessage.Headers, _responseMessage.Content, name);
protected internal override IEnumerable<HttpHeader> EnumerateHeaders() => HttpClientTransport.GetHeaders(_responseMessage.Headers, _responseMessage.Content);
public override void Dispose()
{
_responseMessage?.Dispose();
}
public override string ToString() => _responseMessage.ToString();
}
private class ContentStream : ReadOnlyStream
{
private readonly Task<Stream> _contentTask;
private Stream _contentStream;
public ContentStream(Task<Stream> contentTask)
{
_contentTask = contentTask;
}
public override long Seek(long offset, SeekOrigin origin)
{
EnsureStream();
return _contentStream.Seek(offset, origin);
}
public override async Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
await EnsureStreamAsync();
return await _contentStream.ReadAsync(buffer, offset, count, cancellationToken);
}
public override int Read(byte[] buffer, int offset, int count)
{
EnsureStream();
return _contentStream.Read(buffer, offset, count);
}
public override bool CanRead
{
get
{
EnsureStream();
return _contentStream.CanRead;
}
}
public override bool CanSeek
{
get
{
EnsureStream();
return _contentStream.CanSeek;
}
}
public override long Length
{
get
{
EnsureStream();
return _contentStream.Length;
}
}
public override long Position
{
get
{
EnsureStream();
return _contentStream.Position;
}
set
{
EnsureStream();
_contentStream.Position = value;
}
}
private void EnsureStream()
{
if (_contentStream != null)
{
EnsureStreamAsync().GetAwaiter().GetResult();
}
}
private Task EnsureStreamAsync()
{
async Task EnsureStreamAsyncImpl()
{
_contentStream = await _contentTask;
}
return _contentStream == null ? EnsureStreamAsyncImpl() : Task.CompletedTask;
}
}
}
}
| 36.561321 | 215 | 0.554832 | [
"MIT"
] | sanar-microsoft/azure-sdk-for-net | src/SDKs/Azure.Core/data-plane/Azure.Core/Pipeline/HttpClientTransport.cs | 15,504 | C# |
using FluentValidation.Results;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Text;
namespace Core.Extensions
{
//Hatanın detaylarına dair
public class ErrorDetails
{
public string Message { get; set; }
public int StatusCode { get; set; }
public override string ToString()
{
return JsonConvert.SerializeObject(this);
}
}
public class ValidationErrorDetails : ErrorDetails
{
public IEnumerable<ValidationFailure> ValidationErrors
{
get; set;
}
}
}
| 20.862069 | 62 | 0.636364 | [
"MIT"
] | maziz-create/ReCapProject | Core/Extensions/ErrorDetails.cs | 609 | C# |
using Moq;
using Reifnir.StaticSite.Content;
using Reifnir.StaticSite.Tests.FunctionsTesting;
using System;
using System.IO;
using System.Net;
using System.Text;
using Xunit;
namespace Reifnir.StaticSite.Tests
{
public class StaticSiteFunctionTests
{
[Fact]
public void ParseFileArgument_ContentFoundReturnsHttpStatusOk()
{
var queryString = "anything";
var contentHelper = new Mock<IContentHelper>();
contentHelper
.Setup(x => x.GetContent(queryString))
.Returns(SetupContentFoundResult("", "text/html"));
var logger = TestFactory.CreateLogger();
var sut = new StaticSiteFunction(contentHelper.Object);
var result = sut.Run(queryString, logger);
Assert.Equal(HttpStatusCode.OK, result.StatusCode);
}
[Fact]
public void ParseFileArgument_ContentFoundReturnsContentHelpersMimeType()
{
var queryString = "anything";
var expected = "application/json";
var contentHelper = new Mock<IContentHelper>();
contentHelper
.Setup(x => x.GetContent(queryString))
.Returns(SetupContentFoundResult("", expected));
var logger = TestFactory.CreateLogger();
var sut = new StaticSiteFunction(contentHelper.Object);
var result = sut.Run(queryString, logger);
Assert.Equal(expected, result.Content.Headers.ContentType.ToString());
}
[Fact]
public async void ParseFileArgument_ContentFoundReturnsContentHelpersStream()
{
var queryString = "anything";
var expected = "just some content";
var contentHelper = new Mock<IContentHelper>();
contentHelper
.Setup(x => x.GetContent(queryString))
.Returns(SetupContentFoundResult(expected, "application/json"));
var logger = TestFactory.CreateLogger();
var sut = new StaticSiteFunction(contentHelper.Object);
var result = sut.Run(queryString, logger);
var actual = await result.Content.ReadAsStringAsync();
Assert.Equal(expected, actual);
}
[Fact]
public void ParseFileArgument_UnimplimentedContentTypeThrowsException()
{
var queryString = "anything";
var contentHelper = new Mock<IContentHelper>();
contentHelper
.Setup(x => x.GetContent(queryString))
.Returns(new UnimplementedContentResult());
var logger = TestFactory.CreateLogger();
var sut = new StaticSiteFunction(contentHelper.Object);
Assert.Throws<NotImplementedException>(() => sut.Run(queryString, logger));
}
private ContentFoundResult SetupContentFoundResult(string contentString, string mimeType)
{
return new ContentFoundResult()
{
Content = new MemoryStream(Encoding.UTF8.GetBytes(contentString)),
MimeType = mimeType
};
}
private class UnimplementedContentResult : IContentResult
{
}
}
}
| 33.818182 | 98 | 0.589904 | [
"MIT"
] | reifnir/terraform-azurerm-azure-functions-static-site | function/Reifnir.StaticSite.Tests/StaticSiteFunctionTests.cs | 3,348 | C# |
using System;
namespace Migr8.Test
{
public static class TestConfig
{
public static string ConnectionString => Environment.GetEnvironmentVariable("SQLSERVER")
?? "server=.; database=migr8_test; trusted_connection=true";
}
} | 29.4 | 109 | 0.605442 | [
"MIT"
] | ctrlenter/migr8 | Migr8.Test/TestConfig.cs | 296 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using Android.App;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("LeakCanary.Analyzer")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("LeakCanary.Analyzer")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// 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")]
| 34.677419 | 84 | 0.743256 | [
"Apache-2.0"
] | crehmann/LeakCanaryBinding | LeakCanary.Analyzer/Properties/AssemblyInfo.cs | 1,078 | C# |
namespace Lncodes.DesignPattern.FactoryMethod
{
public enum EnemyTypes
{
Orc,
Slime,
Goblin
}
}
| 13.3 | 46 | 0.571429 | [
"MIT"
] | lncodes/design-pattern-factory-method | c#/src/Data/EnemyTypes.cs | 135 | C# |
////////////////////////////////////////////////////////////////////////////////////
// CameraFilterPack v2.0 - by VETASOFT 2015 //////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////
using UnityEngine;
using System.Collections;
[ExecuteInEditMode]
[AddComponentMenu ("Camera Filter Pack/Blur/Blur Hole")]
public class CameraFilterPack_Blur_BlurHole : MonoBehaviour {
#region Variables
public Shader SCShader;
private float TimeX = 1.0f;
[Range(1, 16)] public float Size = 10;
[Range(0, 1)] public float _Radius = 0.25f;
[Range(0, 4)] public float _SpotSize = 1;
[Range(0, 1)] public float _CenterX = 0.5f;
[Range(0, 1)] public float _CenterY = 0.5f;
[Range(0, 1)] public float _AlphaBlur = 1.0f;
[Range(0, 1)] public float _AlphaBlurInside = 0.0f;
private Vector4 ScreenResolution;
private Material SCMaterial;
public static float ChangeSize;
#endregion
#region Properties
Material material
{
get
{
if(SCMaterial == null)
{
SCMaterial = new Material(SCShader);
SCMaterial.hideFlags = HideFlags.HideAndDontSave;
}
return SCMaterial;
}
}
#endregion
void Start ()
{
ChangeSize = Size;
SCShader = Shader.Find("CameraFilterPack/BlurHole");
if(!SystemInfo.supportsImageEffects)
{
enabled = false;
return;
}
}
void OnRenderImage (RenderTexture sourceTexture, RenderTexture destTexture)
{
if(SCShader != null)
{
TimeX+=Time.deltaTime;
if (TimeX>100) TimeX=0;
material.SetFloat("_TimeX", TimeX);
material.SetFloat("_Distortion", Size);
material.SetFloat("_Radius", _Radius);
material.SetFloat("_SpotSize", _SpotSize);
material.SetFloat("_CenterX", _CenterX);
material.SetFloat("_CenterY", _CenterY);
material.SetFloat("_Alpha", _AlphaBlur);
material.SetFloat("_Alpha2", _AlphaBlurInside);
material.SetVector("_ScreenResolution",new Vector2(Screen.width,Screen.height));
Graphics.Blit(sourceTexture, destTexture, material);
}
else
{
Graphics.Blit(sourceTexture, destTexture);
}
}
void OnValidate()
{
ChangeSize=Size;
}
// Update is called once per frame
void Update ()
{
if (Application.isPlaying)
{
Size = ChangeSize;
}
#if UNITY_EDITOR
if (Application.isPlaying!=true)
{
SCShader = Shader.Find("CameraFilterPack/BlurHole");
}
#endif
}
void OnDisable ()
{
if(SCMaterial)
{
DestroyImmediate(SCMaterial);
}
}
} | 22.445455 | 87 | 0.633455 | [
"MIT"
] | esther5576/CartographStory | Assets/Plugins/Camera Filter Pack/Scripts/CameraFilterPack_Blur_BlurHole.cs | 2,471 | C# |
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Windows;
// 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("ThumbnailSharp.Gui")]
[assembly: AssemblyDescription("A simple program to create an image thumbnail from various sources with many formats.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Mirza Ghulam Rasyid")]
[assembly: AssemblyProduct("ThumbnailSharp.Gui")]
[assembly: AssemblyCopyright("Copyright © 2017 Mirza Ghulam Rasyid")]
[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)]
//In order to begin building localizable applications, set
//<UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file
//inside a <PropertyGroup>. For example, if you are using US english
//in your source files, set the <UICulture> to en-US. Then uncomment
//the NeutralResourceLanguage attribute below. Update the "en-US" in
//the line below to match the UICulture setting in the project file.
//[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)]
[assembly: ThemeInfo(
ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located
//(used if a resource is not found in the page,
// or application resource dictionaries)
ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located
//(used if a resource is not found in the page,
// app, or any theme specific resource dictionaries)
)]
// 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")]
| 44.785714 | 120 | 0.716906 | [
"MIT"
] | mirzaevolution/ThumbnailSharp.Client | ThumbnailSharp.Gui/Properties/AssemblyInfo.cs | 2,511 | C# |
// --------------------------------------------------------------------------------------------------------------------
// Copyright (c) Lead Pipe Software. All rights reserved.
// Licensed under the MIT License. Please see the LICENSE file in the project root for full license information.
// --------------------------------------------------------------------------------------------------------------------
namespace LeadPipe.Net.Lucene.Tests
{
public class FooSearchData : IKeyed
{
public string Bar { get; set; }
public string Key { get; set; }
public string Parrot { get; set; }
public string Score { get; set; }
}
} | 37.333333 | 120 | 0.421131 | [
"MIT"
] | LeadPipeSoftware/LeadPipe.Net | src/LeadPipe.Net.Lucene.Tests/FooSearchData.cs | 674 | C# |
#region License
/* **********************************************************************************
* Copyright (c) Roman Ivantsov
* This source code is subject to terms and conditions of the MIT License
* for Irony. A copy of the license can be found in the License.txt file
* at the root of this distribution.
* By using this source code in any fashion, you are agreeing to be bound by the terms of the
* MIT License.
* You must not remove this notice from this software.
* **********************************************************************************/
#endregion License
using System;
using System.Collections.Generic;
using Irony.Interpreter.Ast;
namespace Irony.Interpreter
{
/// <summary>
/// Describes all variables (locals and parameters) defined in a scope of a function or module.
/// <para />
/// Note that all access to SlotTable is done through "lock" operator, so it's thread safe
/// </summary>
/// <remarks>
/// ScopeInfo is metadata, it does not contain variable values. The Scope object (described by ScopeInfo) is a container for values.
/// </remarks>
public class ScopeInfo
{
public readonly string AsString;
public int Level;
/// <summary>
/// Might be null
/// </summary>
public AstNode OwnerNode;
/// <summary>
/// Experiment: reusable scope instance; see ScriptThread.cs class
/// </summary>
public Scope ScopeInstance;
/// <summary>
/// Static/singleton scopes only; for ex, modules are singletons. Index in App.StaticScopes array
/// </summary>
public int StaticIndex = -1;
public int ValuesCount, ParametersCount;
protected internal object LockObject = new object();
private ScopeInfo parent;
private SlotInfoDictionary slots;
public ScopeInfo(AstNode ownerNode, bool caseSensitive)
{
if (ownerNode == null)
throw new Exception("ScopeInfo owner node may not be null.");
this.OwnerNode = ownerNode;
this.slots = new SlotInfoDictionary(caseSensitive);
this.Level = this.Parent == null ? 0 : this.Parent.Level + 1;
var sLevel = "level=" + this.Level;
this.AsString = this.OwnerNode == null ? sLevel : this.OwnerNode.AsString + ", " + sLevel;
}
/// <summary>
/// Lexical parent
/// </summary>
public ScopeInfo Parent
{
get
{
if (this.parent == null)
this.parent = this.GetParent();
return this.parent;
}
}
public ScopeInfo GetParent()
{
if (this.OwnerNode == null)
return null;
var currentParent = this.OwnerNode.Parent;
while (currentParent != null)
{
var result = currentParent.DependentScopeInfo;
if (result != null)
return result;
currentParent = currentParent.Parent;
}
// Should never happen
return null;
}
#region Slot operations
public SlotInfo AddSlot(string name, SlotType type)
{
lock (this.LockObject)
{
var index = type == SlotType.Value ? this.ValuesCount++ : this.ParametersCount++;
var slot = new SlotInfo(this, type, name, index);
this.slots.Add(name, slot);
return slot;
}
}
public IList<string> GetNames()
{
lock (this.LockObject)
{
return new List<string>(this.slots.Keys);
}
}
/// <summary>
/// Returns null if slot not found.
/// </summary>
/// <param name="name"></param>
/// <returns></returns>
public SlotInfo GetSlot(string name)
{
lock (this.LockObject)
{
SlotInfo slot;
this.slots.TryGetValue(name, out slot);
return slot;
}
}
public int GetSlotCount()
{
lock (this.LockObject)
{
return this.slots.Count;
}
}
public IList<SlotInfo> GetSlots()
{
lock (this.LockObject)
{
return new List<SlotInfo>(this.slots.Values);
}
}
#endregion Slot operations
public override string ToString()
{
return this.AsString;
}
}
public class ScopeInfoList : List<ScopeInfo> { }
}
| 23.083832 | 133 | 0.638132 | [
"MIT"
] | Tyelpion/irony | Irony.Interpreter/Scopes/ScopeInfo.cs | 3,855 | C# |
//Author Maxim Kuzmin//makc//
using Makc2020.Core.Base.Execution;
using Makc2020.Core.Base.Ext;
using Makc2020.Mods.DummyMain.Base.Common.Jobs.Option.List.Get;
using Makc2020.Mods.DummyMain.Base.Jobs.Item.Get;
using Makc2020.Mods.DummyMain.Base.Jobs.List.Get;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Threading.Tasks;
namespace Makc2020.Mods.DummyMain.Web.Api
{
/// <summary>
/// Мод "DummyMain". Веб. API. Контроллер.
/// </summary>
[ApiController, Route("api/dummy-main")]
public class ModDummyMainWebApiController : ControllerBase
{
#region Properties
private ModDummyMainWebApiModel MyModel { get; set; }
#endregion Properties
#region Constructors
/// <summary>
/// Конструктор.
/// </summary>
/// <param name="model">Модель.</param>
public ModDummyMainWebApiController(ModDummyMainWebApiModel model)
{
MyModel = model;
}
#endregion Constructors
#region Public methods
/// <summary>
/// Получить список.
/// </summary>
/// <param name="input">Ввод.</param>
/// <returns>Результат выполнения с данными списка.</returns>
[Route("list"), HttpGet]
public async Task<IActionResult> Get([FromQuery] ModDummyMainBaseJobListGetInput input)
{
var result = new ModDummyMainBaseJobListGetResult();
var (execute, onSuccess, onError) = MyModel.BuildActionListGet(input);
try
{
result.Data = await execute().CoreBaseExtTaskWithCurrentCulture(false);
onSuccess(result);
}
catch (Exception ex)
{
onError(ex, result);
}
return Ok(result);
}
/// <summary>
/// Получить элемент.
/// </summary>
/// <param name="intput">Ввод.</param>
/// <returns>Результат выполнения с данными элемента.</returns>
[Route("item"), HttpGet]
public async Task<IActionResult> Get([FromQuery] ModDummyMainBaseJobItemGetInput input)
{
var result = new ModDummyMainBaseJobItemGetResult();
var (execute, onSuccess, onError) = MyModel.BuildActionItemGet(input);
try
{
result.Data = await execute().CoreBaseExtTaskWithCurrentCulture(false);
onSuccess(result);
}
catch (Exception ex)
{
onError(ex, result);
}
return Ok(result);
}
/// <summary>
/// Получить варианты выбора сущности "DummyManyToMany".
/// </summary>
/// <returns>Результат выполнения с вариантами выбора.</returns>
[Route("options/dummy-many-to-many"), HttpGet]
public async Task<IActionResult> GetOptionsDummyManyToMany()
{
var result = new ModDummyMainBaseCommonJobOptionListGetResult();
var (execute, onSuccess, onError) = MyModel.BuildActionOptionDummyManyToManyListGet();
try
{
result.Data = await execute().CoreBaseExtTaskWithCurrentCulture(false);
onSuccess(result);
}
catch (Exception ex)
{
onError(ex, result);
}
return Ok(result);
}
/// <summary>
/// Получить варианты выбора сущности "DummyOneToMany".
/// </summary>
/// <returns>Результат выполнения с вариантами выбора.</returns>
[Route("options/dummy-one-to-many"), HttpGet]
public async Task<IActionResult> GetOptionsDummyOneToMany()
{
var result = new ModDummyMainBaseCommonJobOptionListGetResult();
var (execute, onSuccess, onError) = MyModel.BuildActionOptionDummyOneToManyListGet();
try
{
result.Data = await execute().CoreBaseExtTaskWithCurrentCulture(false);
onSuccess(result);
}
catch (Exception ex)
{
onError(ex, result);
}
return Ok(result);
}
/// <summary>
/// Добавить элемент.
/// </summary>
/// <param name="intput">Ввод.</param>
/// <returns>Результат выполнения с данными элемента.</returns>
[Route("item"), HttpPost]
public async Task<IActionResult> Post([FromBody] ModDummyMainBaseJobItemGetOutput input)
{
var result = new ModDummyMainBaseJobItemGetResult();
var (execute, onSuccess, onError) = MyModel.BuildActionItemInsert(input);
try
{
result.Data = await execute().CoreBaseExtTaskWithCurrentCulture(false);
onSuccess(result);
}
catch (Exception ex)
{
onError(ex, result);
}
return Ok(result);
}
/// <summary>
/// Обновить элемент.
/// </summary>
/// <param name="intput">Ввод.</param>
/// <returns>Результат выполнения с данными элемента.</returns>
[Route("item"), HttpPut]
public async Task<IActionResult> Put([FromBody] ModDummyMainBaseJobItemGetOutput input)
{
var result = new ModDummyMainBaseJobItemGetResult();
var (execute, onSuccess, onError) = MyModel.BuildActionItemUpdate(input);
try
{
result.Data = await execute().CoreBaseExtTaskWithCurrentCulture(false);
onSuccess(result);
}
catch (Exception ex)
{
onError(ex, result);
}
return Ok(result);
}
/// <summary>
/// Удалить элемент.
/// </summary>
/// <param name="intputData">Ввод.</param>
/// <returns>Результат выполнения.</returns>
[Route("item"), HttpDelete]
public async Task<IActionResult> Delete([FromQuery] ModDummyMainBaseJobItemGetInput input)
{
var result = new CoreBaseExecutionResult();
var (execute, onSuccess, onError) = MyModel.BuildActionItemDelete(input);
try
{
await execute().CoreBaseExtTaskWithCurrentCulture(false);
onSuccess(result);
}
catch (Exception ex)
{
onError(ex, result);
}
return Ok(result);
}
#endregion Public methods
}
} | 29.686099 | 98 | 0.554683 | [
"MIT"
] | balkar20/SibTrain | net-core/Makc2020.Mods.DummyMain.Web/Api/ModDummyMainWebApiController.cs | 7,037 | C# |
#if NET5_0_OR_GREATER
namespace Bunit
{
/// <summary>
/// Represents a bUnit JSInterop module.
/// </summary>
public sealed class BunitJSModuleInterop : BunitJSInterop
{
private readonly BunitJSInterop parent;
private JSRuntimeMode? handlerMode;
/// <summary>
/// Gets or sets whether this <see cref="BunitJSInterop"/>
/// is running in <see cref="JSRuntimeMode.Loose"/> or <see cref="JSRuntimeMode.Strict"/>.
/// </summary>
/// <remarks>
/// When this is not set explicitly, the mode from <see cref="BunitJSInterop.Mode"/> is used.
/// As soon as this is set, the mode will no longer be changed when the <see cref="BunitJSInterop.Mode"/>
/// changes.
/// </remarks>
public override JSRuntimeMode Mode
{
get => handlerMode ?? parent.Mode;
set => handlerMode = value;
}
/// <summary>
/// Initializes a new instance of the <see cref="BunitJSModuleInterop"/> class.
/// </summary>
/// <param name="parent">The parent <see cref="BunitJSInterop"/>.</param>
public BunitJSModuleInterop(BunitJSInterop parent)
: base()
{
this.parent = parent;
handlerMode = null;
}
/// <inheritdoc/>
internal override void RegisterInvocation(JSRuntimeInvocation invocation)
{
Invocations.RegisterInvocation(invocation);
parent.RegisterInvocation(invocation);
}
}
}
#endif
| 28.255319 | 107 | 0.689006 | [
"MIT"
] | Christian-Oleson/bUn | src/bunit.web/JSInterop/BunitJSModuleInterop.cs | 1,328 | C# |
using System.Linq;
using System.Runtime.InteropServices;
namespace Pomegranate
{
[StructLayout(LayoutKind.Auto)]
public readonly struct PomegranateNamespace
{
public int Length { get; init; }
public ulong[] HashSet { get; init; }
internal PomegranateNamespace(ulong[] hashSet)
{
HashSet = hashSet;
Length = hashSet.Length;
}
/// <summary>
/// Determines if a namespace is a subset of another namespace
/// </summary>
/// <param name="hash">Supplied namespace</param>
/// <returns>True if this namespace contains the supplied namespace as a subset</returns>
public bool Contains(PomegranateNamespace hash)
{
for (ushort i = 0; i < Length; i++)
{
if (!HashSet[i].Equals(hash.HashSet[i])) { return false; }
}
return true;
}
public override bool Equals(object? obj)
{
return obj is PomegranateNamespace hash && HashSet.SequenceEqual(hash.HashSet);
}
/// <summary>
/// This is generally not safe to use
/// Only use this in the same runtime as the object
/// and only keep it for the life of the object.
/// </summary>
public override int GetHashCode()
{
return HashSet.GetHashCode();
}
public static bool operator ==(PomegranateNamespace left, PomegranateNamespace right)
{
return left.Equals(right);
}
public static bool operator !=(PomegranateNamespace left, PomegranateNamespace right)
{
return !(left == right);
}
}
}
| 29.135593 | 97 | 0.568935 | [
"BSD-2-Clause"
] | rooper149/Pomegranate | Pomegranate/PomegranateNamespace.cs | 1,721 | C# |
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using Newtonsoft.Json;
using QuantConnect.AlgorithmFactory;
using QuantConnect.Brokerages;
using QuantConnect.Brokerages.InteractiveBrokers;
using QuantConnect.Configuration;
using QuantConnect.Data.Market;
using QuantConnect.Interfaces;
using QuantConnect.Lean.Engine.DataFeeds;
using QuantConnect.Lean.Engine.RealTime;
using QuantConnect.Lean.Engine.Results;
using QuantConnect.Lean.Engine.TransactionHandlers;
using QuantConnect.Logging;
using QuantConnect.Packets;
using QuantConnect.Securities;
using QuantConnect.Util;
namespace QuantConnect.Lean.Engine.Setup
{
/// <summary>
/// Defines a set up handler that initializes the algorithm instance using values retrieved from the user's brokerage account
/// </summary>
public class BrokerageSetupHandler : ISetupHandler
{
/// <summary>
/// Any errors from the initialization stored here:
/// </summary>
public List<string> Errors { get; set; }
/// <summary>
/// Get the maximum runtime for this algorithm job.
/// </summary>
public TimeSpan MaximumRuntime { get; private set; }
/// <summary>
/// Algorithm starting capital for statistics calculations
/// </summary>
public decimal StartingPortfolioValue { get; private set; }
/// <summary>
/// Start date for analysis loops to search for data.
/// </summary>
public DateTime StartingDate { get; private set; }
/// <summary>
/// Maximum number of orders for the algorithm run -- applicable for backtests only.
/// </summary>
public int MaxOrders { get; private set; }
// saves ref to algo so we can call quit if runtime error encountered
private IBrokerageFactory _factory;
/// <summary>
/// Initializes a new BrokerageSetupHandler
/// </summary>
public BrokerageSetupHandler()
{
Errors = new List<string>();
MaximumRuntime = TimeSpan.FromDays(10*365);
MaxOrders = int.MaxValue;
}
/// <summary>
/// Create a new instance of an algorithm from a physical dll path.
/// </summary>
/// <param name="assemblyPath">The path to the assembly's location</param>
/// <param name="algorithmNodePacket">Details of the task required</param>
/// <returns>A new instance of IAlgorithm, or throws an exception if there was an error</returns>
public IAlgorithm CreateAlgorithmInstance(AlgorithmNodePacket algorithmNodePacket, string assemblyPath)
{
string error;
IAlgorithm algorithm;
// limit load times to 10 seconds and force the assembly to have exactly one derived type
var loader = new Loader(algorithmNodePacket.Language, TimeSpan.FromSeconds(15), names => names.SingleOrAlgorithmTypeName(Config.Get("algorithm-type-name")));
var complete = loader.TryCreateAlgorithmInstanceWithIsolator(assemblyPath, algorithmNodePacket.RamAllocation, out algorithm, out error);
if (!complete) throw new Exception(error + " Try re-building algorithm and remove duplicate QCAlgorithm base classes.");
return algorithm;
}
/// <summary>
/// Creates the brokerage as specified by the job packet
/// </summary>
/// <param name="algorithmNodePacket">Job packet</param>
/// <param name="uninitializedAlgorithm">The algorithm instance before Initialize has been called</param>
/// <param name="factory">The brokerage factory</param>
/// <returns>The brokerage instance, or throws if error creating instance</returns>
public IBrokerage CreateBrokerage(AlgorithmNodePacket algorithmNodePacket, IAlgorithm uninitializedAlgorithm, out IBrokerageFactory factory)
{
var liveJob = algorithmNodePacket as LiveNodePacket;
if (liveJob == null)
{
throw new ArgumentException("BrokerageSetupHandler.CreateBrokerage requires a live node packet");
}
// find the correct brokerage factory based on the specified brokerage in the live job packet
_factory = Composer.Instance.Single<IBrokerageFactory>(brokerageFactory => brokerageFactory.BrokerageType.MatchesTypeName(liveJob.Brokerage));
factory = _factory;
// initialize the correct brokerage using the resolved factory
var brokerage = _factory.CreateBrokerage(liveJob, uninitializedAlgorithm);
return brokerage;
}
/// <summary>
/// Primary entry point to setup a new algorithm
/// </summary>
/// <param name="algorithm">Algorithm instance</param>
/// <param name="brokerage">New brokerage output instance</param>
/// <param name="job">Algorithm job task</param>
/// <param name="resultHandler">The configured result handler</param>
/// <param name="transactionHandler">The configurated transaction handler</param>
/// <param name="realTimeHandler">The configured real time handler</param>
/// <returns>True on successfully setting up the algorithm state, or false on error.</returns>
public bool Setup(IAlgorithm algorithm, IBrokerage brokerage, AlgorithmNodePacket job, IResultHandler resultHandler, ITransactionHandler transactionHandler, IRealTimeHandler realTimeHandler)
{
// verify we were given the correct job packet type
var liveJob = job as LiveNodePacket;
if (liveJob == null)
{
AddInitializationError("BrokerageSetupHandler requires a LiveNodePacket");
return false;
}
// verify the brokerage was specified
if (string.IsNullOrWhiteSpace(liveJob.Brokerage))
{
AddInitializationError("A brokerage must be specified");
return false;
}
// attach to the message event to relay brokerage specific initialization messages
EventHandler<BrokerageMessageEvent> brokerageOnMessage = (sender, args) =>
{
if (args.Type == BrokerageMessageType.Error)
{
AddInitializationError(string.Format("Brokerage Error Code: {0} - {1}", args.Code, args.Message));
}
};
try
{
Log.Trace("BrokerageSetupHandler.Setup(): Initializing algorithm...");
resultHandler.SendStatusUpdate(AlgorithmStatus.Initializing, "Initializing algorithm...");
//Execute the initialize code:
var controls = job.Controls;
var isolator = new Isolator();
var initializeComplete = isolator.ExecuteWithTimeLimit(TimeSpan.FromSeconds(300), () =>
{
try
{
//Set the default brokerage model before initialize
algorithm.SetBrokerageModel(_factory.BrokerageModel);
//Margin calls are disabled by default in live mode
algorithm.Portfolio.MarginCallModel = MarginCallModel.Null;
//Set our parameters
algorithm.SetParameters(job.Parameters);
algorithm.SetAvailableDataTypes(GetConfiguredDataFeeds());
//Algorithm is live, not backtesting:
algorithm.SetLiveMode(true);
//Initialize the algorithm's starting date
algorithm.SetDateTime(DateTime.UtcNow);
//Set the source impl for the event scheduling
algorithm.Schedule.SetEventSchedule(realTimeHandler);
// set the option chain provider
algorithm.SetOptionChainProvider(new CachingOptionChainProvider(new LiveOptionChainProvider()));
// If we're going to receive market data from IB,
// set the default subscription limit to 100,
// algorithms can override this setting in the Initialize method
if (brokerage is InteractiveBrokersBrokerage &&
liveJob.DataQueueHandler.EndsWith("InteractiveBrokersBrokerage"))
{
algorithm.Settings.DataSubscriptionLimit = 100;
}
//Initialise the algorithm, get the required data:
algorithm.Initialize();
if (liveJob.Brokerage != "PaperBrokerage")
{
//Zero the CashBook - we'll populate directly from brokerage
foreach (var kvp in algorithm.Portfolio.CashBook)
{
kvp.Value.SetAmount(0);
}
}
}
catch (Exception err)
{
AddInitializationError(err.ToString());
}
}, controls.RamAllocation);
if (!initializeComplete)
{
AddInitializationError("Initialization timed out.");
return false;
}
// let the world know what we're doing since logging in can take a minute
resultHandler.SendStatusUpdate(AlgorithmStatus.LoggingIn, "Logging into brokerage...");
brokerage.Message += brokerageOnMessage;
Log.Trace("BrokerageSetupHandler.Setup(): Connecting to brokerage...");
try
{
// this can fail for various reasons, such as already being logged in somewhere else
brokerage.Connect();
}
catch (Exception err)
{
Log.Error(err);
AddInitializationError(string.Format("Error connecting to brokerage: {0}. " +
"This may be caused by incorrect login credentials or an unsupported account type.", err.Message));
return false;
}
if (!brokerage.IsConnected)
{
// if we're reporting that we're not connected, bail
AddInitializationError("Unable to connect to brokerage.");
return false;
}
Log.Trace("BrokerageSetupHandler.Setup(): Fetching cash balance from brokerage...");
try
{
// set the algorithm's cash balance for each currency
var cashBalance = brokerage.GetCashBalance();
foreach (var cash in cashBalance)
{
Log.Trace("BrokerageSetupHandler.Setup(): Setting " + cash.Symbol + " cash to " + cash.Amount);
algorithm.Portfolio.SetCash(cash.Symbol, cash.Amount, cash.ConversionRate);
}
}
catch (Exception err)
{
Log.Error(err);
AddInitializationError("Error getting cash balance from brokerage: " + err.Message);
return false;
}
Log.Trace("BrokerageSetupHandler.Setup(): Fetching open orders from brokerage...");
try
{
// populate the algorithm with the account's outstanding orders
var openOrders = brokerage.GetOpenOrders();
foreach (var order in openOrders)
{
// be sure to assign order IDs such that we increment from the SecurityTransactionManager to avoid ID collisions
Log.Trace("BrokerageSetupHandler.Setup(): Has open order: " + order.Symbol.Value + " - " + order.Quantity);
order.Id = algorithm.Transactions.GetIncrementOrderId();
transactionHandler.Orders.AddOrUpdate(order.Id, order, (i, o) => order);
}
}
catch (Exception err)
{
Log.Error(err);
AddInitializationError("Error getting open orders from brokerage: " + err.Message);
return false;
}
Log.Trace("BrokerageSetupHandler.Setup(): Fetching holdings from brokerage...");
try
{
// populate the algorithm with the account's current holdings
var holdings = brokerage.GetAccountHoldings();
var supportedSecurityTypes = new HashSet<SecurityType> { SecurityType.Equity, SecurityType.Forex, SecurityType.Cfd, SecurityType.Option, SecurityType.Future };
var minResolution = new Lazy<Resolution>(() => algorithm.Securities.Select(x => x.Value.Resolution).DefaultIfEmpty(Resolution.Second).Min());
foreach (var holding in holdings)
{
Log.Trace("BrokerageSetupHandler.Setup(): Has existing holding: " + holding);
// verify existing holding security type
if (!supportedSecurityTypes.Contains(holding.Type))
{
Log.Error("BrokerageSetupHandler.Setup(): Unsupported security type: " + holding.Type + "-" + holding.Symbol.Value);
AddInitializationError("Found unsupported security type in existing brokerage holdings: " + holding.Type + ". " +
"QuantConnect currently supports the following security types: " + string.Join(",", supportedSecurityTypes));
// keep aggregating these errors
continue;
}
if (!algorithm.Portfolio.ContainsKey(holding.Symbol))
{
Log.Trace("BrokerageSetupHandler.Setup(): Adding unrequested security: " + holding.Symbol.Value);
if (holding.Type == SecurityType.Option)
{
// add current option contract to the system
algorithm.AddOptionContract(holding.Symbol, minResolution.Value, true, 1.0m);
}
else if (holding.Type == SecurityType.Future)
{
// add current future contract to the system
algorithm.AddFutureContract(holding.Symbol, minResolution.Value, true, 1.0m);
}
else
{
// for items not directly requested set leverage to 1 and at the min resolution
algorithm.AddSecurity(holding.Type, holding.Symbol.Value, minResolution.Value, null, true, 1.0m, false);
}
}
algorithm.Portfolio[holding.Symbol].SetHoldings(holding.AveragePrice, holding.Quantity);
algorithm.Securities[holding.Symbol].SetMarketPrice(new TradeBar
{
Time = DateTime.Now,
Open = holding.MarketPrice,
High = holding.MarketPrice,
Low = holding.MarketPrice,
Close = holding.MarketPrice,
Volume = 0,
Symbol = holding.Symbol,
DataType = MarketDataType.TradeBar
});
}
}
catch (Exception err)
{
Log.Error(err);
AddInitializationError("Error getting account holdings from brokerage: " + err.Message);
return false;
}
algorithm.PostInitialize();
//Set the starting portfolio value for the strategy to calculate performance:
StartingPortfolioValue = algorithm.Portfolio.TotalPortfolioValue;
StartingDate = DateTime.Now;
}
catch (Exception err)
{
AddInitializationError(err.ToString());
}
finally
{
if (brokerage != null)
{
brokerage.Message -= brokerageOnMessage;
}
}
return Errors.Count == 0;
}
/// <summary>
/// Get the available data feeds from config.json,
/// If none available, throw an error
/// </summary>
private static Dictionary<SecurityType, List<TickType>> GetConfiguredDataFeeds()
{
var dataFeedsConfigString = Config.Get("security-data-feeds");
Dictionary<SecurityType, List<TickType>> dataFeeds = new Dictionary<SecurityType, List<TickType>>();
if (dataFeedsConfigString != string.Empty)
{
dataFeeds = JsonConvert.DeserializeObject<Dictionary<SecurityType, List<TickType>>>(dataFeedsConfigString);
}
return dataFeeds;
}
/// <summary>
/// Adds initializaion error to the Errors list
/// </summary>
/// <param name="message">The error message to be added</param>
private void AddInitializationError(string message)
{
Errors.Add("Failed to initialize algorithm: " + message);
}
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
/// </summary>
/// <filterpriority>2</filterpriority>
public void Dispose()
{
if (_factory != null)
{
_factory.Dispose();
}
}
}
}
| 45.94964 | 198 | 0.559626 | [
"MIT"
] | jdm7dv/financial | windows/Lean/Engine/Setup/BrokerageSetupHandler.cs | 19,163 | C# |
using System;
using System.Diagnostics;
#if CONTRACTS_FULL
using System.Diagnostics.Contracts;
#else
using PixelLab.Contracts;
#endif
using System.Windows;
namespace PixelLab.Common
{
public class GeoHelper
{
/// <summary>
/// Returns the scale factor by which an object of size <paramref name="source"/>
/// should be scaled to fit within an object of size <param name="target"/>.
/// </summary>
/// <param name="target">The target size.</param>
/// <param name="size2">The source size.</param>
public double ScaleToFit(Size target, Size source)
{
Contract.Requires(target.IsValid());
Contract.Requires(source.IsValid());
Contract.Requires(target.Width > 0);
Contract.Requires(source.Width > 0);
double targetHWR = target.Height / target.Width;
double sourceHWR = source.Height / source.Width;
if (targetHWR > sourceHWR)
{
return target.Width / source.Width;
}
else
{
return target.Height / source.Height;
}
}
public bool Animate(
double currentValue, double currentVelocity, double targetValue,
double attractionFator, double dampening,
double terminalVelocity, double minValueDelta, double minVelocityDelta,
out double newValue, out double newVelocity)
{
Debug.Assert(currentValue.IsValid());
Debug.Assert(currentVelocity.IsValid());
Debug.Assert(targetValue.IsValid());
Debug.Assert(dampening.IsValid());
Debug.Assert(dampening > 0 && dampening < 1);
Debug.Assert(attractionFator.IsValid());
Debug.Assert(attractionFator > 0);
Debug.Assert(terminalVelocity > 0);
Debug.Assert(minValueDelta > 0);
Debug.Assert(minVelocityDelta > 0);
double diff = targetValue - currentValue;
if (diff.Abs() > minValueDelta || currentVelocity.Abs() > minVelocityDelta)
{
newVelocity = currentVelocity * (1 - dampening);
newVelocity += diff * attractionFator;
if (currentVelocity.Abs() > terminalVelocity)
{
newVelocity *= terminalVelocity / currentVelocity.Abs();
}
newValue = currentValue + newVelocity;
return true;
}
else
{
newValue = targetValue;
newVelocity = 0;
return false;
}
}
public bool Animate(
Point currentValue, Vector currentVelocity, Point targetValue,
double attractionFator, double dampening,
double terminalVelocity, double minValueDelta, double minVelocityDelta,
out Point newValue, out Vector newVelocity)
{
Debug.Assert(currentValue.IsValid());
Debug.Assert(currentVelocity.IsValid());
Debug.Assert(targetValue.IsValid());
Debug.Assert(dampening.IsValid());
Debug.Assert(dampening > 0 && dampening < 1);
Debug.Assert(attractionFator.IsValid());
Debug.Assert(attractionFator > 0);
Debug.Assert(terminalVelocity > 0);
Debug.Assert(minValueDelta > 0);
Debug.Assert(minVelocityDelta > 0);
Vector diff = targetValue.Subtract(currentValue);
if (diff.Length > minValueDelta || currentVelocity.Length > minVelocityDelta)
{
newVelocity = currentVelocity * (1 - dampening);
newVelocity += diff * attractionFator;
if (currentVelocity.Length > terminalVelocity)
{
newVelocity *= terminalVelocity / currentVelocity.Length;
}
newValue = currentValue + newVelocity;
return true;
}
else
{
newValue = targetValue;
newVelocity = new Vector();
return false;
}
}
public double AngleRad(Point point1, Point point2, Point point3)
{
Debug.Assert(point1.IsValid());
Debug.Assert(point2.IsValid());
Debug.Assert(point3.IsValid());
double rad = AngleRad(point2.Subtract(point1), point2.Subtract(point3));
double rad2 = AngleRad(point2.Subtract(point1), (point2.Subtract(point3)).RightAngle());
if (rad2 < (Math.PI / 2))
{
return rad;
}
else
{
return (Math.PI * 2) - rad;
}
}
public double Dot(Vector v1, Vector v2)
{
Debug.Assert(v1.IsValid());
Debug.Assert(v2.IsValid());
return v1.X * v2.X + v1.Y * v2.Y;
}
public double AngleRad(Vector v1, Vector v2)
{
Debug.Assert(v1.IsValid());
Debug.Assert(v2.IsValid());
double dot = Dot(v1, v2);
double dotNormalize = dot / (v1.Length * v2.Length);
double acos = Math.Acos(dotNormalize);
return acos;
}
public Vector GetVectorFromAngle(double angleRadians, double length)
{
Contract.Requires(angleRadians.IsValid());
Contract.Requires(length.IsValid());
double x = Math.Cos(angleRadians) * length;
double y = -Math.Sin(angleRadians) * length;
return new Vector(x, y);
}
public readonly Size SizeInfinite = new Size(double.PositiveInfinity, double.PositiveInfinity);
}
}
| 31.489247 | 104 | 0.543964 | [
"MIT"
] | WertherHu/AYUI8Community | Ay/ay/SDK/ThreeLib/Transitions/Core/GeoHelper.cs | 5,859 | C# |
using System;
namespace EasyCli.ConsoleInterface
{
public enum OutputColor
{
Black, DarkBlue, DarkGreen, DarkCyan, DarkRed, DarkMagenta,
DarkYellow, Gray, DarkGray, Blue, Green, Cyan, Red, Magenta,
Yellow, White
}
public static class OutputColorExtensions
{
public static ConsoleColor ToConsoleColor(this OutputColor color)
{
switch (color)
{
case OutputColor.Black:
return ConsoleColor.Black;
case OutputColor.DarkBlue:
return ConsoleColor.DarkBlue;
case OutputColor.DarkGreen:
return ConsoleColor.DarkGreen;
case OutputColor.DarkCyan:
return ConsoleColor.DarkCyan;
case OutputColor.DarkRed:
return ConsoleColor.DarkRed;
case OutputColor.DarkMagenta:
return ConsoleColor.DarkMagenta;
case OutputColor.DarkYellow:
return ConsoleColor.DarkYellow;
case OutputColor.Gray:
return ConsoleColor.Gray;
case OutputColor.DarkGray:
return ConsoleColor.DarkGray;
case OutputColor.Blue:
return ConsoleColor.Blue;
case OutputColor.Green:
return ConsoleColor.Green;
case OutputColor.Cyan:
return ConsoleColor.Cyan;
case OutputColor.Red:
return ConsoleColor.Red;
case OutputColor.Magenta:
return ConsoleColor.Magenta;
case OutputColor.Yellow:
return ConsoleColor.Yellow;
case OutputColor.White:
return ConsoleColor.White;
default:
return ConsoleColor.White;
}
}
public static OutputColor ToOutputColor(this ConsoleColor color)
{
switch (color)
{
case ConsoleColor.Black:
return OutputColor.Black;
case ConsoleColor.Blue:
return OutputColor.Blue;
case ConsoleColor.Cyan:
return OutputColor.Cyan;
case ConsoleColor.DarkBlue:
return OutputColor.DarkBlue;
case ConsoleColor.DarkCyan:
return OutputColor.DarkCyan;
case ConsoleColor.DarkGray:
return OutputColor.DarkGray;
case ConsoleColor.DarkGreen:
return OutputColor.DarkGreen;
case ConsoleColor.DarkMagenta:
return OutputColor.DarkMagenta;
case ConsoleColor.DarkRed:
return OutputColor.DarkRed;
case ConsoleColor.DarkYellow:
return OutputColor.DarkYellow;
case ConsoleColor.Gray:
return OutputColor.Gray;
case ConsoleColor.Green:
return OutputColor.Green;
case ConsoleColor.Magenta:
return OutputColor.Magenta;
case ConsoleColor.Red:
return OutputColor.Red;
case ConsoleColor.Yellow:
return OutputColor.Yellow;
case ConsoleColor.White:
return OutputColor.White;
default:
return OutputColor.White;
}
}
}
public interface IOutput : IDisposable
{
#region Meta Information and advanced features
/// <summary>
/// Gets or sets the line terminator string used by the current TextWriter
/// </summary>
string NewLine { get; set; }
/// <summary>
/// Sets font color of the display.
///
/// This property may do nothing
/// </summary>
OutputColor ForegrondColor { get; set; }
/// <summary>
/// Sets background color of the display.
///
/// This property may do nothing
/// </summary>
OutputColor BackgroundColor { get; set; }
/// <summary>
/// Resets the background and foreground colors back to their defaults.
///
/// If Foreground and/or BackgroundColor are considered, this may not do nothing
/// </summary>
void ResetColor();
#endregion
#region Writting functions
/// <summary>
/// Clears the buffer for the current writer and causes any buffered data
/// to be written to the underlying device
/// </summary>
void Flush();
#region Write
void Write(char value);
void Write(string value);
void Write(string format, params object[] arg);
void Write(int value);
void Write(long value);
void Write(float value);
void Write(double value);
void Write(decimal value);
void Write(char[] buffer, int index, int count);
void Write(char[] buffer);
void Write(bool value);
void Write(object value);
#endregion
#region WriteLine
void WriteLine();
void WriteLine(char value);
void WriteLine(string value);
void WriteLine(string format, params object[] arg);
void WriteLine(int value);
void WriteLine(long value);
void WriteLine(float value);
void WriteLine(double value);
void WriteLine(decimal value);
void WriteLine(char[] buffer, int index, int count);
void WriteLine(char[] buffer);
void WriteLine(bool value);
void WriteLine(object value);
#endregion
#endregion
}
}
| 35.439759 | 88 | 0.537821 | [
"MIT"
] | AblingerOscar/EasyCLI | EasyCLI/ConsoleInterface/IOutput.cs | 5,885 | C# |
/*
Project Orleans Cloud Service SDK ver. 1.0
Copyright (c) Microsoft Corporation
All rights reserved.
MIT License
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
associated documentation files (the ""Software""), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO
THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS
OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
using System;
using System.Collections.Generic;
using System.Data.Common;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Orleans.SqlUtils;
namespace UnitTests.General
{
public abstract class RelationalStorageForTesting
{
private static readonly Dictionary<string, Func<string, RelationalStorageForTesting>> instanceFactory =
new Dictionary<string, Func<string, RelationalStorageForTesting>>
{
{AdoNetInvariants.InvariantNameSqlServer, cs => new SqlServerStorageForTesting(cs)},
{AdoNetInvariants.InvariantNameMySql, cs => new MySqlStorageForTesting(cs)}
};
private readonly IRelationalStorage storage;
public string CurrentConnectionString
{
get { return storage.ConnectionString; }
}
/// <summary>
/// Default connection string for testing
/// </summary>
public abstract string DefaultConnectionString { get; }
/// <summary>
/// The script that creates Orleans schema in the database, usually CreateOrleansTables_xxxx.sql
/// </summary>
protected abstract string SetupSqlScriptFileName { get; }
/// <summary>
/// A query template to create a database with a given name.
/// </summary>
protected abstract string CreateDatabaseTemplate { get; }
/// <summary>
/// A query template to drop a database with a given name.
/// </summary>
protected abstract string DropDatabaseTemplate { get; }
/// <summary>
/// A query template if a database with a given name exists.
/// </summary>
protected abstract string ExistsDatabaseTemplate { get; }
/// <summary>
/// Converts the given script into batches to execute sequentially
/// </summary>
/// <param name="setupScript">the script. usually CreateOrleansTables_xxxx.sql</param>
protected abstract IEnumerable<string> ConvertToExecutableBatches(string setupScript, string databaseName);
public static async Task<RelationalStorageForTesting> SetupInstance(string invariantName, string testDatabaseName)
{
if (string.IsNullOrWhiteSpace(invariantName))
{
throw new ArgumentException("The name of invariant must contain characters", "invariantName");
}
if (string.IsNullOrWhiteSpace(testDatabaseName))
{
throw new ArgumentException("database string must contain characters", "testDatabaseName");
}
Console.WriteLine("Initializing relational databases...");
var testStorage = CreateTestInstance(invariantName);
Console.WriteLine("Dropping and recreating database '{0}' with connectionstring '{1}'", testDatabaseName, testStorage.DefaultConnectionString);
if (await testStorage.ExistsDatabaseAsync(testDatabaseName))
{
await testStorage.DropDatabaseAsync(testDatabaseName);
}
await testStorage.CreateDatabaseAsync(testDatabaseName);
//The old storage instance has the previous connection string, time have a new handle with a new connection string...
testStorage = testStorage.CopyInstance(testDatabaseName);
Console.WriteLine("Creating database tables...");
var setupScript = File.ReadAllText(testStorage.SetupSqlScriptFileName);
await testStorage.ExecuteSetupScript(setupScript, testDatabaseName);
Console.WriteLine("Initializing relational databases done.");
return testStorage;
}
private static RelationalStorageForTesting CreateTestInstance(string invariantName, string connectionString)
{
return instanceFactory[invariantName](connectionString);
}
private static RelationalStorageForTesting CreateTestInstance(string invariantName)
{
return CreateTestInstance(invariantName, CreateTestInstance(invariantName, "notempty").DefaultConnectionString);
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="invariantName"></param>
/// <param name="connectionString"></param>
protected RelationalStorageForTesting(string invariantName, string connectionString)
{
storage = RelationalStorage.CreateInstance(invariantName, connectionString);
}
/// <summary>
/// Executes the given script in a test context.
/// </summary>
/// <param name="setupScript">the script. usually CreateOrleansTables_xxxx.sql</param>
/// <param name="dataBaseName">the target database to be populated</param>
/// <returns></returns>
private async Task ExecuteSetupScript(string setupScript, string dataBaseName)
{
var splitScripts = ConvertToExecutableBatches(setupScript, dataBaseName);
foreach (var script in splitScripts)
{
var res1 = await storage.ExecuteAsync(script);
}
}
/// <summary>
/// Checks the existence of a database using the given <see paramref="storage"/> storage object.
/// </summary>
/// <param name="databaseName">The name of the database existence of which to check.</param>
/// <returns><em>TRUE</em> if the given database exists. <em>FALSE</em> otherwise.</returns>
private async Task<bool> ExistsDatabaseAsync(string databaseName)
{
var ret = await storage.ReadAsync(string.Format(ExistsDatabaseTemplate, databaseName), command =>
{ }, (selector, resultSetCount) => { return selector.GetBoolean(0); }).ConfigureAwait(continueOnCapturedContext: false);
return ret.First();
}
/// <summary>
/// Creates a database with a given name.
/// </summary>
/// <param name="databaseName">The name of the database to create.</param>
/// <returns>The call will be successful if the DDL query is successful. Otherwise an exception will be thrown.</returns>
private async Task CreateDatabaseAsync(string databaseName)
{
await storage.ExecuteAsync(string.Format(CreateDatabaseTemplate, databaseName), command => { }).ConfigureAwait(continueOnCapturedContext: false);
}
/// <summary>
/// Drops a database with a given name.
/// </summary>
/// <param name="databaseName">The name of the database to drop.</param>
/// <returns>The call will be successful if the DDL query is successful. Otherwise an exception will be thrown.</returns>
private Task DropDatabaseAsync(string databaseName)
{
return storage.ExecuteAsync(string.Format(DropDatabaseTemplate, databaseName), command => { });
}
/// <summary>
/// Creates a new instance of the storage based on the old connection string by changing the database name.
/// </summary>
/// <param name="newDatabaseName">Connection string instance name of the database.</param>
/// <returns>A new <see cref="RelationalStorageForTesting"/> instance with having the same connection string but with with a new databaseName.</returns>
private RelationalStorageForTesting CopyInstance(string newDatabaseName)
{
var csb = new DbConnectionStringBuilder();
csb.ConnectionString = storage.ConnectionString;
csb["Database"] = newDatabaseName;
return CreateTestInstance(storage.InvariantName, csb.ConnectionString);
}
}
}
| 44.079208 | 160 | 0.66925 | [
"MIT"
] | rikace/orleans | src/Tester/RelationalUtilities/RelationalStorageForTesting.cs | 8,906 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Pepe
{
static class Program
{
/// <summary>
/// Ponto de entrada principal para o aplicativo.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new FrmMain());
}
}
}
| 22.130435 | 65 | 0.611002 | [
"MIT"
] | lbert1/Pepe-Robot | Program.cs | 511 | C# |
using System;
using System.Reflection;
using System.Runtime.CompilerServices;
namespace LeaderEngine
{
public static class Logger
{
public static bool IgnoreInfo = false;
public static bool IgnoreWarning = false;
public static bool IgnoreError = false;
[MethodImpl(MethodImplOptions.NoInlining)]
public static void Log(object msg, bool forceShow = false)
{
if (IgnoreInfo && !forceShow)
return;
Console.ForegroundColor = ConsoleColor.White;
Console.WriteLine($"[{Assembly.GetCallingAssembly().GetName().Name}] " + msg.ToString());
}
[MethodImpl(MethodImplOptions.NoInlining)]
public static void LogWarning(object msg, bool forceShow = false)
{
if (IgnoreWarning && !forceShow)
return;
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine($"[{Assembly.GetCallingAssembly().GetName().Name}] " + msg.ToString());
Console.ForegroundColor = ConsoleColor.White;
}
[MethodImpl(MethodImplOptions.NoInlining)]
public static void LogError(object msg, bool forceShow = false)
{
if (IgnoreError && !forceShow)
return;
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine($"[{Assembly.GetCallingAssembly().GetName().Name}] " + msg.ToString());
Console.ForegroundColor = ConsoleColor.White;
}
}
} | 33.844444 | 101 | 0.616546 | [
"MIT"
] | Reimnop/LeaderEngine | LeaderEngine/Logic/Logger.cs | 1,525 | C# |
///////////////////////////////////////////////////////////////////////////////
//
// Microsoft Research Singularity
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// Note:
//
using System;
namespace Microsoft.Singularity.UnitTest
{
// This annotation on an assembly indicates that the assembly should be treated
// as a stand-alone test application.
//
[AttributeUsage(AttributeTargets.Method)]
public sealed class TestSetupAttribute : Attribute
{
}
}
| 23.043478 | 84 | 0.566038 | [
"MIT"
] | sphinxlogic/Singularity-RDK-2.0 | base/Libraries/UnitTest/TestSetupAttribute.cs | 530 | C# |
using System;
using System.Collections.Generic;
using System.Text;
namespace SimerERP.Domain.Entities
{
public class TestERP
{
public int TestERPId { get; set; }
public string Name { get; set; }
public string Text { get; set; }
}
}
| 17.0625 | 42 | 0.630037 | [
"MIT"
] | n3v3r94/MediatR-CQRS | SimerERP.Domain/Entities/TestERP.cs | 275 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.Automation.Models
{
using Microsoft.Azure;
using Microsoft.Azure.Management;
using Microsoft.Azure.Management.Automation;
using Newtonsoft.Json;
using System.Linq;
/// <summary>
/// The dsc nodeconfiguration property associated with the entity.
/// </summary>
public partial class DscNodeConfigurationAssociationProperty
{
/// <summary>
/// Initializes a new instance of the
/// DscNodeConfigurationAssociationProperty class.
/// </summary>
public DscNodeConfigurationAssociationProperty()
{
CustomInit();
}
/// <summary>
/// Initializes a new instance of the
/// DscNodeConfigurationAssociationProperty class.
/// </summary>
/// <param name="name">Gets or sets the name of the dsc
/// nodeconfiguration.</param>
public DscNodeConfigurationAssociationProperty(string name = default(string))
{
Name = name;
CustomInit();
}
/// <summary>
/// An initialization method that performs custom operations like setting defaults
/// </summary>
partial void CustomInit();
/// <summary>
/// Gets or sets the name of the dsc nodeconfiguration.
/// </summary>
[JsonProperty(PropertyName = "name")]
public string Name { get; set; }
}
}
| 31.303571 | 90 | 0.635482 | [
"MIT"
] | AzureAutomationTeam/azure-sdk-for-net | src/SDKs/Automation/Management.Automation/Generated/Models/DscNodeConfigurationAssociationProperty.cs | 1,753 | C# |
using System;
using Cosmos.Common.Extensions;
namespace Cosmos.Common
{
/// <summary>
/// Helper class for working with numbers.
/// </summary>
public static class NumberHelper
{
/// <summary>
/// Write number to console.
/// </summary>
/// <param name="aValue">A value to print.</param>
/// <param name="aZeroFill">A value indicating whether strarting zeros should be present.</param>
public static void WriteNumber(uint aValue, bool aZeroFill)
{
WriteNumber(aValue, 32, aZeroFill);
}
/// <summary>
/// Write number to console.
/// </summary>
/// <param name="aValue">A value to print.</param>
/// <param name="aBits">Count of bits to display.</param>
public static void WriteNumber(uint aValue, int aBits)
{
WriteNumber(aValue, aBits, true);
}
/// <summary>
/// Write number to console.
/// </summary>
/// <param name="aValue">A value to print.</param>
/// <param name="aBits">Count of bits to display.</param>
/// <param name="aZeroFill">A value indicating whether strarting zeros should be present.</param>
public static void WriteNumber(uint aValue, int aBits, bool aZeroFill)
{
if (aZeroFill)
{
Console.WriteLine("0x" + aValue.ToHex(aBits / 4));
}
else
{
Console.WriteLine("0x" + aValue.ToHex(aBits / 4).TrimStart('0'));
}
}
}
}
| 31.82 | 105 | 0.543683 | [
"BSD-3-Clause"
] | AcaiBerii/Cosmos | source/Cosmos.Common/NumberHelper.cs | 1,593 | C# |
using CryptoExchange.Net.Converters;
using Paribu.Net.Enums;
using System.Collections.Generic;
namespace Paribu.Net.Converters
{
public class TradeRoleConverter : BaseConverter<TradeRole>
{
public TradeRoleConverter() : this(true) { }
public TradeRoleConverter(bool quotes) : base(quotes) { }
protected override List<KeyValuePair<TradeRole, string>> Mapping => new List<KeyValuePair<TradeRole, string>>
{
new KeyValuePair<TradeRole, string>(TradeRole.Maker, "maker"),
new KeyValuePair<TradeRole, string>(TradeRole.Taker, "taker"),
};
}
} | 34.222222 | 117 | 0.685065 | [
"MIT"
] | burakoner/Paribu.Net | Paribu.Net/Converters/TradeRoleConverter.cs | 618 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by Cake.
// </auto-generated>
//------------------------------------------------------------------------------
using System.Reflection;
[assembly: AssemblyCompany("FrannDotExe")]
| 34.777778 | 81 | 0.341853 | [
"MIT"
] | Frannsoft/FrannHammer | src/SolutionInfo.cs | 315 | C# |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Handelabra.Sentinels.Engine.Controller;
using Handelabra.Sentinels.Engine.Model;
namespace Riverport.Weaver
{
public class HastePatchCardController : PhaseActionPatchCardController
{
public HastePatchCardController(Card card, TurnTakerController turnTakerController) : base(card, turnTakerController)
{
}
protected override Phase IncreasedPhase => Phase.PlayCard;
}
}
| 26.65 | 125 | 0.765478 | [
"MIT"
] | DrakoGlyph/Riverport | Riverport/Hero/Weaver/Patches/HastePatchCardController.cs | 535 | C# |
namespace IbFlexReader.Xml.Contracts.QueryResponse
{
using System.Xml.Serialization;
[XmlRoot(ElementName = "TierInterestDetail")]
public class TierInterestDetail
{
[XmlAttribute(AttributeName = "accountId")]
public string AccountId { get; set; }
[XmlAttribute(AttributeName = "acctAlias")]
public string AcctAlias { get; set; }
[XmlAttribute(AttributeName = "model")]
public string Model { get; set; }
[XmlAttribute(AttributeName = "currency")]
public string Currency { get; set; }
[XmlAttribute(AttributeName = "fxRateToBase")]
public string FxRateToBase { get; set; }
[XmlAttribute(AttributeName = "code")]
public string Code { get; set; }
[XmlAttribute(AttributeName = "toAcct")]
public string ToAcct { get; set; }
[XmlAttribute(AttributeName = "fromAcct")]
public string FromAcct { get; set; }
[XmlAttribute(AttributeName = "totalInterest")]
public string TotalInterest { get; set; }
[XmlAttribute(AttributeName = "ibuklInterest")]
public string IbuklInterest { get; set; }
[XmlAttribute(AttributeName = "commoditiesInterest")]
public string CommoditiesInterest { get; set; }
[XmlAttribute(AttributeName = "securitiesInterest")]
public string SecuritiesInterest { get; set; }
[XmlAttribute(AttributeName = "rate")]
public string Rate { get; set; }
[XmlAttribute(AttributeName = "totalPrincipal")]
public string TotalPrincipal { get; set; }
[XmlAttribute(AttributeName = "ibuklPrincipal")]
public string IbuklPrincipal { get; set; }
[XmlAttribute(AttributeName = "commoditiesPrincipal")]
public string CommoditiesPrincipal { get; set; }
[XmlAttribute(AttributeName = "securitiesPrincipal")]
public string SecuritiesPrincipal { get; set; }
[XmlAttribute(AttributeName = "balanceThreshold")]
public string BalanceThreshold { get; set; }
[XmlAttribute(AttributeName = "tierBreak")]
public string TierBreak { get; set; }
[XmlAttribute(AttributeName = "valueDate")]
public string ValueDate { get; set; }
[XmlAttribute(AttributeName = "interestType")]
public string InterestType { get; set; }
}
}
| 32.958333 | 62 | 0.641804 | [
"MIT"
] | JueMueller/ib-flex-reader | IbFlexReader/IbFlexReader.Xml/Contracts/QueryResponse/TierInterestDetail.cs | 2,375 | C# |
//
// System.Data.FillOptions.cs
//
// Author:
// Tim Coleman (tim@timcoleman.com)
//
// Copyright (C) Tim Coleman, 2003
//
//
// Copyright (C) 2004 Novell, Inc (http://www.novell.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.
//
namespace System.Data {
public enum FillOptions
{
None,
FillChildren,
FillExtendedSchema,
FillWithoutExtendedMetaData
}
}
| 31.311111 | 73 | 0.741661 | [
"Apache-2.0"
] | BitExodus/test01 | mcs/class/System.Data/System.Data/FillOptions.cs | 1,409 | C# |
using System.Windows.Input;
using Xamarin.Forms;
namespace PlantHunter.Mobile.Core.Behaviors
{
public sealed class ItemTappedCommandListView
{
public static readonly BindableProperty ItemTappedCommandProperty =
BindableProperty.CreateAttached(
"ItemTappedCommand",
typeof(ICommand),
typeof(ItemTappedCommandListView),
default(ICommand),
BindingMode.OneWay,
null,
PropertyChanged);
static void PropertyChanged(BindableObject bindable, object oldValue, object newValue)
{
if (bindable is ListView listView)
{
listView.ItemTapped -= ListViewOnItemTapped;
listView.ItemTapped += ListViewOnItemTapped;
}
}
static void ListViewOnItemTapped(object sender, ItemTappedEventArgs e)
{
if (sender is ListView list && list.IsEnabled && !list.IsRefreshing)
{
list.SelectedItem = null;
var command = GetItemTappedCommand(list);
if (command != null && command.CanExecute(e.Item))
{
command.Execute(e.Item);
}
}
}
public static ICommand GetItemTappedCommand(BindableObject bindableObject) => (ICommand)bindableObject.GetValue(ItemTappedCommandProperty);
public static void SetItemTappedCommand(BindableObject bindableObject, object value) => bindableObject.SetValue(ItemTappedCommandProperty, value);
}
} | 36.477273 | 154 | 0.607477 | [
"MIT"
] | HACC2018/Canoe-tree | PlantHunter.Mobile/PlantHunter.Mobile.Core/Behaviors/ItemTappedCommandListView.cs | 1,607 | C# |
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
namespace FlatEarth.Screens.Transitions
{
public class TransitionCrossFade : ScreenTransition
{
public TransitionCrossFade(int lengthInMilliseconds) : base(lengthInMilliseconds)
{
}
public override void Draw(RenderTarget2D target, SpriteBatch spriteBatch, RenderTarget2D currentScreen, RenderTarget2D newScreen)
{
spriteBatch.SetRenderTargetAndClear(target, Color.Black);
spriteBatch.Begin();
spriteBatch.Draw(currentScreen, Vector2.Zero, Color.White * (1 - PercentDone));
spriteBatch.Draw(newScreen, Vector2.Zero, Color.White * PercentDone);
spriteBatch.End();
}
}
}
| 33.173913 | 137 | 0.688073 | [
"MIT"
] | Saliken/FlatEarth | FlatEarth.Framework/Screens/Transitions/TransitionCrossFade.cs | 765 | C# |
using System.Collections.Generic;
using Essensoft.AspNetCore.Payment.Alipay.Response;
namespace Essensoft.AspNetCore.Payment.Alipay.Request
{
/// <summary>
/// alipay.open.app.silan.apigrayfive.query
/// </summary>
public class AlipayOpenAppSilanApigrayfiveQueryRequest : IAlipayRequest<AlipayOpenAppSilanApigrayfiveQueryResponse>
{
#region IAlipayRequest Members
private bool needEncrypt = true;
private string apiVersion = "1.0";
private string terminalType;
private string terminalInfo;
private string prodCode;
private string notifyUrl;
private string returnUrl;
private AlipayObject bizModel;
public void SetNeedEncrypt(bool needEncrypt)
{
this.needEncrypt = needEncrypt;
}
public bool GetNeedEncrypt()
{
return needEncrypt;
}
public void SetNotifyUrl(string notifyUrl)
{
this.notifyUrl = notifyUrl;
}
public string GetNotifyUrl()
{
return notifyUrl;
}
public void SetReturnUrl(string returnUrl)
{
this.returnUrl = returnUrl;
}
public string GetReturnUrl()
{
return returnUrl;
}
public void SetTerminalType(string terminalType)
{
this.terminalType = terminalType;
}
public string GetTerminalType()
{
return terminalType;
}
public void SetTerminalInfo(string terminalInfo)
{
this.terminalInfo = terminalInfo;
}
public string GetTerminalInfo()
{
return terminalInfo;
}
public void SetProdCode(string prodCode)
{
this.prodCode = prodCode;
}
public string GetProdCode()
{
return prodCode;
}
public string GetApiName()
{
return "alipay.open.app.silan.apigrayfive.query";
}
public void SetApiVersion(string apiVersion)
{
this.apiVersion = apiVersion;
}
public string GetApiVersion()
{
return apiVersion;
}
public IDictionary<string, string> GetParameters()
{
var parameters = new AlipayDictionary();
return parameters;
}
public AlipayObject GetBizModel()
{
return bizModel;
}
public void SetBizModel(AlipayObject bizModel)
{
this.bizModel = bizModel;
}
#endregion
}
}
| 23.06087 | 119 | 0.562971 | [
"MIT"
] | LuohuaRain/payment | src/Essensoft.AspNetCore.Payment.Alipay/Request/AlipayOpenAppSilanApigrayfiveQueryRequest.cs | 2,654 | C# |
//*********************************************************
//
// Copyright (c) Microsoft. All rights reserved.
// This code is licensed under the MIT License (MIT).
// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
//
//*********************************************************
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
namespace ASTool.ISMHelper
{
class Mp4BoxDINF : Mp4Box
{
static public Mp4BoxDINF CreateDINFBox(List<Mp4Box> listChild)
{
Mp4BoxDINF box = new Mp4BoxDINF();
if (box != null)
{
int ChildLen = 0;
if(listChild!=null)
{
foreach (var c in listChild)
ChildLen += c.GetBoxLength();
}
box.Length = 8 + ChildLen ;
box.Type = "dinf";
byte[] Buffer = new byte[box.Length - 8 ];
if (Buffer != null)
{
int offset = 0;
if (listChild != null)
{
foreach (var c in listChild)
{
WriteMp4BoxData(Buffer, offset, c.GetBoxBytes());
offset += c.GetBoxLength();
}
}
box.Data = Buffer;
return box;
}
}
return null;
}
}
}
| 31.092593 | 77 | 0.423466 | [
"MIT"
] | flecoqui/ASTool | cs/ASTool/ASTool.Core/ISMHelper/Mp4BoxDINF.cs | 1,681 | C# |
namespace Cade.BookStore
{
public abstract class BookStoreDomainTestBase : BookStoreTestBase<BookStoreDomainTestModule>
{
}
}
| 17.625 | 97 | 0.751773 | [
"MIT"
] | CadeXu/ABP | abpStart/test/Cade.BookStore.Domain.Tests/BookStoreDomainTestBase.cs | 143 | C# |
using System;
using Newtonsoft.Json;
namespace TimeshEAT.Business.API.Converters
{
public class DateTimeJsonConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return (objectType == typeof(DateTime) || objectType == typeof(DateTime?));
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
if (reader.TokenType == JsonToken.Null)
return null;
var newSerializer = new JsonSerializer();
var target = newSerializer.Deserialize<DateTime>(reader);
target = TimeZoneInfo.ConvertTime(target, TimeZoneInfo.Local);
return target;
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
serializer.Serialize(writer, value);
}
}
}
| 27.823529 | 124 | 0.637421 | [
"Apache-2.0"
] | TFZR-RSOK/SI2019-Team01-Timesheat | Business/API/Converters/DateTimeJsonConverter.cs | 948 | C# |
// Copyright (C) 2003-2020 Xtensive LLC.
// This code is distributed under MIT license terms.
// See the License.txt file in the project root for more information.
using System;
using System.Linq;
using Xtensive.Orm.Providers.PostgreSql;
using Xtensive.Sql.Compiler;
using Xtensive.Sql.Dml;
using SqlCompiler = Xtensive.Sql.Compiler.SqlCompiler;
namespace Xtensive.Sql.Drivers.PostgreSql.v8_0
{
internal class Compiler : SqlCompiler
{
private static readonly SqlNative OneYearInterval = SqlDml.Native("interval '1 year'");
private static readonly SqlNative OneMonthInterval = SqlDml.Native("interval '1 month'");
private static readonly SqlNative OneDayInterval = SqlDml.Native("interval '1 day'");
private static readonly SqlNative OneMinuteInterval = SqlDml.Native("interval '1 minute'");
private static readonly SqlNative OneSecondInterval = SqlDml.Native("interval '1 second'");
public override void Visit(SqlDeclareCursor node)
{
}
public override void Visit(SqlOpenCursor node)
{
base.Visit(node.Cursor.Declare());
}
public override void Visit(SqlBinary node)
{
var right = node.Right as SqlArray;
if (!right.IsNullReference() && (node.NodeType==SqlNodeType.In || node.NodeType==SqlNodeType.NotIn)) {
var row = SqlDml.Row(right.GetValues().Select(value => SqlDml.Literal(value)).ToArray());
base.Visit(node.NodeType==SqlNodeType.In ? SqlDml.In(node.Left, row) : SqlDml.NotIn(node.Left, row));
}
else {
switch (node.NodeType) {
case SqlNodeType.DateTimeOffsetMinusDateTimeOffset:
(node.Left - node.Right).AcceptVisitor(this);
return;
case SqlNodeType.DateTimeOffsetMinusInterval:
(node.Left - node.Right).AcceptVisitor(this);
return;
case SqlNodeType.DateTimeOffsetPlusInterval:
(node.Left + node.Right).AcceptVisitor(this);
return;
}
base.Visit(node);
}
}
public override void Visit(SqlFunctionCall node)
{
const double nanosecondsPerSecond = 1000000000.0;
switch (node.FunctionType) {
case SqlFunctionType.PadLeft:
case SqlFunctionType.PadRight:
SqlHelper.GenericPad(node).AcceptVisitor(this);
return;
case SqlFunctionType.Rand:
SqlDml.FunctionCall(translator.Translate(SqlFunctionType.Rand)).AcceptVisitor(this);
return;
case SqlFunctionType.Square:
SqlDml.Power(node.Arguments[0], 2).AcceptVisitor(this);
return;
case SqlFunctionType.IntervalConstruct:
((node.Arguments[0] / SqlDml.Literal(nanosecondsPerSecond)) * OneSecondInterval).AcceptVisitor(this);
return;
case SqlFunctionType.IntervalToMilliseconds:
SqlHelper.IntervalToMilliseconds(node.Arguments[0]).AcceptVisitor(this);
return;
case SqlFunctionType.IntervalToNanoseconds:
SqlHelper.IntervalToNanoseconds(node.Arguments[0]).AcceptVisitor(this);
return;
case SqlFunctionType.IntervalAbs:
SqlHelper.IntervalAbs(node.Arguments[0]).AcceptVisitor(this);
return;
case SqlFunctionType.DateTimeConstruct:
var newNode = (SqlDml.Literal(new DateTime(2001, 1, 1))
+ OneYearInterval * (node.Arguments[0] - 2001)
+ OneMonthInterval * (node.Arguments[1] - 1)
+ OneDayInterval * (node.Arguments[2] - 1));
newNode.AcceptVisitor(this);
return;
case SqlFunctionType.DateTimeTruncate:
(SqlDml.FunctionCall("date_trunc", "day", node.Arguments[0])).AcceptVisitor(this);
return;
case SqlFunctionType.DateTimeAddMonths:
(node.Arguments[0] + node.Arguments[1] * OneMonthInterval).AcceptVisitor(this);
return;
case SqlFunctionType.DateTimeAddYears:
(node.Arguments[0] + node.Arguments[1] * OneYearInterval).AcceptVisitor(this);
return;
case SqlFunctionType.DateTimeToStringIso:
DateTimeToStringIso(node.Arguments[0]).AcceptVisitor(this);
return;
case SqlFunctionType.DateTimeOffsetTimeOfDay:
DateTimeOffsetTimeOfDay(node.Arguments[0]).AcceptVisitor(this);
return;
case SqlFunctionType.DateTimeOffsetAddMonths:
SqlDml.Cast(node.Arguments[0] + node.Arguments[1] * OneMonthInterval, SqlType.DateTimeOffset).AcceptVisitor(this);
return;
case SqlFunctionType.DateTimeOffsetAddYears:
SqlDml.Cast(node.Arguments[0] + node.Arguments[1] * OneYearInterval, SqlType.DateTimeOffset).AcceptVisitor(this);
return;
case SqlFunctionType.DateTimeOffsetConstruct:
ConstructDateTimeOffset(node.Arguments[0], node.Arguments[1]).AcceptVisitor(this);
return;
case SqlFunctionType.DateTimeToDateTimeOffset:
SqlDml.Cast(node.Arguments[0], SqlType.DateTimeOffset).AcceptVisitor(this);
return;
}
base.Visit(node);
}
public override void Visit(SqlCustomFunctionCall node)
{
if (node.FunctionType==PostgresqlSqlFunctionType.NpgsqlPointExtractX) {
NpgsqlPointExtractPart(node.Arguments[0], 0).AcceptVisitor(this);
return;
}
if (node.FunctionType==PostgresqlSqlFunctionType.NpgsqlPointExtractY) {
NpgsqlPointExtractPart(node.Arguments[0], 1).AcceptVisitor(this);
return;
}
if (node.FunctionType==PostgresqlSqlFunctionType.NpgsqlTypeExtractPoint) {
NpgsqlTypeExtractPoint(node.Arguments[0], node.Arguments[1]).AcceptVisitor(this);
return;
}
if (node.FunctionType==PostgresqlSqlFunctionType.NpgsqlBoxExtractHeight) {
NpgsqlBoxExtractHeight(node.Arguments[0]).AcceptVisitor(this);
return;
}
if (node.FunctionType==PostgresqlSqlFunctionType.NpgsqlBoxExtractWidth) {
NpgsqlBoxExtractWidth(node.Arguments[0]).AcceptVisitor(this);
return;
}
if (node.FunctionType==PostgresqlSqlFunctionType.NpgsqlCircleExtractCenter) {
NpgsqlCircleExtractCenter(node.Arguments[0]).AcceptVisitor(this);
return;
}
if (node.FunctionType==PostgresqlSqlFunctionType.NpgsqlCircleExtractRadius) {
NpgsqlCircleExtractRadius(node.Arguments[0]).AcceptVisitor(this);
return;
}
if (node.FunctionType==PostgresqlSqlFunctionType.NpgsqlPathAndPolygonCount) {
NpgsqlPathAndPolygonCount(node.Arguments[0]).AcceptVisitor(this);
return;
}
if (node.FunctionType==PostgresqlSqlFunctionType.NpgsqlPathAndPolygonOpen) {
NpgsqlPathAndPolygonOpen(node.Arguments[0]).AcceptVisitor(this);
return;
}
if (node.FunctionType==PostgresqlSqlFunctionType.NpgsqlPathAndPolygonContains) {
NpgsqlPathAndPolygonContains(node.Arguments[0], node.Arguments[1]).AcceptVisitor(this);
return;
}
if (node.FunctionType==PostgresqlSqlFunctionType.NpgsqlTypeOperatorEquality) {
NpgsqlTypeOperatorEquality(node.Arguments[0], node.Arguments[1]).AcceptVisitor(this);
return;
}
if (node.FunctionType==PostgresqlSqlFunctionType.NpgsqlPointConstructor) {
var newNode = SqlDml.RawConcat(
NpgsqlTypeConstructor(node.Arguments[0], node.Arguments[1], "point'"),
SqlDml.Native("'"));
newNode.AcceptVisitor(this);
return;
}
if (node.FunctionType==PostgresqlSqlFunctionType.NpgsqlBoxConstructor) {
NpgsqlTypeConstructor(node.Arguments[0], node.Arguments[1], "box").AcceptVisitor(this);
return;
}
if (node.FunctionType==PostgresqlSqlFunctionType.NpgsqlCircleConstructor) {
NpgsqlTypeConstructor(node.Arguments[0], node.Arguments[1], "circle").AcceptVisitor(this);
return;
}
if (node.FunctionType==PostgresqlSqlFunctionType.NpgsqlLSegConstructor) {
NpgsqlTypeConstructor(node.Arguments[0], node.Arguments[1], "lseg").AcceptVisitor(this);
return;
}
base.Visit(node);
}
private static SqlExpression DateTimeToStringIso(SqlExpression dateTime)
{
return SqlDml.FunctionCall("To_Char", dateTime, "YYYY-MM-DD\"T\"HH24:MI:SS");
}
private static SqlExpression IntervalToIsoString(SqlExpression interval, bool signed)
{
if (!signed)
return SqlDml.FunctionCall("TO_CHAR", interval, "HH24:MI");
var hours = SqlDml.FunctionCall("TO_CHAR", SqlDml.Extract(SqlIntervalPart.Hour, interval), "SG09");
var minutes = SqlDml.FunctionCall("TO_CHAR", SqlDml.Extract(SqlIntervalPart.Minute, interval), "FM09");
return SqlDml.Concat(hours, ":", minutes);
}
protected static SqlExpression NpgsqlPointExtractPart(SqlExpression expression, int part)
{
return SqlDml.RawConcat(expression, SqlDml.Native(String.Format("[{0}]", part)));
}
protected static SqlExpression NpgsqlTypeExtractPoint(SqlExpression expression, SqlExpression numberPoint)
{
var numberPointAsInt = numberPoint as SqlLiteral<int>;
int valueNumberPoint = numberPointAsInt!=null ? numberPointAsInt.Value : 0;
return SqlDml.RawConcat(
SqlDml.Native("("),
SqlDml.RawConcat(
expression,
SqlDml.Native(String.Format("[{0}])", valueNumberPoint))));
}
protected static SqlExpression NpgsqlBoxExtractHeight(SqlExpression expression)
{
return SqlDml.FunctionCall("HEIGHT", expression);
}
protected static SqlExpression NpgsqlBoxExtractWidth(SqlExpression expression)
{
return SqlDml.FunctionCall("WIDTH", expression);
}
protected static SqlExpression NpgsqlCircleExtractCenter(SqlExpression expression)
{
return SqlDml.RawConcat(SqlDml.Native("@@"), expression);
}
protected static SqlExpression NpgsqlCircleExtractRadius(SqlExpression expression)
{
return SqlDml.FunctionCall("RADIUS", expression);
}
protected static SqlExpression NpgsqlPathAndPolygonCount(SqlExpression expression)
{
return SqlDml.FunctionCall("NPOINTS", expression);
}
protected static SqlExpression NpgsqlPathAndPolygonOpen(SqlExpression expression)
{
return SqlDml.FunctionCall("ISOPEN", expression);
}
protected static SqlExpression NpgsqlPathAndPolygonContains(SqlExpression expression, SqlExpression point)
{
return SqlDml.RawConcat(
expression,
SqlDml.RawConcat(
SqlDml.Native("@>"),
point));
}
protected static SqlExpression NpgsqlTypeOperatorEquality(SqlExpression left, SqlExpression right)
{
return SqlDml.RawConcat(left,
SqlDml.RawConcat(
SqlDml.Native("~="),
right));
}
private static SqlExpression NpgsqlTypeConstructor(SqlExpression left, SqlExpression right, string type)
{
return SqlDml.RawConcat(
SqlDml.Native(String.Format("{0}(", type)),
SqlDml.RawConcat(left,
SqlDml.RawConcat(
SqlDml.Native(","),
SqlDml.RawConcat(
right,
SqlDml.Native(")")))));
}
public override void Visit(SqlExtract node)
{
switch (node.DateTimeOffsetPart) {
case SqlDateTimeOffsetPart.Date:
DateTimeOffsetExtractDate(node.Operand).AcceptVisitor(this);
return;
case SqlDateTimeOffsetPart.DateTime:
DateTimeOffsetExtractDateTime(node.Operand).AcceptVisitor(this);
return;
case SqlDateTimeOffsetPart.UtcDateTime:
DateTimeOffsetToUtcDateTime(node.Operand).AcceptVisitor(this);
return;
case SqlDateTimeOffsetPart.LocalDateTime:
DateTimeOffsetToLocalDateTime(node.Operand).AcceptVisitor(this);
return;
case SqlDateTimeOffsetPart.Offset:
DateTimeOffsetExtractOffset(node);
return;
}
base.Visit(node);
}
protected SqlExpression DateTimeOffsetExtractDate(SqlExpression timestamp)
{
return SqlDml.FunctionCall("DATE", timestamp);
}
protected SqlExpression DateTimeOffsetExtractDateTime(SqlExpression timestamp)
{
return SqlDml.Cast(timestamp, SqlType.DateTime);
}
protected SqlExpression DateTimeOffsetToUtcDateTime(SqlExpression timeStamp)
{
return GetDateTimeInTimeZone(timeStamp, TimeSpan.Zero);
}
protected SqlExpression DateTimeOffsetToLocalDateTime(SqlExpression timestamp)
{
return SqlDml.Cast(timestamp, SqlType.DateTime);
}
protected void DateTimeOffsetExtractOffset(SqlExtract node)
{
using (context.EnterScope(node)) {
context.Output.AppendText(translator.Translate(context, node, ExtractSection.Entry));
var part = node.DateTimePart!=SqlDateTimePart.Nothing
? translator.Translate(node.DateTimePart)
: node.IntervalPart!=SqlIntervalPart.Nothing
? translator.Translate(node.IntervalPart)
: translator.Translate(node.DateTimeOffsetPart);
context.Output.AppendText(part);
context.Output.AppendText(translator.Translate(context, node, ExtractSection.From));
node.Operand.AcceptVisitor(this);
context.Output.AppendText(translator.Translate(context, node, ExtractSection.Exit));
context.Output.AppendText(translator.Translate(SqlNodeType.Multiply));
OneSecondInterval.AcceptVisitor(this);
}
}
protected SqlExpression DateTimeOffsetTimeOfDay(SqlExpression timestamp)
{
return DateTimeOffsetSubstract(timestamp, SqlDml.DateTimeTruncate(timestamp));
}
protected SqlExpression DateTimeOffsetSubstract(SqlExpression timestamp1, SqlExpression timestamp2)
{
return timestamp1 - timestamp2;
}
protected SqlExpression ConstructDateTimeOffset(SqlExpression dateTimeExpression, SqlExpression offsetInMinutes)
{
var dateTimeAsStringExpression = GetDateTimeAsStringExpression(dateTimeExpression);
var offsetAsStringExpression = GetOffsetAsStringExpression(offsetInMinutes);
return ConstructDateTimeOffsetFromExpressions(dateTimeAsStringExpression, offsetAsStringExpression);
}
protected SqlExpression ConstructDateTimeOffsetFromExpressions(SqlExpression datetimeStringExpression, SqlExpression offsetStringExpression)
{
return SqlDml.Cast(SqlDml.Concat(datetimeStringExpression, " ", offsetStringExpression), SqlType.DateTimeOffset);
}
protected SqlExpression GetDateTimeAsStringExpression(SqlExpression dateTimeExpression)
{
return SqlDml.FunctionCall("To_Char", dateTimeExpression, "YYYY-MM-DD\"T\"HH24:MI:SS.MS");
}
protected SqlExpression GetOffsetAsStringExpression(SqlExpression offsetInMinutes)
{
int hours = 0;
int minutes = 0;
//if something simple as double or int or even timespan can be separated into hours and minutes parts
if (TryDivideOffsetIntoParts(offsetInMinutes, ref hours, ref minutes))
return SqlDml.Native(string.Format("'{0}'", ZoneStringFromParts(hours, minutes)));
var intervalExpression = offsetInMinutes * OneMinuteInterval;
return IntervalToIsoString(intervalExpression, true);
}
private string ZoneStringFromParts(int hours, int minutes)
{
return string.Format("{0}{1:00}:{2:00}", hours < 0 ? "-" : "+", Math.Abs(hours), Math.Abs(minutes));
}
private SqlExpression GetDateTimeInTimeZone(SqlExpression expression, SqlExpression zone)
{
return SqlDml.FunctionCall("TIMEZONE", zone, expression);
}
private SqlExpression GetServerTimeZone()
{
return SqlDml.FunctionCall("CURRENT_SETTING", SqlDml.Literal("TIMEZONE"));
}
private bool TryDivideOffsetIntoParts(SqlExpression offsetInMinutes, ref int hours , ref int minutes)
{
var offsetToDouble = offsetInMinutes as SqlLiteral<double>;
if (offsetToDouble!=null) {
hours = (int) offsetToDouble.Value / 60;
minutes = Math.Abs((int) offsetToDouble.Value % 60);
return true;
}
var offsetToInt = offsetInMinutes as SqlLiteral<int>;
if (offsetToInt!=null) {
hours = offsetToInt.Value / 60;
minutes = Math.Abs(offsetToInt.Value % 60);
return true;
}
var offsetToTimeSpan = offsetInMinutes as SqlLiteral<TimeSpan>;
if (offsetToTimeSpan!=null) {
var totalMinutes = offsetToTimeSpan.Value.TotalMinutes;
hours = (int)totalMinutes / 60;
minutes = Math.Abs((int)totalMinutes % 60);
return true;
}
return false;
}
// Constructors
protected internal Compiler(SqlDriver driver)
: base(driver)
{
}
}
} | 39.127059 | 144 | 0.69487 | [
"MIT"
] | NekrasovSt/dataobjects-net | Orm/Xtensive.Orm.PostgreSql/Sql.Drivers.PostgreSql/v8_0/Compiler.cs | 16,629 | C# |
// -------------------------------------------------------------------------------------
// <copyright file="ParallelDynamicProgrammingTest.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// <summary>
// Contains test cases for ParallelDynamicProgramming class.
// </summary>
// -------------------------------------------------------------------------------------
namespace MBF.Tests
{
using System;
using System.Collections.Generic;
using MBF.Algorithms;
using MBF.Algorithms.Alignment;
using MBF.Algorithms.Alignment.MultipleSequenceAlignment;
using MBF.Util.Logging;
using System.Threading.Tasks;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using MBF.SimilarityMatrices;
/// <summary>
/// Test for ParallelDynamicProgramming class
/// </summary>
[TestClass]
public class ParallelDynamicProgrammingTests
{
/// <summary>
/// Test ParallelDynamicProgramming class
/// </summary>
[TestMethod]
[Priority(0)]
[TestCategory("Priority0")]
public void TestParallelDynamicProgramming()
{
ISequence templateSequence = new Sequence(Alphabets.DNA, "ATGCSWRYKMBVHDN-");
Dictionary<ISequenceItem, int> itemSet = new Dictionary<ISequenceItem, int>();
for (int i = 0; i < templateSequence.Count; ++i)
{
itemSet.Add(templateSequence[i], i);
}
Profiles.ItemSet = itemSet;
NeedlemanWunschProfileAlignerSerial profileAligner = new NeedlemanWunschProfileAlignerSerial();
SimilarityMatrix similarityMatrix = new SimilarityMatrix(SimilarityMatrix.StandardSimilarityMatrix.AmbiguousDna);
int gapOpenPenalty = -8;
int gapExtendPenalty = -1;
profileAligner.SimilarityMatrix = similarityMatrix;
profileAligner.GapOpenCost = gapOpenPenalty;
profileAligner.GapExtensionCost = gapExtendPenalty;
int numberOfRows = 8, numberOfCols = 7;
int numberOfPartitions = 4;
int startPosition = 1, endPosition = 100; Dictionary<int, List<int[]>> parallelIndexMaster = profileAligner.ParallelIndexMasterGenerator(numberOfRows, numberOfCols, numberOfPartitions);
foreach (var pair in parallelIndexMaster)
{
Console.Write("{0} ->: ", pair.Key);
for (int i = 0; i < pair.Value.Count; ++i)
{
Console.WriteLine("iteration: {0}: {1}-{2};", i, pair.Value[i][0], pair.Value[i][1]);
}
}
for (int partitionIndex = 0; partitionIndex < numberOfPartitions; ++partitionIndex)
{
int[] indexPositions = profileAligner.IndexLocator(startPosition, endPosition, numberOfPartitions, partitionIndex);
Console.Write("Index number: {0}: {1}-{2}", partitionIndex, indexPositions[0], indexPositions[1]);
}
int numberOfIterations = numberOfPartitions * 2 - 1;
for (int i = 0; i < numberOfIterations; ++i)
{
foreach (var pair in parallelIndexMaster)
{
List<int[]> indexPositions = parallelIndexMaster[pair.Key];
// Parallel in anti-diagonal direction
Parallel.ForEach(indexPositions, indexPosition =>
{
int[] rowPositions = profileAligner.IndexLocator(1, 100, numberOfPartitions, indexPosition[0]);
int[] colPositions = profileAligner.IndexLocator(1, 200, numberOfPartitions, indexPosition[0]);
Console.Write("row positions: {0}-{1}", rowPositions[0], rowPositions[1]);
Console.Write("col positions: {0}-{1}", colPositions[0], colPositions[1]);
});
}
}
}
}
} | 42.468085 | 197 | 0.576653 | [
"Apache-2.0"
] | jdm7dv/Microsoft-Biology-Foundation | archive/Changesets/beta/Tests/MBF.Tests/ParallelDynamicProgrammingTests.cs | 3,994 | C# |
using UnityEngine;
using System.Collections;
public class PowerupManager : MonoBehaviour {
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
}
| 14.125 | 46 | 0.641593 | [
"MIT"
] | jolly-llama-games/bionic-salamander | Assets/Scripts/PowerupManager.cs | 213 | C# |
using Neo.Tests.Framework;
using Neo.Frontend.Lexer;
using Neo.AST;
using Neo.AST.Expressions;
using Neo.AST.Expressions.Atoms;
using Neo.AST.Statements;
namespace Neo.Tests.AST.Statements {
[TestFixture]
public sealed class ExpressionStatementNodeTests {
private ExpressionNode value;
private ExpressionStatementNode subject;
public ExpressionStatementNodeTests() {
value = new IdentNode(SourcePosition.NIL, "foo");
subject = new ExpressionStatementNode(SourcePosition.NIL, value);
}
[Test]
public void ExpressionStatementNodeHasAValue() {
Assert.AreEqual(subject.Value, value);
}
[Test]
public void ExpressionStatementNodesCanBeVisited() {
object got = null;
var testVisitor = new TestASTVisitor();
testVisitor.VisitExpressionStatementNodeHandler = node => got = node;
subject.Accept(testVisitor);
Assert.AreEqual(got, subject);
}
}
} | 24.722222 | 72 | 0.758427 | [
"MIT"
] | sci4me/Neo-old | src/test/AST/Statements/ExpressionStatementNodeTests.cs | 890 | C# |
using System;
namespace umbraco.cms.businesslogic.macro
{
[Serializable]
public class MacroPropertyModel
{
public string Key { get; set; }
public string Value { get; set; }
public string Type { get; set; }
[Obsolete("This is no longer used an will be removed in future versions")]
public string CLRType { get; set; }
public MacroPropertyModel()
{
}
public MacroPropertyModel(string key, string value)
{
Key = key;
Value = value;
}
public MacroPropertyModel(string key, string value, string type, string clrType)
{
Key = key;
Value = value;
Type = type;
CLRType = clrType;
}
}
} | 20 | 83 | 0.626471 | [
"MIT"
] | Abhith/Umbraco-CMS | src/umbraco.cms/businesslogic/macro/MacroPropertyModel.cs | 680 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace ZFramework
{
public class Main : MonoBehaviour
{
void Start()
{
DontDestroyOnLoad(gameObject);
gameObject.AddComponent<Global>();
}
}
}
| 17.9375 | 46 | 0.620209 | [
"MIT"
] | z16388/ZFramework | Assets/Scripts/ZFramework/Main.cs | 289 | C# |
using System.Text.Json.Serialization;
namespace Horizon.Payment.Alipay.Domain
{
/// <summary>
/// MarketingItemSelection Data Structure.
/// </summary>
public class MarketingItemSelection : AlipayObject
{
/// <summary>
/// 营销项目ID
/// </summary>
[JsonPropertyName("id")]
public string Id { get; set; }
}
}
| 21.823529 | 54 | 0.590296 | [
"Apache-2.0"
] | bluexray/Horizon.Sample | Horizon.Payment.Alipay/Domain/MarketingItemSelection.cs | 381 | 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.ApiManagement.V20200601Preview.Outputs
{
[OutputType]
public sealed class BackendProxyContractResponse
{
/// <summary>
/// Password to connect to the WebProxy Server
/// </summary>
public readonly string? Password;
/// <summary>
/// WebProxy Server AbsoluteUri property which includes the entire URI stored in the Uri instance, including all fragments and query strings.
/// </summary>
public readonly string Url;
/// <summary>
/// Username to connect to the WebProxy server
/// </summary>
public readonly string? Username;
[OutputConstructor]
private BackendProxyContractResponse(
string? password,
string url,
string? username)
{
Password = password;
Url = url;
Username = username;
}
}
}
| 28.813953 | 149 | 0.627926 | [
"Apache-2.0"
] | pulumi-bot/pulumi-azure-native | sdk/dotnet/ApiManagement/V20200601Preview/Outputs/BackendProxyContractResponse.cs | 1,239 | C# |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
using System;
using System.Collections.Generic;
using System.Reflection;
using Microsoft.PowerFx.Types;
namespace Microsoft.PowerFx
{
/// <summary>
/// Marshal .Net classes (with fields) to <see cref="RecordValue"/>.
/// This supports both strong typing and lazy marshalling.
/// It will return a <see cref="ObjectMarshaller"/>.
/// </summary>
public class ObjectMarshallerProvider : ITypeMarshallerProvider
{
/// <summary>
/// Provides a customization point to control how properties are marshalled.
/// This returns null to skip the property, else return the name it should have on the power fx record.
/// If this is insufficient, a caller can always implement their own marshaller and return a
/// a <see cref="ObjectMarshaller"/> directly.
/// </summary>
public virtual string GetFxName(PropertyInfo propertyInfo)
{
// By default, the C# name is the Fx name.
return propertyInfo.Name;
}
/// <inheritdoc/>
public bool TryGetMarshaller(Type type, TypeMarshallerCache cache, int maxDepth, out ITypeMarshaller marshaler)
{
if (!type.IsClass ||
typeof(FormulaValue).IsAssignableFrom(type) ||
typeof(FormulaType).IsAssignableFrom(type))
{
// Explicitly reject FormulaValue/FormulaType to catch common bugs.
marshaler = null;
return false;
}
var mapping = new Dictionary<string, Func<object, FormulaValue>>(StringComparer.OrdinalIgnoreCase);
var fxType = new RecordType();
foreach (var prop in type.GetProperties(BindingFlags.Public | BindingFlags.Instance))
{
if (!prop.CanRead)
{
continue;
}
var fxName = GetFxName(prop);
if (fxName == null)
{
continue;
}
var tm = cache.GetMarshaller(prop.PropertyType, maxDepth);
var fxFieldType = tm.Type;
// Basic .net property
if (mapping.ContainsKey(fxName))
{
throw new NameCollisionException(fxName);
}
mapping[fxName] = (object objSource) =>
{
var propValue = prop.GetValue(objSource);
return tm.Marshal(propValue);
};
fxType = fxType.Add(fxName, fxFieldType);
}
marshaler = new ObjectMarshaller(fxType, mapping);
return true;
}
}
}
| 34.365854 | 119 | 0.552165 | [
"MIT"
] | CarlosFigueiraMSFT/Power-Fx | src/libraries/Microsoft.PowerFx.Interpreter/Marshal/ObjectMarshallerProvider.cs | 2,820 | C# |
// Copyright (c) 2014-2022 Sarin Na Wangkanai, All Rights Reserved. Apache License, Version 2.0
using System;
using Microsoft.AspNetCore.Http;
using Wangkanai.Detection.Services;
namespace Backend
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
var agent = "useragent";
var context = new DefaultHttpContext();
context.Request.Headers["User-Agent"] = agent;
var accessor = new HttpContextAccessor { HttpContext = context };
var contextService = new HttpContextService(accessor);
var useragent = new UserAgentService(contextService);
Console.WriteLine(useragent.UserAgent);
}
}
} | 29.5 | 96 | 0.625815 | [
"Apache-2.0"
] | anhgeeky/Detection | sample/Backend/Program.cs | 769 | C# |
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TornCityAPISharp.UserStats
{
public class Company
{
[JsonProperty("name")]
string Name { get; set; }
[JsonProperty("jobpoint")]
int JobPoint { get; set; }
}
}
| 18.684211 | 36 | 0.661972 | [
"Apache-2.0"
] | CarlHalstead/TornCityAPISharp | UserStats/Company.cs | 357 | C# |
namespace RFIDTest
{
partial class Form1
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.dockPanel = new WeifenLuo.WinFormsUI.Docking.DockPanel();
this.SuspendLayout();
//
// dockPanel
//
this.dockPanel.Dock = System.Windows.Forms.DockStyle.Fill;
this.dockPanel.Location = new System.Drawing.Point(0, 0);
this.dockPanel.Name = "dockPanel";
this.dockPanel.Size = new System.Drawing.Size(728, 498);
this.dockPanel.TabIndex = 0;
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(728, 498);
this.Controls.Add(this.dockPanel);
this.IsMdiContainer = true;
this.Name = "Form1";
this.Text = "Form1";
this.Load += new System.EventHandler(this.Form1_Load);
this.ResumeLayout(false);
}
#endregion
private WeifenLuo.WinFormsUI.Docking.DockPanel dockPanel;
}
}
| 32.435484 | 107 | 0.553953 | [
"Apache-2.0"
] | dingfeng/rfid | RFIDApplication/RFIDTest/Form1.Designer.cs | 2,013 | C# |
//
// Kvant/Warp - Warp (hyperspace) light streaks effect
//
// Copyright (C) 2016 Keijiro Takahashi
//
// 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 UnityEngine;
using System.Collections.Generic;
using System.Linq;
namespace Kvant
{
public class WarpTemplate : ScriptableObject
{
#region Public properties
/// Instance count (read only)
public int instanceCount {
get { return _instanceCount; }
}
[SerializeField] int _instanceCount;
/// Tmplate mesh (read only)
public Mesh mesh {
get { return _mesh; }
}
[SerializeField] Mesh _mesh;
#endregion
#region Private members
[SerializeField] Mesh _sourceShape;
#endregion
#region Public methods
#if UNITY_EDITOR
// Template mesh rebuilding method
public void RebuildMesh()
{
// Source mesh
var vtx_in = _sourceShape.vertices;
var idx_in = _sourceShape.triangles;
// Calculate the instance count.
_instanceCount = 65535 / vtx_in.Length;
// Working buffers
var vtx_out = new List<Vector3>();
var uv0_out = new List<Vector3>();
var idx_out = new List<int>();
// Repeat the source mesh.
for (var i = 0; i < _instanceCount; i++)
{
foreach (var idx in idx_in)
idx_out.Add(idx + vtx_out.Count);
vtx_out.AddRange(vtx_in);
var uv0 = new Vector3((i + 0.5f) / _instanceCount, Random.value, Random.value);
uv0_out.AddRange(Enumerable.Repeat(uv0, vtx_in.Length));
}
// Reset the mesh asset.
_mesh.Clear();
_mesh.SetVertices(vtx_out);
_mesh.SetUVs(0, uv0_out);
_mesh.SetIndices(idx_out.ToArray(), MeshTopology.Triangles, 0);
_mesh.bounds = new Bounds(Vector3.zero, Vector3.one * 1000);
;
_mesh.UploadMeshData(true);
}
#endif
#endregion
#region ScriptableObject functions
void OnEnable()
{
if (_mesh == null) {
_mesh = new Mesh();
_mesh.name = "Warp Template";
}
}
#endregion
}
}
| 30.859649 | 96 | 0.587265 | [
"MIT"
] | Adjuvant/videolab | Assets/Kvant/Warp/Script/WarpTemplate.cs | 3,518 | C# |
//------------------------------------------------------------
// Game Framework
// Copyright © 2013-2021 Jiang Yin. All rights reserved.
// Homepage: https://gameframework.cn/
// Feedback: mailto:ellan@gameframework.cn
//------------------------------------------------------------
namespace GameFramework.Scene
{
/// <summary>
/// 加载场景成功事件。
/// </summary>
public sealed class LoadSceneSuccessEventArgs : GameFrameworkEventArgs
{
/// <summary>
/// 初始化加载场景成功事件的新实例。
/// </summary>
public LoadSceneSuccessEventArgs()
{
SceneAssetName = null;
Duration = 0f;
UserData = null;
}
/// <summary>
/// 获取场景资源名称。
/// </summary>
public string SceneAssetName
{
get;
private set;
}
/// <summary>
/// 获取加载持续时间。
/// </summary>
public float Duration
{
get;
private set;
}
/// <summary>
/// 获取用户自定义数据。
/// </summary>
public object UserData
{
get;
private set;
}
/// <summary>
/// 创建加载场景成功事件。
/// </summary>
/// <param name="sceneAssetName">场景资源名称。</param>
/// <param name="duration">加载持续时间。</param>
/// <param name="userData">用户自定义数据。</param>
/// <returns>创建的加载场景成功事件。</returns>
public static LoadSceneSuccessEventArgs Create(string sceneAssetName, float duration, object userData)
{
LoadSceneSuccessEventArgs loadSceneSuccessEventArgs = ReferencePool.Acquire<LoadSceneSuccessEventArgs>();
loadSceneSuccessEventArgs.SceneAssetName = sceneAssetName;
loadSceneSuccessEventArgs.Duration = duration;
loadSceneSuccessEventArgs.UserData = userData;
return loadSceneSuccessEventArgs;
}
/// <summary>
/// 清理加载场景成功事件。
/// </summary>
public override void Clear()
{
SceneAssetName = null;
Duration = 0f;
UserData = null;
}
}
}
| 27.265823 | 117 | 0.500929 | [
"MIT"
] | 823040692/Frame | GameFramework/Scene/LoadSceneSuccessEventArgs.cs | 2,375 | C# |
using CodingTrainer.CodingTrainerModels.Security;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
namespace CodingTrainer.CodingTrainerWeb.Models
{
public class ExternalLoginConfirmationViewModel
{
[Required]
[Display(Name = "Email")]
public string Email { get; set; }
}
public class ExternalLoginListViewModel
{
public string ReturnUrl { get; set; }
}
public class SendCodeViewModel
{
public string SelectedProvider { get; set; }
public ICollection<System.Web.Mvc.SelectListItem> Providers { get; set; }
public string ReturnUrl { get; set; }
public bool RememberMe { get; set; }
}
public class VerifyCodeViewModel
{
[Required]
public string Provider { get; set; }
[Required]
[Display(Name = "Code")]
public string Code { get; set; }
public string ReturnUrl { get; set; }
[Display(Name = "Remember this browser?")]
public bool RememberBrowser { get; set; }
public bool RememberMe { get; set; }
}
public class ForgotViewModel
{
[Required]
[Display(Name = "Email")]
public string Email { get; set; }
}
public class LoginViewModel
{
[Required]
[Display(Name = "Email")]
[EmailAddress]
public string Email { get; set; }
[Required]
[DataType(DataType.Password)]
[Display(Name = "Password")]
public string Password { get; set; }
[Display(Name = "Remember me?")]
public bool RememberMe { get; set; }
}
public class RegisterViewModel
{
[Required]
[EmailAddress]
[Display(Name = "Email")]
public string Email { get; set; }
[Required]
[Display(Name = "First name")]
public string FirstName { get; set; }
[Required]
[Display(Name = "Last name")]
public string LastName { get; set; }
[Required]
[StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
[DataType(DataType.Password)]
[Display(Name = "Password")]
public string Password { get; set; }
[DataType(DataType.Password)]
[Display(Name = "Confirm password")]
[Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
public string ConfirmPassword { get; set; }
public ApplicationUser GetUser()
{
return new ApplicationUser()
{
Email = Email,
UserName = Email,
FirstName = FirstName,
LastName = LastName,
CurrentChapterNo = 1,
CurrentExerciseNo = 1,
Dark = false
};
}
}
public class ResetPasswordViewModel
{
[Required]
[EmailAddress]
[Display(Name = "Email")]
public string Email { get; set; }
[Required]
[StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
[DataType(DataType.Password)]
[Display(Name = "Password")]
public string Password { get; set; }
[DataType(DataType.Password)]
[Display(Name = "Confirm password")]
[Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
public string ConfirmPassword { get; set; }
public string Code { get; set; }
}
public class ForgotPasswordViewModel
{
[Required]
[EmailAddress]
[Display(Name = "Email")]
public string Email { get; set; }
}
}
| 27.691176 | 110 | 0.57196 | [
"Apache-2.0"
] | ddashwood/CodingTrainer | CodingTrainerWeb/Models/AccountViewModels.cs | 3,768 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
namespace FreeRedis
{
partial class RedisClient
{
#if isasync
#region async (copy from sync)
/// <summary>
/// APPEND command (An Asynchronous Version)<br /><br />
/// <br />
/// If key already exists and is a string, this command appends the value at the end of the string. If key does not exist it is created and set as an empty string, so APPEND will be similar to SET in this special case. <br /><br />
/// <br />
/// 若键值已存在且为字符串,则此命令将值附加在字符串的末尾;<br />
/// 若键值不存在,则会先创建一个空字符串,并附加值(在此情况下,APPEND 类似 SET 命令)。<br /><br />
/// <br />
/// Document link: https://redis.io/commands/append <br />
/// Available since 2.0.0.
/// </summary>
/// <param name="key">Key</param>
/// <param name="value">Value</param>
/// <typeparam name="T"></typeparam>
/// <returns>The length of the string after the append operation.</returns>
public Task<long> AppendAsync<T>(string key, T value) => CallAsync("APPEND".InputKey(key).InputRaw(SerializeRedisValue(value)), rt => rt.ThrowOrValue<long>());
/// <summary>
/// BITCOUNT command (An Asynchronous Version)<br /><br />
/// <br />
/// Count the number of set bits (population counting) in a string.<br /><br />
/// <br />
/// 统计字符串中的位数。<br /><br />
/// <br />
/// Document link: https://redis.io/commands/bitcount <br />
/// Available since 2.6.0.
/// </summary>
/// <param name="key">Key</param>
/// <param name="start">Index of the start. It can contain negative values in order to index bytes starting from the end of the string.</param>
/// <param name="end">Index of the end. It can contain negative values in order to index bytes starting from the end of the string.</param>
/// <returns>The number of set bits in the string. Non-existent keys are treated as empty strings and will return zero.</returns>
public Task<long> BitCountAsync(string key, long start, long end) => CallAsync("BITCOUNT".InputKey(key, start, end), rt => rt.ThrowOrValue<long>());
/// <summary>
/// BITOP command (An Asynchronous Version) <br /><br />
/// <br />
/// Perform a bitwise operation between multiple keys (containing string values) and store the result in the destination key.<br /><br />
/// <br />
/// 在(包括字符串值)的多键之间按位运算,并将结果保存在目标键中。<br />
/// 目前支持 AND、OR、XOR 与 NOT 四种运算方式。<br /><br />
/// <br />
/// Document link: https://redis.io/commands/bitop <br />
/// Available since 2.6.0.
/// </summary>
/// <param name="operation">Bit operation type: AND, OR, XOR or NOT</param>
/// <param name="destkey">Destination Key</param>
/// <param name="keys">Multiple keys (containing string values)</param>
/// <returns>The size of the string stored in the destination key, that is equal to the size of the longest input string.</returns>
public Task<long> BitOpAsync(BitOpOperation operation, string destkey, params string[] keys) => CallAsync("BITOP".InputRaw(operation).InputKey(destkey).InputKey(keys), rt => rt.ThrowOrValue<long>());
/// <summary>
/// BITPOS command (An Asynchronous Version) <br /><br />
/// <br />
/// Return the position of the first bit set to 1 or 0 in a string.<br />
/// The position is returned, thinking of the string as an array of bits from left to right, where the first byte's most significant bit is at position 0, the second byte's most significant bit is at position 8, and so forth.<br /><br />
/// <br />
/// 返回字符串中第一个 1 或 0 的位置。<br />
/// 注意,本命令将字符串视作位数组,自左向右计算,第一个字节在位置 0,第二个字节在位置 8,以此类推。<br /><br />
/// <br />
/// Document link: https://redis.io/commands/bitpos <br />
/// Available since 2.8.7.
/// </summary>
/// <param name="key">Key</param>
/// <param name="bit">Bit value, 1 is true, 0 is false.</param>
/// <param name="start">Index of the start. It can contain negative values in order to index bytes starting from the end of the string.</param>
/// <param name="end">Index of the end. It can contain negative values in order to index bytes starting from the end of the string.</param>
/// <returns>Returns the position of the first bit set to 1 or 0 according to the request.</returns>
public Task<long> BitPosAsync(string key, bool bit, long? start = null, long? end = null) => CallAsync("BITPOS"
.InputKey(key, bit ? "1" : "0")
.InputIf(start != null, start)
.InputIf(end != null, start), rt => rt.ThrowOrValue<long>());
/// <summary>
/// DECR command (An Asynchronous Version) <br /><br />
/// <br />
/// Decrements the number stored at key by one. <br />
/// If the key does not exist, it is set to 0 before performing the operation. An error is returned if the key contains a value of the wrong type or contains a string that can not be represented as integer. <br />
/// This operation is limited to 64 bit signed integers.<br /><br />
/// <br />
/// 对该键的值减去 1。<br />
/// 如果键值不存在,则在操作前先设置为 0。如果键对应的值是个错误类型或不能表达为整数的字符串,则返回错误。此操作仅限于 64 位有符号整数。<br /><br />
/// <br />
/// Document link: https://redis.io/commands/decr <br />
/// Available since 1.0.0.
/// </summary>
/// <param name="key">Key</param>
/// <returns>the value of key after the decrement.</returns>
public Task<long> DecrAsync(string key) => CallAsync("DECR".InputKey(key), rt => rt.ThrowOrValue<long>());
/// <summary>
/// DECRBY command (An Asynchronous Version) <br /><br />
/// <br />
/// Decrements the number stored at key by decrement. <br />
/// If the key does not exist, it is set to 0 before performing the operation. An error is returned if the key contains a value of the wrong type or contains a string that can not be represented as integer. <br />
/// This operation is limited to 64 bit signed integers.<br /><br />
/// <br />
/// 对该键的值减去给定的值。<br />
/// 如果键值不存在,则在操作前先设置为 0。如果键对应的值是个错误类型或不能表达为整数的字符串,则返回错误。此操作仅限于 64 位有符号整数。<br /><br />
/// <br />
/// Document link: https://redis.io/commands/decrby <br />
/// Available since 1.0.0.
/// </summary>
/// <param name="key">Key</param>
/// <param name="decrement">The given value to be decreased.</param>
/// <returns>the value of key after the decrement.</returns>
public Task<long> DecrByAsync(string key, long decrement) => CallAsync("DECRBY".InputKey(key, decrement), rt => rt.ThrowOrValue<long>());
/// <summary>
/// GET command (An Asynchronous Version) <br /><br />
/// <br />
/// Get the value of key. If the key does not exist the special value nil is returned. An error is returned if the value stored at key is not a string, because GET only handles string values.<br /><br />
/// <br />
/// 获得给定键的值。若键不存在,则返回特殊的 nil 值。如果给定键的值不是字符串,则返回错误,因为 GET 指令只能处理字符串。 <br /><br />
/// <br />
/// Document link: https://redis.io/commands/get <br />
/// Available since 1.0.0.
/// </summary>
/// <param name="key">Key</param>
/// <returns>The value of key, or nil when key does not exist.</returns>
public Task<string> GetAsync(string key) => CallAsync("GET".InputKey(key), rt => rt.ThrowOrValue<string>());
/// <summary>
/// GET command (An Asynchronous Version) <br /><br />
/// <br />
/// Get the value of key. If the key does not exist the special value nil is returned. An error is returned if the value stored at key is not a string, because GET only handles string values.<br /><br />
/// <br />
/// 获得给定键的值。若键不存在,则返回特殊的 nil 值。如果给定键的值不是字符串,则返回错误,因为 GET 指令只能处理字符串。 <br /><br />
/// <br />
/// Document link: https://redis.io/commands/get <br />
/// Available since 1.0.0.
/// </summary>
/// <param name="key">Key</param>
/// <typeparam name="T"></typeparam>
/// <returns>The value of key, or nil when key does not exist.</returns>
public Task<T> GetAsync<T>(string key) => CallAsync("GET".InputKey(key).FlagReadbytes(true), rt => rt.ThrowOrValue(a => DeserializeRedisValue<T>(a.ConvertTo<byte[]>(), rt.Encoding)));
/// <summary>
/// GETBIT command (An Asynchronous Version) <br /><br />
/// <br />
/// Returns the bit value at offset in the string value stored at key.<br /><br />
/// <br />
/// 返回键所对应字符串值中偏移量的位值。<br /><br />
/// <br />
/// Document link: https://redis.io/commands/getbit <br />
/// Available since 2.2.0.
/// </summary>
/// <param name="key">Key</param>
/// <param name="offset">Offset</param>
/// <returns>The bit value stored at offset.</returns>
public Task<bool> GetBitAsync(string key, long offset) => CallAsync("GETBIT".InputKey(key, offset), rt => rt.ThrowOrValue<bool>());
/// <summary>
/// GETRANGE command (An Asynchronous Version) <br /><br />
/// <br />
/// Returns the substring of the string value stored at key, determined by the offsets start and end (both are inclusive).<br /><br />
/// <br />
/// 返回键值的子字符串该字符串由偏移量 start 和 end 来确定(两端均闭包)。<br /><br />
/// <br />
/// Document link: https://redis.io/commands/getrange <br />
/// Available since 2.0.0. It is called SUBSTR in Redis versions <= 2.0.
/// </summary>
/// <param name="key">Key</param>
/// <param name="start">Start</param>
/// <param name="end">End</param>
/// <returns>The substring of the string value</returns>
public Task<string> GetRangeAsync(string key, long start, long end) => CallAsync("GETRANGE".InputKey(key, start, end), rt => rt.ThrowOrValue<string>());
/// <summary>
/// GETRANGE command (An Asynchronous Version) <br /><br />
/// <br />
/// Returns the substring of the string value stored at key, determined by the offsets start and end (both are inclusive).<br /><br />
/// <br />
/// 返回键值的子字符串该字符串由偏移量 start 和 end 来确定(两端均闭包)。<br /><br />
/// <br />
/// Document link: https://redis.io/commands/getrange <br />
/// Available since 2.0.0. It is called SUBSTR in Redis versions <= 2.0.
/// </summary>
/// <param name="key">Key</param>
/// <param name="start">Start</param>
/// <param name="end">End</param>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
public Task<T> GetRangeAsync<T>(string key, long start, long end) => CallAsync("GETRANGE".InputKey(key, start, end).FlagReadbytes(true), rt => rt.ThrowOrValue(a => DeserializeRedisValue<T>(a.ConvertTo<byte[]>(), rt.Encoding)));
/// <summary>
/// GETSET command (An Asynchronous Version) <br /><br />
/// <br />
/// Atomically sets key to value and returns the old value stored at key. Returns an error when key exists but does not hold a string value.<br /><br />
/// <br />
/// 以原子的方式将新值取代给定键的旧值,并返回旧值。如果该键存在但不包含字符串值时,返回错误。<br /><br />
/// <br />
/// Document link: https://redis.io/commands/getset <br />
/// Available since 1.0.0.
/// </summary>
/// <param name="key">Key</param>
/// <param name="value">New value</param>
/// <typeparam name="T"></typeparam>
/// <returns>The old value stored at key, or nil when key did not exist.</returns>
public Task<string> GetSetAsync<T>(string key, T value) => CallAsync("GETSET".InputKey(key).InputRaw(SerializeRedisValue(value)), rt => rt.ThrowOrValue<string>());
/// <summary>
/// INCR command (An Asynchronous Version) <br /><br />
/// <br />
/// Increments the number stored at key by one. <br />
/// If the key does not exist, it is set to 0 before performing the operation. An error is returned if the key contains a value of the wrong type or contains a string that can not be represented as integer. <br />
/// This operation is limited to 64 bit signed integers.<br /><br />
/// <br />
/// 对该键的值加上 1。<br />
/// 如果键值不存在,则在操作前先设置为 0。如果键对应的值是个错误类型或不能表达为整数的字符串,则返回错误。此操作仅限于 64 位有符号整数。<br /><br />
/// <br />
/// Document link: https://redis.io/commands/incr <br />
/// Available since 1.0.0.
/// </summary>
/// <param name="key">Key</param>
/// <returns>The value of key after the increment</returns>
public Task<long> IncrAsync(string key) => CallAsync("INCR".InputKey(key), rt => rt.ThrowOrValue<long>());
/// <summary>
/// INCRBY command (An Asynchronous Version) <br /><br />
/// <br />
/// Decrements the number stored at key by increment. <br />
/// If the key does not exist, it is set to 0 before performing the operation. An error is returned if the key contains a value of the wrong type or contains a string that can not be represented as integer. <br />
/// This operation is limited to 64 bit signed integers.<br /><br />
/// <br />
/// 对该键的值加上给定的值。<br />
/// 如果键值不存在,则在操作前先设置为 0。如果键对应的值是个错误类型或不能表达为整数的字符串,则返回错误。此操作仅限于 64 位有符号整数。<br /><br />
/// <br />
/// Document link: https://redis.io/commands/incrby <br />
/// Available since 1.0.0.
/// </summary>
/// <param name="key">Key</param>
/// <param name="increment">The given value to be increased.</param>
/// <returns>The value of key after the increment</returns>
public Task<long> IncrByAsync(string key, long increment) => CallAsync("INCRBY".InputKey(key, increment), rt => rt.ThrowOrValue<long>());
/// <summary>
/// INCRBYFLOAT command (An Asynchronous Version) <br /><br />
/// <br />
/// Increment the string representing a floating point number stored at key by the specified increment. <br />
/// By using a negative increment value, the result is that the value stored at the key is decremented (by the obvious properties of addition). <br />
/// If the key does not exist, it is set to 0 before performing the operation. An error is returned if one of the following conditions occur:<br />
/// - The key contains a value of the wrong type (not a string).<br />
/// - The current key content or the specified increment are not parsable as a double precision floating point number.<br />
/// If the command is successful the new incremented value is stored as the new value of the key (replacing the old one), and returned to the caller as a string.<br /><br />
/// <br />
/// 对该键的值加上给定的值,可以通过给定负值来减小对应键的值。<br />
/// 如果键值不存在,则在操作前先设置为 0。如果发生以下情况,则返回错误:<br />
/// - 键所对应的值是错误的类型(不是字符串);<br />
/// - 该键的内容不能被解析为双精度浮点数。<br />
/// 如果命令执行成功,则将新值替换旧值,并返回给调用方。<br /><br />
/// <br />
/// Document link: https://redis.io/commands/incrby <br />
/// Available since 2.6.0.
/// </summary>
/// <param name="key">Key</param>
/// <param name="increment">The given value to be increased.</param>
/// <returns>The value of key after the increment.</returns>
public Task<decimal> IncrByFloatAsync(string key, decimal increment) => CallAsync("INCRBYFLOAT".InputKey(key, increment), rt => rt.ThrowOrValue<decimal>());
/// <summary>
/// MGET command (An Asynchronous Version) <br /><br />
/// <br />
/// Returns the values of all specified keys. For every key that does not hold a string value or does not exist, the special value nil is returned. Because of this, the operation never fails.<br /><br />
/// <br />
/// 返回所有给定键的值,对于其中个别键不存在,或其值不为字符串的,反悔特殊的 nil 值,因此 MGET 指令永远不会执行失败。<br /><br />
/// <br />
/// Document link: https://redis.io/commands/mget <br />
/// Available since 1.0.0.
/// </summary>
/// <param name="keys">Key list</param>
/// <returns>A list of values at the specified keys.</returns>
public Task<string[]> MGetAsync(params string[] keys) => CallAsync("MGET".InputKey(keys), rt => rt.ThrowOrValue<string[]>());
/// <summary>
/// MGET command (An Asynchronous Version) <br /><br />
/// <br />
/// Returns the values of all specified keys. For every key that does not hold a string value or does not exist, the special value nil is returned. Because of this, the operation never fails.<br /><br />
/// <br />
/// 返回所有给定键的值,对于其中个别键不存在,或其值不为字符串的,反悔特殊的 nil 值,因此 MGET 指令永远不会执行失败。<br /><br />
/// <br />
/// Document link: https://redis.io/commands/mget <br />
/// Available since 1.0.0.
/// </summary>
/// <param name="keys">Key list</param>
/// <typeparam name="T"></typeparam>
/// <returns>A list of values at the specified keys.</returns>
public Task<T[]> MGetAsync<T>(params string[] keys) => CallAsync("MGET".InputKey(keys).FlagReadbytes(true), rt => rt
.ThrowOrValue((a, _) => a.Select(b => DeserializeRedisValue<T>(b.ConvertTo<byte[]>(), rt.Encoding)).ToArray()));
/// <summary>
/// MSET command (An Asynchronous Version) <br /><br />
/// <br />
/// Sets the given keys to their respective values. MSET replaces existing values with new values, just as regular SET. <br /><br />
/// <br />
/// 将给定键的值设置为对应的新值。 <br /><br />
/// <br />
/// Document link: https://redis.io/commands/mset <br />
/// Available since 1.0.1.
/// </summary>
/// <param name="key">Key</param>
/// <param name="value">Value</param>
/// <param name="keyValues">Other key-value sets</param>
public Task MSetAsync(string key, object value, params object[] keyValues) => MSetAsync<bool>(false, key, value, keyValues);
/// <summary>
/// MSET command (An Asynchronous Version) <br /><br />
/// <br />
/// Sets the given keys to their respective values. MSET replaces existing values with new values, just as regular SET. <br /><br />
/// <br />
/// 将给定键的值设置为对应的新值。 <br /><br />
/// <br />
/// Document link: https://redis.io/commands/mset <br />
/// Available since 1.0.1.
/// </summary>
/// <param name="keyValues">Key-value sets</param>
/// <typeparam name="T"></typeparam>
public Task MSetAsync<T>(Dictionary<string, T> keyValues) => CallAsync("MSET".SubCommand(null).InputKv(keyValues, true, SerializeRedisValue), rt => rt.ThrowOrValue<string>());
/// <summary>
/// MSETNX command (An Asynchronous Version) <br /><br />
/// <br />
/// Sets the given keys to their respective values. MSETNX will not perform any operation at all even if just a single key already exists.<br /><br />
/// <br />
/// 将给定键的值设置为对应的新值。只要有一个键已经存在,则整组键值都将不会被设置。 <br /><br />
/// <br />
/// Document link: https://redis.io/commands/msetnx <br />
/// Available since 1.0.1.
/// </summary>
/// <param name="key">Key</param>
/// <param name="value">Value</param>
/// <param name="keyValues">Other key-value sets</param>
/// <returns>True if the all the keys were set. False if no key was set (at least one key already existed).</returns>
public Task<bool> MSetNxAsync(string key, object value, params object[] keyValues) => MSetAsync<bool>(true, key, value, keyValues);
/// <summary>
/// MSETNX command (An Asynchronous Version) <br /><br />
/// <br />
/// Sets the given keys to their respective values. MSETNX will not perform any operation at all even if just a single key already exists.<br /><br />
/// <br />
/// 将给定键的值设置为对应的新值。只要有一个键已经存在,则整组键值都将不会被设置。 <br /><br />
/// <br />
/// Document link: https://redis.io/commands/msetnx <br />
/// Available since 1.0.1.
/// </summary>
/// <param name="keyValues">Key-value sets</param>
/// <typeparam name="T"></typeparam>
/// <returns>True if the all the keys were set. False if no key was set (at least one key already existed).</returns>
public Task<bool> MSetNxAsync<T>(Dictionary<string, T> keyValues) => CallAsync("MSETNX".SubCommand(null).InputKv(keyValues, true, SerializeRedisValue), rt => rt.ThrowOrValue<bool>());
/// <summary>
/// MSET key value [key value ...] command (An Asynchronous Version) <br /><br />
/// <br />
/// Sets the given keys to their respective values. MSET replaces existing values with new values, just as regular SET. See MSETNX if you don't want to overwrite existing values.<br /><br />
/// <br />
/// 将给定键的值设置为对应的新值。如果不想覆盖现有的值,可以使用 MSETNX 指令。<br /><br />
/// <br />
/// Document link: https://redis.io/commands/mset <br />
/// Available since 1.0.1.
/// </summary>
/// <param name="nx">Mark whether it is NX mode. If it is, use the MSETNX command; otherwise, use the MSET command.</param>
/// <param name="key">Key</param>
/// <param name="value">Value</param>
/// <param name="keyValues">Other key-value sets</param>
/// <typeparam name="T"></typeparam>
/// <returns>Always OK since MSET can't fail.</returns>
Task<T> MSetAsync<T>(bool nx, string key, object value, params object[] keyValues)
{
if (keyValues?.Any() == true)
return CallAsync((nx ? "MSETNX" : "MSET")
.InputKey(key).InputRaw(SerializeRedisValue(value))
.InputKv(keyValues, true, SerializeRedisValue), rt => rt.ThrowOrValue<T>());
return CallAsync((nx ? "MSETNX" : "MSET").InputKey(key).InputRaw(SerializeRedisValue(value)), rt => rt.ThrowOrValue<T>());
}
/// <summary>
/// PSETEX command (An Asynchronous Version) <br /><br />
/// <br />
/// PSETEX works exactly like SETEX with the sole difference that the expire time is specified in milliseconds instead of seconds.<br /><br />
/// <br />
/// PSETEX 的工作方式与 SETEX 完全相同,唯一的区别是到期时间的单位是毫秒(ms),而不是秒(s)。<br /><br />
/// <br />
/// Document link: https://redis.io/commands/psetex <br />
/// Available since 2.6.0.
/// </summary>
/// <param name="key">Key</param>
/// <param name="milliseconds">Timeout milliseconds value</param>
/// <param name="value">Value</param>
/// <typeparam name="T"></typeparam>
public Task PSetExAsync<T>(string key, long milliseconds, T value) => CallAsync("PSETEX".InputKey(key, milliseconds).InputRaw(SerializeRedisValue(value)), rt => rt.ThrowOrNothing());
/// <summary>
/// SET key value EX seconds (An Asynchronous Version) <br /><br />
/// <br />
/// Set key to hold the string value.<br /><br />
/// <br />
/// 设置键和值。<br /><br />
/// <br />
/// Document link: https://redis.io/commands/set <br />
/// Available since 2.6.12.
/// </summary>
/// <param name="key">Key</param>
/// <param name="value">Value</param>
/// <param name="timeoutSeconds">Timeout seconds</param>
/// <typeparam name="T"></typeparam>
public Task SetAsync<T>(string key, T value, int timeoutSeconds = 0) => SetAsync(key, value, TimeSpan.FromSeconds(timeoutSeconds), false, false, false, false);
/// <summary>
/// SET key value KEEPTTL command (An Asynchronous Version) <br /><br />
/// <br />
/// Set key to hold the string value. Retain the time to live associated with the key. <br /><br />
/// <br />
/// 设置键和值。<br /><br />
/// Document link: https://redis.io/commands/set <br />
/// Available since 6.0.0.
/// </summary>
/// <param name="key">Key</param>
/// <param name="value">Value</param>
/// <param name="keepTtl">Retain the time to live associated with the key</param>
/// <typeparam name="T"></typeparam>
public Task SetAsync<T>(string key, T value, bool keepTtl) => SetAsync(key, value, TimeSpan.Zero, keepTtl, false, false, false);
/// <summary>
/// SET key value EX seconds NX command (An Asynchronous Version) <br /><br />
/// <br />
/// Set key to hold the string value. Only set the key if it does not already exist.<br /><br />
/// <br />
/// 设置键和值。当且仅当键值不存在时才执行命令。<br /><br />
/// <br />
/// Document link: https://redis.io/commands/set <br />
/// Available since 2.6.12.
/// </summary>
/// <param name="key">Key</param>
/// <param name="value">Value</param>
/// <param name="timeoutSeconds">Timeout seconds</param>
/// <typeparam name="T"></typeparam>
/// <returns>
/// Simple string reply: OK if SET was executed correctly.<br />
/// Bulk string reply: when GET option is set, the old value stored at key, or nil when key did not exist.<br />
/// Null reply: a Null Bulk Reply is returned if the SET operation was not performed because the user specified the NX or XX option but the condition was not met or if user specified the NX and GET options that do not met.
/// </returns>
async public Task<bool> SetNxAsync<T>(string key, T value, int timeoutSeconds) => (await SetAsync(key, value, TimeSpan.FromSeconds(timeoutSeconds), false, true, false, false)) == "OK";
/// <summary>
/// SET key value EX seconds XX command (An Asynchronous Version) <br /><br />
/// <br />
/// Set key to hold the string value. Only set the key if it already exist.<br /><br />
/// <br />
/// 设置键和值。当且仅当键值已存在时才执行命令。<br /><br />
/// <br />
/// Document link: https://redis.io/commands/set <br />
/// Available since 2.6.12.
/// </summary>
/// <param name="key">Key</param>
/// <param name="value">Value</param>
/// <param name="timeoutSeconds">Timeout seconds</param>
/// <typeparam name="T"></typeparam>
/// <returns>
/// Simple string reply: OK if SET was executed correctly.<br />
/// Bulk string reply: when GET option is set, the old value stored at key, or nil when key did not exist.<br />
/// Null reply: a Null Bulk Reply is returned if the SET operation was not performed because the user specified the NX or XX option but the condition was not met or if user specified the NX and GET options that do not met.
/// </returns>
async public Task<bool> SetXxAsync<T>(string key, T value, int timeoutSeconds = 0) => (await SetAsync(key, value, TimeSpan.FromSeconds(timeoutSeconds), false, false, true, false)) == "OK";
/// <summary>
/// SET key value KEEPTTL XX command (An Asynchronous Version) <br /><br />
/// <br />
/// Set key to hold the string value. Only set the key if it already exist.<br /><br />
/// <br />
/// 设置键和值。当且仅当键值已存在时才执行命令。<br /><br />
/// <br />
/// Document link: https://redis.io/commands/set <br />
/// Available since 6.0.0.
/// </summary>
/// <param name="key">Key</param>
/// <param name="value">Value</param>
/// <param name="keepTtl">Retain the time to live associated with the key</param>
/// <typeparam name="T"></typeparam>
/// <returns>
/// Simple string reply: OK if SET was executed correctly.<br />
/// Bulk string reply: when GET option is set, the old value stored at key, or nil when key did not exist.<br />
/// Null reply: a Null Bulk Reply is returned if the SET operation was not performed because the user specified the NX or XX option but the condition was not met or if user specified the NX and GET options that do not met.
/// </returns>
async public Task<bool> SetXxAsync<T>(string key, T value, bool keepTtl) => (await SetAsync(key, value, TimeSpan.Zero, keepTtl, false, true, false)) == "OK";
/// <summary>
/// SET command (An Asynchronous Version) <br /><br />
///<br />
/// Set key to hold the string value. If key already holds a value, it is overwritten, regardless of its type. <br /><br />
/// <br />
/// 设置键和值。如果该键已存在,则覆盖之。<br /><br />
/// <br />
/// Document link: https://redis.io/commands/set <br />
/// Available since 1.0.0.
/// </summary>
/// <param name="key">Key</param>
/// <param name="value">Value</param>
/// <param name="timeout">Timeout value</param>
/// <param name="keepTtl">Retain the time to live associated with the key</param>
/// <param name="nx">Only set the key if it does not already exist.</param>
/// <param name="xx">Only set the key if it already exist.</param>
/// <param name="get"></param>
/// <typeparam name="T"></typeparam>
/// <returns>
/// Simple string reply: OK if SET was executed correctly.<br />
/// Bulk string reply: when GET option is set, the old value stored at key, or nil when key did not exist.<br />
/// Null reply: a Null Bulk Reply is returned if the SET operation was not performed because the user specified the NX or XX option but the condition was not met or if user specified the NX and GET options that do not met.
/// </returns>
public Task<string> SetAsync<T>(string key, T value, TimeSpan timeout, bool keepTtl, bool nx, bool xx, bool get) => CallAsync("SET"
.InputKey(key)
.InputRaw(SerializeRedisValue(value))
.InputIf(timeout.TotalSeconds >= 1, "EX", (long) timeout.TotalSeconds)
.InputIf(timeout.TotalSeconds < 1 && timeout.TotalMilliseconds >= 1, "PX", (long) timeout.TotalMilliseconds)
.InputIf(keepTtl, "KEEPTTL")
.InputIf(nx, "NX")
.InputIf(xx, "XX").InputIf(get, "GET"), rt => rt.ThrowOrValue<string>());
/// <summary>
/// SETBIT command (An Asynchronous Version) <br /><br />
///<br />
/// Sets or clears the bit at offset in the string value stored at key.<br /><br />
/// <br />
/// 设置或清除键值字符串指定偏移量的位(bit)。<br /><br />
/// <br />
/// Document link: https://redis.io/commands/setbit <br />
/// Available since 2.2.0.
/// </summary>
/// <param name="key">Key</param>
/// <param name="offset">Offset value</param>
/// <param name="value">New value</param>
/// <returns>The original bit value stored at offset.</returns>
public Task<long> SetBitAsync(string key, long offset, bool value) => CallAsync("SETBIT".InputKey(key, offset, value ? "1" : "0"), rt => rt.ThrowOrValue<long>());
/// <summary>
/// SETEX command (An Asynchronous Version) <br /><br />
/// <br />
/// Set key to hold the string value and set key to timeout after a given number of seconds.<br /><br />
/// <br />
/// 设置键值在给定的秒数后超时。<br /><br />
/// <br />
/// Document link: https://redis.io/commands/setex <br />
/// Available since 2.0.0.
/// </summary>
/// <param name="key">Key</param>
/// <param name="seconds">Seconds</param>
/// <param name="value">Value</param>
/// <typeparam name="T"></typeparam>
public Task SetExAsync<T>(string key, int seconds, T value) => CallAsync("SETEX".InputKey(key, seconds).InputRaw(SerializeRedisValue(value)), rt => rt.ThrowOrNothing());
/// <summary>
/// SETNX command (An Asynchronous Version) <br /><br />
/// <br />
/// Set key to hold string value if key does not exist. In that case, it is equal to SET. When key already holds a value, no operation is performed. <br />
/// SETNX is short for "SET if Not eXists".<br /><br />
/// <br />
/// 如果键值不存在,则设置该键值,在此情况下与 SET 指令相似。当键值已经存在时,不执行任何操作。<br /><br />
/// <br />
/// Document link: https://redis.io/commands/setnx <br />
/// Available since 1.0.0.
/// </summary>
/// <param name="key">Key</param>
/// <param name="value">Value</param>
/// <typeparam name="T"></typeparam>
/// <returns>Set result, specifically: 1 is if the key was set; 0 is if the key was not set.</returns>
public Task<bool> SetNxAsync<T>(string key, T value) => CallAsync("SETNX".InputKey(key).InputRaw(SerializeRedisValue(value)), rt => rt.ThrowOrValue<bool>());
/// <summary>
/// SETRANGE command (An Asynchronous Version) <br /><br />
/// <br />
/// Overwrites part of the string stored at key, starting at the specified offset, for the entire length of value. If the offset is larger than the current length of the string at key, the string is padded with zero-bytes to make offset fit. Non-existing keys are considered as empty strings, so this command will make sure it holds a string large enough to be able to set value at offset.<br /><br />
/// <br />
/// 从给定的偏移量开始覆盖键所对应的字符串值。如果偏移量大于值的长度,则为该字符串填充零字节(zero-bytes)以满足偏移量的要求。若键值不存在则视作空字符串值。故本指令将确保有足够长度的字符串以适应偏移量的要求。<br /><br />
/// <br />
/// Document link: https://redis.io/commands/setrange <br />
/// Available since 2.2.0.
/// </summary>
/// <param name="key">Key</param>
/// <param name="offset">Offset value</param>
/// <param name="value">The value to be filled.</param>
/// <typeparam name="T"></typeparam>
/// <returns>The length of the string after it was modified by the command.</returns>
public Task<long> SetRangeAsync<T>(string key, long offset, T value) => CallAsync("SETRANGE".InputKey(key, offset).InputRaw(SerializeRedisValue(value)), rt => rt.ThrowOrValue<long>());
//STRALGO LCS algo-specific-argument [algo-specific-argument ...]
/// <summary>
/// STRLRN command (An Asynchronous Version) <br /><br />
/// <br />
/// Returns the length of the string value stored at key. An error is returned when key holds a non-string value.<br /><br />
/// <br />
/// 返回键对应值字符串的长度。当该键对应的值不是字符串,则返回错误。<br /><br />
/// <br />
/// Document link: https://redis.io/commands/strlen <br />
/// Available since 2.2.0.
/// </summary>
/// <param name="key">Key</param>
/// <returns>The length of the string at key, or 0 when key does not exist.</returns>
public Task<long> StrLenAsync(string key) => CallAsync("STRLEN".InputKey(key), rt => rt.ThrowOrValue<long>());
#endregion
#endif
/// <summary>
/// APPEND command (A Synchronized Version)<br /><br />
/// <br />
/// If key already exists and is a string, this command appends the value at the end of the string. If key does not exist it is created and set as an empty string, so APPEND will be similar to SET in this special case. <br /><br />
/// <br />
/// 若键值已存在且为字符串,则此命令将值附加在字符串的末尾;<br />
/// 若键值不存在,则会先创建一个空字符串,并附加值(在此情况下,APPEND 类似 SET 命令)。<br /><br />
/// <br />
/// Document link: https://redis.io/commands/append <br />
/// Available since 2.0.0.
/// </summary>
/// <param name="key">Key</param>
/// <param name="value">Value</param>
/// <typeparam name="T"></typeparam>
/// <returns>The length of the string after the append operation.</returns>
public long Append<T>(string key, T value) => Call("APPEND".InputKey(key).InputRaw(SerializeRedisValue(value)), rt => rt.ThrowOrValue<long>());
/// <summary>
/// BITCOUNT command (A Synchronized Version)<br /><br />
/// <br />
/// Count the number of set bits (population counting) in a string.<br /><br />
/// <br />
/// 统计字符串中的位数。<br /><br />
/// <br />
/// Document link: https://redis.io/commands/bitcount <br />
/// Available since 2.6.0.
/// </summary>
/// <param name="key">Key</param>
/// <param name="start">Index of the start. It can contain negative values in order to index bytes starting from the end of the string.</param>
/// <param name="end">Index of the end. It can contain negative values in order to index bytes starting from the end of the string.</param>
/// <returns>The number of set bits in the string. Non-existent keys are treated as empty strings and will return zero.</returns>
public long BitCount(string key, long start, long end) => Call("BITCOUNT".InputKey(key, start, end), rt => rt.ThrowOrValue<long>());
/// <summary>
/// BITOP command (A Synchronized Version) <br /><br />
/// <br />
/// Perform a bitwise operation between multiple keys (containing string values) and store the result in the destination key.<br /><br />
/// <br />
/// 在(包括字符串值)的多键之间按位运算,并将结果保存在目标键中。<br />
/// 目前支持 AND、OR、XOR 与 NOT 四种运算方式。<br /><br />
/// <br />
/// Document link: https://redis.io/commands/bitop <br />
/// Available since 2.6.0.
/// </summary>
/// <param name="operation">Bit operation type: AND, OR, XOR or NOT</param>
/// <param name="destkey">Destination Key</param>
/// <param name="keys">Multiple keys (containing string values)</param>
/// <returns>The size of the string stored in the destination key, that is equal to the size of the longest input string.</returns>
public long BitOp(BitOpOperation operation, string destkey, params string[] keys) => Call("BITOP".InputRaw(operation).InputKey(destkey).InputKey(keys), rt => rt.ThrowOrValue<long>());
/// <summary>
/// BITPOS command (A Synchronized Version) <br /><br />
/// <br />
/// Return the position of the first bit set to 1 or 0 in a string.<br />
/// The position is returned, thinking of the string as an array of bits from left to right, where the first byte's most significant bit is at position 0, the second byte's most significant bit is at position 8, and so forth.<br /><br />
/// <br />
/// 返回字符串中第一个 1 或 0 的位置。<br />
/// 注意,本命令将字符串视作位数组,自左向右计算,第一个字节在位置 0,第二个字节在位置 8,以此类推。<br /><br />
/// <br />
/// Document link: https://redis.io/commands/bitpos <br />
/// Available since 2.8.7.
/// </summary>
/// <param name="key">Key</param>
/// <param name="bit">Bit value, 1 is true, 0 is false.</param>
/// <param name="start">Index of the start. It can contain negative values in order to index bytes starting from the end of the string.</param>
/// <param name="end">Index of the end. It can contain negative values in order to index bytes starting from the end of the string.</param>
/// <returns>Returns the position of the first bit set to 1 or 0 according to the request.</returns>
public long BitPos(string key, bool bit, long? start = null, long? end = null) => Call("BITPOS"
.InputKey(key, bit ? "1" : "0")
.InputIf(start != null, start)
.InputIf(end != null, start), rt => rt.ThrowOrValue<long>());
/// <summary>
/// DECR command (A Synchronized Version) <br /><br />
/// <br />
/// Decrements the number stored at key by one. <br />
/// If the key does not exist, it is set to 0 before performing the operation. An error is returned if the key contains a value of the wrong type or contains a string that can not be represented as integer. <br />
/// This operation is limited to 64 bit signed integers.<br /><br />
/// <br />
/// 对该键的值减去 1。<br />
/// 如果键值不存在,则在操作前先设置为 0。如果键对应的值是个错误类型或不能表达为整数的字符串,则返回错误。此操作仅限于 64 位有符号整数。<br /><br />
/// <br />
/// Document link: https://redis.io/commands/decr <br />
/// Available since 1.0.0.
/// </summary>
/// <param name="key">Key</param>
/// <returns>the value of key after the decrement.</returns>
public long Decr(string key) => Call("DECR".InputKey(key), rt => rt.ThrowOrValue<long>());
/// <summary>
/// DECRBY command (A Synchronized Version) <br /><br />
/// <br />
/// Decrements the number stored at key by decrement. <br />
/// If the key does not exist, it is set to 0 before performing the operation. An error is returned if the key contains a value of the wrong type or contains a string that can not be represented as integer. <br />
/// This operation is limited to 64 bit signed integers.<br /><br />
/// <br />
/// 对该键的值减去给定的值。<br />
/// 如果键值不存在,则在操作前先设置为 0。如果键对应的值是个错误类型或不能表达为整数的字符串,则返回错误。此操作仅限于 64 位有符号整数。<br /><br />
/// <br />
/// Document link: https://redis.io/commands/decrby <br />
/// Available since 1.0.0.
/// </summary>
/// <param name="key">Key</param>
/// <param name="decrement">The given value to be decreased.</param>
/// <returns>the value of key after the decrement.</returns>
public long DecrBy(string key, long decrement) => Call("DECRBY".InputKey(key, decrement), rt => rt.ThrowOrValue<long>());
/// <summary>
/// GET command (A Synchronized Version) <br /><br />
/// <br />
/// Get the value of key. If the key does not exist the special value nil is returned. An error is returned if the value stored at key is not a string, because GET only handles string values.<br /><br />
/// <br />
/// 获得给定键的值。若键不存在,则返回特殊的 nil 值。如果给定键的值不是字符串,则返回错误,因为 GET 指令只能处理字符串。 <br /><br />
/// <br />
/// Document link: https://redis.io/commands/get <br />
/// Available since 1.0.0.
/// </summary>
/// <param name="key">Key</param>
/// <returns>The value of key, or nil when key does not exist.</returns>
public string Get(string key) => Call("GET".InputKey(key), rt => rt.ThrowOrValue<string>());
/// <summary>
/// GET command (A Synchronized Version) <br /><br />
/// <br />
/// Get the value of key. If the key does not exist the special value nil is returned. An error is returned if the value stored at key is not a string, because GET only handles string values.<br /><br />
/// <br />
/// 获得给定键的值。若键不存在,则返回特殊的 nil 值。如果给定键的值不是字符串,则返回错误,因为 GET 指令只能处理字符串。 <br /><br />
/// <br />
/// Document link: https://redis.io/commands/get <br />
/// Available since 1.0.0.
/// </summary>
/// <param name="key">Key</param>
/// <typeparam name="T"></typeparam>
/// <returns>The value of key, or nil when key does not exist.</returns>
public T Get<T>(string key) => Call("GET".InputKey(key).FlagReadbytes(true), rt => rt.ThrowOrValue(a => DeserializeRedisValue<T>(a.ConvertTo<byte[]>(), rt.Encoding)));
/// <summary>
/// GET command (A Synchronized Version) <br /><br />
/// <br />
/// Get the value of key and write to the stream.. If the key does not exist the special value nil is returned. An error is returned if the value stored at key is not a string, because GET only handles string values.<br /><br />
/// <br />
/// 获得给定键的值并写入流中。若键不存在,则返回特殊的 nil 值。如果给定键的值不是字符串,则返回错误,因为 GET 指令只能处理字符串。 <br /><br />
/// <br />
/// Document link: https://redis.io/commands/get <br />
/// Available since 1.0.0.
/// </summary>
/// <param name="key">Key</param>
/// <param name="destination">Destination stream</param>
/// <param name="bufferSize">Size</param>
public void Get(string key, Stream destination, int bufferSize = 1024)
{
var cmd = "GET".InputKey(key);
Adapter.TopOwner.LogCall(cmd, () =>
{
using (var rds = Adapter.GetRedisSocket(cmd))
{
rds.Write(cmd);
rds.ReadChunk(destination, bufferSize);
}
return default(string);
});
}
/// <summary>
/// GETBIT command (A Synchronized Version) <br /><br />
/// <br />
/// Returns the bit value at offset in the string value stored at key.<br /><br />
/// <br />
/// 返回键所对应字符串值中偏移量的位值。<br /><br />
/// <br />
/// Document link: https://redis.io/commands/getbit <br />
/// Available since 2.2.0.
/// </summary>
/// <param name="key">Key</param>
/// <param name="offset">Offset</param>
/// <returns>The bit value stored at offset.</returns>
public bool GetBit(string key, long offset) => Call("GETBIT".InputKey(key, offset), rt => rt.ThrowOrValue<bool>());
/// <summary>
/// GETRANGE command (A Synchronized Version) <br /><br />
/// <br />
/// Returns the substring of the string value stored at key, determined by the offsets start and end (both are inclusive).<br /><br />
/// <br />
/// 返回键值的子字符串该字符串由偏移量 start 和 end 来确定(两端均闭包)。<br /><br />
/// <br />
/// Document link: https://redis.io/commands/getrange <br />
/// Available since 2.0.0. It is called SUBSTR in Redis versions <= 2.0.
/// </summary>
/// <param name="key">Key</param>
/// <param name="start">Start</param>
/// <param name="end">End</param>
/// <returns>The substring of the string value</returns>
public string GetRange(string key, long start, long end) => Call("GETRANGE".InputKey(key, start, end), rt => rt.ThrowOrValue<string>());
/// <summary>
/// GETRANGE command (A Synchronized Version) <br /><br />
/// <br />
/// Returns the substring of the string value stored at key, determined by the offsets start and end (both are inclusive).<br /><br />
/// <br />
/// 返回键值的子字符串该字符串由偏移量 start 和 end 来确定(两端均闭包)。<br /><br />
/// <br />
/// Document link: https://redis.io/commands/getrange <br />
/// Available since 2.0.0. It is called SUBSTR in Redis versions <= 2.0.
/// </summary>
/// <param name="key">Key</param>
/// <param name="start">Start</param>
/// <param name="end">End</param>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
public T GetRange<T>(string key, long start, long end) => Call("GETRANGE".InputKey(key, start, end).FlagReadbytes(true), rt => rt.ThrowOrValue(a => DeserializeRedisValue<T>(a.ConvertTo<byte[]>(), rt.Encoding)));
/// <summary>
/// GETSET command (A Synchronized Version) <br /><br />
/// <br />
/// Atomically sets key to value and returns the old value stored at key. Returns an error when key exists but does not hold a string value.<br /><br />
/// <br />
/// 以原子的方式将新值取代给定键的旧值,并返回旧值。如果该键存在但不包含字符串值时,返回错误。<br /><br />
/// <br />
/// Document link: https://redis.io/commands/getset <br />
/// Available since 1.0.0.
/// </summary>
/// <param name="key">Key</param>
/// <param name="value">New value</param>
/// <typeparam name="T"></typeparam>
/// <returns>The old value stored at key, or nil when key did not exist.</returns>
public string GetSet<T>(string key, T value) => Call("GETSET".InputKey(key).InputRaw(SerializeRedisValue(value)), rt => rt.ThrowOrValue<string>());
/// <summary>
/// INCR command (A Synchronized Version) <br /><br />
/// <br />
/// Increments the number stored at key by one. <br />
/// If the key does not exist, it is set to 0 before performing the operation. An error is returned if the key contains a value of the wrong type or contains a string that can not be represented as integer. <br />
/// This operation is limited to 64 bit signed integers.<br /><br />
/// <br />
/// 对该键的值加上 1。<br />
/// 如果键值不存在,则在操作前先设置为 0。如果键对应的值是个错误类型或不能表达为整数的字符串,则返回错误。此操作仅限于 64 位有符号整数。<br /><br />
/// <br />
/// Document link: https://redis.io/commands/incr <br />
/// Available since 1.0.0.
/// </summary>
/// <param name="key">Key</param>
/// <returns>The value of key after the increment</returns>
public long Incr(string key) => Call("INCR".InputKey(key), rt => rt.ThrowOrValue<long>());
/// <summary>
/// INCRBY command (A Synchronized Version) <br /><br />
/// <br />
/// Decrements the number stored at key by increment. <br />
/// If the key does not exist, it is set to 0 before performing the operation. An error is returned if the key contains a value of the wrong type or contains a string that can not be represented as integer. <br />
/// This operation is limited to 64 bit signed integers.<br /><br />
/// <br />
/// 对该键的值加上给定的值。<br />
/// 如果键值不存在,则在操作前先设置为 0。如果键对应的值是个错误类型或不能表达为整数的字符串,则返回错误。此操作仅限于 64 位有符号整数。<br /><br />
/// <br />
/// Document link: https://redis.io/commands/incrby <br />
/// Available since 1.0.0.
/// </summary>
/// <param name="key">Key</param>
/// <param name="increment">The given value to be increased.</param>
/// <returns>The value of key after the increment</returns>
public long IncrBy(string key, long increment) => Call("INCRBY".InputKey(key, increment), rt => rt.ThrowOrValue<long>());
/// <summary>
/// INCRBYFLOAT command (A Synchronized Version) <br /><br />
/// <br />
/// Increment the string representing a floating point number stored at key by the specified increment. <br />
/// By using a negative increment value, the result is that the value stored at the key is decremented (by the obvious properties of addition). <br />
/// If the key does not exist, it is set to 0 before performing the operation. An error is returned if one of the following conditions occur:<br />
/// - The key contains a value of the wrong type (not a string).<br />
/// - The current key content or the specified increment are not parsable as a double precision floating point number.<br />
/// If the command is successful the new incremented value is stored as the new value of the key (replacing the old one), and returned to the caller as a string.<br /><br />
/// <br />
/// 对该键的值加上给定的值,可以通过给定负值来减小对应键的值。<br />
/// 如果键值不存在,则在操作前先设置为 0。如果发生以下情况,则返回错误:<br />
/// - 键所对应的值是错误的类型(不是字符串);<br />
/// - 该键的内容不能被解析为双精度浮点数。<br />
/// 如果命令执行成功,则将新值替换旧值,并返回给调用方。<br /><br />
/// <br />
/// Document link: https://redis.io/commands/incrby <br />
/// Available since 2.6.0.
/// </summary>
/// <param name="key">Key</param>
/// <param name="increment">The given value to be increased.</param>
/// <returns>The value of key after the increment.</returns>
public decimal IncrByFloat(string key, decimal increment) => Call("INCRBYFLOAT".InputKey(key, increment), rt => rt.ThrowOrValue<decimal>());
/// <summary>
/// MGET command (A Synchronized Version) <br /><br />
/// <br />
/// Returns the values of all specified keys. For every key that does not hold a string value or does not exist, the special value nil is returned. Because of this, the operation never fails.<br /><br />
/// <br />
/// 返回所有给定键的值,对于其中个别键不存在,或其值不为字符串的,反悔特殊的 nil 值,因此 MGET 指令永远不会执行失败。<br /><br />
/// <br />
/// Document link: https://redis.io/commands/mget <br />
/// Available since 1.0.0.
/// </summary>
/// <param name="keys">Key list</param>
/// <returns>A list of values at the specified keys.</returns>
public string[] MGet(params string[] keys) => Call("MGET".InputKey(keys), rt => rt.ThrowOrValue<string[]>());
/// <summary>
/// MGET command (A Synchronized Version) <br /><br />
/// <br />
/// Returns the values of all specified keys. For every key that does not hold a string value or does not exist, the special value nil is returned. Because of this, the operation never fails.<br /><br />
/// <br />
/// 返回所有给定键的值,对于其中个别键不存在,或其值不为字符串的,反悔特殊的 nil 值,因此 MGET 指令永远不会执行失败。<br /><br />
/// <br />
/// Document link: https://redis.io/commands/mget <br />
/// Available since 1.0.0.
/// </summary>
/// <param name="keys">Key list</param>
/// <typeparam name="T"></typeparam>
/// <returns>A list of values at the specified keys.</returns>
public T[] MGet<T>(params string[] keys) => Call("MGET".InputKey(keys).FlagReadbytes(true), rt => rt
.ThrowOrValue((a, _) => a.Select(b => DeserializeRedisValue<T>(b.ConvertTo<byte[]>(), rt.Encoding)).ToArray()));
/// <summary>
/// MSET command (A Synchronized Version) <br /><br />
/// <br />
/// Sets the given keys to their respective values. MSET replaces existing values with new values, just as regular SET. <br /><br />
/// <br />
/// 将给定键的值设置为对应的新值。 <br /><br />
/// <br />
/// Document link: https://redis.io/commands/mset <br />
/// Available since 1.0.1.
/// </summary>
/// <param name="key">Key</param>
/// <param name="value">Value</param>
/// <param name="keyValues">Other key-value sets</param>
public void MSet(string key, object value, params object[] keyValues) => MSet<bool>(false, key, value, keyValues);
/// <summary>
/// MSET command (A Synchronized Version) <br /><br />
/// <br />
/// Sets the given keys to their respective values. MSET replaces existing values with new values, just as regular SET. <br /><br />
/// <br />
/// 将给定键的值设置为对应的新值。 <br /><br />
/// <br />
/// Document link: https://redis.io/commands/mset <br />
/// Available since 1.0.1.
/// </summary>
/// <param name="keyValues">Key-value sets</param>
/// <typeparam name="T"></typeparam>
public void MSet<T>(Dictionary<string, T> keyValues) => Call("MSET".SubCommand(null).InputKv(keyValues, true, SerializeRedisValue), rt => rt.ThrowOrValue<string>());
/// <summary>
/// MSETNX command (A Synchronized Version) <br /><br />
/// <br />
/// Sets the given keys to their respective values. MSETNX will not perform any operation at all even if just a single key already exists.<br /><br />
/// <br />
/// 将给定键的值设置为对应的新值。只要有一个键已经存在,则整组键值都将不会被设置。 <br /><br />
/// <br />
/// Document link: https://redis.io/commands/msetnx <br />
/// Available since 1.0.1.
/// </summary>
/// <param name="key">Key</param>
/// <param name="value">Value</param>
/// <param name="keyValues">Other key-value sets</param>
/// <returns>True if the all the keys were set. False if no key was set (at least one key already existed).</returns>
public bool MSetNx(string key, object value, params object[] keyValues) => MSet<bool>(true, key, value, keyValues);
/// <summary>
/// MSETNX command (A Synchronized Version) <br /><br />
/// <br />
/// Sets the given keys to their respective values. MSETNX will not perform any operation at all even if just a single key already exists.<br /><br />
/// <br />
/// 将给定键的值设置为对应的新值。只要有一个键已经存在,则整组键值都将不会被设置。 <br /><br />
/// <br />
/// Document link: https://redis.io/commands/msetnx <br />
/// Available since 1.0.1.
/// </summary>
/// <param name="keyValues">Key-value sets</param>
/// <typeparam name="T"></typeparam>
/// <returns>True if the all the keys were set. False if no key was set (at least one key already existed).</returns>
public bool MSetNx<T>(Dictionary<string, T> keyValues) => Call("MSETNX".SubCommand(null).InputKv(keyValues, true, SerializeRedisValue), rt => rt.ThrowOrValue<bool>());
/// <summary>
/// MSET key value [key value ...] command (A Synchronized Version) <br /><br />
/// <br />
/// Sets the given keys to their respective values. MSET replaces existing values with new values, just as regular SET. See MSETNX if you don't want to overwrite existing values.<br /><br />
/// <br />
/// 将给定键的值设置为对应的新值。如果不想覆盖现有的值,可以使用 MSETNX 指令。<br /><br />
/// <br />
/// Document link: https://redis.io/commands/mset <br />
/// Available since 1.0.1.
/// </summary>
/// <param name="nx">Mark whether it is NX mode. If it is, use the MSETNX command; otherwise, use the MSET command.</param>
/// <param name="key">Key</param>
/// <param name="value">Value</param>
/// <param name="keyValues">Other key-value sets</param>
/// <typeparam name="T"></typeparam>
/// <returns>Always OK since MSET can't fail.</returns>
T MSet<T>(bool nx, string key, object value, params object[] keyValues)
{
if (keyValues?.Any() == true)
return Call((nx ? "MSETNX" : "MSET")
.InputKey(key).InputRaw(SerializeRedisValue(value))
.InputKv(keyValues, true, SerializeRedisValue), rt => rt.ThrowOrValue<T>());
return Call((nx ? "MSETNX" : "MSET").InputKey(key).InputRaw(SerializeRedisValue(value)), rt => rt.ThrowOrValue<T>());
}
/// <summary>
/// PSETEX command (A Synchronized Version) <br /><br />
/// <br />
/// PSETEX works exactly like SETEX with the sole difference that the expire time is specified in milliseconds instead of seconds.<br /><br />
/// <br />
/// PSETEX 的工作方式与 SETEX 完全相同,唯一的区别是到期时间的单位是毫秒(ms),而不是秒(s)。<br /><br />
/// <br />
/// Document link: https://redis.io/commands/psetex <br />
/// Available since 2.6.0.
/// </summary>
/// <param name="key">Key</param>
/// <param name="milliseconds">Timeout milliseconds value</param>
/// <param name="value">Value</param>
/// <typeparam name="T"></typeparam>
public void PSetEx<T>(string key, long milliseconds, T value) => Call("PSETEX".InputKey(key, milliseconds).InputRaw(SerializeRedisValue(value)), rt => rt.ThrowOrNothing());
/// <summary>
/// SET key value EX seconds (A Synchronized Version) <br /><br />
/// <br />
/// Set key to hold the string value.<br /><br />
/// <br />
/// 设置键和值。<br /><br />
/// <br />
/// Document link: https://redis.io/commands/set <br />
/// Available since 2.6.12.
/// </summary>
/// <param name="key">Key</param>
/// <param name="value">Value</param>
/// <param name="timeoutSeconds">Timeout seconds</param>
/// <typeparam name="T"></typeparam>
public void Set<T>(string key, T value, int timeoutSeconds = 0) => Set(key, value, TimeSpan.FromSeconds(timeoutSeconds), false, false, false, false);
/// <summary>
/// SET key value KEEPTTL command (A Synchronized Version) <br /><br />
/// <br />
/// Set key to hold the string value. Retain the time to live associated with the key. <br /><br />
/// <br />
/// 设置键和值。<br /><br />
/// Document link: https://redis.io/commands/set <br />
/// Available since 6.0.0.
/// </summary>
/// <param name="key">Key</param>
/// <param name="value">Value</param>
/// <param name="keepTtl">Retain the time to live associated with the key</param>
/// <typeparam name="T"></typeparam>
public void Set<T>(string key, T value, bool keepTtl) => Set(key, value, TimeSpan.Zero, keepTtl, false, false, false);
/// <summary>
/// SET key value EX seconds NX command (A Synchronized Version) <br /><br />
/// <br />
/// Set key to hold the string value. Only set the key if it does not already exist.<br /><br />
/// <br />
/// 设置键和值。当且仅当键值不存在时才执行命令。<br /><br />
/// <br />
/// Document link: https://redis.io/commands/set <br />
/// Available since 2.6.12.
/// </summary>
/// <param name="key">Key</param>
/// <param name="value">Value</param>
/// <param name="timeoutSeconds">Timeout seconds</param>
/// <typeparam name="T"></typeparam>
/// <returns>
/// Simple string reply: OK if SET was executed correctly.<br />
/// Bulk string reply: when GET option is set, the old value stored at key, or nil when key did not exist.<br />
/// Null reply: a Null Bulk Reply is returned if the SET operation was not performed because the user specified the NX or XX option but the condition was not met or if user specified the NX and GET options that do not met.
/// </returns>
public bool SetNx<T>(string key, T value, int timeoutSeconds) => Set(key, value, TimeSpan.FromSeconds(timeoutSeconds), false, true, false, false) == "OK";
/// <summary>
/// SET key value EX seconds XX command (A Synchronized Version) <br /><br />
/// <br />
/// Set key to hold the string value. Only set the key if it already exist.<br /><br />
/// <br />
/// 设置键和值。当且仅当键值已存在时才执行命令。<br /><br />
/// <br />
/// Document link: https://redis.io/commands/set <br />
/// Available since 2.6.12.
/// </summary>
/// <param name="key">Key</param>
/// <param name="value">Value</param>
/// <param name="timeoutSeconds">Timeout seconds</param>
/// <typeparam name="T"></typeparam>
/// <returns>
/// Simple string reply: OK if SET was executed correctly.<br />
/// Bulk string reply: when GET option is set, the old value stored at key, or nil when key did not exist.<br />
/// Null reply: a Null Bulk Reply is returned if the SET operation was not performed because the user specified the NX or XX option but the condition was not met or if user specified the NX and GET options that do not met.
/// </returns>
public bool SetXx<T>(string key, T value, int timeoutSeconds = 0) => Set(key, value, TimeSpan.FromSeconds(timeoutSeconds), false, false, true, false) == "OK";
/// <summary>
/// SET key value KEEPTTL XX command (A Synchronized Version) <br /><br />
/// <br />
/// Set key to hold the string value. Only set the key if it already exist.<br /><br />
/// <br />
/// 设置键和值。当且仅当键值已存在时才执行命令。<br /><br />
/// <br />
/// Document link: https://redis.io/commands/set <br />
/// Available since 6.0.0.
/// </summary>
/// <param name="key">Key</param>
/// <param name="value">Value</param>
/// <param name="keepTtl">Retain the time to live associated with the key</param>
/// <typeparam name="T"></typeparam>
/// <returns>
/// Simple string reply: OK if SET was executed correctly.<br />
/// Bulk string reply: when GET option is set, the old value stored at key, or nil when key did not exist.<br />
/// Null reply: a Null Bulk Reply is returned if the SET operation was not performed because the user specified the NX or XX option but the condition was not met or if user specified the NX and GET options that do not met.
/// </returns>
public bool SetXx<T>(string key, T value, bool keepTtl) => Set(key, value, TimeSpan.Zero, keepTtl, false, true, false) == "OK";
/// <summary>
/// SET command (A Synchronized Version) <br /><br />
/// <br />
/// Set key to hold the string value. If key already holds a value, it is overwritten, regardless of its type. <br /><br />
/// <br />
/// 设置键和值。如果该键已存在,则覆盖之。<br /><br />
/// <br />
/// Document link: https://redis.io/commands/set <br />
/// Available since 6.0.0.
/// </summary>
/// <param name="key">Key</param>
/// <param name="value">Value</param>
/// <param name="timeout">Timeout value</param>
/// <param name="keepTtl">Retain the time to live associated with the key</param>
/// <param name="nx">Only set the key if it does not already exist.</param>
/// <param name="xx">Only set the key if it already exist.</param>
/// <param name="get">Return the old value stored at key, or nil when key did not exist.</param>
/// <typeparam name="T"></typeparam>
/// <returns>
/// Simple string reply: OK if SET was executed correctly.<br />
/// Bulk string reply: when GET option is set, the old value stored at key, or nil when key did not exist.<br />
/// Null reply: a Null Bulk Reply is returned if the SET operation was not performed because the user specified the NX or XX option but the condition was not met or if user specified the NX and GET options that do not met.
/// </returns>
public string Set<T>(string key, T value, TimeSpan timeout, bool keepTtl, bool nx, bool xx, bool get) => Call("SET"
.InputKey(key)
.InputRaw(SerializeRedisValue(value))
.InputIf(timeout.TotalSeconds >= 1, "EX", (long) timeout.TotalSeconds)
.InputIf(timeout.TotalSeconds < 1 && timeout.TotalMilliseconds >= 1, "PX", (long) timeout.TotalMilliseconds)
.InputIf(keepTtl, "KEEPTTL")
.InputIf(nx, "NX")
.InputIf(xx, "XX")
.InputIf(get, "GET"), rt => rt.ThrowOrValue<string>());
/// <summary>
/// SETBIT command (A Synchronized Version) <br /><br />
/// <br />
/// Sets or clears the bit at offset in the string value stored at key.<br /><br />
/// <br />
/// 设置或清除键值字符串指定偏移量的位(bit)。<br /><br />
/// <br />
/// Document link: https://redis.io/commands/setbit <br />
/// Available since 2.2.0.
/// </summary>
/// <param name="key">Key</param>
/// <param name="offset">Offset value</param>
/// <param name="value">New value</param>
/// <returns>The original bit value stored at offset.</returns>
public long SetBit(string key, long offset, bool value) => Call("SETBIT".InputKey(key, offset, value ? "1" : "0"), rt => rt.ThrowOrValue<long>());
/// <summary>
/// SETEX command (A Synchronized Version) <br /><br />
/// <br />
/// Set key to hold the string value and set key to timeout after a given number of seconds.<br /><br />
/// <br />
/// 设置键值在给定的秒数后超时。<br /><br />
/// <br />
/// Document link: https://redis.io/commands/setex <br />
/// Available since 2.0.0.
/// </summary>
/// <param name="key">Key</param>
/// <param name="seconds">Seconds</param>
/// <param name="value">Value</param>
/// <typeparam name="T"></typeparam>
public void SetEx<T>(string key, int seconds, T value) => Call("SETEX".InputKey(key, seconds).InputRaw(SerializeRedisValue(value)), rt => rt.ThrowOrNothing());
/// <summary>
/// SETNX command (A Synchronized Version) <br /><br />
/// <br />
/// Set key to hold string value if key does not exist. In that case, it is equal to SET. When key already holds a value, no operation is performed. <br />
/// SETNX is short for "SET if Not eXists".<br /><br />
/// <br />
/// 如果键值不存在,则设置该键值,在此情况下与 SET 指令相似。当键值已经存在时,不执行任何操作。<br /><br />
/// <br />
/// Document link: https://redis.io/commands/setnx <br />
/// Available since 1.0.0.
/// </summary>
/// <param name="key">Key</param>
/// <param name="value">Value</param>
/// <typeparam name="T"></typeparam>
/// <returns>Set result, specifically: 1 is if the key was set; 0 is if the key was not set.</returns>
public bool SetNx<T>(string key, T value) => Call("SETNX".InputKey(key).InputRaw(SerializeRedisValue(value)), rt => rt.ThrowOrValue<bool>());
/// <summary>
/// SETRANGE command (A Synchronized Version) <br /><br />
/// <br />
/// Overwrites part of the string stored at key, starting at the specified offset, for the entire length of value. If the offset is larger than the current length of the string at key, the string is padded with zero-bytes to make offset fit. Non-existing keys are considered as empty strings, so this command will make sure it holds a string large enough to be able to set value at offset.<br /><br />
/// <br />
/// 从给定的偏移量开始覆盖键所对应的字符串值。如果偏移量大于值的长度,则为该字符串填充零字节(zero-bytes)以满足偏移量的要求。若键值不存在则视作空字符串值。故本指令将确保有足够长度的字符串以适应偏移量的要求。<br /><br />
/// <br />
/// Document link: https://redis.io/commands/setrange <br />
/// Available since 2.2.0.
/// </summary>
/// <param name="key">Key</param>
/// <param name="offset">Offset value</param>
/// <param name="value">The value to be filled.</param>
/// <typeparam name="T"></typeparam>
/// <returns>The length of the string after it was modified by the command.</returns>
public long SetRange<T>(string key, long offset, T value) => Call("SETRANGE".InputKey(key, offset).InputRaw(SerializeRedisValue(value)), rt => rt.ThrowOrValue<long>());
//STRALGO LCS algo-specific-argument [algo-specific-argument ...]
/// <summary>
/// STRLRN command (A Synchronized Version) <br /><br />
/// <br />
/// Returns the length of the string value stored at key. An error is returned when key holds a non-string value.<br /><br />
/// <br />
/// 返回键对应值字符串的长度。当该键对应的值不是字符串,则返回错误。<br /><br />
/// <br />
/// Document link: https://redis.io/commands/strlen <br />
/// Available since 2.2.0.
/// </summary>
/// <param name="key">Key</param>
/// <returns>The length of the string at key, or 0 when key does not exist.</returns>
public long StrLen(string key) => Call("STRLEN".InputKey(key), rt => rt.ThrowOrValue<long>());
}
} | 59.255833 | 409 | 0.564836 | [
"MIT"
] | tomatopunk/FreeRedis | src/FreeRedis/RedisClient/Strings.cs | 79,401 | C# |
/**
* Copyright (c) 2001-2018 Mathew A. Nelson and Robocode contributors
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* https://robocode.sourceforge.io/license/epl-v10.html
*/
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by jni4net. See http://jni4net.sourceforge.net/
// Runtime Version:2.0.50727.8669
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace net.sf.robocode.peer {
#region Component Designer generated code
[global::net.sf.jni4net.attributes.JavaInterfaceAttribute()]
public partial interface IRobotPeer {
[global::net.sf.jni4net.attributes.JavaMethodAttribute("()V")]
void drainEnergy();
[global::net.sf.jni4net.attributes.JavaMethodAttribute("(Lnet/sf/robocode/peer/BadBehavior;)V")]
void punishBadBehavior(global::net.sf.robocode.peer.BadBehavior par0);
[global::net.sf.jni4net.attributes.JavaMethodAttribute("(Z)V")]
void setRunning(bool par0);
[global::net.sf.jni4net.attributes.JavaMethodAttribute("()Z")]
bool isRunning();
[global::net.sf.jni4net.attributes.JavaMethodAttribute("(Lnet/sf/robocode/peer/ExecCommands;)Lnet/sf/robocode/peer/ExecResults;")]
global::java.lang.Object waitForBattleEndImpl(global::java.lang.Object par0);
[global::net.sf.jni4net.attributes.JavaMethodAttribute("(Lnet/sf/robocode/peer/ExecCommands;)Lnet/sf/robocode/peer/ExecResults;")]
global::java.lang.Object executeImpl(global::java.lang.Object par0);
[global::net.sf.jni4net.attributes.JavaMethodAttribute("(Ljava/nio/ByteBuffer;)V")]
void setupBuffer(global::java.nio.ByteBuffer par0);
[global::net.sf.jni4net.attributes.JavaMethodAttribute("()V")]
void executeImplSerial();
[global::net.sf.jni4net.attributes.JavaMethodAttribute("()V")]
void waitForBattleEndImplSerial();
[global::net.sf.jni4net.attributes.JavaMethodAttribute("()V")]
void setupThread();
}
#endregion
#region Component Designer generated code
public partial class IRobotPeer_ {
public static global::java.lang.Class _class {
get {
return global::net.sf.robocode.peer.@__IRobotPeer.staticClass;
}
}
}
#endregion
#region Component Designer generated code
[global::net.sf.jni4net.attributes.JavaProxyAttribute(typeof(global::net.sf.robocode.peer.IRobotPeer), typeof(global::net.sf.robocode.peer.IRobotPeer_))]
[global::net.sf.jni4net.attributes.ClrWrapperAttribute(typeof(global::net.sf.robocode.peer.IRobotPeer), typeof(global::net.sf.robocode.peer.IRobotPeer_))]
internal sealed partial class @__IRobotPeer : global::java.lang.Object, global::net.sf.robocode.peer.IRobotPeer {
internal new static global::java.lang.Class staticClass;
internal static global::net.sf.jni4net.jni.MethodId j4n_drainEnergy0;
internal static global::net.sf.jni4net.jni.MethodId j4n_punishBadBehavior1;
internal static global::net.sf.jni4net.jni.MethodId j4n_setRunning2;
internal static global::net.sf.jni4net.jni.MethodId j4n_isRunning3;
internal static global::net.sf.jni4net.jni.MethodId j4n_waitForBattleEndImpl4;
internal static global::net.sf.jni4net.jni.MethodId j4n_executeImpl5;
internal static global::net.sf.jni4net.jni.MethodId j4n_setupBuffer6;
internal static global::net.sf.jni4net.jni.MethodId j4n_executeImplSerial7;
internal static global::net.sf.jni4net.jni.MethodId j4n_waitForBattleEndImplSerial8;
internal static global::net.sf.jni4net.jni.MethodId j4n_setupThread9;
private @__IRobotPeer(global::net.sf.jni4net.jni.JNIEnv @__env) :
base(@__env) {
}
private static void InitJNI(global::net.sf.jni4net.jni.JNIEnv @__env, java.lang.Class @__class) {
global::net.sf.robocode.peer.@__IRobotPeer.staticClass = @__class;
global::net.sf.robocode.peer.@__IRobotPeer.j4n_drainEnergy0 = @__env.GetMethodID(global::net.sf.robocode.peer.@__IRobotPeer.staticClass, "drainEnergy", "()V");
global::net.sf.robocode.peer.@__IRobotPeer.j4n_punishBadBehavior1 = @__env.GetMethodID(global::net.sf.robocode.peer.@__IRobotPeer.staticClass, "punishBadBehavior", "(Lnet/sf/robocode/peer/BadBehavior;)V");
global::net.sf.robocode.peer.@__IRobotPeer.j4n_setRunning2 = @__env.GetMethodID(global::net.sf.robocode.peer.@__IRobotPeer.staticClass, "setRunning", "(Z)V");
global::net.sf.robocode.peer.@__IRobotPeer.j4n_isRunning3 = @__env.GetMethodID(global::net.sf.robocode.peer.@__IRobotPeer.staticClass, "isRunning", "()Z");
global::net.sf.robocode.peer.@__IRobotPeer.j4n_waitForBattleEndImpl4 = @__env.GetMethodID(global::net.sf.robocode.peer.@__IRobotPeer.staticClass, "waitForBattleEndImpl", "(Lnet/sf/robocode/peer/ExecCommands;)Lnet/sf/robocode/peer/ExecResults;");
global::net.sf.robocode.peer.@__IRobotPeer.j4n_executeImpl5 = @__env.GetMethodID(global::net.sf.robocode.peer.@__IRobotPeer.staticClass, "executeImpl", "(Lnet/sf/robocode/peer/ExecCommands;)Lnet/sf/robocode/peer/ExecResults;");
global::net.sf.robocode.peer.@__IRobotPeer.j4n_setupBuffer6 = @__env.GetMethodID(global::net.sf.robocode.peer.@__IRobotPeer.staticClass, "setupBuffer", "(Ljava/nio/ByteBuffer;)V");
global::net.sf.robocode.peer.@__IRobotPeer.j4n_executeImplSerial7 = @__env.GetMethodID(global::net.sf.robocode.peer.@__IRobotPeer.staticClass, "executeImplSerial", "()V");
global::net.sf.robocode.peer.@__IRobotPeer.j4n_waitForBattleEndImplSerial8 = @__env.GetMethodID(global::net.sf.robocode.peer.@__IRobotPeer.staticClass, "waitForBattleEndImplSerial", "()V");
global::net.sf.robocode.peer.@__IRobotPeer.j4n_setupThread9 = @__env.GetMethodID(global::net.sf.robocode.peer.@__IRobotPeer.staticClass, "setupThread", "()V");
}
public void drainEnergy() {
global::net.sf.jni4net.jni.JNIEnv @__env = this.Env;
using(new global::net.sf.jni4net.jni.LocalFrame(@__env, 10)){
@__env.CallVoidMethod(this, global::net.sf.robocode.peer.@__IRobotPeer.j4n_drainEnergy0);
}
}
public void punishBadBehavior(global::net.sf.robocode.peer.BadBehavior par0) {
global::net.sf.jni4net.jni.JNIEnv @__env = this.Env;
using(new global::net.sf.jni4net.jni.LocalFrame(@__env, 12)){
@__env.CallVoidMethod(this, global::net.sf.robocode.peer.@__IRobotPeer.j4n_punishBadBehavior1, global::net.sf.jni4net.utils.Convertor.ParStrongCp2J(par0));
}
}
public void setRunning(bool par0) {
global::net.sf.jni4net.jni.JNIEnv @__env = this.Env;
using(new global::net.sf.jni4net.jni.LocalFrame(@__env, 12)){
@__env.CallVoidMethod(this, global::net.sf.robocode.peer.@__IRobotPeer.j4n_setRunning2, global::net.sf.jni4net.utils.Convertor.ParPrimC2J(par0));
}
}
public bool isRunning() {
global::net.sf.jni4net.jni.JNIEnv @__env = this.Env;
using(new global::net.sf.jni4net.jni.LocalFrame(@__env, 10)){
return ((bool)(@__env.CallBooleanMethod(this, global::net.sf.robocode.peer.@__IRobotPeer.j4n_isRunning3)));
}
}
public global::java.lang.Object waitForBattleEndImpl(global::java.lang.Object par0) {
global::net.sf.jni4net.jni.JNIEnv @__env = this.Env;
using(new global::net.sf.jni4net.jni.LocalFrame(@__env, 12)){
return global::net.sf.jni4net.utils.Convertor.StrongJ2Cp<global::java.lang.Object>(@__env, @__env.CallObjectMethodPtr(this, global::net.sf.robocode.peer.@__IRobotPeer.j4n_waitForBattleEndImpl4, global::net.sf.jni4net.utils.Convertor.ParStrongCp2J(par0)));
}
}
public global::java.lang.Object executeImpl(global::java.lang.Object par0) {
global::net.sf.jni4net.jni.JNIEnv @__env = this.Env;
using(new global::net.sf.jni4net.jni.LocalFrame(@__env, 12)){
return global::net.sf.jni4net.utils.Convertor.StrongJ2Cp<global::java.lang.Object>(@__env, @__env.CallObjectMethodPtr(this, global::net.sf.robocode.peer.@__IRobotPeer.j4n_executeImpl5, global::net.sf.jni4net.utils.Convertor.ParStrongCp2J(par0)));
}
}
public void setupBuffer(global::java.nio.ByteBuffer par0) {
global::net.sf.jni4net.jni.JNIEnv @__env = this.Env;
using(new global::net.sf.jni4net.jni.LocalFrame(@__env, 12)){
@__env.CallVoidMethod(this, global::net.sf.robocode.peer.@__IRobotPeer.j4n_setupBuffer6, global::net.sf.jni4net.utils.Convertor.ParStrongCp2J(par0));
}
}
public void executeImplSerial() {
global::net.sf.jni4net.jni.JNIEnv @__env = this.Env;
using(new global::net.sf.jni4net.jni.LocalFrame(@__env, 10)){
@__env.CallVoidMethod(this, global::net.sf.robocode.peer.@__IRobotPeer.j4n_executeImplSerial7);
}
}
public void waitForBattleEndImplSerial() {
global::net.sf.jni4net.jni.JNIEnv @__env = this.Env;
using(new global::net.sf.jni4net.jni.LocalFrame(@__env, 10)){
@__env.CallVoidMethod(this, global::net.sf.robocode.peer.@__IRobotPeer.j4n_waitForBattleEndImplSerial8);
}
}
public void setupThread() {
global::net.sf.jni4net.jni.JNIEnv @__env = this.Env;
using(new global::net.sf.jni4net.jni.LocalFrame(@__env, 10)){
@__env.CallVoidMethod(this, global::net.sf.robocode.peer.@__IRobotPeer.j4n_setupThread9);
}
}
private static global::System.Collections.Generic.List<global::net.sf.jni4net.jni.JNINativeMethod> @__Init(global::net.sf.jni4net.jni.JNIEnv @__env, global::java.lang.Class @__class) {
global::System.Type @__type = typeof(__IRobotPeer);
global::System.Collections.Generic.List<global::net.sf.jni4net.jni.JNINativeMethod> methods = new global::System.Collections.Generic.List<global::net.sf.jni4net.jni.JNINativeMethod>();
methods.Add(global::net.sf.jni4net.jni.JNINativeMethod.Create(@__type, "drainEnergy", "drainEnergy0", "()V"));
methods.Add(global::net.sf.jni4net.jni.JNINativeMethod.Create(@__type, "punishBadBehavior", "punishBadBehavior1", "(Lnet/sf/robocode/peer/BadBehavior;)V"));
methods.Add(global::net.sf.jni4net.jni.JNINativeMethod.Create(@__type, "setRunning", "setRunning2", "(Z)V"));
methods.Add(global::net.sf.jni4net.jni.JNINativeMethod.Create(@__type, "isRunning", "isRunning3", "()Z"));
methods.Add(global::net.sf.jni4net.jni.JNINativeMethod.Create(@__type, "waitForBattleEndImpl", "waitForBattleEndImpl4", "(Lnet/sf/robocode/peer/ExecCommands;)Lnet/sf/robocode/peer/ExecResults;"));
methods.Add(global::net.sf.jni4net.jni.JNINativeMethod.Create(@__type, "executeImpl", "executeImpl5", "(Lnet/sf/robocode/peer/ExecCommands;)Lnet/sf/robocode/peer/ExecResults;"));
methods.Add(global::net.sf.jni4net.jni.JNINativeMethod.Create(@__type, "setupBuffer", "setupBuffer6", "(Ljava/nio/ByteBuffer;)V"));
methods.Add(global::net.sf.jni4net.jni.JNINativeMethod.Create(@__type, "executeImplSerial", "executeImplSerial7", "()V"));
methods.Add(global::net.sf.jni4net.jni.JNINativeMethod.Create(@__type, "waitForBattleEndImplSerial", "waitForBattleEndImplSerial8", "()V"));
methods.Add(global::net.sf.jni4net.jni.JNINativeMethod.Create(@__type, "setupThread", "setupThread9", "()V"));
return methods;
}
private static void drainEnergy0(global::System.IntPtr @__envp, global::net.sf.jni4net.utils.JniLocalHandle @__obj) {
// ()V
// ()V
global::net.sf.jni4net.jni.JNIEnv @__env = global::net.sf.jni4net.jni.JNIEnv.Wrap(@__envp);
try {
global::net.sf.robocode.peer.IRobotPeer @__real = global::net.sf.jni4net.utils.Convertor.FullJ2C<global::net.sf.robocode.peer.IRobotPeer>(@__env, @__obj);
@__real.drainEnergy();
}catch (global::System.Exception __ex){@__env.ThrowExisting(__ex);}
}
private static void punishBadBehavior1(global::System.IntPtr @__envp, global::net.sf.jni4net.utils.JniLocalHandle @__obj, global::net.sf.jni4net.utils.JniLocalHandle par0) {
// (Lnet/sf/robocode/peer/BadBehavior;)V
// (Lnet/sf/robocode/peer/BadBehavior;)V
global::net.sf.jni4net.jni.JNIEnv @__env = global::net.sf.jni4net.jni.JNIEnv.Wrap(@__envp);
try {
global::net.sf.robocode.peer.IRobotPeer @__real = global::net.sf.jni4net.utils.Convertor.FullJ2C<global::net.sf.robocode.peer.IRobotPeer>(@__env, @__obj);
@__real.punishBadBehavior(global::net.sf.jni4net.utils.Convertor.StrongJ2Cp<global::net.sf.robocode.peer.BadBehavior>(@__env, par0));
}catch (global::System.Exception __ex){@__env.ThrowExisting(__ex);}
}
private static void setRunning2(global::System.IntPtr @__envp, global::net.sf.jni4net.utils.JniLocalHandle @__obj, bool par0) {
// (Z)V
// (Z)V
global::net.sf.jni4net.jni.JNIEnv @__env = global::net.sf.jni4net.jni.JNIEnv.Wrap(@__envp);
try {
global::net.sf.robocode.peer.IRobotPeer @__real = global::net.sf.jni4net.utils.Convertor.FullJ2C<global::net.sf.robocode.peer.IRobotPeer>(@__env, @__obj);
@__real.setRunning(par0);
}catch (global::System.Exception __ex){@__env.ThrowExisting(__ex);}
}
private static bool isRunning3(global::System.IntPtr @__envp, global::net.sf.jni4net.utils.JniLocalHandle @__obj) {
// ()Z
// ()Z
global::net.sf.jni4net.jni.JNIEnv @__env = global::net.sf.jni4net.jni.JNIEnv.Wrap(@__envp);
bool @__return = default(bool);
try {
global::net.sf.robocode.peer.IRobotPeer @__real = global::net.sf.jni4net.utils.Convertor.FullJ2C<global::net.sf.robocode.peer.IRobotPeer>(@__env, @__obj);
@__return = ((bool)(@__real.isRunning()));
}catch (global::System.Exception __ex){@__env.ThrowExisting(__ex);}
return @__return;
}
private static global::net.sf.jni4net.utils.JniHandle waitForBattleEndImpl4(global::System.IntPtr @__envp, global::net.sf.jni4net.utils.JniLocalHandle @__obj, global::net.sf.jni4net.utils.JniLocalHandle par0) {
// (Lnet/sf/robocode/peer/ExecCommands;)Lnet/sf/robocode/peer/ExecResults;
// (Ljava/lang/Object;)Ljava/lang/Object;
global::net.sf.jni4net.jni.JNIEnv @__env = global::net.sf.jni4net.jni.JNIEnv.Wrap(@__envp);
global::net.sf.jni4net.utils.JniHandle @__return = default(global::net.sf.jni4net.utils.JniHandle);
try {
global::net.sf.robocode.peer.IRobotPeer @__real = global::net.sf.jni4net.utils.Convertor.FullJ2C<global::net.sf.robocode.peer.IRobotPeer>(@__env, @__obj);
@__return = global::net.sf.jni4net.utils.Convertor.StrongCp2J(@__real.waitForBattleEndImpl(global::net.sf.jni4net.utils.Convertor.StrongJ2Cp<global::java.lang.Object>(@__env, par0)));
}catch (global::System.Exception __ex){@__env.ThrowExisting(__ex);}
return @__return;
}
private static global::net.sf.jni4net.utils.JniHandle executeImpl5(global::System.IntPtr @__envp, global::net.sf.jni4net.utils.JniLocalHandle @__obj, global::net.sf.jni4net.utils.JniLocalHandle par0) {
// (Lnet/sf/robocode/peer/ExecCommands;)Lnet/sf/robocode/peer/ExecResults;
// (Ljava/lang/Object;)Ljava/lang/Object;
global::net.sf.jni4net.jni.JNIEnv @__env = global::net.sf.jni4net.jni.JNIEnv.Wrap(@__envp);
global::net.sf.jni4net.utils.JniHandle @__return = default(global::net.sf.jni4net.utils.JniHandle);
try {
global::net.sf.robocode.peer.IRobotPeer @__real = global::net.sf.jni4net.utils.Convertor.FullJ2C<global::net.sf.robocode.peer.IRobotPeer>(@__env, @__obj);
@__return = global::net.sf.jni4net.utils.Convertor.StrongCp2J(@__real.executeImpl(global::net.sf.jni4net.utils.Convertor.StrongJ2Cp<global::java.lang.Object>(@__env, par0)));
}catch (global::System.Exception __ex){@__env.ThrowExisting(__ex);}
return @__return;
}
private static void setupBuffer6(global::System.IntPtr @__envp, global::net.sf.jni4net.utils.JniLocalHandle @__obj, global::net.sf.jni4net.utils.JniLocalHandle par0) {
// (Ljava/nio/ByteBuffer;)V
// (Ljava/nio/ByteBuffer;)V
global::net.sf.jni4net.jni.JNIEnv @__env = global::net.sf.jni4net.jni.JNIEnv.Wrap(@__envp);
try {
global::net.sf.robocode.peer.IRobotPeer @__real = global::net.sf.jni4net.utils.Convertor.FullJ2C<global::net.sf.robocode.peer.IRobotPeer>(@__env, @__obj);
@__real.setupBuffer(global::net.sf.jni4net.utils.Convertor.StrongJ2Cp<global::java.nio.ByteBuffer>(@__env, par0));
}catch (global::System.Exception __ex){@__env.ThrowExisting(__ex);}
}
private static void executeImplSerial7(global::System.IntPtr @__envp, global::net.sf.jni4net.utils.JniLocalHandle @__obj) {
// ()V
// ()V
global::net.sf.jni4net.jni.JNIEnv @__env = global::net.sf.jni4net.jni.JNIEnv.Wrap(@__envp);
try {
global::net.sf.robocode.peer.IRobotPeer @__real = global::net.sf.jni4net.utils.Convertor.FullJ2C<global::net.sf.robocode.peer.IRobotPeer>(@__env, @__obj);
@__real.executeImplSerial();
}catch (global::System.Exception __ex){@__env.ThrowExisting(__ex);}
}
private static void waitForBattleEndImplSerial8(global::System.IntPtr @__envp, global::net.sf.jni4net.utils.JniLocalHandle @__obj) {
// ()V
// ()V
global::net.sf.jni4net.jni.JNIEnv @__env = global::net.sf.jni4net.jni.JNIEnv.Wrap(@__envp);
try {
global::net.sf.robocode.peer.IRobotPeer @__real = global::net.sf.jni4net.utils.Convertor.FullJ2C<global::net.sf.robocode.peer.IRobotPeer>(@__env, @__obj);
@__real.waitForBattleEndImplSerial();
}catch (global::System.Exception __ex){@__env.ThrowExisting(__ex);}
}
private static void setupThread9(global::System.IntPtr @__envp, global::net.sf.jni4net.utils.JniLocalHandle @__obj) {
// ()V
// ()V
global::net.sf.jni4net.jni.JNIEnv @__env = global::net.sf.jni4net.jni.JNIEnv.Wrap(@__envp);
try {
global::net.sf.robocode.peer.IRobotPeer @__real = global::net.sf.jni4net.utils.Convertor.FullJ2C<global::net.sf.robocode.peer.IRobotPeer>(@__env, @__obj);
@__real.setupThread();
}catch (global::System.Exception __ex){@__env.ThrowExisting(__ex);}
}
new internal sealed class ContructionHelper : global::net.sf.jni4net.utils.IConstructionHelper {
public global::net.sf.jni4net.jni.IJvmProxy CreateProxy(global::net.sf.jni4net.jni.JNIEnv @__env) {
return new global::net.sf.robocode.peer.@__IRobotPeer(@__env);
}
}
}
#endregion
}
| 65.254777 | 268 | 0.649097 | [
"Apache-2.0"
] | DarioRomano/robocode | plugins/dotnet/robocode.dotnet.nhost/src/generated/net/sf/robocode/peer/IRobotPeer.generated.cs | 20,490 | 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 mediapackage-vod-2018-11-07.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.MediaPackageVod.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using ThirdParty.Json.LitJson;
namespace Amazon.MediaPackageVod.Model.Internal.MarshallTransformations
{
/// <summary>
/// DashPackage Marshaller
/// </summary>
public class DashPackageMarshaller : IRequestMarshaller<DashPackage, 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(DashPackage requestObject, JsonMarshallerContext context)
{
if(requestObject.IsSetDashManifests())
{
context.Writer.WritePropertyName("dashManifests");
context.Writer.WriteArrayStart();
foreach(var requestObjectDashManifestsListValue in requestObject.DashManifests)
{
context.Writer.WriteObjectStart();
var marshaller = DashManifestMarshaller.Instance;
marshaller.Marshall(requestObjectDashManifestsListValue, context);
context.Writer.WriteObjectEnd();
}
context.Writer.WriteArrayEnd();
}
if(requestObject.IsSetEncryption())
{
context.Writer.WritePropertyName("encryption");
context.Writer.WriteObjectStart();
var marshaller = DashEncryptionMarshaller.Instance;
marshaller.Marshall(requestObject.Encryption, context);
context.Writer.WriteObjectEnd();
}
if(requestObject.IsSetPeriodTriggers())
{
context.Writer.WritePropertyName("periodTriggers");
context.Writer.WriteArrayStart();
foreach(var requestObjectPeriodTriggersListValue in requestObject.PeriodTriggers)
{
context.Writer.Write(requestObjectPeriodTriggersListValue);
}
context.Writer.WriteArrayEnd();
}
if(requestObject.IsSetSegmentDurationSeconds())
{
context.Writer.WritePropertyName("segmentDurationSeconds");
context.Writer.Write(requestObject.SegmentDurationSeconds);
}
if(requestObject.IsSetSegmentTemplateFormat())
{
context.Writer.WritePropertyName("segmentTemplateFormat");
context.Writer.Write(requestObject.SegmentTemplateFormat);
}
}
/// <summary>
/// Singleton Marshaller.
/// </summary>
public readonly static DashPackageMarshaller Instance = new DashPackageMarshaller();
}
} | 36 | 114 | 0.636006 | [
"Apache-2.0"
] | DetlefGolze/aws-sdk-net | sdk/src/Services/MediaPackageVod/Generated/Model/Internal/MarshallTransformations/DashPackageMarshaller.cs | 3,816 | C# |
using System;
using SFA.DAS.Provider.Events.Api.Types;
namespace SFA.DAS.EmployerPayments.Domain.Models.Payments
{
public class Payment
{
public string Id { get; set; }
public long Ukprn { get; set; }
public long Uln { get; set; }
public string EmployerAccountId { get; set; }
public long? ApprenticeshipId { get; set; }
public int DeliveryPeriodMonth { get; set; }
public int DeliveryPeriodYear { get; set; }
public string CollectionPeriodId { get; set; }
public int CollectionPeriodMonth { get; set; }
public int CollectionPeriodYear { get; set; }
public DateTime EvidenceSubmittedOn { get; set; }
public string EmployerAccountVersion { get; set; }
public string ApprenticeshipVersion { get; set; }
public FundingSource FundingSource { get; set; }
public TransactionType TransactionType { get; set; }
public decimal Amount { get; set; }
public long? StandardCode { get; set; }
public int? FrameworkCode { get; set; }
public int? ProgrammeType { get; set; }
public int? PathwayCode { get; set; }
public ContractType ContractType { get; set; }
}
}
| 39.677419 | 60 | 0.636585 | [
"MIT"
] | SkillsFundingAgency/das-employer-payment | src/SFA.DAS.EmployerPayments.Domain/Models/Payments/Payment.cs | 1,232 | C# |
/* Copyright 2010-2012 10gen Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MongoDB.Bson;
using MongoDB.Bson.IO;
using MongoDB.Bson.Serialization;
using MongoDB.Driver;
using MongoDB.Driver.Wrappers;
namespace MongoDB.Driver.Builders
{
/// <summary>
/// A builder for the options used when creating a collection.
/// </summary>
public static class CollectionOptions
{
// public static properties
/// <summary>
/// Gets a null value with a type of IMongoCollectionOptions.
/// </summary>
public static IMongoCollectionOptions Null
{
get { return null; }
}
// public static methods
/// <summary>
/// Sets whether to automatically create an index on the _id element.
/// </summary>
/// <param name="value">Whether to automatically create an index on the _id element.</param>
/// <returns>The builder (so method calls can be chained).</returns>
public static CollectionOptionsBuilder SetAutoIndexId(bool value)
{
return new CollectionOptionsBuilder().SetAutoIndexId(value);
}
/// <summary>
/// Sets whether the collection is capped.
/// </summary>
/// <param name="value">Whether the collection is capped.</param>
/// <returns>The builder (so method calls can be chained).</returns>
public static CollectionOptionsBuilder SetCapped(bool value)
{
return new CollectionOptionsBuilder().SetCapped(value);
}
/// <summary>
/// Sets the max number of documents in a capped collection.
/// </summary>
/// <param name="value">The max number of documents.</param>
/// <returns>The builder (so method calls can be chained).</returns>
public static CollectionOptionsBuilder SetMaxDocuments(long value)
{
return new CollectionOptionsBuilder().SetMaxDocuments(value);
}
/// <summary>
/// Sets the max size of a capped collection.
/// </summary>
/// <param name="value">The max size.</param>
/// <returns>The builder (so method calls can be chained).</returns>
public static CollectionOptionsBuilder SetMaxSize(long value)
{
return new CollectionOptionsBuilder().SetMaxSize(value);
}
}
/// <summary>
/// A builder for the options used when creating a collection.
/// </summary>
[Serializable]
public class CollectionOptionsBuilder : BuilderBase, IMongoCollectionOptions
{
// private fields
private BsonDocument _document;
// constructors
/// <summary>
/// Initializes a new instance of the CollectionOptionsBuilder class.
/// </summary>
public CollectionOptionsBuilder()
{
_document = new BsonDocument();
}
// public methods
/// <summary>
/// Sets whether to automatically create an index on the _id element.
/// </summary>
/// <param name="value">Whether to automatically create an index on the _id element.</param>
/// <returns>The builder (so method calls can be chained).</returns>
public CollectionOptionsBuilder SetAutoIndexId(bool value)
{
if (value)
{
_document["autoIndexId"] = value;
}
else
{
_document.Remove("autoIndexId");
}
return this;
}
/// <summary>
/// Sets whether the collection is capped.
/// </summary>
/// <param name="value">Whether the collection is capped.</param>
/// <returns>The builder (so method calls can be chained).</returns>
public CollectionOptionsBuilder SetCapped(bool value)
{
if (value)
{
_document["capped"] = value;
}
else
{
_document.Remove("capped");
}
return this;
}
/// <summary>
/// Sets the max number of documents in a capped collection.
/// </summary>
/// <param name="value">The max number of documents.</param>
/// <returns>The builder (so method calls can be chained).</returns>
public CollectionOptionsBuilder SetMaxDocuments(long value)
{
_document["max"] = value;
return this;
}
/// <summary>
/// Sets the max size of a capped collection.
/// </summary>
/// <param name="value">The max size.</param>
/// <returns>The builder (so method calls can be chained).</returns>
public CollectionOptionsBuilder SetMaxSize(long value)
{
_document["size"] = value;
return this;
}
/// <summary>
/// Returns the result of the builder as a BsonDocument.
/// </summary>
/// <returns>A BsonDocument.</returns>
public override BsonDocument ToBsonDocument()
{
return _document;
}
// protected methods
/// <summary>
/// Serializes the result of the builder to a BsonWriter.
/// </summary>
/// <param name="bsonWriter">The writer.</param>
/// <param name="nominalType">The nominal type.</param>
/// <param name="options">The serialization options.</param>
protected override void Serialize(BsonWriter bsonWriter, Type nominalType, IBsonSerializationOptions options)
{
((IBsonSerializable)_document).Serialize(bsonWriter, nominalType, options);
}
}
}
| 34.228261 | 117 | 0.595586 | [
"Apache-2.0"
] | nilayparikh/mongo-csharp-driver | Driver/Builders/CollectionOptionsBuilder.cs | 6,300 | C# |
using System;
using System.Threading.Tasks;
using NBitcoin;
namespace Core.Outputs
{
public interface ISpentOutputService
{
Task SaveSpentOutputs(Guid transactionId, Transaction transaction);
Task RemoveSpentOutputs(Transaction transaction);
}
}
| 19.785714 | 75 | 0.743682 | [
"MIT"
] | LykkeCity/bitcoinservice | src/Core/Outputs/ISpentOutputService.cs | 279 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ImageTypers
{
class CommandLineController
{
private Arguments _arguments;
public CommandLineController(string[] args)
{
this.init_parse(args); // init & parse args
}
/// <summary>
/// Init command-line arguments
/// </summary>
/// <param name="args"></param>
private void init_parse(string[] args)
{
// init dict with key, value pair
var d = new Dictionary<string, string>();
for (int i = 0; i < args.Length; i += 2)
{
if (i + 1 == args.Length)
{
break;
}
d.Add(args[i].Replace("\"", "").Trim(), args[i + 1].Replace("\"", "").Trim());
}
// check our dicts length first
if (d.Count == 0)
{
throw new Exception("no arguments given. Check README.md file for examples on how to use it");
}
// not that we have the dict, check for what we're looking for
// init the Arguments obj
// ------------------------------------------------------------
this._arguments = new Arguments(); // init new obj
// check what we're looking for
// ----------------------------
if (d.ContainsKey("-t"))
{
this._arguments.set_token(d["-t"]); // we have token
}
else
{
if (!d.ContainsKey("-u"))
{
throw new Exception("-u arguments is required or use -t (token)");
}
if (!d.ContainsKey("-p"))
{
throw new Exception("-p arguments is required or use -t (token)");
}
this._arguments.set_username(d["-u"]);
this._arguments.set_password(d["-p"]);
}
if (!d.ContainsKey("-m"))
{
throw new Exception("-m arguments is required");
}
this._arguments.set_mode(d["-m"]);
// init the optional ones
// ----------------------
if (d.ContainsKey("-i"))
{
this._arguments.set_captcha_file((d["-i"]));
}
if (d.ContainsKey("-o"))
{
this._arguments.set_output_file((d["-o"]));
}
if (d.ContainsKey("-pageurl"))
{
this._arguments.set_page_url((d["-pageurl"]));
}
if (d.ContainsKey("-sitekey"))
{
this._arguments.set_site_key((d["-sitekey"]));
}
if (d.ContainsKey("-captchaid"))
{
this._arguments.set_captcha_id((d["-captchaid"]));
}
if (d.ContainsKey("-case"))
{
bool b = false;
string cc = d["-case"];
if (cc.Equals("1"))
b = true; // make it true
this._arguments.set_case_sensitive(b);
}
if (d.ContainsKey("-proxy"))
{
this._arguments.set_proxy(d["-proxy"]);
}
}
/// <summary>
/// Run method
/// </summary>
public void run()
{
try
{
this._run();
}
catch (Exception ex)
{
this.save_error(ex.Message); // save error to error text file
throw; // re-throw
}
}
/// <summary>
/// Private _run method
/// </summary>
private void _run()
{
var a = this._arguments; // for easier use local
ImageTypersAPI i;
var token = a.get_token();
if (!string.IsNullOrWhiteSpace(token))
{
i = new ImageTypersAPI(token);
}
else
{
i = new ImageTypersAPI("");
i.set_user_and_password(a.get_username(), a.get_password());
}
switch (a.get_mode())
{
case "1":
// solve normal captcha
// -------------------------
/*string captcha_file = a.get_captcha_file();
if (string.IsNullOrWhiteSpace(captcha_file))
throw new Exception("Invalid captcha file");
bool cs = a.is_case_sensitive();
string resp = i.solve_captcha(captcha_file, cs);
this.show_output(resp);*/
break;
case "2":
// submit recapthca
// ----------------------------------------------------
string page_url = a.get_page_url();
if (string.IsNullOrWhiteSpace(page_url))
throw new Exception("Invalid recaptcha pageurl");
string site_key = a.get_site_key();
if (string.IsNullOrWhiteSpace(site_key))
throw new Exception("Invalid recaptcha sitekey");
string proxy = a.get_proxy();
string captcha_id = "";
Dictionary<string, string> d = new Dictionary<string, string>();
d.Add("page_url", page_url);
d.Add("sitekey", site_key);
// v3
if (!string.IsNullOrWhiteSpace(a.get_type())) d.Add("type", a.get_type());
if (!string.IsNullOrWhiteSpace(a.get_v3_action())) d.Add("v3_action", a.get_v3_action());
if (!string.IsNullOrWhiteSpace(a.get_v3_score())) d.Add("v3_min_score", a.get_v3_score());
// user agent
if (!string.IsNullOrWhiteSpace(a.get_user_agent())) d.Add("user_agent", a.get_user_agent());
// check proxy
if (!string.IsNullOrWhiteSpace(proxy)) d.Add("proxy", proxy);
captcha_id = i.submit_recaptcha(d);
this.show_output(captcha_id);
break;
case "3":
// retrieve captcha
string recaptcha_id = a.get_captcha_id();
if (string.IsNullOrWhiteSpace(recaptcha_id))
throw new Exception("recaptcha captchaid is invalid");
string recaptcha_response = i.retrieve_captcha(recaptcha_id); // get recaptcha response
this.show_output(recaptcha_response); // show response
break;
case "4":
// get balance
// -------------------------
string balance = i.account_balance();
this.show_output(balance); // show balance
break;
case "5":
// set bad captcha
// -------------------------
string bad_id = a.get_captcha_id();
if (string.IsNullOrWhiteSpace(bad_id))
throw new Exception("captchaid is invalid");
string response = i.set_captcha_bad(bad_id); // set it bad
this.show_output(response); // show response
break;
case "6":
// get proxy status
string was_used_id = a.get_captcha_id();
if (string.IsNullOrWhiteSpace(was_used_id))
throw new Exception("captchaid is invalid");
string rr = i.was_proxy_used(was_used_id); // set it bad
this.show_output(rr); // show response
break;
}
}
#region misc
/// <summary>
/// Save error to file
/// </summary>
/// <param name="error"></param>
private void save_error(string error)
{
this.save_text("error.txt", error);
}
/// <summary>
/// Show output and save to file if given
/// </summary>
/// <param name="text"></param>
private void show_output(string text)
{
Console.WriteLine(text); // print to screen
if (!string.IsNullOrWhiteSpace(this._arguments.get_output_file())) // if outputfile arg given
{
this.save_text(this._arguments.get_output_file(), text); // save to file
}
}
/// <summary>
/// Save text to file
/// </summary>
/// <param name="filename"></param>
/// <param name="text"></param>
private void save_text(string filename, string text)
{
System.IO.File.WriteAllText(filename, text);
}
#endregion
}
}
| 37.335968 | 113 | 0.421978 | [
"MIT"
] | imagetyperz-api/imagetyperz-api-csharp | source/cli/CommandLineController.cs | 9,448 | 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.IO;
using System.Threading;
using System.Threading.Tasks;
namespace System.Net.Security
{
internal interface IReadWriteAdapter
{
ValueTask<int> ReadAsync(Memory<byte> buffer);
ValueTask WriteAsync(byte[] buffer, int offset, int count);
Task WaitAsync(TaskCompletionSource<bool> waiter);
CancellationToken CancellationToken { get; }
public async ValueTask<int> ReadAllAsync(Memory<byte> buffer)
{
int length = buffer.Length;
do
{
int bytes = await ReadAsync(buffer).ConfigureAwait(false);
if (bytes == 0)
{
if (!buffer.IsEmpty)
{
throw new IOException(SR.net_io_eof);
}
break;
}
buffer = buffer.Slice(bytes);
}
while (!buffer.IsEmpty);
return length;
}
}
internal readonly struct AsyncReadWriteAdapter : IReadWriteAdapter
{
private readonly Stream _stream;
public AsyncReadWriteAdapter(Stream stream, CancellationToken cancellationToken)
{
_stream = stream;
CancellationToken = cancellationToken;
}
public ValueTask<int> ReadAsync(Memory<byte> buffer) =>
_stream.ReadAsync(buffer, CancellationToken);
public ValueTask WriteAsync(byte[] buffer, int offset, int count) =>
_stream.WriteAsync(new ReadOnlyMemory<byte>(buffer, offset, count), CancellationToken);
public Task WaitAsync(TaskCompletionSource<bool> waiter) => waiter.Task;
public CancellationToken CancellationToken { get; }
}
internal readonly struct SyncReadWriteAdapter : IReadWriteAdapter
{
private readonly Stream _stream;
public SyncReadWriteAdapter(Stream stream) => _stream = stream;
public ValueTask<int> ReadAsync(Memory<byte> buffer) =>
new ValueTask<int>(_stream.Read(buffer.Span));
public ValueTask WriteAsync(byte[] buffer, int offset, int count)
{
_stream.Write(buffer, offset, count);
return default;
}
public Task WaitAsync(TaskCompletionSource<bool> waiter)
{
waiter.Task.GetAwaiter().GetResult();
return Task.CompletedTask;
}
public CancellationToken CancellationToken => default;
}
}
| 29.977778 | 99 | 0.60934 | [
"MIT"
] | CometstarMH/runtime | src/libraries/System.Net.Security/src/System/Net/Security/ReadWriteAdapter.cs | 2,698 | C# |
using AspnetRunBasics.Extensions;
using AspnetRunBasics.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
namespace AspnetRunBasics.Services
{
public class BasketService : IBasketService
{
private readonly HttpClient _client;
public BasketService(HttpClient client)
{
_client = client ?? throw new ArgumentNullException(nameof(client));
}
public async Task CheckoutBasket(BasketCheckoutModel model)
{
var response = await _client.PostAsJson($"/Basket/Checkout", model);
if (!response.IsSuccessStatusCode)
throw new Exception("Something went wrong when calling api.");
}
public async Task<BasketModel> GetBasket(string userName)
{
var response = await _client.GetAsync($"/Basket/{userName}");
return await response.ReadContentAs<BasketModel>();
}
public async Task<BasketModel> UpdateBasket(BasketModel model)
{
var response = await _client.PostAsJson($"/Basket", model);
if (response.IsSuccessStatusCode)
return await response.ReadContentAs<BasketModel>();
throw new Exception("Something went wrong when calling api.");
}
}
}
| 32.238095 | 80 | 0.65288 | [
"MIT"
] | Francois-Labarre/AspnetMicroservices | src/WebApps/AspnetRunBasics/Services/BasketService.cs | 1,356 | C# |
using System.Diagnostics;
namespace DP.Domain.Samples.Visitor
{
/// <summary>
/// 該項商品數量10以上八折優惠
/// </summary>
public class VisitorDiscount4Count : Visitor
{
public override void Visit(IElement elm)
{
if(elm.Amount>=10)
{
elm.TotalPrice = elm.UnitPrice * elm.Amount * 0.8M;
Trace.WriteLine($"(折扣!){elm.Name}: 單價${elm.UnitPrice}, 數量{elm.Amount}, 20% off, 總價格={elm.TotalPrice} ");
}
else
{
elm.TotalPrice = elm.UnitPrice * elm.Amount;
Trace.WriteLine($"{elm.Name}: 單價${elm.UnitPrice}, 數量{elm.Amount}, 總價格={elm.TotalPrice} ");
}
}
}
} | 29.875 | 120 | 0.520223 | [
"MIT"
] | KarateJB/DesignPattern.Sample | CSharp/DP.Domain/Samples/Visitor/VisitorDiscount4Amount.cs | 773 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
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;
namespace Drawing
{
/// <summary>
/// LineJoins.xaml 的交互逻辑
/// </summary>
public partial class LineJoins : Window
{
public LineJoins()
{
InitializeComponent();
}
}
}
| 20.607143 | 43 | 0.69844 | [
"MIT"
] | D15190304050/LearningWpf | Drawing/DrawingShapes/LineJoins.xaml.cs | 589 | C# |
// *****************************************************************************
//
// © Component Factory Pty Ltd 2012. All rights reserved.
// The software and associated documentation supplied hereunder are the
// proprietary information of Component Factory Pty Ltd, PO Box 1504,
// Glen Waverley, Vic 3150, Australia and are supplied subject to licence terms.
//
// Version 4.6.0.0 www.ComponentFactory.com
// *****************************************************************************
using System;
using System.Collections.Generic;
using System.Windows.Forms;
namespace KryptonNumericUpDownExamples
{
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());
}
}
}
| 31.645161 | 81 | 0.553517 | [
"BSD-3-Clause"
] | BMBH/Krypton | Source/Krypton Toolkit Examples/KryptonNumericUpDown Examples/Program.cs | 984 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace Graph
{
public class Node<T>
{
public int ID;
public T Item;
public List<Edge<T>> Edges;
#region A* helpers
public float h;
public float g;
public float f;
public Node<T> Parent;
#endregion
public Node(int ID, T item)
{
this.Item = item;
this.ID = ID;
Edges = new List<Edge<T>>();
}
public void CalculateF()
{
this.f = g + h;
}
public override bool Equals(object obj)
{
return obj is Node<T> node &&
ID == node.ID;
}
}
}
| 17.340909 | 47 | 0.471822 | [
"MIT"
] | godisntheradio/TEOGA | TEOGA/Assets/Graph/Node.cs | 765 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace CinemaOnline.Areas.Admin.Models
{
public class MovieCalendarGet
{
public Guid LFilmId { get; set; }
public Guid LDayOfWeekId { get; set; }
public Guid LMovieDisplayTypeId { get; set; }
public DateTime LStartWeek { get; set; }
public Guid LCinemaRoomId { get; set; }
}
} | 22.05 | 54 | 0.630385 | [
"Unlicense",
"MIT"
] | Mokadev-vn/thuantv | .fr-Kh2sOT/Source/CinemaOnline/Areas/Admin/Models/MovieCalendarGet.cs | 443 | C# |
using System;
using System.Linq;
using System.Text;
using System.Runtime.Serialization;
namespace WowDotNetAPI.Models
{
[DataContract]
public enum RealmType
{
[EnumMember(Value = "pve")]
PVE,
[EnumMember(Value = "pvp")]
PVP,
[EnumMember(Value = "rp")]
RP,
[EnumMember(Value = "rppvp")]
RPPVP
}
//TODO: sort out issue with enum member n/a . It seems there's an issue with the forward slash and how we serialize and the try to parse it
//[DataContract]
//public enum RealmPopulation
//{
// [EnumMember(Value = "low")]
// LOW,
// [EnumMember(Value = "medium")]
// MEDIUM,
// [EnumMember(Value = "high")]
// HIGH,
// [EnumMember(Value = "n/a")]
// NA
//}
[DataContract]
public class Realm
{
[DataMember(Name = "type")]
private string type { get; set; }
[DataMember(Name = "queue")]
public bool Queue { get; set; }
[DataMember(Name = "status")]
public bool Status { get; set; }
[DataMember(Name = "population")]
public string population { get; set; }
[DataMember(Name = "name")]
public string Name { get; set; }
[DataMember(Name = "slug")]
public string Slug { get; set; }
public RealmType Type { get { return (RealmType)Enum.Parse(typeof(RealmType), type, true); } }
//See enum TODO comments
//public RealmPopulation Population { get { return (RealmPopulation)Enum.Parse(typeof(RealmPopulation), population, true); } }
}
}
| 25.888889 | 143 | 0.563458 | [
"MIT",
"Unlicense"
] | ThorwaldOdin/WowDotNetAPI-from-Briandek | Explorers/Models/Realm.cs | 1,633 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
namespace ws1
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
}
| 28.26 | 107 | 0.630573 | [
"MIT"
] | yaras/DockerExperiments | ws1/Startup.cs | 1,413 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.