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.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using AElf.RPC;
using Anemonis.AspNetCore.JsonRpc;
namespace AElf.Monitor
{
[Path("/monitor")]
public class AkkaService :IJsonRpcService
{
[JsonRpcMethod("AkkaState")]
public Task<List<MemberInfo>> ClusterState()
{
return Task.FromResult(AkkaClusterState.MemberInfos.Values.ToList());
}
}
} | 24.166667 | 81 | 0.68046 | [
"MIT"
] | Git-zyn-Hub/AElf | AElf.Monitor/AkkaService.cs | 437 | C# |
// *** WARNING: this file was generated by the Pulumi SDK Generator. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.AzureNative.Network.V20191201.Outputs
{
/// <summary>
/// List of properties of the device.
/// </summary>
[OutputType]
public sealed class DevicePropertiesResponse
{
/// <summary>
/// Model of the device.
/// </summary>
public readonly string? DeviceModel;
/// <summary>
/// Name of the device Vendor.
/// </summary>
public readonly string? DeviceVendor;
/// <summary>
/// Link speed.
/// </summary>
public readonly int? LinkSpeedInMbps;
[OutputConstructor]
private DevicePropertiesResponse(
string? deviceModel,
string? deviceVendor,
int? linkSpeedInMbps)
{
DeviceModel = deviceModel;
DeviceVendor = deviceVendor;
LinkSpeedInMbps = linkSpeedInMbps;
}
}
}
| 26.195652 | 81 | 0.60249 | [
"Apache-2.0"
] | polivbr/pulumi-azure-native | sdk/dotnet/Network/V20191201/Outputs/DevicePropertiesResponse.cs | 1,205 | C# |
using HelloEntityFramework.DataAccess;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Console;
using System;
using System.Collections.Generic;
using System.Linq;
namespace HelloEntityFramework
{
class Program : IMovieRepo
{
// EF database-first approach steps:
//
// 1. have startup project, and data access library project.
// 2. reference data access from startup project.
// 3. add NuGet packages to the startup project:
// - Microsoft.EntityFrameworkCore.Tools
// - Microsoft.EntityFrameworkCore.SqlServer
// and to the data access project:
// - Microsoft.EntityFrameworkCore.SqlServer
// 4. open Package Manager Console in VS
// ( View -> Other Windows -> Package Manager Console
// 5. run command (your solution needs to be able to compile) (one-line):
// Scaffold-DbContext "<your-connection-string>"
// Microsoft.EntityFrameworkCore.SqlServer
// -Project <name-of-data-project> -Force
// (alternate 4/5. run in git bash/terminal:
// dotnet ef dbcontext scaffold "<your-connection-string>"
// Microsoft.EntityFrameworkCore.SqlServer
// --project <name-of-data-project> -Force
// 6. delete the OnConfiguring override in the DbContext, to prevent
// committing your connection string to git.
// (7. any time we change the database (add a new column, etc.), go to step 4.)
// by default, the scaffolding will configure the models in OnModelCreating
// with the fluent API. this is the right way to do it - strongest separation
// of concerns, more flexibility.
// if we scaffold with option "-DataAnnotations" we'll put the configuration
// on the Movie and Genre classes themselves with attributes.
// third "way to configure" is convention-based
static void Main(string[] args)
{
public static readonly LoggerFactory AppLoggerFactory =
#pragma warning disable CS0618 // Type or member is obsolete
new LoggerFactory(new[] { new ConsoleLoggerProvider((_,___) => true, true) });
#pragma warning restore CS0618 // Type or member is obsolete
var optionsBuilder = new DbContextOptionsBuilder<MoviesContext>();
optionsBuilder.UseSqlServer(SecretConfiguration.ConnectionString);
optionsBuilder.UseLoggerFactory(AppLoggerFactory);
var options = optionsBuilder.Options;
using (var dbContext = new MoviesContext(options))
{
// lots of complex setup... here is where the payoff begins
PrintMovies(dbContext);
Console.WriteLine();
AddMovie(dbContext);
PrintMovies(dbContext);
Console.WriteLine();
UpdateMovies(dbContext);
PrintMovies(dbContext);
Console.WriteLine();
DeleteAMovie(dbContext);
PrintMovies(dbContext);
Console.WriteLine();
}
Console.ReadLine();
}
static void DeleteAMovie(MoviesContext dbContext)
{
var movieToDelete = dbContext.Movie
.OrderByDescending(x => x.ReleaseDate)
.First();
dbContext.Movie.Remove(movieToDelete);
dbContext.SaveChanges();
}
static void UpdateMovies(MoviesContext dbContext)
{
foreach (var movie in dbContext.Movie)
{
movie.ReleaseDate = movie.ReleaseDate.AddYears(1);
}
// that loop only runs in memory - changes are written to the DB
// with savechanges
// the objects that we get out of the DbSets are "tracked" by the DbContext.
// basically the DbContext knows about any changes we make to those objects.
dbContext.SaveChanges();
}
static void AddMovie(MoviesContext dbContext)
{
// read from db
// DbSet implements IQueryable, which has LINQ methods just like IEnumerable
// IQueryable supports translating those lambdas into actual SQL commands
// IEnumerable does all the processing in-memory
// so... this doesn't fetch all records into objects and then run a lambda on them
// it translates the lambda/LINQ into a SQL query.
Genre actionGenre = dbContext.Genre.First(g => g.Name.Contains("Action"));
var newMovie = new Movie
{
Title = "LOTR: The Two Towers",
ReleaseDate = DateTime.Now,
Genre = actionGenre
};
// tell the dbcontext we have a new movie to insert.
dbContext.Movie.Add(newMovie);
// won't do anything until we call "SaveChanges"
// this one actually accesses the SQL server and runs INSERT.
dbContext.SaveChanges();
}
static void PrintMovies(MoviesContext dbContext)
{
// foreach (var movie in dbContext.Movie)
// code didn't work with this line, null exception on genre.
// because we needed to load that relationship / navigate property
foreach(var movie in dbContext.Movie.Include(m => m.Genre))
{
Console.WriteLine($"Movie #{movie.MovieId}: {movie.Title}" +
$" ({movie.ReleaseDate.Year})");
}
}
public IEnumerable<Movie> GetAllMovies()
{
throw new NotImplementedException();
}
public IEnumerable<Genre> GetAllGenres()
{
throw new NotImplementedException();
}
public Movie GetMovieById(int id)
{
throw new NotImplementedException();
}
public IEnumerable<Movie> GetMoviesByGenre(Genre genre)
{
throw new NotImplementedException();
}
public void AddMovie(Movie movie)
{
throw new NotImplementedException();
}
public void UpdateMovie(Movie movie)
{
throw new NotImplementedException();
}
public void DeleteMovie(Movie movie)
{
throw new NotImplementedException();
}
}
}
| 36.248619 | 94 | 0.58863 | [
"MIT"
] | 1902-feb18-net/william-code | HelloEntityFramework/HelloEntityFramework/Program.cs | 6,563 | C# |
using Core.DomainModel;
using Microsoft.AspNet.Identity.EntityFramework;
using System;
using System.Data.Entity;
namespace Infrastructure.DataAccess
{
public class ApplicationContext : IdentityDbContext<ApplicationUser>
{
// throwIfV1Schema is used when upgrading Identity in a database from 1 to 2.
// It's a one time thing and can be safely removed.
public ApplicationContext()
: base("DefaultConnection", throwIfV1Schema: false)
{
}
public static ApplicationContext Create()
{
return new ApplicationContext();
}
// Define you conceptual model here. Entity Framework will include these types and all their references.
// There are 3 different inheritance strategies:
// * Table per Hierarchy (TPH) (default): http://weblogs.asp.net/manavi/inheritance-mapping-strategies-with-entity-framework-code-first-ctp5-part-1-table-per-hierarchy-tph
// * Table per Type (TPT): http://weblogs.asp.net/manavi/inheritance-mapping-strategies-with-entity-framework-code-first-ctp5-part-2-table-per-type-tpt
// * Table per Concrete class (TPC): http://weblogs.asp.net/manavi/inheritance-mapping-strategies-with-entity-framework-code-first-ctp5-part-3-table-per-concrete-type-tpc-and-choosing-strategy-guidelines
public IDbSet<Student> Students { get; set; }
public IDbSet<Teacher> Teachers { get; set; }
public IDbSet<Course> Courses { get; set; }
public IDbSet<ClassRoom> ClassRooms { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
// The DateTime type in .NET has the same range and precision as datetime2 in SQL Server.
// Configure DateTime type to use SQL server datetime2 instead.
modelBuilder.Properties<DateTime>().Configure(c => c.HasColumnType("datetime2"));
// Consider setting max length on string properties.
// http://dba.stackexchange.com/questions/48408/ef-code-first-uses-nvarcharmax-for-all-strings-will-this-hurt-query-performan
modelBuilder.Properties<string>().Configure(c => c.HasMaxLength(100));
// Set max length where it makes sense.
modelBuilder.Entity<Student>().Property(s => s.Name).HasMaxLength(50);
modelBuilder.Entity<Teacher>().Property(s => s.Name).HasMaxLength(50);
modelBuilder.Entity<Course>().Property(s => s.Name).HasMaxLength(30);
base.OnModelCreating(modelBuilder);
}
}
}
| 49.442308 | 211 | 0.681058 | [
"MIT"
] | snebjorn/mvc-onion-template | Infrastructure.DataAccess/ApplicationContext.cs | 2,573 | C# |
/* Copyright 2009 dotless project, http://www.dotlesscss.com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License. */
namespace dotless.Core.exceptions
{
using System;
using System.Runtime.Serialization;
public class MixedUnitsException : Exception
{
public MixedUnitsException()
{
}
public MixedUnitsException(string message) : base(message)
{
}
public MixedUnitsException(string message, Exception innerException) : base(message, innerException)
{
}
protected MixedUnitsException(SerializationInfo info, StreamingContext context) : base(info, context)
{
}
}
} | 31.394737 | 109 | 0.688181 | [
"Apache-2.0"
] | chrisjowen/nLess | src/dotless.Core/exceptions/MixedUnitsException.cs | 1,193 | C# |
using Playnite.SDK;
using Playnite.Services;
using Playnite.Settings;
using Playnite.Commands;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Playnite.Windows;
using Playnite.Common;
using Playnite.ViewModels;
namespace Playnite.DesktopApp.ViewModels
{
public class AboutViewModel : ObservableObject
{
private static ILogger logger = LogManager.GetLogger();
private IWindowFactory window;
private IDialogsFactory dialogs;
private IResourceProvider resources;
private ServicesClient client;
public string VersionInfo
{
get
{
return "Playnite " + Updater.CurrentVersion.ToString(2);
}
}
public string SDKVersion
{
get
{
return "SDK: " + Playnite.SDK.SdkVersions.SDKVersion.ToString(3);
}
}
public string ThemeApiVersion
{
get
{
return "Theme API:\n" +
$"Desktop: {ThemeManager.DesktopApiVersion.ToString(3)}\n" +
$"Fullscreen: {ThemeManager.FullscreenApiVersion.ToString(3)}\n";
}
}
public string InstallDir
{
get => PlaynitePaths.ProgramPath;
}
public string UserDir
{
get => PlaynitePaths.ConfigRootPath;
}
public string Contributors
{
get
{
return Resources.ReadFileFromResource("Playnite.DesktopApp.Resources.contributors.txt");
}
}
private string patronsList;
public string PatronsList
{
get
{
if (PlayniteEnvironment.InOfflineMode)
{
return string.Empty;
}
try
{
if (patronsList == null)
{
patronsList = string.Join(Environment.NewLine, client.GetPatrons());
}
}
catch (Exception e)
{
logger.Error(e, "Failed to get patron list.");
}
return patronsList;
}
}
public string PatronsListDownloading
{
get => resources.GetString("LOCDownloadingLabel");
}
public RelayCommand<object> CreateDiagPackageCommand
{
get => new RelayCommand<object>((a) =>
{
CreateDiagPackage();
});
}
public RelayCommand<object> CloseCommand
{
get => new RelayCommand<object>((a) =>
{
CloseView();
});
}
public RelayCommand<object> OpenLicensesCommand
{
get => new RelayCommand<object>((a) =>
{
ProcessStarter.StartProcess(Path.Combine(PlaynitePaths.ProgramPath, "license.txt"));
});
}
public RelayCommand<object> NavigateUrlCommand => GlobalCommands.NavigateUrlCommand;
public AboutViewModel(IWindowFactory window, IDialogsFactory dialogs, IResourceProvider resources, ServicesClient client)
{
this.window = window;
this.dialogs = dialogs;
this.resources = resources;
this.client = client;
}
public void OpenView()
{
window.CreateAndOpenDialog(this);
}
public void CloseView()
{
window.Close();
}
public void CreateDiagPackage()
{
CrashHandlerViewModel.CreateDiagPackage(dialogs);
}
}
}
| 26.646667 | 130 | 0.499124 | [
"MIT"
] | FenDIY/Worknite | source/Playnite.DesktopApp/ViewModels/AboutViewModel.cs | 3,999 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
namespace Seventiny.Cloud.DataApi
{
public class Program
{
public static void Main(string[] args)
{
CreateWebHostBuilder(args).Build().Run();
}
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseUrls("http://*:39011")
.UseStartup<Startup>();
}
}
| 25.461538 | 76 | 0.675227 | [
"Apache-2.0"
] | PayHard/SevenTiny.Cloud.MultiTenantPlatform | 10-Code/Seventiny.Cloud.DataApi/Program.cs | 664 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Reflection;
using System.Threading.Tasks;
using Core.Text;
using Mono.Cecil;
using Xamarin.AndroidX.Data;
namespace Xamarin.AndroidX.Mapper
{
public class MappingsXamarin
{
protected static HttpClient client = null;
static MappingsXamarin()
{
client = new HttpClient();
return;
}
public MappingsXamarin()
{
client = new HttpClient();
return;
}
public bool MergeNestedtypes
{
get;
set;
} = true;
public GoogleMappingData GoogleMappingsData
{
get;
set;
}
string filename = null;
public void Download(string name, string url)
{
if (string.IsNullOrEmpty(name))
{
throw new InvalidOperationException($"Argument needed {nameof(name)}");
}
if (string.IsNullOrEmpty(url) && string.IsNullOrEmpty(AssemblyUrl))
{
throw new InvalidOperationException($"Argument needed {nameof(url)} or {nameof(AssemblyUrl)}");
}
if (string.IsNullOrEmpty(url))
{
url = AssemblyUrl;
}
Stream result = null;
using (HttpResponseMessage response = client.GetAsync(url).Result)
using (HttpContent content = response.Content)
{
// ... Read the string.
result = content.ReadAsStreamAsync().Result;
filename = $"{name}.dll";
if (File.Exists(name))
{
File.Delete(name);
}
FileStream fs = new FileStream(filename, FileMode.Create, FileAccess.Write, FileShare.None);
result
.CopyToAsync(fs)
.ContinueWith
(
(task) =>
{
fs.Flush();
fs.Close();
fs = null;
}
);
}
return;
}
public string AssemblyUrl
{
get;
set;
}
/// <summary>
/// whether duplicates are removed (Distinct() called)
/// </summary>
public bool IsDataUnique
{
get;
set;
} = true;
protected
(
string TypenameFullyQualifiedAndroidSupport,
string TypenameFullyQualifiedAndroidX
)
[]
mapping_sorted_androidx = null;
protected string[] mapping_sorted_androidx_index = null;
protected
(
string TypenameFullyQualifiedAndroidSupport,
string TypenameFullyQualifiedAndroidX
)
[]
mapping_sorted_android_support = null;
protected string[] mapping_sorted_android_support_index = null;
public void Initialize()
{
if (filename.ToLowerInvariant().Contains("androidx"))
{
mapping_sorted_androidx = this.GoogleMappingsData
.Mapping
.OrderBy(tuple => tuple.TypenameFullyQualifiedAndroidX)
.ToArray();
mapping_sorted_androidx_index = mapping_sorted_androidx
.Select(tuple => tuple.TypenameFullyQualifiedAndroidX)
.ToArray();
}
else
{
mapping_sorted_android_support = this.GoogleMappingsData
.Mapping
.OrderBy(tuple => tuple.TypenameFullyQualifiedAndroidSupport)
.ToArray();
mapping_sorted_android_support_index = mapping_sorted_android_support
.Select(tuple => tuple.TypenameFullyQualifiedAndroidSupport)
.ToArray();
}
// Cecilize(); // let user call Cecilize
//MappingsXamarinManaged = Cecilize().OrderBy(tuple => tuple.JavaType).ToArray();
//MappingsXamarinManagedIndex = MappingsXamarinManaged.Select(tuple => tuple.JavaType).ToArray();
return;
}
public
(
string JavaType,
string ManagedClass,
string ManagedNamespace,
string JNIPackage,
string JNIType
)[]
MappingsXamarinManaged
{
get;
private set;
}
public string[] MappingsXamarinManagedIndex
{
get;
private set;
}
public
(
string JavaType,
string ManagedClass,
string ManagedNamespace,
string JNIPackage,
string JNIType
)
Find(string java_type)
{
(
string JavaType,
string ManagedClass,
string ManagedNamespace,
string JNIPackage,
string JNIType
)
result;
int index = System.Array.BinarySearch(this.MappingsXamarinManagedIndex, java_type);
result = MappingsXamarinManaged[index];
return result;
}
/// <summary>
/// Types Android Registered
/// </summary>
public List
<
(
string JavaTypeFullyQualified,
string ManagedTypeFullyQualified
)
>
TAR;
/// <summary>
/// Types Android Registered (found) in Google (mappings)
/// </summary>
public List
<
(
string JavaTypeFullyQualified,
string ManagedTypeFullyQualified
)
>
TARIG;
/// <summary>
/// Types Android Registered NOT (found) in Google (mappings)
/// </summary>
public List
<
(
string JavaTypeFullyQualified,
string ManagedTypeFullyQualified
)
>
TARNIG;
/// <summary>
/// Types Android Registered NOT (found) in Google (mappings), but containing type was found
/// </summary>
public List
<
(
string JavaTypeFullyQualified,
string ManagedTypeFullyQualified
)
>
TARNIGF;
/// <summary>
/// Types Android Registered - Reference Types
/// </summary>
public List
<
(
string JavaTypeFullyQualified,
string ManagedTypeFullyQualified
)
>
TRAR;
/// <summary>
/// Types Android UN-Registered not registered
/// </summary>
public List
<
(
string JavaTypeFullyQualified,
string ManagedTypeFullyQualified
)
>
TAUR;
/// <summary>
/// Types NESTED Android Registered
/// </summary>
public List
<
(
string JavaTypeFullyQualified,
string ManagedTypeFullyQualified
)
>
TNAR;
/// <summary>
/// Types NESTED Android Registered (found) in Google (mappings)
/// </summary>
public List
<
(
string JavaTypeFullyQualified,
string ManagedTypeFullyQualified
)
>
TNARIG;
/// <summary>
/// Types NESTED Android Registered NOT (found) in Google (mappings)
/// </summary>
public List
<
(
string JavaTypeFullyQualified,
string ManagedTypeFullyQualified
)
>
TNARNIG;
/// <summary>
/// Types NESTED Android Registered NOT (found) in Google (mappings), but containing type was found
/// </summary>
public List
<
(
string JavaTypeFullyQualified,
string ManagedTypeFullyQualified
)
>
TNARNIGF;
/// <summary>
/// Types Referenced
/// </summary>
public List
<
(
string JavaTypeFullyQualified,
string ManagedTypeFullyQualified
)
>
TR;
public List
<
(
string TypenameFullyQualifiedAndroidSupport,
string TypenameFullyQualifiedAndroidX,
string TypenameFullyQualifiedXamarin
)
>
MappingsForMigrationMergeJoin;
public void Cecilize()
{
TAR = new List
<
(
string JavaTypeFullyQualified,
string ManagedTypeFullyQualified
)
>();
TARIG = new List
<
(
string JavaTypeFullyQualified,
string ManagedTypeFullyQualified
)
>();
TARNIG = new List
<
(
string JavaTypeFullyQualified,
string ManagedTypeFullyQualified
)
>();
TARNIGF = new List
<
(
string JavaTypeFullyQualified,
string ManagedTypeFullyQualified
)
>();
TAUR = new List
<
(
string JavaTypeFullyQualified,
string ManagedTypeFullyQualified
)
>();
TNAR = new List
<
(
string JavaTypeFullyQualified,
string ManagedTypeFullyQualified
)
>();
TNARIG = new List
<
(
string JavaTypeFullyQualified,
string ManagedTypeFullyQualified
)
>();
TNARNIG = new List
<
(
string JavaTypeFullyQualified,
string ManagedTypeFullyQualified
)
>();
TNARNIGF = new List
<
(
string JavaTypeFullyQualified,
string ManagedTypeFullyQualified
)
>();
TR = new List
<
(
string JavaTypeFullyQualified,
string ManagedTypeFullyQualified
)
>();
TRAR = new List
<
(
string JavaTypeFullyQualified,
string ManagedTypeFullyQualified
)
>();
MappingsForMigrationMergeJoin = new List
<
(
string TypenameFullyQualifiedAndroidSupport,
string TypenameFullyQualifiedAndroidX,
string TypenameFullyQualifiedXamarin
)
>();
if (filename.ToLowerInvariant().Contains("androidx"))
{
CecilizeAX();
}
else
{
CecilizeAS();
}
if (IsDataUnique)
{
Parallel.Invoke
(
() => this.TAR = this.TAR.Distinct().ToList(),
() => this.TARIG = this.TARIG.Distinct().ToList(),
() => this.TARNIG = this.TARNIG.Distinct().ToList(),
() => this.TARNIGF = this.TARNIGF.Distinct().ToList(),
() => this.TNAR = this.TNAR.Distinct().ToList(),
() => this.TNARIG = this.TNARIG.Distinct().ToList(),
() => this.TNARNIG = this.TNARNIG.Distinct().ToList(),
() => this.TNARNIGF = this.TNARNIGF.Distinct().ToList(),
() => this.TAUR = this.TAUR.Distinct().ToList(),
() => this.TRAR = this.TRAR.Distinct().ToList(),
() => this.TR = this.TR.Distinct().ToList()
);
}
(
string JavaTypeFullyQualified,
string ManagedTypeFullyQualified
)[]
merged_tar_tnar = null;
if (MergeNestedtypes)
{
merged_tar_tnar = this.TAR.Concat(this.TNAR).ToArray();
}
MappingsForMigrationMergeJoin = new List
<
(
string TypenameFullyQualifiedAndroidSupport,
string TypenameFullyQualifiedAndroidX,
string TypenameFullyQualifiedXamarin
)
>();
if (filename.ToLowerInvariant().Contains("androidx"))
{
foreach
(
(
string JavaTypeFullyQualified,
string ManagedTypeFullyQualified
) mapping_pair
in merged_tar_tnar
)
{
string tnas = null;
string tnax = mapping_pair.JavaTypeFullyQualified;
string tnxm = mapping_pair.ManagedTypeFullyQualified;
int index = Array.BinarySearch(this.mapping_sorted_androidx_index, tnax);
if (index >= 0 && index < mapping_sorted_androidx_index.Length)
{
tnas = this.mapping_sorted_androidx[index].TypenameFullyQualifiedAndroidSupport;
}
MappingsForMigrationMergeJoin.Add
(
(
TypenameFullyQualifiedAndroidSupport: tnas,
TypenameFullyQualifiedAndroidX: tnax,
TypenameFullyQualifiedXamarin: tnxm
)
);
}
}
else
{
foreach
(
(
string JavaTypeFullyQualified,
string ManagedTypeFullyQualified
) mapping_pair
in merged_tar_tnar
)
{
string tnas = mapping_pair.JavaTypeFullyQualified;
string tnax = null;
string tnxm = mapping_pair.ManagedTypeFullyQualified;
int index = Array.BinarySearch(this.mapping_sorted_android_support_index, tnas);
if (index >= 0 && index < mapping_sorted_android_support_index.Length)
{
tnax = this.mapping_sorted_android_support[index].TypenameFullyQualifiedAndroidX;
}
MappingsForMigrationMergeJoin.Add
(
(
TypenameFullyQualifiedAndroidSupport: tnas,
TypenameFullyQualifiedAndroidX: tnax,
TypenameFullyQualifiedXamarin: tnxm
)
);
}
}
return;
}
protected void CecilizeAS()
{
bool has_symbols_file = false;
ReaderParameters reader_parameters = new ReaderParameters
{
ReadSymbols = has_symbols_file
};
AssemblyDefinition assembly_definition = AssemblyDefinition.ReadAssembly(filename, reader_parameters);
foreach (ModuleDefinition module in assembly_definition.Modules)
{
foreach (TypeDefinition type in module.GetTypes())
{
if(type.HasCustomAttributes)
{
string managed_type = GetTypeName(type);
string managed_namespace = GetNamespace(type);
string managed_type_fq = $"{managed_namespace}.{managed_type}";
bool is_managed_nested_type = managed_type.Contains("/");
string jni_type = null;
string java_type = null;
bool is_jni_nested_type = false;
string attribute = null;
foreach (CustomAttribute attr in type.CustomAttributes)
{
attribute = attr.AttributeType.FullName;
if (attribute.Equals("Android.Runtime.RegisterAttribute"))
{
jni_type = attr.ConstructorArguments[0].Value.ToString();
java_type = jni_type.Replace("/", ".");
is_jni_nested_type = jni_type.Contains("$");
int lastSlash = jni_type.LastIndexOf('/');
if (lastSlash < 0 )
{
string type_with_nested_type = jni_type;
}
string jni_class = jni_type.Substring(lastSlash + 1).Replace('$', '.');
string jni_package = jni_type.Substring(0, lastSlash).Replace('/', '.');
//......................................................................
int index;
string tas = null;
string tax = null;
index = Array.BinarySearch
(
mapping_sorted_android_support_index,
java_type
);
if ( index >=0 && index < mapping_sorted_android_support_index.Count() -1 )
{
// found
TARIG.Add
(
(
JavaTypeFullyQualified: java_type,
ManagedTypeFullyQualified: managed_type_fq
)
);
tas = mapping_sorted_android_support[index].TypenameFullyQualifiedAndroidSupport;
tax = mapping_sorted_android_support[index].TypenameFullyQualifiedAndroidX;
MappingsForMigrationMergeJoin.Add
(
(
TypenameFullyQualifiedAndroidSupport: tas,
TypenameFullyQualifiedAndroidX: tax,
TypenameFullyQualifiedXamarin: managed_type_fq
)
);
}
else
{
// not found in google mappings
// check containing type of the nested type
int idx_tn = java_type.IndexOf('$', 0);
string t_tn = null;
if (idx_tn < 0)
{
t_tn = java_type;
}
else
{
t_tn = java_type.Substring(0, idx_tn);
}
int idx_t_tn = System.Array.BinarySearch
(
mapping_sorted_android_support_index,
t_tn
);
if (idx_t_tn >= 0 && idx_t_tn < mapping_sorted_android_support_index.Count() - 1)
{
// containing type of the nested type was found in google mappings
TARNIGF.Add
(
(
JavaTypeFullyQualified: java_type,
ManagedTypeFullyQualified: managed_type_fq
)
);
}
//else
{
TARNIG.Add
(
(
JavaTypeFullyQualified: java_type,
ManagedTypeFullyQualified: managed_type_fq
)
);
}
}
//......................................................................
TAR.Add
(
(
JavaTypeFullyQualified: java_type,
ManagedTypeFullyQualified: managed_type_fq
//ManagedNamespace: managed_namespace,
//JNIPackage: jni_package,
//JNIType: jni_type
)
);
}
}
}
if (type.HasNestedTypes)
{
foreach(TypeDefinition type_nested in type.NestedTypes)
{
if (type_nested.HasCustomAttributes)
{
string managed_type = GetTypeName(type);
string managed_namespace = GetNamespace(type);
string managed_type_fq = $"{managed_namespace}.{managed_type}";
foreach (CustomAttribute attr in type.CustomAttributes)
{
string attribute = attr.AttributeType.FullName;
if (attribute.Equals("Android.Runtime.RegisterAttribute"))
{
string jni_type = attr.ConstructorArguments[0].Value.ToString();
string java_type = jni_type.Replace("/", ".");
int lastSlash = jni_type.LastIndexOf('/');
if (lastSlash < 0 )
{
string type_with_nested_type = jni_type;
}
string jni_class = jni_type.Substring(lastSlash + 1).Replace('$', '.');
string jni_package = jni_type.Substring(0, lastSlash).Replace('/', '.');
//......................................................................
int index;
string tas = null;
string tax = null;
index = System.Array.BinarySearch
(
mapping_sorted_android_support_index,
java_type
);
if ( index >= 0 && index < mapping_sorted_android_support_index.Count())
{
// found
TNARIG.Add
(
(
JavaTypeFullyQualified: java_type,
ManagedTypeFullyQualified: managed_type_fq
)
);
tas = mapping_sorted_android_support[index].TypenameFullyQualifiedAndroidSupport;
tax = mapping_sorted_android_support[index].TypenameFullyQualifiedAndroidX;
MappingsForMigrationMergeJoin.Add
(
(
TypenameFullyQualifiedAndroidSupport: tas,
TypenameFullyQualifiedAndroidX: tax,
TypenameFullyQualifiedXamarin: managed_type_fq
)
);
}
else
{
// not found in google mappings
// check containing type of the nested type
int idx_tn = java_type.IndexOf('$', 0);
string t_tn = null;
if (idx_tn >= 0 && idx_tn < java_type.Length)
{
t_tn = java_type.Substring(0, idx_tn);
}
else
{
t_tn = java_type;
}
int idx_t_tn = System.Array.BinarySearch
(
mapping_sorted_android_support_index,
t_tn
);
if (idx_t_tn >= 0 && idx_t_tn < mapping_sorted_android_support_index.Count())
{
// containing type of the nested type was found in google mappings
TNARNIGF.Add
(
(
JavaTypeFullyQualified: java_type,
ManagedTypeFullyQualified: managed_type_fq
)
);
}
else
{
java_type = null;
}
TNARNIG.Add
(
(
JavaTypeFullyQualified: java_type,
ManagedTypeFullyQualified: managed_type_fq
)
);
}
//......................................................................
TNAR.Add
(
(
JavaTypeFullyQualified: java_type,
ManagedTypeFullyQualified: managed_type_fq
//ManagedNamespace: managed_namespace,
//JNIPackage: jni_package,
//JNIType: jni_type
)
);
}
}
}
}
}
}
foreach (TypeReference type in module.GetTypeReferences())
{
string managed_type = type.FullName;
string java_type = "jt";
TR.Add
(
(
JavaTypeFullyQualified: java_type,
ManagedTypeFullyQualified: managed_type
)
);
}
}
AnalysisData = new Dictionary<string, int>()
{
{ "$GoogleMappings$", this.GoogleMappingsData.Mapping.Count() },
{ "TAR", TAR.Count },
{ "TARIG", TARIG.Count },
{ "TARNIG", TARNIG.Count },
{ "TNAR", TNAR.Count },
{ "TNAUR", -1 },
{ "TR", TRAR.Count },
};
return;
}
protected void CecilizeAX()
{
bool has_symbols_file = false;
ReaderParameters reader_parameters = new ReaderParameters
{
ReadSymbols = has_symbols_file
};
AssemblyDefinition assembly_definition = AssemblyDefinition.ReadAssembly(filename, reader_parameters);
foreach (ModuleDefinition module in assembly_definition.Modules)
{
foreach (TypeDefinition type in module.GetTypes())
{
if(type.HasCustomAttributes)
{
string managed_type = GetTypeName(type);
string managed_namespace = GetNamespace(type);
string managed_type_fq = $"{managed_namespace}.{managed_type}";
bool is_managed_nested_type = managed_type.Contains("/");
string jni_type = null;
string java_type = null;
bool is_jni_nested_type = false;
string attribute = null;
foreach (CustomAttribute attr in type.CustomAttributes)
{
attribute = attr.AttributeType.FullName;
if (attribute.Equals("Android.Runtime.RegisterAttribute"))
{
jni_type = attr.ConstructorArguments[0].Value.ToString();
java_type = jni_type.Replace("/", ".");
int lastSlash = jni_type.LastIndexOf('/');
if (lastSlash < 0 )
{
string type_with_nested_type = jni_type;
}
string jni_class = jni_type.Substring(lastSlash + 1).Replace('$', '.');
string jni_package = jni_type.Substring(0, lastSlash).Replace('/', '.');
//......................................................................
int index;
string tas = null;
string tax = null;
index = System.Array.BinarySearch
(
mapping_sorted_androidx_index,
java_type
);
if ( index >= 0 && index < mapping_sorted_androidx_index.Count())
{
// found
TARIG.Add
(
(
JavaTypeFullyQualified: java_type,
ManagedTypeFullyQualified: managed_type_fq
)
);
tas = mapping_sorted_androidx[index].TypenameFullyQualifiedAndroidSupport;
tax = mapping_sorted_androidx[index].TypenameFullyQualifiedAndroidX;
MappingsForMigrationMergeJoin.Add
(
(
TypenameFullyQualifiedAndroidSupport: tas,
TypenameFullyQualifiedAndroidX: tax,
TypenameFullyQualifiedXamarin: managed_type_fq
)
);
}
else
{
// not found in google mappings
// check containing type of the nested type
int idx_tn = java_type.IndexOf('$', 0);
string t_tn = null;
if (idx_tn >= 0 && idx_tn < java_type.Length)
{
t_tn = java_type.Substring(0, idx_tn);
}
else
{
t_tn = java_type;
}
int idx_t_tn = System.Array.BinarySearch
(
mapping_sorted_androidx_index,
t_tn
);
if (idx_t_tn >= 0 && idx_t_tn < mapping_sorted_androidx_index.Count())
{
// containing type of the nested type was found in google mappings
TARNIGF.Add
(
(
JavaTypeFullyQualified: java_type,
ManagedTypeFullyQualified: managed_type_fq
)
);
}
else
{
java_type = null;
}
TARNIG.Add
(
(
JavaTypeFullyQualified: java_type,
ManagedTypeFullyQualified: managed_type_fq
)
);
}
//......................................................................
TAR.Add
(
(
JavaTypeFullyQualified: java_type,
ManagedTypeFullyQualified: managed_type_fq
//ManagedNamespace: managed_namespace,
//JNIPackage: jni_package,
//JNIType: jni_type
)
);
}
}
}
if (type.HasNestedTypes)
{
foreach(TypeDefinition type_nested in type.NestedTypes)
{
if (type_nested.HasCustomAttributes)
{
string managed_type = GetTypeName(type);
string managed_namespace = GetNamespace(type);
string managed_type_fq = $"{managed_namespace}.{managed_type}";
foreach (CustomAttribute attr in type.CustomAttributes)
{
string attribute = attr.AttributeType.FullName;
if (attribute.Equals("Android.Runtime.RegisterAttribute"))
{
string jni_type = attr.ConstructorArguments[0].Value.ToString();
string java_type = jni_type.Replace("/", ".");
int lastSlash = jni_type.LastIndexOf('/');
if (lastSlash < 0 )
{
string type_with_nested_type = jni_type;
}
string jni_class = jni_type.Substring(lastSlash + 1).Replace('$', '.');
string jni_package = jni_type.Substring(0, lastSlash).Replace('/', '.');
//......................................................................
int index;
string tas = null;
string tax = null;
index = System.Array.BinarySearch
(
mapping_sorted_androidx_index,
java_type
);
if ( index >= 0 && index < mapping_sorted_androidx_index.Count())
{
// found
TNARIG.Add
(
(
JavaTypeFullyQualified: java_type,
ManagedTypeFullyQualified: managed_type_fq
)
);
tas = mapping_sorted_androidx[index].TypenameFullyQualifiedAndroidSupport;
tax = mapping_sorted_androidx[index].TypenameFullyQualifiedAndroidX;
MappingsForMigrationMergeJoin.Add
(
(
TypenameFullyQualifiedAndroidSupport: tas,
TypenameFullyQualifiedAndroidX: tax,
TypenameFullyQualifiedXamarin: managed_type_fq
)
);
}
else
{
// not found in google mappings
// check containing type of the nested type
int idx_tn = java_type.IndexOf('$', 0);
string t_tn = null;
if (idx_tn < 0)
{
t_tn = java_type;
}
else
{
t_tn = java_type.Substring(0, idx_tn);
}
int idx_t_tn = System.Array.BinarySearch
(
mapping_sorted_androidx_index,
t_tn
);
if (idx_t_tn >= 0 && idx_t_tn < mapping_sorted_androidx_index.Count() - 1)
{
// containing type of the nested type was found in google mappings
TNARNIGF.Add
(
(
JavaTypeFullyQualified: java_type,
ManagedTypeFullyQualified: managed_type_fq
)
);
}
//else
{
TNARNIG.Add
(
(
JavaTypeFullyQualified: java_type,
ManagedTypeFullyQualified: managed_type_fq
)
);
}
}
//......................................................................
TNAR.Add
(
(
JavaTypeFullyQualified: java_type,
ManagedTypeFullyQualified: managed_type_fq
//ManagedNamespace: managed_namespace,
//JNIPackage: jni_package,
//JNIType: jni_type
)
);
}
}
}
}
}
}
foreach (TypeReference type in module.GetTypeReferences())
{
string managed_type = type.FullName;
string java_type = "jt";
TR.Add
(
(
JavaTypeFullyQualified: java_type,
ManagedTypeFullyQualified: managed_type
)
);
}
}
AnalysisData = new Dictionary<string, int>()
{
{ "$GoogleMappings$", this.GoogleMappingsData.Mapping.Count() },
{ "TAR", TAR.Count },
{ "TARIG", TARIG.Count },
{ "TARNIG", TARNIG.Count },
{ "TNAR", TNAR.Count },
{ "TNAUR", -1 },
{ "TR", TRAR.Count },
};
return;
}
public Dictionary<string, int> AnalysisData
{
get;
set;
}
private string GetNamespace(TypeDefinition type_definition)
{
TypeDefinition td = type_definition;
string ns = type_definition.Namespace;
while (string.IsNullOrEmpty(ns))
{
if (td.DeclaringType == null)
{
break;
}
ns = td.DeclaringType.Namespace;
td = td.DeclaringType;
}
return ns;
}
private string GetTypeName(TypeDefinition typeDef)
{
TypeDefinition td = typeDef;
string tn = typeDef.Name;
while (td.DeclaringType != null)
{
tn = td.DeclaringType.Name + "." + tn;
td = td.DeclaringType;
}
return tn;
}
public void Dump()
{
Parallel.Invoke
(
() =>
{
Assembly assembly = Assembly.GetExecutingAssembly();
string[] resource_names = assembly.GetManifestResourceNames();
string file = resource_names
.Single(f => f.EndsWith("assembly-analysis-report.md", StringComparison.InvariantCulture));
string report = null;
using (Stream stream = assembly.GetManifestResourceStream(file))
using (StreamReader reader = new StreamReader(stream))
{
report = reader.ReadToEnd();
}
string replacement = null;
replacement = this.GoogleMappingsData.Mapping.Count().ToString();
report = report.Replace($@"$GoogleMappings$", replacement);
replacement = string.Join
(
Environment.NewLine,
this.GoogleMappingsData.ReducedWithFiltering
);
report = report.Replace($@"$SizeReductionReport$", replacement);
int n_google_mappings = GoogleMappingsData.Mapping.Count();
report = report.Replace("$FILENAME$", filename);
report = report.Replace("$GoogleMappings$", n_google_mappings.ToString());
report = report.Replace("$NTAR$", this.TAR.Count().ToString());
report = report.Replace("$NTARIG$", this.TARIG.Count().ToString());
report = report.Replace("$NTARNIG$", this.TARNIG.Count().ToString());
int sum_tar = this.TARIG.Count() + this.TARNIG.Count();
report = report.Replace("$SUM_TAR$", sum_tar.ToString());
report = report.Replace("$NTNAR$", this.TNAR.Count().ToString());
report = report.Replace("$NTNARIG$", this.TNARIG.Count().ToString());
report = report.Replace("$NTNARNIG$", this.TNARNIG.Count().ToString());
int sum_tnar = this.TNARIG.Count() + this.TNARNIG.Count();
report = report.Replace("$SUM_TNAR$", sum_tnar.ToString());
report = report.Replace("$NTAUR$", this.TAUR.Count().ToString());
report = report.Replace("$NTR$", this.TR.Count().ToString());
report = report.Replace
(
"$N_MappingsForMigrationMergeJoin$",
this.MappingsForMigrationMergeJoin.Count().ToString()
);
File.WriteAllText(Path.ChangeExtension(filename, "assembly-analysis-report.md"), report);
},
() =>
{
string text = string.Join(Environment.NewLine, this.TAR);
text = text.Replace("(", "");
text = text.Replace(")", "");
text = text.Replace(" ", "");
File.WriteAllText(Path.ChangeExtension(filename, "dll.TAR.csv"), text);
},
() =>
{
string text = string.Join(Environment.NewLine, this.TARIG);
text = text.Replace("(", "");
text = text.Replace(")", "");
text = text.Replace(" ", "");
File.WriteAllText(Path.ChangeExtension(filename, "dll.TARIG.csv"), text);
},
() =>
{
string text = string.Join(Environment.NewLine, this.TARNIG);
text = text.Replace("(", "");
text = text.Replace(")", "");
text = text.Replace(" ", "");
File.WriteAllText(Path.ChangeExtension(filename, "dll.TARNIG.csv"), text);
},
() =>
{
string text = string.Join(Environment.NewLine, this.TARNIGF);
text = text.Replace("(", "");
text = text.Replace(")", "");
text = text.Replace(" ", "");
File.WriteAllText(Path.ChangeExtension(filename, "dll.TARNIGF.csv"), text);
},
() =>
{
string text = string.Join(Environment.NewLine, this.TAUR);
text = text.Replace("(", "");
text = text.Replace(")", "");
text = text.Replace(" ", "");
File.WriteAllText(Path.ChangeExtension(filename, "TAUR.csv"), text);
},
() =>
{
string text = string.Join(Environment.NewLine, this.TNAR);
text = text.Replace("(", "");
text = text.Replace(")", "");
text = text.Replace(" ", "");
File.WriteAllText(Path.ChangeExtension(filename, "dll.TNAR.csv"), text);
},
() =>
{
string text = string.Join(Environment.NewLine, this.TNARIG);
text = text.Replace("(", "");
text = text.Replace(")", "");
text = text.Replace(" ", "");
File.WriteAllText(Path.ChangeExtension(filename, "dll.TNARIG.csv"), text);
},
() =>
{
string text = string.Join(Environment.NewLine, this.TNARNIG);
text = text.Replace("(", "");
text = text.Replace(")", "");
text = text.Replace(" ", "");
File.WriteAllText(Path.ChangeExtension(filename, "dll.TNARNIG.csv"), text);
},
() =>
{
string text = string.Join(Environment.NewLine, this.TNARNIGF);
text = text.Replace("(", "");
text = text.Replace(")", "");
text = text.Replace(" ", "");
File.WriteAllText(Path.ChangeExtension(filename, "dll.TNARNIGF.csv"), text);
},
() =>
{
string text = string.Join(Environment.NewLine, this.TR);
text = text.Replace("(", "");
text = text.Replace(")", "");
text = text.Replace(" ", "");
File.WriteAllText(Path.ChangeExtension(filename, "dll.TR.csv"), text);
},
() =>
{
string text = string.Join(Environment.NewLine, this.TRAR);
text = text.Replace("(", "");
text = text.Replace(")", "");
text = text.Replace(" ", "");
File.WriteAllText(Path.ChangeExtension(filename, "dll.TRAR.csv"), text);
},
() =>
{
string text = string.Join(Environment.NewLine, this.MappingsForMigrationMergeJoin);
text = text.Replace("(", "");
text = text.Replace(")", "");
text = text.Replace(" ", "");
File.WriteAllText(Path.ChangeExtension(filename, "dll.MappingsForMigrationMergeJoin.csv"), text);
}
);
return;
}
}
}
| 45.773304 | 131 | 0.317194 | [
"MIT"
] | moljac/HolisticWare.Xamarin.Tools.Bindings.XamarinAndroid.AndroidX.Migraineator | source/Xamarin.AndroidX.Mapper/MappingsXamarin.cs | 61,384 | C# |
using System;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.IdentityModel.Tokens;
using Abp.Runtime.Security;
namespace FirstProject.Web.Host.Startup
{
public static class AuthConfigurer
{
public static void Configure(IServiceCollection services, IConfiguration configuration)
{
if (bool.Parse(configuration["Authentication:JwtBearer:IsEnabled"]))
{
services.AddAuthentication(options => {
options.DefaultAuthenticateScheme = "JwtBearer";
options.DefaultChallengeScheme = "JwtBearer";
}).AddJwtBearer("JwtBearer", options =>
{
options.Audience = configuration["Authentication:JwtBearer:Audience"];
options.TokenValidationParameters = new TokenValidationParameters
{
// The signing key must match!
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(configuration["Authentication:JwtBearer:SecurityKey"])),
// Validate the JWT Issuer (iss) claim
ValidateIssuer = true,
ValidIssuer = configuration["Authentication:JwtBearer:Issuer"],
// Validate the JWT Audience (aud) claim
ValidateAudience = true,
ValidAudience = configuration["Authentication:JwtBearer:Audience"],
// Validate the token expiry
ValidateLifetime = true,
// If you want to allow a certain amount of clock drift, set that here
ClockSkew = TimeSpan.Zero
};
options.Events = new JwtBearerEvents
{
OnMessageReceived = QueryStringTokenResolver
};
});
}
}
/* This method is needed to authorize SignalR javascript client.
* SignalR can not send authorization header. So, we are getting it from query string as an encrypted text. */
private static Task QueryStringTokenResolver(MessageReceivedContext context)
{
if (!context.HttpContext.Request.Path.HasValue ||
!context.HttpContext.Request.Path.Value.StartsWith("/signalr"))
{
// We are just looking for signalr clients
return Task.CompletedTask;
}
var qsAuthToken = context.HttpContext.Request.Query["enc_auth_token"].FirstOrDefault();
if (qsAuthToken == null)
{
// Cookie value does not matches to querystring value
return Task.CompletedTask;
}
// Set auth token from cookie
context.Token = SimpleStringCipher.Instance.Decrypt(qsAuthToken, AppConsts.DefaultPassPhrase);
return Task.CompletedTask;
}
}
}
| 41.101266 | 148 | 0.582692 | [
"MIT"
] | khanhly-dev/Abp_FirstProject | aspnet-core/src/FirstProject.Web.Host/Startup/AuthConfigurer.cs | 3,249 | C# |
using System;
using System.Windows.Input;
namespace Acr.UserDialogs
{
public class LoginViewModel
{
public ICommand Login { get; set; }
public ICommand Cancel { get; set; }
public string UserNameText { get; set; }
public string UserNamePlaceholder { get; set; }
public string PasswordText { get; set; }
public string PasswordPlaceholder { get; set; }
public string UserName { get; set; }
public string Password { get; set; }
public string CancelText { get; set; }
public string LoginText { get; set; }
public string Title { get; set; }
public string Message { get; set; }
}
}
| 27.56 | 55 | 0.612482 | [
"MIT"
] | 1Cor125/userdialogs | src/Acr.UserDialogs/Platforms/Uwp/LoginViewModel.cs | 691 | C# |
namespace MatBlazorSample.Blazor.Pages
{
public partial class Index
{
}
}
| 11 | 39 | 0.659091 | [
"MIT"
] | 271943794/abp-samples | MatBlazorSample/src/MatBlazorSample.Blazor/Pages/Index.razor.cs | 90 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SymNet.Core.Serialization
{
/// <summary>
/// Controls object and some member level serialization
/// </summary>
public class SymConnectObject : System.Attribute
{
internal string _recordName;
internal string _repgenName;
internal SymConnectObjectSerialization _serializationType;
public SymConnectObject(string recordName,
SymConnectObjectSerialization serializationType = SymConnectObjectSerialization.Implicit)
{
_recordName = recordName;
_serializationType = serializationType;
}
public SymConnectObject(string recordName,
string repgenName,
SymConnectObjectSerialization serializationType = SymConnectObjectSerialization.Implicit)
{
_recordName = recordName;
_repgenName = repgenName;
_serializationType = serializationType;
}
}
public enum SymConnectObjectSerialization
{
Implicit,
Explicit
}
}
| 25.711111 | 101 | 0.673293 | [
"MIT"
] | DavidDworetzky/Sym.NET | SymNet.Core/Serialization/SymConnectObject.cs | 1,159 | C# |
using System.Collections.Generic;
using System.Net.Http;
using System.Threading.Tasks;
namespace NgrokApi
{
// <summary>
// Endpoint Configuration managementAn <see
// href="https://ngrok.com/docs/ngrok-link#api-endpoint-configurations">Endpoint
// Configuration</see> describes
// a ngrok network endpoint instance.<em>Endpoints are your gateway to ngrok
// features!</em>
// </summary>
public class EndpointConfigurations
{
private IApiHttpClient apiClient;
internal EndpointConfigurations(IApiHttpClient apiClient)
{
this.apiClient = apiClient;
}
// <summary>
// Create a new endpoint configuration
// </summary>
//
// https://ngrok.com/docs/api#api-endpoint-configurations-create
public async Task<EndpointConfiguration> Create(EndpointConfigurationCreate arg)
{
Dictionary<string, string> query = null;
EndpointConfigurationCreate body = null;
body = arg;
return await apiClient.Do<EndpointConfiguration>(
path: $"/endpoint_configurations",
method: new HttpMethod("post"),
body: body,
query: query
);
}
// <summary>
// Delete an endpoint configuration. This operation will fail if the endpoint
// configuration is still referenced by any reserved domain or reserved address.
// </summary>
//
// https://ngrok.com/docs/api#api-endpoint-configurations-delete
public async Task Delete(string id)
{
var arg = new Item() { Id = id };
Dictionary<string, string> query = null;
Item body = null;
query = new Dictionary<string, string>()
{
};
await apiClient.DoNoReturnBody<Empty>(
path: $"/endpoint_configurations/{arg.Id}",
method: new HttpMethod("delete"),
body: body,
query: query
);
}
// <summary>
// Returns detailed information about an endpoint configuration
// </summary>
//
// https://ngrok.com/docs/api#api-endpoint-configurations-get
public async Task<EndpointConfiguration> Get(string id)
{
var arg = new Item() { Id = id };
Dictionary<string, string> query = null;
Item body = null;
query = new Dictionary<string, string>()
{
};
return await apiClient.Do<EndpointConfiguration>(
path: $"/endpoint_configurations/{arg.Id}",
method: new HttpMethod("get"),
body: body,
query: query
);
}
private async Task<EndpointConfigurationList> ListPage(Paging arg)
{
Dictionary<string, string> query = null;
Paging body = null;
query = new Dictionary<string, string>()
{
["before_id"] = arg.BeforeId,
["limit"] = arg.Limit,
};
return await apiClient.Do<EndpointConfigurationList>(
path: $"/endpoint_configurations",
method: new HttpMethod("get"),
body: body,
query: query
);
}
// <summary>
// Returns a list of all endpoint configurations on this account
// </summary>
//
// https://ngrok.com/docs/api#api-endpoint-configurations-list
public IEnumerable<EndpointConfiguration> List(string limit = null, string beforeId = null)
{
return new Iterator<EndpointConfiguration>(beforeId, async lastId =>
{
var result = await this.ListPage(new Paging()
{
BeforeId = lastId,
Limit = limit,
});
return result.EndpointConfigurations;
});
}
// <summary>
// Updates an endpoint configuration. If a module is not specified in the update,
// it will not be modified. However, each module configuration that is specified
// will completely replace the existing value. There is no way to delete an
// existing module via this API, instead use the delete module API.
// </summary>
//
// https://ngrok.com/docs/api#api-endpoint-configurations-update
public async Task<EndpointConfiguration> Update(EndpointConfigurationUpdate arg)
{
Dictionary<string, string> query = null;
EndpointConfigurationUpdate body = null;
body = arg;
return await apiClient.Do<EndpointConfiguration>(
path: $"/endpoint_configurations/{arg.Id}",
method: new HttpMethod("patch"),
body: body,
query: query
);
}
}
}
| 33.375 | 99 | 0.544648 | [
"MIT"
] | V1RuSyRa/ngrok-api-dotnet | NgrokApi/Services/EndpointConfigurations.cs | 5,073 | 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 lambda-2015-03-31.normal.json service model.
*/
using System;
using System.Runtime.ExceptionServices;
using System.Threading;
using System.Threading.Tasks;
using System.Collections.Generic;
using System.Net;
using Amazon.Lambda.Model;
using Amazon.Lambda.Model.Internal.MarshallTransformations;
using Amazon.Lambda.Internal;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Auth;
using Amazon.Runtime.Internal.Transform;
namespace Amazon.Lambda
{
/// <summary>
/// Implementation for accessing Lambda
///
/// AWS Lambda
/// <para>
/// <b>Overview</b>
/// </para>
///
/// <para>
/// This is the <i>AWS Lambda API Reference</i>. The AWS Lambda Developer Guide provides
/// additional information. For the service overview, see <a href="https://docs.aws.amazon.com/lambda/latest/dg/welcome.html">What
/// is AWS Lambda</a>, and for information about how the service works, see <a href="https://docs.aws.amazon.com/lambda/latest/dg/lambda-introduction.html">AWS
/// Lambda: How it Works</a> in the <b>AWS Lambda Developer Guide</b>.
/// </para>
/// </summary>
public partial class AmazonLambdaClient : AmazonServiceClient, IAmazonLambda
{
private static IServiceMetadata serviceMetadata = new AmazonLambdaMetadata();
#region Constructors
#if NETSTANDARD
/// <summary>
/// Constructs AmazonLambdaClient with the credentials loaded from the application's
/// default configuration, and if unsuccessful from the Instance Profile service on an EC2 instance.
///
/// Example App.config with credentials set.
/// <code>
/// <?xml version="1.0" encoding="utf-8" ?>
/// <configuration>
/// <appSettings>
/// <add key="AWSProfileName" value="AWS Default"/>
/// </appSettings>
/// </configuration>
/// </code>
///
/// </summary>
public AmazonLambdaClient()
: base(FallbackCredentialsFactory.GetCredentials(), new AmazonLambdaConfig()) { }
/// <summary>
/// Constructs AmazonLambdaClient with the credentials loaded from the application's
/// default configuration, and if unsuccessful from the Instance Profile service on an EC2 instance.
///
/// Example App.config with credentials set.
/// <code>
/// <?xml version="1.0" encoding="utf-8" ?>
/// <configuration>
/// <appSettings>
/// <add key="AWSProfileName" value="AWS Default"/>
/// </appSettings>
/// </configuration>
/// </code>
///
/// </summary>
/// <param name="region">The region to connect.</param>
public AmazonLambdaClient(RegionEndpoint region)
: base(FallbackCredentialsFactory.GetCredentials(), new AmazonLambdaConfig{RegionEndpoint = region}) { }
/// <summary>
/// Constructs AmazonLambdaClient with the credentials loaded from the application's
/// default configuration, and if unsuccessful from the Instance Profile service on an EC2 instance.
///
/// Example App.config with credentials set.
/// <code>
/// <?xml version="1.0" encoding="utf-8" ?>
/// <configuration>
/// <appSettings>
/// <add key="AWSProfileName" value="AWS Default"/>
/// </appSettings>
/// </configuration>
/// </code>
///
/// </summary>
/// <param name="config">The AmazonLambdaClient Configuration Object</param>
public AmazonLambdaClient(AmazonLambdaConfig config)
: base(FallbackCredentialsFactory.GetCredentials(), config) { }
#endif
/// <summary>
/// Constructs AmazonLambdaClient with AWS Credentials
/// </summary>
/// <param name="credentials">AWS Credentials</param>
public AmazonLambdaClient(AWSCredentials credentials)
: this(credentials, new AmazonLambdaConfig())
{
}
/// <summary>
/// Constructs AmazonLambdaClient with AWS Credentials
/// </summary>
/// <param name="credentials">AWS Credentials</param>
/// <param name="region">The region to connect.</param>
public AmazonLambdaClient(AWSCredentials credentials, RegionEndpoint region)
: this(credentials, new AmazonLambdaConfig{RegionEndpoint = region})
{
}
/// <summary>
/// Constructs AmazonLambdaClient with AWS Credentials and an
/// AmazonLambdaClient Configuration object.
/// </summary>
/// <param name="credentials">AWS Credentials</param>
/// <param name="clientConfig">The AmazonLambdaClient Configuration Object</param>
public AmazonLambdaClient(AWSCredentials credentials, AmazonLambdaConfig clientConfig)
: base(credentials, clientConfig)
{
}
/// <summary>
/// Constructs AmazonLambdaClient with AWS Access Key ID and AWS Secret Key
/// </summary>
/// <param name="awsAccessKeyId">AWS Access Key ID</param>
/// <param name="awsSecretAccessKey">AWS Secret Access Key</param>
public AmazonLambdaClient(string awsAccessKeyId, string awsSecretAccessKey)
: this(awsAccessKeyId, awsSecretAccessKey, new AmazonLambdaConfig())
{
}
/// <summary>
/// Constructs AmazonLambdaClient with AWS Access Key ID and AWS Secret Key
/// </summary>
/// <param name="awsAccessKeyId">AWS Access Key ID</param>
/// <param name="awsSecretAccessKey">AWS Secret Access Key</param>
/// <param name="region">The region to connect.</param>
public AmazonLambdaClient(string awsAccessKeyId, string awsSecretAccessKey, RegionEndpoint region)
: this(awsAccessKeyId, awsSecretAccessKey, new AmazonLambdaConfig() {RegionEndpoint=region})
{
}
/// <summary>
/// Constructs AmazonLambdaClient with AWS Access Key ID, AWS Secret Key and an
/// AmazonLambdaClient Configuration object.
/// </summary>
/// <param name="awsAccessKeyId">AWS Access Key ID</param>
/// <param name="awsSecretAccessKey">AWS Secret Access Key</param>
/// <param name="clientConfig">The AmazonLambdaClient Configuration Object</param>
public AmazonLambdaClient(string awsAccessKeyId, string awsSecretAccessKey, AmazonLambdaConfig clientConfig)
: base(awsAccessKeyId, awsSecretAccessKey, clientConfig)
{
}
/// <summary>
/// Constructs AmazonLambdaClient with AWS Access Key ID and AWS Secret Key
/// </summary>
/// <param name="awsAccessKeyId">AWS Access Key ID</param>
/// <param name="awsSecretAccessKey">AWS Secret Access Key</param>
/// <param name="awsSessionToken">AWS Session Token</param>
public AmazonLambdaClient(string awsAccessKeyId, string awsSecretAccessKey, string awsSessionToken)
: this(awsAccessKeyId, awsSecretAccessKey, awsSessionToken, new AmazonLambdaConfig())
{
}
/// <summary>
/// Constructs AmazonLambdaClient with AWS Access Key ID and AWS Secret Key
/// </summary>
/// <param name="awsAccessKeyId">AWS Access Key ID</param>
/// <param name="awsSecretAccessKey">AWS Secret Access Key</param>
/// <param name="awsSessionToken">AWS Session Token</param>
/// <param name="region">The region to connect.</param>
public AmazonLambdaClient(string awsAccessKeyId, string awsSecretAccessKey, string awsSessionToken, RegionEndpoint region)
: this(awsAccessKeyId, awsSecretAccessKey, awsSessionToken, new AmazonLambdaConfig{RegionEndpoint = region})
{
}
/// <summary>
/// Constructs AmazonLambdaClient with AWS Access Key ID, AWS Secret Key and an
/// AmazonLambdaClient Configuration object.
/// </summary>
/// <param name="awsAccessKeyId">AWS Access Key ID</param>
/// <param name="awsSecretAccessKey">AWS Secret Access Key</param>
/// <param name="awsSessionToken">AWS Session Token</param>
/// <param name="clientConfig">The AmazonLambdaClient Configuration Object</param>
public AmazonLambdaClient(string awsAccessKeyId, string awsSecretAccessKey, string awsSessionToken, AmazonLambdaConfig clientConfig)
: base(awsAccessKeyId, awsSecretAccessKey, awsSessionToken, clientConfig)
{
}
#endregion
#region Overrides
/// <summary>
/// Creates the signer for the service.
/// </summary>
protected override AbstractAWSSigner CreateSigner()
{
return new AWS4Signer();
}
/// <summary>
/// Capture metadata for the service.
/// </summary>
protected override IServiceMetadata ServiceMetadata
{
get
{
return serviceMetadata;
}
}
#endregion
#region Dispose
/// <summary>
/// Disposes the service client.
/// </summary>
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
}
#endregion
#region AddLayerVersionPermission
internal virtual AddLayerVersionPermissionResponse AddLayerVersionPermission(AddLayerVersionPermissionRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = AddLayerVersionPermissionRequestMarshaller.Instance;
options.ResponseUnmarshaller = AddLayerVersionPermissionResponseUnmarshaller.Instance;
return Invoke<AddLayerVersionPermissionResponse>(request, options);
}
/// <summary>
/// Adds permissions to the resource-based policy of a version of an <a href="https://docs.aws.amazon.com/lambda/latest/dg/configuration-layers.html">AWS
/// Lambda layer</a>. Use this action to grant layer usage permission to other accounts.
/// You can grant permission to a single account, all AWS accounts, or all accounts in
/// an organization.
///
///
/// <para>
/// To revoke permission, call <a>RemoveLayerVersionPermission</a> with the statement
/// ID that you specified when you added it.
/// </para>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the AddLayerVersionPermission service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the AddLayerVersionPermission service method, as returned by Lambda.</returns>
/// <exception cref="Amazon.Lambda.Model.InvalidParameterValueException">
/// One of the parameters in the request is invalid.
/// </exception>
/// <exception cref="Amazon.Lambda.Model.PolicyLengthExceededException">
/// The permissions policy for the resource is too large. <a href="https://docs.aws.amazon.com/lambda/latest/dg/limits.html">Learn
/// more</a>
/// </exception>
/// <exception cref="Amazon.Lambda.Model.PreconditionFailedException">
/// The RevisionId provided does not match the latest RevisionId for the Lambda function
/// or alias. Call the <code>GetFunction</code> or the <code>GetAlias</code> API to retrieve
/// the latest RevisionId for your resource.
/// </exception>
/// <exception cref="Amazon.Lambda.Model.ResourceConflictException">
/// The resource already exists, or another operation is in progress.
/// </exception>
/// <exception cref="Amazon.Lambda.Model.ResourceNotFoundException">
/// The resource specified in the request does not exist.
/// </exception>
/// <exception cref="Amazon.Lambda.Model.ServiceException">
/// The AWS Lambda service encountered an internal error.
/// </exception>
/// <exception cref="Amazon.Lambda.Model.TooManyRequestsException">
/// The request throughput limit was exceeded.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lambda-2015-03-31/AddLayerVersionPermission">REST API Reference for AddLayerVersionPermission Operation</seealso>
public virtual Task<AddLayerVersionPermissionResponse> AddLayerVersionPermissionAsync(AddLayerVersionPermissionRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var options = new InvokeOptions();
options.RequestMarshaller = AddLayerVersionPermissionRequestMarshaller.Instance;
options.ResponseUnmarshaller = AddLayerVersionPermissionResponseUnmarshaller.Instance;
return InvokeAsync<AddLayerVersionPermissionResponse>(request, options, cancellationToken);
}
#endregion
#region AddPermission
internal virtual AddPermissionResponse AddPermission(AddPermissionRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = AddPermissionRequestMarshaller.Instance;
options.ResponseUnmarshaller = AddPermissionResponseUnmarshaller.Instance;
return Invoke<AddPermissionResponse>(request, options);
}
/// <summary>
/// Grants an AWS service or another account permission to use a function. You can apply
/// the policy at the function level, or specify a qualifier to restrict access to a single
/// version or alias. If you use a qualifier, the invoker must use the full Amazon Resource
/// Name (ARN) of that version or alias to invoke the function.
///
///
/// <para>
/// To grant permission to another account, specify the account ID as the <code>Principal</code>.
/// For AWS services, the principal is a domain-style identifier defined by the service,
/// like <code>s3.amazonaws.com</code> or <code>sns.amazonaws.com</code>. For AWS services,
/// you can also specify the ARN or owning account of the associated resource as the <code>SourceArn</code>
/// or <code>SourceAccount</code>. If you grant permission to a service principal without
/// specifying the source, other accounts could potentially configure resources in their
/// account to invoke your Lambda function.
/// </para>
///
/// <para>
/// This action adds a statement to a resource-based permissions policy for the function.
/// For more information about function policies, see <a href="https://docs.aws.amazon.com/lambda/latest/dg/access-control-resource-based.html">Lambda
/// Function Policies</a>.
/// </para>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the AddPermission service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the AddPermission service method, as returned by Lambda.</returns>
/// <exception cref="Amazon.Lambda.Model.InvalidParameterValueException">
/// One of the parameters in the request is invalid.
/// </exception>
/// <exception cref="Amazon.Lambda.Model.PolicyLengthExceededException">
/// The permissions policy for the resource is too large. <a href="https://docs.aws.amazon.com/lambda/latest/dg/limits.html">Learn
/// more</a>
/// </exception>
/// <exception cref="Amazon.Lambda.Model.PreconditionFailedException">
/// The RevisionId provided does not match the latest RevisionId for the Lambda function
/// or alias. Call the <code>GetFunction</code> or the <code>GetAlias</code> API to retrieve
/// the latest RevisionId for your resource.
/// </exception>
/// <exception cref="Amazon.Lambda.Model.ResourceConflictException">
/// The resource already exists, or another operation is in progress.
/// </exception>
/// <exception cref="Amazon.Lambda.Model.ResourceNotFoundException">
/// The resource specified in the request does not exist.
/// </exception>
/// <exception cref="Amazon.Lambda.Model.ServiceException">
/// The AWS Lambda service encountered an internal error.
/// </exception>
/// <exception cref="Amazon.Lambda.Model.TooManyRequestsException">
/// The request throughput limit was exceeded.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lambda-2015-03-31/AddPermission">REST API Reference for AddPermission Operation</seealso>
public virtual Task<AddPermissionResponse> AddPermissionAsync(AddPermissionRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var options = new InvokeOptions();
options.RequestMarshaller = AddPermissionRequestMarshaller.Instance;
options.ResponseUnmarshaller = AddPermissionResponseUnmarshaller.Instance;
return InvokeAsync<AddPermissionResponse>(request, options, cancellationToken);
}
#endregion
#region CreateAlias
internal virtual CreateAliasResponse CreateAlias(CreateAliasRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = CreateAliasRequestMarshaller.Instance;
options.ResponseUnmarshaller = CreateAliasResponseUnmarshaller.Instance;
return Invoke<CreateAliasResponse>(request, options);
}
/// <summary>
/// Creates an <a href="https://docs.aws.amazon.com/lambda/latest/dg/versioning-aliases.html">alias</a>
/// for a Lambda function version. Use aliases to provide clients with a function identifier
/// that you can update to invoke a different version.
///
///
/// <para>
/// You can also map an alias to split invocation requests between two versions. Use the
/// <code>RoutingConfig</code> parameter to specify a second version and the percentage
/// of invocation requests that it receives.
/// </para>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the CreateAlias service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the CreateAlias service method, as returned by Lambda.</returns>
/// <exception cref="Amazon.Lambda.Model.InvalidParameterValueException">
/// One of the parameters in the request is invalid.
/// </exception>
/// <exception cref="Amazon.Lambda.Model.ResourceConflictException">
/// The resource already exists, or another operation is in progress.
/// </exception>
/// <exception cref="Amazon.Lambda.Model.ResourceNotFoundException">
/// The resource specified in the request does not exist.
/// </exception>
/// <exception cref="Amazon.Lambda.Model.ServiceException">
/// The AWS Lambda service encountered an internal error.
/// </exception>
/// <exception cref="Amazon.Lambda.Model.TooManyRequestsException">
/// The request throughput limit was exceeded.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lambda-2015-03-31/CreateAlias">REST API Reference for CreateAlias Operation</seealso>
public virtual Task<CreateAliasResponse> CreateAliasAsync(CreateAliasRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var options = new InvokeOptions();
options.RequestMarshaller = CreateAliasRequestMarshaller.Instance;
options.ResponseUnmarshaller = CreateAliasResponseUnmarshaller.Instance;
return InvokeAsync<CreateAliasResponse>(request, options, cancellationToken);
}
#endregion
#region CreateEventSourceMapping
internal virtual CreateEventSourceMappingResponse CreateEventSourceMapping(CreateEventSourceMappingRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = CreateEventSourceMappingRequestMarshaller.Instance;
options.ResponseUnmarshaller = CreateEventSourceMappingResponseUnmarshaller.Instance;
return Invoke<CreateEventSourceMappingResponse>(request, options);
}
/// <summary>
/// Creates a mapping between an event source and an AWS Lambda function. Lambda reads
/// items from the event source and triggers the function.
///
///
/// <para>
/// For details about each event source type, see the following topics.
/// </para>
/// <ul> <li>
/// <para>
/// <a href="https://docs.aws.amazon.com/lambda/latest/dg/with-ddb.html">Using AWS Lambda
/// with Amazon DynamoDB</a>
/// </para>
/// </li> <li>
/// <para>
/// <a href="https://docs.aws.amazon.com/lambda/latest/dg/with-kinesis.html">Using AWS
/// Lambda with Amazon Kinesis</a>
/// </para>
/// </li> <li>
/// <para>
/// <a href="https://docs.aws.amazon.com/lambda/latest/dg/with-sqs.html">Using AWS Lambda
/// with Amazon SQS</a>
/// </para>
/// </li> </ul>
/// <para>
/// The following error handling options are only available for stream sources (DynamoDB
/// and Kinesis):
/// </para>
/// <ul> <li>
/// <para>
/// <code>BisectBatchOnFunctionError</code> - If the function returns an error, split
/// the batch in two and retry.
/// </para>
/// </li> <li>
/// <para>
/// <code>DestinationConfig</code> - Send discarded records to an Amazon SQS queue or
/// Amazon SNS topic.
/// </para>
/// </li> <li>
/// <para>
/// <code>MaximumRecordAgeInSeconds</code> - Discard records older than the specified
/// age.
/// </para>
/// </li> <li>
/// <para>
/// <code>MaximumRetryAttempts</code> - Discard records after the specified number of
/// retries.
/// </para>
/// </li> <li>
/// <para>
/// <code>ParallelizationFactor</code> - Process multiple batches from each shard concurrently.
/// </para>
/// </li> </ul>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the CreateEventSourceMapping service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the CreateEventSourceMapping service method, as returned by Lambda.</returns>
/// <exception cref="Amazon.Lambda.Model.InvalidParameterValueException">
/// One of the parameters in the request is invalid.
/// </exception>
/// <exception cref="Amazon.Lambda.Model.ResourceConflictException">
/// The resource already exists, or another operation is in progress.
/// </exception>
/// <exception cref="Amazon.Lambda.Model.ResourceNotFoundException">
/// The resource specified in the request does not exist.
/// </exception>
/// <exception cref="Amazon.Lambda.Model.ServiceException">
/// The AWS Lambda service encountered an internal error.
/// </exception>
/// <exception cref="Amazon.Lambda.Model.TooManyRequestsException">
/// The request throughput limit was exceeded.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lambda-2015-03-31/CreateEventSourceMapping">REST API Reference for CreateEventSourceMapping Operation</seealso>
public virtual Task<CreateEventSourceMappingResponse> CreateEventSourceMappingAsync(CreateEventSourceMappingRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var options = new InvokeOptions();
options.RequestMarshaller = CreateEventSourceMappingRequestMarshaller.Instance;
options.ResponseUnmarshaller = CreateEventSourceMappingResponseUnmarshaller.Instance;
return InvokeAsync<CreateEventSourceMappingResponse>(request, options, cancellationToken);
}
#endregion
#region CreateFunction
internal virtual CreateFunctionResponse CreateFunction(CreateFunctionRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = CreateFunctionRequestMarshaller.Instance;
options.ResponseUnmarshaller = CreateFunctionResponseUnmarshaller.Instance;
return Invoke<CreateFunctionResponse>(request, options);
}
/// <summary>
/// Creates a Lambda function. To create a function, you need a <a href="https://docs.aws.amazon.com/lambda/latest/dg/deployment-package-v2.html">deployment
/// package</a> and an <a href="https://docs.aws.amazon.com/lambda/latest/dg/intro-permission-model.html#lambda-intro-execution-role">execution
/// role</a>. The deployment package contains your function code. The execution role grants
/// the function permission to use AWS services, such as Amazon CloudWatch Logs for log
/// streaming and AWS X-Ray for request tracing.
///
///
/// <para>
/// When you create a function, Lambda provisions an instance of the function and its
/// supporting resources. If your function connects to a VPC, this process can take a
/// minute or so. During this time, you can't invoke or modify the function. The <code>State</code>,
/// <code>StateReason</code>, and <code>StateReasonCode</code> fields in the response
/// from <a>GetFunctionConfiguration</a> indicate when the function is ready to invoke.
/// For more information, see <a href="https://docs.aws.amazon.com/lambda/latest/dg/functions-states.html">Function
/// States</a>.
/// </para>
///
/// <para>
/// A function has an unpublished version, and can have published versions and aliases.
/// The unpublished version changes when you update your function's code and configuration.
/// A published version is a snapshot of your function code and configuration that can't
/// be changed. An alias is a named resource that maps to a version, and can be changed
/// to map to a different version. Use the <code>Publish</code> parameter to create version
/// <code>1</code> of your function from its initial configuration.
/// </para>
///
/// <para>
/// The other parameters let you configure version-specific and function-level settings.
/// You can modify version-specific settings later with <a>UpdateFunctionConfiguration</a>.
/// Function-level settings apply to both the unpublished and published versions of the
/// function, and include tags (<a>TagResource</a>) and per-function concurrency limits
/// (<a>PutFunctionConcurrency</a>).
/// </para>
///
/// <para>
/// If another account or an AWS service invokes your function, use <a>AddPermission</a>
/// to grant permission by creating a resource-based IAM policy. You can grant permissions
/// at the function level, on a version, or on an alias.
/// </para>
///
/// <para>
/// To invoke your function directly, use <a>Invoke</a>. To invoke your function in response
/// to events in other AWS services, create an event source mapping (<a>CreateEventSourceMapping</a>),
/// or configure a function trigger in the other service. For more information, see <a
/// href="https://docs.aws.amazon.com/lambda/latest/dg/lambda-invocation.html">Invoking
/// Functions</a>.
/// </para>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the CreateFunction service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the CreateFunction service method, as returned by Lambda.</returns>
/// <exception cref="Amazon.Lambda.Model.CodeStorageExceededException">
/// You have exceeded your maximum total code size per account. <a href="https://docs.aws.amazon.com/lambda/latest/dg/limits.html">Learn
/// more</a>
/// </exception>
/// <exception cref="Amazon.Lambda.Model.InvalidParameterValueException">
/// One of the parameters in the request is invalid.
/// </exception>
/// <exception cref="Amazon.Lambda.Model.ResourceConflictException">
/// The resource already exists, or another operation is in progress.
/// </exception>
/// <exception cref="Amazon.Lambda.Model.ResourceNotFoundException">
/// The resource specified in the request does not exist.
/// </exception>
/// <exception cref="Amazon.Lambda.Model.ServiceException">
/// The AWS Lambda service encountered an internal error.
/// </exception>
/// <exception cref="Amazon.Lambda.Model.TooManyRequestsException">
/// The request throughput limit was exceeded.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lambda-2015-03-31/CreateFunction">REST API Reference for CreateFunction Operation</seealso>
public virtual Task<CreateFunctionResponse> CreateFunctionAsync(CreateFunctionRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var options = new InvokeOptions();
options.RequestMarshaller = CreateFunctionRequestMarshaller.Instance;
options.ResponseUnmarshaller = CreateFunctionResponseUnmarshaller.Instance;
return InvokeAsync<CreateFunctionResponse>(request, options, cancellationToken);
}
#endregion
#region DeleteAlias
internal virtual DeleteAliasResponse DeleteAlias(DeleteAliasRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = DeleteAliasRequestMarshaller.Instance;
options.ResponseUnmarshaller = DeleteAliasResponseUnmarshaller.Instance;
return Invoke<DeleteAliasResponse>(request, options);
}
/// <summary>
/// Deletes a Lambda function <a href="https://docs.aws.amazon.com/lambda/latest/dg/versioning-aliases.html">alias</a>.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the DeleteAlias service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the DeleteAlias service method, as returned by Lambda.</returns>
/// <exception cref="Amazon.Lambda.Model.InvalidParameterValueException">
/// One of the parameters in the request is invalid.
/// </exception>
/// <exception cref="Amazon.Lambda.Model.ResourceConflictException">
/// The resource already exists, or another operation is in progress.
/// </exception>
/// <exception cref="Amazon.Lambda.Model.ServiceException">
/// The AWS Lambda service encountered an internal error.
/// </exception>
/// <exception cref="Amazon.Lambda.Model.TooManyRequestsException">
/// The request throughput limit was exceeded.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lambda-2015-03-31/DeleteAlias">REST API Reference for DeleteAlias Operation</seealso>
public virtual Task<DeleteAliasResponse> DeleteAliasAsync(DeleteAliasRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var options = new InvokeOptions();
options.RequestMarshaller = DeleteAliasRequestMarshaller.Instance;
options.ResponseUnmarshaller = DeleteAliasResponseUnmarshaller.Instance;
return InvokeAsync<DeleteAliasResponse>(request, options, cancellationToken);
}
#endregion
#region DeleteEventSourceMapping
internal virtual DeleteEventSourceMappingResponse DeleteEventSourceMapping(DeleteEventSourceMappingRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = DeleteEventSourceMappingRequestMarshaller.Instance;
options.ResponseUnmarshaller = DeleteEventSourceMappingResponseUnmarshaller.Instance;
return Invoke<DeleteEventSourceMappingResponse>(request, options);
}
/// <summary>
/// Deletes an <a href="https://docs.aws.amazon.com/lambda/latest/dg/intro-invocation-modes.html">event
/// source mapping</a>. You can get the identifier of a mapping from the output of <a>ListEventSourceMappings</a>.
///
///
/// <para>
/// When you delete an event source mapping, it enters a <code>Deleting</code> state and
/// might not be completely deleted for several seconds.
/// </para>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the DeleteEventSourceMapping service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the DeleteEventSourceMapping service method, as returned by Lambda.</returns>
/// <exception cref="Amazon.Lambda.Model.InvalidParameterValueException">
/// One of the parameters in the request is invalid.
/// </exception>
/// <exception cref="Amazon.Lambda.Model.ResourceInUseException">
/// The operation conflicts with the resource's availability. For example, you attempted
/// to update an EventSource Mapping in CREATING, or tried to delete a EventSource mapping
/// currently in the UPDATING state.
/// </exception>
/// <exception cref="Amazon.Lambda.Model.ResourceNotFoundException">
/// The resource specified in the request does not exist.
/// </exception>
/// <exception cref="Amazon.Lambda.Model.ServiceException">
/// The AWS Lambda service encountered an internal error.
/// </exception>
/// <exception cref="Amazon.Lambda.Model.TooManyRequestsException">
/// The request throughput limit was exceeded.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lambda-2015-03-31/DeleteEventSourceMapping">REST API Reference for DeleteEventSourceMapping Operation</seealso>
public virtual Task<DeleteEventSourceMappingResponse> DeleteEventSourceMappingAsync(DeleteEventSourceMappingRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var options = new InvokeOptions();
options.RequestMarshaller = DeleteEventSourceMappingRequestMarshaller.Instance;
options.ResponseUnmarshaller = DeleteEventSourceMappingResponseUnmarshaller.Instance;
return InvokeAsync<DeleteEventSourceMappingResponse>(request, options, cancellationToken);
}
#endregion
#region DeleteFunction
internal virtual DeleteFunctionResponse DeleteFunction(DeleteFunctionRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = DeleteFunctionRequestMarshaller.Instance;
options.ResponseUnmarshaller = DeleteFunctionResponseUnmarshaller.Instance;
return Invoke<DeleteFunctionResponse>(request, options);
}
/// <summary>
/// Deletes a Lambda function. To delete a specific function version, use the <code>Qualifier</code>
/// parameter. Otherwise, all versions and aliases are deleted.
///
///
/// <para>
/// To delete Lambda event source mappings that invoke a function, use <a>DeleteEventSourceMapping</a>.
/// For AWS services and resources that invoke your function directly, delete the trigger
/// in the service where you originally configured it.
/// </para>
/// </summary>
/// <param name="functionName">The name of the Lambda function or version. <p class="title"> <b>Name formats</b> <ul> <li> <b>Function name</b> - <code>my-function</code> (name-only), <code>my-function:1</code> (with version). </li> <li> <b>Function ARN</b> - <code>arn:aws:lambda:us-west-2:123456789012:function:my-function</code>. </li> <li> <b>Partial ARN</b> - <code>123456789012:function:my-function</code>. </li> </ul> You can append a version number or alias to any of the formats. The length constraint applies only to the full ARN. If you specify only the function name, it is limited to 64 characters in length.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the DeleteFunction service method, as returned by Lambda.</returns>
/// <exception cref="Amazon.Lambda.Model.InvalidParameterValueException">
/// One of the parameters in the request is invalid.
/// </exception>
/// <exception cref="Amazon.Lambda.Model.ResourceConflictException">
/// The resource already exists, or another operation is in progress.
/// </exception>
/// <exception cref="Amazon.Lambda.Model.ResourceNotFoundException">
/// The resource specified in the request does not exist.
/// </exception>
/// <exception cref="Amazon.Lambda.Model.ServiceException">
/// The AWS Lambda service encountered an internal error.
/// </exception>
/// <exception cref="Amazon.Lambda.Model.TooManyRequestsException">
/// The request throughput limit was exceeded.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lambda-2015-03-31/DeleteFunction">REST API Reference for DeleteFunction Operation</seealso>
public virtual Task<DeleteFunctionResponse> DeleteFunctionAsync(string functionName, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var request = new DeleteFunctionRequest();
request.FunctionName = functionName;
return DeleteFunctionAsync(request, cancellationToken);
}
/// <summary>
/// Deletes a Lambda function. To delete a specific function version, use the <code>Qualifier</code>
/// parameter. Otherwise, all versions and aliases are deleted.
///
///
/// <para>
/// To delete Lambda event source mappings that invoke a function, use <a>DeleteEventSourceMapping</a>.
/// For AWS services and resources that invoke your function directly, delete the trigger
/// in the service where you originally configured it.
/// </para>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the DeleteFunction service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the DeleteFunction service method, as returned by Lambda.</returns>
/// <exception cref="Amazon.Lambda.Model.InvalidParameterValueException">
/// One of the parameters in the request is invalid.
/// </exception>
/// <exception cref="Amazon.Lambda.Model.ResourceConflictException">
/// The resource already exists, or another operation is in progress.
/// </exception>
/// <exception cref="Amazon.Lambda.Model.ResourceNotFoundException">
/// The resource specified in the request does not exist.
/// </exception>
/// <exception cref="Amazon.Lambda.Model.ServiceException">
/// The AWS Lambda service encountered an internal error.
/// </exception>
/// <exception cref="Amazon.Lambda.Model.TooManyRequestsException">
/// The request throughput limit was exceeded.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lambda-2015-03-31/DeleteFunction">REST API Reference for DeleteFunction Operation</seealso>
public virtual Task<DeleteFunctionResponse> DeleteFunctionAsync(DeleteFunctionRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var options = new InvokeOptions();
options.RequestMarshaller = DeleteFunctionRequestMarshaller.Instance;
options.ResponseUnmarshaller = DeleteFunctionResponseUnmarshaller.Instance;
return InvokeAsync<DeleteFunctionResponse>(request, options, cancellationToken);
}
#endregion
#region DeleteFunctionConcurrency
internal virtual DeleteFunctionConcurrencyResponse DeleteFunctionConcurrency(DeleteFunctionConcurrencyRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = DeleteFunctionConcurrencyRequestMarshaller.Instance;
options.ResponseUnmarshaller = DeleteFunctionConcurrencyResponseUnmarshaller.Instance;
return Invoke<DeleteFunctionConcurrencyResponse>(request, options);
}
/// <summary>
/// Removes a concurrent execution limit from a function.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the DeleteFunctionConcurrency service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the DeleteFunctionConcurrency service method, as returned by Lambda.</returns>
/// <exception cref="Amazon.Lambda.Model.InvalidParameterValueException">
/// One of the parameters in the request is invalid.
/// </exception>
/// <exception cref="Amazon.Lambda.Model.ResourceConflictException">
/// The resource already exists, or another operation is in progress.
/// </exception>
/// <exception cref="Amazon.Lambda.Model.ResourceNotFoundException">
/// The resource specified in the request does not exist.
/// </exception>
/// <exception cref="Amazon.Lambda.Model.ServiceException">
/// The AWS Lambda service encountered an internal error.
/// </exception>
/// <exception cref="Amazon.Lambda.Model.TooManyRequestsException">
/// The request throughput limit was exceeded.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lambda-2015-03-31/DeleteFunctionConcurrency">REST API Reference for DeleteFunctionConcurrency Operation</seealso>
public virtual Task<DeleteFunctionConcurrencyResponse> DeleteFunctionConcurrencyAsync(DeleteFunctionConcurrencyRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var options = new InvokeOptions();
options.RequestMarshaller = DeleteFunctionConcurrencyRequestMarshaller.Instance;
options.ResponseUnmarshaller = DeleteFunctionConcurrencyResponseUnmarshaller.Instance;
return InvokeAsync<DeleteFunctionConcurrencyResponse>(request, options, cancellationToken);
}
#endregion
#region DeleteFunctionEventInvokeConfig
internal virtual DeleteFunctionEventInvokeConfigResponse DeleteFunctionEventInvokeConfig(DeleteFunctionEventInvokeConfigRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = DeleteFunctionEventInvokeConfigRequestMarshaller.Instance;
options.ResponseUnmarshaller = DeleteFunctionEventInvokeConfigResponseUnmarshaller.Instance;
return Invoke<DeleteFunctionEventInvokeConfigResponse>(request, options);
}
/// <summary>
/// Deletes the configuration for asynchronous invocation for a function, version, or
/// alias.
///
///
/// <para>
/// To configure options for asynchronous invocation, use <a>PutFunctionEventInvokeConfig</a>.
/// </para>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the DeleteFunctionEventInvokeConfig service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the DeleteFunctionEventInvokeConfig service method, as returned by Lambda.</returns>
/// <exception cref="Amazon.Lambda.Model.InvalidParameterValueException">
/// One of the parameters in the request is invalid.
/// </exception>
/// <exception cref="Amazon.Lambda.Model.ResourceNotFoundException">
/// The resource specified in the request does not exist.
/// </exception>
/// <exception cref="Amazon.Lambda.Model.ServiceException">
/// The AWS Lambda service encountered an internal error.
/// </exception>
/// <exception cref="Amazon.Lambda.Model.TooManyRequestsException">
/// The request throughput limit was exceeded.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lambda-2015-03-31/DeleteFunctionEventInvokeConfig">REST API Reference for DeleteFunctionEventInvokeConfig Operation</seealso>
public virtual Task<DeleteFunctionEventInvokeConfigResponse> DeleteFunctionEventInvokeConfigAsync(DeleteFunctionEventInvokeConfigRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var options = new InvokeOptions();
options.RequestMarshaller = DeleteFunctionEventInvokeConfigRequestMarshaller.Instance;
options.ResponseUnmarshaller = DeleteFunctionEventInvokeConfigResponseUnmarshaller.Instance;
return InvokeAsync<DeleteFunctionEventInvokeConfigResponse>(request, options, cancellationToken);
}
#endregion
#region DeleteLayerVersion
internal virtual DeleteLayerVersionResponse DeleteLayerVersion(DeleteLayerVersionRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = DeleteLayerVersionRequestMarshaller.Instance;
options.ResponseUnmarshaller = DeleteLayerVersionResponseUnmarshaller.Instance;
return Invoke<DeleteLayerVersionResponse>(request, options);
}
/// <summary>
/// Deletes a version of an <a href="https://docs.aws.amazon.com/lambda/latest/dg/configuration-layers.html">AWS
/// Lambda layer</a>. Deleted versions can no longer be viewed or added to functions.
/// To avoid breaking functions, a copy of the version remains in Lambda until no functions
/// refer to it.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the DeleteLayerVersion service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the DeleteLayerVersion service method, as returned by Lambda.</returns>
/// <exception cref="Amazon.Lambda.Model.ServiceException">
/// The AWS Lambda service encountered an internal error.
/// </exception>
/// <exception cref="Amazon.Lambda.Model.TooManyRequestsException">
/// The request throughput limit was exceeded.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lambda-2015-03-31/DeleteLayerVersion">REST API Reference for DeleteLayerVersion Operation</seealso>
public virtual Task<DeleteLayerVersionResponse> DeleteLayerVersionAsync(DeleteLayerVersionRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var options = new InvokeOptions();
options.RequestMarshaller = DeleteLayerVersionRequestMarshaller.Instance;
options.ResponseUnmarshaller = DeleteLayerVersionResponseUnmarshaller.Instance;
return InvokeAsync<DeleteLayerVersionResponse>(request, options, cancellationToken);
}
#endregion
#region DeleteProvisionedConcurrencyConfig
internal virtual DeleteProvisionedConcurrencyConfigResponse DeleteProvisionedConcurrencyConfig(DeleteProvisionedConcurrencyConfigRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = DeleteProvisionedConcurrencyConfigRequestMarshaller.Instance;
options.ResponseUnmarshaller = DeleteProvisionedConcurrencyConfigResponseUnmarshaller.Instance;
return Invoke<DeleteProvisionedConcurrencyConfigResponse>(request, options);
}
/// <summary>
/// Deletes the provisioned concurrency configuration for a function.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the DeleteProvisionedConcurrencyConfig service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the DeleteProvisionedConcurrencyConfig service method, as returned by Lambda.</returns>
/// <exception cref="Amazon.Lambda.Model.InvalidParameterValueException">
/// One of the parameters in the request is invalid.
/// </exception>
/// <exception cref="Amazon.Lambda.Model.ResourceConflictException">
/// The resource already exists, or another operation is in progress.
/// </exception>
/// <exception cref="Amazon.Lambda.Model.ResourceNotFoundException">
/// The resource specified in the request does not exist.
/// </exception>
/// <exception cref="Amazon.Lambda.Model.ServiceException">
/// The AWS Lambda service encountered an internal error.
/// </exception>
/// <exception cref="Amazon.Lambda.Model.TooManyRequestsException">
/// The request throughput limit was exceeded.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lambda-2015-03-31/DeleteProvisionedConcurrencyConfig">REST API Reference for DeleteProvisionedConcurrencyConfig Operation</seealso>
public virtual Task<DeleteProvisionedConcurrencyConfigResponse> DeleteProvisionedConcurrencyConfigAsync(DeleteProvisionedConcurrencyConfigRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var options = new InvokeOptions();
options.RequestMarshaller = DeleteProvisionedConcurrencyConfigRequestMarshaller.Instance;
options.ResponseUnmarshaller = DeleteProvisionedConcurrencyConfigResponseUnmarshaller.Instance;
return InvokeAsync<DeleteProvisionedConcurrencyConfigResponse>(request, options, cancellationToken);
}
#endregion
#region GetAccountSettings
internal virtual GetAccountSettingsResponse GetAccountSettings(GetAccountSettingsRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = GetAccountSettingsRequestMarshaller.Instance;
options.ResponseUnmarshaller = GetAccountSettingsResponseUnmarshaller.Instance;
return Invoke<GetAccountSettingsResponse>(request, options);
}
/// <summary>
/// Retrieves details about your account's <a href="https://docs.aws.amazon.com/lambda/latest/dg/limits.html">limits</a>
/// and usage in an AWS Region.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the GetAccountSettings service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the GetAccountSettings service method, as returned by Lambda.</returns>
/// <exception cref="Amazon.Lambda.Model.ServiceException">
/// The AWS Lambda service encountered an internal error.
/// </exception>
/// <exception cref="Amazon.Lambda.Model.TooManyRequestsException">
/// The request throughput limit was exceeded.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lambda-2015-03-31/GetAccountSettings">REST API Reference for GetAccountSettings Operation</seealso>
public virtual Task<GetAccountSettingsResponse> GetAccountSettingsAsync(GetAccountSettingsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var options = new InvokeOptions();
options.RequestMarshaller = GetAccountSettingsRequestMarshaller.Instance;
options.ResponseUnmarshaller = GetAccountSettingsResponseUnmarshaller.Instance;
return InvokeAsync<GetAccountSettingsResponse>(request, options, cancellationToken);
}
#endregion
#region GetAlias
internal virtual GetAliasResponse GetAlias(GetAliasRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = GetAliasRequestMarshaller.Instance;
options.ResponseUnmarshaller = GetAliasResponseUnmarshaller.Instance;
return Invoke<GetAliasResponse>(request, options);
}
/// <summary>
/// Returns details about a Lambda function <a href="https://docs.aws.amazon.com/lambda/latest/dg/versioning-aliases.html">alias</a>.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the GetAlias service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the GetAlias service method, as returned by Lambda.</returns>
/// <exception cref="Amazon.Lambda.Model.InvalidParameterValueException">
/// One of the parameters in the request is invalid.
/// </exception>
/// <exception cref="Amazon.Lambda.Model.ResourceNotFoundException">
/// The resource specified in the request does not exist.
/// </exception>
/// <exception cref="Amazon.Lambda.Model.ServiceException">
/// The AWS Lambda service encountered an internal error.
/// </exception>
/// <exception cref="Amazon.Lambda.Model.TooManyRequestsException">
/// The request throughput limit was exceeded.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lambda-2015-03-31/GetAlias">REST API Reference for GetAlias Operation</seealso>
public virtual Task<GetAliasResponse> GetAliasAsync(GetAliasRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var options = new InvokeOptions();
options.RequestMarshaller = GetAliasRequestMarshaller.Instance;
options.ResponseUnmarshaller = GetAliasResponseUnmarshaller.Instance;
return InvokeAsync<GetAliasResponse>(request, options, cancellationToken);
}
#endregion
#region GetEventSourceMapping
internal virtual GetEventSourceMappingResponse GetEventSourceMapping(GetEventSourceMappingRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = GetEventSourceMappingRequestMarshaller.Instance;
options.ResponseUnmarshaller = GetEventSourceMappingResponseUnmarshaller.Instance;
return Invoke<GetEventSourceMappingResponse>(request, options);
}
/// <summary>
/// Returns details about an event source mapping. You can get the identifier of a mapping
/// from the output of <a>ListEventSourceMappings</a>.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the GetEventSourceMapping service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the GetEventSourceMapping service method, as returned by Lambda.</returns>
/// <exception cref="Amazon.Lambda.Model.InvalidParameterValueException">
/// One of the parameters in the request is invalid.
/// </exception>
/// <exception cref="Amazon.Lambda.Model.ResourceNotFoundException">
/// The resource specified in the request does not exist.
/// </exception>
/// <exception cref="Amazon.Lambda.Model.ServiceException">
/// The AWS Lambda service encountered an internal error.
/// </exception>
/// <exception cref="Amazon.Lambda.Model.TooManyRequestsException">
/// The request throughput limit was exceeded.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lambda-2015-03-31/GetEventSourceMapping">REST API Reference for GetEventSourceMapping Operation</seealso>
public virtual Task<GetEventSourceMappingResponse> GetEventSourceMappingAsync(GetEventSourceMappingRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var options = new InvokeOptions();
options.RequestMarshaller = GetEventSourceMappingRequestMarshaller.Instance;
options.ResponseUnmarshaller = GetEventSourceMappingResponseUnmarshaller.Instance;
return InvokeAsync<GetEventSourceMappingResponse>(request, options, cancellationToken);
}
#endregion
#region GetFunction
internal virtual GetFunctionResponse GetFunction(GetFunctionRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = GetFunctionRequestMarshaller.Instance;
options.ResponseUnmarshaller = GetFunctionResponseUnmarshaller.Instance;
return Invoke<GetFunctionResponse>(request, options);
}
/// <summary>
/// Returns information about the function or function version, with a link to download
/// the deployment package that's valid for 10 minutes. If you specify a function version,
/// only details that are specific to that version are returned.
/// </summary>
/// <param name="functionName">The name of the Lambda function, version, or alias. <p class="title"> <b>Name formats</b> <ul> <li> <b>Function name</b> - <code>my-function</code> (name-only), <code>my-function:v1</code> (with alias). </li> <li> <b>Function ARN</b> - <code>arn:aws:lambda:us-west-2:123456789012:function:my-function</code>. </li> <li> <b>Partial ARN</b> - <code>123456789012:function:my-function</code>. </li> </ul> You can append a version number or alias to any of the formats. The length constraint applies only to the full ARN. If you specify only the function name, it is limited to 64 characters in length.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the GetFunction service method, as returned by Lambda.</returns>
/// <exception cref="Amazon.Lambda.Model.InvalidParameterValueException">
/// One of the parameters in the request is invalid.
/// </exception>
/// <exception cref="Amazon.Lambda.Model.ResourceNotFoundException">
/// The resource specified in the request does not exist.
/// </exception>
/// <exception cref="Amazon.Lambda.Model.ServiceException">
/// The AWS Lambda service encountered an internal error.
/// </exception>
/// <exception cref="Amazon.Lambda.Model.TooManyRequestsException">
/// The request throughput limit was exceeded.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lambda-2015-03-31/GetFunction">REST API Reference for GetFunction Operation</seealso>
public virtual Task<GetFunctionResponse> GetFunctionAsync(string functionName, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var request = new GetFunctionRequest();
request.FunctionName = functionName;
return GetFunctionAsync(request, cancellationToken);
}
/// <summary>
/// Returns information about the function or function version, with a link to download
/// the deployment package that's valid for 10 minutes. If you specify a function version,
/// only details that are specific to that version are returned.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the GetFunction service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the GetFunction service method, as returned by Lambda.</returns>
/// <exception cref="Amazon.Lambda.Model.InvalidParameterValueException">
/// One of the parameters in the request is invalid.
/// </exception>
/// <exception cref="Amazon.Lambda.Model.ResourceNotFoundException">
/// The resource specified in the request does not exist.
/// </exception>
/// <exception cref="Amazon.Lambda.Model.ServiceException">
/// The AWS Lambda service encountered an internal error.
/// </exception>
/// <exception cref="Amazon.Lambda.Model.TooManyRequestsException">
/// The request throughput limit was exceeded.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lambda-2015-03-31/GetFunction">REST API Reference for GetFunction Operation</seealso>
public virtual Task<GetFunctionResponse> GetFunctionAsync(GetFunctionRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var options = new InvokeOptions();
options.RequestMarshaller = GetFunctionRequestMarshaller.Instance;
options.ResponseUnmarshaller = GetFunctionResponseUnmarshaller.Instance;
return InvokeAsync<GetFunctionResponse>(request, options, cancellationToken);
}
#endregion
#region GetFunctionConcurrency
internal virtual GetFunctionConcurrencyResponse GetFunctionConcurrency(GetFunctionConcurrencyRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = GetFunctionConcurrencyRequestMarshaller.Instance;
options.ResponseUnmarshaller = GetFunctionConcurrencyResponseUnmarshaller.Instance;
return Invoke<GetFunctionConcurrencyResponse>(request, options);
}
/// <summary>
/// Returns details about the reserved concurrency configuration for a function. To set
/// a concurrency limit for a function, use <a>PutFunctionConcurrency</a>.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the GetFunctionConcurrency service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the GetFunctionConcurrency service method, as returned by Lambda.</returns>
/// <exception cref="Amazon.Lambda.Model.InvalidParameterValueException">
/// One of the parameters in the request is invalid.
/// </exception>
/// <exception cref="Amazon.Lambda.Model.ResourceNotFoundException">
/// The resource specified in the request does not exist.
/// </exception>
/// <exception cref="Amazon.Lambda.Model.ServiceException">
/// The AWS Lambda service encountered an internal error.
/// </exception>
/// <exception cref="Amazon.Lambda.Model.TooManyRequestsException">
/// The request throughput limit was exceeded.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lambda-2015-03-31/GetFunctionConcurrency">REST API Reference for GetFunctionConcurrency Operation</seealso>
public virtual Task<GetFunctionConcurrencyResponse> GetFunctionConcurrencyAsync(GetFunctionConcurrencyRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var options = new InvokeOptions();
options.RequestMarshaller = GetFunctionConcurrencyRequestMarshaller.Instance;
options.ResponseUnmarshaller = GetFunctionConcurrencyResponseUnmarshaller.Instance;
return InvokeAsync<GetFunctionConcurrencyResponse>(request, options, cancellationToken);
}
#endregion
#region GetFunctionConfiguration
internal virtual GetFunctionConfigurationResponse GetFunctionConfiguration(GetFunctionConfigurationRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = GetFunctionConfigurationRequestMarshaller.Instance;
options.ResponseUnmarshaller = GetFunctionConfigurationResponseUnmarshaller.Instance;
return Invoke<GetFunctionConfigurationResponse>(request, options);
}
/// <summary>
/// Returns the version-specific settings of a Lambda function or version. The output
/// includes only options that can vary between versions of a function. To modify these
/// settings, use <a>UpdateFunctionConfiguration</a>.
///
///
/// <para>
/// To get all of a function's details, including function-level settings, use <a>GetFunction</a>.
/// </para>
/// </summary>
/// <param name="functionName">The name of the Lambda function, version, or alias. <p class="title"> <b>Name formats</b> <ul> <li> <b>Function name</b> - <code>my-function</code> (name-only), <code>my-function:v1</code> (with alias). </li> <li> <b>Function ARN</b> - <code>arn:aws:lambda:us-west-2:123456789012:function:my-function</code>. </li> <li> <b>Partial ARN</b> - <code>123456789012:function:my-function</code>. </li> </ul> You can append a version number or alias to any of the formats. The length constraint applies only to the full ARN. If you specify only the function name, it is limited to 64 characters in length.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the GetFunctionConfiguration service method, as returned by Lambda.</returns>
/// <exception cref="Amazon.Lambda.Model.InvalidParameterValueException">
/// One of the parameters in the request is invalid.
/// </exception>
/// <exception cref="Amazon.Lambda.Model.ResourceNotFoundException">
/// The resource specified in the request does not exist.
/// </exception>
/// <exception cref="Amazon.Lambda.Model.ServiceException">
/// The AWS Lambda service encountered an internal error.
/// </exception>
/// <exception cref="Amazon.Lambda.Model.TooManyRequestsException">
/// The request throughput limit was exceeded.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lambda-2015-03-31/GetFunctionConfiguration">REST API Reference for GetFunctionConfiguration Operation</seealso>
public virtual Task<GetFunctionConfigurationResponse> GetFunctionConfigurationAsync(string functionName, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var request = new GetFunctionConfigurationRequest();
request.FunctionName = functionName;
return GetFunctionConfigurationAsync(request, cancellationToken);
}
/// <summary>
/// Returns the version-specific settings of a Lambda function or version. The output
/// includes only options that can vary between versions of a function. To modify these
/// settings, use <a>UpdateFunctionConfiguration</a>.
///
///
/// <para>
/// To get all of a function's details, including function-level settings, use <a>GetFunction</a>.
/// </para>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the GetFunctionConfiguration service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the GetFunctionConfiguration service method, as returned by Lambda.</returns>
/// <exception cref="Amazon.Lambda.Model.InvalidParameterValueException">
/// One of the parameters in the request is invalid.
/// </exception>
/// <exception cref="Amazon.Lambda.Model.ResourceNotFoundException">
/// The resource specified in the request does not exist.
/// </exception>
/// <exception cref="Amazon.Lambda.Model.ServiceException">
/// The AWS Lambda service encountered an internal error.
/// </exception>
/// <exception cref="Amazon.Lambda.Model.TooManyRequestsException">
/// The request throughput limit was exceeded.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lambda-2015-03-31/GetFunctionConfiguration">REST API Reference for GetFunctionConfiguration Operation</seealso>
public virtual Task<GetFunctionConfigurationResponse> GetFunctionConfigurationAsync(GetFunctionConfigurationRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var options = new InvokeOptions();
options.RequestMarshaller = GetFunctionConfigurationRequestMarshaller.Instance;
options.ResponseUnmarshaller = GetFunctionConfigurationResponseUnmarshaller.Instance;
return InvokeAsync<GetFunctionConfigurationResponse>(request, options, cancellationToken);
}
#endregion
#region GetFunctionEventInvokeConfig
internal virtual GetFunctionEventInvokeConfigResponse GetFunctionEventInvokeConfig(GetFunctionEventInvokeConfigRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = GetFunctionEventInvokeConfigRequestMarshaller.Instance;
options.ResponseUnmarshaller = GetFunctionEventInvokeConfigResponseUnmarshaller.Instance;
return Invoke<GetFunctionEventInvokeConfigResponse>(request, options);
}
/// <summary>
/// Retrieves the configuration for asynchronous invocation for a function, version, or
/// alias.
///
///
/// <para>
/// To configure options for asynchronous invocation, use <a>PutFunctionEventInvokeConfig</a>.
/// </para>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the GetFunctionEventInvokeConfig service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the GetFunctionEventInvokeConfig service method, as returned by Lambda.</returns>
/// <exception cref="Amazon.Lambda.Model.InvalidParameterValueException">
/// One of the parameters in the request is invalid.
/// </exception>
/// <exception cref="Amazon.Lambda.Model.ResourceNotFoundException">
/// The resource specified in the request does not exist.
/// </exception>
/// <exception cref="Amazon.Lambda.Model.ServiceException">
/// The AWS Lambda service encountered an internal error.
/// </exception>
/// <exception cref="Amazon.Lambda.Model.TooManyRequestsException">
/// The request throughput limit was exceeded.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lambda-2015-03-31/GetFunctionEventInvokeConfig">REST API Reference for GetFunctionEventInvokeConfig Operation</seealso>
public virtual Task<GetFunctionEventInvokeConfigResponse> GetFunctionEventInvokeConfigAsync(GetFunctionEventInvokeConfigRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var options = new InvokeOptions();
options.RequestMarshaller = GetFunctionEventInvokeConfigRequestMarshaller.Instance;
options.ResponseUnmarshaller = GetFunctionEventInvokeConfigResponseUnmarshaller.Instance;
return InvokeAsync<GetFunctionEventInvokeConfigResponse>(request, options, cancellationToken);
}
#endregion
#region GetLayerVersion
internal virtual GetLayerVersionResponse GetLayerVersion(GetLayerVersionRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = GetLayerVersionRequestMarshaller.Instance;
options.ResponseUnmarshaller = GetLayerVersionResponseUnmarshaller.Instance;
return Invoke<GetLayerVersionResponse>(request, options);
}
/// <summary>
/// Returns information about a version of an <a href="https://docs.aws.amazon.com/lambda/latest/dg/configuration-layers.html">AWS
/// Lambda layer</a>, with a link to download the layer archive that's valid for 10 minutes.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the GetLayerVersion service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the GetLayerVersion service method, as returned by Lambda.</returns>
/// <exception cref="Amazon.Lambda.Model.InvalidParameterValueException">
/// One of the parameters in the request is invalid.
/// </exception>
/// <exception cref="Amazon.Lambda.Model.ResourceNotFoundException">
/// The resource specified in the request does not exist.
/// </exception>
/// <exception cref="Amazon.Lambda.Model.ServiceException">
/// The AWS Lambda service encountered an internal error.
/// </exception>
/// <exception cref="Amazon.Lambda.Model.TooManyRequestsException">
/// The request throughput limit was exceeded.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lambda-2015-03-31/GetLayerVersion">REST API Reference for GetLayerVersion Operation</seealso>
public virtual Task<GetLayerVersionResponse> GetLayerVersionAsync(GetLayerVersionRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var options = new InvokeOptions();
options.RequestMarshaller = GetLayerVersionRequestMarshaller.Instance;
options.ResponseUnmarshaller = GetLayerVersionResponseUnmarshaller.Instance;
return InvokeAsync<GetLayerVersionResponse>(request, options, cancellationToken);
}
#endregion
#region GetLayerVersionByArn
internal virtual GetLayerVersionByArnResponse GetLayerVersionByArn(GetLayerVersionByArnRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = GetLayerVersionByArnRequestMarshaller.Instance;
options.ResponseUnmarshaller = GetLayerVersionByArnResponseUnmarshaller.Instance;
return Invoke<GetLayerVersionByArnResponse>(request, options);
}
/// <summary>
/// Returns information about a version of an <a href="https://docs.aws.amazon.com/lambda/latest/dg/configuration-layers.html">AWS
/// Lambda layer</a>, with a link to download the layer archive that's valid for 10 minutes.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the GetLayerVersionByArn service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the GetLayerVersionByArn service method, as returned by Lambda.</returns>
/// <exception cref="Amazon.Lambda.Model.InvalidParameterValueException">
/// One of the parameters in the request is invalid.
/// </exception>
/// <exception cref="Amazon.Lambda.Model.ResourceNotFoundException">
/// The resource specified in the request does not exist.
/// </exception>
/// <exception cref="Amazon.Lambda.Model.ServiceException">
/// The AWS Lambda service encountered an internal error.
/// </exception>
/// <exception cref="Amazon.Lambda.Model.TooManyRequestsException">
/// The request throughput limit was exceeded.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lambda-2015-03-31/GetLayerVersionByArn">REST API Reference for GetLayerVersionByArn Operation</seealso>
public virtual Task<GetLayerVersionByArnResponse> GetLayerVersionByArnAsync(GetLayerVersionByArnRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var options = new InvokeOptions();
options.RequestMarshaller = GetLayerVersionByArnRequestMarshaller.Instance;
options.ResponseUnmarshaller = GetLayerVersionByArnResponseUnmarshaller.Instance;
return InvokeAsync<GetLayerVersionByArnResponse>(request, options, cancellationToken);
}
#endregion
#region GetLayerVersionPolicy
internal virtual GetLayerVersionPolicyResponse GetLayerVersionPolicy(GetLayerVersionPolicyRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = GetLayerVersionPolicyRequestMarshaller.Instance;
options.ResponseUnmarshaller = GetLayerVersionPolicyResponseUnmarshaller.Instance;
return Invoke<GetLayerVersionPolicyResponse>(request, options);
}
/// <summary>
/// Returns the permission policy for a version of an <a href="https://docs.aws.amazon.com/lambda/latest/dg/configuration-layers.html">AWS
/// Lambda layer</a>. For more information, see <a>AddLayerVersionPermission</a>.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the GetLayerVersionPolicy service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the GetLayerVersionPolicy service method, as returned by Lambda.</returns>
/// <exception cref="Amazon.Lambda.Model.InvalidParameterValueException">
/// One of the parameters in the request is invalid.
/// </exception>
/// <exception cref="Amazon.Lambda.Model.ResourceNotFoundException">
/// The resource specified in the request does not exist.
/// </exception>
/// <exception cref="Amazon.Lambda.Model.ServiceException">
/// The AWS Lambda service encountered an internal error.
/// </exception>
/// <exception cref="Amazon.Lambda.Model.TooManyRequestsException">
/// The request throughput limit was exceeded.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lambda-2015-03-31/GetLayerVersionPolicy">REST API Reference for GetLayerVersionPolicy Operation</seealso>
public virtual Task<GetLayerVersionPolicyResponse> GetLayerVersionPolicyAsync(GetLayerVersionPolicyRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var options = new InvokeOptions();
options.RequestMarshaller = GetLayerVersionPolicyRequestMarshaller.Instance;
options.ResponseUnmarshaller = GetLayerVersionPolicyResponseUnmarshaller.Instance;
return InvokeAsync<GetLayerVersionPolicyResponse>(request, options, cancellationToken);
}
#endregion
#region GetPolicy
internal virtual GetPolicyResponse GetPolicy(GetPolicyRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = GetPolicyRequestMarshaller.Instance;
options.ResponseUnmarshaller = GetPolicyResponseUnmarshaller.Instance;
return Invoke<GetPolicyResponse>(request, options);
}
/// <summary>
/// Returns the <a href="https://docs.aws.amazon.com/lambda/latest/dg/access-control-resource-based.html">resource-based
/// IAM policy</a> for a function, version, or alias.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the GetPolicy service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the GetPolicy service method, as returned by Lambda.</returns>
/// <exception cref="Amazon.Lambda.Model.InvalidParameterValueException">
/// One of the parameters in the request is invalid.
/// </exception>
/// <exception cref="Amazon.Lambda.Model.ResourceNotFoundException">
/// The resource specified in the request does not exist.
/// </exception>
/// <exception cref="Amazon.Lambda.Model.ServiceException">
/// The AWS Lambda service encountered an internal error.
/// </exception>
/// <exception cref="Amazon.Lambda.Model.TooManyRequestsException">
/// The request throughput limit was exceeded.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lambda-2015-03-31/GetPolicy">REST API Reference for GetPolicy Operation</seealso>
public virtual Task<GetPolicyResponse> GetPolicyAsync(GetPolicyRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var options = new InvokeOptions();
options.RequestMarshaller = GetPolicyRequestMarshaller.Instance;
options.ResponseUnmarshaller = GetPolicyResponseUnmarshaller.Instance;
return InvokeAsync<GetPolicyResponse>(request, options, cancellationToken);
}
#endregion
#region GetProvisionedConcurrencyConfig
internal virtual GetProvisionedConcurrencyConfigResponse GetProvisionedConcurrencyConfig(GetProvisionedConcurrencyConfigRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = GetProvisionedConcurrencyConfigRequestMarshaller.Instance;
options.ResponseUnmarshaller = GetProvisionedConcurrencyConfigResponseUnmarshaller.Instance;
return Invoke<GetProvisionedConcurrencyConfigResponse>(request, options);
}
/// <summary>
/// Retrieves the provisioned concurrency configuration for a function's alias or version.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the GetProvisionedConcurrencyConfig service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the GetProvisionedConcurrencyConfig service method, as returned by Lambda.</returns>
/// <exception cref="Amazon.Lambda.Model.InvalidParameterValueException">
/// One of the parameters in the request is invalid.
/// </exception>
/// <exception cref="Amazon.Lambda.Model.ProvisionedConcurrencyConfigNotFoundException">
/// The specified configuration does not exist.
/// </exception>
/// <exception cref="Amazon.Lambda.Model.ResourceNotFoundException">
/// The resource specified in the request does not exist.
/// </exception>
/// <exception cref="Amazon.Lambda.Model.ServiceException">
/// The AWS Lambda service encountered an internal error.
/// </exception>
/// <exception cref="Amazon.Lambda.Model.TooManyRequestsException">
/// The request throughput limit was exceeded.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lambda-2015-03-31/GetProvisionedConcurrencyConfig">REST API Reference for GetProvisionedConcurrencyConfig Operation</seealso>
public virtual Task<GetProvisionedConcurrencyConfigResponse> GetProvisionedConcurrencyConfigAsync(GetProvisionedConcurrencyConfigRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var options = new InvokeOptions();
options.RequestMarshaller = GetProvisionedConcurrencyConfigRequestMarshaller.Instance;
options.ResponseUnmarshaller = GetProvisionedConcurrencyConfigResponseUnmarshaller.Instance;
return InvokeAsync<GetProvisionedConcurrencyConfigResponse>(request, options, cancellationToken);
}
#endregion
#region Invoke
internal virtual InvokeResponse Invoke(InvokeRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = InvokeRequestMarshaller.Instance;
options.ResponseUnmarshaller = InvokeResponseUnmarshaller.Instance;
return Invoke<InvokeResponse>(request, options);
}
/// <summary>
/// Invokes a Lambda function. You can invoke a function synchronously (and wait for the
/// response), or asynchronously. To invoke a function asynchronously, set <code>InvocationType</code>
/// to <code>Event</code>.
///
///
/// <para>
/// For <a href="https://docs.aws.amazon.com/lambda/latest/dg/invocation-sync.html">synchronous
/// invocation</a>, details about the function response, including errors, are included
/// in the response body and headers. For either invocation type, you can find more information
/// in the <a href="https://docs.aws.amazon.com/lambda/latest/dg/monitoring-functions.html">execution
/// log</a> and <a href="https://docs.aws.amazon.com/lambda/latest/dg/lambda-x-ray.html">trace</a>.
/// </para>
///
/// <para>
/// When an error occurs, your function may be invoked multiple times. Retry behavior
/// varies by error type, client, event source, and invocation type. For example, if you
/// invoke a function asynchronously and it returns an error, Lambda executes the function
/// up to two more times. For more information, see <a href="https://docs.aws.amazon.com/lambda/latest/dg/retries-on-errors.html">Retry
/// Behavior</a>.
/// </para>
///
/// <para>
/// For <a href="https://docs.aws.amazon.com/lambda/latest/dg/invocation-async.html">asynchronous
/// invocation</a>, Lambda adds events to a queue before sending them to your function.
/// If your function does not have enough capacity to keep up with the queue, events may
/// be lost. Occasionally, your function may receive the same event multiple times, even
/// if no error occurs. To retain events that were not processed, configure your function
/// with a <a href="https://docs.aws.amazon.com/lambda/latest/dg/invocation-async.html#dlq">dead-letter
/// queue</a>.
/// </para>
///
/// <para>
/// The status code in the API response doesn't reflect function errors. Error codes are
/// reserved for errors that prevent your function from executing, such as permissions
/// errors, <a href="https://docs.aws.amazon.com/lambda/latest/dg/limits.html">limit errors</a>,
/// or issues with your function's code and configuration. For example, Lambda returns
/// <code>TooManyRequestsException</code> if executing the function would cause you to
/// exceed a concurrency limit at either the account level (<code>ConcurrentInvocationLimitExceeded</code>)
/// or function level (<code>ReservedFunctionConcurrentInvocationLimitExceeded</code>).
/// </para>
///
/// <para>
/// For functions with a long timeout, your client might be disconnected during synchronous
/// invocation while it waits for a response. Configure your HTTP client, SDK, firewall,
/// proxy, or operating system to allow for long connections with timeout or keep-alive
/// settings.
/// </para>
///
/// <para>
/// This operation requires permission for the <code>lambda:InvokeFunction</code> action.
/// </para>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the Invoke service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the Invoke service method, as returned by Lambda.</returns>
/// <exception cref="Amazon.Lambda.Model.EC2AccessDeniedException">
/// Need additional permissions to configure VPC settings.
/// </exception>
/// <exception cref="Amazon.Lambda.Model.EC2ThrottledException">
/// AWS Lambda was throttled by Amazon EC2 during Lambda function initialization using
/// the execution role provided for the Lambda function.
/// </exception>
/// <exception cref="Amazon.Lambda.Model.EC2UnexpectedException">
/// AWS Lambda received an unexpected EC2 client exception while setting up for the Lambda
/// function.
/// </exception>
/// <exception cref="Amazon.Lambda.Model.ENILimitReachedException">
/// AWS Lambda was not able to create an elastic network interface in the VPC, specified
/// as part of Lambda function configuration, because the limit for network interfaces
/// has been reached.
/// </exception>
/// <exception cref="Amazon.Lambda.Model.InvalidParameterValueException">
/// One of the parameters in the request is invalid.
/// </exception>
/// <exception cref="Amazon.Lambda.Model.InvalidRequestContentException">
/// The request body could not be parsed as JSON.
/// </exception>
/// <exception cref="Amazon.Lambda.Model.InvalidRuntimeException">
/// The runtime or runtime version specified is not supported.
/// </exception>
/// <exception cref="Amazon.Lambda.Model.InvalidSecurityGroupIDException">
/// The Security Group ID provided in the Lambda function VPC configuration is invalid.
/// </exception>
/// <exception cref="Amazon.Lambda.Model.InvalidSubnetIDException">
/// The Subnet ID provided in the Lambda function VPC configuration is invalid.
/// </exception>
/// <exception cref="Amazon.Lambda.Model.InvalidZipFileException">
/// AWS Lambda could not unzip the deployment package.
/// </exception>
/// <exception cref="Amazon.Lambda.Model.KMSAccessDeniedException">
/// Lambda was unable to decrypt the environment variables because KMS access was denied.
/// Check the Lambda function's KMS permissions.
/// </exception>
/// <exception cref="Amazon.Lambda.Model.KMSDisabledException">
/// Lambda was unable to decrypt the environment variables because the KMS key used is
/// disabled. Check the Lambda function's KMS key settings.
/// </exception>
/// <exception cref="Amazon.Lambda.Model.KMSInvalidStateException">
/// Lambda was unable to decrypt the environment variables because the KMS key used is
/// in an invalid state for Decrypt. Check the function's KMS key settings.
/// </exception>
/// <exception cref="Amazon.Lambda.Model.KMSNotFoundException">
/// Lambda was unable to decrypt the environment variables because the KMS key was not
/// found. Check the function's KMS key settings.
/// </exception>
/// <exception cref="Amazon.Lambda.Model.RequestTooLargeException">
/// The request payload exceeded the <code>Invoke</code> request body JSON input limit.
/// For more information, see <a href="https://docs.aws.amazon.com/lambda/latest/dg/limits.html">Limits</a>.
/// </exception>
/// <exception cref="Amazon.Lambda.Model.ResourceConflictException">
/// The resource already exists, or another operation is in progress.
/// </exception>
/// <exception cref="Amazon.Lambda.Model.ResourceNotFoundException">
/// The resource specified in the request does not exist.
/// </exception>
/// <exception cref="Amazon.Lambda.Model.ResourceNotReadyException">
/// The function is inactive and its VPC connection is no longer available. Wait for the
/// VPC connection to reestablish and try again.
/// </exception>
/// <exception cref="Amazon.Lambda.Model.ServiceException">
/// The AWS Lambda service encountered an internal error.
/// </exception>
/// <exception cref="Amazon.Lambda.Model.SubnetIPAddressLimitReachedException">
/// AWS Lambda was not able to set up VPC access for the Lambda function because one or
/// more configured subnets has no available IP addresses.
/// </exception>
/// <exception cref="Amazon.Lambda.Model.TooManyRequestsException">
/// The request throughput limit was exceeded.
/// </exception>
/// <exception cref="Amazon.Lambda.Model.UnsupportedMediaTypeException">
/// The content type of the <code>Invoke</code> request body is not JSON.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lambda-2015-03-31/Invoke">REST API Reference for Invoke Operation</seealso>
public virtual Task<InvokeResponse> InvokeAsync(InvokeRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var options = new InvokeOptions();
options.RequestMarshaller = InvokeRequestMarshaller.Instance;
options.ResponseUnmarshaller = InvokeResponseUnmarshaller.Instance;
return InvokeAsync<InvokeResponse>(request, options, cancellationToken);
}
#endregion
#region InvokeAsync
[Obsolete("For .NET 3.5/4.5, API InvokeAsyncResponse InvokeAsync(InvokeAsyncRequest) is deprecated, use InvokeResponse Invoke(InvokeRequest), or Task<InvokeResponse> InvokeAsync(InvokeRequest, CancellationToken) instead. For .NET Core and PCL, Task<InvokeAsyncResponse> InvokeAsyncAsync(InvokeAsyncRequest, CancellationToken) is deprecated, use Task<InvokeResponse> InvokeAsync(InvokeRequest, CancellationToken) instead.")]
internal virtual InvokeAsyncResponse InvokeAsync(InvokeAsyncRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = InvokeAsyncRequestMarshaller.Instance;
options.ResponseUnmarshaller = InvokeAsyncResponseUnmarshaller.Instance;
return Invoke<InvokeAsyncResponse>(request, options);
}
/// <summary>
/// <important>
/// <para>
/// For asynchronous function invocation, use <a>Invoke</a>.
/// </para>
/// </important>
/// <para>
/// Invokes a function asynchronously.
/// </para>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the InvokeAsync service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the InvokeAsync service method, as returned by Lambda.</returns>
/// <exception cref="Amazon.Lambda.Model.InvalidRequestContentException">
/// The request body could not be parsed as JSON.
/// </exception>
/// <exception cref="Amazon.Lambda.Model.InvalidRuntimeException">
/// The runtime or runtime version specified is not supported.
/// </exception>
/// <exception cref="Amazon.Lambda.Model.ResourceConflictException">
/// The resource already exists, or another operation is in progress.
/// </exception>
/// <exception cref="Amazon.Lambda.Model.ResourceNotFoundException">
/// The resource specified in the request does not exist.
/// </exception>
/// <exception cref="Amazon.Lambda.Model.ServiceException">
/// The AWS Lambda service encountered an internal error.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lambda-2015-03-31/InvokeAsync">REST API Reference for InvokeAsync Operation</seealso>
[Obsolete("For .NET 3.5/4.5, API InvokeAsyncResponse InvokeAsync(InvokeAsyncRequest) is deprecated, use InvokeResponse Invoke(InvokeRequest), or Task<InvokeResponse> InvokeAsync(InvokeRequest, CancellationToken) instead. For .NET Core and PCL, Task<InvokeAsyncResponse> InvokeAsyncAsync(InvokeAsyncRequest, CancellationToken) is deprecated, use Task<InvokeResponse> InvokeAsync(InvokeRequest, CancellationToken) instead.")]
public virtual Task<InvokeAsyncResponse> InvokeAsyncAsync(InvokeAsyncRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var options = new InvokeOptions();
options.RequestMarshaller = InvokeAsyncRequestMarshaller.Instance;
options.ResponseUnmarshaller = InvokeAsyncResponseUnmarshaller.Instance;
return InvokeAsync<InvokeAsyncResponse>(request, options, cancellationToken);
}
#endregion
#region ListAliases
internal virtual ListAliasesResponse ListAliases(ListAliasesRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = ListAliasesRequestMarshaller.Instance;
options.ResponseUnmarshaller = ListAliasesResponseUnmarshaller.Instance;
return Invoke<ListAliasesResponse>(request, options);
}
/// <summary>
/// Returns a list of <a href="https://docs.aws.amazon.com/lambda/latest/dg/versioning-aliases.html">aliases</a>
/// for a Lambda function.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the ListAliases service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the ListAliases service method, as returned by Lambda.</returns>
/// <exception cref="Amazon.Lambda.Model.InvalidParameterValueException">
/// One of the parameters in the request is invalid.
/// </exception>
/// <exception cref="Amazon.Lambda.Model.ResourceNotFoundException">
/// The resource specified in the request does not exist.
/// </exception>
/// <exception cref="Amazon.Lambda.Model.ServiceException">
/// The AWS Lambda service encountered an internal error.
/// </exception>
/// <exception cref="Amazon.Lambda.Model.TooManyRequestsException">
/// The request throughput limit was exceeded.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lambda-2015-03-31/ListAliases">REST API Reference for ListAliases Operation</seealso>
public virtual Task<ListAliasesResponse> ListAliasesAsync(ListAliasesRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var options = new InvokeOptions();
options.RequestMarshaller = ListAliasesRequestMarshaller.Instance;
options.ResponseUnmarshaller = ListAliasesResponseUnmarshaller.Instance;
return InvokeAsync<ListAliasesResponse>(request, options, cancellationToken);
}
#endregion
#region ListEventSourceMappings
internal virtual ListEventSourceMappingsResponse ListEventSourceMappings(ListEventSourceMappingsRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = ListEventSourceMappingsRequestMarshaller.Instance;
options.ResponseUnmarshaller = ListEventSourceMappingsResponseUnmarshaller.Instance;
return Invoke<ListEventSourceMappingsResponse>(request, options);
}
/// <summary>
/// Lists event source mappings. Specify an <code>EventSourceArn</code> to only show event
/// source mappings for a single event source.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the ListEventSourceMappings service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the ListEventSourceMappings service method, as returned by Lambda.</returns>
/// <exception cref="Amazon.Lambda.Model.InvalidParameterValueException">
/// One of the parameters in the request is invalid.
/// </exception>
/// <exception cref="Amazon.Lambda.Model.ResourceNotFoundException">
/// The resource specified in the request does not exist.
/// </exception>
/// <exception cref="Amazon.Lambda.Model.ServiceException">
/// The AWS Lambda service encountered an internal error.
/// </exception>
/// <exception cref="Amazon.Lambda.Model.TooManyRequestsException">
/// The request throughput limit was exceeded.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lambda-2015-03-31/ListEventSourceMappings">REST API Reference for ListEventSourceMappings Operation</seealso>
public virtual Task<ListEventSourceMappingsResponse> ListEventSourceMappingsAsync(ListEventSourceMappingsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var options = new InvokeOptions();
options.RequestMarshaller = ListEventSourceMappingsRequestMarshaller.Instance;
options.ResponseUnmarshaller = ListEventSourceMappingsResponseUnmarshaller.Instance;
return InvokeAsync<ListEventSourceMappingsResponse>(request, options, cancellationToken);
}
#endregion
#region ListFunctionEventInvokeConfigs
internal virtual ListFunctionEventInvokeConfigsResponse ListFunctionEventInvokeConfigs(ListFunctionEventInvokeConfigsRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = ListFunctionEventInvokeConfigsRequestMarshaller.Instance;
options.ResponseUnmarshaller = ListFunctionEventInvokeConfigsResponseUnmarshaller.Instance;
return Invoke<ListFunctionEventInvokeConfigsResponse>(request, options);
}
/// <summary>
/// Retrieves a list of configurations for asynchronous invocation for a function.
///
///
/// <para>
/// To configure options for asynchronous invocation, use <a>PutFunctionEventInvokeConfig</a>.
/// </para>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the ListFunctionEventInvokeConfigs service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the ListFunctionEventInvokeConfigs service method, as returned by Lambda.</returns>
/// <exception cref="Amazon.Lambda.Model.InvalidParameterValueException">
/// One of the parameters in the request is invalid.
/// </exception>
/// <exception cref="Amazon.Lambda.Model.ResourceNotFoundException">
/// The resource specified in the request does not exist.
/// </exception>
/// <exception cref="Amazon.Lambda.Model.ServiceException">
/// The AWS Lambda service encountered an internal error.
/// </exception>
/// <exception cref="Amazon.Lambda.Model.TooManyRequestsException">
/// The request throughput limit was exceeded.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lambda-2015-03-31/ListFunctionEventInvokeConfigs">REST API Reference for ListFunctionEventInvokeConfigs Operation</seealso>
public virtual Task<ListFunctionEventInvokeConfigsResponse> ListFunctionEventInvokeConfigsAsync(ListFunctionEventInvokeConfigsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var options = new InvokeOptions();
options.RequestMarshaller = ListFunctionEventInvokeConfigsRequestMarshaller.Instance;
options.ResponseUnmarshaller = ListFunctionEventInvokeConfigsResponseUnmarshaller.Instance;
return InvokeAsync<ListFunctionEventInvokeConfigsResponse>(request, options, cancellationToken);
}
#endregion
#region ListFunctions
internal virtual ListFunctionsResponse ListFunctions(ListFunctionsRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = ListFunctionsRequestMarshaller.Instance;
options.ResponseUnmarshaller = ListFunctionsResponseUnmarshaller.Instance;
return Invoke<ListFunctionsResponse>(request, options);
}
/// <summary>
/// Returns a list of Lambda functions, with the version-specific configuration of each.
/// Lambda returns up to 50 functions per call.
///
///
/// <para>
/// Set <code>FunctionVersion</code> to <code>ALL</code> to include all published versions
/// of each function in addition to the unpublished version. To get more information about
/// a function or version, use <a>GetFunction</a>.
/// </para>
/// </summary>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the ListFunctions service method, as returned by Lambda.</returns>
/// <exception cref="Amazon.Lambda.Model.InvalidParameterValueException">
/// One of the parameters in the request is invalid.
/// </exception>
/// <exception cref="Amazon.Lambda.Model.ServiceException">
/// The AWS Lambda service encountered an internal error.
/// </exception>
/// <exception cref="Amazon.Lambda.Model.TooManyRequestsException">
/// The request throughput limit was exceeded.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lambda-2015-03-31/ListFunctions">REST API Reference for ListFunctions Operation</seealso>
public virtual Task<ListFunctionsResponse> ListFunctionsAsync(System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var request = new ListFunctionsRequest();
return ListFunctionsAsync(request, cancellationToken);
}
/// <summary>
/// Returns a list of Lambda functions, with the version-specific configuration of each.
/// Lambda returns up to 50 functions per call.
///
///
/// <para>
/// Set <code>FunctionVersion</code> to <code>ALL</code> to include all published versions
/// of each function in addition to the unpublished version. To get more information about
/// a function or version, use <a>GetFunction</a>.
/// </para>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the ListFunctions service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the ListFunctions service method, as returned by Lambda.</returns>
/// <exception cref="Amazon.Lambda.Model.InvalidParameterValueException">
/// One of the parameters in the request is invalid.
/// </exception>
/// <exception cref="Amazon.Lambda.Model.ServiceException">
/// The AWS Lambda service encountered an internal error.
/// </exception>
/// <exception cref="Amazon.Lambda.Model.TooManyRequestsException">
/// The request throughput limit was exceeded.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lambda-2015-03-31/ListFunctions">REST API Reference for ListFunctions Operation</seealso>
public virtual Task<ListFunctionsResponse> ListFunctionsAsync(ListFunctionsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var options = new InvokeOptions();
options.RequestMarshaller = ListFunctionsRequestMarshaller.Instance;
options.ResponseUnmarshaller = ListFunctionsResponseUnmarshaller.Instance;
return InvokeAsync<ListFunctionsResponse>(request, options, cancellationToken);
}
#endregion
#region ListLayers
internal virtual ListLayersResponse ListLayers(ListLayersRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = ListLayersRequestMarshaller.Instance;
options.ResponseUnmarshaller = ListLayersResponseUnmarshaller.Instance;
return Invoke<ListLayersResponse>(request, options);
}
/// <summary>
/// Lists <a href="https://docs.aws.amazon.com/lambda/latest/dg/configuration-layers.html">AWS
/// Lambda layers</a> and shows information about the latest version of each. Specify
/// a <a href="https://docs.aws.amazon.com/lambda/latest/dg/lambda-runtimes.html">runtime
/// identifier</a> to list only layers that indicate that they're compatible with that
/// runtime.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the ListLayers service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the ListLayers service method, as returned by Lambda.</returns>
/// <exception cref="Amazon.Lambda.Model.InvalidParameterValueException">
/// One of the parameters in the request is invalid.
/// </exception>
/// <exception cref="Amazon.Lambda.Model.ServiceException">
/// The AWS Lambda service encountered an internal error.
/// </exception>
/// <exception cref="Amazon.Lambda.Model.TooManyRequestsException">
/// The request throughput limit was exceeded.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lambda-2015-03-31/ListLayers">REST API Reference for ListLayers Operation</seealso>
public virtual Task<ListLayersResponse> ListLayersAsync(ListLayersRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var options = new InvokeOptions();
options.RequestMarshaller = ListLayersRequestMarshaller.Instance;
options.ResponseUnmarshaller = ListLayersResponseUnmarshaller.Instance;
return InvokeAsync<ListLayersResponse>(request, options, cancellationToken);
}
#endregion
#region ListLayerVersions
internal virtual ListLayerVersionsResponse ListLayerVersions(ListLayerVersionsRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = ListLayerVersionsRequestMarshaller.Instance;
options.ResponseUnmarshaller = ListLayerVersionsResponseUnmarshaller.Instance;
return Invoke<ListLayerVersionsResponse>(request, options);
}
/// <summary>
/// Lists the versions of an <a href="https://docs.aws.amazon.com/lambda/latest/dg/configuration-layers.html">AWS
/// Lambda layer</a>. Versions that have been deleted aren't listed. Specify a <a href="https://docs.aws.amazon.com/lambda/latest/dg/lambda-runtimes.html">runtime
/// identifier</a> to list only versions that indicate that they're compatible with that
/// runtime.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the ListLayerVersions service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the ListLayerVersions service method, as returned by Lambda.</returns>
/// <exception cref="Amazon.Lambda.Model.InvalidParameterValueException">
/// One of the parameters in the request is invalid.
/// </exception>
/// <exception cref="Amazon.Lambda.Model.ResourceNotFoundException">
/// The resource specified in the request does not exist.
/// </exception>
/// <exception cref="Amazon.Lambda.Model.ServiceException">
/// The AWS Lambda service encountered an internal error.
/// </exception>
/// <exception cref="Amazon.Lambda.Model.TooManyRequestsException">
/// The request throughput limit was exceeded.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lambda-2015-03-31/ListLayerVersions">REST API Reference for ListLayerVersions Operation</seealso>
public virtual Task<ListLayerVersionsResponse> ListLayerVersionsAsync(ListLayerVersionsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var options = new InvokeOptions();
options.RequestMarshaller = ListLayerVersionsRequestMarshaller.Instance;
options.ResponseUnmarshaller = ListLayerVersionsResponseUnmarshaller.Instance;
return InvokeAsync<ListLayerVersionsResponse>(request, options, cancellationToken);
}
#endregion
#region ListProvisionedConcurrencyConfigs
internal virtual ListProvisionedConcurrencyConfigsResponse ListProvisionedConcurrencyConfigs(ListProvisionedConcurrencyConfigsRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = ListProvisionedConcurrencyConfigsRequestMarshaller.Instance;
options.ResponseUnmarshaller = ListProvisionedConcurrencyConfigsResponseUnmarshaller.Instance;
return Invoke<ListProvisionedConcurrencyConfigsResponse>(request, options);
}
/// <summary>
/// Retrieves a list of provisioned concurrency configurations for a function.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the ListProvisionedConcurrencyConfigs service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the ListProvisionedConcurrencyConfigs service method, as returned by Lambda.</returns>
/// <exception cref="Amazon.Lambda.Model.InvalidParameterValueException">
/// One of the parameters in the request is invalid.
/// </exception>
/// <exception cref="Amazon.Lambda.Model.ResourceNotFoundException">
/// The resource specified in the request does not exist.
/// </exception>
/// <exception cref="Amazon.Lambda.Model.ServiceException">
/// The AWS Lambda service encountered an internal error.
/// </exception>
/// <exception cref="Amazon.Lambda.Model.TooManyRequestsException">
/// The request throughput limit was exceeded.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lambda-2015-03-31/ListProvisionedConcurrencyConfigs">REST API Reference for ListProvisionedConcurrencyConfigs Operation</seealso>
public virtual Task<ListProvisionedConcurrencyConfigsResponse> ListProvisionedConcurrencyConfigsAsync(ListProvisionedConcurrencyConfigsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var options = new InvokeOptions();
options.RequestMarshaller = ListProvisionedConcurrencyConfigsRequestMarshaller.Instance;
options.ResponseUnmarshaller = ListProvisionedConcurrencyConfigsResponseUnmarshaller.Instance;
return InvokeAsync<ListProvisionedConcurrencyConfigsResponse>(request, options, cancellationToken);
}
#endregion
#region ListTags
internal virtual ListTagsResponse ListTags(ListTagsRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = ListTagsRequestMarshaller.Instance;
options.ResponseUnmarshaller = ListTagsResponseUnmarshaller.Instance;
return Invoke<ListTagsResponse>(request, options);
}
/// <summary>
/// Returns a function's <a href="https://docs.aws.amazon.com/lambda/latest/dg/tagging.html">tags</a>.
/// You can also view tags with <a>GetFunction</a>.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the ListTags service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the ListTags service method, as returned by Lambda.</returns>
/// <exception cref="Amazon.Lambda.Model.InvalidParameterValueException">
/// One of the parameters in the request is invalid.
/// </exception>
/// <exception cref="Amazon.Lambda.Model.ResourceNotFoundException">
/// The resource specified in the request does not exist.
/// </exception>
/// <exception cref="Amazon.Lambda.Model.ServiceException">
/// The AWS Lambda service encountered an internal error.
/// </exception>
/// <exception cref="Amazon.Lambda.Model.TooManyRequestsException">
/// The request throughput limit was exceeded.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lambda-2015-03-31/ListTags">REST API Reference for ListTags Operation</seealso>
public virtual Task<ListTagsResponse> ListTagsAsync(ListTagsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var options = new InvokeOptions();
options.RequestMarshaller = ListTagsRequestMarshaller.Instance;
options.ResponseUnmarshaller = ListTagsResponseUnmarshaller.Instance;
return InvokeAsync<ListTagsResponse>(request, options, cancellationToken);
}
#endregion
#region ListVersionsByFunction
internal virtual ListVersionsByFunctionResponse ListVersionsByFunction(ListVersionsByFunctionRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = ListVersionsByFunctionRequestMarshaller.Instance;
options.ResponseUnmarshaller = ListVersionsByFunctionResponseUnmarshaller.Instance;
return Invoke<ListVersionsByFunctionResponse>(request, options);
}
/// <summary>
/// Returns a list of <a href="https://docs.aws.amazon.com/lambda/latest/dg/versioning-aliases.html">versions</a>,
/// with the version-specific configuration of each. Lambda returns up to 50 versions
/// per call.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the ListVersionsByFunction service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the ListVersionsByFunction service method, as returned by Lambda.</returns>
/// <exception cref="Amazon.Lambda.Model.InvalidParameterValueException">
/// One of the parameters in the request is invalid.
/// </exception>
/// <exception cref="Amazon.Lambda.Model.ResourceNotFoundException">
/// The resource specified in the request does not exist.
/// </exception>
/// <exception cref="Amazon.Lambda.Model.ServiceException">
/// The AWS Lambda service encountered an internal error.
/// </exception>
/// <exception cref="Amazon.Lambda.Model.TooManyRequestsException">
/// The request throughput limit was exceeded.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lambda-2015-03-31/ListVersionsByFunction">REST API Reference for ListVersionsByFunction Operation</seealso>
public virtual Task<ListVersionsByFunctionResponse> ListVersionsByFunctionAsync(ListVersionsByFunctionRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var options = new InvokeOptions();
options.RequestMarshaller = ListVersionsByFunctionRequestMarshaller.Instance;
options.ResponseUnmarshaller = ListVersionsByFunctionResponseUnmarshaller.Instance;
return InvokeAsync<ListVersionsByFunctionResponse>(request, options, cancellationToken);
}
#endregion
#region PublishLayerVersion
internal virtual PublishLayerVersionResponse PublishLayerVersion(PublishLayerVersionRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = PublishLayerVersionRequestMarshaller.Instance;
options.ResponseUnmarshaller = PublishLayerVersionResponseUnmarshaller.Instance;
return Invoke<PublishLayerVersionResponse>(request, options);
}
/// <summary>
/// Creates an <a href="https://docs.aws.amazon.com/lambda/latest/dg/configuration-layers.html">AWS
/// Lambda layer</a> from a ZIP archive. Each time you call <code>PublishLayerVersion</code>
/// with the same layer name, a new version is created.
///
///
/// <para>
/// Add layers to your function with <a>CreateFunction</a> or <a>UpdateFunctionConfiguration</a>.
/// </para>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the PublishLayerVersion service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the PublishLayerVersion service method, as returned by Lambda.</returns>
/// <exception cref="Amazon.Lambda.Model.CodeStorageExceededException">
/// You have exceeded your maximum total code size per account. <a href="https://docs.aws.amazon.com/lambda/latest/dg/limits.html">Learn
/// more</a>
/// </exception>
/// <exception cref="Amazon.Lambda.Model.InvalidParameterValueException">
/// One of the parameters in the request is invalid.
/// </exception>
/// <exception cref="Amazon.Lambda.Model.ResourceNotFoundException">
/// The resource specified in the request does not exist.
/// </exception>
/// <exception cref="Amazon.Lambda.Model.ServiceException">
/// The AWS Lambda service encountered an internal error.
/// </exception>
/// <exception cref="Amazon.Lambda.Model.TooManyRequestsException">
/// The request throughput limit was exceeded.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lambda-2015-03-31/PublishLayerVersion">REST API Reference for PublishLayerVersion Operation</seealso>
public virtual Task<PublishLayerVersionResponse> PublishLayerVersionAsync(PublishLayerVersionRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var options = new InvokeOptions();
options.RequestMarshaller = PublishLayerVersionRequestMarshaller.Instance;
options.ResponseUnmarshaller = PublishLayerVersionResponseUnmarshaller.Instance;
return InvokeAsync<PublishLayerVersionResponse>(request, options, cancellationToken);
}
#endregion
#region PublishVersion
internal virtual PublishVersionResponse PublishVersion(PublishVersionRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = PublishVersionRequestMarshaller.Instance;
options.ResponseUnmarshaller = PublishVersionResponseUnmarshaller.Instance;
return Invoke<PublishVersionResponse>(request, options);
}
/// <summary>
/// Creates a <a href="https://docs.aws.amazon.com/lambda/latest/dg/versioning-aliases.html">version</a>
/// from the current code and configuration of a function. Use versions to create a snapshot
/// of your function code and configuration that doesn't change.
///
///
/// <para>
/// AWS Lambda doesn't publish a version if the function's configuration and code haven't
/// changed since the last version. Use <a>UpdateFunctionCode</a> or <a>UpdateFunctionConfiguration</a>
/// to update the function before publishing a version.
/// </para>
///
/// <para>
/// Clients can invoke versions directly or with an alias. To create an alias, use <a>CreateAlias</a>.
/// </para>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the PublishVersion service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the PublishVersion service method, as returned by Lambda.</returns>
/// <exception cref="Amazon.Lambda.Model.CodeStorageExceededException">
/// You have exceeded your maximum total code size per account. <a href="https://docs.aws.amazon.com/lambda/latest/dg/limits.html">Learn
/// more</a>
/// </exception>
/// <exception cref="Amazon.Lambda.Model.InvalidParameterValueException">
/// One of the parameters in the request is invalid.
/// </exception>
/// <exception cref="Amazon.Lambda.Model.PreconditionFailedException">
/// The RevisionId provided does not match the latest RevisionId for the Lambda function
/// or alias. Call the <code>GetFunction</code> or the <code>GetAlias</code> API to retrieve
/// the latest RevisionId for your resource.
/// </exception>
/// <exception cref="Amazon.Lambda.Model.ResourceConflictException">
/// The resource already exists, or another operation is in progress.
/// </exception>
/// <exception cref="Amazon.Lambda.Model.ResourceNotFoundException">
/// The resource specified in the request does not exist.
/// </exception>
/// <exception cref="Amazon.Lambda.Model.ServiceException">
/// The AWS Lambda service encountered an internal error.
/// </exception>
/// <exception cref="Amazon.Lambda.Model.TooManyRequestsException">
/// The request throughput limit was exceeded.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lambda-2015-03-31/PublishVersion">REST API Reference for PublishVersion Operation</seealso>
public virtual Task<PublishVersionResponse> PublishVersionAsync(PublishVersionRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var options = new InvokeOptions();
options.RequestMarshaller = PublishVersionRequestMarshaller.Instance;
options.ResponseUnmarshaller = PublishVersionResponseUnmarshaller.Instance;
return InvokeAsync<PublishVersionResponse>(request, options, cancellationToken);
}
#endregion
#region PutFunctionConcurrency
internal virtual PutFunctionConcurrencyResponse PutFunctionConcurrency(PutFunctionConcurrencyRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = PutFunctionConcurrencyRequestMarshaller.Instance;
options.ResponseUnmarshaller = PutFunctionConcurrencyResponseUnmarshaller.Instance;
return Invoke<PutFunctionConcurrencyResponse>(request, options);
}
/// <summary>
/// Sets the maximum number of simultaneous executions for a function, and reserves capacity
/// for that concurrency level.
///
///
/// <para>
/// Concurrency settings apply to the function as a whole, including all published versions
/// and the unpublished version. Reserving concurrency both ensures that your function
/// has capacity to process the specified number of events simultaneously, and prevents
/// it from scaling beyond that level. Use <a>GetFunction</a> to see the current setting
/// for a function.
/// </para>
///
/// <para>
/// Use <a>GetAccountSettings</a> to see your Regional concurrency limit. You can reserve
/// concurrency for as many functions as you like, as long as you leave at least 100 simultaneous
/// executions unreserved for functions that aren't configured with a per-function limit.
/// For more information, see <a href="https://docs.aws.amazon.com/lambda/latest/dg/concurrent-executions.html">Managing
/// Concurrency</a>.
/// </para>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the PutFunctionConcurrency service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the PutFunctionConcurrency service method, as returned by Lambda.</returns>
/// <exception cref="Amazon.Lambda.Model.InvalidParameterValueException">
/// One of the parameters in the request is invalid.
/// </exception>
/// <exception cref="Amazon.Lambda.Model.ResourceConflictException">
/// The resource already exists, or another operation is in progress.
/// </exception>
/// <exception cref="Amazon.Lambda.Model.ResourceNotFoundException">
/// The resource specified in the request does not exist.
/// </exception>
/// <exception cref="Amazon.Lambda.Model.ServiceException">
/// The AWS Lambda service encountered an internal error.
/// </exception>
/// <exception cref="Amazon.Lambda.Model.TooManyRequestsException">
/// The request throughput limit was exceeded.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lambda-2015-03-31/PutFunctionConcurrency">REST API Reference for PutFunctionConcurrency Operation</seealso>
public virtual Task<PutFunctionConcurrencyResponse> PutFunctionConcurrencyAsync(PutFunctionConcurrencyRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var options = new InvokeOptions();
options.RequestMarshaller = PutFunctionConcurrencyRequestMarshaller.Instance;
options.ResponseUnmarshaller = PutFunctionConcurrencyResponseUnmarshaller.Instance;
return InvokeAsync<PutFunctionConcurrencyResponse>(request, options, cancellationToken);
}
#endregion
#region PutFunctionEventInvokeConfig
internal virtual PutFunctionEventInvokeConfigResponse PutFunctionEventInvokeConfig(PutFunctionEventInvokeConfigRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = PutFunctionEventInvokeConfigRequestMarshaller.Instance;
options.ResponseUnmarshaller = PutFunctionEventInvokeConfigResponseUnmarshaller.Instance;
return Invoke<PutFunctionEventInvokeConfigResponse>(request, options);
}
/// <summary>
/// Configures options for <a href="https://docs.aws.amazon.com/lambda/latest/dg/invocation-async.html">asynchronous
/// invocation</a> on a function, version, or alias. If a configuration already exists
/// for a function, version, or alias, this operation overwrites it. If you exclude any
/// settings, they are removed. To set one option without affecting existing settings
/// for other options, use <a>PutFunctionEventInvokeConfig</a>.
///
///
/// <para>
/// By default, Lambda retries an asynchronous invocation twice if the function returns
/// an error. It retains events in a queue for up to six hours. When an event fails all
/// processing attempts or stays in the asynchronous invocation queue for too long, Lambda
/// discards it. To retain discarded events, configure a dead-letter queue with <a>UpdateFunctionConfiguration</a>.
/// </para>
///
/// <para>
/// To send an invocation record to a queue, topic, function, or event bus, specify a
/// <a href="https://docs.aws.amazon.com/lambda/latest/dg/invocation-async.html#invocation-async-destinations">destination</a>.
/// You can configure separate destinations for successful invocations (on-success) and
/// events that fail all processing attempts (on-failure). You can configure destinations
/// in addition to or instead of a dead-letter queue.
/// </para>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the PutFunctionEventInvokeConfig service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the PutFunctionEventInvokeConfig service method, as returned by Lambda.</returns>
/// <exception cref="Amazon.Lambda.Model.InvalidParameterValueException">
/// One of the parameters in the request is invalid.
/// </exception>
/// <exception cref="Amazon.Lambda.Model.ResourceNotFoundException">
/// The resource specified in the request does not exist.
/// </exception>
/// <exception cref="Amazon.Lambda.Model.ServiceException">
/// The AWS Lambda service encountered an internal error.
/// </exception>
/// <exception cref="Amazon.Lambda.Model.TooManyRequestsException">
/// The request throughput limit was exceeded.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lambda-2015-03-31/PutFunctionEventInvokeConfig">REST API Reference for PutFunctionEventInvokeConfig Operation</seealso>
public virtual Task<PutFunctionEventInvokeConfigResponse> PutFunctionEventInvokeConfigAsync(PutFunctionEventInvokeConfigRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var options = new InvokeOptions();
options.RequestMarshaller = PutFunctionEventInvokeConfigRequestMarshaller.Instance;
options.ResponseUnmarshaller = PutFunctionEventInvokeConfigResponseUnmarshaller.Instance;
return InvokeAsync<PutFunctionEventInvokeConfigResponse>(request, options, cancellationToken);
}
#endregion
#region PutProvisionedConcurrencyConfig
internal virtual PutProvisionedConcurrencyConfigResponse PutProvisionedConcurrencyConfig(PutProvisionedConcurrencyConfigRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = PutProvisionedConcurrencyConfigRequestMarshaller.Instance;
options.ResponseUnmarshaller = PutProvisionedConcurrencyConfigResponseUnmarshaller.Instance;
return Invoke<PutProvisionedConcurrencyConfigResponse>(request, options);
}
/// <summary>
/// Adds a provisioned concurrency configuration to a function's alias or version.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the PutProvisionedConcurrencyConfig service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the PutProvisionedConcurrencyConfig service method, as returned by Lambda.</returns>
/// <exception cref="Amazon.Lambda.Model.InvalidParameterValueException">
/// One of the parameters in the request is invalid.
/// </exception>
/// <exception cref="Amazon.Lambda.Model.ResourceConflictException">
/// The resource already exists, or another operation is in progress.
/// </exception>
/// <exception cref="Amazon.Lambda.Model.ResourceNotFoundException">
/// The resource specified in the request does not exist.
/// </exception>
/// <exception cref="Amazon.Lambda.Model.ServiceException">
/// The AWS Lambda service encountered an internal error.
/// </exception>
/// <exception cref="Amazon.Lambda.Model.TooManyRequestsException">
/// The request throughput limit was exceeded.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lambda-2015-03-31/PutProvisionedConcurrencyConfig">REST API Reference for PutProvisionedConcurrencyConfig Operation</seealso>
public virtual Task<PutProvisionedConcurrencyConfigResponse> PutProvisionedConcurrencyConfigAsync(PutProvisionedConcurrencyConfigRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var options = new InvokeOptions();
options.RequestMarshaller = PutProvisionedConcurrencyConfigRequestMarshaller.Instance;
options.ResponseUnmarshaller = PutProvisionedConcurrencyConfigResponseUnmarshaller.Instance;
return InvokeAsync<PutProvisionedConcurrencyConfigResponse>(request, options, cancellationToken);
}
#endregion
#region RemoveLayerVersionPermission
internal virtual RemoveLayerVersionPermissionResponse RemoveLayerVersionPermission(RemoveLayerVersionPermissionRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = RemoveLayerVersionPermissionRequestMarshaller.Instance;
options.ResponseUnmarshaller = RemoveLayerVersionPermissionResponseUnmarshaller.Instance;
return Invoke<RemoveLayerVersionPermissionResponse>(request, options);
}
/// <summary>
/// Removes a statement from the permissions policy for a version of an <a href="https://docs.aws.amazon.com/lambda/latest/dg/configuration-layers.html">AWS
/// Lambda layer</a>. For more information, see <a>AddLayerVersionPermission</a>.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the RemoveLayerVersionPermission service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the RemoveLayerVersionPermission service method, as returned by Lambda.</returns>
/// <exception cref="Amazon.Lambda.Model.InvalidParameterValueException">
/// One of the parameters in the request is invalid.
/// </exception>
/// <exception cref="Amazon.Lambda.Model.PreconditionFailedException">
/// The RevisionId provided does not match the latest RevisionId for the Lambda function
/// or alias. Call the <code>GetFunction</code> or the <code>GetAlias</code> API to retrieve
/// the latest RevisionId for your resource.
/// </exception>
/// <exception cref="Amazon.Lambda.Model.ResourceNotFoundException">
/// The resource specified in the request does not exist.
/// </exception>
/// <exception cref="Amazon.Lambda.Model.ServiceException">
/// The AWS Lambda service encountered an internal error.
/// </exception>
/// <exception cref="Amazon.Lambda.Model.TooManyRequestsException">
/// The request throughput limit was exceeded.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lambda-2015-03-31/RemoveLayerVersionPermission">REST API Reference for RemoveLayerVersionPermission Operation</seealso>
public virtual Task<RemoveLayerVersionPermissionResponse> RemoveLayerVersionPermissionAsync(RemoveLayerVersionPermissionRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var options = new InvokeOptions();
options.RequestMarshaller = RemoveLayerVersionPermissionRequestMarshaller.Instance;
options.ResponseUnmarshaller = RemoveLayerVersionPermissionResponseUnmarshaller.Instance;
return InvokeAsync<RemoveLayerVersionPermissionResponse>(request, options, cancellationToken);
}
#endregion
#region RemovePermission
internal virtual RemovePermissionResponse RemovePermission(RemovePermissionRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = RemovePermissionRequestMarshaller.Instance;
options.ResponseUnmarshaller = RemovePermissionResponseUnmarshaller.Instance;
return Invoke<RemovePermissionResponse>(request, options);
}
/// <summary>
/// Revokes function-use permission from an AWS service or another account. You can get
/// the ID of the statement from the output of <a>GetPolicy</a>.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the RemovePermission service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the RemovePermission service method, as returned by Lambda.</returns>
/// <exception cref="Amazon.Lambda.Model.InvalidParameterValueException">
/// One of the parameters in the request is invalid.
/// </exception>
/// <exception cref="Amazon.Lambda.Model.PreconditionFailedException">
/// The RevisionId provided does not match the latest RevisionId for the Lambda function
/// or alias. Call the <code>GetFunction</code> or the <code>GetAlias</code> API to retrieve
/// the latest RevisionId for your resource.
/// </exception>
/// <exception cref="Amazon.Lambda.Model.ResourceNotFoundException">
/// The resource specified in the request does not exist.
/// </exception>
/// <exception cref="Amazon.Lambda.Model.ServiceException">
/// The AWS Lambda service encountered an internal error.
/// </exception>
/// <exception cref="Amazon.Lambda.Model.TooManyRequestsException">
/// The request throughput limit was exceeded.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lambda-2015-03-31/RemovePermission">REST API Reference for RemovePermission Operation</seealso>
public virtual Task<RemovePermissionResponse> RemovePermissionAsync(RemovePermissionRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var options = new InvokeOptions();
options.RequestMarshaller = RemovePermissionRequestMarshaller.Instance;
options.ResponseUnmarshaller = RemovePermissionResponseUnmarshaller.Instance;
return InvokeAsync<RemovePermissionResponse>(request, options, cancellationToken);
}
#endregion
#region TagResource
internal virtual TagResourceResponse TagResource(TagResourceRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = TagResourceRequestMarshaller.Instance;
options.ResponseUnmarshaller = TagResourceResponseUnmarshaller.Instance;
return Invoke<TagResourceResponse>(request, options);
}
/// <summary>
/// Adds <a href="https://docs.aws.amazon.com/lambda/latest/dg/tagging.html">tags</a>
/// to a function.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the TagResource service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the TagResource service method, as returned by Lambda.</returns>
/// <exception cref="Amazon.Lambda.Model.InvalidParameterValueException">
/// One of the parameters in the request is invalid.
/// </exception>
/// <exception cref="Amazon.Lambda.Model.ResourceConflictException">
/// The resource already exists, or another operation is in progress.
/// </exception>
/// <exception cref="Amazon.Lambda.Model.ResourceNotFoundException">
/// The resource specified in the request does not exist.
/// </exception>
/// <exception cref="Amazon.Lambda.Model.ServiceException">
/// The AWS Lambda service encountered an internal error.
/// </exception>
/// <exception cref="Amazon.Lambda.Model.TooManyRequestsException">
/// The request throughput limit was exceeded.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lambda-2015-03-31/TagResource">REST API Reference for TagResource Operation</seealso>
public virtual Task<TagResourceResponse> TagResourceAsync(TagResourceRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var options = new InvokeOptions();
options.RequestMarshaller = TagResourceRequestMarshaller.Instance;
options.ResponseUnmarshaller = TagResourceResponseUnmarshaller.Instance;
return InvokeAsync<TagResourceResponse>(request, options, cancellationToken);
}
#endregion
#region UntagResource
internal virtual UntagResourceResponse UntagResource(UntagResourceRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = UntagResourceRequestMarshaller.Instance;
options.ResponseUnmarshaller = UntagResourceResponseUnmarshaller.Instance;
return Invoke<UntagResourceResponse>(request, options);
}
/// <summary>
/// Removes <a href="https://docs.aws.amazon.com/lambda/latest/dg/tagging.html">tags</a>
/// from a function.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the UntagResource service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the UntagResource service method, as returned by Lambda.</returns>
/// <exception cref="Amazon.Lambda.Model.InvalidParameterValueException">
/// One of the parameters in the request is invalid.
/// </exception>
/// <exception cref="Amazon.Lambda.Model.ResourceConflictException">
/// The resource already exists, or another operation is in progress.
/// </exception>
/// <exception cref="Amazon.Lambda.Model.ResourceNotFoundException">
/// The resource specified in the request does not exist.
/// </exception>
/// <exception cref="Amazon.Lambda.Model.ServiceException">
/// The AWS Lambda service encountered an internal error.
/// </exception>
/// <exception cref="Amazon.Lambda.Model.TooManyRequestsException">
/// The request throughput limit was exceeded.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lambda-2015-03-31/UntagResource">REST API Reference for UntagResource Operation</seealso>
public virtual Task<UntagResourceResponse> UntagResourceAsync(UntagResourceRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var options = new InvokeOptions();
options.RequestMarshaller = UntagResourceRequestMarshaller.Instance;
options.ResponseUnmarshaller = UntagResourceResponseUnmarshaller.Instance;
return InvokeAsync<UntagResourceResponse>(request, options, cancellationToken);
}
#endregion
#region UpdateAlias
internal virtual UpdateAliasResponse UpdateAlias(UpdateAliasRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = UpdateAliasRequestMarshaller.Instance;
options.ResponseUnmarshaller = UpdateAliasResponseUnmarshaller.Instance;
return Invoke<UpdateAliasResponse>(request, options);
}
/// <summary>
/// Updates the configuration of a Lambda function <a href="https://docs.aws.amazon.com/lambda/latest/dg/versioning-aliases.html">alias</a>.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the UpdateAlias service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the UpdateAlias service method, as returned by Lambda.</returns>
/// <exception cref="Amazon.Lambda.Model.InvalidParameterValueException">
/// One of the parameters in the request is invalid.
/// </exception>
/// <exception cref="Amazon.Lambda.Model.PreconditionFailedException">
/// The RevisionId provided does not match the latest RevisionId for the Lambda function
/// or alias. Call the <code>GetFunction</code> or the <code>GetAlias</code> API to retrieve
/// the latest RevisionId for your resource.
/// </exception>
/// <exception cref="Amazon.Lambda.Model.ResourceConflictException">
/// The resource already exists, or another operation is in progress.
/// </exception>
/// <exception cref="Amazon.Lambda.Model.ResourceNotFoundException">
/// The resource specified in the request does not exist.
/// </exception>
/// <exception cref="Amazon.Lambda.Model.ServiceException">
/// The AWS Lambda service encountered an internal error.
/// </exception>
/// <exception cref="Amazon.Lambda.Model.TooManyRequestsException">
/// The request throughput limit was exceeded.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lambda-2015-03-31/UpdateAlias">REST API Reference for UpdateAlias Operation</seealso>
public virtual Task<UpdateAliasResponse> UpdateAliasAsync(UpdateAliasRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var options = new InvokeOptions();
options.RequestMarshaller = UpdateAliasRequestMarshaller.Instance;
options.ResponseUnmarshaller = UpdateAliasResponseUnmarshaller.Instance;
return InvokeAsync<UpdateAliasResponse>(request, options, cancellationToken);
}
#endregion
#region UpdateEventSourceMapping
internal virtual UpdateEventSourceMappingResponse UpdateEventSourceMapping(UpdateEventSourceMappingRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = UpdateEventSourceMappingRequestMarshaller.Instance;
options.ResponseUnmarshaller = UpdateEventSourceMappingResponseUnmarshaller.Instance;
return Invoke<UpdateEventSourceMappingResponse>(request, options);
}
/// <summary>
/// Updates an event source mapping. You can change the function that AWS Lambda invokes,
/// or pause invocation and resume later from the same location.
///
///
/// <para>
/// The following error handling options are only available for stream sources (DynamoDB
/// and Kinesis):
/// </para>
/// <ul> <li>
/// <para>
/// <code>BisectBatchOnFunctionError</code> - If the function returns an error, split
/// the batch in two and retry.
/// </para>
/// </li> <li>
/// <para>
/// <code>DestinationConfig</code> - Send discarded records to an Amazon SQS queue or
/// Amazon SNS topic.
/// </para>
/// </li> <li>
/// <para>
/// <code>MaximumRecordAgeInSeconds</code> - Discard records older than the specified
/// age.
/// </para>
/// </li> <li>
/// <para>
/// <code>MaximumRetryAttempts</code> - Discard records after the specified number of
/// retries.
/// </para>
/// </li> <li>
/// <para>
/// <code>ParallelizationFactor</code> - Process multiple batches from each shard concurrently.
/// </para>
/// </li> </ul>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the UpdateEventSourceMapping service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the UpdateEventSourceMapping service method, as returned by Lambda.</returns>
/// <exception cref="Amazon.Lambda.Model.InvalidParameterValueException">
/// One of the parameters in the request is invalid.
/// </exception>
/// <exception cref="Amazon.Lambda.Model.ResourceConflictException">
/// The resource already exists, or another operation is in progress.
/// </exception>
/// <exception cref="Amazon.Lambda.Model.ResourceInUseException">
/// The operation conflicts with the resource's availability. For example, you attempted
/// to update an EventSource Mapping in CREATING, or tried to delete a EventSource mapping
/// currently in the UPDATING state.
/// </exception>
/// <exception cref="Amazon.Lambda.Model.ResourceNotFoundException">
/// The resource specified in the request does not exist.
/// </exception>
/// <exception cref="Amazon.Lambda.Model.ServiceException">
/// The AWS Lambda service encountered an internal error.
/// </exception>
/// <exception cref="Amazon.Lambda.Model.TooManyRequestsException">
/// The request throughput limit was exceeded.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lambda-2015-03-31/UpdateEventSourceMapping">REST API Reference for UpdateEventSourceMapping Operation</seealso>
public virtual Task<UpdateEventSourceMappingResponse> UpdateEventSourceMappingAsync(UpdateEventSourceMappingRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var options = new InvokeOptions();
options.RequestMarshaller = UpdateEventSourceMappingRequestMarshaller.Instance;
options.ResponseUnmarshaller = UpdateEventSourceMappingResponseUnmarshaller.Instance;
return InvokeAsync<UpdateEventSourceMappingResponse>(request, options, cancellationToken);
}
#endregion
#region UpdateFunctionCode
internal virtual UpdateFunctionCodeResponse UpdateFunctionCode(UpdateFunctionCodeRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = UpdateFunctionCodeRequestMarshaller.Instance;
options.ResponseUnmarshaller = UpdateFunctionCodeResponseUnmarshaller.Instance;
return Invoke<UpdateFunctionCodeResponse>(request, options);
}
/// <summary>
/// Updates a Lambda function's code.
///
///
/// <para>
/// The function's code is locked when you publish a version. You can't modify the code
/// of a published version, only the unpublished version.
/// </para>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the UpdateFunctionCode service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the UpdateFunctionCode service method, as returned by Lambda.</returns>
/// <exception cref="Amazon.Lambda.Model.CodeStorageExceededException">
/// You have exceeded your maximum total code size per account. <a href="https://docs.aws.amazon.com/lambda/latest/dg/limits.html">Learn
/// more</a>
/// </exception>
/// <exception cref="Amazon.Lambda.Model.InvalidParameterValueException">
/// One of the parameters in the request is invalid.
/// </exception>
/// <exception cref="Amazon.Lambda.Model.PreconditionFailedException">
/// The RevisionId provided does not match the latest RevisionId for the Lambda function
/// or alias. Call the <code>GetFunction</code> or the <code>GetAlias</code> API to retrieve
/// the latest RevisionId for your resource.
/// </exception>
/// <exception cref="Amazon.Lambda.Model.ResourceConflictException">
/// The resource already exists, or another operation is in progress.
/// </exception>
/// <exception cref="Amazon.Lambda.Model.ResourceNotFoundException">
/// The resource specified in the request does not exist.
/// </exception>
/// <exception cref="Amazon.Lambda.Model.ServiceException">
/// The AWS Lambda service encountered an internal error.
/// </exception>
/// <exception cref="Amazon.Lambda.Model.TooManyRequestsException">
/// The request throughput limit was exceeded.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lambda-2015-03-31/UpdateFunctionCode">REST API Reference for UpdateFunctionCode Operation</seealso>
public virtual Task<UpdateFunctionCodeResponse> UpdateFunctionCodeAsync(UpdateFunctionCodeRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var options = new InvokeOptions();
options.RequestMarshaller = UpdateFunctionCodeRequestMarshaller.Instance;
options.ResponseUnmarshaller = UpdateFunctionCodeResponseUnmarshaller.Instance;
return InvokeAsync<UpdateFunctionCodeResponse>(request, options, cancellationToken);
}
#endregion
#region UpdateFunctionConfiguration
internal virtual UpdateFunctionConfigurationResponse UpdateFunctionConfiguration(UpdateFunctionConfigurationRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = UpdateFunctionConfigurationRequestMarshaller.Instance;
options.ResponseUnmarshaller = UpdateFunctionConfigurationResponseUnmarshaller.Instance;
return Invoke<UpdateFunctionConfigurationResponse>(request, options);
}
/// <summary>
/// Modify the version-specific settings of a Lambda function.
///
///
/// <para>
/// When you update a function, Lambda provisions an instance of the function and its
/// supporting resources. If your function connects to a VPC, this process can take a
/// minute. During this time, you can't modify the function, but you can still invoke
/// it. The <code>LastUpdateStatus</code>, <code>LastUpdateStatusReason</code>, and <code>LastUpdateStatusReasonCode</code>
/// fields in the response from <a>GetFunctionConfiguration</a> indicate when the update
/// is complete and the function is processing events with the new configuration. For
/// more information, see <a href="https://docs.aws.amazon.com/lambda/latest/dg/functions-states.html">Function
/// States</a>.
/// </para>
///
/// <para>
/// These settings can vary between versions of a function and are locked when you publish
/// a version. You can't modify the configuration of a published version, only the unpublished
/// version.
/// </para>
///
/// <para>
/// To configure function concurrency, use <a>PutFunctionConcurrency</a>. To grant invoke
/// permissions to an account or AWS service, use <a>AddPermission</a>.
/// </para>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the UpdateFunctionConfiguration service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the UpdateFunctionConfiguration service method, as returned by Lambda.</returns>
/// <exception cref="Amazon.Lambda.Model.InvalidParameterValueException">
/// One of the parameters in the request is invalid.
/// </exception>
/// <exception cref="Amazon.Lambda.Model.PreconditionFailedException">
/// The RevisionId provided does not match the latest RevisionId for the Lambda function
/// or alias. Call the <code>GetFunction</code> or the <code>GetAlias</code> API to retrieve
/// the latest RevisionId for your resource.
/// </exception>
/// <exception cref="Amazon.Lambda.Model.ResourceConflictException">
/// The resource already exists, or another operation is in progress.
/// </exception>
/// <exception cref="Amazon.Lambda.Model.ResourceNotFoundException">
/// The resource specified in the request does not exist.
/// </exception>
/// <exception cref="Amazon.Lambda.Model.ServiceException">
/// The AWS Lambda service encountered an internal error.
/// </exception>
/// <exception cref="Amazon.Lambda.Model.TooManyRequestsException">
/// The request throughput limit was exceeded.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lambda-2015-03-31/UpdateFunctionConfiguration">REST API Reference for UpdateFunctionConfiguration Operation</seealso>
public virtual Task<UpdateFunctionConfigurationResponse> UpdateFunctionConfigurationAsync(UpdateFunctionConfigurationRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var options = new InvokeOptions();
options.RequestMarshaller = UpdateFunctionConfigurationRequestMarshaller.Instance;
options.ResponseUnmarshaller = UpdateFunctionConfigurationResponseUnmarshaller.Instance;
return InvokeAsync<UpdateFunctionConfigurationResponse>(request, options, cancellationToken);
}
#endregion
#region UpdateFunctionEventInvokeConfig
internal virtual UpdateFunctionEventInvokeConfigResponse UpdateFunctionEventInvokeConfig(UpdateFunctionEventInvokeConfigRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = UpdateFunctionEventInvokeConfigRequestMarshaller.Instance;
options.ResponseUnmarshaller = UpdateFunctionEventInvokeConfigResponseUnmarshaller.Instance;
return Invoke<UpdateFunctionEventInvokeConfigResponse>(request, options);
}
/// <summary>
/// Updates the configuration for asynchronous invocation for a function, version, or
/// alias.
///
///
/// <para>
/// To configure options for asynchronous invocation, use <a>PutFunctionEventInvokeConfig</a>.
/// </para>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the UpdateFunctionEventInvokeConfig service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the UpdateFunctionEventInvokeConfig service method, as returned by Lambda.</returns>
/// <exception cref="Amazon.Lambda.Model.InvalidParameterValueException">
/// One of the parameters in the request is invalid.
/// </exception>
/// <exception cref="Amazon.Lambda.Model.ResourceNotFoundException">
/// The resource specified in the request does not exist.
/// </exception>
/// <exception cref="Amazon.Lambda.Model.ServiceException">
/// The AWS Lambda service encountered an internal error.
/// </exception>
/// <exception cref="Amazon.Lambda.Model.TooManyRequestsException">
/// The request throughput limit was exceeded.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lambda-2015-03-31/UpdateFunctionEventInvokeConfig">REST API Reference for UpdateFunctionEventInvokeConfig Operation</seealso>
public virtual Task<UpdateFunctionEventInvokeConfigResponse> UpdateFunctionEventInvokeConfigAsync(UpdateFunctionEventInvokeConfigRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var options = new InvokeOptions();
options.RequestMarshaller = UpdateFunctionEventInvokeConfigRequestMarshaller.Instance;
options.ResponseUnmarshaller = UpdateFunctionEventInvokeConfigResponseUnmarshaller.Instance;
return InvokeAsync<UpdateFunctionEventInvokeConfigResponse>(request, options, cancellationToken);
}
#endregion
}
} | 54.034408 | 648 | 0.672908 | [
"Apache-2.0"
] | Vfialkin/aws-sdk-net | sdk/src/Services/Lambda/Generated/_mobile/AmazonLambdaClient.cs | 174,315 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
public class ComparatorInput : TabButton
{
public Text text;
public ComparatorEditorPanel panel;
public void SetType(int i)
{
panel.SetType(group.tabButtons.IndexOf(this), i == 1);
}
public override void OnPointerClick(PointerEventData eventData)
{
return;
}
public override void Remove()
{
panel.Remove(transform.GetSiblingIndex() - 2);
((TabComparatorInputsGroup)group).Remove(this);
group.Unsubscribe(this);
Destroy(gameObject);
}
}
| 22.2 | 67 | 0.681682 | [
"Apache-2.0"
] | Partfinger/Diploma-project | Diploma Project/Assets/Scripts/UI/EditedPanels/Panels/ComparatorInput.cs | 668 | C# |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UnityEngine;
#if UNITY_2017_2_OR_NEWER
using UnityEngine.XR;
#else
using XRSettings = UnityEngine.VR.VRSettings;
using XRDevice = UnityEngine.VR.VRDevice;
#endif
namespace Valve.VR
{
public class SteamVR_Behaviour : MonoBehaviour
{
private const string openVRDeviceName = "OpenVR";
public static bool forcingInitialization = false;
private static SteamVR_Behaviour _instance;
public static SteamVR_Behaviour instance
{
get
{
if (_instance == null)
{
Initialize(false);
}
return _instance;
}
}
public bool initializeSteamVROnAwake = true;
public bool doNotDestroy = true;
[HideInInspector]
public SteamVR_Render steamvr_render;
internal static bool isPlaying = false;
private static bool initializing = false;
public static void Initialize(bool forceUnityVRToOpenVR = false)
{
if (_instance == null && initializing == false)
{
initializing = true;
GameObject steamVRObject = null;
if (forceUnityVRToOpenVR)
forcingInitialization = true;
SteamVR_Render renderInstance = GameObject.FindObjectOfType<SteamVR_Render>();
if (renderInstance != null)
steamVRObject = renderInstance.gameObject;
SteamVR_Behaviour behaviourInstance = GameObject.FindObjectOfType<SteamVR_Behaviour>();
if (behaviourInstance != null)
steamVRObject = behaviourInstance.gameObject;
if (steamVRObject == null)
{
GameObject objectInstance = new GameObject("[SteamVR]");
_instance = objectInstance.AddComponent<SteamVR_Behaviour>();
_instance.steamvr_render = objectInstance.AddComponent<SteamVR_Render>();
}
else
{
behaviourInstance = steamVRObject.GetComponent<SteamVR_Behaviour>();
if (behaviourInstance == null)
behaviourInstance = steamVRObject.AddComponent<SteamVR_Behaviour>();
if (renderInstance != null)
behaviourInstance.steamvr_render = renderInstance;
else
{
behaviourInstance.steamvr_render = steamVRObject.GetComponent<SteamVR_Render>();
if (behaviourInstance.steamvr_render == null)
behaviourInstance.steamvr_render = steamVRObject.AddComponent<SteamVR_Render>();
}
_instance = behaviourInstance;
}
//if (_instance != null && _instance.doNotDestroy)
//GameObject.DontDestroyOnLoad(_instance.transform.root.gameObject);
//initializing = false;
}
}
protected void Awake()
{
isPlaying = true;
if (initializeSteamVROnAwake && forcingInitialization == false)
InitializeSteamVR();
}
public void InitializeSteamVR(bool forceUnityVRToOpenVR = false)
{
if (forceUnityVRToOpenVR)
{
forcingInitialization = true;
if (initializeCoroutine != null)
StopCoroutine(initializeCoroutine);
if (XRSettings.loadedDeviceName == openVRDeviceName)
EnableOpenVR();
else
initializeCoroutine = StartCoroutine(DoInitializeSteamVR(forceUnityVRToOpenVR));
}
else
{
SteamVR.Initialize(false);
}
}
private Coroutine initializeCoroutine;
#if UNITY_2018_3_OR_NEWER
private bool loadedOpenVRDeviceSuccess = false;
private IEnumerator DoInitializeSteamVR(bool forceUnityVRToOpenVR = false)
{
XRDevice.deviceLoaded += XRDevice_deviceLoaded;
XRSettings.LoadDeviceByName(openVRDeviceName);
while (loadedOpenVRDeviceSuccess == false)
{
yield return null;
}
XRDevice.deviceLoaded -= XRDevice_deviceLoaded;
EnableOpenVR();
}
private void XRDevice_deviceLoaded(string deviceName)
{
if (deviceName == openVRDeviceName)
{
loadedOpenVRDeviceSuccess = true;
}
else
{
Debug.LogError("<b>[SteamVR]</b> Tried to async load: " + openVRDeviceName + ". Loaded: " + deviceName);
loadedOpenVRDeviceSuccess = true; //try anyway
}
}
#else
private IEnumerator DoInitializeSteamVR(bool forceUnityVRToOpenVR = false)
{
XRSettings.LoadDeviceByName(openVRDeviceName);
yield return null;
EnableOpenVR();
}
#endif
private void EnableOpenVR()
{
XRSettings.enabled = true;
SteamVR.Initialize(false);
initializeCoroutine = null;
forcingInitialization = false;
}
#if UNITY_EDITOR
//only stop playing if the unity editor is running
private void OnDestroy()
{
isPlaying = false;
}
#endif
#if UNITY_2017_1_OR_NEWER
protected void OnEnable()
{
Application.onBeforeRender += OnBeforeRender;
SteamVR_Events.System(EVREventType.VREvent_Quit).Listen(OnQuit);
}
protected void OnDisable()
{
Application.onBeforeRender -= OnBeforeRender;
SteamVR_Events.System(EVREventType.VREvent_Quit).Remove(OnQuit);
}
protected void OnBeforeRender()
{
PreCull();
}
#else
protected void OnEnable()
{
Camera.onPreCull += OnCameraPreCull;
SteamVR_Events.System(EVREventType.VREvent_Quit).Listen(OnQuit);
}
protected void OnDisable()
{
Camera.onPreCull -= OnCameraPreCull;
SteamVR_Events.System(EVREventType.VREvent_Quit).Remove(OnQuit);
}
protected void OnCameraPreCull(Camera cam)
{
if (!cam.stereoEnabled)
return;
PreCull();
}
#endif
protected static int lastFrameCount = -1;
protected void PreCull()
{
// Only update poses on the first camera per frame.
if (Time.frameCount != lastFrameCount)
{
lastFrameCount = Time.frameCount;
SteamVR_Input.OnPreCull();
}
}
protected void FixedUpdate()
{
SteamVR_Input.FixedUpdate();
}
protected void LateUpdate()
{
SteamVR_Input.LateUpdate();
}
protected void Update()
{
SteamVR_Input.Update();
}
protected void OnQuit(VREvent_t vrEvent)
{
#if UNITY_EDITOR
UnityEditor.EditorApplication.isPlaying = false;
#else
Application.Quit();
#endif
}
}
}
| 30.092742 | 120 | 0.557417 | [
"MIT"
] | Tikhul/rube-goldberg | Assets/SteamVR/Scripts/SteamVR_Behaviour.cs | 7,465 | C# |
/*
* Copyright (c) 2013-present, The Eye Tribe.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the LICENSE file in the root directory of this source tree.
*
*/
using System;
using Newtonsoft.Json;
namespace EyeTribe.ClientSdk.Data
{
public class CalibrationPoint
{
/// <summary>
/// State defines that no data is available for calibration point
/// </summary>
public static readonly int STATE_NO_DATA = 0;
/// <summary>
/// State defines that calibration point should be resampled
/// </summary>
public static readonly int STATE_RESAMPLE = 1;
/// <summary>
/// State defines that calibration point was successfully sampled
/// </summary>
public static readonly int STATE_OK = 2;
/// <summary>
/// State of calibration point
/// </summary>
[JsonProperty(PropertyName = Protocol.CALIBRESULT_STATE)]
public int State { get; set; }
/// <summary>
/// Coordinate in pixels
/// </summary>
[JsonProperty(PropertyName = Protocol.CALIBRESULT_COORDINATES)]
public Point2D Coordinates { get; set; }
/// <summary>
/// Mean estimated coordinates
/// </summary>
[JsonProperty(PropertyName = Protocol.CALIBRESULT_MEAN_ESTIMATED_COORDINATES)]
public Point2D MeanEstimatedCoords { get; set; }
/// <summary>
/// Accuracy
/// </summary>
[JsonProperty(PropertyName = Protocol.CALIBRESULT_ACCURACIES_DEGREES)]
public Accuracy Accuracy { get; set; }
/// <summary>
/// Mean Error
/// </summary>
[JsonProperty(PropertyName = Protocol.CALIBRESULT_MEAN_ERRORS_PIXELS)]
public MeanError MeanError { get; set; }
/// <summary>
/// Standard Deviation
/// </summary>
[JsonProperty(PropertyName = Protocol.CALIBRESULT_STANDARD_DEVIATION_PIXELS)]
public StandardDeviation StandardDeviation { get; set; }
public CalibrationPoint()
{
Coordinates = Point2D.Zero;
MeanEstimatedCoords = Point2D.Zero;
Accuracy = new Accuracy();
MeanError = new MeanError();
StandardDeviation = new StandardDeviation();
}
public override bool Equals(Object o)
{
if (ReferenceEquals(this, o))
return true;
if (!(o is CalibrationPoint))
return false;
var other = o as CalibrationPoint;
return
this.State == other.State &&
this.Coordinates.Equals(other.Coordinates) &&
this.MeanEstimatedCoords.Equals(other.MeanEstimatedCoords) &&
this.Accuracy.Equals(other.Accuracy) &&
this.MeanError.Equals(other.MeanError) &&
this.StandardDeviation.Equals(other.StandardDeviation);
}
public override int GetHashCode()
{
int hash = 157;
hash = hash * 953 + State.GetHashCode();
hash = hash * 953 + Coordinates.GetHashCode();
hash = hash * 953 + MeanEstimatedCoords.GetHashCode();
hash = hash * 953 + Accuracy.GetHashCode();
hash = hash * 953 + MeanError.GetHashCode();
hash = hash * 953 + StandardDeviation.GetHashCode();
return hash;
}
}
} | 32.607477 | 129 | 0.582975 | [
"BSD-2-Clause"
] | EyeTribe/tet-csharp-client | sdk/Data/CalibrationPoint.cs | 3,491 | C# |
// Sharp Essentials Controls
// Copyright 2017 Matthew Hamilton - matthamilton@live.com
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq.Expressions;
using System.Windows.Input;
namespace SharpEssentials.Controls.Mvvm.Commands.Builder
{
/// <summary>
/// Interface for an object that aids in creating complex <see cref="ICommand"/>s.
/// </summary>
/// <typeparam name="TSource">The type of object for which a command is being built</typeparam>
public interface ICommandBuilder<TSource> where TSource : INotifyPropertyChanged
{
/// <summary>
/// Indicates that a command is bound to the given boolean property's value to determine
/// whether it can execute.
/// </summary>
/// <param name="predicateProperty">The boolean property that determines whether a command can execute</param>
/// <returns>A builder for a command bound to a property</returns>
ICommandCompleter DependsOn(Expression<Func<TSource, bool>> predicateProperty);
/// <summary>
/// Indicates that a command is bound to a property of each element of a collection to determine
/// whether it can execute.
/// </summary>
/// <typeparam name="TChild">The type of child object</typeparam>
/// <param name="collection">The collection whose elements determine whether a command can execute</param>
/// <returns>A builder for a command bound to a child property</returns>
IChildBoundCommandBuilder<TSource, TChild> DependsOnCollection<TChild>(Expression<Func<TSource, IEnumerable<TChild>>> collection)
where TChild : INotifyPropertyChanged;
}
} | 44.895833 | 131 | 0.749884 | [
"Apache-2.0"
] | mthamil/SharpEssentials.Controls | SharpEssentials.Controls/Mvvm/Commands/Builder/ICommandBuilder.cs | 2,155 | C# |
using System.Threading.Tasks;
using Application.User;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
namespace API.Controllers
{
public class UserController : BaseController
{
[AllowAnonymous]
[HttpPost("login")]
public async Task<ActionResult<User>> Login(Login.Query query)
{
return await Mediator.Send(query);
}
[AllowAnonymous]
[HttpPost("register")]
public async Task<ActionResult<User>> Register(Register.Command command)
{
return await Mediator.Send(command);
}
[HttpGet]
public async Task<ActionResult<User>> CurrentUser()
{
return await Mediator.Send(new CurrentUser.Query());
}
}
} | 25.225806 | 80 | 0.62532 | [
"MIT"
] | mustafizur8888/Asp.netCoreWithReact | API/Controllers/UserController.cs | 782 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
using Microsoft.Bot.Builder.Skills.Models.Manifest;
using Microsoft.Bot.Builder.Solutions;
using Microsoft.Bot.Configuration;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace Microsoft.Bot.Builder.Skills
{
public class SkillManifestGenerator
{
private const string _skillRoute = "/api/skill/messages";
private readonly HttpClient _httpClient;
public SkillManifestGenerator(HttpClient httpClient)
{
_httpClient = httpClient;
}
public async Task<SkillManifest> GenerateManifest(string manifestFile, string appId, Dictionary<string, BotSettingsBase.CognitiveModelConfiguration> cognitiveModels, string uriBase, bool inlineTriggerUtterances = false)
{
SkillManifest skillManifest = null;
if (string.IsNullOrEmpty(manifestFile))
{
throw new ArgumentNullException(nameof(manifestFile));
}
if (string.IsNullOrEmpty(appId))
{
throw new ArgumentNullException(nameof(appId));
}
if (cognitiveModels == null)
{
throw new ArgumentNullException(nameof(cognitiveModels));
}
if (string.IsNullOrEmpty(uriBase))
{
throw new ArgumentNullException(nameof(uriBase));
}
// Each skill has a manifest template in the root directory and is used as foundation for the generated manifest
using (StreamReader reader = new StreamReader(manifestFile))
{
skillManifest = JsonConvert.DeserializeObject<SkillManifest>(reader.ReadToEnd());
if (string.IsNullOrEmpty(skillManifest.Id))
{
throw new Exception("Skill manifest ID property was not present in the template manifest file.");
}
if (string.IsNullOrEmpty(skillManifest.Name))
{
throw new Exception("Skill manifest Name property was not present in the template manifest file.");
}
skillManifest.MSAappId = appId;
skillManifest.Endpoint = new Uri($"{uriBase}{_skillRoute}");
if (skillManifest.IconUrl != null)
{
skillManifest.IconUrl = new Uri($"{uriBase}/{skillManifest.IconUrl.ToString()}");
}
// The manifest can either return a pointer to the triggering utterances or include them inline in the manifest
// If the developer has requested inline, we need to go through all utteranceSource references and retrieve the utterances and insert inline
if (inlineTriggerUtterances)
{
Dictionary<string, dynamic> localeLuisModels = new Dictionary<string, dynamic>();
// Retrieve all of the LUIS model definitions deployed and configured for the skill which could have multiple locales
// These are used to match the model name and intent so we can retrieve the utterances
foreach (var localeSet in cognitiveModels)
{
// Download/cache all the LUIS models configured for this locale (key is the locale name)
await PreFetchLuisModelContents(localeLuisModels, localeSet.Key, localeSet.Value.LanguageModels);
}
foreach (var action in skillManifest.Actions)
{
// Is this Action triggerd by LUIS utterances rather than events?
if (action.Definition.Triggers.UtteranceSources != null)
{
// We will retrieve all utterances from the referenced source and aggregate into one new aggregated list of utterances per action
action.Definition.Triggers.Utterances = new List<Utterance>();
var utterancesToAdd = new List<string>();
// Iterate through each utterance source, one per locale.
foreach (UtteranceSource utteranceSource in action.Definition.Triggers.UtteranceSources)
{
// There may be multiple intents linked to this
foreach (var source in utteranceSource.Source)
{
// Retrieve the intent mapped to this action trigger
var intentIndex = source.IndexOf('#');
if (intentIndex == -1)
{
throw new Exception($"Utterance source for action: {action.Id} didn't include an intent reference: {source}");
}
// We now have the name of the LUIS model and the Intent
var modelName = source.Substring(0, intentIndex);
string intentToMatch = source.Substring(intentIndex + 1);
// Find the LUIS model from our cache by matching on the locale/modelname
var model = localeLuisModels.SingleOrDefault(m => string.Equals(m.Key, $"{utteranceSource.Locale}_{modelName}", StringComparison.CurrentCultureIgnoreCase)).Value;
if (model == null)
{
throw new Exception($"Utterance source (locale: {utteranceSource.Locale}) for action: '{action.Id}' references the '{modelName}' model which cannot be found in the currently deployed configuration.");
}
// Validate that the intent in the manifest exists in this LUIS model
IEnumerable<JToken> intents = model.intents;
if (!intents.Any(i => string.Equals(i["name"].ToString(), intentToMatch, StringComparison.CurrentCultureIgnoreCase)))
{
throw new Exception($"Utterance source for action: '{action.Id}' references the '{modelName}' model and '{intentToMatch}' intent which does not exist.");
}
// Retrieve the utterances that match this intent
IEnumerable<JToken> utterancesList = model.utterances;
var utterances = utterancesList.Where(s => string.Equals(s["intent"].ToString(), intentToMatch, StringComparison.CurrentCultureIgnoreCase));
if (!utterances.Any())
{
throw new Exception($"Utterance source for action: '{action.Id}' references the '{modelName}' model and '{intentToMatch}' intent which has no utterances.");
}
foreach (JObject utterance in utterances)
{
utterancesToAdd.Add(utterance["text"].Value<string>());
}
}
action.Definition.Triggers.Utterances.Add(new Utterance(utteranceSource.Locale, utterancesToAdd.ToArray()));
}
}
}
}
}
return skillManifest;
}
/// <summary>
/// Retrieve the LUIS model definition for each LUIS model registered in this skill so we have the utterance training data.
/// </summary>
/// <param name="luisServices">List of LuisServices.</param>
/// <returns>Collection of LUIS model definitions grouped by model name.</returns>
private async Task PreFetchLuisModelContents(Dictionary<string, dynamic> localeModelUtteranceCache, string locale, List<LuisService> luisServices)
{
// For each luisSource we identify the Intent and match with available luisServices to identify the LuisAppId which we update
foreach (LuisService luisService in luisServices)
{
string exportModelUri = string.Format("https://{0}.api.cognitive.microsoft.com/luis/api/v2.0/apps/{1}/versions/{2}/export", luisService.Region, luisService.AppId, luisService.Version);
_httpClient.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", luisService.AuthoringKey);
var httpResponse = await _httpClient.GetAsync(exportModelUri);
if (httpResponse.IsSuccessStatusCode)
{
string json = await httpResponse.Content.ReadAsStringAsync();
var luisApp = JsonConvert.DeserializeObject<dynamic>(json);
localeModelUtteranceCache.Add($"{locale}_{luisService.Id}", luisApp);
}
}
}
}
} | 53.4375 | 240 | 0.55194 | [
"MIT"
] | 3ve4me/botframework-solutions | lib/csharp/microsoft.bot.builder.skills/Microsoft.Bot.Builder.Skills/Manifest/SkillManifestGenerator.cs | 9,407 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using CppMathWrapper;
using std;
namespace CsharpSample
{
class Program
{
static void Main(string[] args)
{
ManagedCppMathWrapper managedCppMathWrapper = new ManagedCppMathWrapper();
var values = new List<Tuple<double, uint>>();
values.Add(new Tuple<double, uint>(100.1, 1000));
values.Add(new Tuple<double, uint>(99.98, 1350));
values.Add(new Tuple<double, uint>(104.25, 790));
double vwap = managedCppMathWrapper.Vwap(values);
Console.WriteLine("vwap=" + vwap);
Console.ReadLine();
}
}
}
| 25.766667 | 87 | 0.596378 | [
"MIT"
] | sharpnex/interviews | RuntimeIssues/CppWrapper/CsharpSample/Program.cs | 775 | C# |
// *** WARNING: this file was generated by the Pulumi SDK Generator. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.AzureNextGen.Cache.V20200601
{
/// <summary>
/// Response to put/get linked server (with properties) for Redis cache.
/// </summary>
public partial class LinkedServer : Pulumi.CustomResource
{
/// <summary>
/// Fully qualified resourceId of the linked redis cache.
/// </summary>
[Output("linkedRedisCacheId")]
public Output<string> LinkedRedisCacheId { get; private set; } = null!;
/// <summary>
/// Location of the linked redis cache.
/// </summary>
[Output("linkedRedisCacheLocation")]
public Output<string> LinkedRedisCacheLocation { get; private set; } = null!;
/// <summary>
/// Resource name.
/// </summary>
[Output("name")]
public Output<string> Name { get; private set; } = null!;
/// <summary>
/// Terminal state of the link between primary and secondary redis cache.
/// </summary>
[Output("provisioningState")]
public Output<string> ProvisioningState { get; private set; } = null!;
/// <summary>
/// Role of the linked server.
/// </summary>
[Output("serverRole")]
public Output<string> ServerRole { get; private set; } = null!;
/// <summary>
/// Resource type.
/// </summary>
[Output("type")]
public Output<string> Type { get; private set; } = null!;
/// <summary>
/// Create a LinkedServer resource with the given unique name, arguments, and options.
/// </summary>
///
/// <param name="name">The unique name of the resource</param>
/// <param name="args">The arguments used to populate this resource's properties</param>
/// <param name="options">A bag of options that control this resource's behavior</param>
public LinkedServer(string name, LinkedServerArgs args, CustomResourceOptions? options = null)
: base("azure-nextgen:cache/v20200601:LinkedServer", name, args ?? new LinkedServerArgs(), MakeResourceOptions(options, ""))
{
}
private LinkedServer(string name, Input<string> id, CustomResourceOptions? options = null)
: base("azure-nextgen:cache/v20200601:LinkedServer", name, null, MakeResourceOptions(options, id))
{
}
private static CustomResourceOptions MakeResourceOptions(CustomResourceOptions? options, Input<string>? id)
{
var defaultOptions = new CustomResourceOptions
{
Version = Utilities.Version,
Aliases =
{
new Pulumi.Alias { Type = "azure-nextgen:cache/latest:LinkedServer"},
new Pulumi.Alias { Type = "azure-nextgen:cache/v20170201:LinkedServer"},
new Pulumi.Alias { Type = "azure-nextgen:cache/v20171001:LinkedServer"},
new Pulumi.Alias { Type = "azure-nextgen:cache/v20180301:LinkedServer"},
new Pulumi.Alias { Type = "azure-nextgen:cache/v20190701:LinkedServer"},
},
};
var merged = CustomResourceOptions.Merge(defaultOptions, options);
// Override the ID if one was specified for consistency with other language SDKs.
merged.Id = id ?? merged.Id;
return merged;
}
/// <summary>
/// Get an existing LinkedServer resource's state with the given name, ID, and optional extra
/// properties used to qualify the lookup.
/// </summary>
///
/// <param name="name">The unique name of the resulting resource.</param>
/// <param name="id">The unique provider ID of the resource to lookup.</param>
/// <param name="options">A bag of options that control this resource's behavior</param>
public static LinkedServer Get(string name, Input<string> id, CustomResourceOptions? options = null)
{
return new LinkedServer(name, id, options);
}
}
public sealed class LinkedServerArgs : Pulumi.ResourceArgs
{
/// <summary>
/// Fully qualified resourceId of the linked redis cache.
/// </summary>
[Input("linkedRedisCacheId", required: true)]
public Input<string> LinkedRedisCacheId { get; set; } = null!;
/// <summary>
/// Location of the linked redis cache.
/// </summary>
[Input("linkedRedisCacheLocation", required: true)]
public Input<string> LinkedRedisCacheLocation { get; set; } = null!;
/// <summary>
/// The name of the linked server that is being added to the Redis cache.
/// </summary>
[Input("linkedServerName", required: true)]
public Input<string> LinkedServerName { get; set; } = null!;
/// <summary>
/// The name of the Redis cache.
/// </summary>
[Input("name", required: true)]
public Input<string> Name { get; set; } = null!;
/// <summary>
/// The name of the resource group.
/// </summary>
[Input("resourceGroupName", required: true)]
public Input<string> ResourceGroupName { get; set; } = null!;
/// <summary>
/// Role of the linked server.
/// </summary>
[Input("serverRole", required: true)]
public Input<string> ServerRole { get; set; } = null!;
public LinkedServerArgs()
{
}
}
}
| 39.442177 | 136 | 0.591756 | [
"Apache-2.0"
] | test-wiz-sec/pulumi-azure-nextgen | sdk/dotnet/Cache/V20200601/LinkedServer.cs | 5,798 | C# |
using System;
using System.IdentityModel.Protocols.WSTrust;
using System.Linq;
using System.ServiceModel.Description;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Client;
namespace Microsoft.PowerPlatform.Dataverse.Client.Connector.OnPremises
{
internal sealed partial class ServiceConfiguration<TService>
{
#region IServiceManagement
public AuthenticationCredentials Authenticate(AuthenticationCredentials authenticationCredentials)
{
ClientExceptionHelper.ThrowIfNull(authenticationCredentials, "authenticationCredentials");
switch (AuthenticationType)
{
case AuthenticationProviderType.OnlineFederation:
return AuthenticateOnlineFederationInternal(authenticationCredentials);
case AuthenticationProviderType.Federation:
return AuthenticateFederationInternal(authenticationCredentials);
case AuthenticationProviderType.ActiveDirectory:
{
ServiceMetadataUtility.AdjustUserNameForWindows(authenticationCredentials.ClientCredentials);
return authenticationCredentials;
}
default:
return authenticationCredentials;
}
}
private AuthenticationCredentials AuthenticateFederationInternal(AuthenticationCredentials authenticationCredentials)
{
if (authenticationCredentials.SecurityTokenResponse != null)
{
return AuthenticateFederationTokenInternal(authenticationCredentials);
}
if (authenticationCredentials.AppliesTo == null)
{
authenticationCredentials.AppliesTo = CurrentServiceEndpoint.Address.Uri;
}
authenticationCredentials.EndpointType = GetCredentialsEndpointType(authenticationCredentials.ClientCredentials);
authenticationCredentials.IssuerEndpoints = authenticationCredentials.HomeRealm != null ? CrossRealmIssuerEndpoints[authenticationCredentials.HomeRealm] : IssuerEndpoints;
authenticationCredentials.SecurityTokenResponse = AuthenticateInternal(authenticationCredentials);
return authenticationCredentials;
}
private AuthenticationCredentials AuthenticateFederationTokenInternal(AuthenticationCredentials authenticationCredentials)
{
AuthenticationCredentials returnCredentials = new AuthenticationCredentials();
returnCredentials.SupportingCredentials = authenticationCredentials;
if (authenticationCredentials.AppliesTo == null)
{
authenticationCredentials.AppliesTo = CurrentServiceEndpoint.Address.Uri;
}
authenticationCredentials.EndpointType = _tokenEndpointType;
authenticationCredentials.KeyType = string.Empty;
authenticationCredentials.IssuerEndpoints = IssuerEndpoints;
returnCredentials.SecurityTokenResponse = AuthenticateInternal(authenticationCredentials);
return returnCredentials;
}
/// <summary>
/// Supported matrix:
/// 1. Security Token Response populated: We will submit the token to Org ID to exchange for a CRM token.
/// 2. Credentials passed.
/// a. The UserPrincipalName MUST be populated if the Username/Windows username is empty AND the Home Realm Uri is null.
/// a. If the Home Realm
/// </summary>
/// <param name="authenticationCredentials"></param>
/// <returns></returns>
private AuthenticationCredentials AuthenticateOnlineFederationInternal(AuthenticationCredentials authenticationCredentials)
{
var onlinePolicy = PolicyConfiguration as OnlinePolicyConfiguration;
ClientExceptionHelper.ThrowIfNull(onlinePolicy, "onlinePolicy");
OrgIdentityProviderTrustConfiguration liveTrustConfig = onlinePolicy.OnlineProviders.Values.OfType<OrgIdentityProviderTrustConfiguration>().FirstOrDefault();
ClientExceptionHelper.ThrowIfNull(liveTrustConfig, "liveTrustConfig");
// Two scenarios:
// 1. Managed Credentials
// 2. Federated Credentials
// 3. A token to submit to OrgID.
if (authenticationCredentials.SecurityTokenResponse != null)
{
return AuthenticateOnlineFederationTokenInternal(liveTrustConfig, authenticationCredentials);
}
bool authWithOrgId = true;
if (authenticationCredentials.HomeRealm == null)
{
IdentityProvider identityProvider = !string.IsNullOrEmpty(authenticationCredentials.UserPrincipalName) ? GetIdentityProvider(authenticationCredentials.UserPrincipalName) : GetIdentityProvider(authenticationCredentials.ClientCredentials);
ClientExceptionHelper.ThrowIfNull(identityProvider, "identityProvider");
authenticationCredentials.HomeRealm = identityProvider.ServiceUrl;
authWithOrgId = identityProvider.IdentityProviderType == IdentityProviderType.OrgId;
if (authWithOrgId)
{
ClientExceptionHelper.Assert(onlinePolicy.OnlineProviders.ContainsKey(authenticationCredentials.HomeRealm), "Online Identity Provider NOT found! {0}", identityProvider.ServiceUrl);
}
}
authenticationCredentials.AppliesTo = new Uri(liveTrustConfig.AppliesTo);
authenticationCredentials.IssuerEndpoints = this.IssuerEndpoints;
authenticationCredentials.KeyType = KeyTypes.Bearer;
authenticationCredentials.EndpointType = TokenServiceCredentialType.Username;
if (authWithOrgId)
{
return AuthenticateTokenWithOrgIdForCrm(authenticationCredentials);
}
// Authenticate with ADFS to retrieve a token for OrgId
AuthenticationCredentials adfsCredentials = AuthenticateWithADFSForOrgId(authenticationCredentials, liveTrustConfig.Identifier);
return AuthenticateFederatedTokenWithOrgIdForCRM(adfsCredentials);
}
/// <summary>
/// Authenticates a federated token with OrgID to retrieve a token for CRM
/// </summary>
/// <param name="authenticationCredentials"></param>
private AuthenticationCredentials AuthenticateFederatedTokenWithOrgIdForCRM(AuthenticationCredentials authenticationCredentials)
{
ClientExceptionHelper.ThrowIfNull(authenticationCredentials, "authenticationCredentials");
ClientExceptionHelper.ThrowIfNull(authenticationCredentials.SecurityTokenResponse, "authenticationCredentials.SecurityTokenResponse");
AuthenticationCredentials returnCredentials = new AuthenticationCredentials();
returnCredentials.SupportingCredentials = authenticationCredentials;
returnCredentials.AppliesTo = authenticationCredentials.AppliesTo;
returnCredentials.IssuerEndpoints = authenticationCredentials.IssuerEndpoints;
returnCredentials.EndpointType = TokenServiceCredentialType.SymmetricToken;
returnCredentials.SecurityTokenResponse = AuthenticateInternal(returnCredentials);
return returnCredentials;
}
/// <summary>
/// Authenticates with ADFS to retrieve a federated token to exchange with OrgId for CRM
/// </summary>
/// <param name="authenticationCredentials"></param>
/// <param name="identifier"></param>
private AuthenticationCredentials AuthenticateWithADFSForOrgId(AuthenticationCredentials authenticationCredentials, Uri identifier)
{
AuthenticationCredentials returnCredentials = new AuthenticationCredentials();
returnCredentials.AppliesTo = authenticationCredentials.AppliesTo;
returnCredentials.SupportingCredentials = authenticationCredentials;
returnCredentials.AppliesTo = authenticationCredentials.AppliesTo;
returnCredentials.IssuerEndpoints = authenticationCredentials.IssuerEndpoints;
returnCredentials.EndpointType = TokenServiceCredentialType.SymmetricToken;
// We are authenticating against ADFS with the credentials.
authenticationCredentials.AppliesTo = identifier;
authenticationCredentials.KeyType = KeyTypes.Bearer;
authenticationCredentials.EndpointType = GetCredentialsEndpointType(authenticationCredentials.ClientCredentials);
authenticationCredentials.IssuerEndpoints = CrossRealmIssuerEndpoints[authenticationCredentials.HomeRealm];
returnCredentials.SecurityTokenResponse = AuthenticateInternal(authenticationCredentials);
return returnCredentials;
}
private AuthenticationCredentials AuthenticateTokenWithOrgIdForCrm(AuthenticationCredentials authenticationCredentials)
{
ClientExceptionHelper.ThrowIfNull(authenticationCredentials, "authenticationCredentials");
AuthenticationCredentials returnAcsCredentials = new AuthenticationCredentials();
returnAcsCredentials.SupportingCredentials = authenticationCredentials;
returnAcsCredentials.AppliesTo = authenticationCredentials.AppliesTo;
returnAcsCredentials.IssuerEndpoints = authenticationCredentials.IssuerEndpoints;
returnAcsCredentials.KeyType = KeyTypes.Bearer;
returnAcsCredentials.EndpointType = TokenServiceCredentialType.Username;
returnAcsCredentials.SecurityTokenResponse = AuthenticateInternal(authenticationCredentials);
return returnAcsCredentials;
}
private AuthenticationCredentials AuthenticateOnlineFederationTokenInternal(IdentityProviderTrustConfiguration liveTrustConfig, AuthenticationCredentials authenticationCredentials)
{
AuthenticationCredentials returnCredentials = new AuthenticationCredentials();
returnCredentials.SupportingCredentials = authenticationCredentials;
string appliesTo = authenticationCredentials.AppliesTo != null ? authenticationCredentials.AppliesTo.AbsoluteUri : liveTrustConfig.AppliesTo;
Uri tokenEndpoint = authenticationCredentials.HomeRealm ?? liveTrustConfig.Endpoint.GetServiceRoot();
returnCredentials.SecurityTokenResponse = AuthenticateCrossRealm(authenticationCredentials.SecurityTokenResponse.Token, appliesTo, tokenEndpoint);
return returnCredentials;
}
#endregion IServiceManagement
internal IdentityProvider GetIdentityProvider(ClientCredentials clientCredentials)
{
string userName = string.Empty;
if (!string.IsNullOrWhiteSpace(clientCredentials.UserName.UserName))
{
userName = ExtractUserName(clientCredentials.UserName.UserName);
}
else if (!string.IsNullOrWhiteSpace(clientCredentials.Windows.ClientCredential.UserName))
{
userName = ExtractUserName(clientCredentials.Windows.ClientCredential.UserName);
}
ClientExceptionHelper.Assert(!string.IsNullOrEmpty(userName), "clientCredentials.UserName.UserName or clientCredentials.Windows.ClientCredential.UserName MUST be populated!");
return GetIdentityProvider(userName);
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic")]
private string ExtractUserName(string userName)
{
return userName.Contains('@') ? userName : string.Empty;
}
}
}
| 45.374449 | 241 | 0.821456 | [
"MIT"
] | mohsinonxrm/PowerPlatform-DataverseServiceClient | src/GeneralTools/DataverseClient/Client/Connector/OnPremises/ServiceConfiguration.cs | 10,300 | C# |
using System;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Data.Common;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Xml;
using System.Xml.Serialization;
using SubSonic;
using SubSonic.Utilities;
namespace DalRis
{
/// <summary>
/// Strongly-typed collection for the InsTipoDeposito class.
/// </summary>
[Serializable]
public partial class InsTipoDepositoCollection : ActiveList<InsTipoDeposito, InsTipoDepositoCollection>
{
public InsTipoDepositoCollection() {}
/// <summary>
/// Filters an existing collection based on the set criteria. This is an in-memory filter
/// Thanks to developingchris for this!
/// </summary>
/// <returns>InsTipoDepositoCollection</returns>
public InsTipoDepositoCollection Filter()
{
for (int i = this.Count - 1; i > -1; i--)
{
InsTipoDeposito o = this[i];
foreach (SubSonic.Where w in this.wheres)
{
bool remove = false;
System.Reflection.PropertyInfo pi = o.GetType().GetProperty(w.ColumnName);
if (pi.CanRead)
{
object val = pi.GetValue(o, null);
switch (w.Comparison)
{
case SubSonic.Comparison.Equals:
if (!val.Equals(w.ParameterValue))
{
remove = true;
}
break;
}
}
if (remove)
{
this.Remove(o);
break;
}
}
}
return this;
}
}
/// <summary>
/// This is an ActiveRecord class which wraps the INS_TipoDeposito table.
/// </summary>
[Serializable]
public partial class InsTipoDeposito : ActiveRecord<InsTipoDeposito>, IActiveRecord
{
#region .ctors and Default Settings
public InsTipoDeposito()
{
SetSQLProps();
InitSetDefaults();
MarkNew();
}
private void InitSetDefaults() { SetDefaults(); }
public InsTipoDeposito(bool useDatabaseDefaults)
{
SetSQLProps();
if(useDatabaseDefaults)
ForceDefaults();
MarkNew();
}
public InsTipoDeposito(object keyID)
{
SetSQLProps();
InitSetDefaults();
LoadByKey(keyID);
}
public InsTipoDeposito(string columnName, object columnValue)
{
SetSQLProps();
InitSetDefaults();
LoadByParam(columnName,columnValue);
}
protected static void SetSQLProps() { GetTableSchema(); }
#endregion
#region Schema and Query Accessor
public static Query CreateQuery() { return new Query(Schema); }
public static TableSchema.Table Schema
{
get
{
if (BaseSchema == null)
SetSQLProps();
return BaseSchema;
}
}
private static void GetTableSchema()
{
if(!IsSchemaInitialized)
{
//Schema declaration
TableSchema.Table schema = new TableSchema.Table("INS_TipoDeposito", TableType.Table, DataService.GetInstance("RisProvider"));
schema.Columns = new TableSchema.TableColumnCollection();
schema.SchemaName = @"dbo";
//columns
TableSchema.TableColumn colvarIdTipoDeposito = new TableSchema.TableColumn(schema);
colvarIdTipoDeposito.ColumnName = "idTipoDeposito";
colvarIdTipoDeposito.DataType = DbType.Int32;
colvarIdTipoDeposito.MaxLength = 0;
colvarIdTipoDeposito.AutoIncrement = true;
colvarIdTipoDeposito.IsNullable = false;
colvarIdTipoDeposito.IsPrimaryKey = true;
colvarIdTipoDeposito.IsForeignKey = false;
colvarIdTipoDeposito.IsReadOnly = false;
colvarIdTipoDeposito.DefaultSetting = @"";
colvarIdTipoDeposito.ForeignKeyTableName = "";
schema.Columns.Add(colvarIdTipoDeposito);
TableSchema.TableColumn colvarNombre = new TableSchema.TableColumn(schema);
colvarNombre.ColumnName = "nombre";
colvarNombre.DataType = DbType.AnsiString;
colvarNombre.MaxLength = 50;
colvarNombre.AutoIncrement = false;
colvarNombre.IsNullable = false;
colvarNombre.IsPrimaryKey = false;
colvarNombre.IsForeignKey = false;
colvarNombre.IsReadOnly = false;
colvarNombre.DefaultSetting = @"('')";
colvarNombre.ForeignKeyTableName = "";
schema.Columns.Add(colvarNombre);
TableSchema.TableColumn colvarDescripcion = new TableSchema.TableColumn(schema);
colvarDescripcion.ColumnName = "descripcion";
colvarDescripcion.DataType = DbType.AnsiString;
colvarDescripcion.MaxLength = 200;
colvarDescripcion.AutoIncrement = false;
colvarDescripcion.IsNullable = false;
colvarDescripcion.IsPrimaryKey = false;
colvarDescripcion.IsForeignKey = false;
colvarDescripcion.IsReadOnly = false;
colvarDescripcion.DefaultSetting = @"('')";
colvarDescripcion.ForeignKeyTableName = "";
schema.Columns.Add(colvarDescripcion);
TableSchema.TableColumn colvarBaja = new TableSchema.TableColumn(schema);
colvarBaja.ColumnName = "baja";
colvarBaja.DataType = DbType.Boolean;
colvarBaja.MaxLength = 0;
colvarBaja.AutoIncrement = false;
colvarBaja.IsNullable = false;
colvarBaja.IsPrimaryKey = false;
colvarBaja.IsForeignKey = false;
colvarBaja.IsReadOnly = false;
colvarBaja.DefaultSetting = @"((0))";
colvarBaja.ForeignKeyTableName = "";
schema.Columns.Add(colvarBaja);
BaseSchema = schema;
//add this schema to the provider
//so we can query it later
DataService.Providers["RisProvider"].AddSchema("INS_TipoDeposito",schema);
}
}
#endregion
#region Props
[XmlAttribute("IdTipoDeposito")]
[Bindable(true)]
public int IdTipoDeposito
{
get { return GetColumnValue<int>(Columns.IdTipoDeposito); }
set { SetColumnValue(Columns.IdTipoDeposito, value); }
}
[XmlAttribute("Nombre")]
[Bindable(true)]
public string Nombre
{
get { return GetColumnValue<string>(Columns.Nombre); }
set { SetColumnValue(Columns.Nombre, value); }
}
[XmlAttribute("Descripcion")]
[Bindable(true)]
public string Descripcion
{
get { return GetColumnValue<string>(Columns.Descripcion); }
set { SetColumnValue(Columns.Descripcion, value); }
}
[XmlAttribute("Baja")]
[Bindable(true)]
public bool Baja
{
get { return GetColumnValue<bool>(Columns.Baja); }
set { SetColumnValue(Columns.Baja, value); }
}
#endregion
#region PrimaryKey Methods
protected override void SetPrimaryKey(object oValue)
{
base.SetPrimaryKey(oValue);
SetPKValues();
}
private DalRis.InsDepositoCollection colInsDepositoRecords;
public DalRis.InsDepositoCollection InsDepositoRecords()
{
if(colInsDepositoRecords == null)
{
colInsDepositoRecords = new DalRis.InsDepositoCollection().Where(InsDeposito.Columns.IdTipoDeposito, IdTipoDeposito).Load();
colInsDepositoRecords.ListChanged += new ListChangedEventHandler(colInsDepositoRecords_ListChanged);
}
return colInsDepositoRecords;
}
void colInsDepositoRecords_ListChanged(object sender, ListChangedEventArgs e)
{
if (e.ListChangedType == ListChangedType.ItemAdded)
{
// Set foreign key value
colInsDepositoRecords[e.NewIndex].IdTipoDeposito = IdTipoDeposito;
colInsDepositoRecords.ListChanged += new ListChangedEventHandler(colInsDepositoRecords_ListChanged);
}
}
#endregion
//no foreign key tables defined (0)
//no ManyToMany tables defined (0)
#region ObjectDataSource support
/// <summary>
/// Inserts a record, can be used with the Object Data Source
/// </summary>
public static void Insert(string varNombre,string varDescripcion,bool varBaja)
{
InsTipoDeposito item = new InsTipoDeposito();
item.Nombre = varNombre;
item.Descripcion = varDescripcion;
item.Baja = varBaja;
if (System.Web.HttpContext.Current != null)
item.Save(System.Web.HttpContext.Current.User.Identity.Name);
else
item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name);
}
/// <summary>
/// Updates a record, can be used with the Object Data Source
/// </summary>
public static void Update(int varIdTipoDeposito,string varNombre,string varDescripcion,bool varBaja)
{
InsTipoDeposito item = new InsTipoDeposito();
item.IdTipoDeposito = varIdTipoDeposito;
item.Nombre = varNombre;
item.Descripcion = varDescripcion;
item.Baja = varBaja;
item.IsNew = false;
if (System.Web.HttpContext.Current != null)
item.Save(System.Web.HttpContext.Current.User.Identity.Name);
else
item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name);
}
#endregion
#region Typed Columns
public static TableSchema.TableColumn IdTipoDepositoColumn
{
get { return Schema.Columns[0]; }
}
public static TableSchema.TableColumn NombreColumn
{
get { return Schema.Columns[1]; }
}
public static TableSchema.TableColumn DescripcionColumn
{
get { return Schema.Columns[2]; }
}
public static TableSchema.TableColumn BajaColumn
{
get { return Schema.Columns[3]; }
}
#endregion
#region Columns Struct
public struct Columns
{
public static string IdTipoDeposito = @"idTipoDeposito";
public static string Nombre = @"nombre";
public static string Descripcion = @"descripcion";
public static string Baja = @"baja";
}
#endregion
#region Update PK Collections
public void SetPKValues()
{
if (colInsDepositoRecords != null)
{
foreach (DalRis.InsDeposito item in colInsDepositoRecords)
{
if (item.IdTipoDeposito != IdTipoDeposito)
{
item.IdTipoDeposito = IdTipoDeposito;
}
}
}
}
#endregion
#region Deep Save
public void DeepSave()
{
Save();
if (colInsDepositoRecords != null)
{
colInsDepositoRecords.SaveAll();
}
}
#endregion
}
}
| 27.793367 | 130 | 0.621753 | [
"MIT"
] | saludnqn/prosane | RIS_Publico/RIS_Publico/generated/InsTipoDeposito.cs | 10,895 | C# |
using ProtoBuf;
using System;
using System.Collections.Generic;
namespace GameData
{
[ProtoContract(Name = "GongHuiShangDianShuaXin_ARRAY")]
[Serializable]
public class GongHuiShangDianShuaXin_ARRAY : IExtensible
{
private readonly List<GongHuiShangDianShuaXin> _items = new List<GongHuiShangDianShuaXin>();
private IExtension extensionObject;
[ProtoMember(1, Name = "items", DataFormat = DataFormat.Default)]
public List<GongHuiShangDianShuaXin> items
{
get
{
return this._items;
}
}
IExtension IExtensible.GetExtensionObject(bool createIfMissing)
{
return Extensible.GetExtensionObject(ref this.extensionObject, createIfMissing);
}
}
}
| 22.7 | 94 | 0.767988 | [
"MIT"
] | corefan/tianqi_src | src/GameData/GongHuiShangDianShuaXin_ARRAY.cs | 681 | C# |
using System;
namespace week_2._1ArrayOefenen
{
class Program
{
static void Main(string[] args)
{
// opdracht 1
// maak een lege int array van 5 waarden, vul dezen handmatig per index
// print de 2e waarde naar de console
int[] numberArray;
numberArray = new int[5];
numberArray[0] = 1;
numberArray[1] = 2;
numberArray[2] = 3;
numberArray[2] = 4;
numberArray[2] = 5;
Console.WriteLine("second array value: " + numberArray[1]);
Console.WriteLine();
// opdracht 2
// maak een gevulde int array met 7 getallen en print de 5e waarde naar de console
string[] getallen = { "1", "2", "3", "4", "5", "6", "7" };
Console.WriteLine(getallen[4]);
Console.WriteLine();
// opdracht 3
// maak een logo string array met 3 posities en vul deze met user input d.n.v. een loop
// print de waarde van de array naar de console d.m.v. een foreach loop
string[] input = new string[3];
for (int i = 0; i < input.Length; i++)
{
Console.WriteLine("give some input please:");
input[i] = Console.ReadLine();
}
Console.WriteLine();
foreach (var item in input)
{
Console.WriteLine(item);
}
Console.WriteLine();
// opdracht 4
// maak een logo int array met 10 posities en vul deze m.b.v. een random en een loop
// met random getallen sorteer de array daarna en print de waarde naar de console
Random rnd = new Random();
int[] randomNumber = new int[10];
for (int i = 0; i < randomNumber.Length; i++)
{
randomNumber[i] = rnd.Next(0, 3466);
}
foreach (var number in randomNumber)
{
Console.Write(number + ", ");
}
}
}
}
| 30.852941 | 99 | 0.493804 | [
"MIT"
] | SintBartvdC/scripten-periode-3 | scripten_4/week_2/week_2.1ArrayOefenen/Program.cs | 2,100 | C# |
using System;
using System.Collections.Generic;
using System.Text;
namespace BotSharp.NLP.Featuring
{
public interface IFeatureExtractor
{
/// <summary>
/// Feature dimension size
/// </summary>
int Dimension { get; set; }
}
}
| 18.2 | 38 | 0.615385 | [
"Apache-2.0"
] | david0718/BotSharp | BotSharp.NLP/Featuring/IFeatureExtractor.cs | 275 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
namespace AnotherNetFrameworkDocker
{
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
}
}
| 26.545455 | 70 | 0.714041 | [
"MIT"
] | holapancho/netframework-docker | AnotherNetFrameworkDocker/Global.asax.cs | 586 | C# |
using System;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Xunit;
namespace EntityFrameworkCore.Extensions.Tests
{
public class DatabaseFacadeExtensionsTests
{
[Fact]
public void MigrateIfSupported_should_not_fail_for_inmemory()
{
var options = new DbContextOptionsBuilder<TestContext>()
.UseInMemoryDatabase("MigrateIfSupported_should_not_fail_for_inmemory")
.Options;
var context = new TestContext(options);
context.Database.MigrateIfSupported();
Assert.Throws<InvalidOperationException>(() => context.Database.Migrate());
}
[Fact]
public async Task MigrateIfSupportedAsync_should_not_fail_for_inmemory()
{
var options = new DbContextOptionsBuilder<TestContext>()
.UseInMemoryDatabase("MigrateIfSupported_should_not_fail_for_inmemory")
.Options;
var context = new TestContext(options);
context.Database.MigrateIfSupported();
await Assert.ThrowsAsync<InvalidOperationException>(() => context.Database.MigrateAsync());
}
[Fact]
public void MigrateIfSupported_should_migrate_for_sqlite()
{
var options = new DbContextOptionsBuilder<TestContext>()
.UseSqlite("DataSource=:memory:")
.ReplaceService<IMigrator, MockMigrator>()
.Options;
var context = new TestContext(options);
context.Database.MigrateIfSupported();
var migrator = context.GetService<IMigrator>() as MockMigrator;
Assert.True(migrator?.MigrateCalled ?? false);
}
[Fact]
public async Task MigrateIfSupportedAsync_should_migrate_for_sqlite()
{
var options = new DbContextOptionsBuilder<TestContext>()
.UseSqlite("DataSource=:memory:")
.ReplaceService<IMigrator, MockMigrator>()
.Options;
var context = new TestContext(options);
await context.Database.MigrateIfSupportedAsync();
var migrator = context.GetService<IMigrator>() as MockMigrator;
Assert.True(migrator?.MigrateAsyncCalled ?? false);
}
public class MockMigrator : IMigrator
{
public bool MigrateCalled { get; private set; }
public bool MigrateAsyncCalled { get; private set; }
public void Migrate(string targetMigration = null)
{
MigrateCalled = true;
}
public Task MigrateAsync(string targetMigration = null, CancellationToken cancellationToken = new CancellationToken())
{
MigrateAsyncCalled = true;
return Task.CompletedTask;
}
public string GenerateScript(string fromMigration = null, string toMigration = null, bool idempotent = false)
{
throw new NotImplementedException();
}
}
}
}
| 35.054348 | 130 | 0.623256 | [
"MIT"
] | pecea/EntityFrameworkCore.Extensions | EntityFrameworkCore.Extensions.Tests/DatabaseFacadeExtensionsTests.cs | 3,227 | C# |
using Ayehu.Sdk.ActivityCreation.Interfaces;
using Ayehu.Sdk.ActivityCreation.Extension;
using System.Text;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.IO;
using System.Data;
using System.Diagnostics;
namespace Ayehu.Sdk.ActivityCreation
{
public class ActivityClass : IActivity
{
public string HostName;
public string UserName;
public string Password;
public string VMName;
public ICustomActivityResult Execute()
{
StringWriter sw = new StringWriter();
DataTable dt = new DataTable("resultSet");
dt.Columns.Add("Result", typeof(String));
string sResult = "";
string command_path = "VMWare.exe";
DataTable dtParams = new DataTable("Params");
dtParams.Columns.Add("Command");
dtParams.Columns.Add("UserName");
dtParams.Columns.Add("Password");
dtParams.Columns.Add("HostName");
dtParams.Columns.Add("VMName");
DataRow rParams = dtParams.NewRow();
rParams["Command"] = "VMShutDown";
rParams["UserName"] = UserName;
rParams["Password"] = Password;
rParams["HostName"] = HostName;
rParams["VMName"] = VMName;
dtParams.Rows.Add(rParams);
dtParams.WriteXml(sw, XmlWriteMode.WriteSchema, false);
Process prVMWare = new Process();
prVMWare.StartInfo.FileName = command_path;
prVMWare.StartInfo.Arguments = "\"" + sw.ToString().Replace("\"", "\\\"") + "\"";
prVMWare.StartInfo.UseShellExecute = false;
prVMWare.StartInfo.CreateNoWindow = true;
prVMWare.StartInfo.RedirectStandardError = true;
prVMWare.StartInfo.RedirectStandardInput = true;
prVMWare.StartInfo.RedirectStandardOutput = true;
prVMWare.Start();
StreamReader srResult = prVMWare.StandardOutput;
sResult = srResult.ReadToEnd();
srResult.Close();
prVMWare.Close();
if (sResult == "")
{
return this.GenerateActivityResult(dt);
}
else
{
return this.GenerateActivityResult(sResult);
}
}
}
}
| 32.105263 | 94 | 0.569262 | [
"MIT"
] | Ayehu/activities | VMWare/VMShutdown.cs | 2,440 | C# |
using System.Collections.Generic;
using Newtonsoft.Json;
namespace xAPI.Standard
{
public class InteractionType
{
public static Dictionary<string, object> FromJson(string json)
{
return JsonConvert.DeserializeObject<Dictionary<string, object>>(json, Converter.SETTINGS);
}
}
} | 25.076923 | 103 | 0.687117 | [
"Apache-2.0"
] | iWorkTech/xapi-wrapper-xamarin-core | component/src/TinCan.Standard/InteractionType.cs | 328 | C# |
using System;
using System.Threading.Tasks;
using System.Collections.Generic;
using System.Collections.Concurrent;
namespace Geek.Server
{
public class ComponentDriver
{
static readonly NLog.Logger LOGGER = NLog.LogManager.GetCurrentClassLogger();
readonly ComponentActor owner;
readonly ConcurrentDictionary<Type, DateTime> activeTimeMap = new ConcurrentDictionary<Type, DateTime>();
//在actor和driver线程都会访问
readonly ConcurrentDictionary<Type, BaseComponent> activeCompMap = new ConcurrentDictionary<Type, BaseComponent>();
public int ActiveCompNum => activeCompMap.Count;
public ComponentDriver(ComponentActor actor)
{
owner = actor;
}
/// <summary>线程安全</summary>
public async Task<BaseComponent> GetComponent(Type compType)
{
//当comp已激活,且肯定不满足回收条件时可以不用入lifeactor线程
var now = DateTime.Now;
float threshold = Settings.Ins.CompRecycleTime * 0.67f;//0.67 ~= 2/3
if (activeTimeMap.TryGetValue(compType, out var activeTime)
&& (now - activeTime).TotalMinutes < threshold
&& activeCompMap.TryGetValue(compType, out var retComp))
{
activeTimeMap[compType] = DateTime.Now;
return retComp;
}
//comp的active不一定在所属actor线程执行,谁来获取就在谁的线程执行
return await owner.GetLifeActor(compType).SendAsync(async () =>
{
var got = activeCompMap.TryGetValue(compType, out var retComp);
if (retComp == null)
retComp = ComponentMgr.Singleton.NewComponent(owner, compType);
if (retComp == null)//没有注册Comp
return retComp;
if (!retComp.IsActive)
{
await retComp.Active();
if (retComp.GetAgent() != null)
await retComp.GetAgent().Active();
}
if (!got)
activeCompMap.TryAdd(compType, retComp);
activeTimeMap[compType] = DateTime.Now;
return retComp;
});
}
public Task<bool> IsCompActive(Type compType)
{
activeCompMap.TryGetValue(compType, out var comp);
var ret = comp != null && comp.IsActive;
return Task.FromResult(ret);
}
/// <summary>清除所有comp的agent(热更时)</summary>
public void ClearAllCompsAgent()
{
foreach (var kv in activeCompMap)
kv.Value.ClearCacheAgent();
}
/// <summary>actor线程执行</summary>
public async Task InitListener()
{
var list = HotfixMgr.GetEventListeners(owner.ActorType);
if (list == null)
return;
foreach (var listener in list)
await listener.InnerInitListener(owner);
}
public async Task DeactiveAllComps()
{
foreach(var kv in activeCompMap)
await kv.Value.Deactive();
}
public async Task<bool> ReadyToDeactiveAllComps()
{
foreach (var kv in activeCompMap)
{
if (!await kv.Value.ReadyToDeactive())
return false;
}
return true;
}
/// <summary>
/// driver+actor线程
/// 回存需要actor线程await执行
/// </summary>
public async Task RecycleIdleComps(List<Type> excludeList, float idleMinutes = 15f)
{
var now = DateTime.Now;
var allComps = ComponentMgr.Singleton.GetAllCompsInfo(owner);
foreach (var info in allComps)
{
var compType = info.CompType;
if (excludeList.Contains(compType))
continue;
if (!activeTimeMap.ContainsKey(compType))
continue;
activeCompMap.TryGetValue(compType, out var comp);
if (comp == null || !comp.IsActive)
continue;
try
{
//销毁长时间不活跃的模块
if (activeTimeMap.TryGetValue(compType, out var activeTime) && (now - activeTime).TotalMinutes > idleMinutes)
{
await owner.GetLifeActor(compType).SendAsync(async () =>
{
if (activeTimeMap.TryGetValue(compType, out var activeTime) && (now - activeTime).TotalMinutes > idleMinutes)
{
//理论上一定会返回true,因为销毁时长大于回存时间
if (await comp.ReadyToDeactive())
{
await comp.Deactive();
activeCompMap.TryRemove(compType, out _);
activeTimeMap.TryRemove(compType, out _);
}
}
});
}
}
catch (Exception e)
{
LOGGER.Error("com deactive 异常:{} {}", owner.ActorId, comp.GetType());
LOGGER.Fatal(e.ToString());
}
}
}
}
} | 36.292517 | 137 | 0.508529 | [
"MIT"
] | leeveel/GeekServer | GeekServer.Core/Component/ComponentDriver.cs | 5,573 | C# |
// Copyright (c) 2017, centron GmbH
// SolidCP is distributed under the Creative Commons Share-alike license
//
// SolidCP is a fork of WebsitePanel:
// Copyright (c) 2015, Outercurve Foundation.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// - Neither the name of the Outercurve Foundation nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using SolidCP.Providers.Virtualization;
using SolidCP.EnterpriseServer;
using SolidCP.Providers.Common;
//using System.IO;
namespace SolidCP.Portal.Proxmox
{
public partial class VpsDetailsNetwork : SolidCPModuleBase
{
VirtualMachine vm = null;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindVirtualMachine();
BindExternalAddresses();
BindPrivateAddresses();
ToggleButtons();
}
}
private void BindVirtualMachine()
{
vm = ES.Services.Proxmox.GetVirtualMachineItem(PanelRequest.ItemID);
// external network
if (!vm.ExternalNetworkEnabled)
{
secExternalNetwork.Visible = false;
ExternalNetworkPanel.Visible = false;
}
// private network
if (!vm.PrivateNetworkEnabled)
{
secPrivateNetwork.Visible = false;
PrivateNetworkPanel.Visible = false;
}
}
private void BindExternalAddresses()
{
// load details
NetworkAdapterDetails nic = ES.Services.Proxmox.GetExternalNetworkAdapterDetails(PanelRequest.ItemID);
// bind details
foreach (NetworkAdapterIPAddress ip in nic.IPAddresses)
{
if (ip.IsPrimary)
{
litExtAddress.Text = ip.IPAddress;
litExtSubnet.Text = ip.SubnetMask;
litExtGateway.Text = ip.DefaultGateway;
break;
}
}
lblTotalExternal.Text = nic.IPAddresses.Length.ToString();
// bind IP addresses
gvExternalAddresses.DataSource = nic.IPAddresses;
gvExternalAddresses.DataBind();
}
private void BindPrivateAddresses()
{
// load details
NetworkAdapterDetails nic = ES.Services.Proxmox.GetPrivateNetworkAdapterDetails(PanelRequest.ItemID);
// bind details
foreach (NetworkAdapterIPAddress ip in nic.IPAddresses)
{
if (ip.IsPrimary)
{
litPrivAddress.Text = ip.IPAddress;
break;
}
}
litPrivSubnet.Text = nic.SubnetMask;
litPrivFormat.Text = nic.NetworkFormat;
lblTotalPrivate.Text = nic.IPAddresses.Length.ToString();
// bind IP addresses
gvPrivateAddresses.DataSource = nic.IPAddresses;
gvPrivateAddresses.DataBind();
if (nic.IsDHCP)
{
PrivateAddressesPanel.Visible = false;
litPrivAddress.Text = GetLocalizedString("Automatic.Text");
}
}
private void ToggleButtons()
{
bool manageAllowed = VirtualMachinesProxmoxHelper.IsVirtualMachineManagementAllowed(PanelSecurity.PackageId);
btnAddExternalAddress.Visible = manageAllowed;
btnSetPrimaryExternal.Visible = manageAllowed;
btnDeleteExternal.Visible = manageAllowed;
gvExternalAddresses.Columns[0].Visible = manageAllowed;
btnAddPrivateAddress.Visible = manageAllowed;
btnSetPrimaryPrivate.Visible = manageAllowed;
btnDeletePrivate.Visible = manageAllowed;
gvPrivateAddresses.Columns[0].Visible = manageAllowed;
}
protected void btnAddExternalAddress_Click(object sender, EventArgs e)
{
Response.Redirect(EditUrl("ItemID", PanelRequest.ItemID.ToString(), "vps_add_external_ip",
"SpaceID=" + PanelSecurity.PackageId.ToString()));
}
protected void btnAddPrivateAddress_Click(object sender, EventArgs e)
{
Response.Redirect(EditUrl("ItemID", PanelRequest.ItemID.ToString(), "vps_add_private_ip",
"SpaceID=" + PanelSecurity.PackageId.ToString()));
}
protected void btnSetPrimaryPrivate_Click(object sender, EventArgs e)
{
int[] addressIds = GetSelectedItems(gvPrivateAddresses);
// check if at least one is selected
if (addressIds.Length == 0)
{
messageBox.ShowWarningMessage("IP_ADDRESS_NOT_SELECTED");
return;
}
try
{
ResultObject res = ES.Services.Proxmox.SetVirtualMachinePrimaryPrivateIPAddress(PanelRequest.ItemID, addressIds[0]);
if (res.IsSuccess)
{
BindPrivateAddresses();
return;
}
else
{
messageBox.ShowMessage(res, "VPS_ERROR_SETTING_PRIMARY_IP", "VPS");
return;
}
}
catch (Exception ex)
{
messageBox.ShowErrorMessage("VPS_ERROR_SETTING_PRIMARY_IP", ex);
}
}
protected void btnDeletePrivate_Click(object sender, EventArgs e)
{
int[] addressIds = GetSelectedItems(gvPrivateAddresses);
// check if at least one is selected
if (addressIds.Length == 0)
{
messageBox.ShowWarningMessage("IP_ADDRESS_NOT_SELECTED");
return;
}
try
{
ResultObject res = ES.Services.Proxmox.DeleteVirtualMachinePrivateIPAddresses(PanelRequest.ItemID, addressIds);
if (res.IsSuccess)
{
BindPrivateAddresses();
return;
}
else
{
messageBox.ShowMessage(res, "VPS_ERROR_DELETING_IP_ADDRESS", "VPS");
return;
}
}
catch (Exception ex)
{
messageBox.ShowErrorMessage("VPS_ERROR_DELETING_IP_ADDRESS", ex);
}
}
protected void btnSetPrimaryExternal_Click(object sender, EventArgs e)
{
int[] addressIds = GetSelectedItems(gvExternalAddresses);
// check if at least one is selected
if (addressIds.Length == 0)
{
messageBox.ShowWarningMessage("IP_ADDRESS_NOT_SELECTED");
return;
}
try
{
ResultObject res = ES.Services.Proxmox.SetVirtualMachinePrimaryExternalIPAddress(PanelRequest.ItemID, addressIds[0]);
if (res.IsSuccess)
{
BindExternalAddresses();
return;
}
else
{
messageBox.ShowMessage(res, "VPS_ERROR_SETTING_PRIMARY_IP", "VPS");
return;
}
}
catch (Exception ex)
{
messageBox.ShowErrorMessage("VPS_ERROR_SETTING_PRIMARY_IP", ex);
}
}
protected void btnDeleteExternal_Click(object sender, EventArgs e)
{
int[] addressIds = GetSelectedItems(gvExternalAddresses);
// check if at least one is selected
if (addressIds.Length == 0)
{
messageBox.ShowWarningMessage("IP_ADDRESS_NOT_SELECTED");
return;
}
try
{
ResultObject res = ES.Services.Proxmox.DeleteVirtualMachineExternalIPAddresses(PanelRequest.ItemID, addressIds);
if (res.IsSuccess)
{
BindExternalAddresses();
return;
}
else
{
messageBox.ShowMessage(res, "VPS_ERROR_DELETING_IP_ADDRESS", "VPS");
return;
}
}
catch (Exception ex)
{
messageBox.ShowErrorMessage("VPS_ERROR_DELETING_IP_ADDRESS", ex);
}
}
private int[] GetSelectedItems(GridView gv)
{
List<int> items = new List<int>();
for (int i = 0; i < gv.Rows.Count; i++)
{
GridViewRow row = gv.Rows[i];
CheckBox chkSelect = (CheckBox)row.FindControl("chkSelect");
if (chkSelect.Checked)
items.Add((int)gv.DataKeys[i].Value);
}
return items.ToArray();
}
}
}
| 34.462783 | 133 | 0.561931 | [
"BSD-3-Clause"
] | Alirexaa/SolidCP | SolidCP/Sources/SolidCP.WebPortal/DesktopModules/SolidCP/Proxmox/VpsDetailsNetwork.ascx.cs | 10,649 | C# |
using System.Collections.Generic;
using System.Linq;
using GameWork.Core.ObjectPool.Interfaces;
namespace GameWork.Core.ObjectPool
{
public class ObjectPool : ObjectPool<IPoolableObject>
{
}
public class ObjectPool<TPoolableObject> where TPoolableObject : IPoolableObject
{
protected readonly List<TPoolableObject> PoolableObjects = new List<TPoolableObject>();
public ObjectPool(params TPoolableObject[] poolableObjects)
{
PoolableObjects.AddRange(poolableObjects);
}
public virtual bool TryTake(out TPoolableObject poolableObject)
{
poolableObject = PoolableObjects.FirstOrDefault(p => !p.IsTaken);
if (poolableObject == null)
{
return false;
}
poolableObject.SetTaken();
return true;
}
}
}
| 26.058824 | 95 | 0.63544 | [
"MIT"
] | JaredGG/GameWork.Core | GameWork.Core.ObjectPool/ObjectPool.cs | 888 | C# |
using Microsoft.Azure.ApiManagement.WsdlProcessor.Common;
using System;
using System.IO;
using System.Threading.Tasks;
using System.Xml;
using System.Xml.Linq;
namespace TestConsole
{
class Program
{
static async Task Main(string[] args)
{
var log = new ConsoleLog();
var wsdlfile = "API-0427";
var wsdlString = File.ReadAllText(wsdlfile + ".wsdl");
var xDocument = XDocument.Parse(wsdlString);
await WsdlDocument.LoadAsync(xDocument.Root, log);
//WsdlDocument.DumpInvalidNodes(xDocument.Root);
xDocument.Root.Save(wsdlfile + "-processed.wsdl");
//FileStream fs = new FileStream(@"C:\Temp\" + wsdlfile + "-processed.wsdl", FileMode.Create);
//wsdlDocument.Save(XmlWriter.Create(fs, new XmlWriterSettings() { Indent = true }));
//fs.Close();
Console.ReadLine();
}
}
public class ConsoleLog : ILog
{
public void Critical(string eventName)
{
Console.WriteLine("Critical : " + eventName);
}
public void Critical(string eventName, string message)
{
Console.WriteLine("Critical : " + eventName + " : " + message);
}
public void Critical(string eventName, Exception ex)
{
Console.WriteLine("Critical : " + eventName + " : Exception : " + ex.Message);
}
public void Critical(string eventName, string message, Exception ex)
{
Console.WriteLine("Critical : " + eventName + " : " + message + " : Exception : " + ex.Message);
}
public void Critical(string eventName, string message, Exception ex, params object[] args)
{
Console.WriteLine("Critical : " + eventName + " : " + message + " : Exception : " + ex.Message);
}
public void Error(string eventName)
{
Console.WriteLine("Error : " + eventName);
}
public void Error(string eventName, string message)
{
Console.WriteLine("Error : " + eventName + " : " + message);
}
public void Error(string eventName, Exception ex)
{
Console.WriteLine("Error : " + eventName + " : Exception : " + ex.Message);
}
public void Error(string eventName, string message, Exception ex)
{
Console.WriteLine("Error : " + eventName + " : " + message + " : Exception : " + ex.Message);
}
public void Error(string eventName, string message, Exception ex, params object[] args)
{
Console.WriteLine("Error : " + eventName + " : " + message + " : Exception : " + ex.Message);
}
public void Informational(string eventName)
{
Console.WriteLine("Info : " + eventName);
}
public void Informational(string eventName, string message)
{
Console.WriteLine("Info : " + eventName + " : " + message);
}
public void Informational(string eventName, Exception ex)
{
Console.WriteLine("Info : " + eventName + " : Exception : " + ex.Message);
}
public void Informational(string eventName, string message, Exception ex)
{
Console.WriteLine("Info : " + eventName + " : " + message + " : Exception : " + ex.Message);
}
public void Informational(string eventName, string message, Exception ex, params object[] args)
{
Console.WriteLine("Info : " + eventName + " : " + message + " : Exception : " + ex.Message);
}
public void Verbose(string eventName)
{
Console.WriteLine("Verbose : " + eventName);
}
public void Verbose(string eventName, string message)
{
Console.WriteLine("Verbose : " + eventName + " : " + message);
}
public void Verbose(string eventName, Exception ex)
{
Console.WriteLine("Verbose : " + eventName + " : Exception : " + ex.Message);
}
public void Verbose(string eventName, string message, Exception ex)
{
Console.WriteLine("Verbose : " + eventName + " : " + message + " : Exception : " + ex.Message);
}
public void Verbose(string eventName, string message, Exception ex, params object[] args)
{
Console.WriteLine("Verbose : " + eventName + " : " + message + " : Exception : " + ex.Message);
}
public void Warning(string eventName)
{
Console.WriteLine("Warning : " + eventName);
}
public void Warning(string eventName, string message)
{
Console.WriteLine("Warning : " + eventName + " : " + message);
}
public void Warning(string eventName, Exception ex)
{
Console.WriteLine("Warning : " + eventName + " : Exception : " + ex.Message);
}
public void Warning(string eventName, string message, Exception ex)
{
Console.WriteLine("Warning : " + eventName + " : " + message + " : Exception : " + ex.Message);
}
public void Warning(string eventName, string message, Exception ex, params object[] args)
{
Console.WriteLine("Warning : " + eventName + " : " + message + " : Exception : " + ex.Message);
}
}
}
| 34.705128 | 108 | 0.558182 | [
"MIT"
] | Azure-Samples/api-management-schema-import | ApiManagementSchemaImport/TestConsole/Program.cs | 5,416 | C# |
using L2dotNET.world;
namespace L2dotNET.model.skills2.effects
{
public class PBlockSkillPhysical : Effect
{
public PBlockSkillPhysical()
{
Type = EffectType.PBlockSkillPhysical;
}
public override EffectResult OnStart(L2Character caster, L2Character target)
{
target.Mute(0, HashId, true);
return new EffectResult().AsTotalUi();
}
public override EffectResult OnEnd(L2Character caster, L2Character target)
{
target.Mute(0, HashId, false);
return target.MutedPhysically ? new EffectResult().AsTotalUi() : Nothing;
}
}
} | 27.75 | 85 | 0.617117 | [
"MPL-2.0",
"MPL-2.0-no-copyleft-exception"
] | temukaa/develop | src/L2dotNET/model/skills2/effects/PBlockSkillPhysical.cs | 668 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using StoreModels;
namespace StoreMVC.Areas.Identity.Pages.Account.Manage
{
public class SetPasswordModel : PageModel
{
private readonly UserManager<StoreMVCUser> _userManager;
private readonly SignInManager<StoreMVCUser> _signInManager;
public SetPasswordModel(
UserManager<StoreMVCUser> userManager,
SignInManager<StoreMVCUser> signInManager)
{
_userManager = userManager;
_signInManager = signInManager;
}
[BindProperty]
public InputModel Input { get; set; }
[TempData]
public string StatusMessage { get; set; }
public class InputModel
{
[Required]
[StringLength(100, ErrorMessage = "The {0} must be at least {2} and at max {1} characters long.", MinimumLength = 6)]
[DataType(DataType.Password)]
[Display(Name = "New password")]
public string NewPassword { get; set; }
[DataType(DataType.Password)]
[Display(Name = "Confirm new password")]
[Compare("NewPassword", ErrorMessage = "The new password and confirmation password do not match.")]
public string ConfirmPassword { get; set; }
}
public async Task<IActionResult> OnGetAsync()
{
var user = await _userManager.GetUserAsync(User);
if (user == null)
{
return NotFound($"Unable to load user with ID '{_userManager.GetUserId(User)}'.");
}
var hasPassword = await _userManager.HasPasswordAsync(user);
if (hasPassword)
{
return RedirectToPage("./ChangePassword");
}
return Page();
}
public async Task<IActionResult> OnPostAsync()
{
if (!ModelState.IsValid)
{
return Page();
}
var user = await _userManager.GetUserAsync(User);
if (user == null)
{
return NotFound($"Unable to load user with ID '{_userManager.GetUserId(User)}'.");
}
var addPasswordResult = await _userManager.AddPasswordAsync(user, Input.NewPassword);
if (!addPasswordResult.Succeeded)
{
foreach (var error in addPasswordResult.Errors)
{
ModelState.AddModelError(string.Empty, error.Description);
}
return Page();
}
await _signInManager.RefreshSignInAsync(user);
StatusMessage = "Your password has been set.";
return RedirectToPage();
}
}
}
| 31.531915 | 129 | 0.581646 | [
"MIT"
] | 210215-USF-NET/Douglas_Richardson-P1 | StoreMVC/Areas/Identity/Pages/Account/Manage/SetPassword.cshtml.cs | 2,966 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Smart.Web.Mvc.UI.JqGrid.Options
{
public class AjaxSelectOptions
{
}
}
| 16.230769 | 41 | 0.748815 | [
"Apache-2.0"
] | SmallAnts/Smart | Src/Framework/Smart.Web.Mvc.Shared/UI/JqGrid/Options/AjaxSelectOptions.cs | 213 | C# |
using Microsoft.EntityFrameworkCore.Migrations;
namespace Demo.Migrations
{
public partial class Added_Description_And_IsActive_To_Role : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<string>(
name: "Description",
table: "AbpRoles",
maxLength: 5000,
nullable: true);
migrationBuilder.AddColumn<bool>(
name: "IsActive",
table: "AbpRoles",
nullable: false,
defaultValue: false);
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "Description",
table: "AbpRoles");
migrationBuilder.DropColumn(
name: "IsActive",
table: "AbpRoles");
}
}
}
| 27.941176 | 75 | 0.543158 | [
"Apache-2.0"
] | hangyejiadao/AspNetCore | 3.4.0/aspnet-core/src/Demo.EntityFrameworkCore/Migrations/20170621153937_Added_Description_And_IsActive_To_Role.cs | 952 | C# |
using Elsa.Serialization;
using Newtonsoft.Json;
namespace Elsa.Server.Api
{
public static class SerializationHelper
{
public static JsonSerializerSettings GetSettingsForWorkflowDefinition()
{
// Here we don't want to use the `PreserveReferencesHandling` setting because the model will be used by the designer "as-is" and will not resolve $id references.
// Fixes #1605.
var settings = DefaultContentSerializer.CreateDefaultJsonSerializationSettings();
settings.PreserveReferencesHandling = PreserveReferencesHandling.None;
return settings;
}
}
} | 35.777778 | 173 | 0.700311 | [
"MIT"
] | Blazi-Commerce/elsa-core | src/server/Elsa.Server.Api/SerializationHelper.cs | 644 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Azure.Core;
using Azure.Core.Pipeline;
namespace Azure.IoT.TimeSeriesInsights
{
/// <summary>
/// Perform operations such as creating, listing, replacing and deleting Time Series instances.
/// </summary>
public class TimeSeriesInsightsInstances
{
private readonly TimeSeriesInstancesRestClient _instancesRestClient;
private readonly ClientDiagnostics _clientDiagnostics;
/// <summary>
/// Initializes a new instance of TimeSeriesInsightsInstances. This constructor should only be used for mocking purposes.
/// </summary>
protected TimeSeriesInsightsInstances()
{
}
internal TimeSeriesInsightsInstances(TimeSeriesInstancesRestClient instancesRestClient, ClientDiagnostics clientDiagnostics)
{
Argument.AssertNotNull(instancesRestClient, nameof(instancesRestClient));
Argument.AssertNotNull(clientDiagnostics, nameof(clientDiagnostics));
_instancesRestClient = instancesRestClient;
_clientDiagnostics = clientDiagnostics;
}
/// <summary>
/// Gets Time Series instances in pages asynchronously.
/// </summary>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>The pageable list <see cref="AsyncPageable{TimeSeriesInstance}"/> of Time Series instances belonging to the TSI environment and the http response.</returns>
/// <remarks>
/// For more samples, see <see href="https://github.com/Azure/azure-sdk-for-net/tree/main/sdk/timeseriesinsights/Azure.IoT.TimeSeriesInsights/samples">our repo samples</see>.
/// </remarks>
/// <example>
/// <code snippet="Snippet:TimeSeriesInsightsGetAllInstances" language="csharp">
/// // Get all instances for the Time Series Insights environment
/// AsyncPageable<TimeSeriesInstance> tsiInstances = instancesClient.GetAsync();
/// await foreach (TimeSeriesInstance tsiInstance in tsiInstances)
/// {
/// Console.WriteLine($"Retrieved Time Series Insights instance with Id '{tsiInstance.TimeSeriesId}' and name '{tsiInstance.Name}'.");
/// }
/// </code>
/// </example>
public virtual AsyncPageable<TimeSeriesInstance> GetAsync(CancellationToken cancellationToken = default)
{
using DiagnosticScope scope = _clientDiagnostics.CreateScope($"{nameof(TimeSeriesInsightsClient)}.{nameof(Get)}");
scope.Start();
try
{
async Task<Page<TimeSeriesInstance>> FirstPageFunc(int? pageSizeHint)
{
using DiagnosticScope scope = _clientDiagnostics.CreateScope($"{nameof(TimeSeriesInsightsClient)}.{nameof(Get)}");
scope.Start();
try
{
Response<GetInstancesPage> getInstancesResponse = await _instancesRestClient
.ListAsync(null, null, cancellationToken)
.ConfigureAwait(false);
return Page.FromValues(getInstancesResponse.Value.Instances, getInstancesResponse.Value.ContinuationToken, getInstancesResponse.GetRawResponse());
}
catch (Exception ex)
{
scope.Failed(ex);
throw;
}
}
async Task<Page<TimeSeriesInstance>> NextPageFunc(string nextLink, int? pageSizeHint)
{
using DiagnosticScope scope = _clientDiagnostics.CreateScope($"{nameof(TimeSeriesInsightsClient)}.{nameof(Get)}");
scope.Start();
try
{
Response<GetInstancesPage> getInstancesResponse = await _instancesRestClient
.ListAsync(nextLink, null, cancellationToken)
.ConfigureAwait(false);
return Page.FromValues(getInstancesResponse.Value.Instances, getInstancesResponse.Value.ContinuationToken, getInstancesResponse.GetRawResponse());
}
catch (Exception ex)
{
scope.Failed(ex);
throw;
}
}
return PageableHelpers.CreateAsyncEnumerable(FirstPageFunc, NextPageFunc);
}
catch (Exception ex)
{
scope.Failed(ex);
throw;
}
}
/// <summary>
/// Gets Time Series instances synchronously in pages.
/// </summary>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>The pageable list <see cref="Pageable{TimeSeriesInstance}"/> of Time Series instances belonging to the TSI environment and the http response.</returns>
/// <seealso cref="GetAsync(CancellationToken)">
/// See the asynchronous version of this method for examples.
/// </seealso>
public virtual Pageable<TimeSeriesInstance> Get(CancellationToken cancellationToken = default)
{
using DiagnosticScope scope = _clientDiagnostics.CreateScope($"{nameof(TimeSeriesInsightsClient)}.{nameof(Get)}");
scope.Start();
try
{
Page<TimeSeriesInstance> FirstPageFunc(int? pageSizeHint)
{
using DiagnosticScope scope = _clientDiagnostics.CreateScope($"{nameof(TimeSeriesInsightsClient)}.{nameof(Get)}");
scope.Start();
try
{
Response<GetInstancesPage> getInstancesResponse = _instancesRestClient.List(null, null, cancellationToken);
return Page.FromValues(getInstancesResponse.Value.Instances, getInstancesResponse.Value.ContinuationToken, getInstancesResponse.GetRawResponse());
}
catch (Exception ex)
{
scope.Failed(ex);
throw;
}
}
Page<TimeSeriesInstance> NextPageFunc(string nextLink, int? pageSizeHint)
{
using DiagnosticScope scope = _clientDiagnostics.CreateScope($"{nameof(TimeSeriesInsightsClient)}.{nameof(Get)}");
scope.Start();
try
{
Response<GetInstancesPage> getInstancesResponse = _instancesRestClient.List(nextLink, null, cancellationToken);
return Page.FromValues(getInstancesResponse.Value.Instances, getInstancesResponse.Value.ContinuationToken, getInstancesResponse.GetRawResponse());
}
catch (Exception ex)
{
scope.Failed(ex);
throw;
}
}
return PageableHelpers.CreateEnumerable(FirstPageFunc, NextPageFunc);
}
catch (Exception ex)
{
scope.Failed(ex);
throw;
}
}
/// <summary>
/// Gets Time Series instances by instance names asynchronously.
/// </summary>
/// <param name="timeSeriesNames">List of names of the Time Series instance to return.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>
/// List of instance or error objects corresponding by position to the array in the request. Instance object is set when operation is successful
/// and error object is set when operation is unsuccessful.
/// </returns>
/// <remarks>
/// For more samples, see <see href="https://github.com/Azure/azure-sdk-for-net/tree/main/sdk/timeseriesinsights/Azure.IoT.TimeSeriesInsights/samples">our repo samples</see>.
/// </remarks>
/// <exception cref="ArgumentNullException">
/// The exception is thrown when <paramref name="timeSeriesNames"/> is <c>null</c>.
/// </exception>
/// <exception cref="ArgumentException">
/// The exception is thrown when <paramref name="timeSeriesNames"/> is empty.
/// </exception>
public virtual async Task<Response<InstancesOperationResult[]>> GetByNameAsync(
IEnumerable<string> timeSeriesNames,
CancellationToken cancellationToken = default)
{
using DiagnosticScope scope = _clientDiagnostics.CreateScope($"{nameof(TimeSeriesInsightsClient)}.{nameof(GetByName)}");
scope.Start();
try
{
Argument.AssertNotNullOrEmpty(timeSeriesNames, nameof(timeSeriesNames));
var batchRequest = new InstancesBatchRequest
{
Get = new InstancesRequestBatchGetOrDelete()
};
foreach (string timeSeriesName in timeSeriesNames)
{
batchRequest.Get.Names.Add(timeSeriesName);
}
Response<InstancesBatchResponse> executeBatchResponse = await _instancesRestClient
.ExecuteBatchAsync(batchRequest, null, cancellationToken)
.ConfigureAwait(false);
return Response.FromValue(executeBatchResponse.Value.Get.ToArray(), executeBatchResponse.GetRawResponse());
}
catch (Exception ex)
{
scope.Failed(ex);
throw;
}
}
/// <summary>
/// Gets Time Series instances by instance names synchronously.
/// </summary>
/// <param name="timeSeriesNames">List of names of the Time Series instance to return.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>
/// List of instance or error objects corresponding by position to the array in the request. Instance object is set when operation is successful
/// and error object is set when operation is unsuccessful.
/// </returns>
/// <seealso cref="GetByNameAsync(IEnumerable{string}, CancellationToken)">
/// See the asynchronous version of this method for examples.
/// </seealso>
/// <exception cref="ArgumentNullException">
/// The exception is thrown when <paramref name="timeSeriesNames"/> is <c>null</c>.
/// </exception>
/// <exception cref="ArgumentException">
/// The exception is thrown when <paramref name="timeSeriesNames"/> is empty.
/// </exception>
public virtual Response<InstancesOperationResult[]> GetByName(
IEnumerable<string> timeSeriesNames,
CancellationToken cancellationToken = default)
{
using DiagnosticScope scope = _clientDiagnostics.CreateScope($"{nameof(TimeSeriesInsightsClient)}.{nameof(GetByName)}");
scope.Start();
try
{
Argument.AssertNotNullOrEmpty(timeSeriesNames, nameof(timeSeriesNames));
var batchRequest = new InstancesBatchRequest
{
Get = new InstancesRequestBatchGetOrDelete()
};
foreach (string timeSeriesName in timeSeriesNames)
{
batchRequest.Get.Names.Add(timeSeriesName);
}
Response<InstancesBatchResponse> executeBatchResponse = _instancesRestClient
.ExecuteBatch(batchRequest, null, cancellationToken);
return Response.FromValue(executeBatchResponse.Value.Get.ToArray(), executeBatchResponse.GetRawResponse());
}
catch (Exception ex)
{
scope.Failed(ex);
throw;
}
}
/// <summary>
/// Gets Time Series instances by Time Series Ids asynchronously.
/// </summary>
/// <param name="timeSeriesIds">List of Ids of the Time Series instances to return.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>
/// List of instance or error objects corresponding by position to the array in the request. Instance object is set when operation is successful
/// and error object is set when operation is unsuccessful.
/// </returns>
/// <remarks>
/// For more samples, see <see href="https://github.com/Azure/azure-sdk-for-net/tree/main/sdk/timeseriesinsights/Azure.IoT.TimeSeriesInsights/samples">our repo samples</see>.
/// </remarks>
/// <example>
/// <code snippet="Snippet:TimeSeriesInsightsGetnstancesById" language="csharp">
/// // Get Time Series Insights instances by Id
/// // tsId is created above using `TimeSeriesIdHelper.CreateTimeSeriesId`.
/// var timeSeriesIds = new List<TimeSeriesId>
/// {
/// tsId,
/// };
///
/// Response<InstancesOperationResult[]> getByIdsResult = await instancesClient.GetByIdAsync(timeSeriesIds);
///
/// // The response of calling the API contains a list of instance or error objects corresponding by position to the array in the request.
/// // Instance object is set when operation is successful and error object is set when operation is unsuccessful.
/// for (int i = 0; i < getByIdsResult.Value.Length; i++)
/// {
/// InstancesOperationResult currentOperationResult = getByIdsResult.Value[i];
///
/// if (currentOperationResult.Instance != null)
/// {
/// Console.WriteLine($"Retrieved Time Series Insights instance with Id '{currentOperationResult.Instance.TimeSeriesId}' and name '{currentOperationResult.Instance.Name}'.");
/// }
/// else if (currentOperationResult.Error != null)
/// {
/// Console.WriteLine($"Failed to retrieve a Time Series Insights instance with Id '{timeSeriesIds[i]}'. Error message: '{currentOperationResult.Error.Message}'.");
/// }
/// }
/// </code>
/// </example>
/// <exception cref="ArgumentNullException">
/// The exception is thrown when <paramref name="timeSeriesIds"/> is <c>null</c>.
/// </exception>
/// <exception cref="ArgumentException">
/// The exception is thrown when <paramref name="timeSeriesIds"/> is empty.
/// </exception>
public virtual async Task<Response<InstancesOperationResult[]>> GetByIdAsync(
IEnumerable<TimeSeriesId> timeSeriesIds,
CancellationToken cancellationToken = default)
{
using DiagnosticScope scope = _clientDiagnostics.CreateScope($"{nameof(TimeSeriesInsightsClient)}.{nameof(GetById)}");
scope.Start();
try
{
Argument.AssertNotNullOrEmpty(timeSeriesIds, nameof(timeSeriesIds));
var batchRequest = new InstancesBatchRequest
{
Get = new InstancesRequestBatchGetOrDelete()
};
foreach (TimeSeriesId timeSeriesId in timeSeriesIds)
{
batchRequest.Get.TimeSeriesIds.Add(timeSeriesId);
}
Response<InstancesBatchResponse> executeBatchResponse = await _instancesRestClient
.ExecuteBatchAsync(batchRequest, null, cancellationToken)
.ConfigureAwait(false);
return Response.FromValue(executeBatchResponse.Value.Get.ToArray(), executeBatchResponse.GetRawResponse());
}
catch (Exception ex)
{
scope.Failed(ex);
throw;
}
}
/// <summary>
/// Gets Time Series instances by Time Series Ids synchronously.
/// </summary>
/// <param name="timeSeriesIds">List of Ids of the Time Series instances to return.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>
/// List of instance or error objects corresponding by position to the array in the request. Instance object is set when operation is successful
/// and error object is set when operation is unsuccessful.
/// </returns>
/// <seealso cref="GetByIdAsync(IEnumerable{TimeSeriesId}, CancellationToken)">
/// See the asynchronous version of this method for examples.
/// </seealso>
/// <exception cref="ArgumentNullException">
/// The exception is thrown when <paramref name="timeSeriesIds"/> is <c>null</c>.
/// </exception>
/// <exception cref="ArgumentException">
/// The exception is thrown when <paramref name="timeSeriesIds"/> is empty.
/// </exception>
public virtual Response<InstancesOperationResult[]> GetById(
IEnumerable<TimeSeriesId> timeSeriesIds,
CancellationToken cancellationToken = default)
{
using DiagnosticScope scope = _clientDiagnostics.CreateScope($"{nameof(TimeSeriesInsightsClient)}.{nameof(GetById)}");
scope.Start();
try
{
Argument.AssertNotNullOrEmpty(timeSeriesIds, nameof(timeSeriesIds));
var batchRequest = new InstancesBatchRequest
{
Get = new InstancesRequestBatchGetOrDelete()
};
foreach (TimeSeriesId timeSeriesId in timeSeriesIds)
{
batchRequest.Get.TimeSeriesIds.Add(timeSeriesId);
}
Response<InstancesBatchResponse> executeBatchResponse = _instancesRestClient
.ExecuteBatch(batchRequest, null, cancellationToken);
return Response.FromValue(executeBatchResponse.Value.Get.ToArray(), executeBatchResponse.GetRawResponse());
}
catch (Exception ex)
{
scope.Failed(ex);
throw;
}
}
/// <summary>
/// Creates Time Series instances asynchronously. If a provided instance is already in use, then this will attempt to replace the existing
/// instance with the provided Time Series Instance.
/// </summary>
/// <param name="timeSeriesInstances">The Time Series instances to be created or replaced.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>
/// List of error objects corresponding by position to the <paramref name="timeSeriesInstances"/> array in the request.
/// A <seealso cref="TimeSeriesOperationError"/> object will be set when operation is unsuccessful.
/// </returns>
/// <remarks>
/// For more samples, see <see href="https://github.com/Azure/azure-sdk-for-net/tree/main/sdk/timeseriesinsights/Azure.IoT.TimeSeriesInsights/samples">our repo samples</see>.
/// </remarks>
/// <example>
/// <code snippet="Snippet:TimeSeriesInsightsSampleCreateInstance" language="csharp">
/// // Create a Time Series Instance object with the default Time Series Insights type Id.
/// // The default type Id can be obtained programmatically by using the ModelSettings client.
/// // tsId is created above using `TimeSeriesIdHelper.CreateTimeSeriesId`.
/// var instance = new TimeSeriesInstance(tsId, defaultTypeId)
/// {
/// Name = "instance1",
/// };
///
/// var tsiInstancesToCreate = new List<TimeSeriesInstance>
/// {
/// instance,
/// };
///
/// Response<TimeSeriesOperationError[]> createInstanceErrors = await instancesClient
/// .CreateOrReplaceAsync(tsiInstancesToCreate);
///
/// // The response of calling the API contains a list of error objects corresponding by position to the input parameter
/// // array in the request. If the error object is set to null, this means the operation was a success.
/// for (int i = 0; i < createInstanceErrors.Value.Length; i++)
/// {
/// TimeSeriesId tsiId = tsiInstancesToCreate[i].TimeSeriesId;
///
/// if (createInstanceErrors.Value[i] == null)
/// {
/// Console.WriteLine($"Created Time Series Insights instance with Id '{tsiId}'.");
/// }
/// else
/// {
/// Console.WriteLine($"Failed to create a Time Series Insights instance with Id '{tsiId}', " +
/// $"Error Message: '{createInstanceErrors.Value[i].Message}, " +
/// $"Error code: '{createInstanceErrors.Value[i].Code}'.");
/// }
/// }
/// </code>
/// </example>
/// <exception cref="ArgumentNullException">
/// The exception is thrown when <paramref name="timeSeriesInstances"/> is <c>null</c>.
/// </exception>
/// <exception cref="ArgumentException">
/// The exception is thrown when <paramref name="timeSeriesInstances"/> is empty.
/// </exception>
public virtual async Task<Response<TimeSeriesOperationError[]>> CreateOrReplaceAsync(
IEnumerable<TimeSeriesInstance> timeSeriesInstances,
CancellationToken cancellationToken = default)
{
using DiagnosticScope scope = _clientDiagnostics
.CreateScope($"{nameof(TimeSeriesInsightsClient)}.{nameof(CreateOrReplace)}");
scope.Start();
try
{
Argument.AssertNotNullOrEmpty(timeSeriesInstances, nameof(timeSeriesInstances));
var batchRequest = new InstancesBatchRequest();
foreach (TimeSeriesInstance instance in timeSeriesInstances)
{
batchRequest.Put.Add(instance);
}
Response<InstancesBatchResponse> executeBatchResponse = await _instancesRestClient
.ExecuteBatchAsync(batchRequest, null, cancellationToken)
.ConfigureAwait(false);
// Extract the errors array from the response. If there was an error with creating or replacing one of the instances,
// it will be placed at the same index location that corresponds to its place in the input array.
IEnumerable<TimeSeriesOperationError> errorResults = executeBatchResponse.Value.Put.Select((result) => result.Error);
return Response.FromValue(errorResults.ToArray(), executeBatchResponse.GetRawResponse());
}
catch (Exception ex)
{
scope.Failed(ex);
throw;
}
}
/// <summary>
/// Creates Time Series instances synchronously. If a provided instance is already in use, then this will attempt to replace the existing
/// instance with the provided Time Series Instance.
/// </summary>
/// <param name="timeSeriesInstances">The Time Series instances to be created or replaced.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>
/// List of error objects corresponding by position to the <paramref name="timeSeriesInstances"/> array in the request.
/// A <seealso cref="TimeSeriesOperationError"/> object will be set when operation is unsuccessful.
/// </returns>
/// <seealso cref="CreateOrReplaceAsync(IEnumerable{TimeSeriesInstance}, CancellationToken)">
/// See the asynchronous version of this method for examples.
/// </seealso>
/// <exception cref="ArgumentNullException">
/// The exception is thrown when <paramref name="timeSeriesInstances"/> is <c>null</c>.
/// </exception>
/// <exception cref="ArgumentException">
/// The exception is thrown when <paramref name="timeSeriesInstances"/> is empty.
/// </exception>
public virtual Response<TimeSeriesOperationError[]> CreateOrReplace(
IEnumerable<TimeSeriesInstance> timeSeriesInstances,
CancellationToken cancellationToken = default)
{
using DiagnosticScope scope = _clientDiagnostics.CreateScope($"{nameof(TimeSeriesInsightsClient)}.{nameof(CreateOrReplace)}");
scope.Start();
try
{
Argument.AssertNotNullOrEmpty(timeSeriesInstances, nameof(timeSeriesInstances));
var batchRequest = new InstancesBatchRequest();
foreach (TimeSeriesInstance instance in timeSeriesInstances)
{
batchRequest.Put.Add(instance);
}
Response<InstancesBatchResponse> executeBatchResponse = _instancesRestClient
.ExecuteBatch(batchRequest, null, cancellationToken);
// Extract the errors array from the response. If there was an error with creating or replacing one of the instances,
// it will be placed at the same index location that corresponds to its place in the input array.
IEnumerable<TimeSeriesOperationError> errorResults = executeBatchResponse.Value.Put.Select((result) => result.Error);
return Response.FromValue(errorResults.ToArray(), executeBatchResponse.GetRawResponse());
}
catch (Exception ex)
{
scope.Failed(ex);
throw;
}
}
/// <summary>
/// Replaces Time Series instances asynchronously.
/// </summary>
/// <param name="timeSeriesInstances">The Time Series instances to replaced.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>
/// List of objects corresponding by position to the <paramref name="timeSeriesInstances"/> array in the request. Instance object
/// is set when operation is successful and error object is set when operation is unsuccessful.
/// </returns>
/// <remarks>
/// For more samples, see <see href="https://github.com/Azure/azure-sdk-for-net/tree/main/sdk/timeseriesinsights/Azure.IoT.TimeSeriesInsights/samples">our repo samples</see>.
/// </remarks>
/// <example>
/// <code snippet="Snippet:TimeSeriesInsightsReplaceInstance" language="csharp">
/// // Get Time Series Insights instances by Id
/// // tsId is created above using `TimeSeriesIdHelper.CreateTimeSeriesId`.
/// var instanceIdsToGet = new List<TimeSeriesId>
/// {
/// tsId,
/// };
///
/// Response<InstancesOperationResult[]> getInstancesByIdResult = await instancesClient.GetByIdAsync(instanceIdsToGet);
///
/// TimeSeriesInstance instanceResult = getInstancesByIdResult.Value[0].Instance;
/// Console.WriteLine($"Retrieved Time Series Insights instance with Id '{instanceResult.TimeSeriesId}' and name '{instanceResult.Name}'.");
///
/// // Now let's replace the instance with an updated name
/// instanceResult.Name = "newInstanceName";
///
/// var instancesToReplace = new List<TimeSeriesInstance>
/// {
/// instanceResult,
/// };
///
/// Response<InstancesOperationResult[]> replaceInstancesResult = await instancesClient.ReplaceAsync(instancesToReplace);
///
/// // The response of calling the API contains a list of error objects corresponding by position to the input parameter.
/// // array in the request. If the error object is set to null, this means the operation was a success.
/// for (int i = 0; i < replaceInstancesResult.Value.Length; i++)
/// {
/// TimeSeriesId tsiId = instancesToReplace[i].TimeSeriesId;
///
/// TimeSeriesOperationError currentError = replaceInstancesResult.Value[i].Error;
///
/// if (currentError != null)
/// {
/// Console.WriteLine($"Failed to replace Time Series Insights instance with Id '{tsiId}'," +
/// $" Error Message: '{currentError.Message}', Error code: '{currentError.Code}'.");
/// }
/// else
/// {
/// Console.WriteLine($"Replaced Time Series Insights instance with Id '{tsiId}'.");
/// }
/// }
/// </code>
/// </example>
/// <exception cref="ArgumentNullException">
/// The exception is thrown when <paramref name="timeSeriesInstances"/> is <c>null</c>.
/// </exception>
/// <exception cref="ArgumentException">
/// The exception is thrown when <paramref name="timeSeriesInstances"/> is empty.
/// </exception>
public virtual async Task<Response<InstancesOperationResult[]>> ReplaceAsync(
IEnumerable<TimeSeriesInstance> timeSeriesInstances,
CancellationToken cancellationToken = default)
{
using DiagnosticScope scope = _clientDiagnostics
.CreateScope($"{nameof(TimeSeriesInsightsClient)}.{nameof(Replace)}");
scope.Start();
try
{
Argument.AssertNotNullOrEmpty(timeSeriesInstances, nameof(timeSeriesInstances));
var batchRequest = new InstancesBatchRequest();
foreach (TimeSeriesInstance instance in timeSeriesInstances)
{
batchRequest.Update.Add(instance);
}
Response<InstancesBatchResponse> executeBatchResponse = await _instancesRestClient
.ExecuteBatchAsync(batchRequest, null, cancellationToken)
.ConfigureAwait(false);
return Response.FromValue(executeBatchResponse.Value.Update.ToArray(), executeBatchResponse.GetRawResponse());
}
catch (Exception ex)
{
scope.Failed(ex);
throw;
}
}
/// <summary>
/// Replaces Time Series instances synchronously.
/// </summary>
/// <param name="timeSeriesInstances">The Time Series instances to be replaced.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>
/// List of objects corresponding by position to the <paramref name="timeSeriesInstances"/> array in the request. Instance object
/// is set when operation is successful and error object is set when operation is unsuccessful.
/// </returns>
/// <seealso cref="ReplaceAsync(IEnumerable{TimeSeriesInstance}, CancellationToken)">
/// See the asynchronous version of this method for examples.
/// </seealso>
/// <exception cref="ArgumentNullException">
/// The exception is thrown when <paramref name="timeSeriesInstances"/> is <c>null</c>.
/// </exception>
/// <exception cref="ArgumentException">
/// The exception is thrown when <paramref name="timeSeriesInstances"/> is empty.
/// </exception>
public virtual Response<InstancesOperationResult[]> Replace(
IEnumerable<TimeSeriesInstance> timeSeriesInstances,
CancellationToken cancellationToken = default)
{
using DiagnosticScope scope = _clientDiagnostics.CreateScope($"{nameof(TimeSeriesInsightsClient)}.{nameof(Replace)}");
scope.Start();
try
{
Argument.AssertNotNullOrEmpty(timeSeriesInstances, nameof(timeSeriesInstances));
var batchRequest = new InstancesBatchRequest();
foreach (TimeSeriesInstance instance in timeSeriesInstances)
{
batchRequest.Update.Add(instance);
}
Response<InstancesBatchResponse> executeBatchResponse = _instancesRestClient
.ExecuteBatch(batchRequest, null, cancellationToken);
return Response.FromValue(executeBatchResponse.Value.Update.ToArray(), executeBatchResponse.GetRawResponse());
}
catch (Exception ex)
{
scope.Failed(ex);
throw;
}
}
/// <summary>
/// Deletes Time Series instances from the environment by instance names asynchronously.
/// </summary>
/// <param name="timeSeriesNames">List of names of the Time Series instance to delete.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>
/// List of error objects corresponding by position to the array in the request. Null means the instance has been deleted, or did not exist.
/// Error object is set when operation is unsuccessful.
/// </returns>
/// <remarks>
/// For more samples, see <see href="https://github.com/Azure/azure-sdk-for-net/tree/main/sdk/timeseriesinsights/Azure.IoT.TimeSeriesInsights/samples">our repo samples</see>.
/// </remarks>
/// <example>
/// <code snippet="Snippet:TimeSeriesInsightsSampleDeleteInstanceById" language="csharp">
/// // tsId is created above using `TimeSeriesIdHelper.CreateTimeSeriesId`.
/// var instancesToDelete = new List<TimeSeriesId>
/// {
/// tsId,
/// };
///
/// Response<TimeSeriesOperationError[]> deleteInstanceErrors = await instancesClient
/// .DeleteByIdAsync(instancesToDelete);
///
/// // The response of calling the API contains a list of error objects corresponding by position to the input parameter
/// // array in the request. If the error object is set to null, this means the operation was a success.
/// for (int i = 0; i < deleteInstanceErrors.Value.Length; i++)
/// {
/// TimeSeriesId tsiId = instancesToDelete[i];
///
/// if (deleteInstanceErrors.Value[i] == null)
/// {
/// Console.WriteLine($"Deleted Time Series Insights instance with Id '{tsiId}'.");
/// }
/// else
/// {
/// Console.WriteLine($"Failed to delete a Time Series Insights instance with Id '{tsiId}'. Error Message: '{deleteInstanceErrors.Value[i].Message}'");
/// }
/// }
/// </code>
/// </example>
/// <exception cref="ArgumentNullException">
/// The exception is thrown when <paramref name="timeSeriesNames"/> is <c>null</c>.
/// </exception>
/// <exception cref="ArgumentException">
/// The exception is thrown when <paramref name="timeSeriesNames"/> is empty.
/// </exception>
public virtual async Task<Response<TimeSeriesOperationError[]>> DeleteByNameAsync(
IEnumerable<string> timeSeriesNames,
CancellationToken cancellationToken = default)
{
using DiagnosticScope scope = _clientDiagnostics.CreateScope($"{nameof(TimeSeriesInsightsClient)}.{nameof(DeleteByName)}");
scope.Start();
try
{
Argument.AssertNotNullOrEmpty(timeSeriesNames, nameof(timeSeriesNames));
var batchRequest = new InstancesBatchRequest
{
Delete = new InstancesRequestBatchGetOrDelete()
};
foreach (string timeSeriesName in timeSeriesNames)
{
batchRequest.Delete.Names.Add(timeSeriesName);
}
Response<InstancesBatchResponse> executeBatchResponse = await _instancesRestClient
.ExecuteBatchAsync(batchRequest, null, cancellationToken)
.ConfigureAwait(false);
return Response.FromValue(executeBatchResponse.Value.Delete.ToArray(), executeBatchResponse.GetRawResponse());
}
catch (Exception ex)
{
scope.Failed(ex);
throw;
}
}
/// <summary>
/// Deletes Time Series instances from the environment by instance names synchronously.
/// </summary>
/// <param name="timeSeriesNames">List of names of the Time Series instance to delete.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>
/// List of error objects corresponding by position to the array in the request. Null means the instance has been deleted, or did not exist.
/// Error object is set when operation is unsuccessful.
/// </returns>
/// <seealso cref="DeleteByNameAsync(IEnumerable{string}, CancellationToken)">
/// See the asynchronous version of this method for examples.
/// </seealso>
/// <exception cref="ArgumentNullException">
/// The exception is thrown when <paramref name="timeSeriesNames"/> is <c>null</c>.
/// </exception>
/// <exception cref="ArgumentException">
/// The exception is thrown when <paramref name="timeSeriesNames"/> is empty.
/// </exception>
public virtual Response<TimeSeriesOperationError[]> DeleteByName(
IEnumerable<string> timeSeriesNames,
CancellationToken cancellationToken = default)
{
using DiagnosticScope scope = _clientDiagnostics.CreateScope($"{nameof(TimeSeriesInsightsClient)}.{nameof(DeleteByName)}");
scope.Start();
try
{
Argument.AssertNotNullOrEmpty(timeSeriesNames, nameof(timeSeriesNames));
var batchRequest = new InstancesBatchRequest
{
Delete = new InstancesRequestBatchGetOrDelete()
};
foreach (string timeSeriesName in timeSeriesNames)
{
batchRequest.Delete.Names.Add(timeSeriesName);
}
Response<InstancesBatchResponse> executeBatchResponse = _instancesRestClient
.ExecuteBatch(batchRequest, null, cancellationToken);
return Response.FromValue(executeBatchResponse.Value.Delete.ToArray(), executeBatchResponse.GetRawResponse());
}
catch (Exception ex)
{
scope.Failed(ex);
throw;
}
}
/// <summary>
/// Deletes Time Series instances from the environment by Time Series Ids asynchronously.
/// </summary>
/// <param name="timeSeriesIds">List of Ids of the Time Series instances to delete.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>
/// List of error objects corresponding by position to the array in the request. Null means the instance has been deleted, or did not exist.
/// Error object is set when operation is unsuccessful.
/// </returns>
/// <remarks>
/// For more samples, see <see href="https://github.com/Azure/azure-sdk-for-net/tree/main/sdk/timeseriesinsights/Azure.IoT.TimeSeriesInsights/samples">our repo samples</see>.
/// </remarks>
/// <exception cref="ArgumentNullException">
/// The exception is thrown when <paramref name="timeSeriesIds"/> is <c>null</c>.
/// </exception>
/// <exception cref="ArgumentException">
/// The exception is thrown when <paramref name="timeSeriesIds"/> is empty.
/// </exception>
public virtual async Task<Response<TimeSeriesOperationError[]>> DeleteByIdAsync(
IEnumerable<TimeSeriesId> timeSeriesIds,
CancellationToken cancellationToken = default)
{
using DiagnosticScope scope = _clientDiagnostics.CreateScope($"{nameof(TimeSeriesInsightsClient)}.{nameof(DeleteById)}");
scope.Start();
try
{
Argument.AssertNotNullOrEmpty(timeSeriesIds, nameof(timeSeriesIds));
var batchRequest = new InstancesBatchRequest
{
Delete = new InstancesRequestBatchGetOrDelete()
};
foreach (TimeSeriesId timeSeriesId in timeSeriesIds)
{
batchRequest.Delete.TimeSeriesIds.Add(timeSeriesId);
}
Response<InstancesBatchResponse> executeBatchResponse = await _instancesRestClient
.ExecuteBatchAsync(batchRequest, null, cancellationToken)
.ConfigureAwait(false);
return Response.FromValue(executeBatchResponse.Value.Delete.ToArray(), executeBatchResponse.GetRawResponse());
}
catch (Exception ex)
{
scope.Failed(ex);
throw;
}
}
/// <summary>
/// Deletes Time Series instances from the environment by Time Series Ids synchronously.
/// </summary>
/// <param name="timeSeriesIds">List of Ids of the Time Series instances to delete.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>
/// List of error objects corresponding by position to the array in the request. Null means the instance has been deleted, or did not exist.
/// Error object is set when operation is unsuccessful.
/// </returns>
/// <seealso cref="DeleteByIdAsync(IEnumerable{TimeSeriesId}, CancellationToken)">
/// See the asynchronous version of this method for examples.
/// </seealso>
/// <exception cref="ArgumentNullException">
/// The exception is thrown when <paramref name="timeSeriesIds"/> is <c>null</c>.
/// </exception>
/// <exception cref="ArgumentException">
/// The exception is thrown when <paramref name="timeSeriesIds"/> is empty.
/// </exception>
public virtual Response<TimeSeriesOperationError[]> DeleteById(
IEnumerable<TimeSeriesId> timeSeriesIds,
CancellationToken cancellationToken = default)
{
using DiagnosticScope scope = _clientDiagnostics.CreateScope($"{nameof(TimeSeriesInsightsClient)}.{nameof(DeleteById)}");
scope.Start();
try
{
Argument.AssertNotNullOrEmpty(timeSeriesIds, nameof(timeSeriesIds));
var batchRequest = new InstancesBatchRequest
{
Delete = new InstancesRequestBatchGetOrDelete()
};
foreach (TimeSeriesId timeSeriesId in timeSeriesIds)
{
batchRequest.Delete.TimeSeriesIds.Add(timeSeriesId);
}
Response<InstancesBatchResponse> executeBatchResponse = _instancesRestClient
.ExecuteBatch(batchRequest, null, cancellationToken);
return Response.FromValue(executeBatchResponse.Value.Delete.ToArray(), executeBatchResponse.GetRawResponse());
}
catch (Exception ex)
{
scope.Failed(ex);
throw;
}
}
}
}
| 47.995671 | 220 | 0.599734 | [
"MIT"
] | 93mishra/azure-sdk-for-net | sdk/timeseriesinsights/Azure.IoT.TimeSeriesInsights/src/TimeSeriesInsightsInstances.cs | 44,348 | C# |
namespace SpellforceDataEditor.SFMap.map_dialog
{
partial class MapAutoTextureDialog
{
/// <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.SlopeValueTrackbar = new System.Windows.Forms.TrackBar();
this.label1 = new System.Windows.Forms.Label();
this.PanelBelowThreshold = new System.Windows.Forms.Panel();
this.ButtonAddBelow = new System.Windows.Forms.Button();
this.label5 = new System.Windows.Forms.Label();
this.label2 = new System.Windows.Forms.Label();
this.label4 = new System.Windows.Forms.Label();
this.SlopeValue = new System.Windows.Forms.TextBox();
this.ButtonCancel = new System.Windows.Forms.Button();
this.ButtonApply = new System.Windows.Forms.Button();
this.PanelAboveThreshold = new System.Windows.Forms.Panel();
this.ButtonAddAbove = new System.Windows.Forms.Button();
this.label3 = new System.Windows.Forms.Label();
this.label6 = new System.Windows.Forms.Label();
this.label7 = new System.Windows.Forms.Label();
((System.ComponentModel.ISupportInitialize)(this.SlopeValueTrackbar)).BeginInit();
this.PanelBelowThreshold.SuspendLayout();
this.PanelAboveThreshold.SuspendLayout();
this.SuspendLayout();
//
// SlopeValueTrackbar
//
this.SlopeValueTrackbar.Location = new System.Drawing.Point(101, 12);
this.SlopeValueTrackbar.Maximum = 90;
this.SlopeValueTrackbar.Name = "SlopeValueTrackbar";
this.SlopeValueTrackbar.Orientation = System.Windows.Forms.Orientation.Vertical;
this.SlopeValueTrackbar.Size = new System.Drawing.Size(45, 334);
this.SlopeValueTrackbar.SmallChange = 5;
this.SlopeValueTrackbar.TabIndex = 0;
this.SlopeValueTrackbar.TickFrequency = 10;
this.SlopeValueTrackbar.Value = 30;
this.SlopeValueTrackbar.ValueChanged += new System.EventHandler(this.SlopeValueTrackbar_ValueChanged);
//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(9, 163);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(83, 13);
this.label1.TabIndex = 1;
this.label1.Text = "Slope threshold";
//
// PanelBelowThreshold
//
this.PanelBelowThreshold.Controls.Add(this.ButtonAddBelow);
this.PanelBelowThreshold.Controls.Add(this.label5);
this.PanelBelowThreshold.Controls.Add(this.label2);
this.PanelBelowThreshold.Controls.Add(this.label4);
this.PanelBelowThreshold.Location = new System.Drawing.Point(152, 182);
this.PanelBelowThreshold.Name = "PanelBelowThreshold";
this.PanelBelowThreshold.Size = new System.Drawing.Size(421, 164);
this.PanelBelowThreshold.TabIndex = 0;
//
// ButtonAddBelow
//
this.ButtonAddBelow.Font = new System.Drawing.Font("Microsoft Sans Serif", 24F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(238)));
this.ButtonAddBelow.Location = new System.Drawing.Point(58, 58);
this.ButtonAddBelow.Name = "ButtonAddBelow";
this.ButtonAddBelow.Size = new System.Drawing.Size(70, 70);
this.ButtonAddBelow.TabIndex = 6;
this.ButtonAddBelow.Text = "+";
this.ButtonAddBelow.UseVisualStyleBackColor = true;
this.ButtonAddBelow.Click += new System.EventHandler(this.ButtonAddBelow_Click);
//
// label5
//
this.label5.AutoSize = true;
this.label5.Location = new System.Drawing.Point(3, 131);
this.label5.Name = "label5";
this.label5.Size = new System.Drawing.Size(41, 13);
this.label5.TabIndex = 3;
this.label5.Text = "Weight";
//
// label2
//
this.label2.AutoSize = true;
this.label2.Location = new System.Drawing.Point(3, 9);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(106, 13);
this.label2.TabIndex = 0;
this.label2.Text = "Tiles below threshold";
//
// label4
//
this.label4.AutoSize = true;
this.label4.Location = new System.Drawing.Point(3, 39);
this.label4.Name = "label4";
this.label4.Size = new System.Drawing.Size(38, 13);
this.label4.TabIndex = 2;
this.label4.Text = "Tile ID";
//
// SlopeValue
//
this.SlopeValue.Location = new System.Drawing.Point(12, 182);
this.SlopeValue.Name = "SlopeValue";
this.SlopeValue.Size = new System.Drawing.Size(83, 20);
this.SlopeValue.TabIndex = 3;
this.SlopeValue.Text = "30";
this.SlopeValue.Validated += new System.EventHandler(this.SlopeValue_Validated);
//
// ButtonCancel
//
this.ButtonCancel.Location = new System.Drawing.Point(12, 352);
this.ButtonCancel.Name = "ButtonCancel";
this.ButtonCancel.Size = new System.Drawing.Size(75, 23);
this.ButtonCancel.TabIndex = 4;
this.ButtonCancel.Text = "Close";
this.ButtonCancel.UseVisualStyleBackColor = true;
this.ButtonCancel.Click += new System.EventHandler(this.ButtonCancel_Click);
//
// ButtonApply
//
this.ButtonApply.Location = new System.Drawing.Point(498, 352);
this.ButtonApply.Name = "ButtonApply";
this.ButtonApply.Size = new System.Drawing.Size(75, 23);
this.ButtonApply.TabIndex = 5;
this.ButtonApply.Text = "Apply";
this.ButtonApply.UseVisualStyleBackColor = true;
this.ButtonApply.Click += new System.EventHandler(this.ButtonApply_Click);
//
// PanelAboveThreshold
//
this.PanelAboveThreshold.Controls.Add(this.ButtonAddAbove);
this.PanelAboveThreshold.Controls.Add(this.label3);
this.PanelAboveThreshold.Controls.Add(this.label6);
this.PanelAboveThreshold.Controls.Add(this.label7);
this.PanelAboveThreshold.Location = new System.Drawing.Point(152, 12);
this.PanelAboveThreshold.Name = "PanelAboveThreshold";
this.PanelAboveThreshold.Size = new System.Drawing.Size(421, 164);
this.PanelAboveThreshold.TabIndex = 7;
//
// ButtonAddAbove
//
this.ButtonAddAbove.Font = new System.Drawing.Font("Microsoft Sans Serif", 24F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(238)));
this.ButtonAddAbove.Location = new System.Drawing.Point(58, 58);
this.ButtonAddAbove.Name = "ButtonAddAbove";
this.ButtonAddAbove.Size = new System.Drawing.Size(70, 70);
this.ButtonAddAbove.TabIndex = 6;
this.ButtonAddAbove.Text = "+";
this.ButtonAddAbove.UseVisualStyleBackColor = true;
this.ButtonAddAbove.Click += new System.EventHandler(this.ButtonAddAbove_Click);
//
// label3
//
this.label3.AutoSize = true;
this.label3.Location = new System.Drawing.Point(3, 131);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(41, 13);
this.label3.TabIndex = 3;
this.label3.Text = "Weight";
//
// label6
//
this.label6.AutoSize = true;
this.label6.Location = new System.Drawing.Point(3, 9);
this.label6.Name = "label6";
this.label6.Size = new System.Drawing.Size(108, 13);
this.label6.TabIndex = 0;
this.label6.Text = "Tiles above threshold";
//
// label7
//
this.label7.AutoSize = true;
this.label7.Location = new System.Drawing.Point(3, 41);
this.label7.Name = "label7";
this.label7.Size = new System.Drawing.Size(38, 13);
this.label7.TabIndex = 2;
this.label7.Text = "Tile ID";
//
// MapAutoTextureDialog
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(585, 388);
this.Controls.Add(this.PanelAboveThreshold);
this.Controls.Add(this.ButtonApply);
this.Controls.Add(this.ButtonCancel);
this.Controls.Add(this.SlopeValue);
this.Controls.Add(this.PanelBelowThreshold);
this.Controls.Add(this.label1);
this.Controls.Add(this.SlopeValueTrackbar);
this.Name = "MapAutoTextureDialog";
this.Text = "Slope-based paint";
((System.ComponentModel.ISupportInitialize)(this.SlopeValueTrackbar)).EndInit();
this.PanelBelowThreshold.ResumeLayout(false);
this.PanelBelowThreshold.PerformLayout();
this.PanelAboveThreshold.ResumeLayout(false);
this.PanelAboveThreshold.PerformLayout();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.TrackBar SlopeValueTrackbar;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Panel PanelBelowThreshold;
private System.Windows.Forms.Label label5;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.Label label4;
private System.Windows.Forms.TextBox SlopeValue;
private System.Windows.Forms.Button ButtonCancel;
private System.Windows.Forms.Button ButtonApply;
private System.Windows.Forms.Button ButtonAddBelow;
private System.Windows.Forms.Panel PanelAboveThreshold;
private System.Windows.Forms.Button ButtonAddAbove;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.Label label6;
private System.Windows.Forms.Label label7;
}
} | 47.243802 | 176 | 0.597044 | [
"MIT"
] | leszekd25/spellforce_data_editor | SpellforceDataEditor/SFMap/map_dialog/MapAutoTextureDialog.Designer.cs | 11,435 | C# |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Data;
namespace MetroTrilithon.Converters
{
public class ReverseBooleanConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
return !(value as bool?) ?? false;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
return !(value as bool?) ?? false;
}
}
}
| 24.478261 | 98 | 0.728242 | [
"MIT"
] | CirnoV/MetroTrilithon | source/RetroTrilithon.Desktop/MetroTrilithon/Converters/ReverseBooleanConverter.cs | 565 | C# |
using MessagePackLib.MessagePack;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net.Security;
using System.Net.Sockets;
using System.Security.Authentication;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading;
namespace Plugin
{
public static class Connection
{
public static Socket TcpClient { get; set; }
public static SslStream SslClient { get; set; }
public static X509Certificate2 ServerCertificate { get; set; }
private static byte[] Buffer { get; set; }
private static long HeaderSize { get; set; }
private static long Offset { get; set; }
private static Timer Tick { get; set; }
public static bool IsConnected { get; set; }
private static object SendSync { get; } = new object();
public static string Hwid { get; set; }
public static void InitializeClient()
{
try
{
TcpClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
{
ReceiveBufferSize = 50 * 1024,
SendBufferSize = 50 * 1024,
};
TcpClient.Connect(Plugin.Socket.RemoteEndPoint.ToString().Split(':')[0], Convert.ToInt32(Plugin.Socket.RemoteEndPoint.ToString().Split(':')[1]));
if (TcpClient.Connected)
{
Debug.WriteLine("Plugin Connected!");
IsConnected = true;
SslClient = new SslStream(new NetworkStream(TcpClient, true), false, ValidateServerCertificate);
SslClient.AuthenticateAsClient(TcpClient.RemoteEndPoint.ToString().Split(':')[0], null, SslProtocols.Tls, false);
HeaderSize = 4;
Buffer = new byte[HeaderSize];
Offset = 0;
Tick = new Timer(new TimerCallback(CheckServer), null, new Random().Next(15 * 1000, 30 * 1000), new Random().Next(15 * 1000, 30 * 1000));
SslClient.BeginRead(Buffer, 0, Buffer.Length, ReadServertData, null);
new Thread(() =>
{
MsgPack msgpack = new MsgPack();
msgpack.ForcePathObject("Packet").AsString = "chat-";
msgpack.ForcePathObject("Hwid").AsString = Hwid;
Send(msgpack.Encode2Bytes());
new HandlerChat().CreateChat();
}).Start();
}
else
{
IsConnected = false;
return;
}
}
catch
{
Debug.WriteLine("Disconnected!");
IsConnected = false;
return;
}
}
private static bool ValidateServerCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
{
#if DEBUG
return true;
#endif
return ServerCertificate.Equals(certificate);
}
public static void Disconnected()
{
try
{
IsConnected = false;
Tick?.Dispose();
SslClient?.Dispose();
TcpClient?.Dispose();
}
catch { }
}
public static void ReadServertData(IAsyncResult ar) //Socket read/recevie
{
try
{
if (!TcpClient.Connected || !IsConnected)
{
IsConnected = false;
return;
}
int recevied = SslClient.EndRead(ar);
if (recevied > 0)
{
Offset += recevied;
HeaderSize -= recevied;
if (HeaderSize == 0)
{
HeaderSize = BitConverter.ToInt32(Buffer, 0);
Debug.WriteLine("/// Plugin Buffersize " + HeaderSize.ToString() + " Bytes ///");
if (HeaderSize > 0)
{
Offset = 0;
Buffer = new byte[HeaderSize];
while (HeaderSize > 0)
{
int rc = SslClient.Read(Buffer, (int)Offset, (int)HeaderSize);
if (rc <= 0)
{
IsConnected = false;
return;
}
Offset += rc;
HeaderSize -= rc;
if (HeaderSize < 0)
{
IsConnected = false;
return;
}
}
Thread thread = new Thread(new ParameterizedThreadStart(Packet.Read));
thread.Start(Buffer);
Offset = 0;
HeaderSize = 4;
Buffer = new byte[HeaderSize];
}
else
{
HeaderSize = 4;
Buffer = new byte[HeaderSize];
Offset = 0;
}
}
else if (HeaderSize < 0)
{
IsConnected = false;
return;
}
SslClient.BeginRead(Buffer, (int)Offset, (int)HeaderSize, ReadServertData, null);
}
else
{
IsConnected = false;
return;
}
}
catch
{
IsConnected = false;
return;
}
}
public static void Send(byte[] msg)
{
lock (SendSync)
{
try
{
if (!IsConnected || msg == null)
{
return;
}
byte[] buffersize = BitConverter.GetBytes(msg.Length);
TcpClient.Poll(-1, SelectMode.SelectWrite);
SslClient.Write(buffersize, 0, buffersize.Length);
if (msg.Length > 1000000) //1mb
{
Debug.WriteLine("send chunks");
using (MemoryStream memoryStream = new MemoryStream(msg))
{
int read = 0;
memoryStream.Position = 0;
byte[] chunk = new byte[50 * 1000];
while ((read = memoryStream.Read(chunk, 0, chunk.Length)) > 0)
{
TcpClient.Poll(-1, SelectMode.SelectWrite);
SslClient.Write(chunk, 0, read);
SslClient.Flush();
}
}
}
else
{
TcpClient.Poll(-1, SelectMode.SelectWrite);
SslClient.Write(msg, 0, msg.Length);
SslClient.Flush();
}
Debug.WriteLine("Plugin Packet Sent");
}
catch
{
IsConnected = false;
return;
}
}
}
public static void CheckServer(object obj)
{
MsgPack msgpack = new MsgPack();
msgpack.ForcePathObject("Packet").AsString = "Ping!)";
Send(msgpack.Encode2Bytes());
GC.Collect();
}
}
}
| 36.331858 | 161 | 0.411643 | [
"MIT"
] | 0xyg3n/AsyncRAT-C-Sharp | AsyncRAT-C#/Plugin/Chat/Chat/Connection.cs | 8,213 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
namespace instinct360.Controllers
{
public class UserController : Controller
{
//
// GET: /User/
public ActionResult Index()
{
return View();
}
[HttpGet]
public ActionResult Login()
{
return View();
}
[HttpPost]
public ActionResult Login(Models.User user)
{
if (ModelState.IsValid)
{
if (user.IsValid(user.UserName, user.Password))
{
FormsAuthentication.SetAuthCookie(user.UserName, user.RememberMe);
return RedirectToAction("Index", "Secure");
}
else
{
ModelState.AddModelError("", "Login data is incorrect!");
}
}
return View(user);
}
public ActionResult Logout()
{
FormsAuthentication.SignOut();
return RedirectToAction("Index", "Home");
}
}
} | 24.5 | 86 | 0.5 | [
"MIT"
] | hipparchus2000/instinct360 | instinct360/Controllers/UserController.cs | 1,178 | C# |
using Microsoft.Data.Entity;
namespace UnicornClicker.UWP.Models
{
class UnicornClickerContext : DbContext
{
public DbSet<GameScore> GameScores { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlite("Filename=UnicornClicker.db");
}
}
}
| 23.933333 | 85 | 0.682451 | [
"Apache-2.0"
] | SajjadArifGul/UnicornStore | UnicornClicker/UWP/UnicornClicker.UWP/Models/UnicornClickerContext.cs | 361 | C# |
using System;
namespace SharpGlyph {
/// <summary>
/// font descriptors table (fdsc).
/// <para>Apple Table</para>
/// </summary>
//[AppleTable]
public class FdscTable : Table {
}
}
| 17.272727 | 35 | 0.636842 | [
"MIT"
] | hikipuro/SharpGlyph | SharpGlyph/SharpGlyph/Tables/fdsc/FdscTable.cs | 192 | C# |
using System.Reflection;
using System.Runtime.InteropServices;
using Sceelix.Annotations;
using Sceelix.Core.Annotations;
// 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("Sceelix.Gis")]
[assembly: AssemblyDescription("Sceelix engine library that handles geographic data.")]
[assembly: AssemblyConfiguration("Sceelix")]
[assembly: AssemblyCompany("Sceelix")]
[assembly: AssemblyProduct("Sceelix.Gis")]
[assembly: AssemblyCopyright("Copyright © Sceelix Project 2021")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: AssemblyWebsite("https://sceelix.com")]
[assembly: AssemblyTags("Gis")]
[assembly: EngineLibrary]
// 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("44deafc2-5b80-4cdd-aa5e-e808ef43d55f")]
// 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")] | 40.1 | 87 | 0.753117 | [
"MIT"
] | IxxyXR/Sceelix | Source/Sceelix.Gis/Properties/AssemblyInfo.cs | 1,607 | C# |
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
#if UNITY_EDITOR
public class AssetDatabaseBackend : FileSystemBackend
{
protected override T LoadAsset<T>(string filePath)
{
return UnityEditor.AssetDatabase.LoadAssetAtPath<T>(filePath);
}
protected override string[] LoadAssetList(string folder, string search)
{
var list = new List<string>();
if (!System.IO.Directory.Exists(folder))
return list.ToArray();
var assets = UnityEditor.AssetDatabase.FindAssets("", new[] { folder.TrimEnd( '/' ) }).Select(guid => UnityEditor.AssetDatabase.GUIDToAssetPath(guid)).Distinct();
foreach (var path in assets)
{
if (!string.IsNullOrEmpty(search) && path.IndexOf(search, System.StringComparison.InvariantCultureIgnoreCase) == -1)
continue;
list.Add(path);
}
return list.ToArray();
}
}
#endif
| 24.648649 | 165 | 0.70614 | [
"MIT"
] | Facepunch/Rust.World | Assets/Plugins/Rust.FileSystem/AssetDatabaseBackend.cs | 914 | C# |
using CodingTracker;
namespace CreateAttribute
{
[Author("Ventsi")]
class StartUp
{
[Author("Gosho")]
static void Main(string[] args)
{
var tracker = new Tracker();
tracker.PrintMethodsByAuthor("Gosho");
}
}
}
| 17.75 | 50 | 0.538732 | [
"MIT"
] | elipopovadev/CSharp-OOP | ReflectionAndAttributes-Lab/CodingTracker/StartUp.cs | 286 | C# |
namespace Oxide.Ext.BriansMod.Model.Rust.Contracts
{
public interface IHeldEntity : IBaseEntity
{
HoldType HoldType { get; }
IBasePlayer OwnerPlayer { get; }
}
} | 21.125 | 51 | 0.739645 | [
"MIT"
] | bgourlie/BriansMod | Oxide.Ext.BriansMod/Model/Rust/Contracts/IHeldEntity.cs | 171 | C# |
using System.Collections.Generic;
namespace Calculator
{
public class PlusOperation : EquationItem, IFunction
{
public PlusOperation(FunctionType type)
{
Type = type;
}
public double Execute(List<object> EqItems)
{
double leftNum = Index == 0 ? 0 : GetNum(EqItems, Index, -1);
double rightNum = GetNum(EqItems, Index, 1);
return leftNum + rightNum;
}
public override string GetStringRepresentation()
{
return "+";
}
public IFunction NewInstance()
{
return new PlusOperation(Type);
}
}
}
| 22.4 | 73 | 0.544643 | [
"MIT"
] | Memdis/Calculator | Calculator/Classes/EquationItems/Operations/PlusOperation.cs | 674 | C# |
using System;
using Umbraco.Core;
using Umbraco.Core.Logging;
using Umbraco.Core.PropertyEditors;
using Umbraco.Core.Services;
using Umbraco.Web.PropertyEditors;
namespace HappyPorch.UmbracoExtensions.Core.PropertyEditors
{
[DataEditor(
EditorAlias,
"Nested Content - Elements",
"~/App_Plugins/UmbracoBase/backoffice/views/nestedcontent.html",
ValueType = ValueTypes.Json,
Group = Constants.PropertyEditors.Groups.Lists,
Icon = "icon-thumbnail-list")]
public class NestedContentElementsPropertyEditor : NestedContentPropertyEditor
{
public const string EditorAlias = Constants.PropertyEditors.Aliases.NestedContent + "Elements";
public NestedContentElementsPropertyEditor(ILogger logger, Lazy<PropertyEditorCollection> propertyEditors, IDataTypeService dataTypeService, IContentTypeService contentTypeService)
: base(logger, propertyEditors, dataTypeService, contentTypeService)
{
}
}
}
| 36.962963 | 188 | 0.747495 | [
"MIT"
] | HappyPorch/HappyPorch.UmbracoExtensions.Core | Happyporch.UmbracoExtensions.Core/PropertyEditors/NestedContentElementsPropertyEditor.cs | 1,000 | C# |
using System;
using DevBot9.Protocols.Homie;
using DevBot9.Protocols.Homie.Utilities;
using NLog;
namespace IotFleet.Shed;
partial class Domekt200 {
private HostDevice _device;
private readonly YahiTevuxHostConnection _broker = new();
private readonly ReliableModbus _reliableModbus = new();
public HostChoiceProperty ActualState { get; private set; }
public HostChoiceProperty ActualVentilationLevelProperty { get; private set; }
public HostNumberProperty SupplyAirTemperatureProperty { get; private set; }
HostTextProperty _actualDateTimeProperty;
HostChoiceProperty _targetState;
HostChoiceProperty _actualModbusConnectionState;
HostNumberProperty _disconnectCount;
private readonly DateTime _startTime = DateTime.Now;
private HostNumberProperty _systemUptime;
public static Logger Log = LogManager.GetCurrentClassLogger();
public Domekt200() { }
}
| 32.551724 | 83 | 0.762712 | [
"MIT"
] | devbotas/IotFleet.Shed | Domekt200/Code/Domekt200.cs | 918 | C# |
/* Copyright (c) Citrix Systems Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms,
* with or without modification, are permitted provided
* that the following conditions are met:
*
* * Redistributions of source code must retain the above
* copyright notice, this list of conditions and the
* following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the
* following disclaimer in the documentation and/or other
* materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
* CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Text;
using XenAdmin.Network;
using XenAPI;
namespace XenAdmin.Actions.VMActions
{
public class SuspendAndShutdownVMsAction : AsyncAction
{
private List<VM> VmsToSuspend;
private List<VM> VmsToShutdown;
private int ActionCountTotal;
private int ActionCountCompleted;
public SuspendAndShutdownVMsAction(IXenConnection connection, Host host, List<VM> vmsToSuspend, List<VM> vmsToShutdown)
: base(connection, Messages.SUSPEND_SHUTDOWN_VMS_ACTION_DESC, true)
{
Host = host;
VmsToSuspend = vmsToSuspend;
VmsToShutdown = vmsToShutdown;
#region RBAC Dependencies
ApiMethodsToRoleCheck.AddRange(Role.CommonSessionApiList);
ApiMethodsToRoleCheck.AddRange(Role.CommonTaskApiList);
if (vmsToSuspend.Count > 0)
ApiMethodsToRoleCheck.Add("vm.suspend");
if (vmsToShutdown.Count > 0)
ApiMethodsToRoleCheck.Add("vm.hard_shutdown");
#endregion
}
protected override void Run()
{
ActionCountCompleted = 0;
ActionCountTotal = VmsToSuspend.Count + VmsToShutdown.Count;
foreach (VM vm in VmsToSuspend)
{
Description = string.Format(Messages.SUSPENDING_VM_OUT_OF, ActionCountCompleted + 1, VmsToSuspend.Count);
var action = new VMSuspendAction(vm);
action.Changed += action_Changed;
action.RunExternal(Session);
ActionCountCompleted++;
}
foreach (VM vm in VmsToShutdown)
{
Description = string.Format(Messages.SHUTTING_DOWN_VM_OUT_OF, ActionCountCompleted - VmsToSuspend.Count + 1, VmsToShutdown.Count);
var action = new VMHardShutdown(vm);
action.Changed += action_Changed;
action.RunExternal(Session);
ActionCountCompleted++;
}
}
void action_Changed(ActionBase a)
{
PercentComplete = ((ActionCountCompleted * 100) + a.PercentComplete) / ActionCountTotal;
}
}
}
| 37.917526 | 146 | 0.662588 | [
"BSD-2-Clause"
] | wdxgy136/xenadmin-yeesan | XenModel/Actions/VM/SuspendAndShutdownVMsAction.cs | 3,680 | C# |
using BehavioralDesignPatterns.Command.Interfaces;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BehavioralDesignPatterns.Command.Model.Commands
{
class VolumeDownTvCommand : ICommand
{
public VolumeDownTvCommand(IElectronicDevice device)
{
_device = device;
}
IElectronicDevice _device;
public void Execute()
{
_device.VolumeDown();
}
}
}
| 20.64 | 60 | 0.668605 | [
"MIT"
] | Pavel-Durov/Design-Patterns | BehavioralDesignPatterns/Command/Model/Commands/VolumeDownTvCommand.cs | 518 | C# |
/*
* Copyright 2021, Denyol (https://github.com/Denyol)
*
* 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.IO;
using Budget.Model.Spreadsheet;
using Budget.Model.Spreadsheet.Cells;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace BudgetTest.Model.Spreadsheet {
[TestClass]
[DeploymentItem(@"BudgetTest\resources\TestWorkbook.xlsx")]
public class OfficeWorkbookTest {
[TestMethod]
public void CreateSheet() {
string testEmptyWorkbookPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "resources", "TestWorkbookEmpty.xlsx");
OfficeSpreadsheet spreadsheet = new(testEmptyWorkbookPath);
string sheetName = "Test";
var specialSheetExists = spreadsheet.SheetExists(sheetName);
Assert.IsFalse(specialSheetExists);
spreadsheet.CreateSheet(sheetName);
specialSheetExists = spreadsheet.SheetExists(sheetName);
Assert.IsTrue(specialSheetExists);
spreadsheet.Close();
if (File.Exists(testEmptyWorkbookPath)) {
File.Delete(testEmptyWorkbookPath);
Console.WriteLine($"Deleting {testEmptyWorkbookPath}");
}
}
[TestMethod]
public void GetRows() {
OfficeSpreadsheet spreadsheet = GetTestWorkbook();
Dictionary<int, Row> rows = spreadsheet.GetRows("Special", 1, 1);
Assert.AreEqual("Categories:", rows[1].GetCell(1).ToString());
Assert.AreEqual("Transfer", rows[2].GetCell(1).ToString());
Assert.AreEqual("Medical", rows[6].GetCell(1).ToString());
Assert.IsFalse(rows[6].GetCell(1).Empty);
Assert.IsTrue(rows[10].GetCell(1).Empty);
}
[TestMethod]
public void GetRowTest() {
OfficeSpreadsheet spreadsheet = GetTestWorkbook();
try {
spreadsheet.GetRow("Nonexistent sheet", 0);
} catch (Exception e) {
if (!(e is ArgumentOutOfRangeException))
Assert.Fail("Error not thrown on non-existent sheet query");
}
Row rowContents255 = spreadsheet.GetRow("Transactions", 256);
Assert.IsTrue(rowContents255.Empty);
Console.WriteLine("Row 256 was empty");
Row rowContents0 = spreadsheet.GetRow("Special", 1);
Console.WriteLine("Row 1 contents: " + rowContents0);
Assert.AreEqual("Categories:", rowContents0.GetCell(1).ToString());
Assert.AreEqual("Accounts:", rowContents0.GetCell(2).ToString());
Assert.IsTrue(rowContents0.GetCell(3).Empty);
Assert.AreEqual("Net Worth:", rowContents0.GetCell(4).ToString());
Assert.IsTrue(rowContents0.GetCell(5).Empty);
Assert.AreEqual("1", rowContents0.GetCell(6).ToString());
Row shouldBeEmptyRow = spreadsheet.GetRow("Special", 13);
Assert.IsTrue(shouldBeEmptyRow.Empty);
Assert.IsTrue(rowContents0.GetCell(11).Empty);
spreadsheet.Close();
}
[TestMethod]
public void GetColumnTest() {
OfficeSpreadsheet spreadsheet = GetTestWorkbook();
// Test non-existent sheet
try {
spreadsheet.GetColumn("Nonexistent sheet", 0);
} catch (Exception e) {
if (!(e is ArgumentOutOfRangeException))
Assert.Fail("Error not thrown on non-existent sheet query");
}
// Empty column test
Column column = spreadsheet.GetColumn("Special", 3);
Console.WriteLine("Empty test: " + column);
Assert.IsTrue(column.Empty);
column = spreadsheet.GetColumn("Special", 2);
Console.WriteLine("Test column 2: " + column);
Assert.AreEqual("Accounts:", column.GetCell(1).ToString());
Assert.AreEqual("UP Bank", column.GetCell(2).ToString());
Assert.AreEqual("Bundll", column.GetCell(3).ToString());
Assert.AreEqual(0.0d, column.GetCell(12).ToDouble());
Assert.IsTrue(column.GetCell(13).Empty);
// Test non-existing row
column = spreadsheet.GetColumn("Special", 10);
Assert.IsTrue(column.Empty);
spreadsheet.Close();
}
[TestMethod]
public void SetCellsTest() {
OfficeSpreadsheet spreadsheet = GetTestWorkbook();
Cell? cell;
String testCellName = "Test value1";
spreadsheet.SetCell("Test", 1, 1, testCellName);
cell = spreadsheet.GetCell("Test", 1, 1);
Assert.AreEqual(cell.ToString(), testCellName);
spreadsheet.SetCell("Test", 1, 2, DateTime.Now);
cell = spreadsheet.GetCell("Test", 1, 2);
string todayDate = DateTime.Now.ToString(IWorkbook.EngDateFormat);
Console.WriteLine(todayDate);
Assert.AreEqual(todayDate, cell.ToDate().Value.ToString(IWorkbook.EngDateFormat));
spreadsheet.Close();
}
[TestMethod]
public void GetLastRowNumberTest() {
OfficeSpreadsheet spreadsheet = GetTestWorkbook();
int specialRowNum = spreadsheet.GetLastPhysicalRowNumber("Special");
Console.WriteLine($"{specialRowNum} rows on 'Special'.");
Assert.AreEqual(13, specialRowNum);
int netWorthRowNum = spreadsheet.GetLastPhysicalRowNumber("NET WORTH");
Console.WriteLine($"{netWorthRowNum} rows on 'NET WORTH'");
Assert.AreEqual(11, netWorthRowNum);
}
[TestMethod]
public void TestSheetLoad() {
var workbook = GetTestWorkbook();
Console.WriteLine($"Test: ClosedXMLWorkbook with {workbook.NumberOfSheets} loaded!");
Assert.IsTrue(workbook.NumberOfSheets == 8);
}
private OfficeSpreadsheet GetTestWorkbook() {
//String fileURL = TestConstants.TEST_WORKBOOK_PATH;
string fileURL = Path.Combine("resources", "TestWorkbook.xlsx");
Console.WriteLine(@"Loading {0} from {1}", TestConstants.TEST_WORKBOOK_NAME, fileURL);
OfficeSpreadsheet? spreadsheet = null;
try {
spreadsheet = new OfficeSpreadsheet(fileURL);
} catch (IOException e) {
Console.WriteLine(e);
}
if (spreadsheet == null)
throw new AssertFailedException("Spreadsheet returned null");
return spreadsheet;
}
}
}
| 31.182741 | 125 | 0.716588 | [
"Apache-2.0"
] | Denyol/zero-based-budget-java | test/BudgetTest/Model/Spreadsheet/OfficeWorkbookTest.cs | 6,143 | C# |
using System;
using System.Collections.Generic;
using System.Text;
using System.Xml.Linq;
namespace Biz.Morsink.Rest.HttpConverter.Xml
{
/// <summary>
/// Static class containing readonly/const members to be used for Xml Schema and instances (for nil)
/// </summary>
public static class XsdConstants
{
/// <summary>
/// The Xml schema namespace.
/// </summary>
public static readonly XNamespace XSD = "http://www.w3.org/2001/XMLSchema";
/// <summary>
/// The Xml schema instance namespace.
/// </summary>
public static readonly XNamespace XSI = "http://www.w3.org/2001/XMLSchema-instance";
public const string schema = nameof(schema);
public const string schemaLocation = nameof(schemaLocation);
public const string include = nameof(include);
public const string simpleType = nameof(simpleType);
public const string complexType = nameof(complexType);
public const string choice = nameof(choice);
public const string sequence = nameof(sequence);
public const string all = nameof(all);
public const string element = nameof(element);
public const string restriction = nameof(restriction);
public const string enumeration = nameof(enumeration);
public const string type = nameof(type);
public const string name = nameof(name);
public const string @base = nameof(@base);
public const string minOccurs = nameof(minOccurs);
public const string maxOccurs = nameof(maxOccurs);
public const string unbounded = nameof(unbounded);
public const string nil = nameof(nil);
public const string nillable = nameof(nillable);
public const string value = nameof(value);
public const string boolean = xs + ":" + nameof(boolean);
public const string @string = xs + ":" + nameof(@string);
public const string integer = xs + ":" + nameof(integer);
public const string dateTime = xs + ":" + nameof(dateTime);
public const string @decimal = xs + ":" + nameof(@decimal);
public const string any = xs + ":" + nameof(any);
public const string xs = nameof(xs);
public const string xsi = nameof(xsi);
}
}
| 44.862745 | 104 | 0.645105 | [
"MIT"
] | joost-morsink/Rest | Biz.Morsink.Rest.HttpConverter.Xml/XsdConstants.cs | 2,290 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
namespace TSE.App
{
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
}
}
| 25.727273 | 70 | 0.70318 | [
"MIT"
] | AdrianAVA9/TSE-Search | TSE.App/Global.asax.cs | 568 | C# |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//
using System;
public class AA
{
static Array[,] m_ax;
static bool m_bFlag;
static void Static3(int param1)
{
if (m_bFlag)
Main();
else
m_ax[param1, param1] = null;
}
static int Main()
{
try
{
Static3(0);
return 101;
}
catch (NullReferenceException)
{
return 100;
}
}
}
| 17.666667 | 101 | 0.523156 | [
"MIT"
] | CyberSys/coreclr-mono | tests/src/JIT/Regression/CLR-x86-JIT/V1-M13-RTM/b89946/b89946.cs | 583 | C# |
using CmlLib.Core.Files;
using System.Linq;
namespace CmlLib.Core.Version
{
public class MVersion
{
public MVersion(string id)
{
this.Id = id;
}
public bool IsInherited { get; set; }
public string? ParentVersionId { get; set; }
public string Id { get; set; }
public string? AssetId { get; set; }
public string? AssetUrl { get; set; }
public string? AssetHash { get; set; }
public string? JavaVersion { get; set; }
public string? JavaBinaryPath { get; set; }
public string? Jar { get; set; }
public string? ClientDownloadUrl { get; set; }
public string? ClientHash { get; set; }
public MLibrary[]? Libraries { get; set; }
public string? MainClass { get; set; }
public string? MinecraftArguments { get; set; }
public string[]? GameArguments { get; set; }
public string[]? JvmArguments { get; set; }
public string? ReleaseTime { get; set; }
public MVersionType Type { get; set; } = MVersionType.Custom;
public string? TypeStr { get; set; }
public void InheritFrom(MVersion parentVersion)
{
/*
Overload :
AssetId, AssetUrl, AssetHash, ClientDownloadUrl,
ClientHash, MainClass, MinecraftArguments, JavaVersion
Combine :
Libraries, GameArguments, JvmArguments
*/
// Overloads
if (nc(AssetId))
AssetId = parentVersion.AssetId;
if (nc(AssetUrl))
AssetUrl = parentVersion.AssetUrl;
if (nc(AssetHash))
AssetHash = parentVersion.AssetHash;
if (nc(ClientDownloadUrl))
ClientDownloadUrl = parentVersion.ClientDownloadUrl;
if (nc(ClientHash))
ClientHash = parentVersion.ClientHash;
if (nc(MainClass))
MainClass = parentVersion.MainClass;
if (nc(MinecraftArguments))
MinecraftArguments = parentVersion.MinecraftArguments;
if (nc(JavaVersion))
JavaVersion = parentVersion.JavaVersion;
Jar = parentVersion.Jar;
// Combine
if (parentVersion.Libraries != null)
{
if (Libraries != null)
Libraries = Libraries.Concat(parentVersion.Libraries).ToArray();
else
Libraries = parentVersion.Libraries;
}
if (parentVersion.GameArguments != null)
{
if (GameArguments != null)
GameArguments = GameArguments.Concat(parentVersion.GameArguments).ToArray();
else
GameArguments = parentVersion.GameArguments;
}
if (parentVersion.JvmArguments != null)
{
if (JvmArguments != null)
JvmArguments = JvmArguments.Concat(parentVersion.JvmArguments).ToArray();
else
JvmArguments = parentVersion.JvmArguments;
}
}
private static bool nc(string? t) // check null string
{
return string.IsNullOrEmpty(t);
}
public override string ToString()
{
return this.Id;
}
}
}
| 30.495575 | 96 | 0.531921 | [
"MIT"
] | MehmetErbicakci/CmlLib.Core | CmlLib/Core/Version/MVersion.cs | 3,448 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace Microsoft.IIS.Administration.WebServer.UrlRewrite
{
using System;
using Web.Administration;
class RuleCollectionBase : ConfigurationElementCollectionBase<RuleElement> {
public RuleElement Add(string name) {
RuleElement element = this.CreateElement();
element.Name = name;
return base.Add(element);
}
public new RuleElement this[string name] {
get {
for (int i = 0; (i < this.Count); i = (i + 1)) {
RuleElement element = base[i];
if ((string.Equals(element.Name, name, StringComparison.OrdinalIgnoreCase) == true)) {
return element;
}
}
return null;
}
}
public new int IndexOf(RuleElement rule)
{
int index = -1;
for (int i = 0; i < Count; i++) {
if (this[i].Name.Equals(rule.Name, StringComparison.OrdinalIgnoreCase)) {
index = i;
break;
}
}
return index;
}
public virtual void Move(RuleElement rule, int index)
{
if (index < 0 || index >= this.Count) {
throw new IndexOutOfRangeException();
}
int currentIndex = IndexOf(rule);
if (currentIndex == -1) {
throw new ArgumentException(nameof(rule));
}
//
// Make sure rule comes from this collection instance
RuleElement r = this[currentIndex];
this.RemoveAt(currentIndex);
this.AddCopyAt(index, r);
}
protected virtual void CopyInfo(RuleElement source, RuleElement destination) {
source.Action.CopyTo(destination.Action);
source.Conditions.CopyTo(destination.Conditions);
source.Match.CopyTo(destination.Match);
ConfigurationHelper.CopyAttributes(source, destination);
ConfigurationHelper.CopyMetadata(source, destination);
}
private RuleElement AddCopyAt(int index, RuleElement rule)
{
RuleElement element = CreateElement();
CopyInfo(rule, element);
return AddAt(index, element);
}
}
static class ConfigurationHelper {
public static void CopyAttributes(ConfigurationElement source, ConfigurationElement destination) {
foreach (ConfigurationAttribute attribute in source.Attributes) {
if (!attribute.IsInheritedFromDefaultValue) {
destination[attribute.Name] = attribute.Value;
}
}
}
public static void CopyMetadata(ConfigurationElement source, ConfigurationElement destination) {
object o = source.GetMetadata("lockItem");
if (o != null) {
destination.SetMetadata("lockItem", o);
}
o = source.GetMetadata("lockAttributes");
if (o != null) {
destination.SetMetadata("lockAttributes", o);
}
o = source.GetMetadata("lockElements");
if (o != null) {
destination.SetMetadata("lockElements", o);
}
o = source.GetMetadata("lockAllAttributesExcept");
if (o != null) {
destination.SetMetadata("lockAllAttributesExcept", o);
}
o = source.GetMetadata("lockAllElementsExcept");
if (o != null) {
destination.SetMetadata("lockAllElementsExcept", o);
}
}
}
}
| 30.936 | 106 | 0.546677 | [
"MIT"
] | 202006233011/IIS.Administration | src/Microsoft.IIS.Administration.WebServer.UrlRewrite/Configuration/Rule/RuleCollection.cs | 3,867 | C# |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
using System;
using System.Collections.Generic;
using Aliyun.Acs.Core.Transform;
using Aliyun.Acs.dataworks_public.Model.V20200518;
namespace Aliyun.Acs.dataworks_public.Transform.V20200518
{
public class CreateDagComplementResponseUnmarshaller
{
public static CreateDagComplementResponse Unmarshall(UnmarshallerContext context)
{
CreateDagComplementResponse createDagComplementResponse = new CreateDagComplementResponse();
createDagComplementResponse.HttpResponse = context.HttpResponse;
createDagComplementResponse.ErrorCode = context.StringValue("CreateDagComplement.ErrorCode");
createDagComplementResponse.ErrorMessage = context.StringValue("CreateDagComplement.ErrorMessage");
createDagComplementResponse.HttpStatusCode = context.IntegerValue("CreateDagComplement.HttpStatusCode");
createDagComplementResponse.RequestId = context.StringValue("CreateDagComplement.RequestId");
createDagComplementResponse.Success = context.BooleanValue("CreateDagComplement.Success");
List<string> createDagComplementResponse_data = new List<string>();
for (int i = 0; i < context.Length("CreateDagComplement.Data.Length"); i++) {
createDagComplementResponse_data.Add(context.StringValue("CreateDagComplement.Data["+ i +"]"));
}
createDagComplementResponse.Data = createDagComplementResponse_data;
return createDagComplementResponse;
}
}
}
| 44.82 | 108 | 0.776885 | [
"Apache-2.0"
] | chys0404/aliyun-openapi-net-sdk | aliyun-net-sdk-dataworks-public/Dataworks_public/Transform/V20200518/CreateDagComplementResponseUnmarshaller.cs | 2,241 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Xamarin.Forms;
namespace PxlItFactorApp
{
public partial class App : Application
{
public App ()
{
InitializeComponent();
MainPage = new PxlItFactorApp.Views.ConnectionSettingsPage();
}
protected override void OnStart ()
{
// Handle when your app starts
}
protected override void OnSleep ()
{
// Handle when your app sleeps
}
protected override void OnResume ()
{
// Handle when your app resumes
}
}
}
| 15.514286 | 64 | 0.694291 | [
"MIT"
] | krishermans/pxlitfactor | PxlItFactorApp/PxlItFactorApp/App.xaml.cs | 545 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using Microsoft.Xna.Framework;
using Quaver.API.Replays;
using Quaver.Shared.Config;
using Quaver.Shared.Database.Maps;
using Quaver.Shared.Database.Scores;
using Quaver.Shared.Graphics;
using Quaver.Shared.Graphics.Form.Dropdowns.RightClick;
using Quaver.Shared.Graphics.Notifications;
using Quaver.Shared.Helpers;
using Quaver.Shared.Online;
using Quaver.Shared.Scheduling;
using Quaver.Shared.Screens.Gameplay;
using Quaver.Shared.Screens.Loading;
using Quaver.Shared.Screens.Result;
using Quaver.Shared.Screens.Selection.UI.Leaderboard.Dialogs;
using Wobble;
using Wobble.Graphics;
using Wobble.Graphics.UI.Dialogs;
using Wobble.Platform;
using Wobble.Platform.Linux;
namespace Quaver.Shared.Screens.Selection.UI.Leaderboard.Components
{
public class LeaderboardScoreRightClickOptions : RightClickOptions
{
/// <summary>
/// </summary>
private Score Score { get; }
private const string ViewResults = "View Results";
private const string WatchReplay = "Watch Replay";
private const string DownloadReplay = "Download Replay";
private const string ExportReplay = "Export Replay";
private const string PlayerProfile = "Player Profile";
private const string Delete = "Delete";
/// <summary>
/// </summary>
public LeaderboardScoreRightClickOptions(Score score) : base(GetOptions(score), new ScalableVector2(200, 40), 22)
{
Score = score;
ItemSelected += (sender, args) =>
{
var game = (QuaverGame) GameBase.Game;
var replayPath = $"{ConfigManager.DataDirectory.Value}/r/{Score.Id}.qr";
switch (args.Text)
{
case ViewResults:
game.CurrentScreen.Exit(() => new ResultScreen(Score));
break;
case WatchReplay:
// Download Online Replay
if (Score.IsOnline)
{
var dialog = new LoadingDialog("Downloading Replay",
"Fetching online replay! Please wait...", () =>
{
var replay = Score.DownloadOnlineReplay();
if (replay == null)
{
NotificationManager.Show(NotificationLevel.Error, "The replay you have tried to download failed. It may be unavailable.");
return;
}
game.CurrentScreen.Exit(() => new MapLoadingScreen(new List<Score>(), replay));
});
DialogManager.Show(dialog);
return;
}
if (!File.Exists(replayPath))
{
NotificationManager.Show(NotificationLevel.Error, "The replay file could not be found!");
return;
}
game.CurrentScreen.Exit(() => new MapLoadingScreen(new List<Score>(), new Replay(replayPath)));
break;
case DownloadReplay:
if (!Score.IsOnline)
return;
// Download Online Replay
if (Score.IsOnline)
{
var dialog = new LoadingDialog("Downloading Replay",
"Fetching online replay! Please wait...", () =>
{
var replay = Score.DownloadOnlineReplay(false);
if (replay == null)
{
NotificationManager.Show(NotificationLevel.Error, "The replay you have tried to download failed. It may be unavailable.");
return;
}
var dir = $"{ConfigManager.DataDirectory}/Downloads";
var downloadPath = $"{dir}/{Score.Id}.qr";
Utils.NativeUtils.HighlightInFileManager(downloadPath);
});
DialogManager.Show(dialog);
return;
}
break;
case ExportReplay:
var path = $"{ConfigManager.DataDirectory.Value}/r/{Score.Id}.qr";
if (!File.Exists(path))
{
NotificationManager.Show(NotificationLevel.Error, "The replay file could not be found!");
return;
}
Utils.NativeUtils.HighlightInFileManager(path);
break;
case Delete:
DialogManager.Show(new DeleteScoreDialog(Score));
break;
case PlayerProfile:
BrowserHelper.OpenURL($"https://quavergame.com/profile/{Score.Name}");
break;
}
};
}
/// <summary>
/// </summary>
/// <param name="score"></param>
/// <returns></returns>
private static Dictionary<string, Color> GetOptions(Score score)
{
var options = new Dictionary<string, Color>();
if (OnlineManager.CurrentGame == null)
{
options.Add(ViewResults, Color.White);
options.Add(WatchReplay, ColorHelper.HexToColor("#9B51E0"));
}
if (score.IsOnline)
{
options.Add(DownloadReplay, ColorHelper.HexToColor("#0FBAE5"));
options.Add(PlayerProfile, ColorHelper.HexToColor("#27B06E"));
return options;
}
options.Add(ExportReplay, ColorHelper.HexToColor("#0787E3"));
options.Add(Delete, ColorHelper.HexToColor($"#FF6868"));
return options;
}
}
} | 38.730539 | 162 | 0.48222 | [
"MPL-2.0",
"MPL-2.0-no-copyleft-exception"
] | IceDynamix/Quaver | Quaver.Shared/Screens/Selection/UI/Leaderboard/Components/LeaderboardScoreRightClickOptions.cs | 6,468 | C# |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Security;
using System.Text;
namespace System.IO
{
public sealed partial class DriveInfo
{
public static unsafe DriveInfo[] GetDrives()
{
const int StringBufferLength = 8192; // there's no defined max size nor an indication through the API when you supply too small a buffer; choosing something that seems reasonable
byte* strBuf = stackalloc byte[StringBufferLength];
// Parse the mounts file
const string MountsPath = "/proc/mounts"; // Linux mounts file
IntPtr fp;
Interop.CheckIoPtr(fp = Interop.libc.setmntent(MountsPath, Interop.libc.MNTOPT_RO), path: MountsPath);
try
{
// Walk the entries in the mounts file, creating a DriveInfo for each that shouldn't be ignored.
List<DriveInfo> drives = new List<DriveInfo>();
Interop.libc.mntent mntent = default(Interop.libc.mntent);
while (Interop.libc.getmntent_r(fp, ref mntent, strBuf, StringBufferLength) != IntPtr.Zero)
{
string type = DecodeString(mntent.mnt_type);
if (!string.IsNullOrWhiteSpace(type) && type != Interop.libc.MNTTYPE_IGNORE)
{
string name = DecodeString(mntent.mnt_dir);
drives.Add(new DriveInfo(name));
}
}
return drives.ToArray();
}
finally
{
int result = Interop.libc.endmntent(fp);
Debug.Assert(result == 1); // documented to always return 1
}
}
// -----------------------------
// ---- PAL layer ends here ----
// -----------------------------
/// <summary>Gets the string starting at the specifying pointer and going until null termination.</summary>
/// <param name="str">Pointer to the first byte in the string.</param>
/// <returns>The decoded string.</returns>
private static unsafe string DecodeString(byte* str)
{
return str != null ? Marshal.PtrToStringAnsi((IntPtr)str) : null;
}
}
}
| 41.45 | 190 | 0.575794 | [
"MIT"
] | bpschoch/corefx | src/System.IO.FileSystem.DriveInfo/src/System/IO/DriveInfo.Linux.cs | 2,487 | C# |
using Microsoft.AspNetCore.Blazor.Hosting;
using System.Threading.Tasks;
namespace ComponentTen
{
public class Program
{
public static async Task Main(string[] args)
{
var builder = WebAssemblyHostBuilder.CreateDefault(args);
builder.RootComponents.Add<App>("app");
await builder.Build().RunAsync();
}
}
}
| 23.75 | 69 | 0.631579 | [
"MIT"
] | KeyboardMonkey221/practical-aspnetcore | projects/blazor/ComponentTen/Program.cs | 382 | C# |
// Copyright (c) 2015-present, Parse, LLC. All rights reserved. This source code is licensed under the BSD-style license found in the LICENSE file in the root directory of this source tree. An additional grant of patent rights can be found in the PATENTS file in the same directory.
using Parse.Internal;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using Android.Content;
using Android.App;
namespace Parse {
public partial class ParsePush {
/// <summary>
/// Attach this method to <see cref="ParsePush.ParsePushNotificationReceived"/> to utilize a
/// default handler for push notification.
/// </summary>
/// <remarks>
/// This handler will try to get the launcher <see cref="Activity"/> and application icon, then construct a
/// <see cref="Notification"/> out of them. It uses push payload's <c>title</c> and <c>alert</c> as the
/// <see cref="Notification.ContentView"/> title and text.
/// </remarks>
/// <param name="sender"></param>
/// <param name="args"></param>
public static void DefaultParsePushNotificationReceivedHandler(object sender, ParsePushNotificationEventArgs args) {
IDictionary<string, object> pushData = args.Payload;
Context context = Application.Context;
if (pushData == null || (!pushData.ContainsKey("alert") && !pushData.ContainsKey("title"))) {
return;
}
string title = pushData.ContainsKey("title") ? pushData["title"] as string : ManifestInfo.DisplayName;
string alert = pushData.ContainsKey("alert") ? pushData["alert"] as string : "Notification received.";
string tickerText = title + ": " + alert;
Random random = new Random();
int contentIntentRequestCode = random.Next();
Intent activityIntent = ManifestInfo.LauncherIntent;
PendingIntent pContentIntent = PendingIntent.GetActivity(context, contentIntentRequestCode, activityIntent, PendingIntentFlags.UpdateCurrent);
NotificationCompat.Builder builder = new NotificationCompat.Builder(context)
.SetContentTitle(new Java.Lang.String(title))
.SetContentText(new Java.Lang.String(alert))
.SetTicker(new Java.Lang.String(tickerText))
.SetSmallIcon(ManifestInfo.PushIconId)
.SetContentIntent(pContentIntent)
.SetAutoCancel(true)
.SetDefaults(NotificationDefaults.All);
Notification notification = builder.Build();
NotificationManager manager = context.GetSystemService(Context.NotificationService) as NotificationManager;
int notificationId = (int)DateTime.UtcNow.Ticks;
try {
manager.Notify(notificationId, notification);
} catch (Exception) {
// Some phones throw exception for unapproved vibration.
notification.Defaults = NotificationDefaults.Lights | NotificationDefaults.Sound;
manager.Notify(notificationId, notification);
}
}
/// <summary>
/// Helper method to extract the full Push JSON provided to Parse, including any
/// non-visual custom information.
/// </summary>
/// <param name="intent"><see cref="Android.Content.Intent"/> received typically
/// from a <see cref="Android.Content.BroadcastReceiver"/></param>
/// <returns>Returns the push payload in the intent. Returns an empty dictionary if the intent
/// doesn't contain push payload.</returns>
internal static IDictionary<string, object> PushJson(Intent intent) {
IDictionary<string, object> result = new Dictionary<string, object>();
string messageType = intent.GetStringExtra("message_type");
if (messageType != null) {
// The GCM docs reserve the right to use the message_type field for new actions, but haven't
// documented what those new actions are yet. For forwards compatibility, ignore anything
// with a message_type field.
} else {
string pushDataString = intent.GetStringExtra("data");
IDictionary<string, object> pushData = null;
// We encode the data payload as JSON string. Deserialize that string now.
if (pushDataString != null) {
pushData = ParseClient.DeserializeJsonString(pushDataString);
}
if (pushData != null) {
result = pushData;
}
}
return result;
}
}
}
| 43.83 | 285 | 0.692448 | [
"BSD-3-Clause"
] | Julien-Mialon/Parse-SDK-dotNET | Parse/Public/Android/ParsePush.Android.cs | 4,383 | C# |
using System;
namespace Certes.Acme
{
/// <summary>
/// The ACME challenge types.
/// </summary>
public static class ChallengeTypes
{
/// <summary>
/// The HTTP challenge. version 1.
/// </summary>
public const string Http01 = "http-01";
/// <summary>
/// The DNS challenge. version 1.
/// </summary>
public const string Dns01 = "dns-01";
/// <summary>
/// The TLS with Server Name Indication challenge. version 2.
/// </summary>
public const string TlsSni02 = "tls-sni-02";
/// <summary>
/// The TLS with Server Name Indication challenge. version 1.
/// </summary>
[Obsolete]
public const string TlsSni01 = "tls-sni-01";
}
}
| 24.71875 | 69 | 0.534766 | [
"MIT"
] | muffadalis/rrod | lib/Certes/Acme/ChallengeTypes.cs | 793 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using LentoCore.Atoms;
using LentoCore.Atoms.Types;
using LentoCore.Evaluator;
using LentoCore.Exception;
using LentoCore.Util;
namespace LentoCore.Expressions
{
public class VariableDeclaration : Expression
{
private readonly string _name;
private readonly Expression _value;
public VariableDeclaration(LineColumnSpan span, string name, Expression value) : base(span)
{
_name = name;
_value = value;
}
public override Atomic Evaluate(Scope scope)
{
if (scope.Contains(_name)) throw new RuntimeErrorException(ErrorHandler.EvaluateError(Span.Start, $"A local variable or function named '{_name}' is already defined in this scope"));
Atomic value = scope.Set(_name, _value.Evaluate(scope));
scope.TypeTable.Set(_name, value.Type);
return value;
}
public override AtomicType GetReturnType(TypeTable table)
{
AtomicType returnType = _value.GetReturnType(table);
table.Set(_name, returnType);
return returnType;
}
public override string ToString(string indent) => $"Variable declaration: {_name.ToString()} = {_value.ToString(indent)}";
}
}
| 33.463415 | 193 | 0.668367 | [
"MIT"
] | Lento-lang/Lento | LentoCore/Expressions/VariableDeclaration.cs | 1,374 | C# |
using System;
using System.Globalization;
class HolidaysBetweenTwoDates
{
static void Main()
{
DateTime startDate = DateTime.ParseExact(Console.ReadLine(), "d.M.yyyy", CultureInfo.InvariantCulture);
DateTime endDate = DateTime.ParseExact(Console.ReadLine(), "d.M.yyyy", CultureInfo.InvariantCulture);
int holidaysCount = 0;
for (DateTime date = startDate; date <= endDate; date = date.AddDays(1))
{
if (date.DayOfWeek == DayOfWeek.Saturday || date.DayOfWeek == DayOfWeek.Sunday)
{
holidaysCount++;
}
}
Console.WriteLine(holidaysCount);
}
}
| 28.869565 | 111 | 0.618976 | [
"MIT"
] | stanislavstoyanov99/SoftUni-Software-Engineering | Technology-Fundamentals-with-C#/Labs-And-Homeworks/BasicSyntaxConditionalStatementsLoops/HolidaysBetweenTwoDates/Program.cs | 666 | C# |
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ComputerComplectorWebAPI.Models.Requests.Get
{
public class GetVideocardsRequest
{
public string[] Company { get; set; }
public string[] Series { get; set; }
public string[] Proccessor { get; set; }
public string[] VRAM { get; set; }
public int[] Capacity { get; set; }
public string[] Connector { get; set; }
public string[] Family { get; set; }
public int? SelectedBody { get; private set; }
public int? SelectedCharger { get; private set; }
public string Expression { get; } = "SELECT * FROM VIDEOCARD v JOIN VIDEOCARD_CONNECTOR vc on v.ID = vc.VideocardID";
public List<SqlParameter> Parameters { get; } = new List<SqlParameter>();
public GetVideocardsRequest(string[] company, string[] series, string[] proccessor, string[] vRAM, int[] capacity,
string[] connector, string[] family, int? selectedCharger, int? selectedBody)
{
List<string> cond = new List<string>();
Company = company;
if (Company != null)
{
List<string> con = new List<string>();
for (int i = 0; i < Company.Length; i++)
{
con.Add($"Company=@company{i}");
Parameters.Add(new SqlParameter($"@company{i}", Company[i]));
}
cond.Add(string.Join(" OR ", con));
}
Series = series;
if (Series != null)
{
List<string> con = new List<string>();
for (int i = 0; i < Series.Length; i++)
{
con.Add($"Series=@series{i}");
Parameters.Add(new SqlParameter($"@series{i}", Series[i]));
}
cond.Add(string.Join(" OR ", con));
}
Proccessor = proccessor;
if (Proccessor != null)
{
List<string> con = new List<string>();
for (int i = 0; i < Proccessor.Length; i++)
{
con.Add($"GraphicalProccessor=@proccessor{i}");
Parameters.Add(new SqlParameter($"@proccessor{i}", Proccessor[i]));
}
cond.Add(string.Join(" OR ", con));
}
VRAM = vRAM;
if (VRAM != null)
{
List<string> con = new List<string>();
for (int i = 0; i < VRAM.Length; i++)
{
con.Add($"VRAM=@vRAM{i}");
Parameters.Add(new SqlParameter($"@vRAM{i}", VRAM[i]));
}
cond.Add(string.Join(" OR ", con));
}
Capacity = capacity;
if (Capacity != null)
{
List<string> con = new List<string>();
for (int i = 0; i < Capacity.Length; i++)
{
con.Add($"Capacity=@capacity{i}");
Parameters.Add(new SqlParameter($"@capacity{i}", Capacity[i]));
}
cond.Add(string.Join(" OR ", con));
}
Connector = connector;
if (Connector != null)
{
List<string> con = new List<string>();
for (int i = 0; i < Connector.Length; i++)
{
con.Add($"ID IN (SELECT DISTINCT VideocardID FROM VIDEOCARD_CONNECTOR WHERE Connector = @connector{i})");
Parameters.Add(new SqlParameter($"@connector{i}", Connector[i]));
}
cond.Add(string.Join(" OR ", con));
}
Family = family;
if (Family != null)
{
List<string> con = new List<string>();
for (int i = 0; i < Family.Length; i++)
{
con.Add($"Family=@family{i}");
Parameters.Add(new SqlParameter($"@family{i}", Family[i]));
}
cond.Add(string.Join(" OR ", con));
}
SelectedCharger = selectedCharger;
if (SelectedCharger != null)
{
cond.Add("Pin = (SELECT TOP 1 VideocardConnector FROM CHARGER WHERE ID = @cID)");
Parameters.Add(new SqlParameter("@cID", SelectedCharger));
}
SelectedBody = selectedBody;
if (SelectedBody != null)
{
cond.Add("Length <= (SELECT TOP 1 VideocardMaxLength FROM BODY WHERE ID = @bID)");
Parameters.Add(new SqlParameter("@bID", SelectedBody));
}
if (cond.Count > 0)
{
Expression += $" WHERE {string.Join(" AND ", cond)}";
}
}
}
}
| 36.948529 | 125 | 0.461692 | [
"MIT"
] | Stranger-In-The-Darkness/Computer-Complector-Web-API | Models/Requests/Get/GetVideocardsRequest.cs | 5,027 | C# |
using System.Collections.Generic;
namespace MyTool.KeyValue
{
public class KeyValueList
{
public KeyValueList(string type, string txt)
{
list = new List<KeyValue>();
if (type == "json1")
{
string[] list1 = txt.Split(';');
for (int i = 0; i < list1.Length; i++)
{
if (list1[i] != "")
{
string[] list2 = list1[i].Split(',');
if (list2.Length == 2)
{
list.Add(new KeyValue(list2[0], list2[1]));
}
}
}
}
if (type == "json2")
{
string[] list1 = txt.Split('&');
for (int i = 0; i < list1.Length; i++)
{
if (list1[i] != "")
{
string[] list2 = list1[i].Split('=');
if (list2.Length == 2)
{
list.Add(new KeyValue(list2[0], list2[1]));
}
}
}
}
fun = GetValue("fun");
id = GetValue("id");
}
/// <summary>
///
/// </summary>
/// <param name="key"></param>
/// <returns>如果找不到对应值,则返回值为""</returns>
public string GetValue(string key)
{
if (list != null && list.Count > 0)
{
KeyValue obj = list.Find(p => p.key.ToLower() == key.ToLower());
if (obj != null)
{
return obj.value;
}
}
return "";
}
public string GetValue(string key, string rep)
{
key = rep.Replace("{0}", key);
if (list != null && list.Count > 0)
{
KeyValue obj = list.Find(p => p.key.ToLower() == key.ToLower());
if (obj != null)
{
return obj.value;
}
}
return "";
}
public void SetValue(string key, string value)
{
if (list != null && list.Count > 0)
{
KeyValue obj = list.Find(p => p.key.ToLower() == key.ToLower());
if (obj != null)
{
obj.value = value;
}
}
}
public void Add(KeyValue it)
{
string key = it.key;
if (list != null && list.Count > 0)
{
KeyValue obj = list.Find(p => p.key == key);
if (obj != null)
{
SetValue(key, it.value);
return;
}
}
this.list.Add(it);
}
public void Delete(KeyValue it)
{
this.list.Remove(it);
}
public List<KeyValue> list = new List<KeyValue>();
public string fun = "";
public string id = "";
}
}
| 27.282051 | 80 | 0.340852 | [
"Apache-2.0"
] | nnugaoz/HLAQSC | MyTool/KeyValue/KeyValueList.cs | 3,222 | C# |
// This file contains auto-generated code.
namespace Microsoft
{
namespace AspNetCore
{
namespace Hosting
{
// Generated from `Microsoft.AspNetCore.Hosting.DelegateStartup` in `Microsoft.AspNetCore.Hosting, Version=5.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60`
public class DelegateStartup : Microsoft.AspNetCore.Hosting.StartupBase<Microsoft.Extensions.DependencyInjection.IServiceCollection>
{
public override void Configure(Microsoft.AspNetCore.Builder.IApplicationBuilder app) => throw null;
public DelegateStartup(Microsoft.Extensions.DependencyInjection.IServiceProviderFactory<Microsoft.Extensions.DependencyInjection.IServiceCollection> factory, System.Action<Microsoft.AspNetCore.Builder.IApplicationBuilder> configureApp) : base(default(Microsoft.Extensions.DependencyInjection.IServiceProviderFactory<Microsoft.Extensions.DependencyInjection.IServiceCollection>)) => throw null;
}
// Generated from `Microsoft.AspNetCore.Hosting.HostingEnvironmentExtensions` in `Microsoft.AspNetCore.Hosting, Version=5.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60; Microsoft.AspNetCore.Hosting.Abstractions, Version=5.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60`
public static partial class HostingEnvironmentExtensions
{
}
// Generated from `Microsoft.AspNetCore.Hosting.StartupBase` in `Microsoft.AspNetCore.Hosting, Version=5.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60`
public abstract class StartupBase : Microsoft.AspNetCore.Hosting.IStartup
{
public abstract void Configure(Microsoft.AspNetCore.Builder.IApplicationBuilder app);
public virtual void ConfigureServices(Microsoft.Extensions.DependencyInjection.IServiceCollection services) => throw null;
System.IServiceProvider Microsoft.AspNetCore.Hosting.IStartup.ConfigureServices(Microsoft.Extensions.DependencyInjection.IServiceCollection services) => throw null;
public virtual System.IServiceProvider CreateServiceProvider(Microsoft.Extensions.DependencyInjection.IServiceCollection services) => throw null;
protected StartupBase() => throw null;
}
// Generated from `Microsoft.AspNetCore.Hosting.StartupBase<>` in `Microsoft.AspNetCore.Hosting, Version=5.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60`
public abstract class StartupBase<TBuilder> : Microsoft.AspNetCore.Hosting.StartupBase
{
public virtual void ConfigureContainer(TBuilder builder) => throw null;
public override System.IServiceProvider CreateServiceProvider(Microsoft.Extensions.DependencyInjection.IServiceCollection services) => throw null;
public StartupBase(Microsoft.Extensions.DependencyInjection.IServiceProviderFactory<TBuilder> factory) => throw null;
}
// Generated from `Microsoft.AspNetCore.Hosting.WebHostBuilder` in `Microsoft.AspNetCore.Hosting, Version=5.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60`
public class WebHostBuilder : Microsoft.AspNetCore.Hosting.IWebHostBuilder
{
public Microsoft.AspNetCore.Hosting.IWebHost Build() => throw null;
public Microsoft.AspNetCore.Hosting.IWebHostBuilder ConfigureAppConfiguration(System.Action<Microsoft.AspNetCore.Hosting.WebHostBuilderContext, Microsoft.Extensions.Configuration.IConfigurationBuilder> configureDelegate) => throw null;
public Microsoft.AspNetCore.Hosting.IWebHostBuilder ConfigureServices(System.Action<Microsoft.Extensions.DependencyInjection.IServiceCollection> configureServices) => throw null;
public Microsoft.AspNetCore.Hosting.IWebHostBuilder ConfigureServices(System.Action<Microsoft.AspNetCore.Hosting.WebHostBuilderContext, Microsoft.Extensions.DependencyInjection.IServiceCollection> configureServices) => throw null;
public string GetSetting(string key) => throw null;
public Microsoft.AspNetCore.Hosting.IWebHostBuilder UseSetting(string key, string value) => throw null;
public WebHostBuilder() => throw null;
}
// Generated from `Microsoft.AspNetCore.Hosting.WebHostBuilderExtensions` in `Microsoft.AspNetCore.Hosting, Version=5.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60`
public static class WebHostBuilderExtensions
{
public static Microsoft.AspNetCore.Hosting.IWebHostBuilder Configure(this Microsoft.AspNetCore.Hosting.IWebHostBuilder hostBuilder, System.Action<Microsoft.AspNetCore.Hosting.WebHostBuilderContext, Microsoft.AspNetCore.Builder.IApplicationBuilder> configureApp) => throw null;
public static Microsoft.AspNetCore.Hosting.IWebHostBuilder Configure(this Microsoft.AspNetCore.Hosting.IWebHostBuilder hostBuilder, System.Action<Microsoft.AspNetCore.Builder.IApplicationBuilder> configureApp) => throw null;
public static Microsoft.AspNetCore.Hosting.IWebHostBuilder ConfigureAppConfiguration(this Microsoft.AspNetCore.Hosting.IWebHostBuilder hostBuilder, System.Action<Microsoft.Extensions.Configuration.IConfigurationBuilder> configureDelegate) => throw null;
public static Microsoft.AspNetCore.Hosting.IWebHostBuilder ConfigureLogging(this Microsoft.AspNetCore.Hosting.IWebHostBuilder hostBuilder, System.Action<Microsoft.Extensions.Logging.ILoggingBuilder> configureLogging) => throw null;
public static Microsoft.AspNetCore.Hosting.IWebHostBuilder ConfigureLogging(this Microsoft.AspNetCore.Hosting.IWebHostBuilder hostBuilder, System.Action<Microsoft.AspNetCore.Hosting.WebHostBuilderContext, Microsoft.Extensions.Logging.ILoggingBuilder> configureLogging) => throw null;
public static Microsoft.AspNetCore.Hosting.IWebHostBuilder UseDefaultServiceProvider(this Microsoft.AspNetCore.Hosting.IWebHostBuilder hostBuilder, System.Action<Microsoft.Extensions.DependencyInjection.ServiceProviderOptions> configure) => throw null;
public static Microsoft.AspNetCore.Hosting.IWebHostBuilder UseDefaultServiceProvider(this Microsoft.AspNetCore.Hosting.IWebHostBuilder hostBuilder, System.Action<Microsoft.AspNetCore.Hosting.WebHostBuilderContext, Microsoft.Extensions.DependencyInjection.ServiceProviderOptions> configure) => throw null;
public static Microsoft.AspNetCore.Hosting.IWebHostBuilder UseStartup<TStartup>(this Microsoft.AspNetCore.Hosting.IWebHostBuilder hostBuilder, System.Func<Microsoft.AspNetCore.Hosting.WebHostBuilderContext, TStartup> startupFactory) where TStartup : class => throw null;
public static Microsoft.AspNetCore.Hosting.IWebHostBuilder UseStartup<TStartup>(this Microsoft.AspNetCore.Hosting.IWebHostBuilder hostBuilder) where TStartup : class => throw null;
public static Microsoft.AspNetCore.Hosting.IWebHostBuilder UseStartup(this Microsoft.AspNetCore.Hosting.IWebHostBuilder hostBuilder, System.Type startupType) => throw null;
public static Microsoft.AspNetCore.Hosting.IWebHostBuilder UseStaticWebAssets(this Microsoft.AspNetCore.Hosting.IWebHostBuilder builder) => throw null;
}
// Generated from `Microsoft.AspNetCore.Hosting.WebHostExtensions` in `Microsoft.AspNetCore.Hosting, Version=5.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60`
public static class WebHostExtensions
{
public static void Run(this Microsoft.AspNetCore.Hosting.IWebHost host) => throw null;
public static System.Threading.Tasks.Task RunAsync(this Microsoft.AspNetCore.Hosting.IWebHost host, System.Threading.CancellationToken token = default(System.Threading.CancellationToken)) => throw null;
public static System.Threading.Tasks.Task StopAsync(this Microsoft.AspNetCore.Hosting.IWebHost host, System.TimeSpan timeout) => throw null;
public static void WaitForShutdown(this Microsoft.AspNetCore.Hosting.IWebHost host) => throw null;
public static System.Threading.Tasks.Task WaitForShutdownAsync(this Microsoft.AspNetCore.Hosting.IWebHost host, System.Threading.CancellationToken token = default(System.Threading.CancellationToken)) => throw null;
}
namespace Builder
{
// Generated from `Microsoft.AspNetCore.Hosting.Builder.ApplicationBuilderFactory` in `Microsoft.AspNetCore.Hosting, Version=5.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60`
public class ApplicationBuilderFactory : Microsoft.AspNetCore.Hosting.Builder.IApplicationBuilderFactory
{
public ApplicationBuilderFactory(System.IServiceProvider serviceProvider) => throw null;
public Microsoft.AspNetCore.Builder.IApplicationBuilder CreateBuilder(Microsoft.AspNetCore.Http.Features.IFeatureCollection serverFeatures) => throw null;
}
// Generated from `Microsoft.AspNetCore.Hosting.Builder.IApplicationBuilderFactory` in `Microsoft.AspNetCore.Hosting, Version=5.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60`
public interface IApplicationBuilderFactory
{
Microsoft.AspNetCore.Builder.IApplicationBuilder CreateBuilder(Microsoft.AspNetCore.Http.Features.IFeatureCollection serverFeatures);
}
}
namespace Server
{
namespace Features
{
// Generated from `Microsoft.AspNetCore.Hosting.Server.Features.ServerAddressesFeature` in `Microsoft.AspNetCore.Hosting, Version=5.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60`
public class ServerAddressesFeature : Microsoft.AspNetCore.Hosting.Server.Features.IServerAddressesFeature
{
public System.Collections.Generic.ICollection<string> Addresses { get => throw null; }
public bool PreferHostingUrls { get => throw null; set => throw null; }
public ServerAddressesFeature() => throw null;
}
}
}
namespace StaticWebAssets
{
// Generated from `Microsoft.AspNetCore.Hosting.StaticWebAssets.StaticWebAssetsLoader` in `Microsoft.AspNetCore.Hosting, Version=5.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60`
public class StaticWebAssetsLoader
{
public StaticWebAssetsLoader() => throw null;
public static void UseStaticWebAssets(Microsoft.AspNetCore.Hosting.IWebHostEnvironment environment, Microsoft.Extensions.Configuration.IConfiguration configuration) => throw null;
}
}
}
namespace Http
{
// Generated from `Microsoft.AspNetCore.Http.DefaultHttpContextFactory` in `Microsoft.AspNetCore.Hosting, Version=5.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60`
public class DefaultHttpContextFactory : Microsoft.AspNetCore.Http.IHttpContextFactory
{
public Microsoft.AspNetCore.Http.HttpContext Create(Microsoft.AspNetCore.Http.Features.IFeatureCollection featureCollection) => throw null;
public DefaultHttpContextFactory(System.IServiceProvider serviceProvider) => throw null;
public void Dispose(Microsoft.AspNetCore.Http.HttpContext httpContext) => throw null;
}
}
}
namespace Extensions
{
namespace Hosting
{
// Generated from `Microsoft.Extensions.Hosting.GenericHostWebHostBuilderExtensions` in `Microsoft.AspNetCore.Hosting, Version=5.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60`
public static class GenericHostWebHostBuilderExtensions
{
public static Microsoft.Extensions.Hosting.IHostBuilder ConfigureWebHost(this Microsoft.Extensions.Hosting.IHostBuilder builder, System.Action<Microsoft.AspNetCore.Hosting.IWebHostBuilder> configure, System.Action<Microsoft.Extensions.Hosting.WebHostBuilderOptions> configureWebHostBuilder) => throw null;
public static Microsoft.Extensions.Hosting.IHostBuilder ConfigureWebHost(this Microsoft.Extensions.Hosting.IHostBuilder builder, System.Action<Microsoft.AspNetCore.Hosting.IWebHostBuilder> configure) => throw null;
}
// Generated from `Microsoft.Extensions.Hosting.WebHostBuilderOptions` in `Microsoft.AspNetCore.Hosting, Version=5.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60`
public class WebHostBuilderOptions
{
public bool SuppressEnvironmentConfiguration { get => throw null; set => throw null; }
public WebHostBuilderOptions() => throw null;
}
}
}
}
| 87 | 409 | 0.732663 | [
"MIT"
] | 01SMD/codeql | csharp/ql/test/resources/stubs/_frameworks/Microsoft.AspNetCore.App/Microsoft.AspNetCore.Hosting.cs | 13,137 | C# |
using UnityEngine;
using System.Collections;
using System;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
using UnityEngine.SocialPlatforms;
public class EstadoJuego : MonoBehaviour {
public int puntuacionMaxima = 0;
public static EstadoJuego estadoJuego;
private String rutaArchivo;
void Awake(){
rutaArchivo = Application.persistentDataPath + "/datos.dat";
if(estadoJuego==null){
estadoJuego = this;
DontDestroyOnLoad(gameObject);
}else if(estadoJuego!=this){
Destroy(gameObject);
Debug.Log("Soy el primero");
}
}
// Use this for initialization
void Start () {
Cargar();
}
// Update is called once per frame
void Update () {
}
public void Guardar(){
BinaryFormatter bf = new BinaryFormatter();
FileStream file = File.Create(rutaArchivo);
DatosAGuardar datos = new DatosAGuardar();
datos.puntuacionMaxima = puntuacionMaxima;
bf.Serialize(file, datos);
file.Close();
}
void Cargar(){
if(File.Exists(rutaArchivo)){
BinaryFormatter bf = new BinaryFormatter();
FileStream file = File.Open(rutaArchivo, FileMode.Open);
DatosAGuardar datos = (DatosAGuardar) bf.Deserialize(file);
puntuacionMaxima = datos.puntuacionMaxima;
file.Close();
}else{
puntuacionMaxima = 0;
}
}
}
[Serializable]
class DatosAGuardar{
public int puntuacionMaxima;
} | 20.132353 | 62 | 0.71439 | [
"MIT"
] | EnriqueLeal/VideojuegoUnity2 | Papi/PapiRun3.2/Papi/Papi/PapiRun/Assets/Scripts/EstadoJuego.cs | 1,371 | C# |
using System;
using System.IO;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
namespace NetCoreAPI
{
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.AddDbContext<AppContext>(opt => opt.UseInMemoryDatabase("AppDb"));
services.AddMvc();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, AppContext app_context)
{
/*
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
*/
SeedData.SeedDb(app_context);
app.Use(async (context, next) => {
await next();
if (context.Response.StatusCode == 404 &&
!Path.HasExtension(context.Request.Path.Value) &&
!context.Request.Path.Value.StartsWith("/api/"))
{
context.Request.Path = "/index.html";
await next();
}
});
//app.UseCors(options => options.WithOrigins("http://localhost:4200").AllowAnyHeader().AllowAnyMethod().AllowCredentials());
app.UseMvcWithDefaultRoute();
app.UseDefaultFiles();
app.UseStaticFiles();
}
}
}
| 31.05 | 136 | 0.589372 | [
"MIT"
] | emregocer/core_angular | Startup.cs | 1,865 | C# |
// Decompiled with JetBrains decompiler
// Type: CocoStudio.Core.Service.Runtime
// Assembly: CocoStudio.Core, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null
// MVID: 664CC19D-01B7-42F7-9640-243AA07066CE
// Assembly location: C:\Program Files (x86)\Cocos\Cocos Studio 2\CocoStudio.Core.dll
using CocoStudio.Basic;
using Mono.Addins;
using MonoDevelop.Core;
using MonoDevelop.Core.Assemblies;
using MonoDevelop.Core.Execution;
using MonoDevelop.Ide.Gui;
using System;
using System.Threading;
namespace CocoStudio.Core.Service
{
public static class Runtime
{
private static SystemAssemblyService systemAssemblyService;
private static bool initialized;
public static ProcessService ProcessService
{
get
{
return MonoDevelop.Core.Runtime.ProcessService;
}
}
public static void Initialize(string configDir, string addinsDir)
{
if (Runtime.initialized)
return;
Platform.Initialize();
if (SynchronizationContext.Current == null)
{
SynchronizationContext.SetSynchronizationContext((SynchronizationContext) new GtkSynchronizationContext());
MonoDevelop.Core.Runtime.MainSynchronizationContext = SynchronizationContext.Current;
}
AddinManager.AddinLoadError += new AddinErrorEventHandler(Runtime.OnLoadError);
AddinManager.AddinLoaded += new AddinEventHandler(Runtime.OnLoad);
AddinManager.AddinUnloaded += new AddinEventHandler(Runtime.OnUnload);
try
{
AddinManager.Initialize(configDir, addinsDir);
AddinManager.Registry.Update((IProgressStatus) null);
Runtime.systemAssemblyService = new SystemAssemblyService();
MonoDevelop.Core.Runtime.SystemAssemblyService = Runtime.systemAssemblyService;
Runtime.systemAssemblyService.Initialize();
}
catch (Exception ex)
{
LogConfig.Logger.Error((object) "RunTime initialize failed.", ex);
AddinManager.AddinLoadError -= new AddinErrorEventHandler(Runtime.OnLoadError);
AddinManager.AddinLoaded -= new AddinEventHandler(Runtime.OnLoad);
AddinManager.AddinUnloaded -= new AddinEventHandler(Runtime.OnUnload);
}
Runtime.initialized = true;
}
private static void OnLoadError(object s, AddinErrorEventArgs args)
{
LogConfig.Logger.Error((object) ("Add-in error (" + args.AddinId + "): " + args.Message), args.Exception);
}
private static void OnLoad(object s, AddinEventArgs args)
{
LogConfig.Logger.Info((object) ("Add-in loaded: " + args.AddinId));
}
private static void OnUnload(object s, AddinEventArgs args)
{
}
}
}
| 34.571429 | 115 | 0.718257 | [
"MIT"
] | gdbobu/CocoStudio2.0.6 | CocoStudio.Core/Service/Runtime.cs | 2,664 | C# |
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Content.Client.Actions;
using Content.Client.Actions.UI;
using Content.Client.UserInterface;
using Content.Server.Actions;
using Content.Server.Hands.Components;
using Content.Server.Items;
using Content.Shared.Actions;
using Content.Shared.Actions.Components;
using Content.Shared.Actions.Prototypes;
using Content.Shared.Cooldown;
using NUnit.Framework;
using Robust.Client.UserInterface;
using Robust.Shared.GameObjects;
using Robust.Shared.Map;
using Robust.Shared.Timing;
using Robust.Shared.Utility;
using IPlayerManager = Robust.Server.Player.IPlayerManager;
namespace Content.IntegrationTests.Tests.GameObjects.Components.Mobs
{
[TestFixture]
[TestOf(typeof(SharedActionsComponent))]
[TestOf(typeof(ClientActionsComponent))]
[TestOf(typeof(ServerActionsComponent))]
[TestOf(typeof(ItemActionsComponent))]
public class ActionsComponentTests : ContentIntegrationTest
{
const string Prototypes = @"
- type: entity
name: flashlight
parent: BaseItem
id: TestFlashlight
components:
- type: HandheldLight
- type: ItemActions
actions:
- actionType: ToggleLight
- type: PowerCellSlot
- type: Sprite
sprite: Objects/Tools/flashlight.rsi
layers:
- state: lantern_off
- state: HandheldLightOnOverlay
shader: unshaded
visible: false
- type: Item
sprite: Objects/Tools/flashlight.rsi
HeldPrefix: off
- type: PointLight
enabled: false
radius: 3
- type: LoopingSound
- type: Appearance
visuals:
- type: FlashLightVisualizer
";
[Test]
public async Task GrantsAndRevokesActionsTest()
{
var (client, server) = await StartConnectedServerClientPair();
await server.WaitIdleAsync();
await client.WaitIdleAsync();
var serverPlayerManager = server.ResolveDependency<IPlayerManager>();
var innateActions = new List<ActionType>();
await server.WaitAssertion(() =>
{
var player = serverPlayerManager.GetAllPlayers().Single();
var playerEnt = player.AttachedEntity;
var actionsComponent = playerEnt!.GetComponent<ServerActionsComponent>();
// player should begin with their innate actions granted
innateActions.AddRange(actionsComponent.InnateActions);
foreach (var innateAction in actionsComponent.InnateActions)
{
Assert.That(actionsComponent.TryGetActionState(innateAction, out var innateState));
Assert.That(innateState.Enabled);
}
Assert.That(innateActions.Count, Is.GreaterThan(0));
actionsComponent.Grant(ActionType.DebugInstant);
Assert.That(actionsComponent.TryGetActionState(ActionType.HumanScream, out var state) && state.Enabled);
});
// check that client has the actions
await server.WaitRunTicks(5);
await client.WaitRunTicks(5);
var clientPlayerMgr = client.ResolveDependency<Robust.Client.Player.IPlayerManager>();
var clientUIMgr = client.ResolveDependency<IUserInterfaceManager>();
var expectedOrder = new List<ActionType>();
await client.WaitAssertion(() =>
{
var local = clientPlayerMgr.LocalPlayer;
var controlled = local!.ControlledEntity;
var actionsComponent = controlled!.GetComponent<ClientActionsComponent>();
// we should have our innate actions and debug1.
foreach (var innateAction in innateActions)
{
Assert.That(actionsComponent.TryGetActionState(innateAction, out var innateState));
Assert.That(innateState.Enabled);
}
Assert.That(actionsComponent.TryGetActionState(ActionType.DebugInstant, out var state) && state.Enabled);
// innate actions should've auto-populated into our slots (in non-deterministic order),
// but debug1 should be in the last slot
var actionsUI =
clientUIMgr.StateRoot.Children.FirstOrDefault(c => c is ActionsUI) as ActionsUI;
Assert.That(actionsUI, Is.Not.Null);
var expectedInnate = new HashSet<ActionType>(innateActions);
var expectEmpty = false;
expectedOrder.Clear();
foreach (var slot in actionsUI.Slots)
{
if (expectEmpty)
{
Assert.That(slot.HasAssignment, Is.False);
Assert.That(slot.Item, Is.Null);
Assert.That(slot.Action, Is.Null);
Assert.That(slot.ActionEnabled, Is.False);
continue;
}
Assert.That(slot.HasAssignment);
// all the actions we gave so far are not tied to an item
Assert.That(slot.Item, Is.Null);
Assert.That(slot.Action, Is.Not.Null);
Assert.That(slot.ActionEnabled);
var asAction = slot.Action as ActionPrototype;
Assert.That(asAction, Is.Not.Null);
expectedOrder.Add(asAction.ActionType);
if (expectedInnate.Count != 0)
{
Assert.That(expectedInnate.Remove(asAction.ActionType));
}
else
{
Assert.That(asAction.ActionType, Is.EqualTo(ActionType.DebugInstant));
Assert.That(slot.Cooldown, Is.Null);
expectEmpty = true;
}
}
});
// now revoke the action and check that the client sees it as revoked
await server.WaitAssertion(() =>
{
var player = serverPlayerManager.GetAllPlayers().Single();
var playerEnt = player.AttachedEntity;
var actionsComponent = playerEnt!.GetComponent<ServerActionsComponent>();
actionsComponent.Revoke(ActionType.DebugInstant);
});
await server.WaitRunTicks(5);
await client.WaitRunTicks(5);
await client.WaitAssertion(() =>
{
var local = clientPlayerMgr.LocalPlayer;
var controlled = local!.ControlledEntity;
var actionsComponent = controlled!.GetComponent<ClientActionsComponent>();
// we should have our innate actions, but debug1 should be revoked
foreach (var innateAction in innateActions)
{
Assert.That(actionsComponent.TryGetActionState(innateAction, out var innateState));
Assert.That(innateState.Enabled);
}
Assert.That(actionsComponent.TryGetActionState(ActionType.DebugInstant, out _), Is.False);
// all actions should be in the same order as before, but the slot with DebugInstant should appear
// disabled.
var actionsUI =
clientUIMgr.StateRoot.Children.FirstOrDefault(c => c is ActionsUI) as ActionsUI;
Assert.That(actionsUI, Is.Not.Null);
var idx = 0;
foreach (var slot in actionsUI.Slots)
{
if (idx < expectedOrder.Count)
{
var expected = expectedOrder[idx++];
Assert.That(slot.HasAssignment);
// all the actions we gave so far are not tied to an item
Assert.That(slot.Item, Is.Null);
Assert.That(slot.Action, Is.Not.Null);
var asAction = slot.Action as ActionPrototype;
Assert.That(asAction, Is.Not.Null);
Assert.That(expected, Is.EqualTo(asAction.ActionType));
if (asAction.ActionType == ActionType.DebugInstant)
{
Assert.That(slot.ActionEnabled, Is.False);
}
else
{
Assert.That(slot.ActionEnabled);
}
}
else
{
Assert.That(slot.HasAssignment, Is.False);
Assert.That(slot.Item, Is.Null);
Assert.That(slot.Action, Is.Null);
Assert.That(slot.ActionEnabled, Is.False);
}
}
});
}
[Test]
public async Task GrantsAndRevokesItemActions()
{
var serverOptions = new ServerIntegrationOptions { ExtraPrototypes = Prototypes };
var clientOptions = new ClientIntegrationOptions { ExtraPrototypes = Prototypes };
var (client, server) = await StartConnectedServerClientPair(serverOptions: serverOptions, clientOptions: clientOptions);
await server.WaitIdleAsync();
await client.WaitIdleAsync();
var serverPlayerManager = server.ResolveDependency<IPlayerManager>();
var serverEntManager = server.ResolveDependency<IEntityManager>();
var serverGameTiming = server.ResolveDependency<IGameTiming>();
var cooldown = Cooldowns.SecondsFromNow(30, serverGameTiming);
ServerActionsComponent serverActionsComponent = null;
ClientActionsComponent clientActionsComponent = null;
IEntity serverPlayerEnt = null;
IEntity serverFlashlight = null;
await server.WaitAssertion(() =>
{
serverPlayerEnt = serverPlayerManager.GetAllPlayers().Single().AttachedEntity;
serverActionsComponent = serverPlayerEnt!.GetComponent<ServerActionsComponent>();
// spawn and give them an item that has actions
serverFlashlight = serverEntManager.SpawnEntity("TestFlashlight",
new EntityCoordinates(new EntityUid(1), (0, 0)));
Assert.That(serverFlashlight.TryGetComponent<ItemActionsComponent>(out var itemActions));
// we expect this only to have a toggle light action initially
var actionConfigs = itemActions.ActionConfigs.ToList();
Assert.That(actionConfigs.Count == 1);
Assert.That(actionConfigs[0].ActionType == ItemActionType.ToggleLight);
Assert.That(actionConfigs[0].Enabled);
// grant an extra item action, before pickup, initially disabled
itemActions.GrantOrUpdate(ItemActionType.DebugToggle, false);
serverPlayerEnt.GetComponent<HandsComponent>().PutInHand(serverFlashlight.GetComponent<ItemComponent>(), false);
// grant an extra item action, after pickup, with a cooldown
itemActions.GrantOrUpdate(ItemActionType.DebugInstant, cooldown: cooldown);
Assert.That(serverActionsComponent.TryGetItemActionStates(serverFlashlight.Uid, out var state));
// they should have been granted all 3 actions
Assert.That(state.Count == 3);
Assert.That(state.TryGetValue(ItemActionType.ToggleLight, out var toggleLightState));
Assert.That(toggleLightState.Equals(new ActionState(true)));
Assert.That(state.TryGetValue(ItemActionType.DebugInstant, out var debugInstantState));
Assert.That(debugInstantState.Equals(new ActionState(true, cooldown: cooldown)));
Assert.That(state.TryGetValue(ItemActionType.DebugToggle, out var debugToggleState));
Assert.That(debugToggleState.Equals(new ActionState(false)));
});
await server.WaitRunTicks(5);
await client.WaitRunTicks(5);
// check that client has the actions, and toggle the light on via the action slot it was auto-assigned to
var clientPlayerMgr = client.ResolveDependency<Robust.Client.Player.IPlayerManager>();
var clientUIMgr = client.ResolveDependency<IUserInterfaceManager>();
EntityUid clientFlashlight = default;
await client.WaitAssertion(() =>
{
var local = clientPlayerMgr.LocalPlayer;
var controlled = local!.ControlledEntity;
clientActionsComponent = controlled!.GetComponent<ClientActionsComponent>();
var lightEntry = clientActionsComponent.ItemActionStates()
.Where(entry => entry.Value.ContainsKey(ItemActionType.ToggleLight))
.FirstOrNull();
clientFlashlight = lightEntry!.Value.Key;
Assert.That(lightEntry, Is.Not.Null);
Assert.That(lightEntry.Value.Value.TryGetValue(ItemActionType.ToggleLight, out var lightState));
Assert.That(lightState.Equals(new ActionState(true)));
Assert.That(lightEntry.Value.Value.TryGetValue(ItemActionType.DebugInstant, out var debugInstantState));
Assert.That(debugInstantState.Equals(new ActionState(true, cooldown: cooldown)));
Assert.That(lightEntry.Value.Value.TryGetValue(ItemActionType.DebugToggle, out var debugToggleState));
Assert.That(debugToggleState.Equals(new ActionState(false)));
var actionsUI = clientUIMgr.StateRoot.Children.FirstOrDefault(c => c is ActionsUI) as ActionsUI;
Assert.That(actionsUI, Is.Not.Null);
var toggleLightSlot = actionsUI.Slots.FirstOrDefault(slot => slot.Action is ItemActionPrototype
{
ActionType: ItemActionType.ToggleLight
});
Assert.That(toggleLightSlot, Is.Not.Null);
clientActionsComponent.AttemptAction(toggleLightSlot);
});
await server.WaitRunTicks(5);
await client.WaitRunTicks(5);
// server should see the action toggled on
await server.WaitAssertion(() =>
{
Assert.That(serverActionsComponent.ItemActionStates().TryGetValue(serverFlashlight.Uid, out var lightStates));
Assert.That(lightStates.TryGetValue(ItemActionType.ToggleLight, out var lightState));
Assert.That(lightState, Is.EqualTo(new ActionState(true, toggledOn: true)));
});
// client should see it toggled on.
await client.WaitAssertion(() =>
{
Assert.That(clientActionsComponent.ItemActionStates().TryGetValue(clientFlashlight, out var lightStates));
Assert.That(lightStates.TryGetValue(ItemActionType.ToggleLight, out var lightState));
Assert.That(lightState, Is.EqualTo(new ActionState(true, toggledOn: true)));
});
await server.WaitAssertion(() =>
{
// drop the item, and the item actions should go away
serverPlayerEnt.GetComponent<HandsComponent>()
.TryDropEntity(serverFlashlight, serverPlayerEnt.Transform.Coordinates, false);
Assert.That(serverActionsComponent.ItemActionStates().ContainsKey(serverFlashlight.Uid), Is.False);
});
await server.WaitRunTicks(5);
await client.WaitRunTicks(5);
// client should see they have no item actions for that item either.
await client.WaitAssertion(() =>
{
Assert.That(clientActionsComponent.ItemActionStates().ContainsKey(clientFlashlight), Is.False);
});
await server.WaitAssertion(() =>
{
// pick the item up again, the states should be back to what they were when dropped,
// as the states "stick" with the item
serverPlayerEnt.GetComponent<HandsComponent>().PutInHand(serverFlashlight.GetComponent<ItemComponent>(), false);
Assert.That(serverActionsComponent.ItemActionStates().TryGetValue(serverFlashlight.Uid, out var lightStates));
Assert.That(lightStates.TryGetValue(ItemActionType.ToggleLight, out var lightState));
Assert.That(lightState.Equals(new ActionState(true, toggledOn: true)));
Assert.That(lightStates.TryGetValue(ItemActionType.DebugInstant, out var debugInstantState));
Assert.That(debugInstantState.Equals(new ActionState(true, cooldown: cooldown)));
Assert.That(lightStates.TryGetValue(ItemActionType.DebugToggle, out var debugToggleState));
Assert.That(debugToggleState.Equals(new ActionState(false)));
});
await server.WaitRunTicks(5);
await client.WaitRunTicks(5);
// client should see the actions again, with their states back to what they were
await client.WaitAssertion(() =>
{
Assert.That(clientActionsComponent.ItemActionStates().TryGetValue(clientFlashlight, out var lightStates));
Assert.That(lightStates.TryGetValue(ItemActionType.ToggleLight, out var lightState));
Assert.That(lightState.Equals(new ActionState(true, toggledOn: true)));
Assert.That(lightStates.TryGetValue(ItemActionType.DebugInstant, out var debugInstantState));
Assert.That(debugInstantState.Equals(new ActionState(true, cooldown: cooldown)));
Assert.That(lightStates.TryGetValue(ItemActionType.DebugToggle, out var debugToggleState));
Assert.That(debugToggleState.Equals(new ActionState(false)));
});
}
}
}
| 48.217507 | 132 | 0.603917 | [
"MIT"
] | AndrewSmart/space-station-14 | Content.IntegrationTests/Tests/GameObjects/Components/Mobs/ActionsComponentTests.cs | 18,178 | C# |
using System;
using SDRSharp.Radio;
namespace SDRSharp.DNR
{
public unsafe class NoiseFilter : FftProcessor
{
private const int WindowSize = 32;
private float _noiseThreshold;
private readonly UnsafeBuffer _gainBuffer;
private readonly float* _gainPtr;
private readonly UnsafeBuffer _smoothedGainBuffer;
private readonly float* _smoothedGainPtr;
private readonly UnsafeBuffer _powerBuffer;
private readonly float* _powerPtr;
public NoiseFilter(int fftSize)
: base(fftSize)
{
_gainBuffer = UnsafeBuffer.Create(fftSize, sizeof(float));
_gainPtr = (float*) _gainBuffer;
_smoothedGainBuffer = UnsafeBuffer.Create(fftSize, sizeof(float));
_smoothedGainPtr = (float*) _smoothedGainBuffer;
_powerBuffer = UnsafeBuffer.Create(fftSize, sizeof(float));
_powerPtr = (float*) _powerBuffer;
}
public float NoiseThreshold
{
get { return _noiseThreshold; }
set
{
_noiseThreshold = value;
}
}
protected override void ProcessFft(Complex* buffer, int length)
{
Fourier.SpectrumPower(buffer, _powerPtr, length);
for (var i = 0; i < length; i++)
{
_gainPtr[i] = _powerPtr[i] > _noiseThreshold ? 1.0f : 0.0f;
}
for (var i = 0; i < length; i++)
{
var sum = 0.0f;
for (var j = -WindowSize / 2; j < WindowSize / 2; j++)
{
var index = i + j;
if (index >= length)
{
index -= length;
}
if (index < 0)
{
index += length;
}
sum += _gainPtr[index];
}
var gain = sum / WindowSize;
_smoothedGainPtr[i] = gain;
}
for (var i = 0; i < length; i++)
{
buffer[i] *= _smoothedGainPtr[i];
}
}
}
} | 28.45679 | 79 | 0.462039 | [
"MIT"
] | CraftyBastard/sdrsharp | DNR/NoiseFilter.cs | 2,307 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using HrApp.Infrastructure;
using HrApp.Models;
namespace HrApp.Controllers
{
[Authorize]
public class TypeJobController : Controller
{
private UnitOfWork _unitOfWork;
public TypeJobController(UnitOfWork unitOfWork)
{
this._unitOfWork = unitOfWork;
}
// GET: TypeJob/Create
public ActionResult Create(int id)
{
var typejob = new TypeJob();
ViewBag.JobName = _unitOfWork.TypeJobsNameRepository.GetAll();
typejob.PersonId = id;
return View(typejob);
}
// POST: TypeJob/Create
[HttpPost]
public ActionResult Create(TypeJob job)
{
if (ModelState.IsValid)
{
_unitOfWork.TypeJobRepository.Add(job);
return RedirectToAction("FullInformation", "Home", new { id = job.PersonId });
}
ViewBag.JobName = _unitOfWork.JobRepository.GetAll();
return View(job);
}
// GET: TypeJob/Edit/5
public ActionResult Edit(int id)
{
ViewBag.JobName = _unitOfWork.TypeJobRepository.GetAll();
var job = _unitOfWork.TypeJobRepository.Get(id);
return View(job);
}
// POST: TypeJob/Edit/5
[HttpPost]
public ActionResult Edit(TypeJob job)
{
if (ModelState.IsValid)
{
_unitOfWork.TypeJobRepository.Edit(job);
return RedirectToAction("FullInformation", "Home", new { id = job.PersonId });
}
ViewBag.JobName = _unitOfWork.TypeJobRepository.GetAll();
return View(job);
}
// GET: TypeJob/Delete/5
public ActionResult Delete(int idPerson, int idPersonTypeJob)
{
_unitOfWork.TypeJobRepository.Delete(idPersonTypeJob);
return RedirectToAction("FullInformation", "Home", new { id = idPerson });
}
}
} | 30.577465 | 95 | 0.55965 | [
"MIT"
] | YuraHavrylko/HrApp | HrApp/Controllers/TypeJobController.cs | 2,173 | C# |
namespace BinaryStream.NET.Extensions
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Threading.Tasks;
using Ionic.Zlib;
public static partial class StreamReader
{
/// <summary>
/// Reads a byte value from the stream.
/// </summary>
/// <param name="Stream">The stream.</param>
#if NET5_0
public static async ValueTask<byte> ReadByteAsync(this Stream Stream)
#else
public static async Task<byte> ReadByteAsync(this Stream Stream)
#endif
{
var Buffer = new byte[sizeof(byte)];
await Stream.ReadAsync(Buffer, 0, Buffer.Length);
return Buffer[0];
}
/// <summary>
/// Reads a signed byte value from the stream.
/// </summary>
/// <param name="Stream">The stream.</param>
#if NET5_0
public static async ValueTask<sbyte> ReadSignedByteAsync(this Stream Stream)
#else
public static async Task<sbyte> ReadSignedByteAsync(this Stream Stream)
#endif
{
var Buffer = new byte[sizeof(sbyte)];
await Stream.ReadAsync(Buffer, 0, Buffer.Length);
return (sbyte) Buffer[0];
}
/// <summary>
/// Reads a boolean value from the stream.
/// </summary>
/// <param name="Stream">The stream.</param>
#if NET5_0
public static async ValueTask<bool> ReadBoolAsync(this Stream Stream)
#else
public static async Task<bool> ReadBoolAsync(this Stream Stream)
#endif
{
var Buffer = new byte[sizeof(bool)];
await Stream.ReadAsync(Buffer, 0, Buffer.Length);
if (BitConverter.IsLittleEndian)
Array.Reverse(Buffer);
return BitConverter.ToBoolean(Buffer, 0);
}
/// <summary>
/// Reads a char value from the stream.
/// </summary>
/// <param name="Stream">The stream.</param>
#if NET5_0
public static async ValueTask<char> ReadCharAsync(this Stream Stream)
#else
public static async Task<char> ReadCharAsync(this Stream Stream)
#endif
{
var Buffer = new byte[sizeof(char)];
await Stream.ReadAsync(Buffer, 0, Buffer.Length);
if (BitConverter.IsLittleEndian)
Array.Reverse(Buffer);
return BitConverter.ToChar(Buffer, 0);
}
/// <summary>
/// Reads a short value from the stream.
/// </summary>
/// <param name="Stream">The stream.</param>
#if NET5_0
public static async ValueTask<short> ReadShortAsync(this Stream Stream)
#else
public static async Task<short> ReadShortAsync(this Stream Stream)
#endif
{
var Buffer = new byte[sizeof(short)];
await Stream.ReadAsync(Buffer, 0, Buffer.Length);
if (BitConverter.IsLittleEndian)
Array.Reverse(Buffer);
return BitConverter.ToInt16(Buffer, 0);
}
/// <summary>
/// Reads an unsigned short value from the stream.
/// </summary>
/// <param name="Stream">The stream.</param>
#if NET5_0
public static async ValueTask<ushort> ReadUnsignedShortAsync(this Stream Stream)
#else
public static async Task<ushort> ReadUnsignedShortAsync(this Stream Stream)
#endif
{
var Buffer = new byte[sizeof(ushort)];
await Stream.ReadAsync(Buffer, 0, Buffer.Length);
if (BitConverter.IsLittleEndian)
Array.Reverse(Buffer);
return BitConverter.ToUInt16(Buffer, 0);
}
/// <summary>
/// Reads an integer value from the stream.
/// </summary>
/// <param name="Stream">The stream.</param>
#if NET5_0
public static async ValueTask<int> ReadIntegerAsync(this Stream Stream)
#else
public static async Task<int> ReadIntegerAsync(this Stream Stream)
#endif
{
var Buffer = new byte[sizeof(int)];
await Stream.ReadAsync(Buffer, 0, Buffer.Length);
if (BitConverter.IsLittleEndian)
Array.Reverse(Buffer);
return BitConverter.ToInt32(Buffer, 0);
}
/// <summary>
/// Reads an unsigned integer value from the stream.
/// </summary>
/// <param name="Stream">The stream.</param>
#if NET5_0
public static async ValueTask<uint> ReadUnsignedIntegerAsync(this Stream Stream)
#else
public static async Task<uint> ReadUnsignedIntegerAsync(this Stream Stream)
#endif
{
var Buffer = new byte[sizeof(uint)];
await Stream.ReadAsync(Buffer, 0, Buffer.Length);
if (BitConverter.IsLittleEndian)
Array.Reverse(Buffer);
return BitConverter.ToUInt32(Buffer, 0);
}
/// <summary>
/// Reads a long value from the stream.
/// </summary>
/// <param name="Stream">The stream.</param>
#if NET5_0
public static async ValueTask<long> ReadLongAsync(this Stream Stream)
#else
public static async Task<long> ReadLongAsync(this Stream Stream)
#endif
{
var Buffer = new byte[sizeof(long)];
await Stream.ReadAsync(Buffer, 0, Buffer.Length);
if (BitConverter.IsLittleEndian)
Array.Reverse(Buffer);
return BitConverter.ToInt64(Buffer, 0);
}
/// <summary>
/// Reads an unsigned long value from the stream.
/// </summary>
/// <param name="Stream">The stream.</param>
#if NET5_0
public static async ValueTask<ulong> ReadUnsignedLongAsync(this Stream Stream)
#else
public static async Task<ulong> ReadUnsignedLongAsync(this Stream Stream)
#endif
{
var Buffer = new byte[sizeof(ulong)];
await Stream.ReadAsync(Buffer, 0, Buffer.Length);
if (BitConverter.IsLittleEndian)
Array.Reverse(Buffer);
return BitConverter.ToUInt64(Buffer, 0);
}
/// <summary>
/// Reads a double value from the stream.
/// </summary>
/// <param name="Stream">The stream.</param>
#if NET5_0
public static async ValueTask<double> ReadDoubleAsync(this Stream Stream)
#else
public static async Task<double> ReadDoubleAsync(this Stream Stream)
#endif
{
var Buffer = new byte[sizeof(double)];
await Stream.ReadAsync(Buffer, 0, Buffer.Length);
if (BitConverter.IsLittleEndian)
Array.Reverse(Buffer);
return BitConverter.ToDouble(Buffer, 0);
}
/// <summary>
/// Reads a single value from the stream.
/// </summary>
/// <param name="Stream">The stream.</param>
#if NET5_0
public static async ValueTask<float> ReadSingleAsync(this Stream Stream)
#else
public static async Task<float> ReadSingleAsync(this Stream Stream)
#endif
{
var Buffer = new byte[sizeof(float)];
await Stream.ReadAsync(Buffer, 0, Buffer.Length);
if (BitConverter.IsLittleEndian)
Array.Reverse(Buffer);
return BitConverter.ToSingle(Buffer, 0);
}
/// <summary>
/// Reads an enum value from the stream.
/// </summary>
/// <param name="Stream">The stream.</param>
#if NET5_0
public static async ValueTask<T> ReadEnumAsync<T>(this Stream Stream) where T : Enum
#else
public static async Task<T> ReadEnumAsync<T>(this Stream Stream) where T : Enum
#endif
{
switch (Type.GetTypeCode(typeof(T)))
{
case TypeCode.Byte:
return (T) Enum.ToObject(typeof(T), (byte) await Stream.ReadByteAsync());
case TypeCode.SByte:
return (T) Enum.ToObject(typeof(T), (sbyte) await Stream.ReadByteAsync());
case TypeCode.Int16:
return (T) Enum.ToObject(typeof(T), await Stream.ReadShortAsync());
case TypeCode.UInt16:
return (T) Enum.ToObject(typeof(T), await Stream.ReadUnsignedShortAsync());
case TypeCode.Int32:
return (T) Enum.ToObject(typeof(T), await Stream.ReadIntegerAsync());
case TypeCode.UInt32:
return (T) Enum.ToObject(typeof(T), await Stream.ReadUnsignedIntegerAsync());
case TypeCode.Int64:
return (T) Enum.ToObject(typeof(T), await Stream.ReadLongAsync());
case TypeCode.UInt64:
return (T) Enum.ToObject(typeof(T), await Stream.ReadUnsignedLongAsync());
default:
throw new InvalidOperationException("This underlying type of enum is not supported");
}
}
/// <summary>
/// Reads an array from the stream.
/// </summary>
/// <param name="Stream">The stream.</param>
/// <param name="EntryDecoder">The entry decoder.</param>
#if NET5_0
public static async ValueTask<IEnumerable<T>> ReadArrayAsync<T>(this Stream Stream, Func<Stream, Task<T>> EntryDecoder)
#else
public static async Task<IEnumerable<T>> ReadArrayAsync<T>(this Stream Stream, Func<Stream, Task<T>> EntryDecoder)
#endif
{
var NumberOfEntries = await Stream.ReadIntegerAsync();
if (NumberOfEntries == -1)
return null;
if (NumberOfEntries == 0)
return new T[0];
var Entries = new T[NumberOfEntries];
for (var EntryId = 0; EntryId < NumberOfEntries; EntryId++)
Entries[EntryId] = await EntryDecoder(Stream);
return Entries;
}
/// <summary>
/// Reads an array from the stream.
/// </summary>
/// <param name="Stream">The stream.</param>
#if NET5_0
public static async ValueTask<byte[]> ReadBufferAsync(this Stream Stream)
#else
public static async Task<byte[]> ReadBufferAsync(this Stream Stream)
#endif
{
var NumberOfBytes = await Stream.ReadIntegerAsync();
if (NumberOfBytes == -1)
return null;
var Buffer = new byte[NumberOfBytes];
if (NumberOfBytes != 0)
await Stream.ReadAsync(Buffer, 0, Buffer.Length);
return Buffer;
}
/// <summary>
/// Writes a compressed array to the stream.
/// </summary>
/// <param name="Stream">The stream.</param>
#if NET5_0
public static async ValueTask<byte[]> ReadCompressedBufferAsync(this Stream Stream)
#else
public static async Task<byte[]> ReadCompressedBufferAsync(this Stream Stream)
#endif
{
var CompressedBuffer = await Stream.ReadBufferAsync();
if (CompressedBuffer == null)
return null;
if (CompressedBuffer.Length == 0)
return new byte[0];
return ZlibStream.UncompressBuffer(CompressedBuffer);
}
/// <summary>
/// Reads a string value from the stream.
/// </summary>
/// <param name="Stream">The stream.</param>
/// <param name="Encoding">The string encoding.</param>
#if NET5_0
public static async ValueTask<string> ReadStringAsync(this Stream Stream, Encoding Encoding = null)
#else
public static async Task<string> ReadStringAsync(this Stream Stream, Encoding Encoding = null)
#endif
{
if (Encoding == null || Encoding.Equals(Encoding.Unicode))
Encoding = Encoding.BigEndianUnicode;
var Buffer = await Stream.ReadBufferAsync();
if (Buffer == null)
return null;
if (Buffer.Length == 0)
return string.Empty;
return Encoding.GetString(Buffer);
}
/// <summary>
/// Reads a compressed string value from the stream.
/// </summary>
/// <param name="Stream">The stream.</param>
/// <param name="Encoding">The string encoding.</param>
#if NET5_0
public static async ValueTask<string> ReadCompressedStringAsync(this Stream Stream, Encoding Encoding = null)
#else
public static async Task<string> ReadCompressedStringAsync(this Stream Stream, Encoding Encoding = null)
#endif
{
if (Encoding == null || Encoding.Equals(Encoding.Unicode))
Encoding = Encoding.BigEndianUnicode;
var Buffer = await Stream.ReadCompressedBufferAsync();
if (Buffer == null)
return null;
if (Buffer.Length == 0)
return string.Empty;
return Encoding.GetString(Buffer);
}
/// <summary>
/// Reads a <see cref="DateTime"/> value from the stream.
/// </summary>
/// <param name="Stream">The stream.</param>
/// <returns>A datetime that is expected to be UTC.</returns>
#if NET5_0
public static async ValueTask<DateTime> ReadDateTimeAsync(this Stream Stream)
#else
public static async Task<DateTime> ReadDateTimeAsync(this Stream Stream)
#endif
{
var Ticks = await Stream.ReadLongAsync();
var Value = new DateTime(Ticks, DateTimeKind.Utc);
return Value;
}
/// <summary>
/// Reads a <see cref="DateTimeOffset"/> value from the stream.
/// </summary>
/// <param name="Stream">The stream.</param>
/// <returns>A datetime that is expected to be UTC.</returns>
#if NET5_0
public static async ValueTask<DateTimeOffset> ReadDateTimeOffsetAsync(this Stream Stream)
#else
public static async Task<DateTimeOffset> ReadDateTimeOffsetAsync(this Stream Stream)
#endif
{
var Ticks = await Stream.ReadLongAsync();
var Offset = await Stream.ReadTimeSpanAsync();
var Value = new DateTimeOffset(Ticks, Offset);
return Value;
}
/// <summary>
/// Reads a <see cref="TimeSpan"/> value from the stream.
/// </summary>
/// <param name="Stream">The stream.</param>
#if NET5_0
public static async ValueTask<TimeSpan> ReadTimeSpanAsync(this Stream Stream)
#else
public static async Task<TimeSpan> ReadTimeSpanAsync(this Stream Stream)
#endif
{
var Ticks = await Stream.ReadLongAsync();
return new TimeSpan(Ticks);
}
/// <summary>
/// Reads a <see cref="Guid"/> value from the stream.
/// </summary>
/// <param name="Stream">The stream.</param>
#if NET5_0
public static async ValueTask<Guid> ReadGuidAsync(this Stream Stream)
#else
public static async Task<Guid> ReadGuidAsync(this Stream Stream)
#endif
{
return new Guid(await Stream.ReadBufferAsync());
}
/// <summary>
/// Reads a compressed integer value from the stream.
/// </summary>
/// <param name="Stream">The stream.</param>
#if NET5_0
public static async ValueTask<int> ReadCompressedIntegerAsync(this Stream Stream)
#else
public static async Task<int> ReadCompressedIntegerAsync(this Stream Stream)
#endif
{
var Byte = await Stream.ReadByteAsync();
int Result;
if ((Byte & 0x40) != 0)
{
Result = Byte & 0x3F;
if ((Byte & 0x80) != 0)
{
Result |= ((Byte = await Stream.ReadByteAsync()) & 0x7F) << 6;
if ((Byte & 0x80) != 0)
{
Result |= ((Byte = await Stream.ReadByteAsync()) & 0x7F) << 13;
if ((Byte & 0x80) != 0)
{
Result |= ((Byte = await Stream.ReadByteAsync()) & 0x7F) << 20;
if ((Byte & 0x80) != 0)
{
Result |= ((Byte = await Stream.ReadByteAsync()) & 0x7F) << 27;
return (int) (Result | 0x80000000);
}
return (int) (Result | 0xF8000000);
}
return (int) (Result | 0xFFF00000);
}
return (int) (Result | 0xFFFFE000);
}
return (int) (Result | 0xFFFFFFC0);
}
else
{
Result = Byte & 0x3F;
if ((Byte & 0x80) != 0)
{
Result |= ((Byte = await Stream.ReadByteAsync()) & 0x7F) << 6;
if ((Byte & 0x80) != 0)
{
Result |= ((Byte = await Stream.ReadByteAsync()) & 0x7F) << 13;
if ((Byte & 0x80) != 0)
{
Result |= ((Byte = await Stream.ReadByteAsync()) & 0x7F) << 20;
if ((Byte & 0x80) != 0)
{
Result |= ((Byte = await Stream.ReadByteAsync()) & 0x7F) << 27;
}
}
}
}
}
return Result;
}
/// <summary>
/// Reads a compressed unsigned integer value from the stream.
/// </summary>
/// <param name="Stream">The stream.</param>
#if NET5_0
public static async ValueTask<uint> ReadCompressedUnsignedIntegerAsync(this Stream Stream)
#else
public static async Task<uint> ReadCompressedUnsignedIntegerAsync(this Stream Stream)
#endif
{
var Byte = await Stream.ReadByteAsync();
int Result;
if ((Byte & 0x40) != 0)
{
Result = Byte & 0x3F;
if ((Byte & 0x80) != 0)
{
Result |= ((Byte = await Stream.ReadByteAsync()) & 0x7F) << 6;
if ((Byte & 0x80) != 0)
{
Result |= ((Byte = await Stream.ReadByteAsync()) & 0x7F) << 13;
if ((Byte & 0x80) != 0)
{
Result |= ((Byte = await Stream.ReadByteAsync()) & 0x7F) << 20;
if ((Byte & 0x80) != 0)
{
Result |= ((Byte = await Stream.ReadByteAsync()) & 0x7F) << 27;
return (uint) (Result | 0x80000000);
}
return (uint) (Result | 0xF8000000);
}
return (uint) (Result | 0xFFF00000);
}
return (uint) (Result | 0xFFFFE000);
}
return (uint) (Result | 0xFFFFFFC0);
}
else
{
Result = Byte & 0x3F;
if ((Byte & 0x80) != 0)
{
Result |= ((Byte = await Stream.ReadByteAsync()) & 0x7F) << 6;
if ((Byte & 0x80) != 0)
{
Result |= ((Byte = await Stream.ReadByteAsync()) & 0x7F) << 13;
if ((Byte & 0x80) != 0)
{
Result |= ((Byte = await Stream.ReadByteAsync()) & 0x7F) << 20;
if ((Byte & 0x80) != 0)
{
Result |= ((Byte = await Stream.ReadByteAsync()) & 0x7F) << 27;
}
}
}
}
}
return (uint) Result;
}
}
}
| 34.11405 | 127 | 0.51519 | [
"MIT"
] | BerkanYildiz/BinaryStream.NET | BinaryStream.NET/Extensions/StreamReaderAsync.cs | 20,641 | C# |
#region using statements
using System;
using DataJuggler.Net.Core.Delegates;
using DataJuggler.Net.Core.Enumerations;
#endregion
namespace ObjectLibrary.BusinessObjects
{
#region class Image
public partial class Image
{
#region Private Variables
private DateTime createdDate;
private string extension;
private int fileSize;
private string fullPath;
private int height;
private int id;
private int imageNumber;
private string imageUrl;
private string name;
private int ownerId;
private string sitePath;
private bool visible;
private int width;
private ItemChangedCallback callback;
#endregion
#region Methods
#region UpdateIdentity(int id)
// <summary>
// This method provides a 'setter'
// functionality for the Identity field.
// </summary>
public void UpdateIdentity(int id)
{
// Update The Identity field
this.id = id;
}
#endregion
#endregion
#region Properties
#region DateTime CreatedDate
public DateTime CreatedDate
{
get
{
return createdDate;
}
set
{
// local
bool hasChanges = (CreatedDate != value);
// Set the value
createdDate = value;
// if the Callback exists and changes occurred
if ((HasCallback) && (hasChanges))
{
// Notify the Callback changes have occurred
Callback(this, ChangeTypeEnum.ItemChanged);
}
}
}
#endregion
#region string Extension
public string Extension
{
get
{
return extension;
}
set
{
// local
bool hasChanges = (Extension != value);
// Set the value
extension = value;
// if the Callback exists and changes occurred
if ((HasCallback) && (hasChanges))
{
// Notify the Callback changes have occurred
Callback(this, ChangeTypeEnum.ItemChanged);
}
}
}
#endregion
#region int FileSize
public int FileSize
{
get
{
return fileSize;
}
set
{
// local
bool hasChanges = (FileSize != value);
// Set the value
fileSize = value;
// if the Callback exists and changes occurred
if ((HasCallback) && (hasChanges))
{
// Notify the Callback changes have occurred
Callback(this, ChangeTypeEnum.ItemChanged);
}
}
}
#endregion
#region string FullPath
public string FullPath
{
get
{
return fullPath;
}
set
{
// local
bool hasChanges = (FullPath != value);
// Set the value
fullPath = value;
// if the Callback exists and changes occurred
if ((HasCallback) && (hasChanges))
{
// Notify the Callback changes have occurred
Callback(this, ChangeTypeEnum.ItemChanged);
}
}
}
#endregion
#region int Height
public int Height
{
get
{
return height;
}
set
{
// local
bool hasChanges = (Height != value);
// Set the value
height = value;
// if the Callback exists and changes occurred
if ((HasCallback) && (hasChanges))
{
// Notify the Callback changes have occurred
Callback(this, ChangeTypeEnum.ItemChanged);
}
}
}
#endregion
#region int Id
public int Id
{
get
{
return id;
}
}
#endregion
#region int ImageNumber
public int ImageNumber
{
get
{
return imageNumber;
}
set
{
// local
bool hasChanges = (ImageNumber != value);
// Set the value
imageNumber = value;
// if the Callback exists and changes occurred
if ((HasCallback) && (hasChanges))
{
// Notify the Callback changes have occurred
Callback(this, ChangeTypeEnum.ItemChanged);
}
}
}
#endregion
#region string ImageUrl
public string ImageUrl
{
get
{
return imageUrl;
}
set
{
// local
bool hasChanges = (ImageUrl != value);
// Set the value
imageUrl = value;
// if the Callback exists and changes occurred
if ((HasCallback) && (hasChanges))
{
// Notify the Callback changes have occurred
Callback(this, ChangeTypeEnum.ItemChanged);
}
}
}
#endregion
#region string Name
public string Name
{
get
{
return name;
}
set
{
// local
bool hasChanges = (Name != value);
// Set the value
name = value;
// if the Callback exists and changes occurred
if ((HasCallback) && (hasChanges))
{
// Notify the Callback changes have occurred
Callback(this, ChangeTypeEnum.ItemChanged);
}
}
}
#endregion
#region int OwnerId
public int OwnerId
{
get
{
return ownerId;
}
set
{
// local
bool hasChanges = (OwnerId != value);
// Set the value
ownerId = value;
// if the Callback exists and changes occurred
if ((HasCallback) && (hasChanges))
{
// Notify the Callback changes have occurred
Callback(this, ChangeTypeEnum.ItemChanged);
}
}
}
#endregion
#region string SitePath
public string SitePath
{
get
{
return sitePath;
}
set
{
// local
bool hasChanges = (SitePath != value);
// Set the value
sitePath = value;
// if the Callback exists and changes occurred
if ((HasCallback) && (hasChanges))
{
// Notify the Callback changes have occurred
Callback(this, ChangeTypeEnum.ItemChanged);
}
}
}
#endregion
#region bool Visible
public bool Visible
{
get
{
return visible;
}
set
{
// local
bool hasChanges = (Visible != value);
// Set the value
visible = value;
// if the Callback exists and changes occurred
if ((HasCallback) && (hasChanges))
{
// Notify the Callback changes have occurred
Callback(this, ChangeTypeEnum.ItemChanged);
}
}
}
#endregion
#region int Width
public int Width
{
get
{
return width;
}
set
{
// local
bool hasChanges = (Width != value);
// Set the value
width = value;
// if the Callback exists and changes occurred
if ((HasCallback) && (hasChanges))
{
// Notify the Callback changes have occurred
Callback(this, ChangeTypeEnum.ItemChanged);
}
}
}
#endregion
#region bool IsNew
public bool IsNew
{
get
{
// Initial Value
bool isNew = (this.Id < 1);
// return value
return isNew;
}
}
#endregion
#region ItemChangedCallback Callback
public ItemChangedCallback Callback
{
get
{
return callback;
}
set
{
callback = value;
}
}
#endregion
#region bool HasCallback
public bool HasCallback
{
get
{
// Initial Value
bool hasCallback = (this.Callback != null);
// return value
return hasCallback;
}
}
#endregion
#endregion
}
#endregion
}
| 27.349515 | 68 | 0.366258 | [
"MIT"
] | DataJuggler/BlazorImageGallery | Data/ObjectLibrary/BusinessObjects/Image.data.cs | 11,268 | C# |
/**
* Autogenerated by Thrift Compiler (0.13.0)
*
* DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
* @generated
*/
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Thrift.Protocol;
using Thrift.Protocol.Entities;
using Thrift.Protocol.Utilities;
namespace Jaeger.Thrift.Agent
{
public partial class BaggageRestriction : TBase
{
public string BaggageKey { get; set; }
public int MaxValueLength { get; set; }
public BaggageRestriction()
{
}
public BaggageRestriction(string baggageKey, int maxValueLength) : this()
{
this.BaggageKey = baggageKey;
this.MaxValueLength = maxValueLength;
}
public async Task ReadAsync(TProtocol iprot, CancellationToken cancellationToken)
{
iprot.IncrementRecursionDepth();
try
{
bool isset_baggageKey = false;
bool isset_maxValueLength = false;
TField field;
await iprot.ReadStructBeginAsync(cancellationToken);
while (true)
{
field = await iprot.ReadFieldBeginAsync(cancellationToken);
if (field.Type == TType.Stop)
{
break;
}
switch (field.ID)
{
case 1:
if (field.Type == TType.String)
{
BaggageKey = await iprot.ReadStringAsync(cancellationToken);
isset_baggageKey = true;
}
else
{
await TProtocolUtil.SkipAsync(iprot, field.Type, cancellationToken);
}
break;
case 2:
if (field.Type == TType.I32)
{
MaxValueLength = await iprot.ReadI32Async(cancellationToken);
isset_maxValueLength = true;
}
else
{
await TProtocolUtil.SkipAsync(iprot, field.Type, cancellationToken);
}
break;
default:
await TProtocolUtil.SkipAsync(iprot, field.Type, cancellationToken);
break;
}
await iprot.ReadFieldEndAsync(cancellationToken);
}
await iprot.ReadStructEndAsync(cancellationToken);
if (!isset_baggageKey)
{
throw new TProtocolException(TProtocolException.INVALID_DATA);
}
if (!isset_maxValueLength)
{
throw new TProtocolException(TProtocolException.INVALID_DATA);
}
}
finally
{
iprot.DecrementRecursionDepth();
}
}
public async Task WriteAsync(TProtocol oprot, CancellationToken cancellationToken)
{
oprot.IncrementRecursionDepth();
try
{
var struc = new TStruct("BaggageRestriction");
await oprot.WriteStructBeginAsync(struc, cancellationToken);
var field = new TField();
field.Name = "baggageKey";
field.Type = TType.String;
field.ID = 1;
await oprot.WriteFieldBeginAsync(field, cancellationToken);
await oprot.WriteStringAsync(BaggageKey, cancellationToken);
await oprot.WriteFieldEndAsync(cancellationToken);
field.Name = "maxValueLength";
field.Type = TType.I32;
field.ID = 2;
await oprot.WriteFieldBeginAsync(field, cancellationToken);
await oprot.WriteI32Async(MaxValueLength, cancellationToken);
await oprot.WriteFieldEndAsync(cancellationToken);
await oprot.WriteFieldStopAsync(cancellationToken);
await oprot.WriteStructEndAsync(cancellationToken);
}
finally
{
oprot.DecrementRecursionDepth();
}
}
public override bool Equals(object that)
{
var other = that as BaggageRestriction;
if (other == null) return false;
if (ReferenceEquals(this, other)) return true;
return System.Object.Equals(BaggageKey, other.BaggageKey)
&& System.Object.Equals(MaxValueLength, other.MaxValueLength);
}
public override int GetHashCode() {
int hashcode = 157;
unchecked {
hashcode = (hashcode * 397) + BaggageKey.GetHashCode();
hashcode = (hashcode * 397) + MaxValueLength.GetHashCode();
}
return hashcode;
}
public override string ToString()
{
var sb = new StringBuilder("BaggageRestriction(");
sb.Append(", BaggageKey: ");
sb.Append(BaggageKey);
sb.Append(", MaxValueLength: ");
sb.Append(MaxValueLength);
sb.Append(")");
return sb.ToString();
}
}
}
| 28.36646 | 86 | 0.604773 | [
"Apache-2.0"
] | BojanPantovic1989/jaeger-client-csharp | src/Communication/Jaeger.Communication.Thrift/Agent/BaggageRestriction.cs | 4,567 | C# |
// <copyright file="StepCommand.cs" company="xBehave.net contributors">
// Copyright (c) xBehave.net contributors. All rights reserved.
// </copyright>
namespace Xbehave.Sdk
{
using System;
using System.Globalization;
using System.Linq;
using Xunit.Sdk;
[CLSCompliant(false)]
public class StepCommand : ContextCommand
{
private readonly Step step;
public StepCommand(MethodCall methodCall, int contextOrdinal, int stepOrdinal, Step step)
: base(methodCall, contextOrdinal, stepOrdinal)
{
Guard.AgainstNullArgument("methodCall", methodCall);
Guard.AgainstNullArgument("step", step);
if (step.Name == null)
{
throw new ArgumentException("The step name is null.", "step");
}
this.step = step;
var provider = CultureInfo.InvariantCulture;
string stepName;
try
{
stepName = string.Format(provider, step.Name, methodCall.Arguments.Select(argument => argument.Value ?? "null").ToArray());
}
catch (FormatException)
{
stepName = step.Name;
}
this.Name = string.Format(provider, "{0} {1}", this.Name, stepName);
this.DisplayName = string.Format(CultureInfo.InvariantCulture, "{0} {1}", this.DisplayName, stepName);
}
public override MethodResult Execute(object testClass)
{
if (this.step.SkipReason != null)
{
return new SkipResult(this.testMethod, this.DisplayName, this.step.SkipReason);
}
if (Context.FailedStepName != null)
{
throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, "Failed to execute preceding step \"{0}\".", Context.FailedStepName));
}
try
{
this.step.Execute();
}
catch (Exception)
{
Context.FailedStepName = this.Name;
throw;
}
return new PassedResult(this.testMethod, this.DisplayName);
}
}
}
| 32.295775 | 167 | 0.543393 | [
"MIT"
] | jamesfoster/xbehave.net | src/Xbehave.Sdk.Net40/StepCommand.cs | 2,295 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
namespace GymFitnessOlympic.Models
{
public partial class HoiVien
{
public int MaHoiVien { get; set; }
public string MaThe { get; set; }
public string TenHoiVien { get; set; }
//public string MaSauna { get; set; }
public bool GioiTinh { get; set; }
public string DiaChi { get; set; }
public DateTime NgaySinh { get; set; }
public string SoDienThoai { get; set; }
public DateTime NgayHetHanGYM { get; set; }
public DateTime NgayHetHanSauNa { get; set; }
public DateTime GiaHanCuoiGYM { get; set; }
public DateTime GiaHanCuoiSauna { get; set; }
public PhongTap PhongTap { get; set; }
public int MaPhongTap { get; set; }
public byte[] Anh { get; set; }
public List<PhieuThu> DanhSachPhieuThu { get; set; }
public List<HistoryHoiVien> LichSu { get; set; }
public DateTime NgayGioDangKy { get; set; }
public bool IsDangKyNhanh { get; set; }
public HoiVien()
{
NgayHetHanGYM = NgayHetHanSauNa = GiaHanCuoiGYM = GiaHanCuoiSauna = DateTime.Now;
NgayGioDangKy = DateTime.Now;
IsDangKyNhanh = false;
}
public String DaCapNhatString {
get {
return IsDangKyNhanh ? "Chưa cập nhật" : "Đã cập nhật";
}
}
public int TongTien {
get {
return DanhSachPhieuThu.Sum(p => p.TienSauGiam);
}
}
}
}
| 32.27451 | 93 | 0.587485 | [
"Apache-2.0"
] | hynguyen2610/OlympicGym | GymFitnessOlympic/Models/entity/HoiVien.cs | 1,659 | C# |
// *** WARNING: this file was generated by the Pulumi SDK Generator. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.AzureNextGen.Cdn.V20190615Preview
{
/// <summary>
/// Friendly domain name mapping to the endpoint hostname that the customer provides for branding purposes, e.g. www.contoso.com.
/// </summary>
[AzureNextGenResourceType("azure-nextgen:cdn/v20190615preview:CustomDomain")]
public partial class CustomDomain : Pulumi.CustomResource
{
/// <summary>
/// Certificate parameters for securing custom HTTPS
/// </summary>
[Output("customHttpsParameters")]
public Output<Union<Outputs.CdnManagedHttpsParametersResponse, Outputs.UserManagedHttpsParametersResponse>?> CustomHttpsParameters { get; private set; } = null!;
/// <summary>
/// Provisioning status of Custom Https of the custom domain.
/// </summary>
[Output("customHttpsProvisioningState")]
public Output<string> CustomHttpsProvisioningState { get; private set; } = null!;
/// <summary>
/// Provisioning substate shows the progress of custom HTTPS enabling/disabling process step by step.
/// </summary>
[Output("customHttpsProvisioningSubstate")]
public Output<string> CustomHttpsProvisioningSubstate { get; private set; } = null!;
/// <summary>
/// The host name of the custom domain. Must be a domain name.
/// </summary>
[Output("hostName")]
public Output<string> HostName { get; private set; } = null!;
/// <summary>
/// Resource name.
/// </summary>
[Output("name")]
public Output<string> Name { get; private set; } = null!;
/// <summary>
/// Provisioning status of the custom domain.
/// </summary>
[Output("provisioningState")]
public Output<string> ProvisioningState { get; private set; } = null!;
/// <summary>
/// Resource status of the custom domain.
/// </summary>
[Output("resourceState")]
public Output<string> ResourceState { get; private set; } = null!;
/// <summary>
/// Resource type.
/// </summary>
[Output("type")]
public Output<string> Type { get; private set; } = null!;
/// <summary>
/// Special validation or data may be required when delivering CDN to some regions due to local compliance reasons. E.g. ICP license number of a custom domain is required to deliver content in China.
/// </summary>
[Output("validationData")]
public Output<string?> ValidationData { get; private set; } = null!;
/// <summary>
/// Create a CustomDomain resource with the given unique name, arguments, and options.
/// </summary>
///
/// <param name="name">The unique name of the resource</param>
/// <param name="args">The arguments used to populate this resource's properties</param>
/// <param name="options">A bag of options that control this resource's behavior</param>
public CustomDomain(string name, CustomDomainArgs args, CustomResourceOptions? options = null)
: base("azure-nextgen:cdn/v20190615preview:CustomDomain", name, args ?? new CustomDomainArgs(), MakeResourceOptions(options, ""))
{
}
private CustomDomain(string name, Input<string> id, CustomResourceOptions? options = null)
: base("azure-nextgen:cdn/v20190615preview:CustomDomain", name, null, MakeResourceOptions(options, id))
{
}
private static CustomResourceOptions MakeResourceOptions(CustomResourceOptions? options, Input<string>? id)
{
var defaultOptions = new CustomResourceOptions
{
Version = Utilities.Version,
Aliases =
{
new Pulumi.Alias { Type = "azure-nextgen:cdn:CustomDomain"},
new Pulumi.Alias { Type = "azure-nextgen:cdn/latest:CustomDomain"},
new Pulumi.Alias { Type = "azure-nextgen:cdn/v20150601:CustomDomain"},
new Pulumi.Alias { Type = "azure-nextgen:cdn/v20160402:CustomDomain"},
new Pulumi.Alias { Type = "azure-nextgen:cdn/v20161002:CustomDomain"},
new Pulumi.Alias { Type = "azure-nextgen:cdn/v20170402:CustomDomain"},
new Pulumi.Alias { Type = "azure-nextgen:cdn/v20171012:CustomDomain"},
new Pulumi.Alias { Type = "azure-nextgen:cdn/v20190415:CustomDomain"},
new Pulumi.Alias { Type = "azure-nextgen:cdn/v20190615:CustomDomain"},
new Pulumi.Alias { Type = "azure-nextgen:cdn/v20191231:CustomDomain"},
new Pulumi.Alias { Type = "azure-nextgen:cdn/v20200331:CustomDomain"},
new Pulumi.Alias { Type = "azure-nextgen:cdn/v20200415:CustomDomain"},
new Pulumi.Alias { Type = "azure-nextgen:cdn/v20200901:CustomDomain"},
},
};
var merged = CustomResourceOptions.Merge(defaultOptions, options);
// Override the ID if one was specified for consistency with other language SDKs.
merged.Id = id ?? merged.Id;
return merged;
}
/// <summary>
/// Get an existing CustomDomain resource's state with the given name, ID, and optional extra
/// properties used to qualify the lookup.
/// </summary>
///
/// <param name="name">The unique name of the resulting resource.</param>
/// <param name="id">The unique provider ID of the resource to lookup.</param>
/// <param name="options">A bag of options that control this resource's behavior</param>
public static CustomDomain Get(string name, Input<string> id, CustomResourceOptions? options = null)
{
return new CustomDomain(name, id, options);
}
}
public sealed class CustomDomainArgs : Pulumi.ResourceArgs
{
/// <summary>
/// Name of the custom domain within an endpoint.
/// </summary>
[Input("customDomainName")]
public Input<string>? CustomDomainName { get; set; }
/// <summary>
/// Name of the endpoint under the profile which is unique globally.
/// </summary>
[Input("endpointName", required: true)]
public Input<string> EndpointName { get; set; } = null!;
/// <summary>
/// The host name of the custom domain. Must be a domain name.
/// </summary>
[Input("hostName", required: true)]
public Input<string> HostName { get; set; } = null!;
/// <summary>
/// Name of the CDN profile which is unique within the resource group.
/// </summary>
[Input("profileName", required: true)]
public Input<string> ProfileName { get; set; } = null!;
/// <summary>
/// Name of the Resource group within the Azure subscription.
/// </summary>
[Input("resourceGroupName", required: true)]
public Input<string> ResourceGroupName { get; set; } = null!;
public CustomDomainArgs()
{
}
}
}
| 44.5 | 207 | 0.608882 | [
"Apache-2.0"
] | pulumi/pulumi-azure-nextgen | sdk/dotnet/Cdn/V20190615Preview/CustomDomain.cs | 7,476 | C# |
using Xunit.Abstractions;
using Xunit.DependencyInjection;
namespace Stl.Testing.Output;
public class TestOutputHelperAccessor : ITestOutputHelperAccessor
{
public ITestOutputHelper? Output { get; set; }
public TestOutputHelperAccessor(ITestOutputHelper? output)
=> Output = output;
}
| 23.384615 | 65 | 0.776316 | [
"MIT"
] | ScriptBox21/Stl.Fusion | src/Stl.Testing/Output/TestOutputHelperAccessor.cs | 304 | C# |
// Licensed to Elasticsearch B.V under one or more agreements.
// Elasticsearch B.V licenses this file to you under the Apache 2.0 License.
// See the LICENSE file in the project root for more information
using System;
using System.Collections.Generic;
using FluentAssertions;
using Nest;
using Tests.Core.Extensions;
using Tests.Core.ManagedElasticsearch.Clusters;
using Tests.Domain;
using Tests.Framework.EndpointTests.TestState;
using static Nest.Infer;
namespace Tests.Aggregations.Metric.PercentileRanks
{
public class PercentileRanksAggregationUsageTests : AggregationUsageTestBase
{
public PercentileRanksAggregationUsageTests(ReadOnlyCluster i, EndpointUsage usage) : base(i, usage) { }
protected override object AggregationJson => new
{
commits_outlier = new
{
percentile_ranks = new
{
field = "numberOfCommits",
values = new[] { 15.0, 30.0 },
tdigest = new
{
compression = 200.0
},
script = new
{
source = "doc['numberOfCommits'].value * 1.2",
},
missing = 0.0
}
}
};
protected override Func<AggregationContainerDescriptor<Project>, IAggregationContainer> FluentAggs => a => a
.PercentileRanks("commits_outlier", pr => pr
.Field(p => p.NumberOfCommits)
.Values(15, 30)
.Method(m => m
.TDigest(td => td
.Compression(200)
)
)
.Script(ss => ss.Source("doc['numberOfCommits'].value * 1.2"))
.Missing(0)
);
protected override AggregationDictionary InitializerAggs =>
new PercentileRanksAggregation("commits_outlier", Field<Project>(p => p.NumberOfCommits))
{
Values = new List<double> { 15, 30 },
Method = new TDigestMethod
{
Compression = 200
},
Script = new InlineScript("doc['numberOfCommits'].value * 1.2"),
Missing = 0
};
protected override void ExpectResponse(ISearchResponse<Project> response)
{
response.ShouldBeValid();
var commitsOutlier = response.Aggregations.PercentileRanks("commits_outlier");
commitsOutlier.Should().NotBeNull();
commitsOutlier.Items.Should().NotBeNullOrEmpty();
foreach (var item in commitsOutlier.Items)
item.Should().NotBeNull();
}
}
// hide
public class PercentileRanksAggregationNonKeyedValuesUsageTests : AggregationUsageTestBase
{
public PercentileRanksAggregationNonKeyedValuesUsageTests(ReadOnlyCluster i, EndpointUsage usage) : base(i, usage) { }
protected override object AggregationJson => new
{
commits_outlier = new
{
percentile_ranks = new
{
field = "numberOfCommits",
values = new[] { 15.0, 30.0 },
tdigest = new
{
compression = 200.0
},
script = new
{
source = "doc['numberOfCommits'].value * 1.2",
},
missing = 0.0,
keyed = false
}
}
};
protected override Func<AggregationContainerDescriptor<Project>, IAggregationContainer> FluentAggs => a => a
.PercentileRanks("commits_outlier", pr => pr
.Field(p => p.NumberOfCommits)
.Values(15, 30)
.Method(m => m
.TDigest(td => td
.Compression(200)
)
)
.Script(ss => ss.Source("doc['numberOfCommits'].value * 1.2"))
.Missing(0)
.Keyed(false)
);
protected override AggregationDictionary InitializerAggs =>
new PercentileRanksAggregation("commits_outlier", Field<Project>(p => p.NumberOfCommits))
{
Values = new List<double> { 15, 30 },
Method = new TDigestMethod
{
Compression = 200
},
Script = new InlineScript("doc['numberOfCommits'].value * 1.2"),
Missing = 0,
Keyed = false
};
protected override void ExpectResponse(ISearchResponse<Project> response)
{
response.ShouldBeValid();
var commitsOutlier = response.Aggregations.PercentileRanks("commits_outlier");
commitsOutlier.Should().NotBeNull();
commitsOutlier.Items.Should().NotBeNullOrEmpty();
foreach (var item in commitsOutlier.Items)
item.Should().NotBeNull();
}
}
}
| 27.615385 | 120 | 0.6784 | [
"Apache-2.0"
] | Atharvpatel21/elasticsearch-net | tests/Tests/Aggregations/Metric/PercentileRanks/PercentileRanksAggregationUsageTests.cs | 3,949 | C# |
using System;
using MikhailKhalizev.Processor.x86.BinToCSharp;
namespace MikhailKhalizev.Max.Program
{
public partial class RawProgram
{
[MethodInfo("0x18_a922-e62d7335")]
public void Method_0018_a922()
{
ii(0x18_a922, 3); call(0x18_ab18, 0x1f3); /* call 0xab18 */
ii(0x18_a925, 2); if(jae(0x18_a92f, 8)) goto l_0x18_a92f; /* jae 0xa92f */
ii(0x18_a927, 3); call(0x18_a893, -0x97); /* call 0xa893 */
ii(0x18_a92a, 3); mov(ax, memw[ds, bx + 22]); /* mov ax, [bx+0x16] */
ii(0x18_a92d, 2); jmp(0x18_a999, 0x6a); goto l_0x18_a999; /* jmp 0xa999 */
l_0x18_a92f:
ii(0x18_a92f, 3); mov(dx, memw[ss, bp + 20]); /* mov dx, [bp+0x14] */
ii(0x18_a932, 3); mov(di, memw[ss, bp + 18]); /* mov di, [bp+0x12] */
ii(0x18_a935, 3); mov(ax, memw[ds, 0xa]); /* mov ax, [0xa] */
ii(0x18_a938, 3); mov(memw[ds, bx + 18], ax); /* mov [bx+0x12], ax */
ii(0x18_a93b, 3); mov(es, memw[ss, bp + 4]); /* mov es, [bp+0x4] */
l_0x18_a93e:
ii(0x18_a93e, 1); sti(); /* sti */
ii(0x18_a93f, 2); mov(cx, dx); /* mov cx, dx */
ii(0x18_a941, 4); cmp(cx, memw[ds, 0xe]); /* cmp cx, [0xe] */
ii(0x18_a945, 2); if(jbe(0x18_a94b, 4)) goto l_0x18_a94b; /* jbe 0xa94b */
ii(0x18_a947, 4); mov(cx, memw[ds, 0xe]); /* mov cx, [0xe] */
l_0x18_a94b:
ii(0x18_a94b, 3); mov(memw[ds, bx + 20], cx); /* mov [bx+0x14], cx */
ii(0x18_a94e, 3); mov(ax, memw[ss, bp + 22]); /* mov ax, [bp+0x16] */
ii(0x18_a951, 3); mov(memw[ds, bx + 22], ax); /* mov [bx+0x16], ax */
ii(0x18_a954, 1); push(cx); /* push cx */
ii(0x18_a955, 1); push(es); /* push es */
ii(0x18_a956, 3); call(0x18_a893, -0xc6); /* call 0xa893 */
ii(0x18_a959, 1); pop(es); /* pop es */
ii(0x18_a95a, 3); mov(ax, memw[ds, bx + 22]); /* mov ax, [bx+0x16] */
ii(0x18_a95d, 4); test(memb[ds, bx + 38], 1); /* test byte [bx+0x26], 0x1 */
ii(0x18_a961, 2); if(jnz(0x18_a999, 0x36)) goto l_0x18_a999;/* jnz 0xa999 */
ii(0x18_a963, 4); mov(si, memw[ds, 0xa]); /* mov si, [0xa] */
ii(0x18_a967, 2); mov(cx, ax); /* mov cx, ax */
ii(0x18_a969, 1); push(di); /* push di */
ii(0x18_a96a, 2); add(di, cx); /* add di, cx */
ii(0x18_a96c, 1); pop(di); /* pop di */
ii(0x18_a96d, 2); if(jae(0x18_a982, 0x13)) goto l_0x18_a982;/* jae 0xa982 */
ii(0x18_a96f, 2); if(jz(0x18_a982, 0x11)) goto l_0x18_a982;/* jz 0xa982 */
ii(0x18_a971, 2); mov(cx, di); /* mov cx, di */
ii(0x18_a973, 1); push(cx); /* push cx */
ii(0x18_a974, 2); neg(cx); /* neg cx */
ii(0x18_a976, 2); rep(() => movsb()); /* rep movsb */
ii(0x18_a978, 2); mov(cx, es); /* mov cx, es */
ii(0x18_a97a, 3); add(cx, 8); /* add cx, 0x8 */
ii(0x18_a97d, 2); mov(es, cx); /* mov es, cx */
ii(0x18_a97f, 1); pop(cx); /* pop cx */
ii(0x18_a980, 2); add(cx, ax); /* add cx, ax */
l_0x18_a982:
ii(0x18_a982, 2); shr(cx, 1); /* shr cx, 1 */
ii(0x18_a984, 2); rep(() => movsw()); /* rep movsw */
ii(0x18_a986, 2); rcl(cx, 1); /* rcl cx, 1 */
ii(0x18_a988, 2); rep(() => movsb()); /* rep movsb */
ii(0x18_a98a, 1); sti(); /* sti */
ii(0x18_a98b, 1); pop(cx); /* pop cx */
ii(0x18_a98c, 2); sub(dx, ax); /* sub dx, ax */
ii(0x18_a98e, 2); if(jz(0x18_a994, 4)) goto l_0x18_a994; /* jz 0xa994 */
ii(0x18_a990, 2); cmp(ax, cx); /* cmp ax, cx */
ii(0x18_a992, 2); if(jz(0x18_a93e, -0x56)) goto l_0x18_a93e;/* jz 0xa93e */
l_0x18_a994:
ii(0x18_a994, 3); mov(ax, memw[ss, bp + 20]); /* mov ax, [bp+0x14] */
ii(0x18_a997, 2); sub(ax, dx); /* sub ax, dx */
l_0x18_a999:
ii(0x18_a999, 3); mov(memw[ss, bp + 22], ax); /* mov [bp+0x16], ax */
ii(0x18_a99c, 3); jmp_func(0x18_a82f, -0x170); /* jmp 0xa82f */
}
}
}
| 71.4 | 102 | 0.385994 | [
"Apache-2.0"
] | mikhail-khalizev/max | source/MikhailKhalizev.Max/source/Program/Auto/z-0018-a922.cs | 5,355 | C# |
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Gat.Define
{
/// <summary>
/// BusinessLogic Find 方法的傳出結果。
/// </summary>
public class FindOutputResult
{
/// <summary>
/// Entity 資料表
/// </summary>
public DataTable Table { get; set; }
}
}
| 18.761905 | 44 | 0.614213 | [
"Apache-2.0"
] | Sway0308/GHM-PY | Library/Gat.Define/Args/FindOutputResult.cs | 418 | C# |
using System;
using Xplat_Core;
using System.Net.Mail;
namespace ImapClientAppShared
{
/// <summary>
/// View model for the mail details page.
/// </summary>
public class MailDetailsViewModel : ViewModelBase
{
public MailDetailsViewModel () : base()
{
}
/// <summary>
/// Gets or sets the message.
/// </summary>
public MailMessage Message
{
get
{
return base.GetProperty<MailMessage> ();
}
set
{
base.SetProperty (value);
}
}
/// <summary>
/// Gets the subject.
/// </summary>
public string Subject
{
get
{
return this.Message != null ? this.Message.Subject : string.Empty;
}
}
/// <summary>
/// Gets the body.
/// </summary>
public string Body
{
get
{
return this.Message != null ? this.Message.Body : string.Empty;
}
}
/// <summary>
/// Gets the sender address.
/// </summary>
public string From
{
get
{
return this.Message != null ? this.Message.From.Address : string.Empty;
}
}
}
}
| 16.409091 | 76 | 0.55771 | [
"MIT"
] | Samples-Playgrounds/Samples.Xamarin.Forms | diverse/forum-samples/beta-users/Krumelur/ImapClient/ImapClientAppShared/App/ViewModels/MailDetailsViewModel.cs | 1,083 | C# |
using PFSoftware.Extensions;
using PFSoftware.Extensions.DataTypeHelpers;
using PFSoftware.Extensions.Enums;
using PFSoftware.Finances.Models;
using PFSoftware.Finances.Models.Categories;
using PFSoftware.Finances.Models.Data;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
namespace PFSoftware.Finances.Views.Search
{
/// <summary>Interaction logic for SearchTransactionsWindow.xaml</summary>
public partial class SearchTransactionsPage
{
private readonly List<Account> _allAccounts = AppState.AllAccounts;
private readonly List<Category> _allCategories = AppState.AllCategories;
private Category _selectedCategory = new Category();
private Account _selectedAccount = new Account();
private List<FinancialTransaction> _matchingTransactions = new List<FinancialTransaction>(AppState.AllTransactions);
#region Data-Binding
/// <summary>Event that fires if a Property value has changed so that the UI can properly be updated.</summary>
public event PropertyChangedEventHandler PropertyChanged;
/// <summary>Invokes <see cref="PropertyChangedEventHandler"/> to update the UI when a Property value changes.</summary>
/// <param name="property">Name of Property whose value has changed</param>
private void NotifyPropertyChanged(string property) => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(property));
#endregion Data-Binding
/// <summary>Searches the list of transactions for specified criteria.</summary>
/// <returns>Return true if any items match</returns>
private bool SearchTransaction()
{
DateTime selectedDate = TransactionDate.SelectedDate != null ? DateTimeHelper.Parse(TransactionDate.SelectedDate) : DateTime.MinValue;
string payee = TxtPayee.Text.ToLower();
string majorCategory = CmbMajorCategory.SelectedIndex != -1 ? CmbMajorCategory.SelectedValue.ToString().ToLower() : "";
string minorCategory = CmbMinorCategory.SelectedIndex != -1 ? CmbMinorCategory.SelectedValue.ToString().ToLower() : "";
string memo = TxtMemo.Text.ToLower();
decimal outflow = DecimalHelper.Parse(TxtOutflow.Text.ToLower());
decimal inflow = DecimalHelper.Parse(TxtInflow.Text.ToLower());
string account = _selectedAccount.Name?.ToLower() ?? "";
if (selectedDate != DateTime.MinValue)
_matchingTransactions = _matchingTransactions.Where(transaction => transaction.Date == selectedDate).ToList();
if (!string.IsNullOrWhiteSpace(payee))
_matchingTransactions = _matchingTransactions.Where(transaction => transaction.Payee.ToLower().Contains(payee)).ToList();
if (!string.IsNullOrWhiteSpace(majorCategory))
_matchingTransactions = _matchingTransactions.Where(transaction => transaction.MajorCategory.ToLower() == majorCategory).ToList();
if (!string.IsNullOrWhiteSpace(minorCategory))
_matchingTransactions = _matchingTransactions.Where(transaction => transaction.MinorCategory.ToLower() == minorCategory).ToList();
if (!string.IsNullOrWhiteSpace(memo))
_matchingTransactions = _matchingTransactions.Where(transaction => transaction.Memo.ToLower().Contains(memo)).ToList();
if (outflow != 0M)
_matchingTransactions = _matchingTransactions.Where(transaction => transaction.Outflow == outflow).ToList();
if (inflow != 0M)
_matchingTransactions = _matchingTransactions.Where(transaction => transaction.Inflow == inflow).ToList();
if (!string.IsNullOrWhiteSpace(account))
_matchingTransactions = _matchingTransactions.Where(transaction => transaction.Account.ToLower() == account).ToList();
return _matchingTransactions.Count > 0;
}
/// <summary>Resets all values to default status.</summary>
private void Reset()
{
CmbMajorCategory.SelectedIndex = -1;
CmbMinorCategory.SelectedIndex = -1;
TxtMemo.Text = "";
TxtPayee.Text = "";
TxtInflow.Text = "";
TxtOutflow.Text = "";
CmbAccount.SelectedIndex = -1;
_matchingTransactions = new List<FinancialTransaction>(AppState.AllTransactions);
}
#region Button-Click Methods
private void BtnCancel_Click(object sender, RoutedEventArgs e) => ClosePage();
private void BtnSearch_Click(object sender, RoutedEventArgs e)
{
if (SearchTransaction())
{
CmbMinorCategory.Focus();
SearchResultsPage searchResultsWindow = new SearchResultsPage();
searchResultsWindow.LoadWindow(_matchingTransactions);
AppState.Navigate(searchResultsWindow);
}
else
AppState.DisplayNotification("No results found matching your search criteria.", "Personal Tracker");
}
private void BtnReset_Click(object sender, RoutedEventArgs e) => Reset();
#endregion Button-Click Methods
#region Text/Selection Changed
/// <summary>Checks whether or not the Submit button should be enabled.</summary>
private void TextChanged() => BtnSearch.IsEnabled =
TransactionDate.SelectedDate != null || CmbMajorCategory.SelectedIndex >= 0
|| CmbMinorCategory.SelectedIndex >= 0 || TxtPayee.Text.Length > 0
|| TxtInflow.Text.Length > 0 || TxtOutflow.Text.Length > 0
|| CmbAccount.SelectedIndex >= 0;
private void Txt_TextChanged(object sender, TextChangedEventArgs e) => TextChanged();
private void TxtInOutflow_TextChanged(object sender, TextChangedEventArgs e)
{
Functions.TextBoxTextChanged(sender, KeyType.Decimals);
TextChanged();
}
private void DatePicker_SelectedDateChanged(object sender, SelectionChangedEventArgs e) => TextChanged();
private void CmbCategory_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (CmbMajorCategory.SelectedIndex >= 0)
{
CmbMinorCategory.IsEnabled = true;
_selectedCategory = (Category)CmbMajorCategory.SelectedValue;
CmbMinorCategory.ItemsSource = _selectedCategory.MinorCategories;
}
else
{
CmbMinorCategory.IsEnabled = false;
_selectedCategory = new Category();
CmbMinorCategory.ItemsSource = _selectedCategory.MinorCategories;
}
TextChanged();
}
private void CmbAccount_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (CmbAccount.SelectedIndex >= 0)
_selectedAccount = (Account)CmbAccount.SelectedValue;
else
_selectedAccount = new Account();
TextChanged();
}
#endregion Text/Selection Changed
#region Page-Manipulation Methods
/// <summary>Closes the Page.</summary>
private void ClosePage() => AppState.GoBack();
public SearchTransactionsPage()
{
InitializeComponent();
CmbAccount.ItemsSource = _allAccounts;
CmbMajorCategory.ItemsSource = _allCategories;
CmbMinorCategory.ItemsSource = _selectedCategory.MinorCategories;
}
private void TxtInflowOutflow_PreviewKeyDown(object sender, KeyEventArgs e) => Functions.PreviewKeyDown(e, KeyType.Decimals);
private void Txt_GotFocus(object sender, RoutedEventArgs e) => Functions.TextBoxGotFocus(sender);
#endregion Page-Manipulation Methods
}
} | 44.803371 | 146 | 0.666834 | [
"MIT"
] | PFSoftware/Finances | Views/Search/SearchTransactionsPage.xaml.cs | 7,977 | C# |
using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WindowsInput {
internal static class SWITCHES {
static SWITCHES() {
try {
var value = Registry.GetValue(@"HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion", "ReleaseId", "")?.ToString() ?? "";
if(long.TryParse(value, out var V)) {
ReleaseId = V;
}
} catch {
}
if(ReleaseId > 1607) {
Windows10_AtLeast_v1607_Enabled = true;
}
}
public static long ReleaseId { get; private set; }
public static bool Windows10_AtLeast_v1607_Enabled { get; private set; }
}
}
| 22.888889 | 149 | 0.566748 | [
"MIT"
] | AlexCSDev/WindowsInput | WindowsInput/SWITCHES.cs | 826 | 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("12. Legendary Farming")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("12. Legendary Farming")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("e2a13a79-1f62-4c69-8714-33ca08922204")]
// 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.243243 | 84 | 0.74417 | [
"MIT"
] | AlexanderStanev/SoftUni | CSharpFundamentalsModule/CSharpAdvanced/SetsAndDictionaries/SetsAndDictionariesExercise/12. Legendary Farming/Properties/AssemblyInfo.cs | 1,418 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraTreeList.Nodes;
using Clifton.Tools.Data;
using Intertexti.Controls;
using Intertexti.DevExpressControls;
using Intertexti.Models;
namespace Intertexti.Views
{
public class OrphanNotecardsView : NotecardListView
{
public override string MenuName { get { return "mnuOrphanNotecards"; } }
public NotecardRecord SelectedRecord { get { return ((TreeListNode)TreeView.SelectedNode).Tag as NotecardRecord; } }
public override void RefreshView()
{
TreeView.Clear();
Model.ForEachNotecard(r =>
{
AddIfQualified(r);
});
base.RefreshView();
}
protected void AddIfQualified(NotecardRecord r)
{
// Notecards with a TOC entry or tags are not orphans, they will appear at the root level of the TOC.
if ((String.IsNullOrEmpty(r.TableOfContents)) && (Model.GetTags(r).Length == 0))
{
// Only add the notecard if it is not referenced and has no references.
if ((Model.GetReferences(r).Count == 0) && (Model.GetReferencedFrom(r).Count == 0))
{
TreeView.AddNode(null, new object[] { r.GetTitle(), r.DateCreated, r.DateModified, r.DateLastViewed }, r, r.IsChecked);
}
}
}
/// <summary>
/// If a TOC entry is created, the record is no longer an orphan.
/// If a TOC entry is blanked, the record may be an orphan if it has no references and no index.
/// </summary>
protected override void TableOfContentsChanged(NotecardRecord rec)
{
// If it has a TOC, then it's not orphaned.
if (!String.IsNullOrEmpty(rec.TableOfContents))
{
// If it was orphaned, we can now remove it. The orphan list is a 1:1 list of nodes and notecard records.
TreeView.Hierarchy().SingleOrDefault(n => n.Tag == rec).IfNotNull(n => TreeView.Nodes.Remove(n));
}
// If it doesn't have a TOC, and doesn't have an index...
else
{
TreeView.Hierarchy().SingleOrDefault(n => n.Tag == rec).IfNull(() => AddIfQualified(rec));
}
}
/// <summary>
/// Remove a notecard as an orphaned notecard if it has tags.
/// </summary>
protected override void TagsChanged(NotecardRecord rec)
{
if (Model.GetTags(rec).Length != 0)
{
TreeView.Hierarchy().SingleOrDefault(n => n.Tag == rec).IfNotNull(n => TreeView.Nodes.Remove(n));
}
else
{
TreeView.Hierarchy().SingleOrDefault(n => n.Tag == rec).IfNull(() => AddIfQualified(rec));
}
}
protected override void AssociationAdded(NotecardRecord parent, NotecardRecord child)
{
// Remove orphans that are associated.
// TODO: This does not test if we have associated notecards that, as a group, are orphaned!
TreeView.Hierarchy().SingleOrDefault(n => n.Tag == parent).IfNotNull(n => TreeView.Nodes.Remove(n));
TreeView.Hierarchy().SingleOrDefault(n => n.Tag == child).IfNotNull(n => TreeView.Nodes.Remove(n));
}
protected override void AssociationRemoved(NotecardRecord parent, NotecardRecord child)
{
AddIfQualified(parent);
AddIfQualified(child);
}
}
}
| 31.295918 | 124 | 0.69449 | [
"MIT"
] | cliftonm/intertexti | Views/OrphanNotecardsView.cs | 3,069 | C# |
namespace JoinRpg.Dal.Impl.Migrations
{
using System.Data.Entity.Migrations;
public partial class FieldsOrdering : DbMigration
{
public override void Up()
{
AddColumn("dbo.Projects", "ProjectFieldsOrdering", c => c.String());
AddColumn("dbo.ProjectCharacterFields", "ValuesOrdering", c => c.String());
DropColumn("dbo.ProjectCharacterFields", "Order");
}
public override void Down()
{
AddColumn("dbo.ProjectCharacterFields", "Order", c => c.Int(nullable: false));
DropColumn("dbo.ProjectCharacterFields", "ValuesOrdering");
DropColumn("dbo.Projects", "ProjectFieldsOrdering");
}
}
}
| 32.772727 | 90 | 0.613037 | [
"MIT"
] | HeyLaurelTestOrg/joinrpg-net | src/JoinRpg.Dal.Impl/Migrations/201601091848544_FieldsOrdering.cs | 721 | C# |
// Copyright(c) .NET Foundation.All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
namespace Microsoft.AspNetCore.Razor.Language
{
public static class DirectiveDescriptorBuilderExtensions
{
public static IDirectiveDescriptorBuilder AddMemberToken(
this IDirectiveDescriptorBuilder builder
)
{
return AddMemberToken(builder, name: null, description: null);
}
public static IDirectiveDescriptorBuilder AddMemberToken(
this IDirectiveDescriptorBuilder builder,
string name,
string description
)
{
if (builder == null)
{
throw new ArgumentNullException(nameof(builder));
}
builder.Tokens.Add(
DirectiveTokenDescriptor.CreateToken(
DirectiveTokenKind.Member,
optional: false,
name: name,
description: description
)
);
return builder;
}
public static IDirectiveDescriptorBuilder AddNamespaceToken(
this IDirectiveDescriptorBuilder builder
)
{
return AddNamespaceToken(builder, name: null, description: null);
}
public static IDirectiveDescriptorBuilder AddNamespaceToken(
this IDirectiveDescriptorBuilder builder,
string name,
string description
)
{
if (builder == null)
{
throw new ArgumentNullException(nameof(builder));
}
builder.Tokens.Add(
DirectiveTokenDescriptor.CreateToken(
DirectiveTokenKind.Namespace,
optional: false,
name: name,
description: description
)
);
return builder;
}
public static IDirectiveDescriptorBuilder AddStringToken(
this IDirectiveDescriptorBuilder builder
)
{
return AddStringToken(builder, name: null, description: null);
}
public static IDirectiveDescriptorBuilder AddStringToken(
this IDirectiveDescriptorBuilder builder,
string name,
string description
)
{
if (builder == null)
{
throw new ArgumentNullException(nameof(builder));
}
builder.Tokens.Add(
DirectiveTokenDescriptor.CreateToken(
DirectiveTokenKind.String,
optional: false,
name: name,
description: description
)
);
return builder;
}
public static IDirectiveDescriptorBuilder AddTypeToken(
this IDirectiveDescriptorBuilder builder
)
{
return AddTypeToken(builder, name: null, description: null);
}
public static IDirectiveDescriptorBuilder AddTypeToken(
this IDirectiveDescriptorBuilder builder,
string name,
string description
)
{
if (builder == null)
{
throw new ArgumentNullException(nameof(builder));
}
builder.Tokens.Add(
DirectiveTokenDescriptor.CreateToken(
DirectiveTokenKind.Type,
optional: false,
name: name,
description: description
)
);
return builder;
}
public static IDirectiveDescriptorBuilder AddAttributeToken(
this IDirectiveDescriptorBuilder builder
)
{
return AddAttributeToken(builder, name: null, description: null);
}
public static IDirectiveDescriptorBuilder AddAttributeToken(
this IDirectiveDescriptorBuilder builder,
string name,
string description
)
{
if (builder == null)
{
throw new ArgumentNullException(nameof(builder));
}
builder.Tokens.Add(
DirectiveTokenDescriptor.CreateToken(
DirectiveTokenKind.Attribute,
optional: false,
name: name,
description: description
)
);
return builder;
}
public static IDirectiveDescriptorBuilder AddBooleanToken(
this IDirectiveDescriptorBuilder builder
)
{
return AddBooleanToken(builder, name: null, description: null);
}
public static IDirectiveDescriptorBuilder AddBooleanToken(
this IDirectiveDescriptorBuilder builder,
string name,
string description
)
{
if (builder == null)
{
throw new ArgumentNullException(nameof(builder));
}
builder.Tokens.Add(
DirectiveTokenDescriptor.CreateToken(
DirectiveTokenKind.Boolean,
optional: false,
name: name,
description: description
)
);
return builder;
}
public static IDirectiveDescriptorBuilder AddOptionalMemberToken(
this IDirectiveDescriptorBuilder builder
)
{
return AddOptionalMemberToken(builder, name: null, description: null);
}
public static IDirectiveDescriptorBuilder AddOptionalMemberToken(
this IDirectiveDescriptorBuilder builder,
string name,
string description
)
{
if (builder == null)
{
throw new ArgumentNullException(nameof(builder));
}
builder.Tokens.Add(
DirectiveTokenDescriptor.CreateToken(
DirectiveTokenKind.Member,
optional: true,
name: name,
description: description
)
);
return builder;
}
public static IDirectiveDescriptorBuilder AddOptionalNamespaceToken(
this IDirectiveDescriptorBuilder builder
)
{
return AddOptionalNamespaceToken(builder, name: null, description: null);
}
public static IDirectiveDescriptorBuilder AddOptionalNamespaceToken(
this IDirectiveDescriptorBuilder builder,
string name,
string description
)
{
if (builder == null)
{
throw new ArgumentNullException(nameof(builder));
}
builder.Tokens.Add(
DirectiveTokenDescriptor.CreateToken(
DirectiveTokenKind.Namespace,
optional: true,
name: name,
description: description
)
);
return builder;
}
public static IDirectiveDescriptorBuilder AddOptionalStringToken(
this IDirectiveDescriptorBuilder builder
)
{
return AddOptionalStringToken(builder, name: null, description: null);
}
public static IDirectiveDescriptorBuilder AddOptionalStringToken(
this IDirectiveDescriptorBuilder builder,
string name,
string description
)
{
if (builder == null)
{
throw new ArgumentNullException(nameof(builder));
}
builder.Tokens.Add(
DirectiveTokenDescriptor.CreateToken(
DirectiveTokenKind.String,
optional: true,
name: name,
description: description
)
);
return builder;
}
public static IDirectiveDescriptorBuilder AddOptionalTypeToken(
this IDirectiveDescriptorBuilder builder
)
{
return AddOptionalTypeToken(builder, name: null, description: null);
}
public static IDirectiveDescriptorBuilder AddOptionalTypeToken(
this IDirectiveDescriptorBuilder builder,
string name,
string description
)
{
if (builder == null)
{
throw new ArgumentNullException(nameof(builder));
}
builder.Tokens.Add(
DirectiveTokenDescriptor.CreateToken(
DirectiveTokenKind.Type,
optional: true,
name: name,
description: description
)
);
return builder;
}
public static IDirectiveDescriptorBuilder AddOptionalAttributeToken(
this IDirectiveDescriptorBuilder builder
)
{
return AddOptionalAttributeToken(builder, name: null, description: null);
}
public static IDirectiveDescriptorBuilder AddOptionalAttributeToken(
this IDirectiveDescriptorBuilder builder,
string name,
string description
)
{
if (builder == null)
{
throw new ArgumentNullException(nameof(builder));
}
builder.Tokens.Add(
DirectiveTokenDescriptor.CreateToken(
DirectiveTokenKind.Attribute,
optional: true,
name: name,
description: description
)
);
return builder;
}
}
}
| 29.366569 | 111 | 0.527162 | [
"Apache-2.0"
] | belav/aspnetcore | src/Razor/Microsoft.AspNetCore.Razor.Language/src/DirectiveDescriptorBuilderExtensions.cs | 10,016 | C# |
/*
* Copyright (c) Citrix Systems, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1) Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2) Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
namespace XenAPI
{
public enum task_status_type
{
pending, success, failure, cancelling, cancelled, unknown
}
public static class task_status_type_helper
{
public static string ToString(task_status_type x)
{
switch (x)
{
case task_status_type.pending:
return "pending";
case task_status_type.success:
return "success";
case task_status_type.failure:
return "failure";
case task_status_type.cancelling:
return "cancelling";
case task_status_type.cancelled:
return "cancelled";
default:
return "unknown";
}
}
}
}
| 36.546875 | 71 | 0.642582 | [
"BSD-2-Clause"
] | ChrisH4rding/xenadmin | XenModel/XenAPI/task_status_type.cs | 2,339 | C# |
using System.Collections.Generic;
using System.Data;
using System.Linq;
using Perpetuum.Data;
using Perpetuum.EntityFramework;
using Perpetuum.ExportedTypes;
using Perpetuum.Log;
using Perpetuum.Services.ProductionEngine.CalibrationPrograms;
namespace Perpetuum.Services.ProductionEngine
{
public class ProductionDataAccess : IProductionDataAccess
{
private readonly IEntityDefaultReader _entityDefaultReader;
private IDictionary<int, int> _prototypes;
private IDictionary<int, ItemResearchLevel> _researchlevels;
private ILookup<int, ProductionComponent> _productionComponents;
private IDictionary<CategoryFlags, double> _productionDurations;
private IDictionary<int, CalibrationDefault> _calibrationDefaults;
private IDictionary<CategoryFlags, ProductionDecalibration> _productionDecalibrations;
private IProductionCostReader _productionCostReader;
public ProductionDataAccess(IEntityDefaultReader entityDefaultReader, IProductionCostReader costReader)
{
_entityDefaultReader = entityDefaultReader;
_productionCostReader = costReader;
}
public void Init()
{
_prototypes = Database.CreateCache<int, int>("prototypes", k.definition, "prototype");
_researchlevels = Database.CreateCache<int, ItemResearchLevel>("itemresearchlevels", k.definition, r =>
{
var level = new ItemResearchLevel
{
definition = r.GetValue<int>(k.definition),
researchLevel = r.GetValue<int>(k.researchLevel.ToLower()),
calibrationProgramDefinition = r.GetValue<int?>(k.calibrationProgram.ToLower())
};
return level;
}, ItemResearchLevelFilter);
_productionComponents = Database.CreateLookupCache<int, ProductionComponent>("components", k.definition, r =>
{
var ed = _entityDefaultReader.Get(r.GetValue<int>(k.componentDefinition.ToLower()));
var amount = r.GetValue<int>(k.componentAmount.ToLower());
return new ProductionComponent(ed, amount);
}, r => _entityDefaultReader.Exists(r.GetValue<int>(k.definition)));
_productionDurations = Database.CreateCache<CategoryFlags, double>("productionduration", k.category, "durationmodifier");
_calibrationDefaults = Database.CreateCache<int, CalibrationDefault>("calibrationdefaults", k.definition, r => new CalibrationDefault(r));
_productionDecalibrations = Database.CreateCache<CategoryFlags, ProductionDecalibration>("productiondecalibration", "categoryflag", r =>
{
var distorsionMin = r.GetValue<double>(k.distorsionMin.ToLower());
var distorsionMax = r.GetValue<double>(k.distorsionMax.ToLower());
var decrease = r.GetValue<double>("decrease");
return new ProductionDecalibration(distorsionMin, distorsionMax, decrease);
});
_researchlevels = Database.CreateCache<int, ItemResearchLevel>("itemresearchlevels", k.definition, r =>
{
var level = new ItemResearchLevel
{
definition = r.GetValue<int>(k.definition),
researchLevel = r.GetValue<int>(k.researchLevel.ToLower()),
calibrationProgramDefinition = r.GetValue<int?>(k.calibrationProgram.ToLower())
};
return level;
}, ItemResearchLevelFilter);
ProductionCost = new Dictionary<int, double>();
foreach (var ed in EntityDefault.All)
{
ProductionCost.Add(ed.Definition, _productionCostReader.GetProductionCostModByED(ed));
}
}
public bool ItemResearchLevelFilter(IDataRecord record)
{
var definition = record.GetValue<int>(k.definition);
if (!_entityDefaultReader.Exists(definition) || !record.GetValue<bool>(k.enabled))
{
return false;
}
var calibrationPrg = record.GetValue<int?>(k.calibrationProgram.ToLower());
if (calibrationPrg == null)
return true;
var cprgED = _entityDefaultReader.Get((int)calibrationPrg);
if (cprgED.CategoryFlags.IsCategory(CategoryFlags.cf_calibration_programs))
return true;
Logger.Error("illegal calibration program was defined for definition:" + definition + " calibration program def:" + cprgED.Name + " " + cprgED.Definition);
return false;
}
public IDictionary<int, int> Prototypes => _prototypes;
public IDictionary<int, ItemResearchLevel> ResearchLevels => _researchlevels;
public ILookup<int, ProductionComponent> ProductionComponents => _productionComponents;
public IDictionary<CategoryFlags, double> ProductionDurations => _productionDurations;
public IDictionary<int, CalibrationDefault> CalibrationDefaults => _calibrationDefaults;
public IDictionary<int, double> ProductionCost { get; private set; }
public ProductionDecalibration GetDecalibration(int targetDefinition)
{
if (!_entityDefaultReader.TryGet(targetDefinition, out EntityDefault ed))
{
Logger.Error("consistency error! definition was not found for production line. definition:" + targetDefinition);
return ProductionDecalibration.Default;
}
return GetDecalibration(ed);
}
public ProductionDecalibration GetDecalibration(EntityDefault target)
{
foreach (var flagInTree in target.CategoryFlags.GetCategoryFlagsTree())
{
if (_productionDecalibrations.TryGetValue(flagInTree, out ProductionDecalibration productionDecalibration))
return productionDecalibration;
}
return ProductionDecalibration.Default;
}
}
} | 47.695313 | 167 | 0.655201 | [
"MIT"
] | OpenPerpetuum/PerpetuumServer | src/Perpetuum/Services/ProductionEngine/ProductionDataAccess.cs | 6,105 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Assets.Weapons;
namespace Assets.Weapons
{
public class MeleeWeapon : Weapon
{
/// <summary>
///
/// </summary>
public override void Attack()
{
Debug.Log("Attacking with melee weapon");
}
}
}
| 19.473684 | 54 | 0.554054 | [
"MIT"
] | TanguyHerbron/ShapeScape | Assets/Script/Weapons/Melee Weapons/MeleeWeapon.cs | 372 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.