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 Amazon;
using Amazon.S3;
using Amazon.S3.Model;
using DataProcessor;
using DataProcessor.Contracts;
using DataProcessor.DataSource.InStream;
using DataProcessor.InputDefinitionFile;
using DataProcessor.InputDefinitionFile.Models;
using DataProcessor.Models;
using DataProcessor.ProcessorDefinition;
using DataProcessor.ProcessorDefinition.Models;
using Microsoft.Extensions.Configuration;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Threading.Tasks;
using static Amazon.S3.Util.S3EventNotification;
namespace IntakerAWSLambda
{
public class FileProcessorConfiguration
{
public string BucketIntakerOut { get; set; }
public string BucketIntakerFileSpecs { get; set; }
}
public class FileProcessor
{
private readonly FileProcessorConfiguration _config;
private readonly IFileProcessorLogger _logger;
public FileProcessor(IConfiguration configuration, IFileProcessorLogger logger)
{
_logger = logger;
_config = configuration.GetSection(AppConstants.CONFIG_SECTION_FILE_PROCESSOR).Get<FileProcessorConfiguration>();
LogObject("Configuration - FileProcessor:", _config);
}
public async Task ProcessFileAsync(S3EventNotificationRecord record)
{
_logger.Log($"Processing file '{record.S3.Object.Key}' from bucket '{record.S3.Bucket.Name}'");
var intakerFileContent = await LoadIntakerFileAsync(record);
_logger.Log($"Intaker file content:{Environment.NewLine}{intakerFileContent}");
var intakerVersion = GetFrameworkVersionFromIntakerFileContent(intakerFileContent);
switch (intakerVersion)
{
case "1.0":
await ProcessFileWithVersion10Async(intakerFileContent, record);
break;
default:
throw new Exception($"Intaker FrameworkVersion '{intakerVersion}' not supported");
}
await ExecuteAsync(() => DeleteFileFromBucketAsync(record));
}
private async Task ProcessFileWithVersion10Async(string intakerFileContent, S3EventNotificationRecord record)
{
InputDefinitionFile10 inputDefinitionFile = null;
FileProcessorDefinition10 fileProcessorDefinition = null;
Execute(() =>
{
inputDefinitionFile = FileLoader.LoadFromXml<InputDefinitionFile10>(intakerFileContent);
fileProcessorDefinition = FileProcessorDefinitionBuilder.CreateFileProcessorDefinition(inputDefinitionFile);
});
ParsedData10 parsed = null;
await ExecuteAsync(async () =>
{
var regionEndpoint = RegionEndpoint.GetBySystemName(record.AwsRegion);
using var client = new AmazonS3Client(regionEndpoint);
var request = new GetObjectRequest
{
BucketName = record.S3.Bucket.Name,
Key = record.S3.Object.Key
};
using var response = await client.GetObjectAsync(request);
var dataSource = BuildDataSource(response.ResponseStream, inputDefinitionFile);
var processor = new ParsedDataProcessor10(dataSource, fileProcessorDefinition);
parsed = processor.Process();
if (record.S3.Object.Size < 5000)
{
LogObject("Parsed Data:", parsed);
}
else
{
_logger.Log($"File is too large to log the parsed data");
}
});
var outputFilename = $"{Path.GetFileNameWithoutExtension(record.S3.Object.Key)}-{DateTime.Now:yyyyMMdd-HHmmss}.json";
await ExecuteAsync(() => CreateOutputFileAsync(record, outputFilename, parsed.DataRows));
}
private async Task CreateOutputFileAsync(S3EventNotificationRecord sourceRecord, string outputFilename, IList<Row> rows)
{
var sb = new StringBuilder();
sb.AppendLine("[");
foreach(var row in rows)
{
sb.AppendLine(row.Json);
}
sb.AppendLine("]");
var contentBody = sb.ToString();
var request = new PutObjectRequest
{
BucketName = _config.BucketIntakerOut,
Key = outputFilename,
ContentBody = contentBody
};
_logger.Log($"Creating file '{request.Key}' in bucket '{request.BucketName}'");
var regionEndpoint = RegionEndpoint.GetBySystemName(sourceRecord.AwsRegion);
using var client = new AmazonS3Client(regionEndpoint);
await client.PutObjectAsync(request);
}
private static IDataSource<ParserContext10> BuildDataSource(Stream stream, InputDefinitionFile10 inputDefinition)
{
var streamDataSourceConfig = new StreamDataSourceConfig
{
Delimiter = inputDefinition.Delimiter,
HasFieldsEnclosedInQuotes = inputDefinition.HasFieldsEnclosedInQuotes,
CommentedOutIndicator = inputDefinition.CommentedOutIndicator
};
return new StreamDataSource<ParserContext10>(streamDataSourceConfig, stream);
}
private string GetFrameworkVersionFromIntakerFileContent(string intakerFileContent)
{
var inputDefinitionFrameworkVersion = FileLoader.LoadFromXml<InputDefinitionFrameworkVersion>(intakerFileContent);
return inputDefinitionFrameworkVersion.FrameworkVersion;
}
private async Task<string> LoadIntakerFileAsync(S3EventNotificationRecord record)
{
var intakerFile = BuildFileSpecsName(record.S3.Object.Key);
var regionEndpoint = RegionEndpoint.GetBySystemName(record.AwsRegion);
using var client = new AmazonS3Client(regionEndpoint);
var request = new GetObjectRequest { BucketName = _config.BucketIntakerFileSpecs, Key = intakerFile };
_logger.Log($"Getting intaker file '{request.Key}' from bucket '{request.BucketName}'");
using var response = await client.GetObjectAsync(request);
using var reader = new StreamReader(response.ResponseStream);
return reader.ReadToEnd();
}
private string BuildFileSpecsName(string filename)
{
var temp = Path.GetFileNameWithoutExtension(filename);
var ext = Path.GetExtension(temp);
if (string.IsNullOrWhiteSpace(ext))
{
throw new Exception($"Invalid file name format '{filename}'");
}
return $"intaker{ext}.xml";
}
private async Task DeleteFileFromBucketAsync(S3EventNotificationRecord record)
{
RegionEndpoint regionEndpoint = RegionEndpoint.GetBySystemName(record.AwsRegion);
using var client = new AmazonS3Client(regionEndpoint);
var request = new DeleteObjectRequest
{
BucketName = record.S3.Bucket.Name,
Key = record.S3.Object.Key
};
_logger.Log($"Deleting file '{request.Key}' from bucket '{request.BucketName}'");
await client.DeleteObjectAsync(request);
}
private Task ExecuteAsync(Func<Task> func, [System.Runtime.CompilerServices.CallerMemberName] string caller = "")
{
try
{
return func.Invoke();
}
catch (AmazonS3Exception ex)
{
_logger.Log($"{caller} - Error encountered on server. {ex}");
throw;
}
catch (Exception ex)
{
_logger.Log($"{caller} - Unknown encountered on server. {ex}");
throw;
}
}
private void Execute(Action action, [System.Runtime.CompilerServices.CallerMemberName] string caller = "")
{
try
{
action.Invoke();
}
catch (AmazonS3Exception ex)
{
_logger.Log($"{caller} - Error encountered on server. {ex}");
throw;
}
catch (Exception ex)
{
_logger.Log($"{caller} - Unknown encountered on server. {ex}");
throw;
}
}
private void LogObject(string message, object obj)
{
_logger.Log($"{message}{Environment.NewLine}{JsonConvert.SerializeObject(obj)}");
}
}
}
| 37.412766 | 129 | 0.61101 | [
"MIT"
] | dbsafe/intaker-demo | IntakerDemos/IntakerAWSLambda/FileProcessor.cs | 8,794 | C# |
using AdventOfCode.Tools.TopologicalOrder;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AdventOfCode.Days.Tools.Day7
{
class Bag: TopoItem
{
public override string Name { get; set; }
public Dictionary<string, int> ContainedBags { get; set; } = new Dictionary<string, int>();
public override Dictionary<string, int> Dependencies { get => ContainedBags; set => ContainedBags = value; }
public override string ToString()
{
return Name;
}
}
}
| 27.045455 | 116 | 0.670588 | [
"MIT"
] | Crazymine-hub/AdventOfCode | AoC2020/Days/Tools/Day7/Bag.cs | 597 | C# |
namespace KompasPlugin
{
public enum Parameters
{
BoltBodyHeight,
InnerRingDiameter,
OuterRingDiameter,
ThreadDiameter,
HeadDiameter,
BoltHeadHeight,
}
} | 14.083333 | 23 | 0.763314 | [
"MIT"
] | Cherries-beep/SAPR | KompasPlugin/KompasPlugin/Parameters.cs | 171 | C# |
using System;
using System.Globalization;
namespace TimeApprox.PRC
{
public sealed class ApproxTime
{
public static Tier DefaultTier
{ get { return Tier.DayTime; } }
private string language;
public ApproxTime()
{
this.language = "cs";
}
public ApproxTime(string language) {
this.language = language;
}
private const string Dunno = "dunno";
private static string[] _hours = new string[] {
"time-0",
"time-1",
"time-2",
"time-3",
"time-4",
"time-5",
"time-6",
"time-7",
"time-8",
"time-9",
"time-10",
"time-11",
"time-12",
"time-13",
"time-14",
"time-15",
"time-16",
"time-17",
"time-18",
"time-19",
"time-20",
"time-21",
"time-22",
"time-23"
};
private static string[] _quarterHours = new string[] {
"time-q-5",
"time-q-10",
"time-q-15",
"time-q-20",
"time-q-25",
"time-q-30",
"time-q-35",
"time-q-40",
"time-q-45",
"time-q-50",
"time-q-55",
"time-q-60"
};
public string GetCurrentApproxTime(int year, int month, int day, int hour, int minute, Tier tier)
{
return GetCurrentApproxTime(new DateTimeOffset(
year, month, day, hour, minute, 0, new TimeSpan()), tier);
}
public string GetCurrentApproxTime(DateTimeOffset time, Tier tier)
{
int hour = time.Hour;
int minutes = time.Minute;
switch (tier)
{
// 2014
case Tier.Year:
return time.ToString("yyyy", new CultureInfo(language));
// červen
case Tier.Month:
return time.ToString("MMMM", new CultureInfo(language));
// neděle
case Tier.DayInWeek:
return time.ToString("dddd", new CultureInfo(language));
// noc
case Tier.DayTime:
string code;
if (6 <= hour && hour < 9)
code = "morning";
else if (9 <= hour && hour < 11)
code = "beforenoon";
else if (11 <= hour && hour < 13)
code = "lunchtime";
else if (13 <= hour && hour < 18)
code = "afternoon";
else if (18 <= hour && hour < 22)
code = "evening";
else
code = "night";
return LocalizedTimeCodes.GetTimeName(code);
// pět
case Tier.Hour:
if (minutes > 45)
hour = (hour + 1) % 24;
return LocalizedTimeCodes.GetTimeName(_hours[hour]);
case Tier.QuarterHour:
int size = _quarterHours.Length;
double idx = ((minutes / 60d) * size) - 0.5;
idx = idx < 0 ? idx + size : idx;
return LocalizedTimeCodes.GetTimeName(_quarterHours[(int)idx]);
// na sekundy - systémový čas
case Tier.SystemClock:
return time.ToString("HH:mm:ss", new CultureInfo(language));
// na desetiny sekundy - NTP :-)
case Tier.PreciseNtp:
return time.ToString("HH:mm:ss.f z", new CultureInfo(language));
// někdy... :D
case Tier.Dunno:
default:
return LocalizedTimeCodes.GetTimeName(Dunno);
}
}
}
}
| 30.765152 | 105 | 0.415907 | [
"MIT"
] | PaulosV/pribliznycas-windows | TimeApprox.PRC/ApproxTime.cs | 4,070 | C# |
// mksysnum_openbsd.pl
// Code generated by the command above; DO NOT EDIT.
// +build arm,openbsd
// package syscall -- go2cs converted at 2020 October 09 05:04:21 UTC
// import "syscall" ==> using syscall = go.syscall_package
// Original source: C:\Go\src\syscall\zsysnum_openbsd_arm.go
using static go.builtin;
namespace go
{
public static partial class syscall_package
{
public static readonly long SYS_EXIT = (long)1L; // { void sys_exit(int rval); }
public static readonly long SYS_FORK = (long)2L; // { int sys_fork(void); }
public static readonly long SYS_READ = (long)3L; // { ssize_t sys_read(int fd, void *buf, size_t nbyte); }
public static readonly long SYS_WRITE = (long)4L; // { ssize_t sys_write(int fd, const void *buf, \
public static readonly long SYS_OPEN = (long)5L; // { int sys_open(const char *path, \
public static readonly long SYS_CLOSE = (long)6L; // { int sys_close(int fd); }
public static readonly long SYS_GETENTROPY = (long)7L; // { int sys_getentropy(void *buf, size_t nbyte); }
public static readonly long SYS___TFORK = (long)8L; // { int sys___tfork(const struct __tfork *param, \
public static readonly long SYS_LINK = (long)9L; // { int sys_link(const char *path, const char *link); }
public static readonly long SYS_UNLINK = (long)10L; // { int sys_unlink(const char *path); }
public static readonly long SYS_WAIT4 = (long)11L; // { pid_t sys_wait4(pid_t pid, int *status, \
public static readonly long SYS_CHDIR = (long)12L; // { int sys_chdir(const char *path); }
public static readonly long SYS_FCHDIR = (long)13L; // { int sys_fchdir(int fd); }
public static readonly long SYS_MKNOD = (long)14L; // { int sys_mknod(const char *path, mode_t mode, \
public static readonly long SYS_CHMOD = (long)15L; // { int sys_chmod(const char *path, mode_t mode); }
public static readonly long SYS_CHOWN = (long)16L; // { int sys_chown(const char *path, uid_t uid, \
public static readonly long SYS_OBREAK = (long)17L; // { int sys_obreak(char *nsize); } break
public static readonly long SYS_GETDTABLECOUNT = (long)18L; // { int sys_getdtablecount(void); }
public static readonly long SYS_GETRUSAGE = (long)19L; // { int sys_getrusage(int who, \
public static readonly long SYS_GETPID = (long)20L; // { pid_t sys_getpid(void); }
public static readonly long SYS_MOUNT = (long)21L; // { int sys_mount(const char *type, const char *path, \
public static readonly long SYS_UNMOUNT = (long)22L; // { int sys_unmount(const char *path, int flags); }
public static readonly long SYS_SETUID = (long)23L; // { int sys_setuid(uid_t uid); }
public static readonly long SYS_GETUID = (long)24L; // { uid_t sys_getuid(void); }
public static readonly long SYS_GETEUID = (long)25L; // { uid_t sys_geteuid(void); }
public static readonly long SYS_PTRACE = (long)26L; // { int sys_ptrace(int req, pid_t pid, caddr_t addr, \
public static readonly long SYS_RECVMSG = (long)27L; // { ssize_t sys_recvmsg(int s, struct msghdr *msg, \
public static readonly long SYS_SENDMSG = (long)28L; // { ssize_t sys_sendmsg(int s, \
public static readonly long SYS_RECVFROM = (long)29L; // { ssize_t sys_recvfrom(int s, void *buf, size_t len, \
public static readonly long SYS_ACCEPT = (long)30L; // { int sys_accept(int s, struct sockaddr *name, \
public static readonly long SYS_GETPEERNAME = (long)31L; // { int sys_getpeername(int fdes, struct sockaddr *asa, \
public static readonly long SYS_GETSOCKNAME = (long)32L; // { int sys_getsockname(int fdes, struct sockaddr *asa, \
public static readonly long SYS_ACCESS = (long)33L; // { int sys_access(const char *path, int amode); }
public static readonly long SYS_CHFLAGS = (long)34L; // { int sys_chflags(const char *path, u_int flags); }
public static readonly long SYS_FCHFLAGS = (long)35L; // { int sys_fchflags(int fd, u_int flags); }
public static readonly long SYS_SYNC = (long)36L; // { void sys_sync(void); }
public static readonly long SYS_STAT = (long)38L; // { int sys_stat(const char *path, struct stat *ub); }
public static readonly long SYS_GETPPID = (long)39L; // { pid_t sys_getppid(void); }
public static readonly long SYS_LSTAT = (long)40L; // { int sys_lstat(const char *path, struct stat *ub); }
public static readonly long SYS_DUP = (long)41L; // { int sys_dup(int fd); }
public static readonly long SYS_FSTATAT = (long)42L; // { int sys_fstatat(int fd, const char *path, \
public static readonly long SYS_GETEGID = (long)43L; // { gid_t sys_getegid(void); }
public static readonly long SYS_PROFIL = (long)44L; // { int sys_profil(caddr_t samples, size_t size, \
public static readonly long SYS_KTRACE = (long)45L; // { int sys_ktrace(const char *fname, int ops, \
public static readonly long SYS_SIGACTION = (long)46L; // { int sys_sigaction(int signum, \
public static readonly long SYS_GETGID = (long)47L; // { gid_t sys_getgid(void); }
public static readonly long SYS_SIGPROCMASK = (long)48L; // { int sys_sigprocmask(int how, sigset_t mask); }
public static readonly long SYS_GETLOGIN = (long)49L; // { int sys_getlogin(char *namebuf, u_int namelen); }
public static readonly long SYS_SETLOGIN = (long)50L; // { int sys_setlogin(const char *namebuf); }
public static readonly long SYS_ACCT = (long)51L; // { int sys_acct(const char *path); }
public static readonly long SYS_SIGPENDING = (long)52L; // { int sys_sigpending(void); }
public static readonly long SYS_FSTAT = (long)53L; // { int sys_fstat(int fd, struct stat *sb); }
public static readonly long SYS_IOCTL = (long)54L; // { int sys_ioctl(int fd, \
public static readonly long SYS_REBOOT = (long)55L; // { int sys_reboot(int opt); }
public static readonly long SYS_REVOKE = (long)56L; // { int sys_revoke(const char *path); }
public static readonly long SYS_SYMLINK = (long)57L; // { int sys_symlink(const char *path, \
public static readonly long SYS_READLINK = (long)58L; // { ssize_t sys_readlink(const char *path, \
public static readonly long SYS_EXECVE = (long)59L; // { int sys_execve(const char *path, \
public static readonly long SYS_UMASK = (long)60L; // { mode_t sys_umask(mode_t newmask); }
public static readonly long SYS_CHROOT = (long)61L; // { int sys_chroot(const char *path); }
public static readonly long SYS_GETFSSTAT = (long)62L; // { int sys_getfsstat(struct statfs *buf, size_t bufsize, \
public static readonly long SYS_STATFS = (long)63L; // { int sys_statfs(const char *path, \
public static readonly long SYS_FSTATFS = (long)64L; // { int sys_fstatfs(int fd, struct statfs *buf); }
public static readonly long SYS_FHSTATFS = (long)65L; // { int sys_fhstatfs(const fhandle_t *fhp, \
public static readonly long SYS_VFORK = (long)66L; // { int sys_vfork(void); }
public static readonly long SYS_GETTIMEOFDAY = (long)67L; // { int sys_gettimeofday(struct timeval *tp, \
public static readonly long SYS_SETTIMEOFDAY = (long)68L; // { int sys_settimeofday(const struct timeval *tv, \
public static readonly long SYS_SETITIMER = (long)69L; // { int sys_setitimer(int which, \
public static readonly long SYS_GETITIMER = (long)70L; // { int sys_getitimer(int which, \
public static readonly long SYS_SELECT = (long)71L; // { int sys_select(int nd, fd_set *in, fd_set *ou, \
public static readonly long SYS_KEVENT = (long)72L; // { int sys_kevent(int fd, \
public static readonly long SYS_MUNMAP = (long)73L; // { int sys_munmap(void *addr, size_t len); }
public static readonly long SYS_MPROTECT = (long)74L; // { int sys_mprotect(void *addr, size_t len, \
public static readonly long SYS_MADVISE = (long)75L; // { int sys_madvise(void *addr, size_t len, \
public static readonly long SYS_UTIMES = (long)76L; // { int sys_utimes(const char *path, \
public static readonly long SYS_FUTIMES = (long)77L; // { int sys_futimes(int fd, \
public static readonly long SYS_MINCORE = (long)78L; // { int sys_mincore(void *addr, size_t len, \
public static readonly long SYS_GETGROUPS = (long)79L; // { int sys_getgroups(int gidsetsize, \
public static readonly long SYS_SETGROUPS = (long)80L; // { int sys_setgroups(int gidsetsize, \
public static readonly long SYS_GETPGRP = (long)81L; // { int sys_getpgrp(void); }
public static readonly long SYS_SETPGID = (long)82L; // { int sys_setpgid(pid_t pid, pid_t pgid); }
public static readonly long SYS_SENDSYSLOG = (long)83L; // { int sys_sendsyslog(const void *buf, size_t nbyte); }
public static readonly long SYS_UTIMENSAT = (long)84L; // { int sys_utimensat(int fd, const char *path, \
public static readonly long SYS_FUTIMENS = (long)85L; // { int sys_futimens(int fd, \
public static readonly long SYS_CLOCK_GETTIME = (long)87L; // { int sys_clock_gettime(clockid_t clock_id, \
public static readonly long SYS_CLOCK_SETTIME = (long)88L; // { int sys_clock_settime(clockid_t clock_id, \
public static readonly long SYS_CLOCK_GETRES = (long)89L; // { int sys_clock_getres(clockid_t clock_id, \
public static readonly long SYS_DUP2 = (long)90L; // { int sys_dup2(int from, int to); }
public static readonly long SYS_NANOSLEEP = (long)91L; // { int sys_nanosleep(const struct timespec *rqtp, \
public static readonly long SYS_FCNTL = (long)92L; // { int sys_fcntl(int fd, int cmd, ... void *arg); }
public static readonly long SYS_ACCEPT4 = (long)93L; // { int sys_accept4(int s, struct sockaddr *name, \
public static readonly long SYS___THRSLEEP = (long)94L; // { int sys___thrsleep(const volatile void *ident, \
public static readonly long SYS_FSYNC = (long)95L; // { int sys_fsync(int fd); }
public static readonly long SYS_SETPRIORITY = (long)96L; // { int sys_setpriority(int which, id_t who, int prio); }
public static readonly long SYS_SOCKET = (long)97L; // { int sys_socket(int domain, int type, int protocol); }
public static readonly long SYS_CONNECT = (long)98L; // { int sys_connect(int s, const struct sockaddr *name, \
public static readonly long SYS_GETDENTS = (long)99L; // { int sys_getdents(int fd, void *buf, size_t buflen); }
public static readonly long SYS_GETPRIORITY = (long)100L; // { int sys_getpriority(int which, id_t who); }
public static readonly long SYS_PIPE2 = (long)101L; // { int sys_pipe2(int *fdp, int flags); }
public static readonly long SYS_DUP3 = (long)102L; // { int sys_dup3(int from, int to, int flags); }
public static readonly long SYS_SIGRETURN = (long)103L; // { int sys_sigreturn(struct sigcontext *sigcntxp); }
public static readonly long SYS_BIND = (long)104L; // { int sys_bind(int s, const struct sockaddr *name, \
public static readonly long SYS_SETSOCKOPT = (long)105L; // { int sys_setsockopt(int s, int level, int name, \
public static readonly long SYS_LISTEN = (long)106L; // { int sys_listen(int s, int backlog); }
public static readonly long SYS_CHFLAGSAT = (long)107L; // { int sys_chflagsat(int fd, const char *path, \
public static readonly long SYS_PPOLL = (long)109L; // { int sys_ppoll(struct pollfd *fds, \
public static readonly long SYS_PSELECT = (long)110L; // { int sys_pselect(int nd, fd_set *in, fd_set *ou, \
public static readonly long SYS_SIGSUSPEND = (long)111L; // { int sys_sigsuspend(int mask); }
public static readonly long SYS_GETSOCKOPT = (long)118L; // { int sys_getsockopt(int s, int level, int name, \
public static readonly long SYS_READV = (long)120L; // { ssize_t sys_readv(int fd, \
public static readonly long SYS_WRITEV = (long)121L; // { ssize_t sys_writev(int fd, \
public static readonly long SYS_KILL = (long)122L; // { int sys_kill(int pid, int signum); }
public static readonly long SYS_FCHOWN = (long)123L; // { int sys_fchown(int fd, uid_t uid, gid_t gid); }
public static readonly long SYS_FCHMOD = (long)124L; // { int sys_fchmod(int fd, mode_t mode); }
public static readonly long SYS_SETREUID = (long)126L; // { int sys_setreuid(uid_t ruid, uid_t euid); }
public static readonly long SYS_SETREGID = (long)127L; // { int sys_setregid(gid_t rgid, gid_t egid); }
public static readonly long SYS_RENAME = (long)128L; // { int sys_rename(const char *from, const char *to); }
public static readonly long SYS_FLOCK = (long)131L; // { int sys_flock(int fd, int how); }
public static readonly long SYS_MKFIFO = (long)132L; // { int sys_mkfifo(const char *path, mode_t mode); }
public static readonly long SYS_SENDTO = (long)133L; // { ssize_t sys_sendto(int s, const void *buf, \
public static readonly long SYS_SHUTDOWN = (long)134L; // { int sys_shutdown(int s, int how); }
public static readonly long SYS_SOCKETPAIR = (long)135L; // { int sys_socketpair(int domain, int type, \
public static readonly long SYS_MKDIR = (long)136L; // { int sys_mkdir(const char *path, mode_t mode); }
public static readonly long SYS_RMDIR = (long)137L; // { int sys_rmdir(const char *path); }
public static readonly long SYS_ADJTIME = (long)140L; // { int sys_adjtime(const struct timeval *delta, \
public static readonly long SYS_SETSID = (long)147L; // { int sys_setsid(void); }
public static readonly long SYS_QUOTACTL = (long)148L; // { int sys_quotactl(const char *path, int cmd, \
public static readonly long SYS_NFSSVC = (long)155L; // { int sys_nfssvc(int flag, void *argp); }
public static readonly long SYS_GETFH = (long)161L; // { int sys_getfh(const char *fname, fhandle_t *fhp); }
public static readonly long SYS_SYSARCH = (long)165L; // { int sys_sysarch(int op, void *parms); }
public static readonly long SYS_PREAD = (long)173L; // { ssize_t sys_pread(int fd, void *buf, \
public static readonly long SYS_PWRITE = (long)174L; // { ssize_t sys_pwrite(int fd, const void *buf, \
public static readonly long SYS_SETGID = (long)181L; // { int sys_setgid(gid_t gid); }
public static readonly long SYS_SETEGID = (long)182L; // { int sys_setegid(gid_t egid); }
public static readonly long SYS_SETEUID = (long)183L; // { int sys_seteuid(uid_t euid); }
public static readonly long SYS_PATHCONF = (long)191L; // { long sys_pathconf(const char *path, int name); }
public static readonly long SYS_FPATHCONF = (long)192L; // { long sys_fpathconf(int fd, int name); }
public static readonly long SYS_SWAPCTL = (long)193L; // { int sys_swapctl(int cmd, const void *arg, int misc); }
public static readonly long SYS_GETRLIMIT = (long)194L; // { int sys_getrlimit(int which, \
public static readonly long SYS_SETRLIMIT = (long)195L; // { int sys_setrlimit(int which, \
public static readonly long SYS_MMAP = (long)197L; // { void *sys_mmap(void *addr, size_t len, int prot, \
public static readonly long SYS_LSEEK = (long)199L; // { off_t sys_lseek(int fd, int pad, off_t offset, \
public static readonly long SYS_TRUNCATE = (long)200L; // { int sys_truncate(const char *path, int pad, \
public static readonly long SYS_FTRUNCATE = (long)201L; // { int sys_ftruncate(int fd, int pad, off_t length); }
public static readonly long SYS___SYSCTL = (long)202L; // { int sys___sysctl(const int *name, u_int namelen, \
public static readonly long SYS_MLOCK = (long)203L; // { int sys_mlock(const void *addr, size_t len); }
public static readonly long SYS_MUNLOCK = (long)204L; // { int sys_munlock(const void *addr, size_t len); }
public static readonly long SYS_GETPGID = (long)207L; // { pid_t sys_getpgid(pid_t pid); }
public static readonly long SYS_UTRACE = (long)209L; // { int sys_utrace(const char *label, const void *addr, \
public static readonly long SYS_SEMGET = (long)221L; // { int sys_semget(key_t key, int nsems, int semflg); }
public static readonly long SYS_MSGGET = (long)225L; // { int sys_msgget(key_t key, int msgflg); }
public static readonly long SYS_MSGSND = (long)226L; // { int sys_msgsnd(int msqid, const void *msgp, size_t msgsz, \
public static readonly long SYS_MSGRCV = (long)227L; // { int sys_msgrcv(int msqid, void *msgp, size_t msgsz, \
public static readonly long SYS_SHMAT = (long)228L; // { void *sys_shmat(int shmid, const void *shmaddr, \
public static readonly long SYS_SHMDT = (long)230L; // { int sys_shmdt(const void *shmaddr); }
public static readonly long SYS_MINHERIT = (long)250L; // { int sys_minherit(void *addr, size_t len, \
public static readonly long SYS_POLL = (long)252L; // { int sys_poll(struct pollfd *fds, \
public static readonly long SYS_ISSETUGID = (long)253L; // { int sys_issetugid(void); }
public static readonly long SYS_LCHOWN = (long)254L; // { int sys_lchown(const char *path, uid_t uid, gid_t gid); }
public static readonly long SYS_GETSID = (long)255L; // { pid_t sys_getsid(pid_t pid); }
public static readonly long SYS_MSYNC = (long)256L; // { int sys_msync(void *addr, size_t len, int flags); }
public static readonly long SYS_PIPE = (long)263L; // { int sys_pipe(int *fdp); }
public static readonly long SYS_FHOPEN = (long)264L; // { int sys_fhopen(const fhandle_t *fhp, int flags); }
public static readonly long SYS_PREADV = (long)267L; // { ssize_t sys_preadv(int fd, \
public static readonly long SYS_PWRITEV = (long)268L; // { ssize_t sys_pwritev(int fd, \
public static readonly long SYS_KQUEUE = (long)269L; // { int sys_kqueue(void); }
public static readonly long SYS_MLOCKALL = (long)271L; // { int sys_mlockall(int flags); }
public static readonly long SYS_MUNLOCKALL = (long)272L; // { int sys_munlockall(void); }
public static readonly long SYS_GETRESUID = (long)281L; // { int sys_getresuid(uid_t *ruid, uid_t *euid, \
public static readonly long SYS_SETRESUID = (long)282L; // { int sys_setresuid(uid_t ruid, uid_t euid, \
public static readonly long SYS_GETRESGID = (long)283L; // { int sys_getresgid(gid_t *rgid, gid_t *egid, \
public static readonly long SYS_SETRESGID = (long)284L; // { int sys_setresgid(gid_t rgid, gid_t egid, \
public static readonly long SYS_MQUERY = (long)286L; // { void *sys_mquery(void *addr, size_t len, int prot, \
public static readonly long SYS_CLOSEFROM = (long)287L; // { int sys_closefrom(int fd); }
public static readonly long SYS_SIGALTSTACK = (long)288L; // { int sys_sigaltstack(const struct sigaltstack *nss, \
public static readonly long SYS_SHMGET = (long)289L; // { int sys_shmget(key_t key, size_t size, int shmflg); }
public static readonly long SYS_SEMOP = (long)290L; // { int sys_semop(int semid, struct sembuf *sops, \
public static readonly long SYS_FHSTAT = (long)294L; // { int sys_fhstat(const fhandle_t *fhp, \
public static readonly long SYS___SEMCTL = (long)295L; // { int sys___semctl(int semid, int semnum, int cmd, \
public static readonly long SYS_SHMCTL = (long)296L; // { int sys_shmctl(int shmid, int cmd, \
public static readonly long SYS_MSGCTL = (long)297L; // { int sys_msgctl(int msqid, int cmd, \
public static readonly long SYS_SCHED_YIELD = (long)298L; // { int sys_sched_yield(void); }
public static readonly long SYS_GETTHRID = (long)299L; // { pid_t sys_getthrid(void); }
public static readonly long SYS___THRWAKEUP = (long)301L; // { int sys___thrwakeup(const volatile void *ident, \
public static readonly long SYS___THREXIT = (long)302L; // { void sys___threxit(pid_t *notdead); }
public static readonly long SYS___THRSIGDIVERT = (long)303L; // { int sys___thrsigdivert(sigset_t sigmask, \
public static readonly long SYS___GETCWD = (long)304L; // { int sys___getcwd(char *buf, size_t len); }
public static readonly long SYS_ADJFREQ = (long)305L; // { int sys_adjfreq(const int64_t *freq, \
public static readonly long SYS_SETRTABLE = (long)310L; // { int sys_setrtable(int rtableid); }
public static readonly long SYS_GETRTABLE = (long)311L; // { int sys_getrtable(void); }
public static readonly long SYS_FACCESSAT = (long)313L; // { int sys_faccessat(int fd, const char *path, \
public static readonly long SYS_FCHMODAT = (long)314L; // { int sys_fchmodat(int fd, const char *path, \
public static readonly long SYS_FCHOWNAT = (long)315L; // { int sys_fchownat(int fd, const char *path, \
public static readonly long SYS_LINKAT = (long)317L; // { int sys_linkat(int fd1, const char *path1, int fd2, \
public static readonly long SYS_MKDIRAT = (long)318L; // { int sys_mkdirat(int fd, const char *path, \
public static readonly long SYS_MKFIFOAT = (long)319L; // { int sys_mkfifoat(int fd, const char *path, \
public static readonly long SYS_MKNODAT = (long)320L; // { int sys_mknodat(int fd, const char *path, \
public static readonly long SYS_OPENAT = (long)321L; // { int sys_openat(int fd, const char *path, int flags, \
public static readonly long SYS_READLINKAT = (long)322L; // { ssize_t sys_readlinkat(int fd, const char *path, \
public static readonly long SYS_RENAMEAT = (long)323L; // { int sys_renameat(int fromfd, const char *from, \
public static readonly long SYS_SYMLINKAT = (long)324L; // { int sys_symlinkat(const char *path, int fd, \
public static readonly long SYS_UNLINKAT = (long)325L; // { int sys_unlinkat(int fd, const char *path, \
public static readonly long SYS___SET_TCB = (long)329L; // { void sys___set_tcb(void *tcb); }
public static readonly long SYS___GET_TCB = (long)330L; // { void *sys___get_tcb(void); }
}
}
| 100.608108 | 125 | 0.678845 | [
"MIT"
] | GridProtectionAlliance/go2cs | src/go-src-converted/syscall/zsysnum_openbsd_arm.cs | 22,335 | C# |
// Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// 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 Google.Api.Ads.Common.Util;
using Google.Api.Ads.AdManager.Lib;
using Google.Api.Ads.AdManager.Util.v202105;
using Google.Api.Ads.AdManager.v202105;
using System;
using System.Collections.Generic;
namespace Google.Api.Ads.AdManager.Examples.CSharp.v202105
{
/// <summary>
/// This code example fetches and creates match table files from the
/// Line_Item and Ad_Unit tables. This example may take a while to run.
/// </summary>
public class FetchMatchTables : SampleBase
{
/// <summary>
/// Returns a description about the code example.
/// </summary>
public override string Description
{
get
{
return
"This code example fetches and creates match table files from the Line_Item " +
"and Ad_Unit tables. This example may take a while to run.";
}
}
/// <summary>
/// Main method, to run this code example as a standalone application.
/// </summary>
public static void Main()
{
FetchMatchTables codeExample = new FetchMatchTables();
Console.WriteLine(codeExample.Description);
codeExample.Run(new AdManagerUser());
}
/// <summary>
/// Run the code example.
/// </summary>
public void Run(AdManagerUser user)
{
using (PublisherQueryLanguageService pqlService =
user.GetService<PublisherQueryLanguageService>())
{
try
{
StatementBuilder lineItemStatementBuilder = new StatementBuilder()
.Select("Id, Name, Status").From("Line_Item").OrderBy("Id ASC")
.Limit(StatementBuilder.SUGGESTED_PAGE_LIMIT);
string lineItemFilePath = "Line-Item-Matchtable.csv";
fetchMatchTables(pqlService, lineItemStatementBuilder, lineItemFilePath);
StatementBuilder adUnitStatementBuilder = new StatementBuilder()
.Select("Id, Name").From("Ad_Unit").OrderBy("Id ASC")
.Limit(StatementBuilder.SUGGESTED_PAGE_LIMIT);
string adUnitFilePath = "Ad-Unit-Matchtable.csv";
fetchMatchTables(pqlService, adUnitStatementBuilder, adUnitFilePath);
Console.WriteLine("Ad units saved to {0}", adUnitFilePath);
Console.WriteLine("Line items saved to {0}\n", lineItemFilePath);
}
catch (Exception e)
{
Console.WriteLine("Failed to get match tables. Exception says \"{0}\"",
e.Message);
}
}
}
/// <summary>
/// Fetches a match table from a PQL statement and writes it to a file.
/// </summary>
/// <param name="pqlService">The PQL service.</param>
/// <param name="statementBuilder">The statement builder to use.</param>
/// <param name="fileName">Name of the file.</param>
private static void fetchMatchTables(PublisherQueryLanguageService pqlService,
StatementBuilder statementBuilder, string fileName)
{
int resultSetSize = 0;
List<Row> allRows = new List<Row>();
ResultSet resultSet;
do
{
resultSet = pqlService.select(statementBuilder.ToStatement());
allRows.AddRange(resultSet.rows);
Console.WriteLine(PqlUtilities.ResultSetToString(resultSet));
statementBuilder.IncreaseOffsetBy(StatementBuilder.SUGGESTED_PAGE_LIMIT);
resultSetSize = resultSet.rows == null ? 0 : resultSet.rows.Length;
} while (resultSetSize == StatementBuilder.SUGGESTED_PAGE_LIMIT);
resultSet.rows = allRows.ToArray();
List<String[]> rows = PqlUtilities.ResultSetToStringArrayList(resultSet);
// Write the contents to a csv file.
CsvFile file = new CsvFile();
file.Headers.AddRange(rows[0]);
file.Records.AddRange(rows.GetRange(1, rows.Count - 1).ToArray());
file.Write(fileName);
}
}
}
| 40.421488 | 99 | 0.598242 | [
"Apache-2.0"
] | googleads/googleads-dotnet-lib | examples/AdManager/CSharp/v202105/PublisherQueryLanguageService/FetchMatchTables.cs | 4,891 | C# |
/* Copyright 2010-present MongoDB Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using MongoDB.Bson;
namespace MongoDB.Driver
{
/// <summary>
/// Represents a database in MongoDB.
/// </summary>
/// <remarks>
/// This interface is not guaranteed to remain stable. Implementors should use
/// <see cref="MongoDatabaseBase" />.
/// </remarks>
public interface IMongoDatabase
{
/// <summary>
/// Gets the client.
/// </summary>
IMongoClient Client { get; }
/// <summary>
/// Gets the namespace of the database.
/// </summary>
DatabaseNamespace DatabaseNamespace { get; }
/// <summary>
/// Gets the settings.
/// </summary>
MongoDatabaseSettings Settings { get; }
/// <summary>
/// Creates the collection with the specified name.
/// </summary>
/// <param name="name">The name.</param>
/// <param name="options">The options.</param>
/// <param name="cancellationToken">The cancellation token.</param>
void CreateCollection(string name, CreateCollectionOptions options = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Creates the collection with the specified name.
/// </summary>
/// <param name="session">The session.</param>
/// <param name="name">The name.</param>
/// <param name="options">The options.</param>
/// <param name="cancellationToken">The cancellation token.</param>
void CreateCollection(IClientSessionHandle session, string name, CreateCollectionOptions options = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Creates the collection with the specified name.
/// </summary>
/// <param name="name">The name.</param>
/// <param name="options">The options.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>A task.</returns>
Task CreateCollectionAsync(string name, CreateCollectionOptions options = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Creates the collection with the specified name.
/// </summary>
/// <param name="session">The session.</param>
/// <param name="name">The name.</param>
/// <param name="options">The options.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>
/// A task.
/// </returns>
Task CreateCollectionAsync(IClientSessionHandle session, string name, CreateCollectionOptions options = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Creates a view.
/// </summary>
/// <typeparam name="TDocument">The type of the input documents.</typeparam>
/// <typeparam name="TResult">The type of the pipeline result documents.</typeparam>
/// <param name="viewName">The name of the view.</param>
/// <param name="viewOn">The name of the collection that the view is on.</param>
/// <param name="pipeline">The pipeline.</param>
/// <param name="options">The options.</param>
/// <param name="cancellationToken">The cancellation token.</param>
void CreateView<TDocument, TResult>(string viewName, string viewOn, PipelineDefinition<TDocument, TResult> pipeline, CreateViewOptions<TDocument> options = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Creates a view.
/// </summary>
/// <typeparam name="TDocument">The type of the input documents.</typeparam>
/// <typeparam name="TResult">The type of the pipeline result documents.</typeparam>
/// <param name="session">The session.</param>
/// <param name="viewName">The name of the view.</param>
/// <param name="viewOn">The name of the collection that the view is on.</param>
/// <param name="pipeline">The pipeline.</param>
/// <param name="options">The options.</param>
/// <param name="cancellationToken">The cancellation token.</param>
void CreateView<TDocument, TResult>(IClientSessionHandle session, string viewName, string viewOn, PipelineDefinition<TDocument, TResult> pipeline, CreateViewOptions<TDocument> options = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Creates a view.
/// </summary>
/// <typeparam name="TDocument">The type of the input documents.</typeparam>
/// <typeparam name="TResult">The type of the pipeline result documents.</typeparam>
/// <param name="viewName">The name of the view.</param>
/// <param name="viewOn">The name of the collection that the view is on.</param>
/// <param name="pipeline">The pipeline.</param>
/// <param name="options">The options.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>A task.</returns>
Task CreateViewAsync<TDocument, TResult>(string viewName, string viewOn, PipelineDefinition<TDocument, TResult> pipeline, CreateViewOptions<TDocument> options = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Creates a view.
/// </summary>
/// <typeparam name="TDocument">The type of the input documents.</typeparam>
/// <typeparam name="TResult">The type of the pipeline result documents.</typeparam>
/// <param name="session">The session.</param>
/// <param name="viewName">The name of the view.</param>
/// <param name="viewOn">The name of the collection that the view is on.</param>
/// <param name="pipeline">The pipeline.</param>
/// <param name="options">The options.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>
/// A task.
/// </returns>
Task CreateViewAsync<TDocument, TResult>(IClientSessionHandle session, string viewName, string viewOn, PipelineDefinition<TDocument, TResult> pipeline, CreateViewOptions<TDocument> options = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Drops the collection with the specified name.
/// </summary>
/// <param name="name">The name of the collection to drop.</param>
/// <param name="cancellationToken">The cancellation token.</param>
void DropCollection(string name, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Drops the collection with the specified name.
/// </summary>
/// <param name="session">The session.</param>
/// <param name="name">The name of the collection to drop.</param>
/// <param name="cancellationToken">The cancellation token.</param>
void DropCollection(IClientSessionHandle session, string name, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Drops the collection with the specified name.
/// </summary>
/// <param name="name">The name of the collection to drop.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>A task.</returns>
Task DropCollectionAsync(string name, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Drops the collection with the specified name.
/// </summary>
/// <param name="session">The session.</param>
/// <param name="name">The name of the collection to drop.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>
/// A task.
/// </returns>
Task DropCollectionAsync(IClientSessionHandle session, string name, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets a collection.
/// </summary>
/// <typeparam name="TDocument">The document type.</typeparam>
/// <param name="name">The name of the collection.</param>
/// <param name="settings">The settings.</param>
/// <returns>An implementation of a collection.</returns>
IMongoCollection<TDocument> GetCollection<TDocument>(string name, MongoCollectionSettings settings = null);
/// <summary>
/// Lists the names of all the collections in the database.
/// </summary>
/// <param name="options">The options.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>A cursor.</returns>
IAsyncCursor<string> ListCollectionNames(ListCollectionNamesOptions options = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Lists the names of all the collections in the database.
/// </summary>
/// <param name="session">The session.</param>
/// <param name="options">The options.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>A cursor.</returns>
IAsyncCursor<string> ListCollectionNames(IClientSessionHandle session, ListCollectionNamesOptions options = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Lists the names of all the collections in the database.
/// </summary>
/// <param name="options">The options.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>A Task whose result is a cursor.</returns>
Task<IAsyncCursor<string>> ListCollectionNamesAsync(ListCollectionNamesOptions options = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Lists the names of all the collections in the database.
/// </summary>
/// <param name="session">The session.</param>
/// <param name="options">The options.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>A Task whose result is a cursor.</returns>
Task<IAsyncCursor<string>> ListCollectionNamesAsync(IClientSessionHandle session, ListCollectionNamesOptions options = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Lists all the collections in the database.
/// </summary>
/// <param name="options">The options.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>A cursor.</returns>
IAsyncCursor<BsonDocument> ListCollections(ListCollectionsOptions options = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Lists all the collections in the database.
/// </summary>
/// <param name="session">The session.</param>
/// <param name="options">The options.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>
/// A cursor.
/// </returns>
IAsyncCursor<BsonDocument> ListCollections(IClientSessionHandle session, ListCollectionsOptions options = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Lists all the collections in the database.
/// </summary>
/// <param name="options">The options.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>A Task whose result is a cursor.</returns>
Task<IAsyncCursor<BsonDocument>> ListCollectionsAsync(ListCollectionsOptions options = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Lists all the collections in the database.
/// </summary>
/// <param name="session">The session.</param>
/// <param name="options">The options.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>
/// A Task whose result is a cursor.
/// </returns>
Task<IAsyncCursor<BsonDocument>> ListCollectionsAsync(IClientSessionHandle session, ListCollectionsOptions options = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Renames the collection.
/// </summary>
/// <param name="oldName">The old name.</param>
/// <param name="newName">The new name.</param>
/// <param name="options">The options.</param>
/// <param name="cancellationToken">The cancellation token.</param>
void RenameCollection(string oldName, string newName, RenameCollectionOptions options = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Renames the collection.
/// </summary>
/// <param name="session">The session.</param>
/// <param name="oldName">The old name.</param>
/// <param name="newName">The new name.</param>
/// <param name="options">The options.</param>
/// <param name="cancellationToken">The cancellation token.</param>
void RenameCollection(IClientSessionHandle session, string oldName, string newName, RenameCollectionOptions options = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Renames the collection.
/// </summary>
/// <param name="oldName">The old name.</param>
/// <param name="newName">The new name.</param>
/// <param name="options">The options.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>A task.</returns>
Task RenameCollectionAsync(string oldName, string newName, RenameCollectionOptions options = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Renames the collection.
/// </summary>
/// <param name="session">The session.</param>
/// <param name="oldName">The old name.</param>
/// <param name="newName">The new name.</param>
/// <param name="options">The options.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>
/// A task.
/// </returns>
Task RenameCollectionAsync(IClientSessionHandle session, string oldName, string newName, RenameCollectionOptions options = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Runs a command.
/// </summary>
/// <typeparam name="TResult">The result type of the command.</typeparam>
/// <param name="command">The command.</param>
/// <param name="readPreference">The read preference.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>
/// The result of the command.
/// </returns>
TResult RunCommand<TResult>(Command<TResult> command, ReadPreference readPreference = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Runs a command.
/// </summary>
/// <typeparam name="TResult">The result type of the command.</typeparam>
/// <param name="session">The session.</param>
/// <param name="command">The command.</param>
/// <param name="readPreference">The read preference.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>
/// The result of the command.
/// </returns>
TResult RunCommand<TResult>(IClientSessionHandle session, Command<TResult> command, ReadPreference readPreference = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Runs a command.
/// </summary>
/// <typeparam name="TResult">The result type of the command.</typeparam>
/// <param name="command">The command.</param>
/// <param name="readPreference">The read preference.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>
/// The result of the command.
/// </returns>
Task<TResult> RunCommandAsync<TResult>(Command<TResult> command, ReadPreference readPreference = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Runs a command.
/// </summary>
/// <typeparam name="TResult">The result type of the command.</typeparam>
/// <param name="session">The session.</param>
/// <param name="command">The command.</param>
/// <param name="readPreference">The read preference.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>
/// The result of the command.
/// </returns>
Task<TResult> RunCommandAsync<TResult>(IClientSessionHandle session, Command<TResult> command, ReadPreference readPreference = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Watches changes on all collections in a database.
/// </summary>
/// <typeparam name="TResult">The type of the result.</typeparam>
/// <param name="pipeline">The pipeline.</param>
/// <param name="options">The options.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>
/// A change stream.
/// </returns>
IAsyncCursor<TResult> Watch<TResult>(
PipelineDefinition<ChangeStreamDocument<BsonDocument>, TResult> pipeline,
ChangeStreamOptions options = null,
CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Watches changes on all collections in a database.
/// </summary>
/// <typeparam name="TResult">The type of the result.</typeparam>
/// <param name="session">The session.</param>
/// <param name="pipeline">The pipeline.</param>
/// <param name="options">The options.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>
/// A change stream.
/// </returns>
IAsyncCursor<TResult> Watch<TResult>(
IClientSessionHandle session,
PipelineDefinition<ChangeStreamDocument<BsonDocument>, TResult> pipeline,
ChangeStreamOptions options = null,
CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Watches changes on all collections in a database.
/// </summary>
/// <typeparam name="TResult">The type of the result.</typeparam>
/// <param name="pipeline">The pipeline.</param>
/// <param name="options">The options.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>
/// A change stream.
/// </returns>
Task<IAsyncCursor<TResult>> WatchAsync<TResult>(
PipelineDefinition<ChangeStreamDocument<BsonDocument>, TResult> pipeline,
ChangeStreamOptions options = null,
CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Watches changes on all collections in a database.
/// </summary>
/// <typeparam name="TResult">The type of the result.</typeparam>
/// <param name="session">The session.</param>
/// <param name="pipeline">The pipeline.</param>
/// <param name="options">The options.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>
/// A change stream.
/// </returns>
Task<IAsyncCursor<TResult>> WatchAsync<TResult>(
IClientSessionHandle session,
PipelineDefinition<ChangeStreamDocument<BsonDocument>, TResult> pipeline,
ChangeStreamOptions options = null,
CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Returns a new IMongoDatabase instance with a different read concern setting.
/// </summary>
/// <param name="readConcern">The read concern.</param>
/// <returns>A new IMongoDatabase instance with a different read concern setting.</returns>
IMongoDatabase WithReadConcern(ReadConcern readConcern);
/// <summary>
/// Returns a new IMongoDatabase instance with a different read preference setting.
/// </summary>
/// <param name="readPreference">The read preference.</param>
/// <returns>A new IMongoDatabase instance with a different read preference setting.</returns>
IMongoDatabase WithReadPreference(ReadPreference readPreference);
/// <summary>
/// Returns a new IMongoDatabase instance with a different write concern setting.
/// </summary>
/// <param name="writeConcern">The write concern.</param>
/// <returns>A new IMongoDatabase instance with a different write concern setting.</returns>
IMongoDatabase WithWriteConcern(WriteConcern writeConcern);
}
} | 51.606481 | 271 | 0.64089 | [
"MIT"
] | 13294029724/ET | Server/ThirdParty/MongoDBDriver/MongoDB.Driver/IMongoDatabase.cs | 22,294 | C# |
using Home.Neeo.Device.Validation;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System;
using System.Threading.Tasks;
namespace Home.Neeo.Models
{
public class NEEORecipe
{
public class DetailData
{
[JsonProperty("deviceName")]
public string DeviceName { get; set; }
[JsonProperty("rootName")]
public string RootName { get; set; }
[JsonProperty("model")]
public string Model { get; set; }
[JsonProperty("manufacturer")]
public string Manufacturer { get; set; }
[JsonProperty("deviceType")]
[JsonConverter(typeof(StringEnumConverter))]
public DeviceType.TYPE DeviceType { get; set; }
}
public class UrlData
{
[JsonProperty("identify")]
public string Identify { get; set; }
[JsonProperty("setPowerOn")]
public string SetPowerOn { get; set; }
[JsonProperty("setPowerOff")]
public string SetPowerOff { get; set; }
[JsonProperty("getPowerState")]
public string GetPowerState { get; set; }
}
public class ActionData
{
public Func<Task<bool>> Identify { get; set; }
public Func<Task<bool>> PowerOn { get; set; }
public Func<Task<bool>> PowerOff { get; set; }
public Func<Task<bool>> GetPowerState { get; set; }
}
[JsonProperty("type")]
public string Type { get; set; }
[JsonProperty("detail")]
public DetailData Detail { get; set; }
[JsonProperty("url")]
public UrlData Url { get; set; }
[JsonProperty("isCustom")]
public bool IsCustom { get; set; }
[JsonProperty("isPoweredOn")]
public bool IsPoweredOn { get; set; }
[JsonProperty("uid")]
public string UID { get; set; }
[JsonProperty("powerKey")]
public string PowerKey { get; set; }
[JsonIgnore]
public ActionData Action { get; set; }
}
}
| 39.451613 | 71 | 0.479967 | [
"MIT"
] | MilanOTy/NeeoApi | NeeoApiLib/Models/NEEORecipe.cs | 2,448 | C# |
using System.IO;
using System.Threading.Tasks;
using Microsoft.Extensions.Options;
using Newtonsoft.Json;
using OrchardCore.ContentManagement.Metadata.Records;
using OrchardCore.Environment.Shell;
namespace OrchardCore.ContentManagement
{
public class FileContentDefinitionStore : IContentDefinitionStore
{
private readonly IOptions<ShellOptions> _shellOptions;
private readonly ShellSettings _shellSettings;
private ContentDefinitionRecord _contentDefinitionRecord;
public FileContentDefinitionStore(IOptions<ShellOptions> shellOptions, ShellSettings shellSettings)
{
_shellOptions = shellOptions;
_shellSettings = shellSettings;
}
/// <summary>
/// Loads a single document (or create a new one) for updating and that should not be cached.
/// </summary>
public async Task<ContentDefinitionRecord> LoadContentDefinitionAsync()
{
if (_contentDefinitionRecord != null)
{
return _contentDefinitionRecord;
}
return _contentDefinitionRecord = await GetContentDefinitionAsync();
}
/// <summary>
/// Gets a single document (or create a new one) for caching and that should not be updated.
/// </summary>
public Task<ContentDefinitionRecord> GetContentDefinitionAsync()
{
ContentDefinitionRecord result;
if (!File.Exists(Filename))
{
result = new ContentDefinitionRecord();
}
else
{
lock (this)
{
using (var file = File.OpenText(Filename))
{
var serializer = new JsonSerializer();
result = (ContentDefinitionRecord)serializer.Deserialize(file, typeof(ContentDefinitionRecord));
}
}
}
return Task.FromResult(result);
}
public Task SaveContentDefinitionAsync(ContentDefinitionRecord contentDefinitionRecord)
{
lock (this)
{
using (var file = File.CreateText(Filename))
{
var serializer = new JsonSerializer();
serializer.Formatting = Formatting.Indented;
serializer.Serialize(file, contentDefinitionRecord);
}
}
return Task.CompletedTask;
}
private string Filename => PathExtensions.Combine(
_shellOptions.Value.ShellsApplicationDataPath,
_shellOptions.Value.ShellsContainerName,
_shellSettings.Name, "ContentDefinition.json");
}
}
| 33.373494 | 120 | 0.594224 | [
"BSD-3-Clause"
] | DariuS231/OrchardCore | src/OrchardCore/OrchardCore.ContentManagement/FileContentDefinitionStore.cs | 2,770 | C# |
// CS0507: `DerivedClass.Message': cannot change access modifiers when overriding `public' inherited member `BaseClass.Message'
// Line: 12
class BaseClass {
public virtual string Message {
set {
}
}
}
class DerivedClass : BaseClass {
protected override string Message {
set {
}
}
}
| 16.555556 | 127 | 0.708054 | [
"Apache-2.0"
] | 121468615/mono | mcs/errors/cs0507-6.cs | 298 | C# |
namespace Filesy
{
/// <summary>
/// Base class for Filesy directory entries.
/// </summary>
public abstract class FileSyDirectoryInfo : FileSyInfo
{
/// <summary>
/// Initializes a new instance of the <see cref="FileSyDirectoryInfo"/> class.
/// </summary>
/// <param name="fullName">Full path of the directory. Assumed to not be null therefor a null value should never be passed.</param>
protected FileSyDirectoryInfo(string fullName)
: base(fullName, FileSyInfoType.Directory)
{
}
}
}
| 32.277778 | 139 | 0.619621 | [
"MIT"
] | Locate64/Filesy | src/Filesy/FileSyDirectoryInfo.cs | 583 | C# |
using Northwind.Domain;
using System.Linq;
namespace Northwind.Persistance
{
public class NorthwindInitializer
{
public static void Initialize(NorthwindContext context)
{
context.Database.EnsureCreated();
if (context.Customers.Any())
{
return;
}
Seed(context);
}
private static void Seed(NorthwindContext context)
{
var customers = new[]
{
new Customer { Name = "Jerry Smith" },
new Customer { Name = "Summer Smith" },
new Customer { Name = "Morty Smith" },
new Customer { Name = "Rick Sanchez" },
new Customer { Name = "Beth Smith" },
new Customer { Name = "Mr. Meeseeks" },
};
context.Customers.AddRange(customers);
context.SaveChanges();
}
}
}
| 25.540541 | 63 | 0.498413 | [
"MIT"
] | JasonGT/NDCSydney2017Demo | SimplifiedApproachDemo/Northwind/Persistance/NorthwindInitializer.cs | 947 | C# |
using FatecMauaJobNewsletter.Domains.Models;
using FatecMauaJobNewsletter.Domains.Models.Response;
using Mapster;
namespace FatecMauaJobNewsletter.Domains.Utils
{
public static class ConfigMapster
{
public static TypeAdapterConfig Configs()
{
var config = new TypeAdapterConfig();
config.NewConfig<JobVacancy, JobResume>();
return config;
}
}
}
| 22.157895 | 54 | 0.674584 | [
"MIT"
] | lucasvieiravicente/FatecMauaJobNewsletterBlazor | Domains/Utils/ConfigMapster.cs | 423 | C# |
using System;
namespace Minsk.CodeAnalysis
{
public sealed class VariableSymbol
{
internal VariableSymbol(string name, bool isReadOnly, Type type)
{
Name = name;
IsReadOnly = isReadOnly;
Type = type;
}
public string Name { get; }
public bool IsReadOnly { get; }
public Type Type { get; }
public override string ToString() => Name;
}
} | 22.05 | 72 | 0.564626 | [
"MIT"
] | shbfeng/minsk | src/Minsk/CodeAnalysis/VariableSymbol.cs | 441 | C# |
// ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Management.Automation;
namespace StaticAnalysis.SignatureVerifier
{
/// <summary>
/// Data about the cmdlet signature
/// </summary>
[Serializable]
public class CmdletSignatureMetadata
{
private IList<OutputMetadata> _outputTypes = new List<OutputMetadata>();
private IList<ParameterMetadata> _parameters = new List<ParameterMetadata>();
#region ShouldContinueVerbs
private static readonly List<string> ShouldContinueVerbs = new List<string>
{
VerbsCommon.Clear,
VerbsCommon.Copy,
VerbsData.Edit,
VerbsData.Export,
VerbsData.Import,
VerbsData.Initialize,
VerbsCommon.Move,
VerbsCommon.Redo,
VerbsCommon.Remove,
VerbsCommon.Rename,
VerbsDiagnostic.Repair,
VerbsCommon.Reset,
VerbsCommon.Resize,
VerbsLifecycle.Restart,
VerbsData.Restore,
VerbsCommon.Set,
VerbsLifecycle.Stop,
VerbsLifecycle.Suspend,
VerbsLifecycle.Uninstall,
VerbsData.Update,
VerbsCommunications.Write
};
#endregion
#region ShouldProcessVerbs
private static readonly List<string> ShouldProcessVerbs = new List<string>
{
VerbsCommon.Close,
VerbsData.Compress,
VerbsLifecycle.Disable,
VerbsCommunications.Disconnect,
VerbsData.Dismount,
VerbsCommon.Exit,
VerbsCommon.Hide,
VerbsCommon.Lock,
VerbsData.Merge,
VerbsData.Mount,
VerbsData.Limit,
VerbsCommon.New,
VerbsCommon.Optimize,
VerbsData.Publish,
VerbsData.Save,
VerbsData.Sync,
VerbsCommon.Switch,
VerbsCommon.Undo,
VerbsCommon.Unlock,
VerbsSecurity.Unprotect,
VerbsData.Unpublish,
VerbsLifecycle.Unregister,
VerbsCommon.Add,
VerbsLifecycle.Approve,
VerbsData.Backup,
VerbsData.Checkpoint,
VerbsLifecycle.Complete,
VerbsCommunications.Connect,
VerbsData.Convert,
VerbsData.ConvertFrom,
VerbsData.ConvertTo,
VerbsLifecycle.Deny,
VerbsLifecycle.Enable,
VerbsData.Group,
VerbsCommon.Enter,
VerbsData.Expand,
VerbsCommon.Format,
VerbsLifecycle.Install,
VerbsLifecycle.Invoke,
VerbsCommon.Open,
VerbsCommon.Push,
VerbsCommon.Pop,
VerbsCommunications.Read,
VerbsCommunications.Receive,
VerbsLifecycle.Register,
VerbsLifecycle.Request,
VerbsLifecycle.Resume,
VerbsCommunications.Send,
VerbsCommon.Split,
VerbsLifecycle.Start,
VerbsLifecycle.Submit,
VerbsSecurity.Block,
VerbsSecurity.Grant,
VerbsSecurity.Protect,
VerbsSecurity.Revoke,
VerbsSecurity.Unblock
};
#endregion
#region ApprovedVerbs
private static List<string> ApprovedVerbs;
private static List<string> GetApprovedVerbs()
{
if (ApprovedVerbs == null)
{
ApprovedVerbs = new List<string>();
PowerShell powershell = PowerShell.Create();
powershell.AddCommand("Get-Verb");
var cmdletResult = powershell.Invoke();
foreach (PSObject result in cmdletResult)
{
ApprovedVerbs.Add(result.Members["Verb"].Value.ToString());
}
}
return ApprovedVerbs;
}
#endregion
#region SingularNouns
private static readonly List<string> SingularNouns = new List<string>
{
"Access",
"Address",
"Alias",
"Anonymous",
"Diagnostics",
"Express",
"Https",
"InBytes",
"InDays",
"InHours",
"InMinutes",
"InMonths",
"InSeconds",
"Insights",
"Loss",
"Mbps",
"Permissions",
"Process",
"Progress",
"SaveAs",
"Statistics",
"Status",
"Success",
"Vmss"
};
public List<ParameterMetadata> GetParametersWithPluralNoun()
{
List<ParameterMetadata> pluralParameters = new List<ParameterMetadata>();
foreach (var parameter in _parameters)
{
if (parameter.Name.EndsWith("s") && SingularNouns.Find(n => parameter.Name.EndsWith(n)) == null)
{
pluralParameters.Add(parameter);
}
}
return pluralParameters;
}
#endregion
/// <summary>
/// The name of the assembly containing cmdlet
/// </summary>
public string AssemblyName { get; set; }
/// <summary>
/// The verb portion of the cmdlet name
/// </summary>
public string VerbName { get; set; }
/// <summary>
/// The noun portion of the cmdlet name
/// </summary>
public string NounName { get; set; }
/// <summary>
/// The name of the cmdlet
/// </summary>
public string Name { get { return string.Format("{0}-{1}", VerbName, NounName); } }
/// <summary>
/// True if the cmdlet should have execution protected by ShouldProcess
/// </summary>
public bool IsShouldProcessVerb
{
get { return VerbName != null && ShouldProcessVerbs.Contains(VerbName) || ShouldContinueVerbs.Contains(VerbName); }
}
/// <summary>
/// True if the cmdlet may have an additional ShouldContinue
/// </summary>
public bool IsShouldContinueVerb
{
get { return VerbName != null && ShouldContinueVerbs.Contains(VerbName); }
}
/// <summary>
/// True if the cmdlet has an approved verb
/// </summary>
public bool IsApprovedVerb
{
get { return VerbName != null && GetApprovedVerbs().Contains(VerbName); }
}
/// <summary>
/// True if the cmdlet has a singular noun
/// </summary>
public bool HasSingularNoun
{
get { return !NounName.EndsWith("s") || SingularNouns.Find(n => NounName.EndsWith(n)) != null; }
}
/// <summary>
/// The name of the class that implements the cmdlet
/// </summary>
public string ClassName { get; set; }
/// <summary>
/// Indicates whether the cmdlet may ask for confirmation
/// </summary>
public bool SupportsShouldProcess { get; set; }
/// <summary>
/// The impact of the operation, used to determine prompting with SHouldProcess
/// </summary>
public ConfirmImpact ConfirmImpact { get; set; }
/// <summary>
/// Indicates whether the cmdlet has a -Force switch parameter
/// </summary>
public bool HasForceSwitch { get; set; }
/// <summary>
/// The set of output types for the cmdlet
/// </summary>
public IList<OutputMetadata> OutputTypes { get { return _outputTypes; } }
/// <summary>
/// The set of cmdlet parameters
/// </summary>
public IList<ParameterMetadata> Parameters { get { return _parameters; } }
}
} | 32.940959 | 128 | 0.525036 | [
"MIT"
] | ThmsRynr/azure-powershell | tools/StaticAnalysis/SignatureVerifier/CmdletSignatureMetadata.cs | 8,659 | C# |
namespace Apex.ConnectApi
{
using ApexSharp;
using ApexSharp.ApexAttributes;
using ApexSharp.Implementation;
using global::Apex.System;
/// <summary>
///
/// </summary>
public class BinaryInput
{
// infrastructure
public BinaryInput(dynamic self)
{
Self = self;
}
dynamic Self { get; set; }
static dynamic Implementation
{
get
{
return Implementor.GetImplementation(typeof(BinaryInput));
}
}
// API
public BinaryInput(Blob blobValue, string contentType, string filename)
{
Self = Implementation.Constructor(blobValue, contentType, filename);
}
public object clone()
{
return Self.clone();
}
public Blob getBlobValue()
{
return Self.getBlobValue();
}
public string getContentType()
{
return Self.getContentType();
}
public string getFilename()
{
return Self.getFilename();
}
public string toString()
{
return Self.toString();
}
}
}
| 20.196721 | 80 | 0.508929 | [
"MIT"
] | apexsharp/apexsharp | Apex/ConnectApi/BinaryInput.cs | 1,232 | C# |
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Diagnostics;
using System.Collections.Immutable;
using System.Linq;
namespace CodeCracker.CSharp.Style
{
[DiagnosticAnalyzer(LanguageNames.CSharp)]
public class AlwaysUseVarAnalyzer : DiagnosticAnalyzer
{
internal const string Title = "You should use 'var' whenever possible.";
internal const string MessageFormat = "Use 'var' instead of specifying the type name.";
internal const string Category = SupportedCategories.Style;
const string Description = "Usage of an implicit type improve readability of the code.\r\n"
+ "Code depending on types for their readability should be refactored with better variable "
+ "names or by introducing well-named methods.";
internal static DiagnosticDescriptor Rule = new DiagnosticDescriptor(
DiagnosticId.AlwaysUseVar.ToDiagnosticId(),
Title,
MessageFormat,
Category,
DiagnosticSeverity.Warning,
isEnabledByDefault: true,
description:Description,
helpLinkUri: HelpLink.ForDiagnostic(DiagnosticId.AlwaysUseVar));
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Rule);
public override void Initialize(AnalysisContext context) =>
context.RegisterSyntaxNodeAction(AnalyzeNode, SyntaxKind.LocalDeclarationStatement);
private void AnalyzeNode(SyntaxNodeAnalysisContext context)
{
var localDeclaration = (LocalDeclarationStatementSyntax)context.Node;
if (localDeclaration.IsConst) return;
var variableDeclaration = localDeclaration.ChildNodes()
.OfType<VariableDeclarationSyntax>()
.FirstOrDefault();
if (variableDeclaration.Type.IsVar) return;
var semanticModel = context.SemanticModel;
var variableTypeName = localDeclaration.Declaration.Type;
var variableType = semanticModel.GetTypeInfo(variableTypeName).ConvertedType;
foreach (var variable in variableDeclaration.Variables)
{
if (variable.Initializer == null) return;
var conversion = semanticModel.ClassifyConversion(variable.Initializer.Value, variableType);
if (!conversion.IsIdentity) return;
}
var diagnostic = Diagnostic.Create(Rule, variableDeclaration.Type.GetLocation());
context.ReportDiagnostic(diagnostic);
}
}
} | 44.4 | 113 | 0.68994 | [
"Apache-2.0"
] | f14n/code-cracker | src/CSharp/CodeCracker/Style/AlwaysUseVarAnalyzer.cs | 2,666 | C# |
using UnityEngine.UI;
namespace _Scripts.Level.Interactable.Talents
{
class Talent : Interactable
{
public Talents TargetTalent;
public Image Image;
}
}
| 16.636364 | 45 | 0.672131 | [
"MIT"
] | ofeerist/PeonRogue-2 | peon/Assets/_Scripts/Level/Interactable/Talents/Talent.cs | 185 | C# |
using Raylib;
using static Raylib.Raylib;
using MathClasses;
// ---------------------------------- //
// used to centeralize input handling //
// ---------------------------------- //
static class Input
{
//primary movement
public static KeyboardKey KEY_RIGHT_1 = KeyboardKey.KEY_D;
public static KeyboardKey KEY_UP_1 = KeyboardKey.KEY_W;
public static KeyboardKey KEY_LEFT_1 = KeyboardKey.KEY_A;
public static KeyboardKey KEY_DOWN_1 = KeyboardKey.KEY_S;
//secondary movement
public static KeyboardKey KEY_RIGHT_2 = KeyboardKey.KEY_RIGHT;
public static KeyboardKey KEY_UP_2 = KeyboardKey.KEY_UP;
public static KeyboardKey KEY_LEFT_2 = KeyboardKey.KEY_LEFT;
public static KeyboardKey KEY_DOWN_2 = KeyboardKey.KEY_DOWN;
// -- // -- //
//Return a Vector3 based on player's input
// -- // -- //
public static Vector2 get_primary_input()
{
int r = IsKeyDown(KEY_RIGHT_1) ? 1 : 0;
int l = IsKeyDown(KEY_LEFT_1) ? 1 : 0;
int u = IsKeyDown(KEY_UP_1) ? 1 : 0;
int d = IsKeyDown(KEY_DOWN_1) ? 1 : 0;
var result = new Vector2(r - l, d - u);
result.Normalize();
return result;
}
public static Vector2 get_secondary_input()
{
int r = IsKeyDown(KEY_RIGHT_2) ? 1 : 0;
int l = IsKeyDown(KEY_LEFT_2) ? 1 : 0;
int u = IsKeyDown(KEY_UP_2) ? 1 : 0;
int d = IsKeyDown(KEY_DOWN_2) ? 1 : 0;
var result = new Vector2(r - l, d - u);
result.Normalize();
return result;
}
}
| 27.509804 | 63 | 0.665716 | [
"MIT"
] | MallocStudio/Uni_YR1_Tank-Game | RaylibStarter2/Project2D/Global/Input.cs | 1,405 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using AzureGuidance.Domain;
using AzureGuidance.Common;
using System.Threading.Tasks;
using AzureGuidance.API.Models;
using System.Configuration;
namespace AzureGuidance.API.Controllers
{
public class OrdersController : ApiController
{
AzureDocumentDBHelper azureDocDBHelper;
public OrdersController()
{
string endpointUrl = ConfigurationManager.AppSettings["Microsoft.DocumentDB.StorageUrl"];
string authorizationKey = ConfigurationManager.AppSettings["Microsoft.DocumentDB.AuthorizationKey"];
azureDocDBHelper = new AzureDocumentDBHelper(endpointUrl, authorizationKey);
}
// GET: api/OrdersAPI
public async Task<OrderResource> Get()
{
List<Order> listOrderDetails;
listOrderDetails = await azureDocDBHelper.GetOrders();
OrderResource orderResource = new OrderResource();
orderResource.Data = listOrderDetails;
// var resource=new Orde
return orderResource;
}
//GET: api/Orders/5
public async Task<ProductResource> Get(Guid id)
{
List<ProductDetails> listProductDetails;
listProductDetails = await azureDocDBHelper.GetOrderProductsDetails(id);
ProductResource productResource = new ProductResource();
productResource.Data = listProductDetails;
return productResource;
}
}
}
| 31.84 | 112 | 0.680276 | [
"MIT"
] | AccelNA/azure-guidance | CloudServices/AzureGuidance/AzureGuidance.API/Controllers/OrdersController.cs | 1,594 | C# |
/*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the ivs-2020-07-14.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using System.Net;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.IVS.Model
{
/// <summary>
/// A key pair used to sign and validate a playback authorization token.
/// </summary>
public partial class PlaybackKeyPair
{
private string _arn;
private string _fingerprint;
private string _name;
private Dictionary<string, string> _tags = new Dictionary<string, string>();
/// <summary>
/// Gets and sets the property Arn.
/// <para>
/// Key-pair ARN.
/// </para>
/// </summary>
[AWSProperty(Min=1, Max=128)]
public string Arn
{
get { return this._arn; }
set { this._arn = value; }
}
// Check to see if Arn property is set
internal bool IsSetArn()
{
return this._arn != null;
}
/// <summary>
/// Gets and sets the property Fingerprint.
/// <para>
/// Key-pair identifier.
/// </para>
/// </summary>
public string Fingerprint
{
get { return this._fingerprint; }
set { this._fingerprint = value; }
}
// Check to see if Fingerprint property is set
internal bool IsSetFingerprint()
{
return this._fingerprint != null;
}
/// <summary>
/// Gets and sets the property Name.
/// <para>
/// Key-pair name.
/// </para>
/// </summary>
[AWSProperty(Min=0, Max=128)]
public string Name
{
get { return this._name; }
set { this._name = value; }
}
// Check to see if Name property is set
internal bool IsSetName()
{
return this._name != null;
}
/// <summary>
/// Gets and sets the property Tags.
/// <para>
/// Array of 1-50 maps, each of the form <code>string:string (key:value)</code>.
/// </para>
/// </summary>
[AWSProperty(Min=0, Max=50)]
public Dictionary<string, string> Tags
{
get { return this._tags; }
set { this._tags = value; }
}
// Check to see if Tags property is set
internal bool IsSetTags()
{
return this._tags != null && this._tags.Count > 0;
}
}
} | 28.57265 | 102 | 0.537541 | [
"Apache-2.0"
] | philasmar/aws-sdk-net | sdk/src/Services/IVS/Generated/Model/PlaybackKeyPair.cs | 3,343 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Xml.XPath;
namespace MS.Internal.Xml.XPath
{
internal sealed class Group : AstNode
{
private readonly AstNode _groupNode;
public Group(AstNode groupNode)
{
_groupNode = groupNode;
}
public override AstType Type
{
get { return AstType.Group; }
}
public override XPathResultType ReturnType
{
get { return XPathResultType.NodeSet; }
}
public AstNode GroupNode
{
get { return _groupNode; }
}
}
}
| 22.21875 | 71 | 0.586498 | [
"MIT"
] | belav/runtime | src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/Group.cs | 711 | C# |
// *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.Oci.Ons.Outputs
{
[OutputType]
public sealed class GetSubscriptionsSubscriptionResult
{
/// <summary>
/// The [OCID](https://docs.cloud.oracle.com/iaas/Content/General/Concepts/identifiers.htm) of the compartment.
/// </summary>
public readonly string CompartmentId;
/// <summary>
/// The time when this suscription was created.
/// </summary>
public readonly string CreatedTime;
/// <summary>
/// Defined tags for this resource. Each key is predefined and scoped to a namespace. For more information, see [Resource Tags](https://docs.cloud.oracle.com/iaas/Content/General/Concepts/resourcetags.htm). Example: `{"Operations.CostCenter": "42"}`
/// </summary>
public readonly ImmutableDictionary<string, object> DefinedTags;
public readonly Outputs.GetSubscriptionsSubscriptionDeliveryPolicyResult DeliveryPolicy;
/// <summary>
/// A locator that corresponds to the subscription protocol. For example, an email address for a subscription that uses the `EMAIL` protocol, or a URL for a subscription that uses an HTTP-based protocol. Avoid entering confidential information.
/// </summary>
public readonly string Endpoint;
/// <summary>
/// For optimistic concurrency control. See `if-match`.
/// </summary>
public readonly string Etag;
/// <summary>
/// Free-form tags for this resource. Each tag is a simple key-value pair with no predefined name, type, or namespace. For more information, see [Resource Tags](https://docs.cloud.oracle.com/iaas/Content/General/Concepts/resourcetags.htm). Example: `{"Department": "Finance"}`
/// </summary>
public readonly ImmutableDictionary<string, object> FreeformTags;
/// <summary>
/// The [OCID](https://docs.cloud.oracle.com/iaas/Content/General/Concepts/identifiers.htm) of the subscription.
/// </summary>
public readonly string Id;
/// <summary>
/// The protocol used for the subscription.
/// </summary>
public readonly string Protocol;
/// <summary>
/// The lifecycle state of the subscription. The status of a new subscription is PENDING; when confirmed, the subscription status changes to ACTIVE.
/// </summary>
public readonly string State;
/// <summary>
/// Return all subscriptions that are subscribed to the given topic OCID. Either this query parameter or the compartmentId query parameter must be set.
/// </summary>
public readonly string TopicId;
[OutputConstructor]
private GetSubscriptionsSubscriptionResult(
string compartmentId,
string createdTime,
ImmutableDictionary<string, object> definedTags,
Outputs.GetSubscriptionsSubscriptionDeliveryPolicyResult deliveryPolicy,
string endpoint,
string etag,
ImmutableDictionary<string, object> freeformTags,
string id,
string protocol,
string state,
string topicId)
{
CompartmentId = compartmentId;
CreatedTime = createdTime;
DefinedTags = definedTags;
DeliveryPolicy = deliveryPolicy;
Endpoint = endpoint;
Etag = etag;
FreeformTags = freeformTags;
Id = id;
Protocol = protocol;
State = state;
TopicId = topicId;
}
}
}
| 40.708333 | 285 | 0.64304 | [
"ECL-2.0",
"Apache-2.0"
] | EladGabay/pulumi-oci | sdk/dotnet/Ons/Outputs/GetSubscriptionsSubscriptionResult.cs | 3,908 | C# |
using System;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Arcus.Observability.Correlation;
using Arcus.WebApi.Logging.Core.Correlation;
using GuardNet;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
using Microsoft.Extensions.Options;
using Microsoft.Extensions.Primitives;
// ReSharper disable once CheckNamespace
namespace Arcus.WebApi.Logging.Correlation
{
/// <summary>
/// Provides the functionality to correlate HTTP requests and responses according to configured <see cref="CorrelationInfoOptions"/>,
/// using the <see cref="ICorrelationInfoAccessor"/> to expose the result.
/// </summary>
/// <seealso cref="HttpCorrelationInfoAccessor"/>
public class HttpCorrelation : ICorrelationInfoAccessor
{
private readonly IHttpContextAccessor _httpContextAccessor;
private readonly HttpCorrelationInfoOptions _options;
private readonly ICorrelationInfoAccessor<CorrelationInfo> _correlationInfoAccessor;
private readonly ILogger<HttpCorrelation> _logger;
private static readonly Regex RequestIdRegex =
new Regex(@"^(\|)?([a-zA-Z0-9\-]+(\.[a-zA-Z0-9\-]+)?)+(_|\.)?$", RegexOptions.Compiled, matchTimeout: TimeSpan.FromSeconds(1));
/// <summary>
/// Initializes a new instance of the <see cref="HttpCorrelation"/> class.
/// </summary>
/// <param name="options">The options controlling how the correlation should happen.</param>
/// <param name="correlationInfoAccessor">The instance to set and retrieve the <see cref="CorrelationInfo"/> instance.</param>
/// <param name="logger">The logger to trace diagnostic messages during the correlation.</param>
/// <param name="httpContextAccessor">The instance to have access to the current HTTP context.</param>
/// <exception cref="ArgumentNullException">When any of the parameters are <c>null</c>.</exception>
/// <exception cref="ArgumentException">When the <paramref name="options"/> doesn't contain a non-<c>null</c> <see cref="IOptions{TOptions}.Value"/></exception>
public HttpCorrelation(
IOptions<HttpCorrelationInfoOptions> options,
IHttpContextAccessor httpContextAccessor,
IHttpCorrelationInfoAccessor correlationInfoAccessor,
ILogger<HttpCorrelation> logger)
#pragma warning disable CS0618 // Until we can remove the other constructor.
: this(options, httpContextAccessor, (ICorrelationInfoAccessor<CorrelationInfo>) correlationInfoAccessor, logger)
#pragma warning restore CS0618
{
}
/// <summary>
/// Initializes a new instance of the <see cref="HttpCorrelation"/> class.
/// </summary>
/// <param name="options">The options controlling how the correlation should happen.</param>
/// <param name="correlationInfoAccessor">The instance to set and retrieve the <see cref="CorrelationInfo"/> instance.</param>
/// <param name="logger">The logger to trace diagnostic messages during the correlation.</param>
/// <param name="httpContextAccessor">The instance to have access to the current HTTP context.</param>
/// <exception cref="ArgumentNullException">When any of the parameters are <c>null</c>.</exception>
/// <exception cref="ArgumentException">When the <paramref name="options"/> doesn't contain a non-<c>null</c> <see cref="IOptions{TOptions}.Value"/></exception>
[Obsolete("Use the constructor overload with the " + nameof(IHttpCorrelationInfoAccessor) + " instead")]
public HttpCorrelation(
IOptions<HttpCorrelationInfoOptions> options,
IHttpContextAccessor httpContextAccessor,
ICorrelationInfoAccessor<CorrelationInfo> correlationInfoAccessor,
ILogger<HttpCorrelation> logger)
{
Guard.NotNull(options, nameof(options), "Requires a set of options to configure the correlation process");
Guard.NotNull(httpContextAccessor, nameof(httpContextAccessor), "Requires a HTTP context accessor to get the current HTTP context");
Guard.NotNull(correlationInfoAccessor, nameof(correlationInfoAccessor), "Requires a correlation info instance to set and retrieve the correlation information");
Guard.NotNull(options.Value, nameof(options.Value), "Requires a value in the set of options to configure the correlation process");
_httpContextAccessor = httpContextAccessor;
_options = options.Value;
_correlationInfoAccessor = correlationInfoAccessor;
_logger = logger ?? NullLogger<HttpCorrelation>.Instance;
}
/// <summary>
/// Initializes a new instance of the <see cref="HttpCorrelation"/> class.
/// </summary>
/// <param name="options">The options controlling how the correlation should happen.</param>
/// <param name="correlationInfoAccessor">The instance to set and retrieve the <see cref="CorrelationInfo"/> instance.</param>
/// <param name="logger">The logger to trace diagnostic messages during the correlation.</param>
/// <param name="httpContextAccessor">The instance to have access to the current HTTP context.</param>
/// <exception cref="ArgumentNullException">When any of the parameters are <c>null</c>.</exception>
/// <exception cref="ArgumentException">When the <paramref name="options"/> doesn't contain a non-<c>null</c> <see cref="IOptions{TOptions}.Value"/></exception>
[Obsolete("Use the constructor overload with the " + nameof(HttpCorrelationInfoOptions) + " instead")]
public HttpCorrelation(
IOptions<CorrelationInfoOptions> options,
IHttpContextAccessor httpContextAccessor,
ICorrelationInfoAccessor<CorrelationInfo> correlationInfoAccessor,
ILogger<HttpCorrelation> logger)
: this(Options.Create(CreateHttpCorrelationOptions(options?.Value)), httpContextAccessor, correlationInfoAccessor, logger)
{
}
private static HttpCorrelationInfoOptions CreateHttpCorrelationOptions(CorrelationInfoOptions options)
{
if (options is null)
{
return new HttpCorrelationInfoOptions();
}
return new HttpCorrelationInfoOptions
{
Operation =
{
GenerateId = options.Operation.GenerateId,
HeaderName = options.Operation.HeaderName,
IncludeInResponse = options.Operation.IncludeInResponse
},
Transaction =
{
GenerateId = options.Transaction.GenerateId,
HeaderName = options.Transaction.HeaderName,
IncludeInResponse = options.Transaction.IncludeInResponse,
AllowInRequest = options.Transaction.AllowInRequest,
GenerateWhenNotSpecified = options.Transaction.GenerateWhenNotSpecified
}
};
}
/// <summary>
/// Gets the current correlation information initialized in this context.
/// </summary>
public CorrelationInfo GetCorrelationInfo()
{
return _correlationInfoAccessor.GetCorrelationInfo();
}
/// <summary>
/// Sets the current correlation information for this context.
/// </summary>
/// <param name="correlationInfo">The correlation model to set.</param>
/// <exception cref="ArgumentNullException">Thrown when the <paramref name="correlationInfo"/> is <c>null</c>.</exception>
public void SetCorrelationInfo(CorrelationInfo correlationInfo)
{
Guard.NotNull(correlationInfo, nameof(correlationInfo));
_correlationInfoAccessor.SetCorrelationInfo(correlationInfo);
}
/// <summary>
/// Correlate the current HTTP request according to the previously configured <see cref="CorrelationInfoOptions"/>;
/// returning an <paramref name="errorMessage"/> when the correlation failed.
/// </summary>
/// <param name="errorMessage">The failure message that describes why the correlation of the HTTP request wasn't successful.</param>
/// <returns>
/// <para>[true] when the HTTP request was successfully correlated and the HTTP response was altered accordingly;</para>
/// <para>[false] there was a problem with the correlation, describing the failure in the <paramref name="errorMessage"/>.</para>
/// </returns>
/// <exception cref="ArgumentNullException">Thrown when the given <see cref="HttpContext"/> is not available to correlate the request with the response.</exception>
/// <exception cref="ArgumentException">Thrown when the given <see cref="HttpContext"/> doesn't have any response headers to set the correlation headers.</exception>
public bool TryHttpCorrelate(out string errorMessage)
{
HttpContext httpContext = _httpContextAccessor.HttpContext;
Guard.NotNull(httpContext, nameof(httpContext), "Requires a HTTP context from the HTTP context accessor to start correlating the HTTP request");
Guard.For<ArgumentException>(() => httpContext.Response is null, "Requires a 'Response'");
Guard.For<ArgumentException>(() => httpContext.Response.Headers is null, "Requires a 'Response' object with headers");
if (httpContext.Request.Headers.TryGetValue(_options.Transaction.HeaderName, out StringValues transactionIds))
{
if (!_options.Transaction.AllowInRequest)
{
_logger.LogError("No correlation request header '{HeaderName}' for transaction ID was allowed in request", _options.Transaction.HeaderName);
errorMessage = $"No correlation transaction ID request header '{_options.Transaction.HeaderName}' was allowed in the request";
return false;
}
_logger.LogTrace("Correlation request header '{HeaderName}' found with transaction ID '{TransactionId}'", _options.Transaction.HeaderName, transactionIds);
}
string transactionId = DetermineTransactionId(transactionIds);
string operationId, operationParentId = null;
if (_options.UpstreamService.ExtractFromRequest && TryGetUpstreamOperationId(httpContext, out operationParentId))
{
operationId = ExtractOperationIdFromOperationParentId(operationParentId);
if (operationId is null)
{
_logger.LogError("No operation parent ID with a correct format could be found in the request header '{HeaderName}' which means no operation ID could be extracted", _options.UpstreamService.OperationParentIdHeaderName);
errorMessage = $"No correlation operation ID could be extracted from upstream service's '{_options.UpstreamService.OperationParentIdHeaderName}' request header";
return false;
}
}
else
{
operationId = DetermineOperationIdWithoutUpstreamService(httpContext);
}
httpContext.Features.Set(new CorrelationInfo(operationId, transactionId, operationParentId));
AddCorrelationResponseHeaders(httpContext);
errorMessage = null;
return true;
}
private string DetermineTransactionId(StringValues transactionIds)
{
var alreadyPresentTransactionId = transactionIds.ToString();
if (String.IsNullOrWhiteSpace(alreadyPresentTransactionId))
{
if (_options.Transaction.GenerateWhenNotSpecified)
{
_logger.LogTrace("No transactional ID was found in the request, generating one...");
string newlyGeneratedTransactionId = _options.Transaction.GenerateId();
if (String.IsNullOrWhiteSpace(newlyGeneratedTransactionId))
{
throw new InvalidOperationException(
$"Correlation cannot use function '{nameof(_options.Transaction.GenerateId)}' to generate an transaction ID because the resulting ID value is blank");
}
_logger.LogTrace("Generated '{TransactionId}' as transactional correlation ID", newlyGeneratedTransactionId);
return newlyGeneratedTransactionId;
}
_logger.LogTrace("No transactional correlation ID found in request header '{HeaderName}' but since the correlation options specifies that no transactional ID should be generated, there will be no ID present",
_options.Transaction.HeaderName);
return null;
}
_logger.LogTrace("Found transactional correlation ID '{TransactionId}' in request header '{HeaderName}'", alreadyPresentTransactionId, _options.Transaction.HeaderName);
return alreadyPresentTransactionId;
}
private bool TryGetUpstreamOperationId(HttpContext context, out string operationParentId)
{
if (context.Request.Headers.TryGetValue(_options.UpstreamService.OperationParentIdHeaderName, out StringValues requestId)
&& !String.IsNullOrWhiteSpace(requestId)
&& requestId.Count > 0
&& MatchesRequestIdFormat(requestId))
{
_logger.LogTrace("Found operation parent ID '{OperationParentId}' from upstream service in request's header '{HeaderName}'", requestId, _options.UpstreamService.OperationParentIdHeaderName);
operationParentId = requestId;
return true;
}
_logger.LogTrace("No operation parent ID found from upstream service in the request's header '{HeaderName}' that matches the expected format: |Guid.", _options.UpstreamService.OperationParentIdHeaderName);
operationParentId = null;
return false;
}
private bool MatchesRequestIdFormat(string requestId)
{
try
{
return RequestIdRegex.IsMatch(requestId);
}
catch (RegexMatchTimeoutException exception)
{
_logger.LogTrace(exception, "Upstream service's '{HeaderName}' was timed-out during regular expression validation", _options.UpstreamService.OperationParentIdHeaderName);
return false;
}
}
private string ExtractOperationIdFromOperationParentId(string operationParentId)
{
if (operationParentId is null)
{
return null;
}
// Returns the root ID from the '|' to the first '.' if any, according to W3C Trace-Context standard
// Ex. Request-Id=|7515DCD2-6340-41A9-AA4F-0E1DD28055B6.
// returns: 7515DCD2-6340-41A9-AA4F-0E1DD28055B6
_logger.LogTrace("Extracting operation ID from operation parent ID '{OperationParentId}' from the upstream service according to W3C Trace-Context standard", operationParentId);
int rootStart;
if (operationParentId[0] == '|')
{
rootStart = 1;
}
else
{
rootStart = 0;
}
int rootEnd = operationParentId.IndexOf('.');
if (rootEnd < 0)
{
rootEnd = operationParentId.Length;
}
string operationId = operationParentId.Substring(rootStart, rootEnd - rootStart);
_logger.LogTrace("Extracted operation ID '{OperationId}' from operation parent ID '{OperationParentId}' from the upstream service", operationId, operationParentId);
return operationId;
}
private string DetermineOperationIdWithoutUpstreamService(HttpContext httpContext)
{
if (String.IsNullOrWhiteSpace(httpContext.TraceIdentifier))
{
_logger.LogTrace("No unique trace identifier ID was found in the request, generating one...");
string operationId = _options.Operation.GenerateId();
if (String.IsNullOrWhiteSpace(operationId))
{
throw new InvalidOperationException(
$"Correlation cannot use '{nameof(_options.Operation.GenerateId)}' to generate an operation ID because the resulting ID value is blank");
}
_logger.LogTrace("Generated '{OperationId}' as unique operation correlation ID", operationId);
return operationId;
}
_logger.LogTrace("Found unique trace identifier ID '{TraceIdentifier}' for operation correlation ID", httpContext.TraceIdentifier);
return httpContext.TraceIdentifier;
}
private void AddCorrelationResponseHeaders(HttpContext httpContext)
{
if (_options.Operation.IncludeInResponse)
{
_logger.LogTrace("Prepare for the operation correlation ID to be included in the response...");
httpContext.Response.OnStarting(() =>
{
CorrelationInfo correlationInfo = _correlationInfoAccessor.GetCorrelationInfo();
if (String.IsNullOrWhiteSpace(correlationInfo?.OperationId))
{
_logger.LogWarning("No response header was added given no operation correlation ID was found");
}
else
{
AddResponseHeader(httpContext, _options.Operation.HeaderName, correlationInfo.OperationId);
}
return Task.CompletedTask;
});
}
if (_options.Transaction.IncludeInResponse)
{
_logger.LogTrace("Prepare for the transactional correlation ID to be included in the response...");
httpContext.Response.OnStarting(() =>
{
CorrelationInfo correlationInfo = _correlationInfoAccessor.GetCorrelationInfo();
if (String.IsNullOrWhiteSpace(correlationInfo?.TransactionId))
{
_logger.LogWarning("No response header was added given no transactional correlation ID was found");
}
else
{
AddResponseHeader(httpContext, _options.Transaction.HeaderName, correlationInfo.TransactionId);
}
return Task.CompletedTask;
});
}
}
private void AddResponseHeader(HttpContext httpContext, string headerName, string headerValue)
{
_logger.LogTrace("Setting correlation response header '{HeaderName}' to '{CorrelationId}'", headerName, headerValue);
httpContext.Response.Headers[headerName] = headerValue;
}
}
}
| 53.417582 | 238 | 0.640918 | [
"MIT"
] | arcus-azure/arcus.webapi | src/Arcus.WebApi.Logging.Core/Correlation/HttpCorrelation.cs | 19,446 | C# |
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
namespace Xamarin.Forms
{
public class SwipeItems : Element, IList<ISwipeItem>, INotifyCollectionChanged
{
readonly ObservableCollection<ISwipeItem> _internal;
public SwipeItems()
{
_internal = new ObservableCollection<ISwipeItem>();
_internal.CollectionChanged += OnSwipeItemsChanged;
}
public static readonly BindableProperty ModeProperty = BindableProperty.Create(nameof(Mode), typeof(SwipeMode), typeof(SwipeItems), SwipeMode.Reveal);
public static readonly BindableProperty SwipeBehaviorOnInvokedProperty = BindableProperty.Create(nameof(SwipeBehaviorOnInvoked), typeof(SwipeBehaviorOnInvoked), typeof(SwipeItems), SwipeBehaviorOnInvoked.Auto);
public SwipeMode Mode
{
get { return (SwipeMode)GetValue(ModeProperty); }
set { SetValue(ModeProperty, value); }
}
public SwipeBehaviorOnInvoked SwipeBehaviorOnInvoked
{
get { return (SwipeBehaviorOnInvoked)GetValue(SwipeBehaviorOnInvokedProperty); }
set { SetValue(SwipeBehaviorOnInvokedProperty, value); }
}
public event NotifyCollectionChangedEventHandler CollectionChanged
{
add { _internal.CollectionChanged += value; }
remove { _internal.CollectionChanged -= value; }
}
public ISwipeItem this[int index]
{
get => _internal.Count > index ? _internal[index] : null;
set => _internal[index] = value;
}
public int Count => _internal.Count;
public bool IsReadOnly => false;
public void Add(ISwipeItem item)
{
_internal.Add(item);
}
public void Clear()
{
_internal.Clear();
}
public bool Contains(ISwipeItem item)
{
return _internal.Contains(item);
}
public void CopyTo(ISwipeItem[] array, int arrayIndex)
{
_internal.CopyTo(array, arrayIndex);
}
public IEnumerator<ISwipeItem> GetEnumerator()
{
return _internal.GetEnumerator();
}
public int IndexOf(ISwipeItem item)
{
return _internal.IndexOf(item);
}
public void Insert(int index, ISwipeItem item)
{
_internal.Insert(index, item);
}
public bool Remove(ISwipeItem item)
{
return _internal.Remove(item);
}
public void RemoveAt(int index)
{
_internal.RemoveAt(index);
}
protected override void OnBindingContextChanged()
{
base.OnBindingContextChanged();
object bc = BindingContext;
foreach (BindableObject item in _internal)
SetInheritedBindingContext(item, bc);
}
void OnSwipeItemsChanged(object sender, NotifyCollectionChangedEventArgs notifyCollectionChangedEventArgs)
{
if (notifyCollectionChangedEventArgs.NewItems == null)
return;
object bc = BindingContext;
foreach (BindableObject item in notifyCollectionChangedEventArgs.NewItems)
SetInheritedBindingContext(item, bc);
}
IEnumerator IEnumerable.GetEnumerator()
{
return _internal.GetEnumerator();
}
}
} | 24.4 | 212 | 0.745902 | [
"MIT"
] | 1iveowl/Xamarin.Forms | Xamarin.Forms.Core/SwipeItems.cs | 2,930 | C# |
using System;
using Android.App;
using Android.Content.PM;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.OS;
using Xamarin.Forms.Platform.Android;
namespace Cookies.Tests.Droid
{
[Activity(Label = "Cookies.Tests", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)]
public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsApplicationActivity
{
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
global::Xamarin.Forms.Forms.Init(this, bundle);
LoadApplication(new App());
}
}
}
| 25.111111 | 137 | 0.705015 | [
"MIT"
] | MedElba/CookieXamarinExample | Cookies.Tests/Cookies.Tests.Android/MainActivity.cs | 680 | C# |
using UnityEngine;
namespace PF
{
/** Integer Rectangle.
* Works almost like UnityEngine.Rect but with integer coordinates
*/
[System.Serializable]
public struct IntRect {
public int xmin, ymin, xmax, ymax;
public IntRect (int xmin, int ymin, int xmax, int ymax) {
this.xmin = xmin;
this.xmax = xmax;
this.ymin = ymin;
this.ymax = ymax;
}
public bool Contains (int x, int y) {
return !(x < xmin || y < ymin || x > xmax || y > ymax);
}
public int Width {
get {
return xmax-xmin+1;
}
}
public int Height {
get {
return ymax-ymin+1;
}
}
/** Returns if this rectangle is valid.
* An invalid rect could have e.g xmin > xmax.
* Rectamgles with a zero area area invalid.
*/
public bool IsValid () {
return xmin <= xmax && ymin <= ymax;
}
public static bool operator == (IntRect a, IntRect b) {
return a.xmin == b.xmin && a.xmax == b.xmax && a.ymin == b.ymin && a.ymax == b.ymax;
}
public static bool operator != (IntRect a, IntRect b) {
return a.xmin != b.xmin || a.xmax != b.xmax || a.ymin != b.ymin || a.ymax != b.ymax;
}
public override bool Equals (System.Object obj) {
var rect = (IntRect)obj;
return xmin == rect.xmin && xmax == rect.xmax && ymin == rect.ymin && ymax == rect.ymax;
}
public override int GetHashCode () {
return xmin*131071 ^ xmax*3571 ^ ymin*3109 ^ ymax*7;
}
/** Returns the intersection rect between the two rects.
* The intersection rect is the area which is inside both rects.
* If the rects do not have an intersection, an invalid rect is returned.
* \see IsValid
*/
public static IntRect Intersection (IntRect a, IntRect b) {
return new IntRect(
System.Math.Max(a.xmin, b.xmin),
System.Math.Max(a.ymin, b.ymin),
System.Math.Min(a.xmax, b.xmax),
System.Math.Min(a.ymax, b.ymax)
);
}
/** Returns if the two rectangles intersect each other
*/
public static bool Intersects (IntRect a, IntRect b) {
return !(a.xmin > b.xmax || a.ymin > b.ymax || a.xmax < b.xmin || a.ymax < b.ymin);
}
/** Returns a new rect which contains both input rects.
* This rectangle may contain areas outside both input rects as well in some cases.
*/
public static IntRect Union (IntRect a, IntRect b) {
return new IntRect(
System.Math.Min(a.xmin, b.xmin),
System.Math.Min(a.ymin, b.ymin),
System.Math.Max(a.xmax, b.xmax),
System.Math.Max(a.ymax, b.ymax)
);
}
/** Returns a new IntRect which is expanded to contain the point */
public IntRect ExpandToContain (int x, int y) {
return new IntRect(
System.Math.Min(xmin, x),
System.Math.Min(ymin, y),
System.Math.Max(xmax, x),
System.Math.Max(ymax, y)
);
}
/** Returns a new rect which is expanded by \a range in all directions.
* \param range How far to expand. Negative values are permitted.
*/
public IntRect Expand (int range) {
return new IntRect(xmin-range,
ymin-range,
xmax+range,
ymax+range
);
}
/** Matrices for rotation.
* Each group of 4 elements is a 2x2 matrix.
* The XZ position is multiplied by this.
* So
* \code
* //A rotation by 90 degrees clockwise, second matrix in the array
* (5,2) * ((0, 1), (-1, 0)) = (2,-5)
* \endcode
*/
private static readonly int[] Rotations = {
1, 0, //Identity matrix
0, 1,
0, 1,
-1, 0,
-1, 0,
0, -1,
0, -1,
1, 0
};
/** Returns a new rect rotated around the origin 90*r degrees.
* Ensures that a valid rect is returned.
*/
public IntRect Rotate (int r) {
int mx1 = Rotations[r*4+0];
int mx2 = Rotations[r*4+1];
int my1 = Rotations[r*4+2];
int my2 = Rotations[r*4+3];
int p1x = mx1*xmin + mx2*ymin;
int p1y = my1*xmin + my2*ymin;
int p2x = mx1*xmax + mx2*ymax;
int p2y = my1*xmax + my2*ymax;
return new IntRect(
System.Math.Min(p1x, p2x),
System.Math.Min(p1y, p2y),
System.Math.Max(p1x, p2x),
System.Math.Max(p1y, p2y)
);
}
/** Returns a new rect which is offset by the specified amount.
*/
public IntRect Offset (Int2 offset) {
return new IntRect(xmin+offset.x, ymin + offset.y, xmax + offset.x, ymax + offset.y);
}
/** Returns a new rect which is offset by the specified amount.
*/
public IntRect Offset (int x, int y) {
return new IntRect(xmin+x, ymin + y, xmax + x, ymax + y);
}
public override string ToString () {
return "[x: "+xmin+"..."+xmax+", y: " + ymin +"..."+ymax+"]";
}
#if !SERVER
/** Draws some debug lines representing the rect */
public void DebugDraw (GraphTransform transform, UnityEngine.Color color) {
Vector3 p1 = transform.Transform(new Vector3(xmin, 0, ymin));
Vector3 p2 = transform.Transform(new Vector3(xmin, 0, ymax));
Vector3 p3 = transform.Transform(new Vector3(xmax, 0, ymax));
Vector3 p4 = transform.Transform(new Vector3(xmax, 0, ymin));
UnityEngine.Debug.DrawLine(p1, p2, color);
UnityEngine.Debug.DrawLine(p2, p3, color);
UnityEngine.Debug.DrawLine(p3, p4, color);
UnityEngine.Debug.DrawLine(p4, p1, color);
}
#endif
}
} | 27.842105 | 92 | 0.604348 | [
"MIT"
] | naivetang/2019MiniGame22 | Unity/Assets/Model/Module/Pathfinding/Recast/IntRect.cs | 5,290 | C# |
using CSPlang.Any2;
namespace CSPlang
{
class PoisonableAny2AnyChannelIntImpl : Any2AnyIntImpl
{
internal PoisonableAny2AnyChannelIntImpl(int _immunity) : base(new PoisonableOne2OneChannelIntImpl(_immunity))
{
}
}
} | 19.538462 | 118 | 0.708661 | [
"MIT"
] | PasierbKarol/CSPsharp | CSPlang/Poisonable/PoisonableAny2AnyChannelIntImpl.cs | 254 | C# |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Threading.Tasks;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics.AddUsing
{
public partial class AddUsingTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest
{
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddUsing)]
public async Task TestWhereExtension()
{
await TestAsync(
@"using System ; using System . Collections . Generic ; class Program { static void Main ( string [ ] args ) { var q = args . [|Where|] } } ",
@"using System ; using System . Collections . Generic ; using System . Linq ; class Program { static void Main ( string [ ] args ) { var q = args . Where } } ");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddUsing)]
public async Task TestSelectExtension()
{
await TestAsync(
@"using System ; using System . Collections . Generic ; class Program { static void Main ( string [ ] args ) { var q = args . [|Select|] } } ",
@"using System ; using System . Collections . Generic ; using System . Linq ; class Program { static void Main ( string [ ] args ) { var q = args . Select } } ");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddUsing)]
public async Task TestGroupByExtension()
{
await TestAsync(
@"using System ; using System . Collections . Generic ; class Program { static void Main ( string [ ] args ) { var q = args . [|GroupBy|] } } ",
@"using System ; using System . Collections . Generic ; using System . Linq ; class Program { static void Main ( string [ ] args ) { var q = args . GroupBy } } ");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddUsing)]
public async Task TestJoinExtension()
{
await TestAsync(
@"using System ; using System . Collections . Generic ; class Program { static void Main ( string [ ] args ) { var q = args . [|Join|] } } ",
@"using System ; using System . Collections . Generic ; using System . Linq ; class Program { static void Main ( string [ ] args ) { var q = args . Join } } ");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddUsing)]
public async Task RegressionFor8455()
{
await TestMissingAsync(
@"class C { void M ( ) { int dim = ( int ) Math . [|Min|] ( ) ; } } ");
}
[WorkItem(772321, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/772321")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddUsing)]
public async Task TestExtensionWithThePresenceOfTheSameNameNonExtensionMethod()
{
await TestAsync(
@"namespace NS1 { class Program { void Main() { [|new C().Foo(4);|] } } class C { public void Foo(string y) { } } } namespace NS2 { static class CExt { public static void Foo(this NS1.C c, int x) { } } } ",
@"using NS2; namespace NS1 { class Program { void Main() { new C().Foo(4); } } class C { public void Foo(string y) { } } } namespace NS2 { static class CExt { public static void Foo(this NS1.C c, int x) { } } } ");
}
[WorkItem(772321, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/772321")]
[WorkItem(920398, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/920398")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddUsing)]
public async Task TestExtensionWithThePresenceOfTheSameNameNonExtensionPrivateMethod()
{
await TestAsync(
@"namespace NS1 { class Program { void Main() { [|new C().Foo(4);|] } } class C { private void Foo(int x) { } } } namespace NS2 { static class CExt { public static void Foo(this NS1.C c, int x) { } } } ",
@"using NS2; namespace NS1 { class Program { void Main() { new C().Foo(4); } } class C { private void Foo(int x) { } } } namespace NS2 { static class CExt { public static void Foo(this NS1.C c, int x) { } } } ");
}
[WorkItem(772321, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/772321")]
[WorkItem(920398, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/920398")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddUsing)]
public async Task TestExtensionWithThePresenceOfTheSameNameExtensionPrivateMethod()
{
await TestAsync(
@"using NS2; namespace NS1 { class Program { void Main() { [|new C().Foo(4);|] } } class C { } } namespace NS2 { static class CExt { private static void Foo(this NS1.C c, int x) { } } } namespace NS3 { static class CExt { public static void Foo(this NS1.C c, int x) { } } } ",
@"using NS2; using NS3; namespace NS1 { class Program { void Main() { new C().Foo(4); } } class C { } } namespace NS2 { static class CExt { private static void Foo(this NS1.C c, int x) { } } } namespace NS3 { static class CExt { public static void Foo(this NS1.C c, int x) { } } } ");
}
[WorkItem(269, "https://github.com/dotnet/roslyn/issues/269")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddUsing)]
public async Task TestAddUsingForAddExtentionMethod()
{
await TestAsync(
@"using System ; using System . Collections ; class X : IEnumerable { public IEnumerator GetEnumerator ( ) { new X { [|1|] } ; return null ; } } namespace Ext { static class Extensions { public static void Add ( this X x , int i ) { } } } ",
@"using System ; using System . Collections ; using Ext ; class X : IEnumerable { public IEnumerator GetEnumerator ( ) { new X { 1 } ; return null ; } } namespace Ext { static class Extensions { public static void Add ( this X x , int i ) { } } } ",
parseOptions: null);
}
[WorkItem(269, "https://github.com/dotnet/roslyn/issues/269")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddUsing)]
public async Task TestAddUsingForAddExtentionMethod2()
{
await TestAsync(
@"using System ; using System . Collections ; class X : IEnumerable { public IEnumerator GetEnumerator ( ) { new X { 1 , 2 , [|3|] } ; return null ; } } namespace Ext { static class Extensions { public static void Add ( this X x , int i ) { } } } ",
@"using System ; using System . Collections ; using Ext ; class X : IEnumerable { public IEnumerator GetEnumerator ( ) { new X { 1 , 2 , 3 } ; return null ; } } namespace Ext { static class Extensions { public static void Add ( this X x , int i ) { } } } ",
parseOptions: null);
}
[WorkItem(269, "https://github.com/dotnet/roslyn/issues/269")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddUsing)]
public async Task TestAddUsingForAddExtentionMethod3()
{
await TestAsync(
@"using System ; using System . Collections ; class X : IEnumerable { public IEnumerator GetEnumerator ( ) { new X { 1 , [|2|] , 3 } ; return null ; } } namespace Ext { static class Extensions { public static void Add ( this X x , int i ) { } } } ",
@"using System ; using System . Collections ; using Ext ; class X : IEnumerable { public IEnumerator GetEnumerator ( ) { new X { 1 , 2 , 3 } ; return null ; } } namespace Ext { static class Extensions { public static void Add ( this X x , int i ) { } } } ",
parseOptions: null);
}
[WorkItem(269, "https://github.com/dotnet/roslyn/issues/269")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddUsing)]
public async Task TestAddUsingForAddExtentionMethod4()
{
await TestAsync(
@"using System ; using System . Collections ; class X : IEnumerable { public IEnumerator GetEnumerator ( ) { new X { { 1 , 2 , 3 } , [|{ 4 , 5 , 6 }|] , { 7 , 8 , 9 } } ; return null ; } } namespace Ext { static class Extensions { public static void Add ( this X x , int i ) { } } } ",
@"using System ; using System . Collections ; using Ext ; class X : IEnumerable { public IEnumerator GetEnumerator ( ) { new X { { 1 , 2 , 3 } , { 4 , 5 , 6 } , { 7 , 8 , 9 } } ; return null ; } } namespace Ext { static class Extensions { public static void Add ( this X x , int i ) { } } } ",
parseOptions: null);
}
[WorkItem(269, "https://github.com/dotnet/roslyn/issues/269")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddUsing)]
public async Task TestAddUsingForAddExtentionMethod5()
{
await TestAsync(
@"using System ; using System . Collections ; class X : IEnumerable { public IEnumerator GetEnumerator ( ) { new X { { 1 , 2 , 3 } , { 4 , 5 , 6 } , [|{ 7 , 8 , 9 }|] } ; return null ; } } namespace Ext { static class Extensions { public static void Add ( this X x , int i ) { } } } ",
@"using System ; using System . Collections ; using Ext ; class X : IEnumerable { public IEnumerator GetEnumerator ( ) { new X { { 1 , 2 , 3 } , { 4 , 5 , 6 } , { 7 , 8 , 9 } } ; return null ; } } namespace Ext { static class Extensions { public static void Add ( this X x , int i ) { } } } ",
parseOptions: null);
}
[WorkItem(269, "https://github.com/dotnet/roslyn/issues/269")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddUsing)]
public async Task TestAddUsingForAddExtentionMethod6()
{
await TestAsync(
@"using System ; using System . Collections ; class X : IEnumerable { public IEnumerator GetEnumerator ( ) { new X { { 1 , 2 , 3 } , { ""Four"" , ""Five"" , ""Six"" } , [|{ '7' , '8' , '9' }|] } ; return null ; } } namespace Ext { static class Extensions { public static void Add ( this X x , int i ) { } } } ",
@"using System ; using System . Collections ; using Ext ; class X : IEnumerable { public IEnumerator GetEnumerator ( ) { new X { { 1 , 2 , 3 } , { ""Four"" , ""Five"" , ""Six"" } , { '7' , '8' , '9' } } ; return null ; } } namespace Ext { static class Extensions { public static void Add ( this X x , int i ) { } } } ",
parseOptions: null);
}
[WorkItem(269, "https://github.com/dotnet/roslyn/issues/269")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddUsing)]
public async Task TestAddUsingForAddExtentionMethod7()
{
await TestAsync(
@"using System ; using System . Collections ; class X : IEnumerable { public IEnumerator GetEnumerator ( ) { new X { { 1 , 2 , 3 } , [|{ ""Four"" , ""Five"" , ""Six"" }|] , { '7' , '8' , '9' } } ; return null ; } } namespace Ext { static class Extensions { public static void Add ( this X x , int i ) { } } } ",
@"using System ; using System . Collections ; using Ext ; class X : IEnumerable { public IEnumerator GetEnumerator ( ) { new X { { 1 , 2 , 3 } , { ""Four"" , ""Five"" , ""Six"" } , { '7' , '8' , '9' } } ; return null ; } } namespace Ext { static class Extensions { public static void Add ( this X x , int i ) { } } } ",
parseOptions: null);
}
[WorkItem(269, "https://github.com/dotnet/roslyn/issues/269")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddUsing)]
public async Task TestAddUsingForAddExtentionMethod8()
{
await TestAsync(
@"using System ; using System . Collections ; class X : IEnumerable { public IEnumerator GetEnumerator ( ) { new X { [|{ 1 , 2 , 3 }|] } ; return null ; } } namespace Ext { static class Extensions { public static void Add ( this X x , int i ) { } } } ",
@"using System ; using System . Collections ; using Ext ; class X : IEnumerable { public IEnumerator GetEnumerator ( ) { new X { { 1 , 2 , 3 } } ; return null ; } } namespace Ext { static class Extensions { public static void Add ( this X x , int i ) { } } } ",
parseOptions: null);
}
[WorkItem(269, "https://github.com/dotnet/roslyn/issues/269")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddUsing)]
public async Task TestAddUsingForAddExtentionMethod9()
{
await TestAsync(
@"using System ; using System . Collections ; class X : IEnumerable { public IEnumerator GetEnumerator ( ) { new X { [|""This""|] } ; return null ; } } namespace Ext { static class Extensions { public static void Add ( this X x , int i ) { } } } ",
@"using System ; using System . Collections ; using Ext ; class X : IEnumerable { public IEnumerator GetEnumerator ( ) { new X { ""This"" } ; return null ; } } namespace Ext { static class Extensions { public static void Add ( this X x , int i ) { } } } ",
parseOptions: null);
}
[WorkItem(269, "https://github.com/dotnet/roslyn/issues/269")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddUsing)]
public async Task TestAddUsingForAddExtentionMethod10()
{
await TestAsync(
@"using System ; using System . Collections ; class X : IEnumerable { public IEnumerator GetEnumerator ( ) { new X { [|{ 1 , 2 , 3 }|] , { ""Four"" , ""Five"" , ""Six"" } , { '7' , '8' , '9' } } ; return null ; } } namespace Ext { static class Extensions { public static void Add ( this X x , int i ) { } } } namespace Ext2 { static class Extensions { public static void Add ( this X x , object [ ] i ) { } } } ",
@"using System ; using System . Collections ; using Ext ; class X : IEnumerable { public IEnumerator GetEnumerator ( ) { new X { { 1 , 2 , 3 } , { ""Four"" , ""Five"" , ""Six"" } , { '7' , '8' , '9' } } ; return null ; } } namespace Ext { static class Extensions { public static void Add ( this X x , int i ) { } } } namespace Ext2 { static class Extensions { public static void Add ( this X x , object [ ] i ) { } } } ",
parseOptions: null);
}
[WorkItem(269, "https://github.com/dotnet/roslyn/issues/269")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddUsing)]
public async Task TestAddUsingForAddExtentionMethod11()
{
await TestAsync(
@"using System ; using System . Collections ; class X : IEnumerable { public IEnumerator GetEnumerator ( ) { new X { [|{ 1 , 2 , 3 }|] , { ""Four"" , ""Five"" , ""Six"" } , { '7' , '8' , '9' } } ; return null ; } } namespace Ext { static class Extensions { public static void Add ( this X x , int i ) { } } } namespace Ext2 { static class Extensions { public static void Add ( this X x , object [ ] i ) { } } } ",
@"using System ; using System . Collections ; using Ext2 ; class X : IEnumerable { public IEnumerator GetEnumerator ( ) { new X { { 1 , 2 , 3 } , { ""Four"" , ""Five"" , ""Six"" } , { '7' , '8' , '9' } } ; return null ; } } namespace Ext { static class Extensions { public static void Add ( this X x , int i ) { } } } namespace Ext2 { static class Extensions { public static void Add ( this X x , object [ ] i ) { } } } ",
index: 1,
parseOptions: null);
}
[WorkItem(3818, "https://github.com/dotnet/roslyn/issues/3818")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddUsing)]
public async Task InExtensionMethodUnderConditionalAccessExpression()
{
var initialText =
@"<Workspace>
<Project Language=""C#"" AssemblyName=""CSAssembly"" CommonReferences=""true"">
<Document FilePath = ""Program"">
namespace Sample
{
class Program
{
static void Main(string[] args)
{
string myString = ""Sample"";
var other = myString?[|.StringExtension()|].Substring(0);
}
}
}
</Document>
<Document FilePath = ""Extensions"">
namespace Sample.Extensions
{
public static class StringExtensions
{
public static string StringExtension(this string s)
{
return ""Ok"";
}
}
}
</Document>
</Project>
</Workspace>";
var expectedText =
@"using Sample.Extensions;
namespace Sample
{
class Program
{
static void Main(string[] args)
{
string myString = ""Sample"";
var other = myString?.StringExtension().Substring(0);
}
}
}";
await TestAsync(initialText, expectedText);
}
[WorkItem(3818, "https://github.com/dotnet/roslyn/issues/3818")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddUsing)]
public async Task InExtensionMethodUnderMultipleConditionalAccessExpressions()
{
var initialText =
@"<Workspace>
<Project Language=""C#"" AssemblyName=""CSAssembly"" CommonReferences=""true"">
<Document FilePath = ""Program"">
public class C
{
public T F<T>(T x)
{
return F(new C())?.F(new C())?[|.Extn()|];
}
}
</Document>
<Document FilePath = ""Extensions"">
namespace Sample.Extensions
{
public static class Extensions
{
public static C Extn(this C obj)
{
return obj.F(new C());
}
}
}
</Document>
</Project>
</Workspace>";
var expectedText =
@"using Sample.Extensions;
public class C
{
public T F<T>(T x)
{
return F(new C())?.F(new C())?.Extn();
}
}";
await TestAsync(initialText, expectedText);
}
[WorkItem(3818, "https://github.com/dotnet/roslyn/issues/3818")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddUsing)]
public async Task InExtensionMethodUnderMultipleConditionalAccessExpressions2()
{
var initialText =
@"<Workspace>
<Project Language=""C#"" AssemblyName=""CSAssembly"" CommonReferences=""true"">
<Document FilePath = ""Program"">
public class C
{
public T F<T>(T x)
{
return F(new C())?.F(new C())[|.Extn()|]?.F(newC());
}
}
</Document>
<Document FilePath = ""Extensions"">
namespace Sample.Extensions
{
public static class Extensions
{
public static C Extn(this C obj)
{
return obj.F(new C());
}
}
}
</Document>
</Project>
</Workspace>";
var expectedText =
@"using Sample.Extensions;
public class C
{
public T F<T>(T x)
{
return F(new C())?.F(new C()).Extn()?.F(newC());
}
}";
await TestAsync(initialText, expectedText);
}
}
}
| 55.506098 | 422 | 0.614852 | [
"Apache-2.0"
] | Unknown6656/roslyn | src/EditorFeatures/CSharpTest/Diagnostics/AddUsing/AddUsingTests_ExtensionMethods.cs | 18,206 | C# |
using UnityEngine;
public class PlataformPoint : MonoBehaviour
{
[SerializeField] private PlataformPoint targetPoint;
private bool isReached = false;
public bool WaitForTargetReached()
{
return targetPoint.GetIsReached();
}
public bool GetIsReached()
{
return isReached;
}
public Transform GetTargetPointPosition()
{
return targetPoint.transform;
}
public bool PlataformDistance(Transform plataform)
{
if (Vector3.Distance(plataform.position, transform.position) < 1 && isReached == false)
{
isReached = true;
return true;
}
return false;
}
}
| 18.783784 | 95 | 0.617266 | [
"MIT"
] | atletist/platformgame | Assets/Scripts/Lab/PlataformPoint.cs | 695 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Model
{
public class GetIndex
{
public DateTime CreateDate { get; set; }
public string Account { get; set; }
public string Body { get; set; }
public int ID { get; set; }
public string Title { get; set; }
public bool ismaincontent { get; set; }
}
}
| 20.809524 | 48 | 0.627002 | [
"MIT"
] | dearme61002/MsgBoard | MsgBoardSystem/Model/GetIndex.cs | 439 | C# |
namespace Clase7v2.Authorization
{
public static class PermissionNames
{
public const string Pages_Tenants = "Pages.Tenants";
public const string Pages_Users = "Pages.Users";
public const string Pages_Users_Activation = "Pages.Users.Activation";
public const string Pages_Roles = "Pages.Roles";
}
}
| 26.615385 | 78 | 0.690751 | [
"MIT"
] | REL1980/Clase7v2 | aspnet-core/src/Clase7v2.Core/Authorization/PermissionNames.cs | 348 | C# |
using System.Threading.Tasks;
namespace DragonSpark.Model.Operations;
public class AppendedOperate : IOperation
{
readonly Operate _previous, _current;
public AppendedOperate(Operate previous, Operate current)
{
_previous = previous;
_current = current;
}
public async ValueTask Get()
{
await _previous();
await _current();
}
} | 17.4 | 58 | 0.747126 | [
"MIT"
] | DragonSpark/Framework | DragonSpark/Model/Operations/AppendedOperate.cs | 350 | C# |
using Newtonsoft.Json;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Text;
using UnityEngine;
using UnityEngine.SceneManagement;
namespace CommonCore
{
/// <summary>
/// Core Utilities class: Contains functions for loading resources, saving/loading JSON, getting root transforms and a few other miscellaneous things.
/// </summary>
public static class CoreUtils
{
internal static CCResourceManager ResourceManager {get; set;}
/// <summary>
/// Load a resource, respecting virtual/redirected paths
/// </summary>
public static T LoadResource<T>(string path) where T: UnityEngine.Object
{
return ResourceManager.GetResource<T>(path);
}
/// <summary>
/// Load resources from a folder, respecting virtual/redirected paths
/// </summary>
public static T[] LoadResources<T>(string path) where T: UnityEngine.Object
{
return ResourceManager.GetResources<T>(path);
}
/// <summary>
/// Load a resource, returning a prioritized collection based on virtual/redirected path precedence
/// </summary>
public static T[] LoadDataResource<T>(string path) where T: UnityEngine.Object
{
return ResourceManager.GetDataResource<T>(path);
}
/// <summary>
/// Load resources from a folder, returning a prioritized collection based on virtual/redirected path precedence
/// </summary>
public static T[][] LoadDataResources<T>(string path) where T: UnityEngine.Object
{
return ResourceManager.GetDataResources<T>(path);
}
/// <summary>
/// Check if a resource exists, respecting virtual/redirected paths
/// </summary>
public static bool CheckResource<T>(string path) where T: UnityEngine.Object
{
return ResourceManager.ContainsResource<T>(path);
}
public static T LoadExternalJson<T>(string path)
{
if (!File.Exists(path))
{
return default(T);
}
string text = File.ReadAllText(path);
return LoadJson<T>(text);
}
public static T LoadJson<T>(string text)
{
return JsonConvert.DeserializeObject<T>(text, new JsonSerializerSettings
{
Converters = CCJsonConverters.Defaults.Converters,
TypeNameHandling = TypeNameHandling.Auto
});
}
public static void SaveExternalJson(string path, System.Object obj)
{
string json = SaveJson(obj);
File.WriteAllText(path, json);
}
public static string SaveJson(object obj)
{
return JsonConvert.SerializeObject(obj, Formatting.Indented, new JsonSerializerSettings
{
Converters = CCJsonConverters.Defaults.Converters,
TypeNameHandling = TypeNameHandling.Auto
});
}
/// <summary>
/// Gets a list of scenes (by name) in the game
/// </summary>
/// <returns>A list of scenes in the game</returns>
public static string[] GetSceneList() //TODO we'll probably move this into some kind of CommonCore.SceneManagement
{
int sceneCount = SceneManager.sceneCountInBuildSettings;
var scenes = new List<string>(sceneCount);
for (int i = 0; i < sceneCount; i++)
{
try
{
scenes.Add(SceneUtility.GetScenePathByBuildIndex(i));
}
catch (Exception e)
{
//ignore it, we've gone over or some stupid bullshit
}
}
return scenes.ToArray();
}
private static Transform WorldRoot;
public static Transform GetWorldRoot() //TODO really ought to move this
{
if (WorldRoot == null)
{
GameObject rootGo = GameObject.Find("WorldRoot");
if (rootGo == null)
return null;
WorldRoot = rootGo.transform;
}
return WorldRoot;
}
private static Transform UIRoot;
public static Transform GetUIRoot()
{
if(UIRoot == null)
{
GameObject rootGo = GameObject.Find("UIRoot");
if (rootGo == null)
rootGo = new GameObject("UIRoot");
UIRoot = rootGo.transform;
}
return UIRoot;
}
}
} | 32.506849 | 154 | 0.562158 | [
"MIT"
] | XCVG/heavymetalslug | Assets/CommonCore/Core/CoreUtils.cs | 4,748 | C# |
namespace Endscript
{
/// <summary>
/// Represents executable caller version that is being checked when parsing endscript files.
/// </summary>
public static class Version
{
/// <summary>
/// Major version value of executable caller.
/// </summary>
public static System.Version Value { get; set; }
}
}
| 22.642857 | 93 | 0.684543 | [
"MIT"
] | SpeedReflect/Endscript | Endscript/Version.cs | 319 | C# |
using System;
namespace AMKsGear.Architecture
{
public static class ConstantTable
{
public const AttributeTargets AllMembers = AttributeTargets.Event | AttributeTargets.Field | AttributeTargets.Method | AttributeTargets.Property;
public const AttributeTargets AllValueMembers = AttributeTargets.Field | AttributeTargets.Property;
}
} | 36.2 | 153 | 0.779006 | [
"Unlicense",
"MIT"
] | amkherad/AMKs-Gear.net | 00-Core/Architecture/ConstantTable.cs | 362 | C# |
using System;
using Aquarius.Weixin.Entity.Enums;
using Aquarius.Weixin.Entity.WeixinMessage;
namespace Aquarius.Weixin.Core.Message.Handler.DefaultHandler
{
public class DefaultLocationMessageHandler : ILocationMessageHandler
{
public string Handle(LocationMessage message)
{
return Consts.Success;
}
}
}
| 23.733333 | 72 | 0.719101 | [
"MIT"
] | Weidaicheng/Aquarius.Weixin | src/Aquarius.Weixin/Aquarius.Weixin/Core/Message/Handler/DefaultHandler/DefaultLocationMessageHandler.cs | 358 | C# |
using System.Collections.Generic;
using Pugzor.Core.Helpers;
using Xunit;
namespace Pugzor.Test
{
[Trait("Category", "Helper")]
public class PathHelperTests
{
public static IEnumerable<object[]> Paths =
new List<object[]>
{
new object[]{ "/this/is/absolute.pug", true },
new object[]{ "~/this/is/absolute.pug", true },
new object[]{ "this/is/relative.pug", false }
};
[Theory]
[MemberData(nameof(Paths))]
public void PathHelperIsRelativePath_WithPath_ReturnsCorrectValue(string path, bool expectedResult)
{
Assert.Equal(!expectedResult, PathHelper.IsRelativePath(path));
}
[Theory]
[MemberData(nameof(Paths))]
public void PathHelperIsAbsolutePath_WithPath_ReturnsCorrectValue(string path, bool expectedResult)
{
Assert.Equal(expectedResult, PathHelper.IsAbsolutePath(path));
}
}
}
| 29.352941 | 107 | 0.606212 | [
"MIT"
] | AspNetMonsters/pugzor | Pugzor.Test/PathHelperTests.cs | 1,000 | C# |
/**
* Copyright 2013 Canada Health Infoway, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Author: $LastChangedBy: tmcgrady $
* Last modified: $LastChangedDate: 2011-05-04 15:47:15 -0400 (Wed, 04 May 2011) $
* Revision: $LastChangedRevision: 2623 $
*/
/* This class was auto-generated by the message builder generator tools. */
namespace Ca.Infoway.Messagebuilder.Model.Sk_cerx_v01_r04_2.Interaction {
using Ca.Infoway.Messagebuilder.Annotation;
using Ca.Infoway.Messagebuilder.Model;
using Ca.Infoway.Messagebuilder.Model.Sk_cerx_v01_r04_2.Common.Mcai_mt700220ca;
using Ca.Infoway.Messagebuilder.Model.Sk_cerx_v01_r04_2.Common.Mcci_mt000300ca;
using Ca.Infoway.Messagebuilder.Model.Sk_cerx_v01_r04_2.Pharmacy.Porx_mt990010ca;
/**
* <summary>Business Name: POIZ_IN010090CA: Update immunization
* request refused</summary>
*
* <remarks>Message: MCCI_MT000300CA.Message Control Act:
* MCAI_MT700220CA.ControlActEvent --> Payload:
* PORX_MT990010CA.ActEvent</remarks>
*/
[Hl7PartTypeMappingAttribute(new string[] {"POIZ_IN010090CA"})]
public class UpdateImmunizationRequestRefused : HL7Message<Ca.Infoway.Messagebuilder.Model.Sk_cerx_v01_r04_2.Common.Mcai_mt700220ca.TriggerEvent<Ca.Infoway.Messagebuilder.Model.Sk_cerx_v01_r04_2.Pharmacy.Porx_mt990010ca.ReferencedRecord>>, IInteraction {
public UpdateImmunizationRequestRefused() {
}
}
} | 44.822222 | 259 | 0.732276 | [
"ECL-2.0",
"Apache-2.0"
] | CanadaHealthInfoway/message-builder-dotnet | message-builder-release-sk-v01_r04_3/Main/Ca/Infoway/Messagebuilder/Model/Sk_cerx_v01_r04_2/Interaction/UpdateImmunizationRequestRefused.cs | 2,017 | C# |
using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("SQLServerSearcher")]
[assembly: AssemblyDescription(@"Tool for searching for tables, views, indexes, stored procedures, functions and extended properties in Microsoft SQL Server.
The application searches the specified database system tables and views for the information.
More info at: https://github.com/CoderAllan/SqlServerSearcher")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("SQLServerSearcher")]
[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("f523595c-558d-4ad1-9717-214af65dd2b2")]
// 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.7")]
[assembly: AssemblyFileVersion("1.7")]
| 43.051282 | 158 | 0.742108 | [
"MIT"
] | CoderAllan/SqlServerSearcher | src/Properties/AssemblyInfo.cs | 1,682 | C# |
// Copyright (c) Xenko contributors (https://xenko.com) and Silicon Studio Corp. (https://www.siliconstudio.co.jp)
// Distributed under the MIT license. See the LICENSE.md file in the project root for more information.
using Xenko.Core.Mathematics;
using Xenko.Engine;
using Xenko.Graphics;
using Xenko.Rendering.Lights;
namespace Xenko.Assets.Presentation.AssetEditors.Gizmos
{
/// <summary>
/// The base class for all light gizmos
/// </summary>
public class LightGizmo : BillboardingGizmo<LightComponent>
{
private static readonly LightComponent DefaultLightComponent = new LightComponent();
protected LightComponent LightComponent => ContentEntity.Get<LightComponent>() ?? DefaultLightComponent;
protected LightGizmo(EntityComponent component, string lightName, byte[] lightImageData)
: base(component,lightName, lightImageData)
{
}
protected Color3 GetLightColor(GraphicsDevice graphicsDevice)
{
var component = LightComponent;
var colorLigth = component.Type as IColorLight;
return colorLigth?.ComputeColor(graphicsDevice.ColorSpace, 1f) ?? new Color3(); // don't want to include light intensity in gizmo color (post effects not applied on gizmos)
}
}
}
| 38.294118 | 184 | 0.710445 | [
"MIT"
] | Aminator/xenko | sources/editor/Xenko.Assets.Presentation/AssetEditors/Gizmos/LightGizmo.cs | 1,302 | C# |
/*
* Copyright (c) 2020, Firely (info@fire.ly) and contributors
* See the file CONTRIBUTORS for details.
*
* This file is licensed under the BSD 3-Clause license
* available at https://raw.githubusercontent.com/FirelyTeam/firely-net-sdk/master/LICENSE
*/
namespace Hl7.Fhir.ElementModel.Types
{
public enum DateTimePrecision
{
Year,
Month,
Day,
Hour,
Minute,
Second,
/// <summary>
/// Milliseconds and fractions
/// </summary>
Fraction
}
}
| 20.884615 | 90 | 0.604052 | [
"BSD-3-Clause"
] | FirelyTeam/fhir-net-common | src/Hl7.Fhir.ElementModel/Types/DateTimePrecision.cs | 545 | C# |
using System;
using System.IO;
using System.Collections.Generic;
using System.Text;
using LumiSoft.Net.IMAP.Client;
namespace LumiSoft.Net.IMAP
{
/// <summary>
/// This class represents IMAP SEARCH <b>UNFLAGGED</b> key. Defined in RFC 3501 6.4.4.
/// </summary>
/// <remarks>Messages that do not have the \Flagged flag set.</remarks>
public class IMAP_Search_Key_Unflagged : IMAP_Search_Key
{
/// <summary>
/// Default constructor.
/// </summary>
public IMAP_Search_Key_Unflagged()
{
}
#region static method Parse
/// <summary>
/// Returns parsed IMAP SEARCH <b>UNFLAGGED</b> key.
/// </summary>
/// <param name="r">String reader.</param>
/// <returns>Returns parsed IMAP SEARCH <b>UNFLAGGED</b> key.</returns>
/// <exception cref="ArgumentNullException">Is raised when <b>r</b> is null reference.</exception>
/// <exception cref="ParseException">Is raised when parsing fails.</exception>
internal static IMAP_Search_Key_Unflagged Parse(StringReader r)
{
if(r == null){
throw new ArgumentNullException("r");
}
string word = r.ReadWord();
if(!string.Equals(word,"UNFLAGGED",StringComparison.InvariantCultureIgnoreCase)){
throw new ParseException("Parse error: Not a SEARCH 'UNFLAGGED' key.");
}
return new IMAP_Search_Key_Unflagged();
}
#endregion
#region override method ToString
/// <summary>
/// Returns this as string.
/// </summary>
/// <returns>Returns this as string.</returns>
public override string ToString()
{
return "UNFLAGGED";
}
#endregion
#region internal override method ToCmdParts
/// <summary>
/// Stores IMAP search-key command parts to the specified array.
/// </summary>
/// <param name="list">Array where to store command parts.</param>
/// <exception cref="ArgumentNullException">Is raised when <b>list</b> is null reference.</exception>
internal override void ToCmdParts(List<IMAP_Client_CmdPart> list)
{
if(list == null){
throw new ArgumentNullException("list");
}
list.Add(new IMAP_Client_CmdPart(IMAP_Client_CmdPart_Type.Constant,ToString()));
}
#endregion
}
}
| 30.439024 | 109 | 0.590144 | [
"MIT"
] | garakutanokiseki/Join.NET | LumiSoftNet/Net/IMAP/IMAP_Search_Key_Unflagged.cs | 2,498 | C# |
/*----------------------------------------------------------------
Copyright (C) 2022 Senparc
文件名:SetMuteData.cs
文件功能描述:成员新消息免打扰参数
创建标识:Senparc - 20150728
----------------------------------------------------------------*/
namespace Senparc.Weixin.Work.AdvancedAPIs.Chat
{
/// <summary>
/// 成员新消息免打扰参数
/// </summary>
public class UserMute
{
/// <summary>
/// 成员UserID
/// </summary>
public string userid { get; set; }
/// <summary>
/// 免打扰状态
/// </summary>
public Mute_Status status { get; set; }
}
} | 22.962963 | 67 | 0.404839 | [
"Apache-2.0"
] | AaronWu666/WeiXinMPSDK | src/Senparc.Weixin.Work/Senparc.Weixin.Work/AdvancedAPIs/Chat/ChatJson/SetMuteData.cs | 708 | C# |
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.
namespace System.Data.Entity.Core.Common.CommandTrees
{
using System.Data.Entity.Core.Metadata.Edm;
using System.Data.Entity.Utilities;
/// <summary>Represents the projection of a given input set over the specified expression. This class cannot be inherited. </summary>
public sealed class DbProjectExpression : DbExpression
{
private readonly DbExpressionBinding _input;
private readonly DbExpression _projection;
internal DbProjectExpression(TypeUsage resultType, DbExpressionBinding input, DbExpression projection)
: base(DbExpressionKind.Project, resultType)
{
DebugCheck.NotNull(input);
DebugCheck.NotNull(projection);
_input = input;
_projection = projection;
}
/// <summary>
/// Gets the <see cref="T:System.Data.Entity.Core.Common.CommandTrees.DbExpressionBinding" /> that specifies the input set.
/// </summary>
/// <returns>
/// The <see cref="T:System.Data.Entity.Core.Common.CommandTrees.DbExpressionBinding" /> that specifies the input set.
/// </returns>
public DbExpressionBinding Input
{
get { return _input; }
}
/// <summary>
/// Gets the <see cref="T:System.Data.Entity.Core.Common.CommandTrees.DbExpression" /> that defines the projection.
/// </summary>
/// <returns>
/// The <see cref="T:System.Data.Entity.Core.Common.CommandTrees.DbExpression" /> that defines the projection.
/// </returns>
/// <exception cref="T:System.ArgumentNullException">The expression is null.</exception>
/// <exception cref="T:System.ArgumentException">
/// The expression is not associated with the command tree of the
/// <see
/// cref="T:System.Data.Entity.Core.Common.CommandTrees.DbProjectExpression" />
/// , or its result type is not equal or promotable to the reference type of the current projection.
/// </exception>
public DbExpression Projection
{
get { return _projection; }
}
/// <summary>Implements the visitor pattern for expressions that do not produce a result value.</summary>
/// <param name="visitor">
/// An instance of <see cref="T:System.Data.Entity.Core.Common.CommandTrees.DbExpressionVisitor" />.
/// </param>
/// <exception cref="T:System.ArgumentNullException"> visitor is null.</exception>
public override void Accept(DbExpressionVisitor visitor)
{
Check.NotNull(visitor, "visitor");
visitor.Visit(this);
}
/// <summary>Implements the visitor pattern for expressions that produce a result value of a specific type.</summary>
/// <returns>
/// A result value of a specific type produced by
/// <see
/// cref="T:System.Data.Entity.Core.Common.CommandTrees.DbExpressionVisitor" />
/// .
/// </returns>
/// <param name="visitor">
/// An instance of a typed <see cref="T:System.Data.Entity.Core.Common.CommandTrees.DbExpressionVisitor" /> that produces a result value of a specific type.
/// </param>
/// <typeparam name="TResultType">The type of the result produced by visitor .</typeparam>
/// <exception cref="T:System.ArgumentNullException"> visitor is null.</exception>
public override TResultType Accept<TResultType>(DbExpressionVisitor<TResultType> visitor)
{
Check.NotNull(visitor, "visitor");
return visitor.Visit(this);
}
}
}
| 44.647059 | 164 | 0.638735 | [
"Apache-2.0"
] | CZEMacLeod/EntityFramework6 | src/EntityFramework/Core/Common/CommandTrees/DbProjectExpression.cs | 3,795 | C# |
using UnityEngine;
using UnityEngine.UI;
public class LoaderProgress : MonoBehaviour
{
private Slider loadingProgress;
private void Awake()
{
loadingProgress = GetComponent<Slider>();
}
private void Update()
{
loadingProgress.value = Loader.GetLoadingProgress();
}
}
| 17.5 | 60 | 0.666667 | [
"Apache-2.0"
] | aeyonblack/tanya-masvita-software-development-projects | Reborn - Mobile Game Codebase (C#)/Reborn/Assets/Scripts/Utilities/LoaderProgress.cs | 317 | C# |
namespace Test {
public sealed class CPOD2 {
public string Aa {
get;
set;
}
public bool IsAa {
get;
set;
}
}
}
| 11.214286 | 29 | 0.477707 | [
"CC0-1.0"
] | CardanoSharp/CBOR | CBORTest/CPOD2.cs | 159 | 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.
*
* Contains some contributions under the Thrift Software License.
* Please see doc/old-thrift-license.txt in the Thrift distribution for
* details.
*/
using System;
using System.IO;
namespace Thrift.Transport
{
internal class TStreamTransport : TTransport
{
protected Stream inputStream;
protected Stream outputStream;
protected TStreamTransport()
{
}
public TStreamTransport(Stream inputStream, Stream outputStream)
{
this.inputStream = inputStream;
this.outputStream = outputStream;
}
public Stream OutputStream
{
get { return outputStream; }
}
public Stream InputStream
{
get { return inputStream; }
}
public override bool IsOpen
{
get { return true; }
}
public override void Open()
{
}
public override void Close()
{
if (inputStream != null)
{
inputStream.Close();
inputStream = null;
}
if (outputStream != null)
{
outputStream.Close();
outputStream = null;
}
}
public override int Read(byte[] buf, int off, int len)
{
if (inputStream == null)
{
throw new TTransportException(TTransportException.ExceptionType.NotOpen, "Cannot read from null inputstream");
}
return inputStream.Read(buf, off, len);
}
public override void Write(byte[] buf, int off, int len)
{
if (outputStream == null)
{
throw new TTransportException(TTransportException.ExceptionType.NotOpen, "Cannot write to null outputstream");
}
outputStream.Write(buf, off, len);
}
public override void Flush()
{
if (outputStream == null)
{
throw new TTransportException(TTransportException.ExceptionType.NotOpen, "Cannot flush null outputstream");
}
outputStream.Flush();
}
#region " IDisposable Support "
private bool _IsDisposed;
// IDisposable
protected override void Dispose(bool disposing)
{
if (!_IsDisposed)
{
if (disposing)
{
if (InputStream != null)
InputStream.Dispose();
if (OutputStream != null)
OutputStream.Dispose();
}
}
_IsDisposed = true;
}
#endregion
}
}
| 27.55814 | 126 | 0.56315 | [
"MIT"
] | oldmine/cassandra-thrift-client | Cassandra.ThriftClient/Internal/Thrift/Transport/TStreamTransport.cs | 3,555 | C# |
#pragma warning disable CS1591
#region License
/*
**************************************************************
* Author: Rick Strahl
* © West Wind Technologies, 2010-2011
* http://www.west-wind.com/
*
* Created: 1/4/2010
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following
* conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
**************************************************************
*/
#endregion
namespace Westwind.RazorHosting
{
/// <summary>
/// Not used at the moment - more of a placeholder for now
/// </summary>
public class RazorRequest
{
/// <summary>
/// Full Path to the template.
/// Only applies to running with RazorFolderHost
/// </summary>
public string TemplatePath { get; set; }
/// <summary>
/// RelativePath to the template as a virtual (~/) path
/// based on the root of the template host.
///
/// Only applies to RazorFolderHost
/// </summary>
public string TemplateRelativePath { get; set; }
}
}
| 37.140351 | 69 | 0.619273 | [
"MIT",
"Unlicense"
] | RickStrahl/Westwind.RazorHosting | Westwind.RazorHosting/TemplateBase/RazorRequest.cs | 2,120 | C# |
// <auto-generated>
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// </auto-generated>
namespace Microsoft.Azure.Management.WebSites
{
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// Extension methods for AppServiceCertificateOrdersOperations.
/// </summary>
public static partial class AppServiceCertificateOrdersOperationsExtensions
{
/// <summary>
/// List all certificate orders in a subscription.
/// </summary>
/// <remarks>
/// List all certificate orders in a subscription.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static IPage<AppServiceCertificateOrder> List(this IAppServiceCertificateOrdersOperations operations)
{
return operations.ListAsync().GetAwaiter().GetResult();
}
/// <summary>
/// List all certificate orders in a subscription.
/// </summary>
/// <remarks>
/// List all certificate orders in a subscription.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<AppServiceCertificateOrder>> ListAsync(this IAppServiceCertificateOrdersOperations operations, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Validate information for a certificate order.
/// </summary>
/// <remarks>
/// Validate information for a certificate order.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='appServiceCertificateOrder'>
/// Information for a certificate order.
/// </param>
public static void ValidatePurchaseInformation(this IAppServiceCertificateOrdersOperations operations, AppServiceCertificateOrder appServiceCertificateOrder)
{
operations.ValidatePurchaseInformationAsync(appServiceCertificateOrder).GetAwaiter().GetResult();
}
/// <summary>
/// Validate information for a certificate order.
/// </summary>
/// <remarks>
/// Validate information for a certificate order.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='appServiceCertificateOrder'>
/// Information for a certificate order.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task ValidatePurchaseInformationAsync(this IAppServiceCertificateOrdersOperations operations, AppServiceCertificateOrder appServiceCertificateOrder, CancellationToken cancellationToken = default(CancellationToken))
{
(await operations.ValidatePurchaseInformationWithHttpMessagesAsync(appServiceCertificateOrder, null, cancellationToken).ConfigureAwait(false)).Dispose();
}
/// <summary>
/// Get certificate orders in a resource group.
/// </summary>
/// <remarks>
/// Get certificate orders in a resource group.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the resource group to which the resource belongs.
/// </param>
public static IPage<AppServiceCertificateOrder> ListByResourceGroup(this IAppServiceCertificateOrdersOperations operations, string resourceGroupName)
{
return operations.ListByResourceGroupAsync(resourceGroupName).GetAwaiter().GetResult();
}
/// <summary>
/// Get certificate orders in a resource group.
/// </summary>
/// <remarks>
/// Get certificate orders in a resource group.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the resource group to which the resource belongs.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<AppServiceCertificateOrder>> ListByResourceGroupAsync(this IAppServiceCertificateOrdersOperations operations, string resourceGroupName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListByResourceGroupWithHttpMessagesAsync(resourceGroupName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Get a certificate order.
/// </summary>
/// <remarks>
/// Get a certificate order.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the resource group to which the resource belongs.
/// </param>
/// <param name='certificateOrderName'>
/// Name of the certificate order..
/// </param>
public static AppServiceCertificateOrder Get(this IAppServiceCertificateOrdersOperations operations, string resourceGroupName, string certificateOrderName)
{
return operations.GetAsync(resourceGroupName, certificateOrderName).GetAwaiter().GetResult();
}
/// <summary>
/// Get a certificate order.
/// </summary>
/// <remarks>
/// Get a certificate order.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the resource group to which the resource belongs.
/// </param>
/// <param name='certificateOrderName'>
/// Name of the certificate order..
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<AppServiceCertificateOrder> GetAsync(this IAppServiceCertificateOrdersOperations operations, string resourceGroupName, string certificateOrderName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetWithHttpMessagesAsync(resourceGroupName, certificateOrderName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Create or update a certificate purchase order.
/// </summary>
/// <remarks>
/// Create or update a certificate purchase order.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the resource group to which the resource belongs.
/// </param>
/// <param name='certificateOrderName'>
/// Name of the certificate order.
/// </param>
/// <param name='certificateDistinguishedName'>
/// Distinguished name to use for the certificate order.
/// </param>
public static AppServiceCertificateOrder CreateOrUpdate(this IAppServiceCertificateOrdersOperations operations, string resourceGroupName, string certificateOrderName, AppServiceCertificateOrder certificateDistinguishedName)
{
return operations.CreateOrUpdateAsync(resourceGroupName, certificateOrderName, certificateDistinguishedName).GetAwaiter().GetResult();
}
/// <summary>
/// Create or update a certificate purchase order.
/// </summary>
/// <remarks>
/// Create or update a certificate purchase order.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the resource group to which the resource belongs.
/// </param>
/// <param name='certificateOrderName'>
/// Name of the certificate order.
/// </param>
/// <param name='certificateDistinguishedName'>
/// Distinguished name to use for the certificate order.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<AppServiceCertificateOrder> CreateOrUpdateAsync(this IAppServiceCertificateOrdersOperations operations, string resourceGroupName, string certificateOrderName, AppServiceCertificateOrder certificateDistinguishedName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.CreateOrUpdateWithHttpMessagesAsync(resourceGroupName, certificateOrderName, certificateDistinguishedName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Delete an existing certificate order.
/// </summary>
/// <remarks>
/// Delete an existing certificate order.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the resource group to which the resource belongs.
/// </param>
/// <param name='certificateOrderName'>
/// Name of the certificate order.
/// </param>
public static void Delete(this IAppServiceCertificateOrdersOperations operations, string resourceGroupName, string certificateOrderName)
{
operations.DeleteAsync(resourceGroupName, certificateOrderName).GetAwaiter().GetResult();
}
/// <summary>
/// Delete an existing certificate order.
/// </summary>
/// <remarks>
/// Delete an existing certificate order.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the resource group to which the resource belongs.
/// </param>
/// <param name='certificateOrderName'>
/// Name of the certificate order.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task DeleteAsync(this IAppServiceCertificateOrdersOperations operations, string resourceGroupName, string certificateOrderName, CancellationToken cancellationToken = default(CancellationToken))
{
(await operations.DeleteWithHttpMessagesAsync(resourceGroupName, certificateOrderName, null, cancellationToken).ConfigureAwait(false)).Dispose();
}
/// <summary>
/// Create or update a certificate purchase order.
/// </summary>
/// <remarks>
/// Create or update a certificate purchase order.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the resource group to which the resource belongs.
/// </param>
/// <param name='certificateOrderName'>
/// Name of the certificate order.
/// </param>
/// <param name='certificateDistinguishedName'>
/// Distinguished name to use for the certificate order.
/// </param>
public static AppServiceCertificateOrder Update(this IAppServiceCertificateOrdersOperations operations, string resourceGroupName, string certificateOrderName, AppServiceCertificateOrderPatchResource certificateDistinguishedName)
{
return operations.UpdateAsync(resourceGroupName, certificateOrderName, certificateDistinguishedName).GetAwaiter().GetResult();
}
/// <summary>
/// Create or update a certificate purchase order.
/// </summary>
/// <remarks>
/// Create or update a certificate purchase order.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the resource group to which the resource belongs.
/// </param>
/// <param name='certificateOrderName'>
/// Name of the certificate order.
/// </param>
/// <param name='certificateDistinguishedName'>
/// Distinguished name to use for the certificate order.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<AppServiceCertificateOrder> UpdateAsync(this IAppServiceCertificateOrdersOperations operations, string resourceGroupName, string certificateOrderName, AppServiceCertificateOrderPatchResource certificateDistinguishedName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.UpdateWithHttpMessagesAsync(resourceGroupName, certificateOrderName, certificateDistinguishedName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// List all certificates associated with a certificate order.
/// </summary>
/// <remarks>
/// List all certificates associated with a certificate order.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the resource group to which the resource belongs.
/// </param>
/// <param name='certificateOrderName'>
/// Name of the certificate order.
/// </param>
public static IPage<AppServiceCertificateResource> ListCertificates(this IAppServiceCertificateOrdersOperations operations, string resourceGroupName, string certificateOrderName)
{
return operations.ListCertificatesAsync(resourceGroupName, certificateOrderName).GetAwaiter().GetResult();
}
/// <summary>
/// List all certificates associated with a certificate order.
/// </summary>
/// <remarks>
/// List all certificates associated with a certificate order.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the resource group to which the resource belongs.
/// </param>
/// <param name='certificateOrderName'>
/// Name of the certificate order.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<AppServiceCertificateResource>> ListCertificatesAsync(this IAppServiceCertificateOrdersOperations operations, string resourceGroupName, string certificateOrderName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListCertificatesWithHttpMessagesAsync(resourceGroupName, certificateOrderName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Get the certificate associated with a certificate order.
/// </summary>
/// <remarks>
/// Get the certificate associated with a certificate order.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the resource group to which the resource belongs.
/// </param>
/// <param name='certificateOrderName'>
/// Name of the certificate order.
/// </param>
/// <param name='name'>
/// Name of the certificate.
/// </param>
public static AppServiceCertificateResource GetCertificate(this IAppServiceCertificateOrdersOperations operations, string resourceGroupName, string certificateOrderName, string name)
{
return operations.GetCertificateAsync(resourceGroupName, certificateOrderName, name).GetAwaiter().GetResult();
}
/// <summary>
/// Get the certificate associated with a certificate order.
/// </summary>
/// <remarks>
/// Get the certificate associated with a certificate order.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the resource group to which the resource belongs.
/// </param>
/// <param name='certificateOrderName'>
/// Name of the certificate order.
/// </param>
/// <param name='name'>
/// Name of the certificate.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<AppServiceCertificateResource> GetCertificateAsync(this IAppServiceCertificateOrdersOperations operations, string resourceGroupName, string certificateOrderName, string name, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetCertificateWithHttpMessagesAsync(resourceGroupName, certificateOrderName, name, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Creates or updates a certificate and associates with key vault secret.
/// </summary>
/// <remarks>
/// Creates or updates a certificate and associates with key vault secret.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the resource group to which the resource belongs.
/// </param>
/// <param name='certificateOrderName'>
/// Name of the certificate order.
/// </param>
/// <param name='name'>
/// Name of the certificate.
/// </param>
/// <param name='keyVaultCertificate'>
/// Key vault certificate resource Id.
/// </param>
public static AppServiceCertificateResource CreateOrUpdateCertificate(this IAppServiceCertificateOrdersOperations operations, string resourceGroupName, string certificateOrderName, string name, AppServiceCertificateResource keyVaultCertificate)
{
return operations.CreateOrUpdateCertificateAsync(resourceGroupName, certificateOrderName, name, keyVaultCertificate).GetAwaiter().GetResult();
}
/// <summary>
/// Creates or updates a certificate and associates with key vault secret.
/// </summary>
/// <remarks>
/// Creates or updates a certificate and associates with key vault secret.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the resource group to which the resource belongs.
/// </param>
/// <param name='certificateOrderName'>
/// Name of the certificate order.
/// </param>
/// <param name='name'>
/// Name of the certificate.
/// </param>
/// <param name='keyVaultCertificate'>
/// Key vault certificate resource Id.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<AppServiceCertificateResource> CreateOrUpdateCertificateAsync(this IAppServiceCertificateOrdersOperations operations, string resourceGroupName, string certificateOrderName, string name, AppServiceCertificateResource keyVaultCertificate, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.CreateOrUpdateCertificateWithHttpMessagesAsync(resourceGroupName, certificateOrderName, name, keyVaultCertificate, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Delete the certificate associated with a certificate order.
/// </summary>
/// <remarks>
/// Delete the certificate associated with a certificate order.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the resource group to which the resource belongs.
/// </param>
/// <param name='certificateOrderName'>
/// Name of the certificate order.
/// </param>
/// <param name='name'>
/// Name of the certificate.
/// </param>
public static void DeleteCertificate(this IAppServiceCertificateOrdersOperations operations, string resourceGroupName, string certificateOrderName, string name)
{
operations.DeleteCertificateAsync(resourceGroupName, certificateOrderName, name).GetAwaiter().GetResult();
}
/// <summary>
/// Delete the certificate associated with a certificate order.
/// </summary>
/// <remarks>
/// Delete the certificate associated with a certificate order.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the resource group to which the resource belongs.
/// </param>
/// <param name='certificateOrderName'>
/// Name of the certificate order.
/// </param>
/// <param name='name'>
/// Name of the certificate.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task DeleteCertificateAsync(this IAppServiceCertificateOrdersOperations operations, string resourceGroupName, string certificateOrderName, string name, CancellationToken cancellationToken = default(CancellationToken))
{
(await operations.DeleteCertificateWithHttpMessagesAsync(resourceGroupName, certificateOrderName, name, null, cancellationToken).ConfigureAwait(false)).Dispose();
}
/// <summary>
/// Creates or updates a certificate and associates with key vault secret.
/// </summary>
/// <remarks>
/// Creates or updates a certificate and associates with key vault secret.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the resource group to which the resource belongs.
/// </param>
/// <param name='certificateOrderName'>
/// Name of the certificate order.
/// </param>
/// <param name='name'>
/// Name of the certificate.
/// </param>
/// <param name='keyVaultCertificate'>
/// Key vault certificate resource Id.
/// </param>
public static AppServiceCertificateResource UpdateCertificate(this IAppServiceCertificateOrdersOperations operations, string resourceGroupName, string certificateOrderName, string name, AppServiceCertificatePatchResource keyVaultCertificate)
{
return operations.UpdateCertificateAsync(resourceGroupName, certificateOrderName, name, keyVaultCertificate).GetAwaiter().GetResult();
}
/// <summary>
/// Creates or updates a certificate and associates with key vault secret.
/// </summary>
/// <remarks>
/// Creates or updates a certificate and associates with key vault secret.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the resource group to which the resource belongs.
/// </param>
/// <param name='certificateOrderName'>
/// Name of the certificate order.
/// </param>
/// <param name='name'>
/// Name of the certificate.
/// </param>
/// <param name='keyVaultCertificate'>
/// Key vault certificate resource Id.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<AppServiceCertificateResource> UpdateCertificateAsync(this IAppServiceCertificateOrdersOperations operations, string resourceGroupName, string certificateOrderName, string name, AppServiceCertificatePatchResource keyVaultCertificate, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.UpdateCertificateWithHttpMessagesAsync(resourceGroupName, certificateOrderName, name, keyVaultCertificate, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Reissue an existing certificate order.
/// </summary>
/// <remarks>
/// Reissue an existing certificate order.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the resource group to which the resource belongs.
/// </param>
/// <param name='certificateOrderName'>
/// Name of the certificate order.
/// </param>
/// <param name='reissueCertificateOrderRequest'>
/// Parameters for the reissue.
/// </param>
public static void Reissue(this IAppServiceCertificateOrdersOperations operations, string resourceGroupName, string certificateOrderName, ReissueCertificateOrderRequest reissueCertificateOrderRequest)
{
operations.ReissueAsync(resourceGroupName, certificateOrderName, reissueCertificateOrderRequest).GetAwaiter().GetResult();
}
/// <summary>
/// Reissue an existing certificate order.
/// </summary>
/// <remarks>
/// Reissue an existing certificate order.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the resource group to which the resource belongs.
/// </param>
/// <param name='certificateOrderName'>
/// Name of the certificate order.
/// </param>
/// <param name='reissueCertificateOrderRequest'>
/// Parameters for the reissue.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task ReissueAsync(this IAppServiceCertificateOrdersOperations operations, string resourceGroupName, string certificateOrderName, ReissueCertificateOrderRequest reissueCertificateOrderRequest, CancellationToken cancellationToken = default(CancellationToken))
{
(await operations.ReissueWithHttpMessagesAsync(resourceGroupName, certificateOrderName, reissueCertificateOrderRequest, null, cancellationToken).ConfigureAwait(false)).Dispose();
}
/// <summary>
/// Renew an existing certificate order.
/// </summary>
/// <remarks>
/// Renew an existing certificate order.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the resource group to which the resource belongs.
/// </param>
/// <param name='certificateOrderName'>
/// Name of the certificate order.
/// </param>
/// <param name='renewCertificateOrderRequest'>
/// Renew parameters
/// </param>
public static void Renew(this IAppServiceCertificateOrdersOperations operations, string resourceGroupName, string certificateOrderName, RenewCertificateOrderRequest renewCertificateOrderRequest)
{
operations.RenewAsync(resourceGroupName, certificateOrderName, renewCertificateOrderRequest).GetAwaiter().GetResult();
}
/// <summary>
/// Renew an existing certificate order.
/// </summary>
/// <remarks>
/// Renew an existing certificate order.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the resource group to which the resource belongs.
/// </param>
/// <param name='certificateOrderName'>
/// Name of the certificate order.
/// </param>
/// <param name='renewCertificateOrderRequest'>
/// Renew parameters
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task RenewAsync(this IAppServiceCertificateOrdersOperations operations, string resourceGroupName, string certificateOrderName, RenewCertificateOrderRequest renewCertificateOrderRequest, CancellationToken cancellationToken = default(CancellationToken))
{
(await operations.RenewWithHttpMessagesAsync(resourceGroupName, certificateOrderName, renewCertificateOrderRequest, null, cancellationToken).ConfigureAwait(false)).Dispose();
}
/// <summary>
/// Resend certificate email.
/// </summary>
/// <remarks>
/// Resend certificate email.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the resource group to which the resource belongs.
/// </param>
/// <param name='certificateOrderName'>
/// Name of the certificate order.
/// </param>
public static void ResendEmail(this IAppServiceCertificateOrdersOperations operations, string resourceGroupName, string certificateOrderName)
{
operations.ResendEmailAsync(resourceGroupName, certificateOrderName).GetAwaiter().GetResult();
}
/// <summary>
/// Resend certificate email.
/// </summary>
/// <remarks>
/// Resend certificate email.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the resource group to which the resource belongs.
/// </param>
/// <param name='certificateOrderName'>
/// Name of the certificate order.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task ResendEmailAsync(this IAppServiceCertificateOrdersOperations operations, string resourceGroupName, string certificateOrderName, CancellationToken cancellationToken = default(CancellationToken))
{
(await operations.ResendEmailWithHttpMessagesAsync(resourceGroupName, certificateOrderName, null, cancellationToken).ConfigureAwait(false)).Dispose();
}
/// <summary>
/// Verify domain ownership for this certificate order.
/// </summary>
/// <remarks>
/// Verify domain ownership for this certificate order.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the resource group to which the resource belongs.
/// </param>
/// <param name='certificateOrderName'>
/// Name of the certificate order.
/// </param>
/// <param name='nameIdentifier'>
/// Email address
/// </param>
public static void ResendRequestEmails(this IAppServiceCertificateOrdersOperations operations, string resourceGroupName, string certificateOrderName, NameIdentifier nameIdentifier)
{
operations.ResendRequestEmailsAsync(resourceGroupName, certificateOrderName, nameIdentifier).GetAwaiter().GetResult();
}
/// <summary>
/// Verify domain ownership for this certificate order.
/// </summary>
/// <remarks>
/// Verify domain ownership for this certificate order.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the resource group to which the resource belongs.
/// </param>
/// <param name='certificateOrderName'>
/// Name of the certificate order.
/// </param>
/// <param name='nameIdentifier'>
/// Email address
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task ResendRequestEmailsAsync(this IAppServiceCertificateOrdersOperations operations, string resourceGroupName, string certificateOrderName, NameIdentifier nameIdentifier, CancellationToken cancellationToken = default(CancellationToken))
{
(await operations.ResendRequestEmailsWithHttpMessagesAsync(resourceGroupName, certificateOrderName, nameIdentifier, null, cancellationToken).ConfigureAwait(false)).Dispose();
}
/// <summary>
/// Verify domain ownership for this certificate order.
/// </summary>
/// <remarks>
/// Verify domain ownership for this certificate order.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the resource group to which the resource belongs.
/// </param>
/// <param name='certificateOrderName'>
/// Name of the certificate order.
/// </param>
/// <param name='siteSealRequest'>
/// Site seal request.
/// </param>
public static SiteSeal RetrieveSiteSeal(this IAppServiceCertificateOrdersOperations operations, string resourceGroupName, string certificateOrderName, SiteSealRequest siteSealRequest)
{
return operations.RetrieveSiteSealAsync(resourceGroupName, certificateOrderName, siteSealRequest).GetAwaiter().GetResult();
}
/// <summary>
/// Verify domain ownership for this certificate order.
/// </summary>
/// <remarks>
/// Verify domain ownership for this certificate order.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the resource group to which the resource belongs.
/// </param>
/// <param name='certificateOrderName'>
/// Name of the certificate order.
/// </param>
/// <param name='siteSealRequest'>
/// Site seal request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<SiteSeal> RetrieveSiteSealAsync(this IAppServiceCertificateOrdersOperations operations, string resourceGroupName, string certificateOrderName, SiteSealRequest siteSealRequest, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.RetrieveSiteSealWithHttpMessagesAsync(resourceGroupName, certificateOrderName, siteSealRequest, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Verify domain ownership for this certificate order.
/// </summary>
/// <remarks>
/// Verify domain ownership for this certificate order.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the resource group to which the resource belongs.
/// </param>
/// <param name='certificateOrderName'>
/// Name of the certificate order.
/// </param>
public static void VerifyDomainOwnership(this IAppServiceCertificateOrdersOperations operations, string resourceGroupName, string certificateOrderName)
{
operations.VerifyDomainOwnershipAsync(resourceGroupName, certificateOrderName).GetAwaiter().GetResult();
}
/// <summary>
/// Verify domain ownership for this certificate order.
/// </summary>
/// <remarks>
/// Verify domain ownership for this certificate order.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the resource group to which the resource belongs.
/// </param>
/// <param name='certificateOrderName'>
/// Name of the certificate order.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task VerifyDomainOwnershipAsync(this IAppServiceCertificateOrdersOperations operations, string resourceGroupName, string certificateOrderName, CancellationToken cancellationToken = default(CancellationToken))
{
(await operations.VerifyDomainOwnershipWithHttpMessagesAsync(resourceGroupName, certificateOrderName, null, cancellationToken).ConfigureAwait(false)).Dispose();
}
/// <summary>
/// Retrieve the list of certificate actions.
/// </summary>
/// <remarks>
/// Retrieve the list of certificate actions.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the resource group to which the resource belongs.
/// </param>
/// <param name='name'>
/// Name of the certificate order.
/// </param>
public static IList<CertificateOrderAction> RetrieveCertificateActions(this IAppServiceCertificateOrdersOperations operations, string resourceGroupName, string name)
{
return operations.RetrieveCertificateActionsAsync(resourceGroupName, name).GetAwaiter().GetResult();
}
/// <summary>
/// Retrieve the list of certificate actions.
/// </summary>
/// <remarks>
/// Retrieve the list of certificate actions.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the resource group to which the resource belongs.
/// </param>
/// <param name='name'>
/// Name of the certificate order.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IList<CertificateOrderAction>> RetrieveCertificateActionsAsync(this IAppServiceCertificateOrdersOperations operations, string resourceGroupName, string name, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.RetrieveCertificateActionsWithHttpMessagesAsync(resourceGroupName, name, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Retrieve email history.
/// </summary>
/// <remarks>
/// Retrieve email history.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the resource group to which the resource belongs.
/// </param>
/// <param name='name'>
/// Name of the certificate order.
/// </param>
public static IList<CertificateEmail> RetrieveCertificateEmailHistory(this IAppServiceCertificateOrdersOperations operations, string resourceGroupName, string name)
{
return operations.RetrieveCertificateEmailHistoryAsync(resourceGroupName, name).GetAwaiter().GetResult();
}
/// <summary>
/// Retrieve email history.
/// </summary>
/// <remarks>
/// Retrieve email history.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the resource group to which the resource belongs.
/// </param>
/// <param name='name'>
/// Name of the certificate order.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IList<CertificateEmail>> RetrieveCertificateEmailHistoryAsync(this IAppServiceCertificateOrdersOperations operations, string resourceGroupName, string name, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.RetrieveCertificateEmailHistoryWithHttpMessagesAsync(resourceGroupName, name, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Create or update a certificate purchase order.
/// </summary>
/// <remarks>
/// Create or update a certificate purchase order.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the resource group to which the resource belongs.
/// </param>
/// <param name='certificateOrderName'>
/// Name of the certificate order.
/// </param>
/// <param name='certificateDistinguishedName'>
/// Distinguished name to use for the certificate order.
/// </param>
public static AppServiceCertificateOrder BeginCreateOrUpdate(this IAppServiceCertificateOrdersOperations operations, string resourceGroupName, string certificateOrderName, AppServiceCertificateOrder certificateDistinguishedName)
{
return operations.BeginCreateOrUpdateAsync(resourceGroupName, certificateOrderName, certificateDistinguishedName).GetAwaiter().GetResult();
}
/// <summary>
/// Create or update a certificate purchase order.
/// </summary>
/// <remarks>
/// Create or update a certificate purchase order.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the resource group to which the resource belongs.
/// </param>
/// <param name='certificateOrderName'>
/// Name of the certificate order.
/// </param>
/// <param name='certificateDistinguishedName'>
/// Distinguished name to use for the certificate order.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<AppServiceCertificateOrder> BeginCreateOrUpdateAsync(this IAppServiceCertificateOrdersOperations operations, string resourceGroupName, string certificateOrderName, AppServiceCertificateOrder certificateDistinguishedName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.BeginCreateOrUpdateWithHttpMessagesAsync(resourceGroupName, certificateOrderName, certificateDistinguishedName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Creates or updates a certificate and associates with key vault secret.
/// </summary>
/// <remarks>
/// Creates or updates a certificate and associates with key vault secret.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the resource group to which the resource belongs.
/// </param>
/// <param name='certificateOrderName'>
/// Name of the certificate order.
/// </param>
/// <param name='name'>
/// Name of the certificate.
/// </param>
/// <param name='keyVaultCertificate'>
/// Key vault certificate resource Id.
/// </param>
public static AppServiceCertificateResource BeginCreateOrUpdateCertificate(this IAppServiceCertificateOrdersOperations operations, string resourceGroupName, string certificateOrderName, string name, AppServiceCertificateResource keyVaultCertificate)
{
return operations.BeginCreateOrUpdateCertificateAsync(resourceGroupName, certificateOrderName, name, keyVaultCertificate).GetAwaiter().GetResult();
}
/// <summary>
/// Creates or updates a certificate and associates with key vault secret.
/// </summary>
/// <remarks>
/// Creates or updates a certificate and associates with key vault secret.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the resource group to which the resource belongs.
/// </param>
/// <param name='certificateOrderName'>
/// Name of the certificate order.
/// </param>
/// <param name='name'>
/// Name of the certificate.
/// </param>
/// <param name='keyVaultCertificate'>
/// Key vault certificate resource Id.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<AppServiceCertificateResource> BeginCreateOrUpdateCertificateAsync(this IAppServiceCertificateOrdersOperations operations, string resourceGroupName, string certificateOrderName, string name, AppServiceCertificateResource keyVaultCertificate, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.BeginCreateOrUpdateCertificateWithHttpMessagesAsync(resourceGroupName, certificateOrderName, name, keyVaultCertificate, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// List all certificate orders in a subscription.
/// </summary>
/// <remarks>
/// List all certificate orders in a subscription.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
public static IPage<AppServiceCertificateOrder> ListNext(this IAppServiceCertificateOrdersOperations operations, string nextPageLink)
{
return operations.ListNextAsync(nextPageLink).GetAwaiter().GetResult();
}
/// <summary>
/// List all certificate orders in a subscription.
/// </summary>
/// <remarks>
/// List all certificate orders in a subscription.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<AppServiceCertificateOrder>> ListNextAsync(this IAppServiceCertificateOrdersOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Get certificate orders in a resource group.
/// </summary>
/// <remarks>
/// Get certificate orders in a resource group.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
public static IPage<AppServiceCertificateOrder> ListByResourceGroupNext(this IAppServiceCertificateOrdersOperations operations, string nextPageLink)
{
return operations.ListByResourceGroupNextAsync(nextPageLink).GetAwaiter().GetResult();
}
/// <summary>
/// Get certificate orders in a resource group.
/// </summary>
/// <remarks>
/// Get certificate orders in a resource group.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<AppServiceCertificateOrder>> ListByResourceGroupNextAsync(this IAppServiceCertificateOrdersOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListByResourceGroupNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// List all certificates associated with a certificate order.
/// </summary>
/// <remarks>
/// List all certificates associated with a certificate order.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
public static IPage<AppServiceCertificateResource> ListCertificatesNext(this IAppServiceCertificateOrdersOperations operations, string nextPageLink)
{
return operations.ListCertificatesNextAsync(nextPageLink).GetAwaiter().GetResult();
}
/// <summary>
/// List all certificates associated with a certificate order.
/// </summary>
/// <remarks>
/// List all certificates associated with a certificate order.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<AppServiceCertificateResource>> ListCertificatesNextAsync(this IAppServiceCertificateOrdersOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListCertificatesNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
}
}
| 49.31614 | 344 | 0.578444 | [
"MIT"
] | 0xced/azure-sdk-for-net | src/SDKs/WebSites/Management.Websites/Generated/AppServiceCertificateOrdersOperationsExtensions.cs | 59,278 | C# |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
using System.Collections.Generic;
using Aliyun.Acs.Core;
namespace Aliyun.Acs.companyreg.Model.V20200306
{
public class RejectUserSolutionResponse : AcsResponse
{
private string requestId;
private bool? success;
private string errorMsg;
private string errorCode;
public string RequestId
{
get
{
return requestId;
}
set
{
requestId = value;
}
}
public bool? Success
{
get
{
return success;
}
set
{
success = value;
}
}
public string ErrorMsg
{
get
{
return errorMsg;
}
set
{
errorMsg = value;
}
}
public string ErrorCode
{
get
{
return errorCode;
}
set
{
errorCode = value;
}
}
}
}
| 18.847059 | 63 | 0.649189 | [
"Apache-2.0"
] | aliyun/aliyun-openapi-net-sdk | aliyun-net-sdk-companyreg/Companyreg/Model/V20200306/RejectUserSolutionResponse.cs | 1,602 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// 此代码由工具生成。
// 运行时版本: 4.0.30319.42000
//
// 对此文件的更改可能导致不正确的行为,如果
// 重新生成代码,则所做更改将丢失。
// </auto-generated>
//------------------------------------------------------------------------------
namespace Biba.Properties
{
/// <summary>
/// 强类型资源类,用于查找本地化字符串等。
/// </summary>
// 此类是由 StronglyTypedResourceBuilder
// 类通过类似于 ResGen 或 Visual Studio 的工具自动生成的。
// 若要添加或删除成员,请编辑 .ResX 文件,然后重新运行 ResGen
// (以 /str 作为命令选项),或重新生成 VS 项目。
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class Resources
{
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Resources()
{
}
/// <summary>
/// 返回此类使用的缓存 ResourceManager 实例。
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager
{
get
{
if ((resourceMan == null))
{
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Biba.Properties.Resources", typeof(Resources).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// 覆盖当前线程的 CurrentUICulture 属性
/// 使用此强类型的资源类的资源查找。
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture
{
get
{
return resourceCulture;
}
set
{
resourceCulture = value;
}
}
}
}
| 33.611111 | 170 | 0.572314 | [
"MIT"
] | W-angler/Biba | Biba/Properties/Resources.Designer.cs | 2,750 | C# |
// Copyright (c) Six Labors and contributors.
// Licensed under the Apache License, Version 2.0.
using SixLabors.ImageSharp.PixelFormats;
using SixLabors.ImageSharp.Processing.Processors;
using SixLabors.Primitives;
namespace SixLabors.ImageSharp.Processing.Processors.Transforms
{
/// <summary>
/// The base class for all transform processors. Any processor that changes the dimensions of the image should inherit from this.
/// </summary>
/// <typeparam name="TPixel">The pixel format.</typeparam>
internal abstract class TransformProcessorBase<TPixel> : CloningImageProcessor<TPixel>
where TPixel : struct, IPixel<TPixel>
{
/// <inheritdoc/>
protected override void AfterImageApply(Image<TPixel> source, Image<TPixel> destination, Rectangle sourceRectangle)
=> TransformProcessorHelpers.UpdateDimensionalMetData(destination);
}
} | 42.857143 | 133 | 0.742222 | [
"Apache-2.0"
] | HighEndGuy/ImageSharp | src/ImageSharp/Processing/Processors/Transforms/TransformProcessorBase.cs | 902 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security;
using System.Text;
using System.Web;
using System.Xml;
using System.Xml.Linq;
using Inedo.BuildMaster;
using Inedo.BuildMaster.Data;
using Inedo.BuildMaster.Extensibility.Gadgets;
using Inedo.BuildMaster.Extensibility.Providers.SourceControl;
using Inedo.BuildMaster.Extensibility.Recipes;
using Inedo.BuildMaster.Extensibility.Scripting;
using Inedo.BuildMaster.Web;
using Inedo.BuildMaster.Web.Security;
using Inedo.BuildMasterExtensions.DotNetRecipes.Gadgets;
using Inedo.BuildMasterExtensions.DotNetRecipes.Providers;
using Inedo.Web.Handlers;
namespace Inedo.BuildMasterExtensions.DotNetRecipes
{
[RecipeProperties(
"BitChecker",
"Creates a new application that pulls code from a sample repository, compiles the project, and then publishes the files to local directories.",
RecipeScopes.Example)]
[CustomEditor(typeof(ExampleAspNetRecipeEditor))]
[WorkflowCreatingRequirements(MinimumEnvironmentCount = 1)]
public sealed class ExampleAspNetRecipe : RecipeBase, IApplicationCreatingRecipe, IWorkflowCreatingRecipe, IScmCreatingRecipe, IDashboardCreatingRecipe
{
public string DeploymentPath { get; set; }
public string ApplicationName { get; set; }
public string ApplicationGroup { get; set; }
public int ApplicationId { get; set; }
public string WorkflowName { get; set; }
public int[] WorkflowSteps { get; set; }
public int WorkflowId { get; set; }
public string SourceControlProviderName
{
get { return "Example"; }
set { throw new NotSupportedException(); }
}
public int ScmProviderId { get; set; }
public string ScmPath { get; set; }
public SourceControlProviderBase InstantiateSourceControlProvider()
{
return new ExampleSourceControlProvider();
}
public override void Execute()
{
var workflowSteps = StoredProcs
.Workflows_GetWorkflow(this.WorkflowId)
.Execute()
.WorkflowSteps_Extended;
int deployableId;
int databaseDeployableId;
{
var proc = StoredProcs
.Applications_CreateOrUpdateDeployable(
null,
this.ApplicationId,
"Web",
Domains.DeployableTypes.Other);
proc.ExecuteNonQuery();
deployableId = proc.Deployable_Id.Value;
proc = StoredProcs
.Applications_CreateOrUpdateDeployable(
null,
this.ApplicationId,
"Database",
Domains.DeployableTypes.Other);
proc.ExecuteNonQuery();
databaseDeployableId = proc.Deployable_Id.Value;
}
StoredProcs.Variables_CreateOrUpdateVariableDefinition("PreviousReleaseNumber", null, null, null, this.ApplicationId, null, null, null, null, "1.0", Domains.YN.No).Execute();
StoredProcs.Variables_CreateOrUpdateVariableDefinition("PreviousBuildNumber", null, null, null, this.ApplicationId, null, null, null, null, "1", Domains.YN.No).Execute();
string releaseNumber = "1.1";
StoredProcs.Releases_CreateOrUpdateRelease(
this.ApplicationId,
releaseNumber,
this.WorkflowId,
null,
null,
null,
"<ReleaseDeployables><ReleaseDeployable Deployable_Id=\"" + deployableId.ToString() + "\" InclusionType_Code=\"I\" />" +
"<ReleaseDeployable Deployable_Id=\"" + databaseDeployableId.ToString() + "\" InclusionType_Code=\"I\" /></ReleaseDeployables>")
.ExecuteNonQuery();
int configurationFileId;
{
var proc = StoredProcs.ConfigurationFiles_CreateConfigurationFile(null, deployableId, "web_appsettings.config", null, null);
proc.ExecuteNonQuery();
configurationFileId = proc.ConfigurationFile_Id.Value;
StoredProcs.ConfigurationFiles_CreateConfigurationFileInstance(
ConfigurationFile_Id: configurationFileId,
Instance_Name: "Template",
Environment_Id: null,
Template_Indicator: Domains.YN.Yes,
Template_Instance_Name: null,
TransformType_Code: Domains.ConfigurationFileTransformTypeCodes.KeyValuePair
).Execute();
}
foreach (var step in workflowSteps)
{
StoredProcs.ConfigurationFiles_CreateConfigurationFileInstance(
ConfigurationFile_Id: configurationFileId,
Instance_Name: step.Environment_Name,
Environment_Id: step.Environment_Id,
Template_Indicator: Domains.YN.No,
Template_Instance_Name: "Template",
TransformType_Code: null
).Execute();
}
var utf8 = new UTF8Encoding(false);
StoredProcs.ConfigurationFiles_CreateConfigurationFileVersions(
ConfigurationFile_Id: configurationFileId,
ConfigurationFiles_Xml: new XDocument(
new XElement("ConfigFiles",
from s in workflowSteps
select new XElement("Version",
new XAttribute("Instance_Name", s.Environment_Name),
new XAttribute("VersionNotes_Text", "Created automatically."),
new XAttribute("File_Bytes", Convert.ToBase64String(utf8.GetBytes(string.Format("ContactFormRecipient=contact-form-{0}@example.com\r\nSmtpServer={0}-mail-server", s.Environment_Name.ToLowerInvariant()))))
),
new XElement("Version",
new XAttribute("Instance_Name", "Template"),
new XAttribute("VersionNotes_Text", "Created automatically."),
new XAttribute("File_Bytes", Convert.ToBase64String(utf8.GetBytes(Properties.Resources.web_appsettings)))
)
)
).ToString(SaveOptions.DisableFormatting),
ReleaseNumbers_Csv: "1.1"
).Execute();
int databaseProviderId;
{
var proc = StoredProcs.Providers_CreateOrUpdateProvider(
null,
Domains.ProviderTypes.Database,
1,
"Example",
"Sample database provider for use only with example applications.",
Util.Persistence.SerializeToPersistedObjectXml(new ExampleDatabaseProvider()),
Domains.YN.Yes);
proc.ExecuteNonQuery();
databaseProviderId = (int)proc.Provider_Id;
}
this.CreateApproval();
CreateScript();
this.CreateBuildDeploymentPlan();
for (int i = 0; i < this.WorkflowSteps.Length; i++)
this.CreateEnvironmentDeploymentPlan(i, databaseProviderId);
}
private static int CreateScript()
{
var scriptType = (IScriptMetadataReader)Activator.CreateInstance(Type.GetType("Inedo.BuildMasterExtensions.Windows.Scripting.PowerShell.PowerShellScriptType,Windows"));
var metadata = scriptType.GetScriptMetadata(new StreamReader(new MemoryStream(Properties.Resources.BitChecker_SayHelloScript)));
var existingScript = StoredProcs.Scripts_GetScripts(((ScriptTypeBase)scriptType).ScriptTypeCode, "Y")
.Execute()
.FirstOrDefault(s => s.Script_Name.Equals("Say Hello to Inedo", StringComparison.OrdinalIgnoreCase));
int scriptId;
if (existingScript != null)
{
scriptId = existingScript.Script_Id;
}
else
{
scriptId = (int)StoredProcs.Scripts_CreateOrUpdateScript(null, "Say Hello to Inedo", metadata.Description, ((ScriptTypeBase)scriptType).ScriptTypeCode, "Y", "Y").Execute();
StoredProcs.Scripts_CreateVersion(1, scriptId, Properties.Resources.BitChecker_SayHelloScript).Execute();
foreach (var param in metadata.Parameters)
StoredProcs.Scripts_CreateOrUpdateParameter(scriptId, param.Name, Domains.ScriptParameterTypes.Standard, null, param.Description).Execute();
}
return scriptId;
}
private void CreateBuildDeploymentPlan()
{
var licenseKey = string.Join(
",",
StoredProcs.LicenseKeys_GetLicenseKeys().Execute().Select(k => k.LicenseKey_Text.Remove(5, 27).Insert(5, "..."))
);
var reader = XmlReader.Create(
new StringReader(
Replacer.Replace(
Properties.Resources.BitChecker_Build_Plan,
new Dictionary<string, string>
{
{ "ApplicationId", this.ApplicationId.ToString() },
{ "LicenseKey", licenseKey }
}
)
)
);
int buildPlanId = Util.Plans.ImportFromXml(reader);
StoredProcs.Workflows_SetBuildStep(
Workflow_Id: this.WorkflowId,
Build_DeploymentPlan_Id: buildPlanId,
BuildImporterTemplate_Configuration: null
).Execute();
}
private void CreateEnvironmentDeploymentPlan(int step, int databaseProviderId)
{
var environment = StoredProcs.Environments_GetEnvironment(this.WorkflowSteps[step])
.Execute()
.Environments
.First();
var reader = XmlReader.Create(
new StringReader(
Replacer.Replace(
Properties.Resources.BitChecker_Environment_Plan,
new Dictionary<string, string>
{
{ "Environment", environment.Environment_Name },
{ "DatabaseProviderId", databaseProviderId.ToString() }
}
)
)
);
int planId = Util.Recipes.CreateDeploymentPlanForWorkflowStep(this.WorkflowId, step + 1);
Util.Plans.ImportFromXml(planId, reader);
}
private void CreateApproval()
{
int? directoryProviderId = InedoLib.Util.Int.ParseN(StoredProcs.Configuration_GetValue("CoreEx", "DirectoryProvider", null).Execute());
if (directoryProviderId != 1)
return;
var admin = StoredProcs.Users_GetUsers().Execute().Users.FirstOrDefault(u => u.User_Name.Equals("Admin", StringComparison.OrdinalIgnoreCase));
if (admin == null)
return;
StoredProcs.Promotions_CreateOrUpdateRequirement(
Environment_Id: this.WorkflowSteps[0],
Requirement_Description: "Approved by Admin",
Workflow_Id: this.WorkflowId,
Principal_Name: "Admin"
).Execute();
}
public void CreateDashboards()
{
// application dashboard
{
StoredProcs.Dashboards_CreateDashboard(this.ApplicationId, null, Domains.DashboardScopes.Application).ExecuteNonQuery();
string dashboardText;
using (var stream = typeof(ExampleAspNetRecipe).Assembly.GetManifestResourceStream("Inedo.BuildMasterExtensions.DotNetRecipes.BitCheckerApplicationText.html"))
using (var reader = new StreamReader(stream))
{
dashboardText = reader
.ReadToEnd()
.Replace("__CREATE_BUILD_URL__", HttpUtility.JavaScriptStringEncode(DynamicHttpHandling.GetProcessRequestDelegateUrl(CreateBuild) + "?applicationId=" + this.ApplicationId));
}
int dashboardId = (int)StoredProcs.Dashboards_GetDashboard(this.ApplicationId, Domains.DashboardScopes.Application).ExecuteDataRow()[TableDefs.Dashboards.Dashboard_Id];
var freeTextGadget = Util.Recipes.Munging.MungeInstance("Inedo.BuildMaster.Extensibility.Gadgets.FreeTextGadget,BuildMaster.Web.WebApplication", new
{
AllowHtml = true,
Text = dashboardText
});
AddGadget(dashboardId, 1, freeTextGadget);
AddGadget(dashboardId, 1, new HideNavigationGadget());
}
// build dashboard
{
string dashboardText;
using (var stream = typeof(ExampleAspNetRecipe).Assembly.GetManifestResourceStream("Inedo.BuildMasterExtensions.DotNetRecipes.BitCheckerBuildText.html"))
using (var reader = new StreamReader(stream))
{
dashboardText = reader.ReadToEnd();
}
StoredProcs.Dashboards_CreateDashboard(this.ApplicationId, null, Domains.DashboardScopes.Build).ExecuteNonQuery();
int dashboardId = (int)StoredProcs.Dashboards_GetDashboard(this.ApplicationId, Domains.DashboardScopes.Build).ExecuteDataRow()[TableDefs.Dashboards.Dashboard_Id];
var freeTextGadget = Util.Recipes.Munging.MungeInstance("Inedo.BuildMaster.Extensibility.Gadgets.FreeTextGadget,BuildMaster.Web.WebApplication", new
{
AllowHtml = true,
Text = dashboardText
});
AddGadget(dashboardId, 1, freeTextGadget);
AddGadget(dashboardId, 1, Activator.CreateInstance(Type.GetType("Inedo.BuildMaster.Extensibility.Gadgets.Build.BuildDetailsGadget,BuildMaster.Web.WebApplication")));
AddGadget(dashboardId, 1, Activator.CreateInstance(Type.GetType("Inedo.BuildMaster.Extensibility.Gadgets.Build.BuildPromotionStatusGadget,BuildMaster.Web.WebApplication")));
AddGadget(dashboardId, 2, Activator.CreateInstance(Type.GetType("Inedo.BuildMaster.Extensibility.Gadgets.Build.BuildApprovalsGadget,BuildMaster.Web.WebApplication")));
AddGadget(dashboardId, 2, Activator.CreateInstance(Type.GetType("Inedo.BuildMaster.Extensibility.Gadgets.Build.BuildPromotionsGadget,BuildMaster.Web.WebApplication")));
AddGadget(dashboardId, 2, Activator.CreateInstance(Type.GetType("Inedo.BuildMaster.Extensibility.Gadgets.Build.BuildExecutionsGadget,BuildMaster.Web.WebApplication")));
AddGadget(dashboardId, 3, Activator.CreateInstance(Type.GetType("Inedo.BuildMaster.Extensibility.Gadgets.Build.BuildArtifactsGadget,BuildMaster.Web.WebApplication")));
AddGadget(dashboardId, 3, Activator.CreateInstance(Type.GetType("Inedo.BuildMaster.Extensibility.Gadgets.ReleaseNotesGadget,BuildMaster.Web.WebApplication")));
AddGadget(dashboardId, 4, Activator.CreateInstance(Type.GetType("Inedo.BuildMaster.Extensibility.Gadgets.Build.BuildUnitTestsGadget,BuildMaster.Web.WebApplication")));
AddGadget(dashboardId, 4, Activator.CreateInstance(Type.GetType("Inedo.BuildMaster.Extensibility.Gadgets.Build.BuildReportsGadget,BuildMaster.Web.WebApplication")));
}
}
private static void AddGadget(int dashboardId, int zone, object gadget)
{
StoredProcs.Dashboards_CreateOrUpdateGadget(
null,
dashboardId,
zone,
null,
Util.Reflection.GetCustomAttribute<GadgetPropertiesAttribute>(gadget.GetType()).Name,
gadget.ToString(),
Util.Persistence.SerializeToPersistedObjectXml(gadget)
).ExecuteNonQuery();
}
private static void CreateBuild(HttpContext context)
{
int applicationId = int.Parse(context.Request.QueryString["applicationId"]);
if (!WebUserContext.CanPerformTask(SecuredTask.Builds_CreateBuild, applicationId: applicationId))
throw new SecurityException();
var release = StoredProcs.Releases_GetReleases(applicationId, Domains.ReleaseStatus.Active, 1).Execute().First();
var buildNumber = StoredProcs.Builds_CreateBuild(
Application_Id: applicationId,
Release_Number: release.Release_Number,
PromoteBuild_Indicator: Domains.YN.Yes,
StartExecution_Indicator: Domains.YN.Yes,
ExecutionStart_Date: null,
Requested_Build_Number: null,
BuildVariables_Xml: null,
PromotionVariables_Xml: null,
ExecutionVariables_Xml: null,
Build_Number: null,
BuildImporter_Configuration: null
).Execute();
context.Response.Redirect(
string.Format(
"/applications/{0}/executions/execution-in-progress?releaseNumber={1}&buildNumber={2}",
applicationId,
Uri.EscapeDataString(release.Release_Number),
Uri.EscapeDataString(buildNumber)
)
);
}
}
}
| 49.566757 | 237 | 0.59436 | [
"Unlicense"
] | Inedo/bmx-dotnetrecipes | ExampleAspNetRecipe.cs | 18,193 | C# |
namespace BorderControl
{
public interface IBirthable
{
//---------------------------Properties---------------------------
string Birthdate { get; }
}
}
| 20.222222 | 74 | 0.412088 | [
"MIT"
] | Vanrektus/Software-University | C# Web Development/04. C# OOP/03. Interfaces and Abstraction/Exercise/BirthdayCelebrations/Interfaces/IBirthable.cs | 184 | C# |
using Dfc.CourseDirectory.Services.Models;
namespace Dfc.CourseDirectory.Web.ViewModels.Apprenticeships
{
public class WhatWouldYouLikeToDoViewModel
{
public ApprenticeshipWhatWouldYouLikeToDo ApprenticeshipWhatWouldYouLikeToDo { get; set; }
}
}
| 26.8 | 98 | 0.791045 | [
"MIT"
] | SkillsFundingAgency/dfc-coursedirectory | src/Dfc.CourseDirectory.Web/ViewModels/Apprenticeships/WhatWouldYouLikeToDoViewModel.cs | 270 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Hosting;
using NCrontab;
namespace WarelogManager.Model.BackgroundServices
{
public class GoogleTrendsDataHostedService : BackgroundService
{
private CrontabSchedule _schedule;
private DateTime _nextRun;
private string Schedule => "0 0 * ? * * "; //Runs every hour
public GoogleTrendsDataHostedService()
{
_schedule = CrontabSchedule.Parse(Schedule, new CrontabSchedule.ParseOptions
{ IncludingSeconds = true });
_nextRun = _schedule.GetNextOccurrence(DateTime.Now);
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
do
{
var now = DateTime.Now;
if (now > _nextRun)
{
Process();
_nextRun = _schedule.GetNextOccurrence(DateTime.Now);
}
await Task.Delay(5000, stoppingToken); //5 seconds delay
}
while (!stoppingToken.IsCancellationRequested);
}
private void Process()
{
Console.WriteLine("hello world" + DateTime.Now.ToString("F"));
}
}
}
| 29.652174 | 88 | 0.601173 | [
"MIT"
] | propil5/Warelog | src/Model/BackgroundServices/GoogleTrendsDataHostedService.cs | 1,366 | C# |
using MarcoGazzola.Base;
using MarcoGazzola.Base.Interfaces;
using MarcoGazzola.MongoDB.Interfaces;
using MongoDB.Driver;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace MarcoGazzola.MongoDB
{
public class BaseRepository<T> : IBaseRepository<T> where T : IEntity
{
public readonly IDBContext dbContext;
public BaseRepository(IDBContext dbContext, string CollectionName)
{
this.dbContext = dbContext;
this.CollectionItems = dbContext.database.GetCollection<T>(CollectionName);
this.CollectionName = CollectionName;
}
private IMongoCollection<T> CollectionItems { get; }
public string CollectionName { get; }
public async Task<IInsertOperationResult> Add(T item)
{
try
{
item.CreatedOn = DateTime.Now;
item.Id = null;
await this.CollectionItems.InsertOneAsync(item);
return new InsertOperationResult(item.Id, true);
}
catch (Exception ex)
{
return await new Task<IInsertOperationResult>(() => (IInsertOperationResult)ex.MongoException());
}
}
public T CreateInstance()
{
return (T)Activator.CreateInstance(typeof(T));
}
public async Task<IEnumerable<T>> GetAll()
{
return await this.CollectionItems.Find(_ => true).ToListAsync();
}
public async Task<T> GetByID(string id)
{
return await this.CollectionItems.Find(item => item.Id == id).FirstOrDefaultAsync<T>();
}
public async Task<IOperationResult> Remove(T item)
{
try
{
return (await this.CollectionItems.DeleteOneAsync(Builders<T>.Filter.Eq("Id", item.Id))).ToOperationResult();
}
catch (Exception ex)
{
return await new Task<IOperationResult>(() => ex.MongoException());
}
}
public async Task RemoveAll()
{
await this.dbContext.database.DropCollectionAsync(this.CollectionName);
}
public async Task<IOperationResult> Update(T item)
{
try
{
var filter = Builders<T>.Filter.Eq(s => s.Id, item.Id);
item.UpdatedOn = DateTime.Now;
return (await this.CollectionItems.ReplaceOneAsync(filter, item)).ToOperationResult(); ;
}
catch (Exception ex)
{
return await new Task<IOperationResult>(() => ex.MongoException());
}
}
}
} | 33.023529 | 126 | 0.554328 | [
"Apache-2.0"
] | marcogazzola/MarcoGazzola.Core | MarcoGazzola.MongoDB/BaseRepository.cs | 2,809 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace Population.Properties
{
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0")]
internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase
{
private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
public static Settings Default
{
get
{
return defaultInstance;
}
}
}
}
| 34.354839 | 151 | 0.581221 | [
"MIT"
] | datsukai/owatc | Ch5/Population/Population/Properties/Settings.Designer.cs | 1,067 | C# |
using System;
using System.Threading;
namespace Fibrous
{
internal sealed class TimerAction : IDisposable
{
private readonly Action _action;
private readonly TimeSpan _interval;
private bool _cancelled;
private Timer _timer;
public TimerAction(IFiber fiber, Action action, TimeSpan dueTime)
{
_action = action;
_interval = TimeSpan.FromMilliseconds(-1);
_timer = new Timer(x => ExecuteOnTimerThread(fiber), null, dueTime, _interval);
fiber.Add(this);
}
public TimerAction(IFiber fiber, Action action, TimeSpan dueTime, TimeSpan interval)
{
_action = action;
_interval = interval;
_timer = new Timer(x => ExecuteOnTimerThread(fiber), null, dueTime, interval);
fiber.Add(this);
}
public void Dispose()
{
_cancelled = true;
DisposeTimer();
}
private void ExecuteOnTimerThread(IFiber fiber)
{
if (_interval.Ticks == TimeSpan.FromMilliseconds(-1).Ticks || _cancelled)
{
fiber.Remove(this);
DisposeTimer();
}
if (!_cancelled)
{
fiber.Enqueue(Execute);
}
}
private void Execute()
{
if (!_cancelled)
{
_action();
}
}
private void DisposeTimer()
{
_timer?.Dispose();
_timer = null;
}
}
}
| 24.859375 | 92 | 0.512256 | [
"MIT"
] | chrisa23/Fibrous | Fibrous/Internal/Scheduling/TimerAction.cs | 1,591 | C# |
namespace Web_BTL_Backend.Models.ClientSendForm
{
public class ReportForm
{
public int idPost { set; get; }
public string content { set; get; }
public int reportType { set; get; }
}
}
| 18.583333 | 47 | 0.609865 | [
"MIT"
] | FCBTruong/Web-BTL-Backend | Web-BTL-Backend/Models/ClientSendForm/ReportForm.cs | 225 | 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.ContainerInstance.V20171001Preview
{
public static class GetContainerGroup
{
public static Task<GetContainerGroupResult> InvokeAsync(GetContainerGroupArgs args, InvokeOptions? options = null)
=> Pulumi.Deployment.Instance.InvokeAsync<GetContainerGroupResult>("azure-nextgen:containerinstance/v20171001preview:getContainerGroup", args ?? new GetContainerGroupArgs(), options.WithVersion());
}
public sealed class GetContainerGroupArgs : Pulumi.InvokeArgs
{
/// <summary>
/// The name of the container group.
/// </summary>
[Input("containerGroupName", required: true)]
public string ContainerGroupName { get; set; } = null!;
/// <summary>
/// The name of the resource group.
/// </summary>
[Input("resourceGroupName", required: true)]
public string ResourceGroupName { get; set; } = null!;
public GetContainerGroupArgs()
{
}
}
[OutputType]
public sealed class GetContainerGroupResult
{
/// <summary>
/// The containers within the container group.
/// </summary>
public readonly ImmutableArray<Outputs.ContainerResponse> Containers;
/// <summary>
/// The image registry credentials by which the container group is created from.
/// </summary>
public readonly ImmutableArray<Outputs.ImageRegistryCredentialResponse> ImageRegistryCredentials;
/// <summary>
/// The instance view of the container group. Only valid in response.
/// </summary>
public readonly Outputs.ContainerGroupResponseInstanceView InstanceView;
/// <summary>
/// The IP address type of the container group.
/// </summary>
public readonly Outputs.IpAddressResponse? IpAddress;
/// <summary>
/// The resource location.
/// </summary>
public readonly string Location;
/// <summary>
/// The resource name.
/// </summary>
public readonly string Name;
/// <summary>
/// The operating system type required by the containers in the container group.
/// </summary>
public readonly string OsType;
/// <summary>
/// The provisioning state of the container group. This only appears in the response.
/// </summary>
public readonly string ProvisioningState;
/// <summary>
/// Restart policy for all containers within the container group.
/// - `Always` Always restart
/// - `OnFailure` Restart on failure
/// - `Never` Never restart
/// </summary>
public readonly string? RestartPolicy;
/// <summary>
/// The resource tags.
/// </summary>
public readonly ImmutableDictionary<string, string>? Tags;
/// <summary>
/// The resource type.
/// </summary>
public readonly string Type;
/// <summary>
/// The list of volumes that can be mounted by containers in this container group.
/// </summary>
public readonly ImmutableArray<Outputs.VolumeResponse> Volumes;
[OutputConstructor]
private GetContainerGroupResult(
ImmutableArray<Outputs.ContainerResponse> containers,
ImmutableArray<Outputs.ImageRegistryCredentialResponse> imageRegistryCredentials,
Outputs.ContainerGroupResponseInstanceView instanceView,
Outputs.IpAddressResponse? ipAddress,
string location,
string name,
string osType,
string provisioningState,
string? restartPolicy,
ImmutableDictionary<string, string>? tags,
string type,
ImmutableArray<Outputs.VolumeResponse> volumes)
{
Containers = containers;
ImageRegistryCredentials = imageRegistryCredentials;
InstanceView = instanceView;
IpAddress = ipAddress;
Location = location;
Name = name;
OsType = osType;
ProvisioningState = provisioningState;
RestartPolicy = restartPolicy;
Tags = tags;
Type = type;
Volumes = volumes;
}
}
}
| 34.318519 | 209 | 0.619685 | [
"Apache-2.0"
] | test-wiz-sec/pulumi-azure-nextgen | sdk/dotnet/ContainerInstance/V20171001Preview/GetContainerGroup.cs | 4,633 | C# |
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
namespace CleanWebApi.WebApi.Controllers.V1
{
[ApiVersion("1.0")]
[Route("api/v1/[controller]")]
[ApiExplorerSettings(GroupName = "v1")]
[Authorize]
public abstract class BaseV1Controller : BaseController
{
}
} | 24.076923 | 59 | 0.71246 | [
"MIT"
] | pyrox18/Pyrox.CleanArchitectureTemplates | templates/webapi-clean/src/CleanWebApi.WebApi/Controllers/V1/BaseV1Controller.cs | 313 | 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.Collections.Generic;
using NuGet.Services.Status;
namespace StatusAggregator.Tests
{
public class TestComponent : Component
{
private const string DefaultDescription = "";
public TestComponent(string name)
: base(name, DefaultDescription)
{
}
public TestComponent(
string name,
IEnumerable<IComponent> subComponents,
bool displaySubComponents = true)
: base(name, DefaultDescription, subComponents, displaySubComponents)
{
}
public override ComponentStatus Status { get; set; }
}
} | 28.678571 | 111 | 0.655044 | [
"Apache-2.0"
] | CyberAndrii/NuGet.Jobs | tests/StatusAggregator.Tests/TestComponent.cs | 805 | C# |
using Alachisoft.NCache.Client;
using Alachisoft.NCache.Runtime.Caching;
using Alachisoft.NCache.Runtime.Dependencies;
using Alachisoft.NCache.Samples.Dapper.ConsoleUI.Repository;
using Alachisoft.NCache.Samples.Dapper.ConsoleUI.SeedData;
using Alachisoft.NCache.Samples.Dapper.Models;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Diagnostics;
using System.Linq;
namespace Alachisoft.NCache.Samples.Dapper.ConsoleUI
{
public static class DapperDemo
{
static readonly ICache cache;
static readonly string connectionString;
static readonly bool useCache;
static DapperDemo()
{
var cacheId = ConfigurationManager.AppSettings["cacheId"];
cache = CacheManager.GetCache(cacheId);
connectionString =
ConfigurationManager.ConnectionStrings["sql"].ConnectionString;
useCache = bool.Parse(ConfigurationManager.AppSettings["UseCache"]);
}
public static void Run()
{
var done = false;
while (!done)
{
switch (GetUserChoice())
{
case 1:
{
IEnumerable<string> customerIds;
var stopWatch = new Stopwatch();
if (useCache)
{
stopWatch.Start();
customerIds =
cache.DataTypeManager.GetList<string>(
"Customer:CustomerID:All",
new ReadThruOptions
{
Mode = ReadMode.ReadThru
});
stopWatch.Stop();
}
else
{
stopWatch.Start();
customerIds =
CustomerRepository.GetCustomerIDs();
stopWatch.Stop();
}
var ms = stopWatch.ElapsedMilliseconds;
Console.WriteLine($"Total operation time: {ms} ms");
if (customerIds.Count() == 0)
{
Console.WriteLine("No customers in database");
}
else
{
PrintCustomerIDs(customerIds);
}
}
break;
case 2:
{
var customerID = GetCustomerID();
var stopWatch = new Stopwatch();
if (!string.IsNullOrWhiteSpace(customerID))
{
Customer customer;
if (useCache)
{
stopWatch.Start();
customer =
cache.Get<Customer>(
$"Customer:CustomerID:{customerID}",
new ReadThruOptions(
ReadMode.ReadThru));
stopWatch.Stop();
}
else
{
stopWatch.Start();
customer =
CustomerRepository.GetCustomer(customerID);
stopWatch.Stop();
}
var ms = stopWatch.ElapsedMilliseconds;
Console.WriteLine($"Total operation time: {ms} ms");
PrintCustomerDetails(customer);
}
}
break;
case 3:
{
var customerID = GetCustomerID();
if (!string.IsNullOrWhiteSpace(customerID))
{
if (useCache)
{
cache.Remove(
$"Customer:CustomerID:{customerID}",
null,
null,
new WriteThruOptions(
WriteMode.WriteThru));
}
else
{
CustomerRepository.DeleteCustomer(customerID);
}
}
}
break;
case 4:
{
var customer = CustomerSeed.SeedCustomers()
.Generate();
Console.WriteLine("New customer:\n");
PrintCustomerDetails(customer);
if (useCache)
{
cache.Add(
$"Customer:CustomerID:{customer.CustomerID}",
new CacheItem(customer)
{
Dependency = GetCustomerSqlDependency(
customer.CustomerID),
ResyncOptions = new ResyncOptions(true)
},
new WriteThruOptions
{
Mode = WriteMode.WriteThru
});
}
else
{
CustomerRepository.SaveCustomer(customer);
}
}
break;
case 5:
{
var customerID = GetCustomerID();
Customer oldCustomer = null;
if (!string.IsNullOrWhiteSpace(customerID))
{
if (useCache)
{
oldCustomer =
cache.Get<Customer>(
$"Customer:CustomerID:{customerID}",
new ReadThruOptions
{
Mode = ReadMode.ReadThru
});
}
else
{
oldCustomer =
CustomerRepository.GetCustomer(customerID);
}
}
if (oldCustomer == null)
{
Console.WriteLine(
$"No customer with ID {customerID} exists " +
$"in database");
}
else
{
var newCustomer = CustomerSeed.SeedCustomers()
.Generate();
newCustomer.CustomerID = customerID;
Console.WriteLine("Updated customer:\n");
PrintCustomerDetails(newCustomer);
if (useCache)
{
cache.Insert(
$"Customer:CustomerID:{customerID}",
new CacheItem(newCustomer)
{
Dependency = GetCustomerSqlDependency(
customerID),
ResyncOptions = new ResyncOptions(true)
},
new WriteThruOptions
{
Mode = WriteMode.WriteThru
});
}
else
{
CustomerRepository.UpdateCustomer(newCustomer);
}
}
}
break;
case 6:
{
var country = GetCustomerCountry();
if (!string.IsNullOrWhiteSpace(country))
{
IEnumerable<string> customerIds;
var stopWatch = new Stopwatch();
if (useCache)
{
stopWatch.Start();
customerIds =
cache.DataTypeManager.GetList<string>(
$"Customer:Country:{country}",
new ReadThruOptions
{
Mode = ReadMode.ReadThru
});
stopWatch.Stop();
}
else
{
stopWatch.Start();
customerIds =
CustomerRepository.GetCustomerIDsByCountry(
country);
stopWatch.Stop();
}
var ms = stopWatch.ElapsedMilliseconds;
Console.WriteLine($"Total operation time: {ms} ms");
if (customerIds.Count() == 0)
{
Console.WriteLine(
$"No customers in database with country " +
$" {country}");
}
else
{
PrintCustomerIDs(customerIds);
}
}
}
break;
case 7:
{
done = true;
}
break;
}
}
}
private static int GetUserChoice()
{
Console.WriteLine("");
Console.WriteLine(" 1- View customers list");
Console.WriteLine(" 2- View customer details");
Console.WriteLine(" 3- Delete customer");
Console.WriteLine(" 4- Add customer");
Console.WriteLine(" 5- Update customer");
Console.WriteLine(" 6- View customers by country");
Console.WriteLine(" 7- Exit");
Console.WriteLine("");
Console.Write("Enter your choice (1 - 7): ");
try
{
int choice = Convert.ToInt32(Console.ReadLine());
if (choice >= 1 && choice <= 7)
return choice;
}
catch (Exception)
{
}
Console.WriteLine("Please enter a valid choice (1 - 7)");
return GetUserChoice();
}
private static string GetCustomerID()
{
Console.Write("Please enter the customer Id: ");
string result = Console.ReadLine();
if (string.IsNullOrWhiteSpace(result))
{
Console.WriteLine("customer id can not be empty.");
return null;
}
return result.ToUpperInvariant();
}
private static string GetCustomerCountry()
{
Console.Write("Please enter the country: ");
string result = Console.ReadLine();
if (string.IsNullOrWhiteSpace(result))
{
Console.WriteLine("customer country can not be empty.");
return null;
}
return result;
}
private static void PrintCustomerIDs(IEnumerable<string> customerIds)
{
int i = 1;
foreach (var customerId in customerIds)
{
Console.WriteLine($"{i++}-{customerId}");
}
}
private static void PrintCustomerDetails(Customer customer)
{
if (customer != null)
{
Console.WriteLine("Customer's Details");
Console.WriteLine("------------------");
Console.WriteLine("Customer ID : " + customer.CustomerID);
Console.WriteLine("Name : " + customer.ContactName);
Console.WriteLine("Company : " + customer.CompanyName);
Console.WriteLine("Address : " + customer.Address);
Console.WriteLine("Country : " + customer.Country);
}
else
{
Console.WriteLine("No such customer exists.");
}
}
private static SqlCacheDependency GetCustomerSqlDependency(
string customerId)
{
var sqlQuery = $"SELECT CustomerID, " +
$" CompanyName, " +
$" ContactName, " +
$" ContactTitle, " +
$" City, " +
$" Country, " +
$" Region, " +
$" PostalCode, " +
$" Phone, " +
$" Fax, " +
$" Address " +
$"FROM dbo.Customers " +
$"WHERE CustomerID = @cid";
var cmdParam = new SqlCmdParams
{
Value = customerId,
Size = 255,
Type = CmdParamsType.NVarChar
};
var sqlCmdParams = new Dictionary<string, SqlCmdParams>
{
{"@cid", cmdParam }
};
return new SqlCacheDependency(
connectionString,
sqlQuery,
SqlCommandType.Text,
sqlCmdParams);
}
}
}
| 41.125313 | 89 | 0.31757 | [
"Apache-2.0"
] | Alachisoft/NCache-Solutions | BackingSourceWithDapperUsingNCache/ConsoleUI/DapperDemo.cs | 16,411 | C# |
/*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the kinesis-video-archived-media-2017-09-30.normal.json service model.
*/
using System;
using Amazon.Runtime;
using Amazon.Util.Internal;
namespace Amazon.KinesisVideoArchivedMedia
{
/// <summary>
/// Configuration for accessing Amazon KinesisVideoArchivedMedia service
/// </summary>
public partial class AmazonKinesisVideoArchivedMediaConfig : ClientConfig
{
private static readonly string UserAgentString =
InternalSDKUtils.BuildUserAgentString("3.7.0.116");
private string _userAgent = UserAgentString;
/// <summary>
/// Default constructor
/// </summary>
public AmazonKinesisVideoArchivedMediaConfig()
{
this.AuthenticationServiceName = "kinesisvideo";
}
/// <summary>
/// The constant used to lookup in the region hash the endpoint.
/// </summary>
public override string RegionEndpointServiceName
{
get
{
return "kinesisvideo";
}
}
/// <summary>
/// Gets the ServiceVersion property.
/// </summary>
public override string ServiceVersion
{
get
{
return "2017-09-30";
}
}
/// <summary>
/// Gets the value of UserAgent property.
/// </summary>
public override string UserAgent
{
get
{
return _userAgent;
}
}
}
} | 27.1875 | 126 | 0.602759 | [
"Apache-2.0"
] | raz2017/aws-sdk-net | sdk/src/Services/KinesisVideoArchivedMedia/Generated/AmazonKinesisVideoArchivedMediaConfig.cs | 2,175 | C# |
using System;
namespace AirPlaneDDD.WebAPI.Models
{
public class AirPlaneModelAddModel
{
public Guid Id { get; set; }
}
}
| 14.4 | 38 | 0.645833 | [
"MIT"
] | pedrovasconcellos/AirPlane-Angular6-And-NETCoreInDDD | AirPlaneDDD/AirPlaneDDD.WebAPI/Models/AirPlaneModelAddModel.cs | 146 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
//
using System;
using System.Runtime.CompilerServices;
public class BringUpTest
{
const int Pass = 100;
const int Fail = -1;
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static int JTrueGeFP(float x)
{
int returnValue = -1;
if (x >= 2f) returnValue = 4;
else if (x >= 1f) returnValue = 3;
else if (x >= 0f) returnValue = 2;
else if (x >= -1f) returnValue = 1;
return returnValue;
}
public static int Main()
{
int returnValue = Pass;
if (JTrueGeFP(-1f) != 1) returnValue = Fail;
if (JTrueGeFP(0f) != 2) returnValue = Fail;
if (JTrueGeFP(1f) != 3) returnValue = Fail;
if (JTrueGeFP(2f) != 4) returnValue = Fail;
return returnValue;
}
}
| 26.075 | 71 | 0.534995 | [
"MIT"
] | 2m0nd/runtime | src/tests/JIT/CodeGenBringUpTests/JTrueGeFP.cs | 1,043 | C# |
using System.Collections.Generic;
using System.Dynamic;
namespace Fundigent.Blog.API.Helpers
{
public static class ObjectExtensions
{
public static ExpandoObject Expand<TSource>(this TSource source)
{
var propertyInfoList = typeof(TSource).GetProperties(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance);
var expando = new ExpandoObject();
foreach (var propertyInfo in propertyInfoList)
{
var propertyValue = propertyInfo.GetValue(source);
((IDictionary<string, object>)expando).Add(propertyInfo.Name, propertyValue);
}
return expando;
}
}
}
| 31.130435 | 146 | 0.649441 | [
"MIT"
] | greggsjh/fundigent-blog | Fundigent.Blog.API/Helpers/ObjectExtensions.cs | 716 | C# |
// <auto-generated>
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// </auto-generated>
namespace Gov.Jag.PillPressRegistry.Interfaces
{
using Microsoft.Rest;
using Models;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// Accounts operations.
/// </summary>
public partial interface IAccounts
{
/// <summary>
/// Get entities from accounts
/// </summary>
/// <param name='top'>
/// </param>
/// <param name='skip'>
/// </param>
/// <param name='search'>
/// </param>
/// <param name='filter'>
/// </param>
/// <param name='count'>
/// </param>
/// <param name='orderby'>
/// Order items by property values
/// </param>
/// <param name='select'>
/// Select properties to be returned
/// </param>
/// <param name='expand'>
/// Expand related entities
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="OdataerrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
Task<HttpOperationResponse<AccountsGetResponseModel>> GetWithHttpMessagesAsync(int? top = default(int?), int? skip = default(int?), string search = default(string), string filter = default(string), bool? count = default(bool?), IList<string> orderby = default(IList<string>), IList<string> select = default(IList<string>), IList<string> expand = default(IList<string>), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Add new entity to accounts
/// </summary>
/// <param name='body'>
/// New entity
/// </param>
/// <param name='prefer'>
/// Required in order for the service to return a JSON representation
/// of the object.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="OdataerrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<HttpOperationResponse<MicrosoftDynamicsCRMaccount>> CreateWithHttpMessagesAsync(MicrosoftDynamicsCRMaccount body, string prefer = "return=representation", Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Get entity from accounts by key
/// </summary>
/// <param name='accountid'>
/// key: accountid
/// </param>
/// <param name='select'>
/// Select properties to be returned
/// </param>
/// <param name='expand'>
/// Expand related entities
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="OdataerrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<HttpOperationResponse<MicrosoftDynamicsCRMaccount>> GetByKeyWithHttpMessagesAsync(string accountid, IList<string> select = default(IList<string>), IList<string> expand = default(IList<string>), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Delete entity from accounts
/// </summary>
/// <param name='accountid'>
/// key: accountid
/// </param>
/// <param name='ifMatch'>
/// ETag
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="OdataerrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<HttpOperationResponse> DeleteWithHttpMessagesAsync(string accountid, string ifMatch = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Update entity in accounts
/// </summary>
/// <param name='accountid'>
/// key: accountid
/// </param>
/// <param name='body'>
/// New property values
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="OdataerrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<HttpOperationResponse> UpdateWithHttpMessagesAsync(string accountid, MicrosoftDynamicsCRMaccount body, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
}
}
| 43.666667 | 499 | 0.600705 | [
"Apache-2.0"
] | WadeBarnes/jag-pill-press-registry | pill-press-interfaces/Dynamics-Autorest/IAccounts.cs | 6,812 | C# |
using System.ComponentModel.DataAnnotations;
namespace SmartValley.WebApi.Subscriptions.Requests
{
public class CreateSubscriptionRequest
{
[Required, MaxLength(100)]
public string Name { get; set; }
[Required, EmailAddress]
public string Email { get; set; }
[Required, MaxLength(100)]
public string Sum { get; set; }
[MaxLength(50)]
public string Phone { get; set; }
}
}
| 22.65 | 51 | 0.624724 | [
"MIT"
] | SmartValleyEcosystem/smartvalley | SmartValley.WebApi/Subscriptions/Requests/CreateSubscriptionRequest.cs | 455 | C# |
using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace GroupMaker
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : NavigationWindow
{
public MainWindow()
{
InitializeComponent();
}
}
}
| 19.8 | 54 | 0.7114 | [
"MIT"
] | A-Fitz/Group-Generator | MainWindow.xaml.cs | 695 | C# |
using MaterialDesignThemes.Wpf;
using System;
using System.Data;
using System.Data.SqlClient;
using System.Globalization;
using System.Reflection;
using System.Resources;
using System.Windows;
using System.Windows.Input;
namespace VisualUNITY.DiameterLast
{
/// <summary>
/// Interaction logic for AdminConfirmation.xaml
/// </summary>
public partial class AdminConfirmation : Window
{
SqlConnection localDbConnectionUnity, localDbConnectionUnity2, localDbConnectionProject1;
Assembly assembly;
ResourceManager rm;
CultureInfo cultureInfo;
SnackbarMessageQueue myMessageQueue = new SnackbarMessageQueue(TimeSpan.FromSeconds(2));
int id;
string transaction, nameReceived;
public AdminConfirmation(int idReceived, string transactionReceived, string name)
{
InitializeComponent();
Snackbar.MessageQueue = myMessageQueue;
assembly = Assembly.Load("VisualUNITY");
rm = new ResourceManager("VisualUNITY.Languages.language", assembly);
cultureInfo = new CultureInfo(Properties.Settings.Default.language);
string pathToDBFile = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + @"\VisualUnity\Unity.mdf";
string pathToDBFile2 = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + @"\VisualUnity\Projects.mdf";
localDbConnectionUnity = new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=" + pathToDBFile + ";Integrated Security=True");
localDbConnectionUnity2 = new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=" + pathToDBFile + ";Integrated Security=True");
localDbConnectionProject1 = new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=" + pathToDBFile2 + ";Integrated Security=True");
id = idReceived;
transaction = transactionReceived;
nameReceived = name;
}
private void confirm_Click(object sender, RoutedEventArgs e)
{
doWork(transaction);
}
private void HandleOKMethod()
{
}
private void confirmation_KeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Enter)
{
doWork(transaction);
}
}
private void doWork(string work)
{
switch (work)
{
case "project":
deleteProject();
break;
case "product":
deleteProduct();
break;
case "company":
deleteCompany();
break;
}
}
private void Window_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
this.DragMove();
}
private void deleteProject()
{
if (confirmation.Password == "")
{
myMessageQueue.Enqueue(rm.GetString("confirmationIsEmpty"), rm.GetString("ok"), () => HandleOKMethod());
return;
}
if (localDbConnectionUnity.State == ConnectionState.Closed)
localDbConnectionUnity.Open();
if (localDbConnectionProject1.State == ConnectionState.Closed)
localDbConnectionProject1.Open();
string query = "SELECT Password FROM Admins";
SqlCommand command = new SqlCommand(query, localDbConnectionUnity);
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
if (reader[0].ToString().Trim() == confirmation.Password.Trim())
{
SqlCommand commandToCreateProject = new SqlCommand("dbo.deleteProjectToDo", localDbConnectionProject1);
commandToCreateProject.CommandType = CommandType.StoredProcedure;
commandToCreateProject.Parameters.AddWithValue("@id", id);
commandToCreateProject.ExecuteNonQuery();
MessageBox.Show(rm.GetString("projectDeleted"), rm.GetString("system"),
MessageBoxButton.OK, MessageBoxImage.Information);
localDbConnectionUnity.Close();
localDbConnectionProject1.Close();
this.Close();
return;
}
}
localDbConnectionUnity.Close();
localDbConnectionProject1.Close();
myMessageQueue.Enqueue(rm.GetString("adminConfirmationNotValid", cultureInfo), "OK", () => HandleOKMethod());
}
private void deleteCompany()
{
if (confirmation.Password == "")
{
myMessageQueue.Enqueue(rm.GetString("confirmationIsEmpty"), rm.GetString("ok"), () => HandleOKMethod());
return;
}
if (localDbConnectionUnity.State == ConnectionState.Closed)
localDbConnectionUnity.Open();
if (localDbConnectionUnity2.State == ConnectionState.Closed)
localDbConnectionUnity2.Open();
string query = "SELECT Password FROM Admins";
SqlCommand command = new SqlCommand(query, localDbConnectionUnity);
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
if (reader[0].ToString().Trim() == confirmation.Password.Trim())
{
SqlCommand commandToCreateProject = new SqlCommand("dbo.deleteCompany", localDbConnectionUnity2);
commandToCreateProject.CommandType = CommandType.StoredProcedure;
commandToCreateProject.Parameters.AddWithValue("@name", nameReceived);
commandToCreateProject.ExecuteNonQuery();
MessageBox.Show(rm.GetString("companyInformationDeleted"), rm.GetString("system"),
MessageBoxButton.OK, MessageBoxImage.Information);
this.Close();
localDbConnectionUnity.Close();
localDbConnectionUnity2.Close();
return;
}
}
localDbConnectionUnity.Close();
localDbConnectionUnity2.Close();
myMessageQueue.Enqueue(rm.GetString("adminConfirmationNotValid", cultureInfo), "OK", () => HandleOKMethod());
}
private void deleteProduct()
{
if (confirmation.Password == "")
{
myMessageQueue.Enqueue(rm.GetString("confirmationIsEmpty"), rm.GetString("ok"), () => HandleOKMethod());
return;
}
if (localDbConnectionUnity.State == ConnectionState.Closed)
localDbConnectionUnity.Open();
if (localDbConnectionUnity2.State == ConnectionState.Closed)
localDbConnectionUnity2.Open();
string query = "SELECT Password FROM Admins";
SqlCommand command = new SqlCommand(query, localDbConnectionUnity);
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
if (reader[0].ToString().Trim() == confirmation.Password.Trim())
{
SqlCommand commandToCreateProject = new SqlCommand("dbo.deleteProduct", localDbConnectionUnity2);
commandToCreateProject.CommandType = CommandType.StoredProcedure;
commandToCreateProject.Parameters.AddWithValue("@id", nameReceived);
commandToCreateProject.ExecuteNonQuery();
MessageBox.Show(rm.GetString("productDeleted"), rm.GetString("system"),
MessageBoxButton.OK, MessageBoxImage.Information);
this.Close();
localDbConnectionUnity.Close();
localDbConnectionUnity2.Close();
return;
}
}
localDbConnectionUnity.Close();
localDbConnectionUnity2.Close();
myMessageQueue.Enqueue(rm.GetString("adminConfirmationNotValid", cultureInfo), "OK", () => HandleOKMethod());
}
}
}
| 40.679612 | 161 | 0.586754 | [
"MIT"
] | SymCors/VisualModbus | VisualUNITY/DiameterLaser/AdminConfirmation.xaml.cs | 8,382 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Collections.Generic;
using System.Linq;
namespace Microsoft.EntityFrameworkCore.Scaffolding
{
/// <summary>
/// Specifies which metadata to read from the database.
/// </summary>
public class DatabaseModelFactoryOptions
{
/// <summary>
/// Initializes a new instance of the <see cref="DatabaseModelFactoryOptions" /> class.
/// </summary>
/// <param name="tables"> A list of tables to include. Empty to include all tables. </param>
/// <param name="schemas"> A list of schemas to include. Empty to include all schemas. </param>
public DatabaseModelFactoryOptions(IEnumerable<string>? tables = null, IEnumerable<string>? schemas = null)
{
Tables = tables ?? Enumerable.Empty<string>();
Schemas = schemas ?? Enumerable.Empty<string>();
}
/// <summary>
/// Gets the list of tables to include. If empty, include all tables.
/// </summary>
public virtual IEnumerable<string> Tables { get; }
/// <summary>
/// Gets the list of schemas to include. If empty, include all schemas.
/// </summary>
public virtual IEnumerable<string> Schemas { get; }
}
}
| 38.583333 | 115 | 0.62851 | [
"MIT"
] | FelicePollano/efcore | src/EFCore.Relational/Scaffolding/DatabaseModelFactoryOptions.cs | 1,389 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using RimWorld;
using Verse;
using HarmonyLib;
using System.Reflection;
using System.Globalization;
using UnityEngine;
namespace HumanResources
{
public static class Extension_Research
{
public static SkillDef Bias = new SkillDef();
public static Dictionary<ResearchProjectDef, List<SkillDef>> SkillsByTech = new Dictionary<ResearchProjectDef, List<SkillDef>>();
public static Dictionary<ResearchProjectDef, List<Pawn>> AssignedHomework = new Dictionary<ResearchProjectDef, List<Pawn>>();
private const float MarketValueOffset = 200f;
private static FieldInfo ResearchPointsPerWorkTickInfo = AccessTools.Field(typeof(ResearchManager), "ResearchPointsPerWorkTick");
private static float DifficultyResearchSpeedFactor // 90% from vanilla on easy, 80% on medium, 75% on rough & 70% on hard.
{
get
{
float delta = 1 - Find.Storyteller.difficulty.researchSpeedFactor;
float adjusted = delta > 0 ? delta : delta / 2;
return 1 - (adjusted + 0.2f);
}
}
private static float ResearchPointsPerWorkTick // default is aprox. 10% down down from vanilla 0.00825f, neutralized with half available techs in library.
{
get
{
float baseValue = (float)ResearchPointsPerWorkTickInfo.GetValue(new ResearchManager());
return ModBaseHumanResources.ResearchSpeedTiedToDifficulty ? baseValue * DifficultyResearchSpeedFactor : baseValue * 0.9f;
}
}
private static float StudyPointsPerWorkTick // 100% on easy, 90% on medium, 85% on rough & 80% on hard.
{
get
{
float baseValue = 1.1f;
return ModBaseHumanResources.StudySpeedTiedToDifficulty? baseValue * DifficultyResearchSpeedFactor : baseValue;
}
}
private static bool animalsTag = false;
private static bool artisticTag = false;
private static bool constructionTag = false;
private static bool cookingTag = false;
private static bool craftingTag = false;
private static bool intellectualTag = false;
private static bool medicineTag = false;
private static bool meleeTag = false;
private static bool miningTag = false;
private static bool plantsTag = false;
private static bool shootingTag = false;
private static bool socialTag = false;
public static void CarefullyFinishProject(this ResearchProjectDef project, Thing place)
{
bool careful = !project.prerequisites.NullOrEmpty();
List<ResearchProjectDef> prerequisitesCopy = new List<ResearchProjectDef>();
if (careful)
{
prerequisitesCopy.AddRange(project.prerequisites);
project.prerequisites.Clear();
}
Find.ResearchManager.FinishProject(project);
if (careful) project.prerequisites.AddRange(prerequisitesCopy);
Messages.Message("MessageFiledTech".Translate(project.label), place, MessageTypeDefOf.TaskCompletion, true);
}
public static void CreateStuff(this ResearchProjectDef tech, ThingFilter filter, UnlockManager unlocked)
{
string name = "Tech_" + tech.defName;
ThingCategoryDef tCat = DefDatabase<ThingCategoryDef>.GetNamed(tech.techLevel.ToString());
string label = "KnowledgeLabel".Translate(tech.label);
ThingDef techStuff = new ThingDef
{
thingClass = typeof(ThingWithComps),
defName = name,
label = label,
description = tech.description,
category = ThingCategory.Item,
thingCategories = new List<ThingCategoryDef>() { tCat },
techLevel = tech.techLevel,
menuHidden = true,
stuffProps = new StuffProperties()
{
categories = new List<StuffCategoryDef>() { TechDefOf.Technic },
color = ResearchTree_Assets.ColorCompleted[tech.techLevel],
stuffAdjective = tech.LabelCap,
statOffsets = new List<StatModifier>()
{
new StatModifier
{
stat = StatDefOf.MarketValue,
value = MarketValueOffset
}
},
statFactors = new List<StatModifier>()
{
new StatModifier
{
stat = StatDefOf.WorkToMake,
value = StuffCostFactor(tech)
},
new StatModifier
{
stat = StatDefOf.MarketValue,
value = StuffMarketValueFactor(tech)
}
}
}
};
techStuff.ResolveReferences();
MethodInfo GiveShortHashInfo = AccessTools.Method(typeof(ShortHashGiver), "GiveShortHash");
GiveShortHashInfo.Invoke(tech, new object[] { techStuff, typeof(ThingDef) });
DefDatabase<ThingDef>.Add(techStuff);
filter.SetAllow(techStuff, true);
unlocked.stuffByTech.Add(tech, techStuff);
unlocked.techByStuff.Add(techStuff, tech);
}
public static void EjectTech(this ResearchProjectDef tech, Thing place)
{
FieldInfo progressInfo = AccessTools.Field(typeof(ResearchManager), "progress");
Dictionary<ResearchProjectDef, float> progress = (Dictionary<ResearchProjectDef, float>)progressInfo.GetValue(Find.ResearchManager);
progress[tech] = 0f;
Messages.Message("MessageEjectedTech".Translate(tech.label), place, MessageTypeDefOf.TaskCompletion, true);
}
public static float GetProgress(this ResearchProjectDef tech, Dictionary<ResearchProjectDef, float> expertise)
{
float result;
if (expertise != null && expertise.TryGetValue(tech, out result))
{
return result;
}
expertise.Add(tech, 0f);
return 0f;
}
public static void InferSkillBias(this ResearchProjectDef tech)
{
//Log.Warning("InferSkillBias Starting for "+tech.LabelCap);
//1. check what it unlocks
List<Pair<Def, string>> unlocks = ResearchTree_Patches.GetUnlockDefsAndDescs(tech);
IEnumerable<Def> defs = unlocks.Select(x => x.First).AsEnumerable();
IEnumerable<ThingDef> thingDefs = from d in defs
where d is ThingDef
select d as ThingDef;
IEnumerable<RecipeDef> recipeDefs = from d in defs
where d is RecipeDef
select d as RecipeDef;
IEnumerable<TerrainDef> terrainDefs = from d in defs
where d is TerrainDef
select d as TerrainDef;
//2. look for skills based on unlocked stuff
//a. checking by query on the research tree
//int matches = 0;
if (tech.Matches("scanner") > 0 | tech.Matches("terraform") > 0) { miningTag = true; /*matches++;*/ };
if (tech.Matches("sterile") > 0 | tech.Matches("medical") > 0 | tech.Matches("medicine") > 0 | tech.Matches("cryptosleep") > 0 | tech.Matches("prostheses") > 0 | tech.Matches("implant") > 0 | tech.Matches("organs") > 0 | tech.Matches("surgery") > 0) { medicineTag = true; /*matches++;*/ };
if (tech.Matches("irrigation") > 0 | tech.Matches("soil") > 0 | tech.Matches("hydroponic") > 0) { plantsTag = true; /*matches++;*/ };
if (tech.Matches("tool") > 0) { craftingTag = true; }
if (tech.Matches("manage") > 0) { intellectualTag = true; }
//b. checking by unlocked things
if (thingDefs.Count() > 0)
{
foreach (ThingDef t in thingDefs)
{
if (t != null) InvestigateThingDef(t);
}
}
//c. checking by unlocked recipes
if (recipeDefs.Count() > 0)
{
foreach (RecipeDef r in recipeDefs)
{
//Log.Message("trying recipe " + r.label);
foreach (ThingDef t in r.products.Select(x => x.thingDef))
{
InvestigateThingDef(t);
}
if (r.workSkill != null)
{
AccessTools.Field(typeof(Extension_Research), r.workSkill.defName.ToLower() + "Tag").SetValue(tech, true);
}
}
}
//d. checking by unlocked terrainDefs
if (terrainDefs.Count() > 0)
{
foreach (TerrainDef t in terrainDefs)
{
if (!constructionTag && t.designationCategory != null && t.designationCategory.label.Contains("floor")) constructionTag = true;
else if (!miningTag) miningTag = true;
}
}
//e. special cases
if (HarmonyPatches.RunSpecialCases)
{
if (tech.defName.StartsWith("ResearchProject_RotR"))
{
miningTag = true;
constructionTag = true;
}
if (tech.defName.StartsWith("BackupPower") || tech.defName.StartsWith("FluffyBreakdowns")) constructionTag = true;
}
//3. Figure out Bias.
//int ThingDefCount = thingDefs.Count();
//int RecipeDefCount = recipeDefs.Count();
//int TerrainDefCount = terrainDefs.Count();
List<SkillDef> relevantSkills = new List<SkillDef>();
if (shootingTag)
{
relevantSkills.Add(SkillDefOf.Shooting);
shootingTag = false;
}
if (meleeTag)
{
relevantSkills.Add(SkillDefOf.Melee);
meleeTag = false;
}
if (constructionTag)
{
relevantSkills.Add(SkillDefOf.Construction);
constructionTag = false;
}
if (miningTag)
{
relevantSkills.Add(SkillDefOf.Mining);
miningTag = false;
}
if (cookingTag)
{
relevantSkills.Add(SkillDefOf.Cooking);
cookingTag = false;
}
if (plantsTag)
{
relevantSkills.Add(SkillDefOf.Plants);
plantsTag = false;
}
if (animalsTag)
{
relevantSkills.Add(SkillDefOf.Animals);
animalsTag = false;
}
if (craftingTag)
{
relevantSkills.Add(SkillDefOf.Crafting);
craftingTag = false;
}
if (artisticTag)
{
relevantSkills.Add(SkillDefOf.Artistic);
artisticTag = false;
}
if (medicineTag)
{
relevantSkills.Add(SkillDefOf.Medicine);
medicineTag = false;
}
if (socialTag)
{
relevantSkills.Add(SkillDefOf.Social);
socialTag = false;
}
if (intellectualTag)
{
relevantSkills.Add(SkillDefOf.Intellectual);
intellectualTag = false;
}
if (!relevantSkills.NullOrEmpty())
{
SkillsByTech.Add(tech, relevantSkills);
//if (Prefs.LogVerbose) Log.Message("[HumanResources] " + tech + " associated to "+relevantSkills.ToStringSafeEnumerable()+".");
}
else
{
Log.Warning("[HumanResources] No relevant skills could be calculated for " + tech+". It won't be known by anyone.");
}
}
public static void InvestigateThingDef(ThingDef t)
{
if (t != null)
{
if (!shootingTag) try { shootingTag |= t.IsRangedWeapon | t.designationCategory == DesignationCategoryDefOf.Security; } catch { };
if (!meleeTag) try { meleeTag |= t.IsMeleeWeapon | t.designationCategory == DesignationCategoryDefOf.Security; } catch { };
if (!constructionTag) try { constructionTag |= t.BuildableByPlayer; } catch { };
if (!miningTag) try { miningTag |= t.IsShell; } catch { };
if (!cookingTag) try { cookingTag |= t.ingestible.IsMeal | t.building.isMealSource; } catch { };
if (!plantsTag) try { plantsTag |= t.plant != null; } catch { };
if (!craftingTag) try { craftingTag |= t.IsApparel | t.IsWeapon; } catch { };
if (!artisticTag) try { artisticTag |= t.IsArt | t.IsWithinCategory(ThingCategoryDefOf.BuildingsArt); } catch { };
if (!medicineTag) try { medicineTag |= t.IsMedicine | t.IsDrug; } catch { };
}
}
public static void Learned(this ResearchProjectDef tech, float amount, float recipeCost, Pawn researcher, bool research = false)
{
float total = research ? tech.baseCost : recipeCost * tech.StuffCostFactor();
amount *= research ? ResearchPointsPerWorkTick : StudyPointsPerWorkTick;
Dictionary<ResearchProjectDef, float> expertise = researcher.TryGetComp<CompKnowledge>().expertise;
foreach (ResearchProjectDef ancestor in expertise.Keys)
{
if (!tech.prerequisites.NullOrEmpty() && tech.prerequisites.Contains(ancestor))
{
amount *= 2;
break;
}
}
if (researcher != null && researcher.Faction != null)
{
amount /= tech.CostFactor(researcher.Faction.def.techLevel);
}
if (DebugSettings.fastResearch)
{
amount *= 500f;
}
if (researcher != null && research)
{
researcher.records.AddTo(RecordDefOf.ResearchPointsResearched, amount);
}
float num = tech.GetProgress(expertise);
num += amount / total;
//Log.Warning(tech + " research performed by " + researcher + ": " + amount + "/" + total);
expertise[tech] = num;
}
public static void LearnInstantly(this ResearchProjectDef tech, Pawn researcher)
{
Dictionary<ResearchProjectDef, float> expertise = researcher.TryGetComp<CompKnowledge>().expertise;
if (expertise != null)
{
if (!expertise.ContainsKey(tech)) expertise.Add(tech, 1f);
else expertise[tech] = 1f;
Messages.Message("MessageStudyComplete".Translate(researcher, tech.LabelCap), researcher, MessageTypeDefOf.TaskCompletion, true);
}
else Log.Warning("[HumanResources] " + researcher + " tried to learn a technology without being able to.");
}
public static int Matches(this ResearchProjectDef tech, string query)
{
var culture = CultureInfo.CurrentUICulture;
query = query.ToLower(culture);
if (tech.LabelCap.RawText.ToLower(culture).Contains(query))
return 1;
if (ResearchTree_Patches.GetUnlockDefsAndDescs(tech).Any(unlock => unlock.First.LabelCap.RawText.ToLower(culture).Contains(query)))
return 2;
if (tech.description.ToLower(culture).Contains(query))
return 3;
return 0;
}
public static float StuffCostFactor(this ResearchProjectDef tech)
{
return (float)Math.Round(Math.Pow(tech.baseCost, (1.0 / 2.0)), 1);
}
public static List<ThingDef> UnlockedPlants(this ResearchProjectDef tech)
{
List<ThingDef> result = new List<ThingDef>();
foreach (ThingDef plant in tech.GetPlantsUnlocked()) //Cacau shouldn't be a Tree!
{
result.Add(plant);
}
return result;
}
public static List<ThingDef> UnlockedWeapons(this ResearchProjectDef tech)
{
List<ThingDef> result = new List<ThingDef>();
foreach (RecipeDef r in tech.GetRecipesUnlocked().Where(x => !x.products.NullOrEmpty()))
{
foreach (ThingDef weapon in r.products.Select(x => x.thingDef).Where(x => x.IsWeapon && (x.weaponTags.NullOrEmpty() || !x.weaponTags.Any(t => t.Contains("Basic"))) && !(x.defName.Contains("Tool") || x.defName.Contains("tool"))))
{
result.Add(weapon);
}
}
foreach (ThingDef weapon in tech.GetThingsUnlocked().Where(x => x.building != null && x.building.turretGunDef != null).Select(x => x.building.turretGunDef))
{
result.Add(weapon);
}
return result;
}
//higher tech level
private static float StuffMarketValueFactor(this ResearchProjectDef tech)
{
return (float)Math.Round(Math.Pow(tech.baseCost, 1.0 / 3.0) / 10, 1);
}
private static IEnumerable<Pawn> currentPawns => HarmonyPatches.PrisonLabor ? PawnsFinder.AllMapsCaravansAndTravelingTransportPods_Alive.Where(x => x.CanContribute() && x.TryGetComp<CompKnowledge>() != null) : PawnsFinder.AllMapsCaravansAndTravelingTransportPods_Alive_Colonists.Where(x => x.TryGetComp<CompKnowledge>() != null);
public static bool IsKnownBy(this ResearchProjectDef tech, Pawn pawn)
{
CompKnowledge techComp = pawn.TryGetComp<CompKnowledge>();
var expertise = techComp.expertise;
if (expertise != null) return expertise.ContainsKey(tech) && techComp.expertise[tech] >= 1f;
return false;
}
public static bool RequisitesKnownBy(this ResearchProjectDef tech, Pawn pawn)
{
CompKnowledge techComp = pawn.TryGetComp<CompKnowledge>();
var expertise = techComp.expertise;
if (expertise != null)
{
//1. test if any descendent is known
if (expertise.Where(x => x.Value >= 1 && !x.Key.prerequisites.NullOrEmpty() && x.Key.prerequisites.Contains(tech)).Any()) return true;
//2. test if all ancestors are known
if (!tech.prerequisites.NullOrEmpty()) return tech.prerequisites.All(x => x.IsKnownBy(pawn));
}
//3. test if there are any ancestors
return tech.prerequisites.NullOrEmpty();
}
private static IEnumerable<Pawn> SortedPawns(this ResearchProjectDef tech)
{
if (tech.IsFinished) return currentPawns.Where(x => !tech.IsKnownBy(x)).OrderBy(x => x.workSettings.WorkIsActive(TechDefOf.HR_Learn)).ThenByDescending(x => x.skills.GetSkill(SkillDefOf.Intellectual).Level);
else return currentPawns.OrderBy(x => tech.IsKnownBy(x))/*.ThenBy(x => x.workSettings.WorkIsActive(WorkTypeDefOf.Research)).ThenByDescending(x => x.skills.GetSkill(SkillDefOf.Intellectual).Level)*/;
}
private static IEnumerable<Widgets.DropdownMenuElement<Pawn>> GeneratePawnRestrictionOptions(this ResearchProjectDef tech, bool completed)
{
SkillDef skill = SkillDefOf.Intellectual;
using (IEnumerator<Pawn> enumerator = tech.SortedPawns().GetEnumerator())
{
while (enumerator.MoveNext())
{
Pawn pawn = enumerator.Current;
CompKnowledge techComp = pawn.TryGetComp<CompKnowledge>();
bool known = tech.IsKnownBy(pawn);
WorkTypeDef workGiver = (completed || known) ? TechDefOf.HR_Learn : WorkTypeDefOf.Research;
string header = known ? TechStrings.headerWrite : completed ? TechStrings.headerRead : TechStrings.headerResearch;
if (techComp != null && (techComp.homework.NullOrEmpty() || !techComp.homework.Contains(tech)))
{
if (pawn.WorkTypeIsDisabled(workGiver))
{
yield return new Widgets.DropdownMenuElement<Pawn>
{
option = new FloatMenuOption(string.Format("{0}: {1} ({2})", header, pawn.LabelShortCap, "WillNever".Translate(workGiver.verb)), null, MenuOptionPriority.DisabledOption, null, null, 0f, null, null),
payload = pawn
};
}
else if (!pawn.workSettings.WorkIsActive(workGiver))
{
yield return new Widgets.DropdownMenuElement<Pawn>
{
option = new FloatMenuOption(string.Format("{0}: {1} ({2})", header, pawn.LabelShortCap, "NotAssigned".Translate()), delegate ()
{
techComp.AssignBranch(tech);
}, MenuOptionPriority.VeryLow, null, null, 0f, null, null),
payload = pawn
};
}
else
{
yield return new Widgets.DropdownMenuElement<Pawn>
{
option = new FloatMenuOption(string.Format("{0}: {1} ({2} {3})", new object[]
{
header,
pawn.LabelShortCap,
pawn.skills.GetSkill(skill).Level,
skill.label
}),
delegate () { techComp.AssignBranch(tech); },
MenuOptionPriority.Default, null, null, 0f, null, null),
payload = pawn
};
}
}
}
}
yield break;
}
public static void SelectMenu(this ResearchProjectDef tech, bool completed)
{
Find.WindowStack.FloatMenu?.Close(false);
List<FloatMenuOption> options = (from opt in GeneratePawnRestrictionOptions(tech, completed)
select opt.option).ToList<FloatMenuOption>();
if (!options.Any()) options.Add(new FloatMenuOption("NoOptionsFound".Translate(), null));
Find.WindowStack.Add(new FloatMenu(options));
}
public static void DrawAssignments(this ResearchProjectDef tech, Rect rect)
{
float height = rect.height;
float frameOffset = height / 4;
float startPos = rect.x - frameOffset; //rect.xMax - height/2;
Vector2 size = new Vector2(height, height);
using (IEnumerator<Pawn> enumerator = currentPawns.Where(p => HasBeenAssigned(p,tech)).GetEnumerator())
{
while (enumerator.MoveNext())
{
Vector2 position = new Vector2(startPos, rect.y + (height / 3));
Rect box = new Rect(position, size);
Pawn pawn = enumerator.Current;
GUI.DrawTexture(box, PortraitsCache.Get(pawn, size, default, 1.2f));
Rect clickBox = new Rect(position.x + frameOffset, position.y, size.x - (2 * frameOffset), size.y);
if (Widgets.ButtonInvisible(clickBox)) pawn.TryGetComp<CompKnowledge>().CancelBranch(tech);
TooltipHandler.TipRegion(clickBox, new Func<string>(() => AssignmentStatus(pawn, tech)), tech.GetHashCode());
startPos += height / 2;
}
}
}
private static Func<Pawn, ResearchProjectDef, string> AssignmentStatus = (pawn, tech) =>
{
string status = "error";
CompKnowledge techComp = pawn.TryGetComp<CompKnowledge>();
if (techComp != null && !techComp.homework.NullOrEmpty())
{
if (tech.IsKnownBy(pawn)) status = "AssignedToDocument".Translate(pawn);
else status = tech.IsFinished ? "AssignedToStudy".Translate(pawn) : "AssignedToResearch".Translate(pawn);
}
return status + " (" + "ClickToRemove".Translate() + ")";
};
private static Func<Pawn, ResearchProjectDef, bool> HasBeenAssigned = (pawn, tech) =>
{
CompKnowledge techComp = pawn.TryGetComp<CompKnowledge>();
if (techComp != null && !techComp.homework.NullOrEmpty())
{
return techComp.homework.Contains(tech);
}
return false;
};
}
}
| 46.150538 | 337 | 0.540657 | [
"MIT"
] | MinerSebas/HumanResources | Source/Extensions/Extension_Research.cs | 25,754 | 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("ExtensionMethod")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("ExtensionMethod")]
[assembly: AssemblyCopyright("Copyright © 2013")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("d852e5fb-8c2d-4808-a319-1eb9c923d479")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 37.918919 | 84 | 0.746258 | [
"MIT"
] | DiogoBarbosaSilvaSousa/visual-csharp-2013-passo-a-passo | Exemplos/Chapter 12/Windows 7/ExtensionMethod - Complete/ExtensionMethod/Properties/AssemblyInfo.cs | 1,406 | C# |
using UnityEngine;
public class AutoLODMeshUtility
{
public static void Smooth2FlatShading(Mesh mesh)
{
Vector3[] oldVerts = mesh.vertices;
int[] triangles = mesh.triangles;
Vector3[] vertices = new Vector3[triangles.Length];
Vector2[] oldUv = mesh.uv;
bool hasUv = oldUv.Length != 0;
Vector2[] oldUv2 = mesh.uv2;
bool hasUv2 = oldUv2.Length != 0;
Vector2[] oldUv3 = mesh.uv3;
bool hasUv3 = oldUv3.Length != 0;
Vector2[] oldUv4 = mesh.uv4;
bool hasUv4 = oldUv4.Length != 0;
Color[] oldColors = mesh.colors;
bool hasColors = oldColors.Length != 0;
Vector2[] uv = new Vector2[vertices.Length];
Vector2[] uv2 = new Vector2[vertices.Length];
Vector2[] uv3 = new Vector2[vertices.Length];
Vector2[] uv4 = new Vector2[vertices.Length];
Color[] colors = new Color[vertices.Length];
BoneWeight[] oldBoneWeights = mesh.boneWeights;
bool hasBones = oldBoneWeights.Length != 0;
BoneWeight[] boneWeights = new BoneWeight[vertices.Length];
for (int i = 0; i < triangles.Length; i++)
{
vertices[i] = oldVerts[triangles[i]];
if(hasUv)
uv[i] = oldUv[triangles[i]];
if (hasUv2)
uv2[i] = oldUv2[triangles[i]];
if (hasUv3)
uv3[i] = oldUv3[triangles[i]];
if (hasUv4)
uv4[i] = oldUv4[triangles[i]];
if (hasColors)
colors[i] = oldColors[triangles[i]];
if(hasBones)
boneWeights[i] = oldBoneWeights[triangles[i]];
triangles[i] = i;
}
if (triangles.Length > 65535)
mesh.indexFormat = UnityEngine.Rendering.IndexFormat.UInt32;
mesh.vertices = vertices;
mesh.triangles = triangles;
if (hasUv)
mesh.uv = uv;
if (hasUv2)
mesh.uv2 = uv2;
if (hasUv3)
mesh.uv3 = uv3;
if (hasUv4)
mesh.uv4 = uv4;
if (hasColors)
mesh.colors = colors;
if (hasBones)
mesh.boneWeights = boneWeights;
mesh.RecalculateNormals();
}
}
| 34.507463 | 73 | 0.524654 | [
"MIT"
] | TastSong/CrazyCar | CrazyCar/Assets/Plugins/AutoLOD/Scripts/Tools/MeshUtility.cs | 2,312 | C# |
using System.Security.Claims;
using System.Web;
using System.Web.Mvc;
namespace Psy.Owin.Security.Keycloak.Samples.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
[Authorize]
public ActionResult About()
{
ViewBag.Message = "Your application description page.";
var userPrinciple = User as ClaimsPrincipal;
return View(userPrinciple);
}
public void Logout()
{
Request.GetOwinContext().Authentication.SignOut();
}
public ActionResult Contact()
{
ViewBag.Message = "Your contact page.";
return View();
}
}
} | 21.333333 | 67 | 0.5625 | [
"MIT"
] | pasay/Psy.Owin.Security.Keycloak | samples/Psy.Owin.Security.Keycloak.Samples/Controllers/HomeController.cs | 770 | C# |
using System;
using System.Collections.Generic;
using BattleTech;
using Harmony;
using Localize;
namespace MechEngineer.Features.ArmorStructureRatio.Patches
{
[HarmonyPatch(typeof(MechValidationRules), nameof(MechValidationRules.ValidateMechStructure))]
public static class MechValidationRules_ValidateMechStructure_Patch
{
public static void Postfix(MechDef mechDef, ref Dictionary<MechValidationType, List<Text>> errorMessages)
{
try
{
ArmorStructureRatioFeature.ValidateMechArmorStructureRatio(mechDef, errorMessages);
}
catch (Exception e)
{
Control.mod.Logger.LogError(e);
}
}
}
}
| 29.28 | 113 | 0.670765 | [
"Unlicense"
] | 17783/MechEngineer | source/Features/ArmorStructureRatio/Patches/MechValidationRules_ValidateMechStructure_Patch.cs | 734 | C# |
using System;
using NetOffice;
namespace NetOffice.ExcelApi.Enums
{
/// <summary>
/// SupportByVersion Excel 14, 15, 16
/// </summary>
///<remarks> MSDN Online Documentation: http://msdn.microsoft.com/en-us/en-us/library/office/ff196124.aspx </remarks>
[SupportByVersionAttribute("Excel", 14,15,16)]
[EntityTypeAttribute(EntityType.IsEnum)]
public enum XlDataBarFillType
{
/// <summary>
/// SupportByVersion Excel 14, 15, 16
/// </summary>
/// <remarks>0</remarks>
[SupportByVersionAttribute("Excel", 14,15,16)]
xlDataBarFillSolid = 0,
/// <summary>
/// SupportByVersion Excel 14, 15, 16
/// </summary>
/// <remarks>1</remarks>
[SupportByVersionAttribute("Excel", 14,15,16)]
xlDataBarFillGradient = 1
}
} | 27.925926 | 119 | 0.676393 | [
"MIT"
] | Engineerumair/NetOffice | Source/Excel/Enums/XlDataBarFillType.cs | 754 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable enable
using System.ComponentModel;
namespace Microsoft.CodeAnalysis.CSharp.Syntax
{
public sealed partial class ArgumentSyntax
{
/// <summary>
/// Pre C# 7.2 back-compat overload, which simply calls the replacement property <see cref="RefKindKeyword"/>.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never)]
public SyntaxToken RefOrOutKeyword
{
get => this.RefKindKeyword;
}
/// <summary>
/// Pre C# 7.2 back-compat overload, which simply calls the replacement method <see cref="Update"/>.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never)]
public ArgumentSyntax WithRefOrOutKeyword(SyntaxToken refOrOutKeyword)
{
return this.Update(this.NameColon, refOrOutKeyword, this.Expression);
}
}
}
| 33.5625 | 118 | 0.665736 | [
"MIT"
] | 06needhamt/roslyn | src/Compilers/CSharp/Portable/Syntax/ArgumentSyntax.cs | 1,076 | C# |
// QuickGraph Library
//
// Copyright (c) 2004 Jonathan de Halleux
//
// This software is provided 'as-is', without any express or implied warranty.
//
// In no event will the authors be held liable for any damages arising from
// the use of this software.
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented;
// you must not claim that you wrote the original software.
// If you use this software in a product, an acknowledgment in the product
// documentation would be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such, and must
// not be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source
// distribution.
//
// QuickGraph Library HomePage: http://www.mbunit.com
// Author: Jonathan de Halleux
namespace QuickGraph.Algorithms
{
using System;
using System.Collections;
using QuickGraph.Concepts;
using QuickGraph.Concepts.Algorithms;
using QuickGraph.Concepts.Traversals;
using QuickGraph.Algorithms.Search;
using QuickGraph.Exceptions;
/// <summary>
/// Topological sort of the graph.
/// </summary>
/// <remarks>
/// <para>
/// The topological sort algorithm creates a linear ordering of the
/// vertices such that if edge (u,v) appears in the graph, then v comes
/// before u in the ordering.
/// </para>
/// <para>
/// The graph must be a directed acyclic graph
/// (DAG). The implementation consists mainly of a call to
/// <see cref="Search.DepthFirstSearchAlgorithm"/>.
/// </para>
/// <para>This algorithm is directly inspired from the
/// BoostGraphLibrary implementation.
/// </para>
/// </remarks>
public class TopologicalSortAlgorithm
{
private IVertexListGraph m_VisitedGraph;
private IList m_Vertices;
/// <summary>
/// Builds a new sorter
/// </summary>
/// <param name="g">Graph to sort</param>
public TopologicalSortAlgorithm(IVertexListGraph g)
{
if (g==null)
throw new ArgumentNullException("g");
m_VisitedGraph = g;
m_Vertices = new ArrayList();
}
/// <summary>
/// Builds a new sorter
/// </summary>
/// <param name="g">Graph to sort</param>
/// <param name="vertices">vertices list</param>
public TopologicalSortAlgorithm(IVertexListGraph g, IList vertices)
{
if (g==null)
throw new ArgumentNullException("g");
if (vertices == null)
throw new ArgumentNullException("vertices");
m_VisitedGraph = g;
m_Vertices = vertices;
}
/// <summary>
/// Visited vertex list
/// </summary>
public IVertexListGraph VisitedGraph
{
get
{
return m_VisitedGraph;
}
}
/// <summary>
/// Sorted vertices list
/// </summary>
public IList SortedVertices
{
get
{
return m_Vertices;
}
}
/// <summary>
/// Delegate event that detects cycle. <seealso cref="EdgeEventHandler"/>.
/// </summary>
/// <param name="sender">DepthFirstSearch algorithm</param>
/// <param name="args">Edge that produced the error</param>
/// <exception cref="Exception">Will always throw an exception.</exception>
public void BackEdge(Object sender, EdgeEventArgs args)
{
throw new NonAcyclicGraphException();
}
/// <summary>
/// Delegate that adds the vertex to the vertex list. <seealso cref="VertexEventHandler"/>.
/// </summary>
/// <param name="sender"></param>
/// <param name="args"></param>
public void FinishVertex(Object sender, VertexEventArgs args)
{
m_Vertices.Insert(0,args.Vertex);
}
/// <summary>
/// Computes the topological sort and stores it in the list.
/// </summary>
public void Compute()
{
Compute(null);
}
/// <summary>
/// Computes the topological sort and stores it in the list.
/// </summary>
/// <param name="vertices">Vertex list that will contain the results</param>
public void Compute(IList vertices)
{
if (vertices != null)
m_Vertices = vertices;
DepthFirstSearchAlgorithm dfs = new DepthFirstSearchAlgorithm(VisitedGraph);
dfs.BackEdge += new EdgeEventHandler(this.BackEdge);
dfs.FinishVertex += new VertexEventHandler(this.FinishVertex);
m_Vertices.Clear();
dfs.Compute();
}
}
}
| 28.4 | 94 | 0.662852 | [
"ECL-2.0",
"Apache-2.0"
] | Gallio/mbunit-v2 | src/quickgraph/QuickGraph.Algorithms/TopologicalSortAlgorithm.cs | 4,544 | C# |
// Copyright (c) 2017 Jan Pluskal, Vit Janecek
//
//Licensed under the Apache License, Version 2.0 (the "License");
//you may not use this file except in compliance with the License.
//You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
//Unless required by applicable law or agreed to in writing, software
//distributed under the License is distributed on an "AS IS" BASIS,
//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//See the License for the specific language governing permissions and
//limitations under the License.
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Text.RegularExpressions;
using Netfox.Snoopers.SnooperHTTP.Models;
namespace Netfox.Snoopers.SnooperMAFF.Models.Objects
{
/// <summary>
/// Derived class from Text class desribes all parent objects of each archive.
/// </summary>
/// <seealso cref="TextObject" />
[ComplexType]
public class ParentObject : TextObject
{
private readonly string _sCharSet;
private readonly string _sTitle;
/// <summary>
/// Creates a new object that is a copy of the current instance.
/// </summary>
/// <returns>
/// A new object that is a copy of this instance.
/// </returns>
public override BaseObject Clone()
{
return new ParentObject(this.OriginalUrl, this.PathToFileName, this.FileName, this.FileExtension, this.ContentType, this.RequestMessage, this.CookieInformation, this._sCharSet);
}
/// <summary>
/// Initializes a new instance of the <see cref="ParentObject"/> class.
/// </summary>
/// <param name="sOrigUrl">The original URL.</param>
/// <param name="sPathToFile">The path to file.</param>
/// <param name="sFileName">Name of the file.</param>
/// <param name="sFileExtension">The file extension.</param>
/// <param name="sContentType">Type of the content.</param>
/// <param name="oRequestMsg">The request message.</param>
/// <param name="listCookieInformation">The list cookie information.</param>
/// <param name="sCharSet">The character set.</param>
public ParentObject(
string sOrigUrl,
string sPathToFile,
string sFileName,
string sFileExtension,
string sContentType,
HTTPMsg oRequestMsg,
List<string> listCookieInformation,
string sCharSet) : base(sOrigUrl, sPathToFile, sFileName, sFileExtension, sContentType, oRequestMsg, listCookieInformation)
{
this._sCharSet = sCharSet;
var regMatch = Regex.Match(this.StringContent, @"<title>(.*)</title>");
if (regMatch.Success)
{
this._sTitle = regMatch.Groups[1].ToString();
}
}
/// <summary>
/// Gets the character set of parent object (for whole archive).
/// </summary>
/// <returns>Return object character set</returns>
public string GetCharSet() { return this._sCharSet; }
/// <summary>
/// Gets the title.
/// </summary>
/// <returns>Return web page title</returns>
public string GetTitle() { return this._sTitle; }
/// <summary>
/// Gets the references amount of parent objects.
/// </summary>
/// <returns>Return number of references ammount</returns>
public int GetReferencesAmount() { return this.ListOfReferences.Count; }
/// <summary>
/// Processes and replace the references obtained from list of references by special new referenes with index_files folder.
/// </summary>
public override void ProcessReferences()
{
foreach (var oReference in this.ListOfReferences)
{
//Replace References in String Content
this.Replace(oReference.Item1, "index_files/" + oReference.Item2);
//Fill NewReferenceList For Export
this.ListOfNewReferences.Add("index_files/" + oReference.Item2);
}
}
}
}
| 39.579439 | 189 | 0.626919 | [
"Apache-2.0"
] | pokornysimon/NetfoxDetective | NetfoxCore/Framework/Snoopers/SnooperMAFF/Models/Objects/ParentObject.cs | 4,237 | C# |
using BibliotecaAPI.Data.Mapeamentos;
using BibliotecaAPI.Models;
using Microsoft.EntityFrameworkCore;
namespace BibliotecaAPI.Data
{
public class BibliotecaContexto : DbContext
{
public BibliotecaContexto(DbContextOptions<BibliotecaContexto> options) : base(options)
{
}
public DbSet<Editora> Editoras { get; set; }
public DbSet<Livro> Livros { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.ApplyConfiguration(new EditoraMap());
modelBuilder.ApplyConfiguration(new LivroMap());
}
}
}
| 26.5 | 95 | 0.68239 | [
"MIT"
] | DeivideSilva/Asp.NetCore | ApiBiblioteca/BibliotecaAPI/Data/BibliotecaContexto.cs | 638 | C# |
using EnvDTE;
using Microsoft.VisualStudio.Shell;
using System;
using System.IO;
using System.Runtime.CompilerServices;
namespace ActivityWatchVS.Listeners
{
internal sealed class DTE2EventListener : IDisposable
{
#region Fields
private BuildEvents _buildEv;
private DocumentEvents _documentEv;
private AWPackage _package;
private SelectionEvents _selectionEv;
private SolutionEvents _solutionEv;
private WindowEvents _windowEv;
#endregion Fields
#region Constructors
public DTE2EventListener(AWPackage package)
{
ThreadHelper.ThrowIfNotOnUIThread();
this._package = package;
var dte2Events = this._package.DTE2Service.Events;
_buildEv = dte2Events.BuildEvents;
_documentEv = dte2Events.DocumentEvents;
_selectionEv = dte2Events.SelectionEvents;
_solutionEv = dte2Events.SolutionEvents;
_windowEv = dte2Events.WindowEvents;
_buildEv.OnBuildBegin += buildEvents_OnBuildBegin;
_buildEv.OnBuildDone += buildEvents_OnBuildDone;
_documentEv.DocumentOpened += documentEv_DocumentOpened;
_documentEv.DocumentSaved += documentEv_DocumentSaved;
_documentEv.DocumentClosing += documentEv_DocumentClosing;
_selectionEv.OnChange += selectionEv_OnChange;
_solutionEv.Opened += solutionEvents_Opened;
_solutionEv.BeforeClosing += solutionEv_BeforeClosing;
_windowEv.WindowActivated += windowEv_WindowActivated;
_windowEv.WindowClosing += windowEv_WindowClosing;
_windowEv.WindowCreated += windowEv_WindowCreated;
_windowEv.WindowMoved += windowEv_WindowMoved;
}
private DTE2EventListener()
{ }
private void windowEv_WindowActivated(Window GotFocus, Window LostFocus)
{
produceEvent();
}
private void windowEv_WindowClosing(Window Window)
{
produceEvent();
}
private void windowEv_WindowCreated(Window Window)
{
produceEvent();
}
private void windowEv_WindowMoved(Window Window, int Top, int Left, int Width, int Height)
{
produceEvent();
}
#endregion Constructors
#region Methods
public void textEditorEvents_LineChanged(TextPoint StartPoint, TextPoint EndPoint, int Hint)
{
produceEvent();
}
private void buildEvents_OnBuildBegin(vsBuildScope Scope, vsBuildAction Action)
{
produceEvent();
}
private void buildEvents_OnBuildDone(vsBuildScope Scope, vsBuildAction Action)
{
produceEvent();
}
private void documentEv_DocumentClosing(Document Document)
{
produceEvent();
}
private void documentEv_DocumentOpened(Document Document)
{
produceEvent();
}
private void documentEv_DocumentSaved(Document Document)
{
produceEvent();
}
private void produceEvent([CallerMemberName] string caller = null)
{
if (!_package.IsReady || !_package.AwOptions.IsEnabled)
{
return;
}
try
{
string solution = string.Empty;
string activeDocument = string.Empty;
try
{
solution = _package.DTE2Service.Solution?.FullName;
activeDocument = _package.DTE2Service.ActiveDocument?.FullName;
}
catch (ArgumentException argEx)
{
// ignore this, on some events we are not able to get an active document.
}
if (!string.IsNullOrWhiteSpace(solution) && !string.IsNullOrWhiteSpace(activeDocument))
{
string solutionDir = Path.GetDirectoryName(solution);
if (activeDocument.StartsWith(solutionDir, StringComparison.Ordinal))
{
activeDocument = "." + activeDocument.Substring(solutionDir.Length);
}
}
string language = null;
if (!string.IsNullOrWhiteSpace(activeDocument))
{
// we keep that for later, for now I find it more useful to use the file extension as language
//language = _package.DTE2Service.ActiveDocument?.Language;
//if (string.IsNullOrWhiteSpace(language))
language = Path.GetExtension(activeDocument).TrimStart(".".ToCharArray());
}
var data = new ActivityWatch.API.V1.EventDataAppEditorActivity()
{
Project = string.IsNullOrWhiteSpace(solution) ? "-" : solution,
File = string.IsNullOrWhiteSpace(activeDocument) ? "-" : activeDocument,
Language = string.IsNullOrWhiteSpace(language) ? "-" : language,
};
if (_package.LogService.LogLevel == Services.LogService.EErrorLevel.Debug)
{
data.Caller = caller;
}
var awEvent = new ActivityWatch.API.V1.Event()
{
Timestamp = DateTime.UtcNow,
Duration = 0,
Data = data
};
_package.EventService.AddEvent(awEvent);
}
catch (Exception ex)
{
_package.LogService.Log(ex, $"Caller: {caller}");
}
}
private void selectionEv_OnChange()
{
produceEvent();
}
private void solutionEv_BeforeClosing()
{
produceEvent();
}
private void solutionEvents_Opened()
{
produceEvent();
}
#region IDisposable
public void Dispose()
{
ThreadHelper.ThrowIfNotOnUIThread();
_buildEv.OnBuildBegin -= buildEvents_OnBuildBegin;
_buildEv.OnBuildDone -= buildEvents_OnBuildDone;
_documentEv.DocumentOpened -= documentEv_DocumentOpened;
_documentEv.DocumentSaved -= documentEv_DocumentSaved;
_documentEv.DocumentClosing -= documentEv_DocumentClosing;
_selectionEv.OnChange -= selectionEv_OnChange;
_solutionEv.Opened -= solutionEvents_Opened;
_solutionEv.BeforeClosing -= solutionEv_BeforeClosing;
_windowEv.WindowActivated -= windowEv_WindowActivated;
_windowEv.WindowClosing -= windowEv_WindowClosing;
_windowEv.WindowCreated -= windowEv_WindowCreated;
_windowEv.WindowMoved -= windowEv_WindowMoved;
}
#endregion IDisposable
#endregion Methods
}
} | 33.450237 | 114 | 0.579201 | [
"MPL-2.0"
] | DarkOoze/ActivityWatchVS | ActivityWatchVS/Listeners/DTE2EventListener.cs | 7,060 | C# |
using System.Collections.Generic;
using Essensoft.Paylink.Alipay.Response;
namespace Essensoft.Paylink.Alipay.Request
{
/// <summary>
/// koubei.shop.mall.audit.query
/// </summary>
public class KoubeiShopMallAuditQueryRequest : IAlipayRequest<KoubeiShopMallAuditQueryResponse>
{
/// <summary>
/// 商圈首页地址变更工单审核状态查询
/// </summary>
public string BizContent { get; set; }
#region IAlipayRequest Members
private bool needEncrypt = false;
private string apiVersion = "1.0";
private string terminalType;
private string terminalInfo;
private string prodCode;
private string notifyUrl;
private string returnUrl;
private AlipayObject bizModel;
private Dictionary<string, string> udfParams; //add user-defined text parameters
public void SetNeedEncrypt(bool needEncrypt)
{
this.needEncrypt = needEncrypt;
}
public bool GetNeedEncrypt()
{
return needEncrypt;
}
public void SetNotifyUrl(string notifyUrl)
{
this.notifyUrl = notifyUrl;
}
public string GetNotifyUrl()
{
return notifyUrl;
}
public void SetReturnUrl(string returnUrl)
{
this.returnUrl = returnUrl;
}
public string GetReturnUrl()
{
return returnUrl;
}
public void SetTerminalType(string terminalType)
{
this.terminalType = terminalType;
}
public string GetTerminalType()
{
return terminalType;
}
public void SetTerminalInfo(string terminalInfo)
{
this.terminalInfo = terminalInfo;
}
public string GetTerminalInfo()
{
return terminalInfo;
}
public void SetProdCode(string prodCode)
{
this.prodCode = prodCode;
}
public string GetProdCode()
{
return prodCode;
}
public string GetApiName()
{
return "koubei.shop.mall.audit.query";
}
public void SetApiVersion(string apiVersion)
{
this.apiVersion = apiVersion;
}
public string GetApiVersion()
{
return apiVersion;
}
public void PutOtherTextParam(string key, string value)
{
if (udfParams == null)
{
udfParams = new Dictionary<string, string>();
}
udfParams.Add(key, value);
}
public IDictionary<string, string> GetParameters()
{
var parameters = new AlipayDictionary
{
{ "biz_content", BizContent }
};
if (udfParams != null)
{
parameters.AddAll(udfParams);
}
return parameters;
}
public AlipayObject GetBizModel()
{
return bizModel;
}
public void SetBizModel(AlipayObject bizModel)
{
this.bizModel = bizModel;
}
#endregion
}
}
| 23.413043 | 99 | 0.536985 | [
"MIT"
] | Frunck8206/payment | src/Essensoft.Paylink.Alipay/Request/KoubeiShopMallAuditQueryRequest.cs | 3,265 | C# |
using Microsoft.Extensions.Options;
using Senparc.CO2NET;
using Senparc.CO2NET.Extensions;
using Senparc.Core.Cache;
using Senparc.Core.Models.WeixinTemplate;
using Senparc.Log;
using Senparc.Utility;
using Senparc.Weixin;
using Senparc.Weixin.Entities;
using Senparc.Weixin.MP.AdvancedAPIs;
using Senparc.Weixin.MP.AdvancedAPIs.OAuth;
using Senparc.Weixin.MP.AdvancedAPIs.TemplateMessage;
using Senparc.Weixin.MP.Containers;
using System;
using System.IO;
using System.Linq;
namespace Senparc.Service
{
public class WeixinService /*: IWeixinService*/
{
public string ReplaceWeixinFace(string content)
{
var weixinFaceCahce = SenparcDI.GetService<WeixinFaceCache>();
foreach (var keyValuePair in weixinFaceCahce.Data)
{
var image = $"<img src=\"/Content/WeixinFace/{keyValuePair.Value}.png\" title=\"{keyValuePair.Value.ToString()}\" />";
//表情中有<>之类符号,需要考虑到进来的content已经HtmlEncode的情况
var encodedCode = keyValuePair.Key.HtmlEncode();
if (encodedCode != keyValuePair.Key)
{
content = content.Replace(keyValuePair.Key.HtmlEncode(), image);
}
content = content.Replace(keyValuePair.Key, image);
}
return content;
}
public string GetStandardKeyword(string keyword, int maxKeywordCount = 0)
{
//整理keywords格式
if (!keyword.IsNullOrEmpty())
{
var keywords = keyword.Split(new[] { "|" }, StringSplitOptions.RemoveEmptyEntries).ToList();
if (maxKeywordCount > 0)
{
keywords = keywords.Take(maxKeywordCount).ToList();
}
return $"|{string.Join("|", keywords)}|";
}
return null;
}
/// <summary>
///
/// </summary>
/// <param name="serverId"></param>
/// <param name="filePath">相对路径</param>
/// <returns></returns>
public bool DownloadTemplate(string serverId, string filePath)
{
try
{
//创建目录
Log.LogUtility.Weixin.Debug($"DownloadTemplate:path {filePath} serverId={serverId}");
var downloadTemplateImage = DownloadTemplate(serverId, filePath, false);
Log.LogUtility.Weixin.Debug("DownloadTemplate:downloadTemplateImage " + downloadTemplateImage);
if (!downloadTemplateImage)
{
downloadTemplateImage = DownloadTemplate(serverId, filePath, true);
}
if (!downloadTemplateImage)
{
throw new Exception("图片上传错误(01)!");
}
return true;
}
catch (Exception ex)
{
Log.LogUtility.Weixin.Debug("DownloadTemplate exception: " + ex.Message, ex);
return false;
}
}
/// <summary>
/// 下载微信临时素材Image
/// </summary>
/// <param name="serverId"></param>
/// <param name="fileName"></param>
/// <param name="getNewToken"></param>
/// <returns></returns>
public bool DownloadTemplate(string serverId, string fileName, bool getNewToken = false)
{
using (MemoryStream ms = new MemoryStream())
{
var senparcWeixinSetting = SenparcDI.GetService<IOptions<SenparcWeixinSetting>>().Value;
MediaApi.Get(senparcWeixinSetting.WeixinAppId, serverId, ms);
//保存到文件
ms.Position = 0;
byte[] buffer = new byte[1024];
int bytesRead = 0;
//判断是否上传成功
byte[] topBuffer = new byte[1];
ms.Read(topBuffer, 0, 1);
if (topBuffer[0] == '{')
{
//写入日志
ms.Position = 0;
byte[] logBuffer = new byte[1024];
ms.Read(logBuffer, 0, logBuffer.Length);
string str = System.Text.Encoding.Default.GetString(logBuffer);
Senparc.Log.LogUtility.Weixin.InfoFormat("下载失败:{0}。serverId:{1}", str, serverId);
return false;
}
ms.Position = 0;
//创建目录
using (FileStream fs = new FileStream(fileName, FileMode.Create))
{
while ((bytesRead = ms.Read(buffer, 0, buffer.Length)) != 0)
{
fs.Write(buffer, 0, bytesRead);
}
fs.Flush();
}
Senparc.Log.LogUtility.Weixin.InfoFormat("下载成功:Path[{0}]", fileName);
}
return true;
}
public SendTemplateMessageResult SendTemplateMessage(IWeixinTemplateBase data, string openId, string url = null)
{
try
{
var dt1 = DateTime.Now;
//TODO:写到配置文件里
var accessToken = AccessTokenContainer.TryGetAccessToken(
"wxbe855a981c34aa3f", "2d65ad33a2e8d03c79ecd7b035522227", true);
var dt2 = DateTime.Now;
var result = TemplateApi.SendTemplateMessage(accessToken, openId, data.TemplateId, url, data);
var dt3 = DateTime.Now;
LogUtility.Weixin.InfoFormat("发送模板信息【{2}】。获取AccessToken时间:{0}ms,发送时间:{1}ms",
(dt2 - dt1).TotalMilliseconds, (dt3 - dt2).TotalMilliseconds, data.TemplateName);
return result;
}
catch (Exception ex)
{
LogUtility.Weixin.ErrorFormat($"发送模板消息出错【{data.TemplateName}】:{ex.Message}", ex);
}
return null;
}
public OAuthUserInfo GetOAuthResult(string appId, string appSecret, string code)
{
OAuthAccessTokenResult result = null;
result = OAuthApi.GetAccessToken(appId, appSecret, code);
if (result.errcode != (int)ReturnCode.请求成功)
{
throw new Exception(result.errcode + result.errmsg);
}
return OAuthApi.GetUserInfo(result.access_token, result.openid);
}
}
} | 36.930636 | 134 | 0.532791 | [
"Apache-2.0"
] | xiaohai-xie-baal/SCF | src/Senparc.Service/Weixin/WeixinService.cs | 6,643 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
//
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
//
[assembly: AssemblyTitle("DockSample")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("")]
[assembly: AssemblyCopyright("Copyright 2003, Weifen Luo\nAll rights reserved.")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
//
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Revision and Build Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("1.3.0.0")]
//
// In order to sign your assembly you must specify a key to use. Refer to the
// Microsoft .NET Framework documentation for more information on assembly signing.
//
// Use the attributes below to control which key is used for signing.
//
// Notes:
// (*) If no key is specified, the assembly is not signed.
// (*) KeyName refers to a key that has been installed in the Crypto Service
// Provider (CSP) on your machine. KeyFile refers to a file which contains
// a key.
// (*) If the KeyFile and the KeyName values are both specified, the
// following processing occurs:
// (1) If the KeyName can be found in the CSP, that key is used.
// (2) If the KeyName does not exist and the KeyFile does exist, the key
// in the KeyFile is installed into the CSP and used.
// (*) In order to create a KeyFile, you can use the sn.exe (Strong Name) utility.
// When specifying the KeyFile, the location of the KeyFile should be
// relative to the project output directory which is
// %Project Directory%\obj\<configuration>. For example, if your KeyFile is
// located in the project directory, you would specify the AssemblyKeyFile
// attribute as [assembly: AssemblyKeyFile("..\\..\\mykey.snk")]
// (*) Delay Signing is an advanced option - see the Microsoft .NET Framework
// documentation for more information on this.
//
[assembly: AssemblyDelaySign(false)]
[assembly: AssemblyKeyFile("")]
[assembly: AssemblyKeyName("")]
| 41.152542 | 84 | 0.705519 | [
"MIT"
] | cliftonm/intertexti | DockPanelSuite/DockSample/AssemblyInfo.cs | 2,428 | C# |
namespace ArmyOfCreatures.Tests.Logic.Battles.BattleManagerTests
{
using System;
using ArmyOfCreatures.Logic;
using ArmyOfCreatures.Logic.Battles;
using ArmyOfCreatures.Logic.Creatures;
using ArmyOfCreatures.Tests.MockedClasses;
using Moq;
using NUnit.Framework;
[TestFixture]
public class BattleManager_SkipShould
{
[Test]
public void ThrowArgumentException_WhenNullCreatureIsPassed()
{
var loggerMock = new Mock<ILogger>();
var factoryMock = new Mock<ICreaturesFactory>();
var battleManager = new BattleManager(factoryMock.Object, loggerMock.Object);
var identifier = CreatureIdentifier.CreatureIdentifierFromString("Pesho(1)");
Assert.Throws<ArgumentException>(() => battleManager.Skip(identifier));
}
[Test]
public void CallWriteLineExactly2Times_WhenValidValueIsPassed()
{
var loggerMock = new Mock<ILogger>();
var factoryMock = new Mock<ICreaturesFactory>();
loggerMock.Setup(x => x.WriteLine(It.IsAny<string>()));
var battleManager = new MockedBattleManager(factoryMock.Object, loggerMock.Object);
var creaturesInBattle = new CreaturesInBattle(new Angel(), 1);
var identifier = CreatureIdentifier.CreatureIdentifierFromString("Angel(1)");
battleManager.FirstArmyCreatures.Add(creaturesInBattle);
battleManager.Skip(identifier);
loggerMock.Verify(x => x.WriteLine(It.IsAny<string>()), Times.Exactly(2));
}
}
}
| 32.6 | 95 | 0.654601 | [
"MIT"
] | Valsinev/ComponentTestingWithC | WritedTestsForExams/OOP - 06 April 2015 - Evening/2/ArmyOfCreatures.Tests/Logic/Battles/BattleManagerTests/BattleManager_SkipShould.cs | 1,632 | C# |
using BlazorBoilerplate.Server.Data;
using BlazorBoilerplate.Server.Helpers;
using BlazorBoilerplate.Server.Middleware.Wrappers;
using BlazorBoilerplate.Server.Models;
using BlazorBoilerplate.Server.Services;
using BlazorBoilerplate.Shared;
using BlazorBoilerplate.Shared.AuthorizationDefinitions;
using BlazorBoilerplate.Shared.Dto;
using IdentityModel;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
namespace BlazorBoilerplate.Server.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class AccountController : ControllerBase
{
private static readonly UserInfoDto LoggedOutUser = new UserInfoDto { IsAuthenticated = false, Roles = new List<string>() };
private readonly ILogger<AccountController> _logger;
private readonly IAccountService _accountService;
private readonly UserManager<ApplicationUser> _userManager;
private readonly SignInManager<ApplicationUser> _signInManager;
private readonly RoleManager<IdentityRole<Guid>> _roleManager;
private readonly IEmailService _emailService;
private readonly IConfiguration _configuration;
private readonly IUserProfileService _userProfileService;
private readonly ApplicationDbContext _db;
public AccountController(IAccountService accountService,
UserManager<ApplicationUser> userManager,
ApplicationDbContext db,
SignInManager<ApplicationUser> signInManager,
ILogger<AccountController> logger,
RoleManager<IdentityRole<Guid>> roleManager,
IEmailService emailService,
IUserProfileService userProfileService,
IConfiguration configuration)
{
_accountService = accountService;
_userManager = userManager;
_signInManager = signInManager;
_logger = logger;
_roleManager = roleManager;
_emailService = emailService;
_userProfileService = userProfileService;
_configuration = configuration;
_db = db;
}
// POST: api/Account/Login
[HttpPost("Login")]
[AllowAnonymous]
[ProducesResponseType(204)]
[ProducesResponseType(401)]
public async Task<ApiResponse> Login(LoginDto parameters)
{
if (!ModelState.IsValid)
{
return new ApiResponse(400, "User Model is Invalid");
}
try
{
var result = await _signInManager.PasswordSignInAsync(parameters.UserName, parameters.Password, parameters.RememberMe, true);
// If lock out activated and the max. amounts of attempts is reached.
if (result.IsLockedOut)
{
_logger.LogInformation("User Locked out: {0}", parameters.UserName);
return new ApiResponse(401, "User is locked out!");
}
// If your email is not confirmed but you require it in the settings for login.
if (result.IsNotAllowed)
{
_logger.LogInformation("User not allowed to log in: {0}", parameters.UserName);
return new ApiResponse(401, "Login not allowed!");
}
if (result.Succeeded)
{
_logger.LogInformation("Logged In: {0}", parameters.UserName);
return new ApiResponse(200, "/");
}
}
catch (Exception ex)
{
_logger.LogInformation("Login Failed: " + ex.Message);
}
_logger.LogInformation("Invalid Password for user {0}}", parameters.UserName);
return new ApiResponse(401, "Login Failed");
}
// POST: api/Account/Register
[HttpPost("Register")]
[AllowAnonymous]
public async Task<ApiResponse> Register(RegisterDto parameters)
{
try
{
if (!ModelState.IsValid)
{
return new ApiResponse(400, "User Model is Invalid");
}
var requireConfirmEmail = Convert.ToBoolean(_configuration["BlazorBoilerplate:RequireConfirmedEmail"] ?? "false");
await _accountService.RegisterNewUserAsync(parameters);
if (requireConfirmEmail)
{
return new ApiResponse(200, "Register User Success");
}
else
{
return await Login(new LoginDto
{
UserName = parameters.UserName,
Password = parameters.Password
});
}
}
catch (DomainException ex)
{
_logger.LogError("Register User Failed: {0}, {1}", ex.Description, ex.Message);
return new ApiResponse(400, $"Register User Failed: {ex.Description} ");
}
catch (Exception ex)
{
_logger.LogError("Register User Failed: {0}", ex.Message);
return new ApiResponse(400, "Register User Failed");
}
}
// POST: api/Account/ConfirmEmail
[HttpPost("ConfirmEmail")]
[AllowAnonymous]
public async Task<ApiResponse> ConfirmEmail(ConfirmEmailDto parameters)
{
if (!ModelState.IsValid)
{
return new ApiResponse(400, "User Model is Invalid");
}
if (parameters.UserId == null || parameters.Token == null)
{
return new ApiResponse(404, "User does not exist");
}
var user = await _userManager.FindByIdAsync(parameters.UserId);
if (user == null)
{
_logger.LogInformation("User does not exist: {0}", parameters.UserId);
return new ApiResponse(404, "User does not exist");
}
string token = parameters.Token;
var result = await _userManager.ConfirmEmailAsync(user, token);
if (!result.Succeeded)
{
_logger.LogInformation("User Email Confirmation Failed: {0}", result.Errors.FirstOrDefault()?.Description);
return new ApiResponse(400, "User Email Confirmation Failed");
}
await _signInManager.SignInAsync(user, true);
return new ApiResponse(200, "Success");
}
// POST: api/Account/ForgotPassword
[HttpPost("ForgotPassword")]
[AllowAnonymous]
public async Task<ApiResponse> ForgotPassword(ForgotPasswordDto parameters)
{
if (!ModelState.IsValid)
{
return new ApiResponse(400, "User Model is Invalid");
}
var user = await _userManager.FindByEmailAsync(parameters.Email);
if (user == null || !(await _userManager.IsEmailConfirmedAsync(user)))
{
_logger.LogInformation("Forgot Password with non-existent email / user: {0}", parameters.Email);
// Don't reveal that the user does not exist or is not confirmed
return new ApiResponse(200, "Success");
}
#region Forgot Password Email
try
{
// For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=532713
var token = await _userManager.GeneratePasswordResetTokenAsync(user);
string callbackUrl = string.Format("{0}/Account/ResetPassword/{1}?token={2}", _configuration["BlazorBoilerplate:ApplicationUrl"], user.Id, token); //token must be a query string parameter as it is very long
var email = new EmailMessageDto();
email.ToAddresses.Add(new EmailAddressDto(user.Email, user.Email));
email.BuildForgotPasswordEmail(user.UserName, callbackUrl, token); //Replace First UserName with Name if you want to add name to Registration Form
_logger.LogInformation("Forgot Password Email Sent: {0}", user.Email);
await _emailService.SendEmailAsync(email);
return new ApiResponse(200, "Forgot Password Email Sent");
}
catch (Exception ex)
{
_logger.LogInformation("Forgot Password email failed: {0}", ex.Message);
}
#endregion Forgot Password Email
return new ApiResponse(200, "Success");
}
// PUT: api/Account/ResetPassword
[HttpPost("ResetPassword")]
[AllowAnonymous]
public async Task<ApiResponse> ResetPassword(ResetPasswordDto parameters)
{
if (!ModelState.IsValid)
{
return new ApiResponse(400, "User Model is Invalid");
}
var user = await _userManager.FindByIdAsync(parameters.UserId);
if (user == null)
{
_logger.LogInformation("User does not exist: {0}", parameters.UserId);
return new ApiResponse(404, "User does not exist");
}
#region Reset Password Successful Email
try
{
IdentityResult result = await _userManager.ResetPasswordAsync(user, parameters.Token, parameters.Password);
if (result.Succeeded)
{
#region Email Successful Password change
var email = new EmailMessageDto();
email.ToAddresses.Add(new EmailAddressDto(user.Email, user.Email));
email.BuildPasswordResetEmail(user.UserName); //Replace First UserName with Name if you want to add name to Registration Form
_logger.LogInformation("Reset Password Successful Email Sent: {0}", user.Email);
await _emailService.SendEmailAsync(email);
#endregion Email Successful Password change
return new ApiResponse(200, String.Format("Reset Password Successful Email Sent: {0}", user.Email));
}
else
{
_logger.LogInformation("Error while resetting the password!: {0}", user.UserName);
return new ApiResponse(400, string.Format("Error while resetting the password!: {0}", user.UserName));
}
}
catch (Exception ex)
{
_logger.LogInformation("Reset Password failed: {0}", ex.Message);
return new ApiResponse(400, string.Format("Error while resetting the password!: {0}", ex.Message));
}
#endregion Reset Password Successful Email
}
// POST: api/Account/Logout
[HttpPost("Logout")]
[Authorize]
public async Task<ApiResponse> Logout()
{
await _signInManager.SignOutAsync();
return new ApiResponse(200, "Logout Successful");
}
[HttpGet("UserInfo")]
[ProducesResponseType(200)]
[ProducesResponseType(401)]
public async Task<ApiResponse> UserInfo()
{
UserInfoDto userInfo = await BuildUserInfo();
return new ApiResponse(200, "Retrieved UserInfo", userInfo); ;
}
// POST: api/Account/PhoneAvailabilityCheck/{PhoneNumber}
[HttpGet("PhoneAvailabilityCheck/{id}")]
[ProducesResponseType(200)]
[ProducesResponseType(401)]
public async Task<ApiResponse> PhoneAvailabilityCheck(string id)
{
BoolDto available = new BoolDto() { Boolean = false };
Task<int> t = _db.Users.CountAsync(us => us.PhoneNumber == id);
await t;
int count = t.Result;
if (t.IsCompletedSuccessfully)
{
if (count == 0)
available.Boolean = true;
return new ApiResponse(200, "Retrieved Phone Availability", available); ;
}
return new ApiResponse(401, "Phone Availability Retrieved Error", available); ;
}
private async Task<UserInfoDto> BuildUserInfo()
{
var user = await _userManager.GetUserAsync(User);
if (user != null)
{
try
{
return new UserInfoDto
{
IsAuthenticated = User.Identity.IsAuthenticated,
UserName = user.UserName,
Email = user.Email,
FirstName = user.FirstName,
LastName = user.LastName,
UserId = user.Id,
//Optionally: filter the claims you want to expose to the client
ExposedClaims = User.Claims.Select(c => new KeyValuePair<string, string>(c.Type, c.Value)).ToList(),
Roles = ((ClaimsIdentity)User.Identity).Claims
.Where(c => c.Type == "role")
.Select(c => c.Value).ToList()
};
}
catch (Exception ex)
{
_logger.LogWarning("Could not build UserInfoDto: " + ex.Message);
}
}
else
{
return new UserInfoDto();
}
return null;
}
// DELETE: api/Account/5
[HttpPost("UpdateUser")]
[Authorize]
public async Task<ApiResponse> UpdateUser(UserInfoDto userInfo)
{
if (!ModelState.IsValid)
{
return new ApiResponse(400, "User Model is Invalid");
}
var user = await _userManager.FindByEmailAsync(userInfo.Email);
if (user == null)
{
_logger.LogInformation("User does not exist: {0}", userInfo.Email);
return new ApiResponse(404, "User does not exist");
}
user.FirstName = userInfo.FirstName;
user.LastName = userInfo.LastName;
user.Email = userInfo.Email;
var result = await _userManager.UpdateAsync(user);
if (!result.Succeeded)
{
_logger.LogInformation("User Update Failed: {0}", result.Errors.FirstOrDefault()?.Description);
return new ApiResponse(400, "User Update Failed");
}
return new ApiResponse(200, "User Updated Successfully");
}
///----------Admin User Management Interface Methods
// POST: api/Account/Create
[HttpPost("Create")]
[Authorize(Policy = Policies.IsAdmin)]
public async Task<ApiResponse> Create(RegisterDto parameters)
{
try
{
if (!ModelState.IsValid)
{
return new ApiResponse(400, "User Model is Invalid");
}
var user = new ApplicationUser
{
UserName = parameters.UserName,
PhoneNumber = parameters.PhoneNumber
};
user.UserName = parameters.UserName;
var result = await _userManager.CreateAsync(user, parameters.Password);
if (!result.Succeeded)
{
return new ApiResponse(400, "Register User Failed: " + result.Errors.FirstOrDefault()?.Description);
}
else
{
var claimsResult = _userManager.AddClaimsAsync(user, new Claim[]{
new Claim(Policies.IsUser,""),
new Claim(JwtClaimTypes.Name, parameters.UserName),
new Claim(JwtClaimTypes.PhoneNumber, parameters.PhoneNumber),
new Claim(JwtClaimTypes.EmailVerified, "false", ClaimValueTypes.Boolean)
}).Result;
}
//Role - Here we tie the new user to the "User" role
await _userManager.AddToRoleAsync(user, "User");
if (Convert.ToBoolean(_configuration["BlazorBoilerplate:RequireConfirmedEmail"] ?? "false"))
{
#region New User Confirmation Email
try
{
// For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=532713
var token = await _userManager.GenerateEmailConfirmationTokenAsync(user);
string callbackUrl = string.Format("{0}/Account/ConfirmEmail/{1}?token={2}", _configuration["BlazorBoilerplate:ApplicationUrl"], user.Id, token);
var email = new EmailMessageDto();
email.ToAddresses.Add(new EmailAddressDto(user.Email, user.Email));
email = EmailTemplates.BuildNewUserConfirmationEmail(email, user.UserName, user.Email, callbackUrl, user.Id.ToString(), token); //Replace First UserName with Name if you want to add name to Registration Form
_logger.LogInformation("New user created: {0}", user);
await _emailService.SendEmailAsync(email);
}
catch (Exception ex)
{
_logger.LogInformation("New user email failed: {0}", ex.Message);
}
#endregion New User Confirmation Email
return new ApiResponse(200, "Create User Success");
}
#region New User Email
try
{
var email = new EmailMessageDto();
email.ToAddresses.Add(new EmailAddressDto(user.Email, user.Email));
email.BuildNewUserEmail(user.FullName, user.UserName, user.Email, parameters.Password);
_logger.LogInformation("New user created: {0}", user);
await _emailService.SendEmailAsync(email);
}
catch (Exception ex)
{
_logger.LogInformation("New user email failed: {0}", ex.Message);
}
#endregion New User Email
UserInfoDto userInfo = new UserInfoDto
{
IsAuthenticated = false,
UserName = user.UserName,
Email = user.Email,
FirstName = user.FirstName,
LastName = user.LastName,
//ExposedClaims = user.Claims.ToDictionary(c => c.Type, c => c.Value),
Roles = new List<string> { "User" }
};
return new ApiResponse(200, "Created New User", userInfo);
}
catch (Exception ex)
{
_logger.LogError("Create User Failed: {0}", ex.Message);
return new ApiResponse(400, "Create User Failed");
}
}
// DELETE: api/Account/5
[HttpDelete("{id}")]
[Authorize(Policy = Policies.IsAdmin)]
public async Task<ApiResponse> Delete(string id)
{
var user = await _userManager.FindByIdAsync(id);
if (user.Id == null)
{
return new ApiResponse(404, "User does not exist");
}
try
{
//EF: not a fan this will delete old ApiLogs
var apiLogs = _db.ApiLogs.Where(a => a.ApplicationUserId == user.Id);
foreach (var apiLog in apiLogs)
{
_db.ApiLogs.Remove(apiLog);
}
_db.SaveChanges();
await _userManager.DeleteAsync(user);
return new ApiResponse(200, "User Deletion Successful");
}
catch
{
return new ApiResponse(400, "User Deletion Failed");
}
}
[HttpGet("GetUser")]
public ApiResponse GetUser()
{
UserInfoDto userInfo = User != null && User.Identity.IsAuthenticated
? new UserInfoDto { UserName = User.Identity.Name, IsAuthenticated = true }
: LoggedOutUser;
return new ApiResponse(200, "Get User Successful", userInfo);
}
[HttpGet("ListRoles")]
[Authorize]
public async Task<ApiResponse> ListRoles()
{
var roleList = _roleManager.Roles.Select(x => x.Name).ToList();
return new ApiResponse(200, "", roleList);
}
[HttpPut]
[Authorize(Policy = Policies.IsAdmin)]
// PUT: api/Account/5
public async Task<ApiResponse> Update([FromBody] UserInfoDto userInfo)
{
if (!ModelState.IsValid)
{
return new ApiResponse(400, "User Model is Invalid");
}
// retrieve full user object for updating
var appUser = await _userManager.FindByIdAsync(userInfo.UserId.ToString()).ConfigureAwait(true);
//update values
appUser.UserName = userInfo.UserName;
appUser.FirstName = userInfo.FirstName;
appUser.LastName = userInfo.LastName;
appUser.Email = userInfo.Email;
try
{
var result = await _userManager.UpdateAsync(appUser).ConfigureAwait(true);
}
catch
{
return new ApiResponse(500, "Error Updating User");
}
if (userInfo.Roles != null)
{
try
{
List<string> rolesToAdd = new List<string>();
List<string> rolesToRemove = new List<string>();
var currentUserRoles = (List<string>)(await _userManager.GetRolesAsync(appUser).ConfigureAwait(true));
foreach (var newUserRole in userInfo.Roles)
{
if (!currentUserRoles.Contains(newUserRole))
{
rolesToAdd.Add(newUserRole);
}
}
await _userManager.AddToRolesAsync(appUser, rolesToAdd).ConfigureAwait(true);
//HACK to switch to claims auth
foreach (var role in rolesToAdd)
{
await _userManager.AddClaimAsync(appUser, new Claim($"Is{role}", "true")).ConfigureAwait(true);
}
foreach (var role in currentUserRoles)
{
if (!userInfo.Roles.Contains(role))
{
rolesToRemove.Add(role);
}
}
await _userManager.RemoveFromRolesAsync(appUser, rolesToRemove).ConfigureAwait(true);
//HACK to switch to claims auth
foreach (var role in rolesToRemove)
{
await _userManager.RemoveClaimAsync(appUser, new Claim($"Is{role}", "true")).ConfigureAwait(true);
}
}
catch
{
return new ApiResponse(500, "Error Updating Roles");
}
}
return new ApiResponse(200, "User Updated");
}
[HttpPost("AdminUserPasswordReset/{id}")]
[Authorize(Policy = Policies.IsAdmin)]
[ProducesResponseType(204)]
public async Task<ApiResponse> AdminResetUserPasswordAsync(Guid id, [FromBody] string newPassword)
{
ApplicationUser user;
if (!ModelState.IsValid)
{
return new ApiResponse(400, "Model is Invalid");
}
try
{
user = await _userManager.FindByIdAsync(id.ToString());
if (user.Id == null)
{
throw new KeyNotFoundException();
}
}
catch (KeyNotFoundException ex)
{
return new ApiResponse(400, "Unable to find user" + ex.Message);
}
try
{
var passToken = await _userManager.GeneratePasswordResetTokenAsync(user);
var result = await _userManager.ResetPasswordAsync(user, passToken, newPassword);
if (result.Succeeded)
{
_logger.LogInformation(user.UserName + "'s password reset; Requested from Admin interface by:" + User.Identity.Name);
return new ApiResponse(204, user.UserName + " password reset");
}
else
{
_logger.LogInformation(user.UserName + "'s password reset failed; Requested from Admin interface by:" + User.Identity.Name);
// this is going to an authenticated Admin so it should be safe/useful to send back raw error messages
if (result.Errors.Any())
{
string resultErrorsString = "";
foreach (var identityError in result.Errors)
{
resultErrorsString += identityError.Description + ", ";
}
resultErrorsString.TrimEnd(',');
return new ApiResponse(400, resultErrorsString);
}
else
{
throw new Exception();
}
}
}
catch (Exception ex) // not sure if failed password reset result will throw an exception
{
_logger.LogInformation(user.UserName + "'s password reset failed; Requested from Admin interface by:" + User.Identity.Name);
return new ApiResponse(400, ex.Message);
}
}
}
} | 40.025487 | 231 | 0.536502 | [
"MIT"
] | mobinseven/blazorboilerplate.customized | src/BlazorBoilerplate.Server/Controllers/AccountController.cs | 26,699 | C# |
using Fo76ini.Profiles;
using Fo76ini.Utilities;
using Syroot.Windows.IO;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.AccessControl;
using System.Security.Principal;
namespace Fo76ini
{
public static class IniFiles
{
public static IniFile F76;
public static IniFile F76Prefs;
public static IniFile F76Custom;
public static IniFile Config;
/// <summary>
/// "C:\Users\[username]\Documents\My Games\Fallout 76\"
/// </summary>
public static readonly string ParentPath;
/// <summary>
/// "%LOCALAPPDATA%\Fallout 76 Quick Configuration\config.ini"
/// </summary>
public static readonly string ConfigPath;
/// <summary>
/// "...\DefaultINI"
/// </summary>
public static readonly string DefaultsPath;
/// <summary>
/// "...\DefaultINI\Fallout76.ini"
/// </summary>
public static readonly string DefaultF76Path;
/// <summary>
/// "...\DefaultINI\Medium.ini"
/// </summary>
public static readonly string DefaultF76PrefsPath;
static IniFiles()
{
ParentPath = Path.Combine(
KnownFolders.DocumentsLocalized.ExpandedPath, // Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)
@"My Games\Fallout 76\"
);
ConfigPath = Path.Combine(Shared.AppConfigFolder, "config.ini");
DefaultsPath = Path.Combine(Shared.AppInstallationFolder, "DefaultINI");
DefaultF76Path = Path.Combine(DefaultsPath, "Fallout76.ini");
DefaultF76PrefsPath = Path.Combine(DefaultsPath, "Medium.ini");
}
/// <summary>
/// (Re)Loads config.ini.
/// </summary>
public static void LoadConfig()
{
Config = new IniFile(ConfigPath);
Config.Load(ignoreErrors: true);
}
/// <summary>
/// Loads xyz.ini, xyzPrefs.ini, and xyzCustom.ini.
/// ("xyz" being the *.ini prefix specified by the game instance)
/// </summary>
/// <param name="game"></param>
public static void Load(GameInstance game)
{
F76 = new IniFile(
Path.Combine(ParentPath, $"{game.IniPrefix}.ini"),
DefaultF76Path
);
F76Prefs = new IniFile(
Path.Combine(ParentPath, $"{game.IniPrefix}Prefs.ini"),
DefaultF76PrefsPath
);
F76Custom = new IniFile(
Path.Combine(ParentPath, $"{game.IniPrefix}Custom.ini")
);
F76.Load();
F76Prefs.Load();
F76Custom.Load();
FixDuplicateResourceLists();
}
/// <summary>
/// Checks whether xyz.ini, xyzPrefs.ini, *AND* xyzCustom.ini have been loaded.
/// </summary>
/// <returns>true if loaded, false if not.</returns>
public static bool IsLoaded()
{
return
F76 != null &&
F76Prefs != null &&
F76Custom != null &&
F76.IsLoaded() &&
F76Prefs.IsLoaded() &&
F76Custom.IsLoaded();
}
public static void SetINIsReadOnly(bool readOnly)
{
F76.IsReadOnly = readOnly;
F76Prefs.IsReadOnly = readOnly;
F76Custom.IsReadOnly = readOnly;
}
public static bool AreINIsReadOnly()
{
return F76.IsReadOnly && F76Prefs.IsReadOnly;
}
/// <summary>
/// Makes a backup, then saves xyz.ini, xyzPrefs.ini, xyzCustom.ini, and config.ini.
/// </summary>
public static void Save()
{
Backup();
F76.Save();
F76Prefs.Save();
F76Custom.Save();
Config.Save();
}
/// <summary>
/// Makes a backup of xyz.ini, xyzPrefs.ini, and xyzCustom.ini.
/// </summary>
public static void Backup()
{
string backupDir = Path.Combine(ParentPath, "Backups", DateTime.Now.ToString("yyyy-MM-dd_HH-mm-ss"));
Directory.CreateDirectory(backupDir);
if (File.Exists(F76.FilePath))
File.Copy(F76.FilePath, Path.Combine(backupDir, F76.FileName), true);
if (File.Exists(F76Prefs.FilePath))
File.Copy(F76Prefs.FilePath, Path.Combine(backupDir, F76Prefs.FileName), true);
if (File.Exists(F76Custom.FilePath))
File.Copy(F76Custom.FilePath, Path.Combine(backupDir, F76Custom.FileName), true);
}
/// <summary>
/// Checks whether the files have been modified outside of the tool.
/// </summary>
/// <returns></returns>
public static bool FilesHaveBeenModified()
{
return F76.FileHasBeenModified() || F76Prefs.FileHasBeenModified() || F76Custom.FileHasBeenModified();
}
public static void UpdateLastModifiedDates()
{
F76.UpdateLastModifiedDate();
F76Prefs.UpdateLastModifiedDate();
F76Custom.UpdateLastModifiedDate();
}
/*
*********************************************************************************************************************************************
* GETTER AND SETTER
********************************************************************************************************************************************
*/
/// <summary>
/// Checks whether [section]key exists in xyz.ini, xyzPrefs.ini, or xyzCustom.ini.
/// </summary>
/// <param name="section"></param>
/// <param name="key"></param>
/// <returns>true if found, false if it doesn't exist</returns>
public static bool Exists(string section, string key)
{
foreach (IniFile ini in new IniFile[] { F76, F76Prefs, F76Custom })
if (ini.Exists(section, key))
return true;
return false;
}
public static string GetString(string section, string key, string defaultValue)
{
string value = defaultValue;
foreach (IniFile ini in new IniFile[] { F76, F76Prefs, F76Custom })
if (ini.Exists(section, key))
value = ini.GetString(section, key);
return value;
}
public static string GetString(string section, string key)
{
string value = GetString(section, key, null);
if (value == null)
throw new KeyNotFoundException($"Couldn't find [{section}] {key} in any *.ini file.");
return value;
}
public static bool GetBool(string section, string key)
{
return GetString(section, key) == "1";
}
public static bool GetBool(string section, string key, bool defaultValue)
{
string value = GetString(section, key, defaultValue ? "1" : "0");
if (IniFile.ValidBoolValues.Contains(value))
return value == "1";
else
return defaultValue;
}
public static float GetFloat(string section, string key)
{
return Utils.ToFloat(GetString(section, key));
}
public static float GetFloat(string section, string key, float defaultValue)
{
try
{
return Utils.ToFloat(GetString(section, key, defaultValue.ToString(Shared.en_US)));
}
catch
{
return defaultValue;
}
}
public static uint GetUInt(string section, string key)
{
return Utils.ToUInt(GetString(section, key));
}
public static uint GetUInt(string section, string key, uint defaultValue)
{
try
{
return Utils.ToUInt(GetString(section, key, defaultValue.ToString(Shared.en_US)));
}
catch
{
return defaultValue;
}
}
public static int GetInt(string section, string key)
{
return Utils.ToInt(GetString(section, key));
}
public static int GetInt(string section, string key, int defaultValue)
{
try
{
return Utils.ToInt(GetString(section, key, defaultValue.ToString(Shared.en_US)));
}
catch
{
return defaultValue;
}
}
public static long GetLong(string section, string key)
{
return Utils.ToLong(GetString(section, key));
}
public static long GetLong(string section, string key, int defaultValue)
{
try
{
return Utils.ToLong(GetString(section, key, defaultValue.ToString(Shared.en_US)));
}
catch
{
return defaultValue;
}
}
/// <summary>
/// Removes [section]key from xyz.ini, xyzPrefs.ini, and xyzCustom.ini.
/// </summary>
/// <param name="section"></param>
/// <param name="key"></param>
public static void RemoveAll(string section, string key)
{
foreach (IniFile ini in new IniFile[] { F76, F76Prefs, F76Custom })
ini.Remove(section, key);
}
/*
*********************************************************************************************************************************************
* Fixes for invalid *.ini files:
********************************************************************************************************************************************
*/
private static void MergeLists(IniFile ini, string section, string key)
{
string list = "";
bool found = false;
int i = -1;
IEnumerable<string> lines = File.ReadLines(ini.FilePath);
foreach (string line in lines)
{
if (line.TrimStart().ToLower().StartsWith(key.ToLower()))
{
i = line.IndexOf("=");
if (i > -1)
{
found = true;
list += ", " + line.Substring(i + 1);
}
}
}
list = string.Join<string>(",",
list.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries)
.Select(s => s.Trim()).Distinct().ToArray()
).Trim(',').Replace(",,", ",");
if (found)
ini.Set(section, key, list);
}
private static void FixDuplicateResourceLists()
{
// People seem to have duplicate key=value pairs of sResourceIndexFileList and sResourceArchive2List
// Merge them. Default behaviour of the Parser is overriding and this is probably not what the user wants.
// sResourceDataDirsFinal added in v.1.3.1
// Case insensitive, and whitespace around '=' ignored as of v1.4
if (!File.Exists(F76Custom.FilePath))
return;
MergeLists(F76Custom, "Archive", "sResourceIndexFileList");
MergeLists(F76Custom, "Archive", "sResourceArchive2List");
MergeLists(F76Custom, "Archive", "sResourceDataDirsFinal");
}
/*
*********************************************************************************************************************************************
* Backwards-compatibility:
********************************************************************************************************************************************
*/
/// <summary>
/// Allows or denies write permission to the *.ini parent path (%USERPROFILE%\Documents\My Games\Fallout 76).
/// </summary>
/// <param name="writePermission">true to allow, false to deny</param>
/// <returns>true if successful, false otherwise</returns>
[Obsolete]
public static bool SetNTFSWritePermission(bool writePermission)
{
try
{
// https://stackoverflow.com/questions/7451861/setting-ntfs-permissions-in-c-net
// https://stackoverflow.com/questions/11478917/programmatically-adding-permissions-to-a-folder/11479031
// 'Allow' AND 'Deny' are ticked, wtf?
// Explanation: https://answers.microsoft.com/en-us/windows/forum/all/permission-entry-neither-allow-nor-deny-is-checked/5d210777-b466-49e6-855a-6dc1e85563df
DirectoryInfo dInfo = new DirectoryInfo(ParentPath);
DirectorySecurity dSecurity = dInfo.GetAccessControl();
FileSystemRights rights = FileSystemRights.Write;
// SID: https://support.microsoft.com/en-in/help/243330/well-known-security-identifiers-in-windows-operating-systems
// String account = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
// SecurityIdentifier sidAll = new SecurityIdentifier("S-1-1-0");
// SecurityIdentifier sidAdmins = new SecurityIdentifier("S-1-5-32-544");
SecurityIdentifier sidUsers = new SecurityIdentifier("S-1-5-32-545");
AccessControlType access = writePermission ? AccessControlType.Allow : AccessControlType.Deny;
if (writePermission)
{
dSecurity.RemoveAccessRule(new FileSystemAccessRule(sidUsers, rights, InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit, PropagationFlags.None, AccessControlType.Deny));
dSecurity.AddAccessRule(new FileSystemAccessRule(sidUsers, rights, InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit, PropagationFlags.None, AccessControlType.Allow));
}
else
{
dSecurity.AddAccessRule(new FileSystemAccessRule(sidUsers, rights, InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit, PropagationFlags.None, AccessControlType.Deny));
dSecurity.RemoveAccessRule(new FileSystemAccessRule(sidUsers, rights, InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit, PropagationFlags.None, AccessControlType.Allow));
}
dInfo.SetAccessControl(dSecurity);
}
catch
{
return false;
}
return true;
}
}
}
| 37.5 | 207 | 0.519263 | [
"MIT"
] | FelisDiligens/Fallout76-QuickConfiguration | Fo76ini/Ini/IniFiles.cs | 14,927 | C# |
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Linq;
namespace Iyzipay
{
class RestHttpClientV2
{
static RestHttpClientV2()
{
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
}
public static RestHttpClientV2 Create()
{
return new RestHttpClientV2();
}
public T Get<T>(String url, WebHeaderCollection headers) where T : IyzipayResourceV2
{
HttpClient httpClient = new HttpClient();
foreach (String key in headers.Keys)
{
httpClient.DefaultRequestHeaders.Add(key, headers.Get(key));
}
HttpResponseMessage httpResponseMessage = httpClient.GetAsync(url).Result;
var response = JsonConvert.DeserializeObject<T>(httpResponseMessage.Content.ReadAsStringAsync().Result);
response.AppendWithHttpResponseHeaders(httpResponseMessage);
return response;
}
}
}
| 28.921053 | 116 | 0.649682 | [
"MIT"
] | erhmutlu/iyzipay-dotnet | Iyzipay/RestHttpClientV2.cs | 1,101 | C# |
using Newtonsoft.Json;
namespace HomeAPI.Backend.Models.Lighting.Hue
{
public class HueLightState
{
[JsonProperty("on")]
public bool On { get; set; }
[JsonProperty("bri")]
public int Bri { get; set; }
[JsonProperty("sat")]
public int Sat { get; set; }
[JsonProperty("hue")]
public int Hue { get; set; }
[JsonProperty("ct")]
public int Ct { get; set; }
[JsonProperty("reachable")]
public bool Reachable { get; set; }
}
} | 18.08 | 45 | 0.643805 | [
"MIT"
] | chwun/HomeAPI.Backend | HomeAPI.Backend/Models/Lighting/Hue/HueLightState.cs | 452 | C# |
using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("dexih.connections.flatfile")]
[assembly: AssemblyTrademark("")]
// 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("e9470918-7d49-4ad4-b015-60e4f1e02457")]
| 42.052632 | 84 | 0.777222 | [
"Apache-2.0"
] | DataExperts/dexih.transforms | src/dexih.connections.flatfile/Properties/AssemblyInfo.cs | 801 | C# |
using System;
using System.Collections;
using System.Collections.Generic;
namespace DataStructuresLib.Collections
{
public sealed class SingleItemReadOnlyList<T> :
IReadOnlyList<T>
{
public T ItemValue { get; }
public int ItemIndex { get; }
public int Count { get; }
public T this[int index]
=> index == ItemIndex
? ItemValue
: default;
public SingleItemReadOnlyList(int count, int itemIndex, T itemValue)
{
if (itemIndex < 0 || itemIndex >= Count)
throw new IndexOutOfRangeException();
Count = count;
ItemIndex = itemIndex;
ItemValue = itemValue;
}
public IEnumerator<T> GetEnumerator()
{
for (var i = 0; i < ItemIndex; i++)
yield return default;
yield return ItemValue;
for (var i = ItemIndex + 1; i < Count; i++)
yield return default;
}
IEnumerator IEnumerable.GetEnumerator()
{
for (var i = 0; i < ItemIndex; i++)
yield return default;
yield return ItemValue;
for (var i = ItemIndex + 1; i < Count; i++)
yield return default;
}
}
}
| 23.625 | 76 | 0.517763 | [
"MIT"
] | ga-explorer/GMac | DataStructuresLib/DataStructuresLib/Collections/SingleItemReadOnlyList.cs | 1,325 | C# |
using Amazon.Lambda.Core;
using Amazon.Lambda.SQSEvents;
using Amazon.Lambda.TestUtilities;
using AutoFixture;
using FinancialTransactionListener.Boundary;
using FinancialTransactionListener.Infrastructure;
using Moq;
using System;
using System.Collections.Generic;
using System.Text.Json;
using System.Threading.Tasks;
using Xunit;
namespace FinancialTransactionListener.Tests.E2ETests.Steps
{
public class BaseSteps
{
protected readonly JsonSerializerOptions _jsonOptions = JsonOptions.CreateJsonOptions();
protected readonly Fixture _fixture = new Fixture();
protected Exception _lastException;
public BaseSteps()
{ }
protected SQSEvent.SQSMessage CreateMessage(Guid personId, string eventType = EventTypes.DoSomethingEvent)
{
var personSns = _fixture.Build<EntityEventSns>()
.With(x => x.EntityId, personId)
.With(x => x.EventType, eventType)
.Create();
var msgBody = JsonSerializer.Serialize(personSns, _jsonOptions);
return _fixture.Build<SQSEvent.SQSMessage>()
.With(x => x.Body, msgBody)
.With(x => x.MessageAttributes, new Dictionary<string, SQSEvent.MessageAttribute>())
.Create();
}
protected async Task TriggerFunction(Guid id)
{
var mockLambdaLogger = new Mock<ILambdaLogger>();
ILambdaContext lambdaContext = new TestLambdaContext()
{
Logger = mockLambdaLogger.Object
};
var sqsEvent = _fixture.Build<SQSEvent>()
.With(x => x.Records, new List<SQSEvent.SQSMessage> { CreateMessage(id) })
.Create();
Func<Task> func = async () =>
{
var fn = new SqsFunction();
await fn.FunctionHandler(sqsEvent, lambdaContext).ConfigureAwait(false);
};
_lastException = await Record.ExceptionAsync(func);
}
}
}
| 35.508197 | 114 | 0.588181 | [
"MIT"
] | LBHackney-IT/financial-transaction-listener | FinancialTransactionListener.Tests/E2ETests/Steps/BaseSteps.cs | 2,166 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Collections.Generic;
using Xunit;
namespace System.ComponentModel.Primitives.Tests
{
public class RefreshPropertiesAttributeTests
{
[Theory]
[InlineData(RefreshProperties.None - 1, false)]
[InlineData(RefreshProperties.All, false)]
[InlineData(RefreshProperties.None, true)]
[InlineData(RefreshProperties.Repaint, false)]
public static void Ctor_Refresh(RefreshProperties refresh, bool expectedIsDefaultAttribute)
{
var attribute = new RefreshPropertiesAttribute(refresh);
Assert.Equal(refresh, attribute.RefreshProperties);
Assert.Equal(expectedIsDefaultAttribute, attribute.IsDefaultAttribute());
}
public static IEnumerable<object[]> Equals_TestData()
{
yield return new object[] { RefreshPropertiesAttribute.All, RefreshPropertiesAttribute.All, true };
yield return new object[] { RefreshPropertiesAttribute.All, new RefreshPropertiesAttribute(RefreshProperties.All), true };
yield return new object[] { RefreshPropertiesAttribute.All, RefreshPropertiesAttribute.Repaint, false };
yield return new object[] { RefreshPropertiesAttribute.All, new object(), false };
yield return new object[] { RefreshPropertiesAttribute.All, null, false };
}
[Theory]
[MemberData(nameof(Equals_TestData))]
public void Equals_Object_ReturnsExpected(RefreshPropertiesAttribute attribute, object other, bool expected)
{
Assert.Equal(expected, attribute.Equals(other));
if (other is RefreshPropertiesAttribute)
{
Assert.Equal(expected, attribute.GetHashCode().Equals(other.GetHashCode()));
}
}
public static IEnumerable<object[]> DefaultProperties_TestData()
{
yield return new object[] { RefreshPropertiesAttribute.Default, RefreshProperties.None, true };
yield return new object[] { RefreshPropertiesAttribute.All, RefreshProperties.All, false };
yield return new object[] { RefreshPropertiesAttribute.Repaint, RefreshProperties.Repaint, false };
}
[Theory]
[MemberData(nameof(DefaultProperties_TestData))]
public void DefaultProperties_GetRefreshProperties_ReturnsExpected(RefreshPropertiesAttribute attribute, RefreshProperties expectedRefreshProperties, bool expectedIsDefaultAttribute)
{
Assert.Equal(expectedRefreshProperties, attribute.RefreshProperties);
Assert.Equal(expectedIsDefaultAttribute, attribute.IsDefaultAttribute());
}
}
}
| 46.783333 | 190 | 0.697898 | [
"MIT"
] | 2m0nd/runtime | src/libraries/System.ComponentModel.Primitives/tests/System/ComponentModel/RefreshPropertiesAttributeTests.cs | 2,807 | C# |
namespace io.nem1.sdk.Model.Nis
{
/// <summary>
/// Class NisStatus.
/// </summary>
public class NisStatus
{
/// <summary>
/// Initializes a new instance of the <see cref="NisStatus"/> class.
/// </summary>
/// <param name="code">The code.</param>
/// <param name="type">The type.</param>
/// <param name="message">The message.</param>
public NisStatus(int code, int type, string message)
{
Code = code;
Type = type;
Message = message;
}
/// <summary>
/// Gets the code.
/// </summary>
/// <value>The code.</value>
public int Code { get; }
/// <summary>
/// Gets the type.
/// </summary>
/// <value>The type.</value>
public int Type { get; }
/// <summary>
/// Gets the message.
/// </summary>
/// <value>The message.</value>
public string Message { get; }
}
}
| 26.684211 | 76 | 0.469428 | [
"Apache-2.0"
] | LykkeCity/nem1-sdk-csharp | src/nem1-sdk/src/Model/Nis/NisStatus.cs | 1,016 | C# |
/*
* MailSlurp API
*
* MailSlurp is an API for sending and receiving emails from dynamically allocated email addresses. It's designed for developers and QA teams to test applications, process inbound emails, send templated notifications, attachments, and more. ## Resources - [Homepage](https://www.mailslurp.com) - Get an [API KEY](https://app.mailslurp.com/sign-up/) - Generated [SDK Clients](https://www.mailslurp.com/docs/) - [Examples](https://github.com/mailslurp/examples) repository
*
* The version of the OpenAPI document: 6.5.2
* Contact: contact@mailslurp.dev
* Generated by: https://github.com/openapitools/openapi-generator.git
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.IO;
using System.Runtime.Serialization;
using System.Text;
using System.Text.RegularExpressions;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Linq;
using System.ComponentModel.DataAnnotations;
using OpenAPIDateConverter = mailslurp_netstandard_2x.Client.OpenAPIDateConverter;
namespace mailslurp_netstandard_2x.Model
{
/// <summary>
/// BounceProjection
/// </summary>
[DataContract(Name = "BounceProjection")]
public partial class BounceProjection : IEquatable<BounceProjection>, IValidatableObject
{
/// <summary>
/// Initializes a new instance of the <see cref="BounceProjection" /> class.
/// </summary>
[JsonConstructorAttribute]
protected BounceProjection() { }
/// <summary>
/// Initializes a new instance of the <see cref="BounceProjection" /> class.
/// </summary>
/// <param name="id">id.</param>
/// <param name="sender">sender (required).</param>
/// <param name="createdAt">createdAt (required).</param>
public BounceProjection(Guid id = default(Guid), string sender = default(string), DateTime createdAt = default(DateTime))
{
// to ensure "sender" is required (not null)
this.Sender = sender ?? throw new ArgumentNullException("sender is a required property for BounceProjection and cannot be null");
this.CreatedAt = createdAt;
this.Id = id;
}
/// <summary>
/// Gets or Sets Id
/// </summary>
[DataMember(Name = "id", EmitDefaultValue = false)]
public Guid Id { get; set; }
/// <summary>
/// Gets or Sets Sender
/// </summary>
[DataMember(Name = "sender", IsRequired = true, EmitDefaultValue = false)]
public string Sender { get; set; }
/// <summary>
/// Gets or Sets CreatedAt
/// </summary>
[DataMember(Name = "createdAt", IsRequired = true, EmitDefaultValue = false)]
public DateTime CreatedAt { get; set; }
/// <summary>
/// Returns the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("class BounceProjection {\n");
sb.Append(" Id: ").Append(Id).Append("\n");
sb.Append(" Sender: ").Append(Sender).Append("\n");
sb.Append(" CreatedAt: ").Append(CreatedAt).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public virtual string ToJson()
{
return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="input">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object input)
{
return this.Equals(input as BounceProjection);
}
/// <summary>
/// Returns true if BounceProjection instances are equal
/// </summary>
/// <param name="input">Instance of BounceProjection to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(BounceProjection input)
{
if (input == null)
return false;
return
(
this.Id == input.Id ||
(this.Id != null &&
this.Id.Equals(input.Id))
) &&
(
this.Sender == input.Sender ||
(this.Sender != null &&
this.Sender.Equals(input.Sender))
) &&
(
this.CreatedAt == input.CreatedAt ||
(this.CreatedAt != null &&
this.CreatedAt.Equals(input.CreatedAt))
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
unchecked // Overflow is fine, just wrap
{
int hashCode = 41;
if (this.Id != null)
hashCode = hashCode * 59 + this.Id.GetHashCode();
if (this.Sender != null)
hashCode = hashCode * 59 + this.Sender.GetHashCode();
if (this.CreatedAt != null)
hashCode = hashCode * 59 + this.CreatedAt.GetHashCode();
return hashCode;
}
}
/// <summary>
/// To validate all properties of the instance
/// </summary>
/// <param name="validationContext">Validation context</param>
/// <returns>Validation Result</returns>
IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> IValidatableObject.Validate(ValidationContext validationContext)
{
yield break;
}
}
}
| 37.290909 | 472 | 0.574516 | [
"MIT"
] | mailslurp/mailslurp-client-csharp-netstandard-2x | src/mailslurp_netstandard_2x/Model/BounceProjection.cs | 6,153 | C# |
// /*
// Copyright (c) 2017-12
//
// moljac
// Test.cs
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
// */
#if XUNIT
using Xunit;
// NUnit aliases
using Test = Xunit.FactAttribute;
using OneTimeSetUp = HolisticWare.Core.Testing.UnitTests.UnitTestsCompatibilityAliasAttribute;
// XUnit aliases
using TestClass = HolisticWare.Core.Testing.UnitTests.UnitTestsCompatibilityAliasAttribute;
#elif NUNIT
using NUnit.Framework;
// MSTest aliases
using TestInitialize = NUnit.Framework.SetUpAttribute;
using TestProperty = NUnit.Framework.PropertyAttribute;
using TestClass = HolisticWare.Core.Testing.UnitTests.UnitTestsCompatibilityAliasAttribute;
using TestMethod = NUnit.Framework.TestAttribute;
using TestCleanup = NUnit.Framework.TearDownAttribute;
// XUnit aliases
using Fact = NUnit.Framework.TestAttribute;
#elif MSTEST
using Microsoft.VisualStudio.TestTools.UnitTesting;
// NUnit aliases
using Test = Microsoft.VisualStudio.TestTools.UnitTesting.TestMethodAttribute;
using OneTimeSetUp = Microsoft.VisualStudio.TestTools.UnitTesting.ClassInitializeAttribute;
// XUnit aliases
using Fact = Microsoft.VisualStudio.TestTools.UnitTesting.TestMethodAttribute;
#endif
#if BENCHMARKDOTNET
using BenchmarkDotNet.Running;
using BenchmarkDotNet.Configs;
using BenchmarkDotNet.Attributes.Jobs;
#else
using Benchmark = HolisticWare.Core.Testing.BenchmarkTests.Benchmark;
using ShortRunJob = HolisticWare.Core.Testing.BenchmarkTests.ShortRunJob;
#endif
using System;
using System.Collections.Generic;
using System.Linq;
using System.Diagnostics;
using System.Collections.ObjectModel;
using Core.Math.Statistics.Descriptive.Sequential;
namespace UnitTests.Core.Math.Statistics.Descriptive.Sequential.Sync
{
public partial class Tests20180119Dataset03
{
[Benchmark]
public double Array_SkewnessType1()
{
return data_array.SkewnessType1();
}
[Test]
public void Array_SkewnessType1_Test()
{
Console.WriteLine($"Array_SkewnessType1_Test");
//====================================================================================================
// Arrange
// reading data from files
sw = Stopwatch.StartNew();
//----------------------------------------------------------------------------------------------------
// Act
// extracted to atomic Benchmark method
double skewness = Array_SkewnessType1();
sw.Stop();
Console.WriteLine($"Array<double>.SkewnessType1()");
Console.WriteLine($" skewness = {skewness}");
Console.WriteLine($" size = {data_array.Count()}");
Console.WriteLine($" elapsed[ticks] = {sw.ElapsedTicks}");
Console.WriteLine($" elapsed[ms] = {sw.Elapsed.TotalMilliseconds}");
sw.Reset();
double moment_3 = data_array.Moment(3);
double moment_2 = data_array.Moment(2);
int n = data_array.Count();
double factor = 1.0;
double skewness_check = factor * moment_3 / System.Math.Pow(moment_2, 3 / 2);
//----------------------------------------------------------------------------------------------------
// Assert
#if NUNIT
Assert.AreEqual(0.0, skewness, 0.00001);
Assert.AreEqual(skewness_check, skewness, 0.00001);
#elif XUNIT
Assert.Equal(0.0, skewness, 5);
Assert.Equal(skewness_check, skewness, 5);
#elif MSTEST
Assert.AreEqual(0.0, skewness, 0.00001);
Assert.AreEqual(skewness_check, skewness, 0.00001);
#endif
//====================================================================================================
return;
}
[Benchmark]
public double ArraySegment_SkewnessType1()
{
return data_array_segment.SkewnessType1();
}
[Test]
public void ArraySegment_SkewnessType1_Test()
{
//====================================================================================================
// Arrange
// reading data from files
sw = Stopwatch.StartNew();
//----------------------------------------------------------------------------------------------------
// Act
// extracted to atomic Benchmark method
double skewness = ArraySegment_SkewnessType1();
sw.Stop();
Console.WriteLine($" skewness = {skewness}");
Console.WriteLine($" size = {data.Count()}");
Console.WriteLine($" elapsed[ticks] = {sw.ElapsedTicks}");
Console.WriteLine($" elapsed[ms] = {sw.Elapsed.TotalMilliseconds}");
sw.Reset();
double moment_3 = data_array_segment.Moment(3);
double moment_2 = data_array_segment.Moment(2);
int n = data_array_segment.Count();
double factor = 1.0;
double skewness_check = factor * moment_3 / System.Math.Pow(moment_2, 3 / 2);
//----------------------------------------------------------------------------------------------------
// Assert
#if NUNIT
Assert.AreEqual(0.0, skewness, 0.00001);
Assert.AreEqual(skewness_check, skewness, 0.00001);
#elif XUNIT
Assert.Equal(0.0, skewness, 5);
Assert.Equal(skewness_check, skewness, 5);
#elif MSTEST
Assert.AreEqual(0.0, skewness, 0.00001);
Assert.AreEqual(skewness_check, skewness, 0.00001);
#endif
//====================================================================================================
return;
}
[Benchmark]
public double List_SkewnessType1()
{
return data_list.SkewnessType1();
}
[Test]
public void List_SkewnessType1_Test()
{
//====================================================================================================
// Arrange
// reading data from files
sw = Stopwatch.StartNew();
//----------------------------------------------------------------------------------------------------
// Act
// extracted to atomic Benchmark method
double skewness = List_SkewnessType1();
Console.WriteLine($" skewness = {skewness}");
Console.WriteLine($" size = {data.Count()}");
Console.WriteLine($" elapsed[ticks] = {sw.ElapsedTicks}");
Console.WriteLine($" elapsed[ms] = {sw.Elapsed.TotalMilliseconds}");
sw.Reset();
double moment_3 = data_list.Moment(3);
double moment_2 = data_list.Moment(2);
int n = data_list.Count();
double factor = 1.0;
double skewness_check = factor * moment_3 / System.Math.Pow(moment_2, 3 / 2);
//----------------------------------------------------------------------------------------------------
// Assert
#if NUNIT
Assert.AreEqual(0.0, skewness, 0.00001);
Assert.AreEqual(skewness_check, skewness, 0.00001);
#elif XUNIT
Assert.Equal(0.0, skewness, 5);
Assert.Equal(skewness_check, skewness, 5);
#elif MSTEST
Assert.AreEqual(0.0, skewness, 0.00001);
Assert.AreEqual(skewness_check, skewness, 0.00001);
#endif
//====================================================================================================
return;
}
[Benchmark]
public double Queue_SkewnessType1()
{
return data_queue.SkewnessType1();
}
[Test]
public void Queue_SkewnessType1_Test()
{
//====================================================================================================
// Arrange
sw = Stopwatch.StartNew();
//----------------------------------------------------------------------------------------------------
// Act
// extracted to atomic Benchmark method
double skewness = Queue_SkewnessType1();
sw.Stop();
Console.WriteLine($" skewness = {skewness}");
Console.WriteLine($" size = {data.Count()}");
Console.WriteLine($" elapsed[ticks] = {sw.ElapsedTicks}");
Console.WriteLine($" elapsed[ms] = {sw.Elapsed.TotalMilliseconds}");
sw.Reset();
double moment_3 = data_queue.Moment(3);
double moment_2 = data_queue.Moment(2);
int n = data_queue.Count();
double factor = 1.0;
double skewness_check = factor * moment_3 / System.Math.Pow(moment_2, 3 / 2);
//----------------------------------------------------------------------------------------------------
// Assert
#if NUNIT
Assert.AreEqual(0.0, skewness, 0.00001);
Assert.AreEqual(skewness_check, skewness, 0.00001);
#elif XUNIT
Assert.Equal(0.0, skewness, 5);
Assert.Equal(skewness_check, skewness, 5);
#elif MSTEST
Assert.AreEqual(0.0, skewness, 0.00001);
Assert.AreEqual(skewness_check, skewness, 0.00001);
#endif
//====================================================================================================
return;
}
[Benchmark]
public double Stack_SkewnessType1()
{
return data_stack.SkewnessType1();
}
[Test]
public void Stack_SkewnessType1_Test()
{
//====================================================================================================
// Arrange
// reading data from files
sw = Stopwatch.StartNew();
//----------------------------------------------------------------------------------------------------
// Act
// extracted to atomic Benchmark method
double skewness = Stack_SkewnessType1();
sw.Stop();
Console.WriteLine($" skewness = {skewness}");
Console.WriteLine($" size = {data.Count()}");
Console.WriteLine($" elapsed[ticks] = {sw.ElapsedTicks}");
Console.WriteLine($" elapsed[ms] = {sw.Elapsed.TotalMilliseconds}");
sw.Reset();
double moment_3 = data_stack.Moment(3);
double moment_2 = data_stack.Moment(2);
int n = data_stack.Count();
double factor = 1.0;
double skewness_check = factor * moment_3 / System.Math.Pow(moment_2, 3 / 2);
//----------------------------------------------------------------------------------------------------
// Assert
#if NUNIT
Assert.AreEqual(0.0, skewness, 0.00001);
Assert.AreEqual(skewness_check, skewness, 0.00001);
#elif XUNIT
Assert.Equal(0.0, skewness, 5);
Assert.Equal(skewness_check, skewness, 5);
#elif MSTEST
Assert.AreEqual(0.0, skewness, 0.00001);
Assert.AreEqual(skewness_check, skewness, 0.00001);
#endif
//====================================================================================================
return;
}
[Benchmark]
public double LinkedList_SkewnessType1()
{
return data_linked_list.SkewnessType1();
}
[Test]
public void LinkedList_SkewnessType1_Test()
{
//====================================================================================================
// Arrange
// reading data from files
sw = Stopwatch.StartNew();
//----------------------------------------------------------------------------------------------------
// Act
// extracted to atomic Benchmark method
double skewness = LinkedList_SkewnessType1();
sw.Stop();
Console.WriteLine($" skewness = {skewness}");
Console.WriteLine($" size = {data.Count()}");
Console.WriteLine($" elapsed[ticks] = {sw.ElapsedTicks}");
Console.WriteLine($" elapsed[ms] = {sw.Elapsed.TotalMilliseconds}");
sw.Reset();
double moment_3 = data_linked_list.Moment(3);
double moment_2 = data_linked_list.Moment(2);
int n = data_linked_list.Count();
double factor = 1.0;
double skewness_check = factor * moment_3 / System.Math.Pow(moment_2, 3 / 2);
//----------------------------------------------------------------------------------------------------
// Assert
#if NUNIT
Assert.AreEqual(0.0, skewness, 0.00001);
Assert.AreEqual(skewness_check, skewness, 0.00001);
#elif XUNIT
Assert.Equal(0.0, skewness, 5);
Assert.Equal(skewness_check, skewness, 5);
#elif MSTEST
Assert.AreEqual(0.0, skewness, 0.00001);
Assert.AreEqual(skewness_check, skewness, 0.00001);
#endif
//====================================================================================================
return;
}
[Benchmark]
public double ObservableCollection_SkewnessType1()
{
return data_observable_collection.SkewnessType1();
}
[Test]
public void ObservableCollection_SkewnessType1_Test()
{
//====================================================================================================
// Arrange
// reading data from files
sw = Stopwatch.StartNew();
//----------------------------------------------------------------------------------------------------
// Act
// extracted to atomic Benchmark method
double skewness = ObservableCollection_SkewnessType1();
sw.Stop();
Console.WriteLine($" skewness = {skewness}");
Console.WriteLine($" size = {data.Count()}");
Console.WriteLine($" elapsed[ticks] = {sw.ElapsedTicks}");
Console.WriteLine($" elapsed[ms] = {sw.Elapsed.TotalMilliseconds}");
sw.Reset();
double moment_3 = data_observable_collection.Moment(3);
double moment_2 = data_observable_collection.Moment(2);
int n = data_observable_collection.Count();
double factor = 1.0;
double skewness_check = factor * moment_3 / System.Math.Pow(moment_2, 3 / 2);
//----------------------------------------------------------------------------------------------------
// Assert
#if NUNIT
Assert.AreEqual(0.0, skewness, 0.00001);
Assert.AreEqual(skewness_check, skewness, 0.00001);
#elif XUNIT
Assert.Equal(0.0, skewness, 5);
Assert.Equal(skewness_check, skewness, 5);
#elif MSTEST
Assert.AreEqual(0.0, skewness, 0.00001);
Assert.AreEqual(skewness_check, skewness, 0.00001);
#endif
//====================================================================================================
return;
}
/*
c# 7.2
Span<T>,
ReadOnlySpan<T>,
Memory<T>
ReadOnlyMemory<T>
*/
/*
[Test]
public void Span_SkewnessType1()
{
//====================================================================================================
// Arrange
// reading data from files
sw = Stopwatch.StartNew();
//----------------------------------------------------------------------------------------------------
// Act
Span<double> data =
new Span<double>(data01);
//data01.AsSpan().Slice(start: 0)
;
double skewness = data.SkewnessType1();
sw.Stop();
Console.WriteLine($" skewness = {skewness}");
Console.WriteLine($" size = {data.Count()}");
Console.WriteLine($" elapsed[ticks] = {sw.ElapsedTicks}");
Console.WriteLine($" elapsed[ms] = {sw.Elapsed.TotalMilliseconds}");
sw.Reset();
//----------------------------------------------------------------------------------------------------
// Assert
#if NUNIT
Assert.AreEqual(0.0, skewness, 0.00001);
#elif XUNIT
Assert.Equal(0.0, skewness, 5);
#elif MSTEST
Assert.AreEqual(0.0, skewness, 0.00001);
#endif
//====================================================================================================
return;
}
[Test]
public void Span_SkewnessType1()
{
//====================================================================================================
// Arrange
// reading data from files
sw = Stopwatch.StartNew();
//----------------------------------------------------------------------------------------------------
// Act
Memory<double> data =
new Memory<double>(data01);
//data01.AsSpan().Slice(start: 0)
;
double skewness = data.SkewnessType1();
sw.Stop();
Console.WriteLine($" skewness = {skewness}");
Console.WriteLine($" size = {data.Count()}");
Console.WriteLine($" elapsed[ticks] = {sw.ElapsedTicks}");
Console.WriteLine($" elapsed[ms] = {sw.Elapsed.TotalMilliseconds}");
sw.Reset();
//----------------------------------------------------------------------------------------------------
// Assert
#if NUNIT
Assert.AreEqual(0.0, skewness, 0.00001);
#elif XUNIT
Assert.Equal(0.0, skewness, 5);
#elif MSTEST
Assert.AreEqual(0.0, skewness, 0.00001);
#endif
//====================================================================================================
return;
}
*/
}
}
| 41.742915 | 143 | 0.433733 | [
"MIT"
] | HolisticWare/HolisticWare.Core.Math.Statistics.Descriptive.Sequential | tests/Tests.CommonShared/01-DarkVaderTests/Tests20180119Dataset03/Tests011MeasuresDistribution.SkewnessType1.cs | 20,623 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.