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
namespace OpenMod.Unturned.Animals.Events { public class UnturnedAnimalRevivedEvent : UnturnedAnimalSpawnedEvent { public UnturnedAnimalRevivedEvent(UnturnedAnimal animal) : base(animal) { } } }
23.2
79
0.698276
[ "MIT" ]
01-Feli/openmod
unturned/OpenMod.Unturned/Animals/Events/UnturnedAnimalRevivedEvent.cs
234
C#
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace MobiSys.Models { public partial class Manufacturers { public Manufacturers() { Products = new HashSet<Products>(); } [Key] [Column("id")] [Display(Name = "ID")] public int Id { get; set; } [Required] [Column("name")] [StringLength(16)] [Display(Name = "Name")] public string Name { get; set; } [InverseProperty("Manufacturer")] public virtual ICollection<Products> Products { get; set; } } }
23.689655
67
0.592431
[ "MIT" ]
cirmaciuadrian/MobiSys
Models/Manufacturers.cs
689
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by Codezu. // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ using System; using System.Collections.Generic; namespace Mozu.Api.Contracts.ProductAdmin { /// /// Properties of a value for a product property. /// public class ProductPropertyValue { public AttributeVocabularyValue AttributeVocabularyValueDetail { get; set; } public ProductPropertyValueLocalizedContent Content { get; set; } /// ///The localized content associated with the object. /// public List<ProductPropertyValueLocalizedContent> LocalizedContent { get; set; } public object Value { get; set; } } }
26.057143
83
0.58114
[ "MIT" ]
GaryWayneSmith/mozu-dotnet
Mozu.Api/Contracts/ProductAdmin/ProductPropertyValue.cs
912
C#
using api.Adapters; using api.Context; using api.Dtos; namespace api.Services { public class CaseService { private readonly DcdDbContext _context; private readonly ProjectService _projectService; public CaseService(DcdDbContext context, ProjectService projectService) { _context = context; _projectService = projectService; } public ProjectDto CreateCase(CaseDto caseDto) { var case_ = CaseAdapter.Convert(caseDto); var project = _projectService.GetProject(case_.ProjectId); case_.Project = project; _context.Cases!.Add(case_); _context.SaveChanges(); return _projectService.GetProjectDto(project.Id); } public ProjectDto UpdateCase(CaseDto updatedCaseDto) { var updatedCase = CaseAdapter.Convert(updatedCaseDto); _context.Cases!.Update(updatedCase); _context.SaveChanges(); return _projectService.GetProjectDto(updatedCase.ProjectId); } } }
29.459459
79
0.634862
[ "MIT" ]
InGit5/dcd
backend/api/Services/CaseService.cs
1,090
C#
using PhotoShare.Data; using PhotoShare.Models; using System; using System.Linq; namespace PhotoShare.Services { public class AlbumsService : IAlbumsService { private readonly PhotoShareContext context; private readonly IUsersService usersService; private readonly IUsersSessionService usersSessionService; public AlbumsService(PhotoShareContext context, IUsersService usersService, IUsersSessionService usersSessionService) { this.context = context; this.usersService = usersService; this.usersSessionService = usersSessionService; } public void AddPicture(string albumName, string pictureTitle, string picturePath) { var album = this.AlbumByName(albumName); if (album == null) { throw new ArgumentException($"Album {albumName} not found!"); } var isAlbumOwner = this.context.AlbumRoles .Any(ar => ar.Album == album && ar.Role == Role.Owner && ar.User == this.usersSessionService.User); if (!isAlbumOwner) { throw new InvalidOperationException("Invalid credentials!"); } this.context.Pictures.Add(new Picture { Album = album, Title = pictureTitle, Path = picturePath, UserProfile = this.usersSessionService.User, }); this.context.SaveChanges(); } public void AddTagToAlbum(string albumName, string tagName) { var tag = this.TagByName(tagName); var album = this.AlbumByName(albumName); if (tag == null || album == null) { throw new ArgumentException("Either tag or album do not exist!"); } var albumOwner = this.context.Users .FirstOrDefault(a => a.AlbumRoles.Any(ar => ar.Album == album && ar.Role == Role.Owner)); if (albumOwner != this.usersSessionService.User) { throw new InvalidOperationException("Invalid credentials!"); } this.context.AlbumTags.Add(new AlbumTag { Album = album, Tag = tag }); this.context.SaveChanges(); } public Album AlbumByName(string name) { var album = this.context.Albums .FirstOrDefault(a => a.Name == name); return album; } public Album CreateAlbum(string username, string albumTitle, string color, string[] tags) { var user = this.usersService.ByUsername(username); if (user == null) { throw new ArgumentException($"User {username} not found!"); } if (!Enum.TryParse(typeof(Color), color, out object bgColor)) { throw new ArgumentException($"Color {color} not found!"); } var backColor = (Color)bgColor; if (!tags.All(t => this.TagByName(t) != null)) { throw new ArgumentException("Invalid tags!"); } var album = this.AlbumByName(albumTitle); if (album != null) { throw new ArgumentException($"Album {albumTitle} exists!"); } var albumTags = tags.Select(t => this.TagByName(t)); album = new Album { BackgroundColor = backColor, Name = albumTitle, }; this.context.Albums.Add(album); albumTags.ToList() .ForEach(at => this.context.AlbumTags.Add(new AlbumTag { Album = album, Tag = at })); this.context.AlbumRoles.Add(new AlbumRole { Album = album, User = user, Role = Role.Owner }); this.context.SaveChanges(); return album; } public Tag CreateTag(string name) { var tag = context.Tags.FirstOrDefault(t => t.Name == name); if (tag != null) { throw new ArgumentException($"Tag {tag.Name} exists!"); } tag = new Tag { Name = name }; this.context.Tags.Add(tag); this.context.SaveChanges(); return tag; } public string ShareAlbum(int albumId, string username, string permission) { var album = this.context.Albums .FirstOrDefault(a => a.Id == albumId); if (album == null) { throw new ArgumentException($"Album {albumId} not found!"); } var isAlbumOwner = this.context.AlbumRoles .Any(ar => ar.Album == album && ar.Role == Role.Owner && ar.User == this.usersSessionService.User); if (!isAlbumOwner) { throw new InvalidOperationException("Invalid credentials!"); } var user = this.usersService.ByUsername(username); if (user == null) { throw new ArgumentException($"User {username} not found!"); } if (!Enum.TryParse(typeof(Role), permission, out object roleObj)) { throw new ArgumentException("Permission must be either “Owner” or “Viewer”!"); } var role = (Role)roleObj; this.context.AlbumRoles.Add(new AlbumRole { Album = album, Role = role }); this.context.SaveChanges(); return album.Name; } public Tag TagByName(string name) { var tag = this.context.Tags .FirstOrDefault(t => t.Name == name); return tag; } } }
30.088083
125
0.530222
[ "MIT" ]
TihomirIvanovIvanov/SoftUni
C#DBFundamentals/DB-Advanced-Entity-Framework-Core/07DBBestPracticesAndArchitecture/src/PhotoShare.Services/AlbumsService.cs
5,817
C#
using System; namespace Soft.CalculoJuros.Dominio.Extensoes { public static class ExtensaoDecimal { public static decimal Potencia(this decimal valor, int potencia) { return (decimal)Math.Pow((double)valor, potencia); } public static decimal Truncar(this decimal valor, int precisao) { decimal num = (decimal)Math.Pow(10.0, precisao); return Math.Truncate(num * valor) / num; } } }
25.315789
72
0.611227
[ "MIT" ]
rafaelbitencourt/Soft.Calculo
Soft.CalculoJuros.Dominio/Extensoes/ExtensaoDecimal.cs
483
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> //------------------------------------------------------------------------------ // Generation date: 9/11/2020 3:24:26 PM namespace Microsoft.Dynamics.DataEntities { /// <summary> /// There are no comments for RetailInfocodeActivityType in the schema. /// </summary> public enum RetailInfocodeActivityType { Transaction = 0, OrderFulfillment = 1 } }
30.73913
81
0.507779
[ "MIT" ]
NathanClouseAX/AAXDataEntityPerfTest
Projects/AAXDataEntityPerfTest/ConsoleApp1/Connected Services/D365/RetailInfocodeActivityType.cs
709
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. // // To regenerate code in this file run: // ir Languages/Ruby/Scripts/CodeGenerator.rb DynamicOperations.Generated.cs // using System.Linq.Expressions; using System; using System.Runtime.CompilerServices; using Microsoft.Scripting.Utils; namespace Microsoft.Scripting.Runtime { public sealed partial class DynamicOperations { private const int /*$$*/PregeneratedInvokerCount = 14; private Func<DynamicOperations, CallSiteBinder, object, object[], object> GetInvoker(int paramCount) { Func<DynamicOperations, CallSiteBinder, object, object[], object> invoker; lock (_invokers) { if (!_invokers.TryGetValue(paramCount, out invoker)) { _invokers[paramCount] = invoker = GetPregeneratedInvoker(paramCount) ?? EmitInvoker(paramCount); } } return invoker; } [MethodImpl(MethodImplOptions.NoInlining)] private Func<DynamicOperations, CallSiteBinder, object, object[], object> EmitInvoker(int paramCount) { #if !FEATURE_REFEMIT throw new NotSupportedException(); #else ParameterExpression dynOps = Expression.Parameter(typeof(DynamicOperations)); ParameterExpression callInfo = Expression.Parameter(typeof(CallSiteBinder)); ParameterExpression target = Expression.Parameter(typeof(object)); ParameterExpression args = Expression.Parameter(typeof(object[])); Type funcType = DelegateUtils.EmitCallSiteDelegateType(paramCount); ParameterExpression site = Expression.Parameter(typeof(CallSite<>).MakeGenericType(funcType)); Expression[] siteArgs = new Expression[paramCount + 2]; siteArgs[0] = site; siteArgs[1] = target; for (int i = 0; i < paramCount; i++) { siteArgs[i + 2] = Expression.ArrayIndex(args, Expression.Constant(i)); } var getOrCreateSiteFunc = new Func<CallSiteBinder, CallSite<Func<object>>>(GetOrCreateSite<Func<object>>).GetMethodInfo().GetGenericMethodDefinition(); return Expression.Lambda<Func<DynamicOperations, CallSiteBinder, object, object[], object>>( Expression.Block( new[] { site }, Expression.Assign( site, Expression.Call(dynOps, getOrCreateSiteFunc.MakeGenericMethod(funcType), callInfo) ), Expression.Invoke( Expression.Field( site, site.Type.GetField("Target") ), siteArgs ) ), new[] { dynOps, callInfo, target, args } ).Compile(); #endif } private static Func<DynamicOperations, CallSiteBinder, object, object[], object> GetPregeneratedInvoker(int paramCount) { switch (paramCount) { #if GENERATOR def generate; $PregeneratedInvokerCount.times { |n| @n = n + 1; super }; end def n; @n; end def objects; "object, " * @n; end def args; (0..@n-1).map { |i| ", args[#{i}]" }.join; end #else case /*$n{*/0/*}*/: return (ops, binder, target, args) => { var site = ops.GetOrCreateSite<Func<CallSite, object, /*$objects*/object>>(binder); return site.Target(site, target/*$args*/); }; #endif #region Generated case 1: return (ops, binder, target, args) => { var site = ops.GetOrCreateSite<Func<CallSite, object, object, object>>(binder); return site.Target(site, target, args[0]); }; case 2: return (ops, binder, target, args) => { var site = ops.GetOrCreateSite<Func<CallSite, object, object, object, object>>(binder); return site.Target(site, target, args[0], args[1]); }; case 3: return (ops, binder, target, args) => { var site = ops.GetOrCreateSite<Func<CallSite, object, object, object, object, object>>(binder); return site.Target(site, target, args[0], args[1], args[2]); }; case 4: return (ops, binder, target, args) => { var site = ops.GetOrCreateSite<Func<CallSite, object, object, object, object, object, object>>(binder); return site.Target(site, target, args[0], args[1], args[2], args[3]); }; case 5: return (ops, binder, target, args) => { var site = ops.GetOrCreateSite<Func<CallSite, object, object, object, object, object, object, object>>(binder); return site.Target(site, target, args[0], args[1], args[2], args[3], args[4]); }; case 6: return (ops, binder, target, args) => { var site = ops.GetOrCreateSite<Func<CallSite, object, object, object, object, object, object, object, object>>(binder); return site.Target(site, target, args[0], args[1], args[2], args[3], args[4], args[5]); }; case 7: return (ops, binder, target, args) => { var site = ops.GetOrCreateSite<Func<CallSite, object, object, object, object, object, object, object, object, object>>(binder); return site.Target(site, target, args[0], args[1], args[2], args[3], args[4], args[5], args[6]); }; case 8: return (ops, binder, target, args) => { var site = ops.GetOrCreateSite<Func<CallSite, object, object, object, object, object, object, object, object, object, object>>(binder); return site.Target(site, target, args[0], args[1], args[2], args[3], args[4], args[5], args[6], args[7]); }; case 9: return (ops, binder, target, args) => { var site = ops.GetOrCreateSite<Func<CallSite, object, object, object, object, object, object, object, object, object, object, object>>(binder); return site.Target(site, target, args[0], args[1], args[2], args[3], args[4], args[5], args[6], args[7], args[8]); }; case 10: return (ops, binder, target, args) => { var site = ops.GetOrCreateSite<Func<CallSite, object, object, object, object, object, object, object, object, object, object, object, object>>(binder); return site.Target(site, target, args[0], args[1], args[2], args[3], args[4], args[5], args[6], args[7], args[8], args[9]); }; case 11: return (ops, binder, target, args) => { var site = ops.GetOrCreateSite<Func<CallSite, object, object, object, object, object, object, object, object, object, object, object, object, object>>(binder); return site.Target(site, target, args[0], args[1], args[2], args[3], args[4], args[5], args[6], args[7], args[8], args[9], args[10]); }; case 12: return (ops, binder, target, args) => { var site = ops.GetOrCreateSite<Func<CallSite, object, object, object, object, object, object, object, object, object, object, object, object, object, object>>(binder); return site.Target(site, target, args[0], args[1], args[2], args[3], args[4], args[5], args[6], args[7], args[8], args[9], args[10], args[11]); }; case 13: return (ops, binder, target, args) => { var site = ops.GetOrCreateSite<Func<CallSite, object, object, object, object, object, object, object, object, object, object, object, object, object, object, object>>(binder); return site.Target(site, target, args[0], args[1], args[2], args[3], args[4], args[5], args[6], args[7], args[8], args[9], args[10], args[11], args[12]); }; case 14: return (ops, binder, target, args) => { var site = ops.GetOrCreateSite<Func<CallSite, object, object, object, object, object, object, object, object, object, object, object, object, object, object, object, object>>(binder); return site.Target(site, target, args[0], args[1], args[2], args[3], args[4], args[5], args[6], args[7], args[8], args[9], args[10], args[11], args[12], args[13]); }; #endregion } return null; } } }
58.51875
207
0.533696
[ "Apache-2.0" ]
DjArt/dlr
Src/Microsoft.Scripting/Runtime/DynamicOperations.Generated.cs
9,365
C#
namespace EAuction.Order.Domain.Entities.Base { public interface IEntity { public int Id { get; } } }
17.428571
46
0.622951
[ "MIT" ]
berkayersoyy/e-auction
EAuction.Order.Domain/Entities/Base/IEntity.cs
124
C#
using scrapy.net; using Microsoft.Extensions.Logging; public class QuoteSpider : Spider<IResponse> { private readonly ILogger<QuoteSpider> logger; public override string Name => "quotes"; public override string StartUrl => "http://quotes.toscrape.com/tag/humor/"; public QuoteSpider(ILogger<QuoteSpider> logger) : base() { this.logger = logger; Pipelines = new List<Type> { typeof(UploadPipelineItem), typeof(CleanupPipelineItem) }; } public override async Task<object?> StartRequestsAsync(CancellationToken cancellationToken = default) { logger.LogDebug("Start Requests"); var request = GetRequest<HtmlRequest>(); request.Url = StartUrl; request.CallBack = () => ParseAsync(request, cancellationToken: cancellationToken); return await request.ExecuteAsync(); } public override async Task<object?> ParseAsync(BaseRequest response, CancellationToken cancellationToken = default) { logger.LogInformation("Parsed"); var htmlResponse = (HtmlRequest)response; foreach(var quote in htmlResponse.Html.QuerySelectorAll("div.quote")) { var item = new { Text = quote.QuerySelector("span.text")?.TextContent, Author = quote.QuerySelector("small.author")?.TextContent }; logger.LogInformation($"Text: {item.Text} \nAuthor: {item.Author}\n"); htmlResponse.Yield(item); //yield return item; } var NextPage = htmlResponse.Html.QuerySelector("li.next a")?.GetAttribute("href"); if (NextPage != null) { var uri = new Uri(response.Url); response.Url = uri.GetLeftPart(System.UriPartial.Authority) + NextPage; return await response.ExecuteAsync(); } return await response.EndAsync(); } }
34.482143
119
0.628172
[ "MIT" ]
malisancube/scrapydev
src/samples/QuotesPipeline/QuoteSpider.cs
1,933
C#
using NServiceBus; namespace SFA.DAS.NServiceBus { public abstract class Command : ICommand { } }
13.875
44
0.684685
[ "MIT" ]
SkillsFundingAgency/das-employeraccounts
legacy/SFA.DAS.NServiceBus/Command.cs
113
C#
using FortBlast.UI; using UnityEngine; namespace FortBlast.Spawner { public class PlayerAndBaseSpawner : MonoBehaviour { public Transform player; public GameObject playerBase; private void Start() { player.GetComponent<Rigidbody>().isKinematic = true; player.GetComponent<Rigidbody>().collisionDetectionMode = CollisionDetectionMode.Discrete; Fader.instance.fadeStart += FadeStart; } private void FadeStart() { var playerBaseInstance = Instantiate(playerBase, Vector3.zero, Quaternion.identity); var playerSpawnPoint = playerBaseInstance.transform.GetChild(0).position; player.transform.position = playerSpawnPoint; player.GetComponent<Rigidbody>().isKinematic = false; player.GetComponent<Rigidbody>().collisionDetectionMode = CollisionDetectionMode.ContinuousDynamic; } } }
34
111
0.672269
[ "MIT" ]
Rud156/FortBlast
Assets/Scripts/Spawner/PlayerAndBaseSpawner.cs
954
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("ServiceFabric.ServiceBus.Client")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("ServiceFabric.ServiceBus.Client")] [assembly: AssemblyCopyright("Copyright © 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("f00fb0ee-57ab-4e6a-933d-c02a98e60c9e")]
42.541667
84
0.781587
[ "MIT" ]
gdodd1977/ServiceFabric.ServiceBus
ServiceFabric.ServiceBus.Clients/Properties/AssemblyInfo.cs
1,024
C#
// ------------------------------------------------------------------------------ // <auto-generated> // Generated by Xsd2Code. Version 3.4.0.18239 Microsoft Reciprocal License (Ms-RL) // <NameSpace>Mim.V6301</NameSpace><Collection>Array</Collection><codeType>CSharp</codeType><EnableDataBinding>False</EnableDataBinding><EnableLazyLoading>False</EnableLazyLoading><TrackingChangesEnable>False</TrackingChangesEnable><GenTrackingClasses>False</GenTrackingClasses><HidePrivateFieldInIDE>False</HidePrivateFieldInIDE><EnableSummaryComment>True</EnableSummaryComment><VirtualProp>False</VirtualProp><IncludeSerializeMethod>True</IncludeSerializeMethod><UseBaseClass>False</UseBaseClass><GenBaseClass>False</GenBaseClass><GenerateCloneMethod>True</GenerateCloneMethod><GenerateDataContracts>False</GenerateDataContracts><CodeBaseTag>Net35</CodeBaseTag><SerializeMethodName>Serialize</SerializeMethodName><DeserializeMethodName>Deserialize</DeserializeMethodName><SaveToFileMethodName>SaveToFile</SaveToFileMethodName><LoadFromFileMethodName>LoadFromFile</LoadFromFileMethodName><GenerateXMLAttributes>True</GenerateXMLAttributes><OrderXMLAttrib>False</OrderXMLAttrib><EnableEncoding>False</EnableEncoding><AutomaticProperties>False</AutomaticProperties><GenerateShouldSerialize>False</GenerateShouldSerialize><DisableDebug>False</DisableDebug><PropNameSpecified>Default</PropNameSpecified><Encoder>UTF8</Encoder><CustomUsings></CustomUsings><ExcludeIncludedTypes>True</ExcludeIncludedTypes><EnableInitializeFields>False</EnableInitializeFields> // </auto-generated> // ------------------------------------------------------------------------------ namespace Mim.V6301 { using System; using System.Diagnostics; using System.Xml.Serialization; using System.Collections; using System.Xml.Schema; using System.ComponentModel; using System.IO; using System.Text; [System.CodeDom.Compiler.GeneratedCodeAttribute("Xsd2Code", "3.4.0.18239")] [System.SerializableAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Xml.Serialization.XmlTypeAttribute(Namespace="urn:hl7-org:v3")] public partial class CS_PatientCareProvisionType : CS { private static System.Xml.Serialization.XmlSerializer serializer; private static System.Xml.Serialization.XmlSerializer Serializer { get { if ((serializer == null)) { serializer = new System.Xml.Serialization.XmlSerializer(typeof(CS_PatientCareProvisionType)); } return serializer; } } #region Serialize/Deserialize /// <summary> /// Serializes current CS_PatientCareProvisionType object into an XML document /// </summary> /// <returns>string XML value</returns> public virtual string Serialize() { System.IO.StreamReader streamReader = null; System.IO.MemoryStream memoryStream = null; try { memoryStream = new System.IO.MemoryStream(); Serializer.Serialize(memoryStream, this); memoryStream.Seek(0, System.IO.SeekOrigin.Begin); streamReader = new System.IO.StreamReader(memoryStream); return streamReader.ReadToEnd(); } finally { if ((streamReader != null)) { streamReader.Dispose(); } if ((memoryStream != null)) { memoryStream.Dispose(); } } } /// <summary> /// Deserializes workflow markup into an CS_PatientCareProvisionType object /// </summary> /// <param name="xml">string workflow markup to deserialize</param> /// <param name="obj">Output CS_PatientCareProvisionType object</param> /// <param name="exception">output Exception value if deserialize failed</param> /// <returns>true if this XmlSerializer can deserialize the object; otherwise, false</returns> public static bool Deserialize(string xml, out CS_PatientCareProvisionType obj, out System.Exception exception) { exception = null; obj = default(CS_PatientCareProvisionType); try { obj = Deserialize(xml); return true; } catch (System.Exception ex) { exception = ex; return false; } } public static bool Deserialize(string xml, out CS_PatientCareProvisionType obj) { System.Exception exception = null; return Deserialize(xml, out obj, out exception); } public static CS_PatientCareProvisionType Deserialize(string xml) { System.IO.StringReader stringReader = null; try { stringReader = new System.IO.StringReader(xml); return ((CS_PatientCareProvisionType)(Serializer.Deserialize(System.Xml.XmlReader.Create(stringReader)))); } finally { if ((stringReader != null)) { stringReader.Dispose(); } } } /// <summary> /// Serializes current CS_PatientCareProvisionType object into file /// </summary> /// <param name="fileName">full path of outupt xml file</param> /// <param name="exception">output Exception value if failed</param> /// <returns>true if can serialize and save into file; otherwise, false</returns> public virtual bool SaveToFile(string fileName, out System.Exception exception) { exception = null; try { SaveToFile(fileName); return true; } catch (System.Exception e) { exception = e; return false; } } public virtual void SaveToFile(string fileName) { System.IO.StreamWriter streamWriter = null; try { string xmlString = Serialize(); System.IO.FileInfo xmlFile = new System.IO.FileInfo(fileName); streamWriter = xmlFile.CreateText(); streamWriter.WriteLine(xmlString); streamWriter.Close(); } finally { if ((streamWriter != null)) { streamWriter.Dispose(); } } } /// <summary> /// Deserializes xml markup from file into an CS_PatientCareProvisionType object /// </summary> /// <param name="fileName">string xml file to load and deserialize</param> /// <param name="obj">Output CS_PatientCareProvisionType object</param> /// <param name="exception">output Exception value if deserialize failed</param> /// <returns>true if this XmlSerializer can deserialize the object; otherwise, false</returns> public static bool LoadFromFile(string fileName, out CS_PatientCareProvisionType obj, out System.Exception exception) { exception = null; obj = default(CS_PatientCareProvisionType); try { obj = LoadFromFile(fileName); return true; } catch (System.Exception ex) { exception = ex; return false; } } public static bool LoadFromFile(string fileName, out CS_PatientCareProvisionType obj) { System.Exception exception = null; return LoadFromFile(fileName, out obj, out exception); } public static CS_PatientCareProvisionType LoadFromFile(string fileName) { System.IO.FileStream file = null; System.IO.StreamReader sr = null; try { file = new System.IO.FileStream(fileName, FileMode.Open, FileAccess.Read); sr = new System.IO.StreamReader(file); string xmlString = sr.ReadToEnd(); sr.Close(); file.Close(); return Deserialize(xmlString); } finally { if ((file != null)) { file.Dispose(); } if ((sr != null)) { sr.Dispose(); } } } #endregion #region Clone method /// <summary> /// Create a clone of this CS_PatientCareProvisionType object /// </summary> public virtual CS_PatientCareProvisionType Clone() { return ((CS_PatientCareProvisionType)(this.MemberwiseClone())); } #endregion } }
46.746032
1,358
0.595586
[ "MIT" ]
Kusnaditjung/MimDms
src/Mim.V6301/Generated/CS_PatientCareProvisionType.cs
8,835
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 auditmanager-2017-07-25.normal.json service model. */ using System; using System.Threading; using System.Threading.Tasks; using System.Collections.Generic; using Amazon.Runtime; using Amazon.AuditManager.Model; namespace Amazon.AuditManager { /// <summary> /// Interface for accessing AuditManager /// /// Welcome to the Audit Manager API reference. This guide is for developers who need /// detailed information about the Audit Manager API operations, data types, and errors. /// /// /// /// <para> /// Audit Manager is a service that provides automated evidence collection so that you /// can continually audit your Amazon Web Services usage. You can use it to assess the /// effectiveness of your controls, manage risk, and simplify compliance. /// </para> /// /// <para> /// Audit Manager provides prebuilt frameworks that structure and automate assessments /// for a given compliance standard. Frameworks include a prebuilt collection of controls /// with descriptions and testing procedures. These controls are grouped according to /// the requirements of the specified compliance standard or regulation. You can also /// customize frameworks and controls to support internal audits with specific requirements. /// /// </para> /// /// <para> /// Use the following links to get started with the Audit Manager API: /// </para> /// <ul> <li> /// <para> /// <a href="https://docs.aws.amazon.com/audit-manager/latest/APIReference/API_Operations.html">Actions</a>: /// An alphabetical list of all Audit Manager API operations. /// </para> /// </li> <li> /// <para> /// <a href="https://docs.aws.amazon.com/audit-manager/latest/APIReference/API_Types.html">Data /// types</a>: An alphabetical list of all Audit Manager data types. /// </para> /// </li> <li> /// <para> /// <a href="https://docs.aws.amazon.com/audit-manager/latest/APIReference/CommonParameters.html">Common /// parameters</a>: Parameters that all Query operations can use. /// </para> /// </li> <li> /// <para> /// <a href="https://docs.aws.amazon.com/audit-manager/latest/APIReference/CommonErrors.html">Common /// errors</a>: Client and server errors that all operations can return. /// </para> /// </li> </ul> /// <para> /// If you're new to Audit Manager, we recommend that you review the <a href="https://docs.aws.amazon.com/audit-manager/latest/userguide/what-is.html"> /// Audit Manager User Guide</a>. /// </para> /// </summary> public partial interface IAmazonAuditManager : IAmazonService, IDisposable { #if AWS_ASYNC_ENUMERABLES_API /// <summary> /// Paginators for the service /// </summary> IAuditManagerPaginatorFactory Paginators { get; } #endif #region AssociateAssessmentReportEvidenceFolder /// <summary> /// Associates an evidence folder to an assessment report in a Audit Manager assessment. /// </summary> /// <param name="request">Container for the necessary parameters to execute the AssociateAssessmentReportEvidenceFolder service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the AssociateAssessmentReportEvidenceFolder service method, as returned by AuditManager.</returns> /// <exception cref="Amazon.AuditManager.Model.AccessDeniedException"> /// Your account isn't registered with Audit Manager. Check the delegated administrator /// setup on the Audit Manager settings page, and try again. /// </exception> /// <exception cref="Amazon.AuditManager.Model.InternalServerException"> /// An internal service error occurred during the processing of your request. Try again /// later. /// </exception> /// <exception cref="Amazon.AuditManager.Model.ResourceNotFoundException"> /// The resource that's specified in the request can't be found. /// </exception> /// <exception cref="Amazon.AuditManager.Model.ValidationException"> /// The request has invalid or missing parameters. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/AssociateAssessmentReportEvidenceFolder">REST API Reference for AssociateAssessmentReportEvidenceFolder Operation</seealso> Task<AssociateAssessmentReportEvidenceFolderResponse> AssociateAssessmentReportEvidenceFolderAsync(AssociateAssessmentReportEvidenceFolderRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region BatchAssociateAssessmentReportEvidence /// <summary> /// Associates a list of evidence to an assessment report in an Audit Manager assessment. /// </summary> /// <param name="request">Container for the necessary parameters to execute the BatchAssociateAssessmentReportEvidence service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the BatchAssociateAssessmentReportEvidence service method, as returned by AuditManager.</returns> /// <exception cref="Amazon.AuditManager.Model.AccessDeniedException"> /// Your account isn't registered with Audit Manager. Check the delegated administrator /// setup on the Audit Manager settings page, and try again. /// </exception> /// <exception cref="Amazon.AuditManager.Model.InternalServerException"> /// An internal service error occurred during the processing of your request. Try again /// later. /// </exception> /// <exception cref="Amazon.AuditManager.Model.ResourceNotFoundException"> /// The resource that's specified in the request can't be found. /// </exception> /// <exception cref="Amazon.AuditManager.Model.ValidationException"> /// The request has invalid or missing parameters. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/BatchAssociateAssessmentReportEvidence">REST API Reference for BatchAssociateAssessmentReportEvidence Operation</seealso> Task<BatchAssociateAssessmentReportEvidenceResponse> BatchAssociateAssessmentReportEvidenceAsync(BatchAssociateAssessmentReportEvidenceRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region BatchCreateDelegationByAssessment /// <summary> /// Creates a batch of delegations for an assessment in Audit Manager. /// </summary> /// <param name="request">Container for the necessary parameters to execute the BatchCreateDelegationByAssessment service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the BatchCreateDelegationByAssessment service method, as returned by AuditManager.</returns> /// <exception cref="Amazon.AuditManager.Model.AccessDeniedException"> /// Your account isn't registered with Audit Manager. Check the delegated administrator /// setup on the Audit Manager settings page, and try again. /// </exception> /// <exception cref="Amazon.AuditManager.Model.InternalServerException"> /// An internal service error occurred during the processing of your request. Try again /// later. /// </exception> /// <exception cref="Amazon.AuditManager.Model.ResourceNotFoundException"> /// The resource that's specified in the request can't be found. /// </exception> /// <exception cref="Amazon.AuditManager.Model.ValidationException"> /// The request has invalid or missing parameters. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/BatchCreateDelegationByAssessment">REST API Reference for BatchCreateDelegationByAssessment Operation</seealso> Task<BatchCreateDelegationByAssessmentResponse> BatchCreateDelegationByAssessmentAsync(BatchCreateDelegationByAssessmentRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region BatchDeleteDelegationByAssessment /// <summary> /// Deletes a batch of delegations for an assessment in Audit Manager. /// </summary> /// <param name="request">Container for the necessary parameters to execute the BatchDeleteDelegationByAssessment service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the BatchDeleteDelegationByAssessment service method, as returned by AuditManager.</returns> /// <exception cref="Amazon.AuditManager.Model.AccessDeniedException"> /// Your account isn't registered with Audit Manager. Check the delegated administrator /// setup on the Audit Manager settings page, and try again. /// </exception> /// <exception cref="Amazon.AuditManager.Model.InternalServerException"> /// An internal service error occurred during the processing of your request. Try again /// later. /// </exception> /// <exception cref="Amazon.AuditManager.Model.ResourceNotFoundException"> /// The resource that's specified in the request can't be found. /// </exception> /// <exception cref="Amazon.AuditManager.Model.ValidationException"> /// The request has invalid or missing parameters. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/BatchDeleteDelegationByAssessment">REST API Reference for BatchDeleteDelegationByAssessment Operation</seealso> Task<BatchDeleteDelegationByAssessmentResponse> BatchDeleteDelegationByAssessmentAsync(BatchDeleteDelegationByAssessmentRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region BatchDisassociateAssessmentReportEvidence /// <summary> /// Disassociates a list of evidence from an assessment report in Audit Manager. /// </summary> /// <param name="request">Container for the necessary parameters to execute the BatchDisassociateAssessmentReportEvidence service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the BatchDisassociateAssessmentReportEvidence service method, as returned by AuditManager.</returns> /// <exception cref="Amazon.AuditManager.Model.AccessDeniedException"> /// Your account isn't registered with Audit Manager. Check the delegated administrator /// setup on the Audit Manager settings page, and try again. /// </exception> /// <exception cref="Amazon.AuditManager.Model.InternalServerException"> /// An internal service error occurred during the processing of your request. Try again /// later. /// </exception> /// <exception cref="Amazon.AuditManager.Model.ResourceNotFoundException"> /// The resource that's specified in the request can't be found. /// </exception> /// <exception cref="Amazon.AuditManager.Model.ValidationException"> /// The request has invalid or missing parameters. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/BatchDisassociateAssessmentReportEvidence">REST API Reference for BatchDisassociateAssessmentReportEvidence Operation</seealso> Task<BatchDisassociateAssessmentReportEvidenceResponse> BatchDisassociateAssessmentReportEvidenceAsync(BatchDisassociateAssessmentReportEvidenceRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region BatchImportEvidenceToAssessmentControl /// <summary> /// Uploads one or more pieces of evidence to a control in an Audit Manager assessment. /// </summary> /// <param name="request">Container for the necessary parameters to execute the BatchImportEvidenceToAssessmentControl service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the BatchImportEvidenceToAssessmentControl service method, as returned by AuditManager.</returns> /// <exception cref="Amazon.AuditManager.Model.AccessDeniedException"> /// Your account isn't registered with Audit Manager. Check the delegated administrator /// setup on the Audit Manager settings page, and try again. /// </exception> /// <exception cref="Amazon.AuditManager.Model.InternalServerException"> /// An internal service error occurred during the processing of your request. Try again /// later. /// </exception> /// <exception cref="Amazon.AuditManager.Model.ResourceNotFoundException"> /// The resource that's specified in the request can't be found. /// </exception> /// <exception cref="Amazon.AuditManager.Model.ValidationException"> /// The request has invalid or missing parameters. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/BatchImportEvidenceToAssessmentControl">REST API Reference for BatchImportEvidenceToAssessmentControl Operation</seealso> Task<BatchImportEvidenceToAssessmentControlResponse> BatchImportEvidenceToAssessmentControlAsync(BatchImportEvidenceToAssessmentControlRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region CreateAssessment /// <summary> /// Creates an assessment in Audit Manager. /// </summary> /// <param name="request">Container for the necessary parameters to execute the CreateAssessment service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the CreateAssessment service method, as returned by AuditManager.</returns> /// <exception cref="Amazon.AuditManager.Model.AccessDeniedException"> /// Your account isn't registered with Audit Manager. Check the delegated administrator /// setup on the Audit Manager settings page, and try again. /// </exception> /// <exception cref="Amazon.AuditManager.Model.InternalServerException"> /// An internal service error occurred during the processing of your request. Try again /// later. /// </exception> /// <exception cref="Amazon.AuditManager.Model.ResourceNotFoundException"> /// The resource that's specified in the request can't be found. /// </exception> /// <exception cref="Amazon.AuditManager.Model.ValidationException"> /// The request has invalid or missing parameters. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/CreateAssessment">REST API Reference for CreateAssessment Operation</seealso> Task<CreateAssessmentResponse> CreateAssessmentAsync(CreateAssessmentRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region CreateAssessmentFramework /// <summary> /// Creates a custom framework in Audit Manager. /// </summary> /// <param name="request">Container for the necessary parameters to execute the CreateAssessmentFramework service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the CreateAssessmentFramework service method, as returned by AuditManager.</returns> /// <exception cref="Amazon.AuditManager.Model.AccessDeniedException"> /// Your account isn't registered with Audit Manager. Check the delegated administrator /// setup on the Audit Manager settings page, and try again. /// </exception> /// <exception cref="Amazon.AuditManager.Model.InternalServerException"> /// An internal service error occurred during the processing of your request. Try again /// later. /// </exception> /// <exception cref="Amazon.AuditManager.Model.ResourceNotFoundException"> /// The resource that's specified in the request can't be found. /// </exception> /// <exception cref="Amazon.AuditManager.Model.ValidationException"> /// The request has invalid or missing parameters. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/CreateAssessmentFramework">REST API Reference for CreateAssessmentFramework Operation</seealso> Task<CreateAssessmentFrameworkResponse> CreateAssessmentFrameworkAsync(CreateAssessmentFrameworkRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region CreateAssessmentReport /// <summary> /// Creates an assessment report for the specified assessment. /// </summary> /// <param name="request">Container for the necessary parameters to execute the CreateAssessmentReport service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the CreateAssessmentReport service method, as returned by AuditManager.</returns> /// <exception cref="Amazon.AuditManager.Model.AccessDeniedException"> /// Your account isn't registered with Audit Manager. Check the delegated administrator /// setup on the Audit Manager settings page, and try again. /// </exception> /// <exception cref="Amazon.AuditManager.Model.InternalServerException"> /// An internal service error occurred during the processing of your request. Try again /// later. /// </exception> /// <exception cref="Amazon.AuditManager.Model.ResourceNotFoundException"> /// The resource that's specified in the request can't be found. /// </exception> /// <exception cref="Amazon.AuditManager.Model.ValidationException"> /// The request has invalid or missing parameters. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/CreateAssessmentReport">REST API Reference for CreateAssessmentReport Operation</seealso> Task<CreateAssessmentReportResponse> CreateAssessmentReportAsync(CreateAssessmentReportRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region CreateControl /// <summary> /// Creates a new custom control in Audit Manager. /// </summary> /// <param name="request">Container for the necessary parameters to execute the CreateControl service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the CreateControl service method, as returned by AuditManager.</returns> /// <exception cref="Amazon.AuditManager.Model.AccessDeniedException"> /// Your account isn't registered with Audit Manager. Check the delegated administrator /// setup on the Audit Manager settings page, and try again. /// </exception> /// <exception cref="Amazon.AuditManager.Model.InternalServerException"> /// An internal service error occurred during the processing of your request. Try again /// later. /// </exception> /// <exception cref="Amazon.AuditManager.Model.ResourceNotFoundException"> /// The resource that's specified in the request can't be found. /// </exception> /// <exception cref="Amazon.AuditManager.Model.ValidationException"> /// The request has invalid or missing parameters. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/CreateControl">REST API Reference for CreateControl Operation</seealso> Task<CreateControlResponse> CreateControlAsync(CreateControlRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region DeleteAssessment /// <summary> /// Deletes an assessment in Audit Manager. /// </summary> /// <param name="request">Container for the necessary parameters to execute the DeleteAssessment service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the DeleteAssessment service method, as returned by AuditManager.</returns> /// <exception cref="Amazon.AuditManager.Model.AccessDeniedException"> /// Your account isn't registered with Audit Manager. Check the delegated administrator /// setup on the Audit Manager settings page, and try again. /// </exception> /// <exception cref="Amazon.AuditManager.Model.InternalServerException"> /// An internal service error occurred during the processing of your request. Try again /// later. /// </exception> /// <exception cref="Amazon.AuditManager.Model.ResourceNotFoundException"> /// The resource that's specified in the request can't be found. /// </exception> /// <exception cref="Amazon.AuditManager.Model.ValidationException"> /// The request has invalid or missing parameters. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/DeleteAssessment">REST API Reference for DeleteAssessment Operation</seealso> Task<DeleteAssessmentResponse> DeleteAssessmentAsync(DeleteAssessmentRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region DeleteAssessmentFramework /// <summary> /// Deletes a custom framework in Audit Manager. /// </summary> /// <param name="request">Container for the necessary parameters to execute the DeleteAssessmentFramework service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the DeleteAssessmentFramework service method, as returned by AuditManager.</returns> /// <exception cref="Amazon.AuditManager.Model.AccessDeniedException"> /// Your account isn't registered with Audit Manager. Check the delegated administrator /// setup on the Audit Manager settings page, and try again. /// </exception> /// <exception cref="Amazon.AuditManager.Model.InternalServerException"> /// An internal service error occurred during the processing of your request. Try again /// later. /// </exception> /// <exception cref="Amazon.AuditManager.Model.ResourceNotFoundException"> /// The resource that's specified in the request can't be found. /// </exception> /// <exception cref="Amazon.AuditManager.Model.ValidationException"> /// The request has invalid or missing parameters. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/DeleteAssessmentFramework">REST API Reference for DeleteAssessmentFramework Operation</seealso> Task<DeleteAssessmentFrameworkResponse> DeleteAssessmentFrameworkAsync(DeleteAssessmentFrameworkRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region DeleteAssessmentFrameworkShare /// <summary> /// Deletes a share request for a custom framework in Audit Manager. /// </summary> /// <param name="request">Container for the necessary parameters to execute the DeleteAssessmentFrameworkShare service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the DeleteAssessmentFrameworkShare service method, as returned by AuditManager.</returns> /// <exception cref="Amazon.AuditManager.Model.AccessDeniedException"> /// Your account isn't registered with Audit Manager. Check the delegated administrator /// setup on the Audit Manager settings page, and try again. /// </exception> /// <exception cref="Amazon.AuditManager.Model.InternalServerException"> /// An internal service error occurred during the processing of your request. Try again /// later. /// </exception> /// <exception cref="Amazon.AuditManager.Model.ResourceNotFoundException"> /// The resource that's specified in the request can't be found. /// </exception> /// <exception cref="Amazon.AuditManager.Model.ValidationException"> /// The request has invalid or missing parameters. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/DeleteAssessmentFrameworkShare">REST API Reference for DeleteAssessmentFrameworkShare Operation</seealso> Task<DeleteAssessmentFrameworkShareResponse> DeleteAssessmentFrameworkShareAsync(DeleteAssessmentFrameworkShareRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region DeleteAssessmentReport /// <summary> /// Deletes an assessment report from an assessment in Audit Manager. /// </summary> /// <param name="request">Container for the necessary parameters to execute the DeleteAssessmentReport service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the DeleteAssessmentReport service method, as returned by AuditManager.</returns> /// <exception cref="Amazon.AuditManager.Model.AccessDeniedException"> /// Your account isn't registered with Audit Manager. Check the delegated administrator /// setup on the Audit Manager settings page, and try again. /// </exception> /// <exception cref="Amazon.AuditManager.Model.InternalServerException"> /// An internal service error occurred during the processing of your request. Try again /// later. /// </exception> /// <exception cref="Amazon.AuditManager.Model.ResourceNotFoundException"> /// The resource that's specified in the request can't be found. /// </exception> /// <exception cref="Amazon.AuditManager.Model.ValidationException"> /// The request has invalid or missing parameters. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/DeleteAssessmentReport">REST API Reference for DeleteAssessmentReport Operation</seealso> Task<DeleteAssessmentReportResponse> DeleteAssessmentReportAsync(DeleteAssessmentReportRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region DeleteControl /// <summary> /// Deletes a custom control in Audit Manager. /// </summary> /// <param name="request">Container for the necessary parameters to execute the DeleteControl service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the DeleteControl service method, as returned by AuditManager.</returns> /// <exception cref="Amazon.AuditManager.Model.AccessDeniedException"> /// Your account isn't registered with Audit Manager. Check the delegated administrator /// setup on the Audit Manager settings page, and try again. /// </exception> /// <exception cref="Amazon.AuditManager.Model.InternalServerException"> /// An internal service error occurred during the processing of your request. Try again /// later. /// </exception> /// <exception cref="Amazon.AuditManager.Model.ResourceNotFoundException"> /// The resource that's specified in the request can't be found. /// </exception> /// <exception cref="Amazon.AuditManager.Model.ValidationException"> /// The request has invalid or missing parameters. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/DeleteControl">REST API Reference for DeleteControl Operation</seealso> Task<DeleteControlResponse> DeleteControlAsync(DeleteControlRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region DeregisterAccount /// <summary> /// Deregisters an account in Audit Manager. /// </summary> /// <param name="request">Container for the necessary parameters to execute the DeregisterAccount service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the DeregisterAccount service method, as returned by AuditManager.</returns> /// <exception cref="Amazon.AuditManager.Model.AccessDeniedException"> /// Your account isn't registered with Audit Manager. Check the delegated administrator /// setup on the Audit Manager settings page, and try again. /// </exception> /// <exception cref="Amazon.AuditManager.Model.InternalServerException"> /// An internal service error occurred during the processing of your request. Try again /// later. /// </exception> /// <exception cref="Amazon.AuditManager.Model.ResourceNotFoundException"> /// The resource that's specified in the request can't be found. /// </exception> /// <exception cref="Amazon.AuditManager.Model.ValidationException"> /// The request has invalid or missing parameters. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/DeregisterAccount">REST API Reference for DeregisterAccount Operation</seealso> Task<DeregisterAccountResponse> DeregisterAccountAsync(DeregisterAccountRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region DeregisterOrganizationAdminAccount /// <summary> /// Removes the specified member Amazon Web Services account as a delegated administrator /// for Audit Manager. /// /// <important> /// <para> /// When you remove a delegated administrator from your Audit Manager settings, you continue /// to have access to the evidence that you previously collected under that account. This /// is also the case when you deregister a delegated administrator from Audit Manager. /// However, Audit Manager will stop collecting and attaching evidence to that delegated /// administrator account moving forward. /// </para> /// </important> /// </summary> /// <param name="request">Container for the necessary parameters to execute the DeregisterOrganizationAdminAccount service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the DeregisterOrganizationAdminAccount service method, as returned by AuditManager.</returns> /// <exception cref="Amazon.AuditManager.Model.AccessDeniedException"> /// Your account isn't registered with Audit Manager. Check the delegated administrator /// setup on the Audit Manager settings page, and try again. /// </exception> /// <exception cref="Amazon.AuditManager.Model.InternalServerException"> /// An internal service error occurred during the processing of your request. Try again /// later. /// </exception> /// <exception cref="Amazon.AuditManager.Model.ResourceNotFoundException"> /// The resource that's specified in the request can't be found. /// </exception> /// <exception cref="Amazon.AuditManager.Model.ValidationException"> /// The request has invalid or missing parameters. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/DeregisterOrganizationAdminAccount">REST API Reference for DeregisterOrganizationAdminAccount Operation</seealso> Task<DeregisterOrganizationAdminAccountResponse> DeregisterOrganizationAdminAccountAsync(DeregisterOrganizationAdminAccountRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region DisassociateAssessmentReportEvidenceFolder /// <summary> /// Disassociates an evidence folder from the specified assessment report in Audit Manager. /// </summary> /// <param name="request">Container for the necessary parameters to execute the DisassociateAssessmentReportEvidenceFolder service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the DisassociateAssessmentReportEvidenceFolder service method, as returned by AuditManager.</returns> /// <exception cref="Amazon.AuditManager.Model.AccessDeniedException"> /// Your account isn't registered with Audit Manager. Check the delegated administrator /// setup on the Audit Manager settings page, and try again. /// </exception> /// <exception cref="Amazon.AuditManager.Model.InternalServerException"> /// An internal service error occurred during the processing of your request. Try again /// later. /// </exception> /// <exception cref="Amazon.AuditManager.Model.ResourceNotFoundException"> /// The resource that's specified in the request can't be found. /// </exception> /// <exception cref="Amazon.AuditManager.Model.ValidationException"> /// The request has invalid or missing parameters. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/DisassociateAssessmentReportEvidenceFolder">REST API Reference for DisassociateAssessmentReportEvidenceFolder Operation</seealso> Task<DisassociateAssessmentReportEvidenceFolderResponse> DisassociateAssessmentReportEvidenceFolderAsync(DisassociateAssessmentReportEvidenceFolderRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region GetAccountStatus /// <summary> /// Returns the registration status of an account in Audit Manager. /// </summary> /// <param name="request">Container for the necessary parameters to execute the GetAccountStatus service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the GetAccountStatus service method, as returned by AuditManager.</returns> /// <exception cref="Amazon.AuditManager.Model.InternalServerException"> /// An internal service error occurred during the processing of your request. Try again /// later. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/GetAccountStatus">REST API Reference for GetAccountStatus Operation</seealso> Task<GetAccountStatusResponse> GetAccountStatusAsync(GetAccountStatusRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region GetAssessment /// <summary> /// Returns an assessment from Audit Manager. /// </summary> /// <param name="request">Container for the necessary parameters to execute the GetAssessment service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the GetAssessment service method, as returned by AuditManager.</returns> /// <exception cref="Amazon.AuditManager.Model.AccessDeniedException"> /// Your account isn't registered with Audit Manager. Check the delegated administrator /// setup on the Audit Manager settings page, and try again. /// </exception> /// <exception cref="Amazon.AuditManager.Model.InternalServerException"> /// An internal service error occurred during the processing of your request. Try again /// later. /// </exception> /// <exception cref="Amazon.AuditManager.Model.ResourceNotFoundException"> /// The resource that's specified in the request can't be found. /// </exception> /// <exception cref="Amazon.AuditManager.Model.ValidationException"> /// The request has invalid or missing parameters. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/GetAssessment">REST API Reference for GetAssessment Operation</seealso> Task<GetAssessmentResponse> GetAssessmentAsync(GetAssessmentRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region GetAssessmentFramework /// <summary> /// Returns a framework from Audit Manager. /// </summary> /// <param name="request">Container for the necessary parameters to execute the GetAssessmentFramework service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the GetAssessmentFramework service method, as returned by AuditManager.</returns> /// <exception cref="Amazon.AuditManager.Model.AccessDeniedException"> /// Your account isn't registered with Audit Manager. Check the delegated administrator /// setup on the Audit Manager settings page, and try again. /// </exception> /// <exception cref="Amazon.AuditManager.Model.InternalServerException"> /// An internal service error occurred during the processing of your request. Try again /// later. /// </exception> /// <exception cref="Amazon.AuditManager.Model.ResourceNotFoundException"> /// The resource that's specified in the request can't be found. /// </exception> /// <exception cref="Amazon.AuditManager.Model.ValidationException"> /// The request has invalid or missing parameters. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/GetAssessmentFramework">REST API Reference for GetAssessmentFramework Operation</seealso> Task<GetAssessmentFrameworkResponse> GetAssessmentFrameworkAsync(GetAssessmentFrameworkRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region GetAssessmentReportUrl /// <summary> /// Returns the URL of an assessment report in Audit Manager. /// </summary> /// <param name="request">Container for the necessary parameters to execute the GetAssessmentReportUrl service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the GetAssessmentReportUrl service method, as returned by AuditManager.</returns> /// <exception cref="Amazon.AuditManager.Model.AccessDeniedException"> /// Your account isn't registered with Audit Manager. Check the delegated administrator /// setup on the Audit Manager settings page, and try again. /// </exception> /// <exception cref="Amazon.AuditManager.Model.InternalServerException"> /// An internal service error occurred during the processing of your request. Try again /// later. /// </exception> /// <exception cref="Amazon.AuditManager.Model.ResourceNotFoundException"> /// The resource that's specified in the request can't be found. /// </exception> /// <exception cref="Amazon.AuditManager.Model.ValidationException"> /// The request has invalid or missing parameters. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/GetAssessmentReportUrl">REST API Reference for GetAssessmentReportUrl Operation</seealso> Task<GetAssessmentReportUrlResponse> GetAssessmentReportUrlAsync(GetAssessmentReportUrlRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region GetChangeLogs /// <summary> /// Returns a list of changelogs from Audit Manager. /// </summary> /// <param name="request">Container for the necessary parameters to execute the GetChangeLogs service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the GetChangeLogs service method, as returned by AuditManager.</returns> /// <exception cref="Amazon.AuditManager.Model.AccessDeniedException"> /// Your account isn't registered with Audit Manager. Check the delegated administrator /// setup on the Audit Manager settings page, and try again. /// </exception> /// <exception cref="Amazon.AuditManager.Model.InternalServerException"> /// An internal service error occurred during the processing of your request. Try again /// later. /// </exception> /// <exception cref="Amazon.AuditManager.Model.ResourceNotFoundException"> /// The resource that's specified in the request can't be found. /// </exception> /// <exception cref="Amazon.AuditManager.Model.ValidationException"> /// The request has invalid or missing parameters. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/GetChangeLogs">REST API Reference for GetChangeLogs Operation</seealso> Task<GetChangeLogsResponse> GetChangeLogsAsync(GetChangeLogsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region GetControl /// <summary> /// Returns a control from Audit Manager. /// </summary> /// <param name="request">Container for the necessary parameters to execute the GetControl service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the GetControl service method, as returned by AuditManager.</returns> /// <exception cref="Amazon.AuditManager.Model.AccessDeniedException"> /// Your account isn't registered with Audit Manager. Check the delegated administrator /// setup on the Audit Manager settings page, and try again. /// </exception> /// <exception cref="Amazon.AuditManager.Model.InternalServerException"> /// An internal service error occurred during the processing of your request. Try again /// later. /// </exception> /// <exception cref="Amazon.AuditManager.Model.ResourceNotFoundException"> /// The resource that's specified in the request can't be found. /// </exception> /// <exception cref="Amazon.AuditManager.Model.ValidationException"> /// The request has invalid or missing parameters. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/GetControl">REST API Reference for GetControl Operation</seealso> Task<GetControlResponse> GetControlAsync(GetControlRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region GetDelegations /// <summary> /// Returns a list of delegations from an audit owner to a delegate. /// </summary> /// <param name="request">Container for the necessary parameters to execute the GetDelegations service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the GetDelegations service method, as returned by AuditManager.</returns> /// <exception cref="Amazon.AuditManager.Model.AccessDeniedException"> /// Your account isn't registered with Audit Manager. Check the delegated administrator /// setup on the Audit Manager settings page, and try again. /// </exception> /// <exception cref="Amazon.AuditManager.Model.InternalServerException"> /// An internal service error occurred during the processing of your request. Try again /// later. /// </exception> /// <exception cref="Amazon.AuditManager.Model.ValidationException"> /// The request has invalid or missing parameters. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/GetDelegations">REST API Reference for GetDelegations Operation</seealso> Task<GetDelegationsResponse> GetDelegationsAsync(GetDelegationsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region GetEvidence /// <summary> /// Returns evidence from Audit Manager. /// </summary> /// <param name="request">Container for the necessary parameters to execute the GetEvidence service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the GetEvidence service method, as returned by AuditManager.</returns> /// <exception cref="Amazon.AuditManager.Model.AccessDeniedException"> /// Your account isn't registered with Audit Manager. Check the delegated administrator /// setup on the Audit Manager settings page, and try again. /// </exception> /// <exception cref="Amazon.AuditManager.Model.InternalServerException"> /// An internal service error occurred during the processing of your request. Try again /// later. /// </exception> /// <exception cref="Amazon.AuditManager.Model.ResourceNotFoundException"> /// The resource that's specified in the request can't be found. /// </exception> /// <exception cref="Amazon.AuditManager.Model.ValidationException"> /// The request has invalid or missing parameters. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/GetEvidence">REST API Reference for GetEvidence Operation</seealso> Task<GetEvidenceResponse> GetEvidenceAsync(GetEvidenceRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region GetEvidenceByEvidenceFolder /// <summary> /// Returns all evidence from a specified evidence folder in Audit Manager. /// </summary> /// <param name="request">Container for the necessary parameters to execute the GetEvidenceByEvidenceFolder service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the GetEvidenceByEvidenceFolder service method, as returned by AuditManager.</returns> /// <exception cref="Amazon.AuditManager.Model.AccessDeniedException"> /// Your account isn't registered with Audit Manager. Check the delegated administrator /// setup on the Audit Manager settings page, and try again. /// </exception> /// <exception cref="Amazon.AuditManager.Model.InternalServerException"> /// An internal service error occurred during the processing of your request. Try again /// later. /// </exception> /// <exception cref="Amazon.AuditManager.Model.ResourceNotFoundException"> /// The resource that's specified in the request can't be found. /// </exception> /// <exception cref="Amazon.AuditManager.Model.ValidationException"> /// The request has invalid or missing parameters. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/GetEvidenceByEvidenceFolder">REST API Reference for GetEvidenceByEvidenceFolder Operation</seealso> Task<GetEvidenceByEvidenceFolderResponse> GetEvidenceByEvidenceFolderAsync(GetEvidenceByEvidenceFolderRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region GetEvidenceFolder /// <summary> /// Returns an evidence folder from the specified assessment in Audit Manager. /// </summary> /// <param name="request">Container for the necessary parameters to execute the GetEvidenceFolder service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the GetEvidenceFolder service method, as returned by AuditManager.</returns> /// <exception cref="Amazon.AuditManager.Model.AccessDeniedException"> /// Your account isn't registered with Audit Manager. Check the delegated administrator /// setup on the Audit Manager settings page, and try again. /// </exception> /// <exception cref="Amazon.AuditManager.Model.InternalServerException"> /// An internal service error occurred during the processing of your request. Try again /// later. /// </exception> /// <exception cref="Amazon.AuditManager.Model.ResourceNotFoundException"> /// The resource that's specified in the request can't be found. /// </exception> /// <exception cref="Amazon.AuditManager.Model.ValidationException"> /// The request has invalid or missing parameters. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/GetEvidenceFolder">REST API Reference for GetEvidenceFolder Operation</seealso> Task<GetEvidenceFolderResponse> GetEvidenceFolderAsync(GetEvidenceFolderRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region GetEvidenceFoldersByAssessment /// <summary> /// Returns the evidence folders from a specified assessment in Audit Manager. /// </summary> /// <param name="request">Container for the necessary parameters to execute the GetEvidenceFoldersByAssessment service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the GetEvidenceFoldersByAssessment service method, as returned by AuditManager.</returns> /// <exception cref="Amazon.AuditManager.Model.AccessDeniedException"> /// Your account isn't registered with Audit Manager. Check the delegated administrator /// setup on the Audit Manager settings page, and try again. /// </exception> /// <exception cref="Amazon.AuditManager.Model.InternalServerException"> /// An internal service error occurred during the processing of your request. Try again /// later. /// </exception> /// <exception cref="Amazon.AuditManager.Model.ResourceNotFoundException"> /// The resource that's specified in the request can't be found. /// </exception> /// <exception cref="Amazon.AuditManager.Model.ValidationException"> /// The request has invalid or missing parameters. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/GetEvidenceFoldersByAssessment">REST API Reference for GetEvidenceFoldersByAssessment Operation</seealso> Task<GetEvidenceFoldersByAssessmentResponse> GetEvidenceFoldersByAssessmentAsync(GetEvidenceFoldersByAssessmentRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region GetEvidenceFoldersByAssessmentControl /// <summary> /// Returns a list of evidence folders that are associated with a specified control of /// an assessment in Audit Manager. /// </summary> /// <param name="request">Container for the necessary parameters to execute the GetEvidenceFoldersByAssessmentControl service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the GetEvidenceFoldersByAssessmentControl service method, as returned by AuditManager.</returns> /// <exception cref="Amazon.AuditManager.Model.AccessDeniedException"> /// Your account isn't registered with Audit Manager. Check the delegated administrator /// setup on the Audit Manager settings page, and try again. /// </exception> /// <exception cref="Amazon.AuditManager.Model.InternalServerException"> /// An internal service error occurred during the processing of your request. Try again /// later. /// </exception> /// <exception cref="Amazon.AuditManager.Model.ResourceNotFoundException"> /// The resource that's specified in the request can't be found. /// </exception> /// <exception cref="Amazon.AuditManager.Model.ValidationException"> /// The request has invalid or missing parameters. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/GetEvidenceFoldersByAssessmentControl">REST API Reference for GetEvidenceFoldersByAssessmentControl Operation</seealso> Task<GetEvidenceFoldersByAssessmentControlResponse> GetEvidenceFoldersByAssessmentControlAsync(GetEvidenceFoldersByAssessmentControlRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region GetInsights /// <summary> /// Gets the latest analytics data for all your current active assessments. /// </summary> /// <param name="request">Container for the necessary parameters to execute the GetInsights service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the GetInsights service method, as returned by AuditManager.</returns> /// <exception cref="Amazon.AuditManager.Model.AccessDeniedException"> /// Your account isn't registered with Audit Manager. Check the delegated administrator /// setup on the Audit Manager settings page, and try again. /// </exception> /// <exception cref="Amazon.AuditManager.Model.InternalServerException"> /// An internal service error occurred during the processing of your request. Try again /// later. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/GetInsights">REST API Reference for GetInsights Operation</seealso> Task<GetInsightsResponse> GetInsightsAsync(GetInsightsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region GetInsightsByAssessment /// <summary> /// Gets the latest analytics data for a specific active assessment. /// </summary> /// <param name="request">Container for the necessary parameters to execute the GetInsightsByAssessment service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the GetInsightsByAssessment service method, as returned by AuditManager.</returns> /// <exception cref="Amazon.AuditManager.Model.AccessDeniedException"> /// Your account isn't registered with Audit Manager. Check the delegated administrator /// setup on the Audit Manager settings page, and try again. /// </exception> /// <exception cref="Amazon.AuditManager.Model.InternalServerException"> /// An internal service error occurred during the processing of your request. Try again /// later. /// </exception> /// <exception cref="Amazon.AuditManager.Model.ResourceNotFoundException"> /// The resource that's specified in the request can't be found. /// </exception> /// <exception cref="Amazon.AuditManager.Model.ValidationException"> /// The request has invalid or missing parameters. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/GetInsightsByAssessment">REST API Reference for GetInsightsByAssessment Operation</seealso> Task<GetInsightsByAssessmentResponse> GetInsightsByAssessmentAsync(GetInsightsByAssessmentRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region GetOrganizationAdminAccount /// <summary> /// Returns the name of the delegated Amazon Web Services administrator account for the /// organization. /// </summary> /// <param name="request">Container for the necessary parameters to execute the GetOrganizationAdminAccount service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the GetOrganizationAdminAccount service method, as returned by AuditManager.</returns> /// <exception cref="Amazon.AuditManager.Model.AccessDeniedException"> /// Your account isn't registered with Audit Manager. Check the delegated administrator /// setup on the Audit Manager settings page, and try again. /// </exception> /// <exception cref="Amazon.AuditManager.Model.InternalServerException"> /// An internal service error occurred during the processing of your request. Try again /// later. /// </exception> /// <exception cref="Amazon.AuditManager.Model.ResourceNotFoundException"> /// The resource that's specified in the request can't be found. /// </exception> /// <exception cref="Amazon.AuditManager.Model.ValidationException"> /// The request has invalid or missing parameters. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/GetOrganizationAdminAccount">REST API Reference for GetOrganizationAdminAccount Operation</seealso> Task<GetOrganizationAdminAccountResponse> GetOrganizationAdminAccountAsync(GetOrganizationAdminAccountRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region GetServicesInScope /// <summary> /// Returns a list of the in-scope Amazon Web Services services for the specified assessment. /// </summary> /// <param name="request">Container for the necessary parameters to execute the GetServicesInScope service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the GetServicesInScope service method, as returned by AuditManager.</returns> /// <exception cref="Amazon.AuditManager.Model.AccessDeniedException"> /// Your account isn't registered with Audit Manager. Check the delegated administrator /// setup on the Audit Manager settings page, and try again. /// </exception> /// <exception cref="Amazon.AuditManager.Model.InternalServerException"> /// An internal service error occurred during the processing of your request. Try again /// later. /// </exception> /// <exception cref="Amazon.AuditManager.Model.ValidationException"> /// The request has invalid or missing parameters. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/GetServicesInScope">REST API Reference for GetServicesInScope Operation</seealso> Task<GetServicesInScopeResponse> GetServicesInScopeAsync(GetServicesInScopeRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region GetSettings /// <summary> /// Returns the settings for the specified Amazon Web Services account. /// </summary> /// <param name="request">Container for the necessary parameters to execute the GetSettings service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the GetSettings service method, as returned by AuditManager.</returns> /// <exception cref="Amazon.AuditManager.Model.AccessDeniedException"> /// Your account isn't registered with Audit Manager. Check the delegated administrator /// setup on the Audit Manager settings page, and try again. /// </exception> /// <exception cref="Amazon.AuditManager.Model.InternalServerException"> /// An internal service error occurred during the processing of your request. Try again /// later. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/GetSettings">REST API Reference for GetSettings Operation</seealso> Task<GetSettingsResponse> GetSettingsAsync(GetSettingsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region ListAssessmentControlInsightsByControlDomain /// <summary> /// Lists the latest analytics data for controls within a specific control domain and /// a specific active assessment. /// /// <note> /// <para> /// Control insights are listed only if the control belongs to the control domain and /// assessment that was specified. Moreover, the control must have collected evidence /// on the <code>lastUpdated</code> date of <code>controlInsightsByAssessment</code>. /// If neither of these conditions are met, no data is listed for that control. /// </para> /// </note> /// </summary> /// <param name="request">Container for the necessary parameters to execute the ListAssessmentControlInsightsByControlDomain service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the ListAssessmentControlInsightsByControlDomain service method, as returned by AuditManager.</returns> /// <exception cref="Amazon.AuditManager.Model.AccessDeniedException"> /// Your account isn't registered with Audit Manager. Check the delegated administrator /// setup on the Audit Manager settings page, and try again. /// </exception> /// <exception cref="Amazon.AuditManager.Model.InternalServerException"> /// An internal service error occurred during the processing of your request. Try again /// later. /// </exception> /// <exception cref="Amazon.AuditManager.Model.ResourceNotFoundException"> /// The resource that's specified in the request can't be found. /// </exception> /// <exception cref="Amazon.AuditManager.Model.ValidationException"> /// The request has invalid or missing parameters. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/ListAssessmentControlInsightsByControlDomain">REST API Reference for ListAssessmentControlInsightsByControlDomain Operation</seealso> Task<ListAssessmentControlInsightsByControlDomainResponse> ListAssessmentControlInsightsByControlDomainAsync(ListAssessmentControlInsightsByControlDomainRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region ListAssessmentFrameworks /// <summary> /// Returns a list of the frameworks that are available in the Audit Manager framework /// library. /// </summary> /// <param name="request">Container for the necessary parameters to execute the ListAssessmentFrameworks service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the ListAssessmentFrameworks service method, as returned by AuditManager.</returns> /// <exception cref="Amazon.AuditManager.Model.AccessDeniedException"> /// Your account isn't registered with Audit Manager. Check the delegated administrator /// setup on the Audit Manager settings page, and try again. /// </exception> /// <exception cref="Amazon.AuditManager.Model.InternalServerException"> /// An internal service error occurred during the processing of your request. Try again /// later. /// </exception> /// <exception cref="Amazon.AuditManager.Model.ValidationException"> /// The request has invalid or missing parameters. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/ListAssessmentFrameworks">REST API Reference for ListAssessmentFrameworks Operation</seealso> Task<ListAssessmentFrameworksResponse> ListAssessmentFrameworksAsync(ListAssessmentFrameworksRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region ListAssessmentFrameworkShareRequests /// <summary> /// Returns a list of sent or received share requests for custom frameworks in Audit /// Manager. /// </summary> /// <param name="request">Container for the necessary parameters to execute the ListAssessmentFrameworkShareRequests service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the ListAssessmentFrameworkShareRequests service method, as returned by AuditManager.</returns> /// <exception cref="Amazon.AuditManager.Model.AccessDeniedException"> /// Your account isn't registered with Audit Manager. Check the delegated administrator /// setup on the Audit Manager settings page, and try again. /// </exception> /// <exception cref="Amazon.AuditManager.Model.InternalServerException"> /// An internal service error occurred during the processing of your request. Try again /// later. /// </exception> /// <exception cref="Amazon.AuditManager.Model.ValidationException"> /// The request has invalid or missing parameters. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/ListAssessmentFrameworkShareRequests">REST API Reference for ListAssessmentFrameworkShareRequests Operation</seealso> Task<ListAssessmentFrameworkShareRequestsResponse> ListAssessmentFrameworkShareRequestsAsync(ListAssessmentFrameworkShareRequestsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region ListAssessmentReports /// <summary> /// Returns a list of assessment reports created in Audit Manager. /// </summary> /// <param name="request">Container for the necessary parameters to execute the ListAssessmentReports service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the ListAssessmentReports service method, as returned by AuditManager.</returns> /// <exception cref="Amazon.AuditManager.Model.AccessDeniedException"> /// Your account isn't registered with Audit Manager. Check the delegated administrator /// setup on the Audit Manager settings page, and try again. /// </exception> /// <exception cref="Amazon.AuditManager.Model.InternalServerException"> /// An internal service error occurred during the processing of your request. Try again /// later. /// </exception> /// <exception cref="Amazon.AuditManager.Model.ValidationException"> /// The request has invalid or missing parameters. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/ListAssessmentReports">REST API Reference for ListAssessmentReports Operation</seealso> Task<ListAssessmentReportsResponse> ListAssessmentReportsAsync(ListAssessmentReportsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region ListAssessments /// <summary> /// Returns a list of current and past assessments from Audit Manager. /// </summary> /// <param name="request">Container for the necessary parameters to execute the ListAssessments service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the ListAssessments service method, as returned by AuditManager.</returns> /// <exception cref="Amazon.AuditManager.Model.AccessDeniedException"> /// Your account isn't registered with Audit Manager. Check the delegated administrator /// setup on the Audit Manager settings page, and try again. /// </exception> /// <exception cref="Amazon.AuditManager.Model.InternalServerException"> /// An internal service error occurred during the processing of your request. Try again /// later. /// </exception> /// <exception cref="Amazon.AuditManager.Model.ValidationException"> /// The request has invalid or missing parameters. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/ListAssessments">REST API Reference for ListAssessments Operation</seealso> Task<ListAssessmentsResponse> ListAssessmentsAsync(ListAssessmentsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region ListControlDomainInsights /// <summary> /// Lists the latest analytics data for control domains across all of your active assessments. /// /// /// <note> /// <para> /// A control domain is listed only if at least one of the controls within that domain /// collected evidence on the <code>lastUpdated</code> date of <code>controlDomainInsights</code>. /// If this condition isn’t met, no data is listed for that control domain. /// </para> /// </note> /// </summary> /// <param name="request">Container for the necessary parameters to execute the ListControlDomainInsights service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the ListControlDomainInsights service method, as returned by AuditManager.</returns> /// <exception cref="Amazon.AuditManager.Model.AccessDeniedException"> /// Your account isn't registered with Audit Manager. Check the delegated administrator /// setup on the Audit Manager settings page, and try again. /// </exception> /// <exception cref="Amazon.AuditManager.Model.InternalServerException"> /// An internal service error occurred during the processing of your request. Try again /// later. /// </exception> /// <exception cref="Amazon.AuditManager.Model.ResourceNotFoundException"> /// The resource that's specified in the request can't be found. /// </exception> /// <exception cref="Amazon.AuditManager.Model.ValidationException"> /// The request has invalid or missing parameters. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/ListControlDomainInsights">REST API Reference for ListControlDomainInsights Operation</seealso> Task<ListControlDomainInsightsResponse> ListControlDomainInsightsAsync(ListControlDomainInsightsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region ListControlDomainInsightsByAssessment /// <summary> /// Lists analytics data for control domains within a specified active assessment. /// /// <note> /// <para> /// A control domain is listed only if at least one of the controls within that domain /// collected evidence on the <code>lastUpdated</code> date of <code>controlDomainInsights</code>. /// If this condition isn’t met, no data is listed for that domain. /// </para> /// </note> /// </summary> /// <param name="request">Container for the necessary parameters to execute the ListControlDomainInsightsByAssessment service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the ListControlDomainInsightsByAssessment service method, as returned by AuditManager.</returns> /// <exception cref="Amazon.AuditManager.Model.AccessDeniedException"> /// Your account isn't registered with Audit Manager. Check the delegated administrator /// setup on the Audit Manager settings page, and try again. /// </exception> /// <exception cref="Amazon.AuditManager.Model.InternalServerException"> /// An internal service error occurred during the processing of your request. Try again /// later. /// </exception> /// <exception cref="Amazon.AuditManager.Model.ResourceNotFoundException"> /// The resource that's specified in the request can't be found. /// </exception> /// <exception cref="Amazon.AuditManager.Model.ValidationException"> /// The request has invalid or missing parameters. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/ListControlDomainInsightsByAssessment">REST API Reference for ListControlDomainInsightsByAssessment Operation</seealso> Task<ListControlDomainInsightsByAssessmentResponse> ListControlDomainInsightsByAssessmentAsync(ListControlDomainInsightsByAssessmentRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region ListControlInsightsByControlDomain /// <summary> /// Lists the latest analytics data for controls within a specific control domain across /// all active assessments. /// /// <note> /// <para> /// Control insights are listed only if the control belongs to the control domain that /// was specified and the control collected evidence on the <code>lastUpdated</code> date /// of <code>controlInsightsMetadata</code>. If neither of these conditions are met, no /// data is listed for that control. /// </para> /// </note> /// </summary> /// <param name="request">Container for the necessary parameters to execute the ListControlInsightsByControlDomain service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the ListControlInsightsByControlDomain service method, as returned by AuditManager.</returns> /// <exception cref="Amazon.AuditManager.Model.AccessDeniedException"> /// Your account isn't registered with Audit Manager. Check the delegated administrator /// setup on the Audit Manager settings page, and try again. /// </exception> /// <exception cref="Amazon.AuditManager.Model.InternalServerException"> /// An internal service error occurred during the processing of your request. Try again /// later. /// </exception> /// <exception cref="Amazon.AuditManager.Model.ResourceNotFoundException"> /// The resource that's specified in the request can't be found. /// </exception> /// <exception cref="Amazon.AuditManager.Model.ValidationException"> /// The request has invalid or missing parameters. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/ListControlInsightsByControlDomain">REST API Reference for ListControlInsightsByControlDomain Operation</seealso> Task<ListControlInsightsByControlDomainResponse> ListControlInsightsByControlDomainAsync(ListControlInsightsByControlDomainRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region ListControls /// <summary> /// Returns a list of controls from Audit Manager. /// </summary> /// <param name="request">Container for the necessary parameters to execute the ListControls service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the ListControls service method, as returned by AuditManager.</returns> /// <exception cref="Amazon.AuditManager.Model.AccessDeniedException"> /// Your account isn't registered with Audit Manager. Check the delegated administrator /// setup on the Audit Manager settings page, and try again. /// </exception> /// <exception cref="Amazon.AuditManager.Model.InternalServerException"> /// An internal service error occurred during the processing of your request. Try again /// later. /// </exception> /// <exception cref="Amazon.AuditManager.Model.ValidationException"> /// The request has invalid or missing parameters. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/ListControls">REST API Reference for ListControls Operation</seealso> Task<ListControlsResponse> ListControlsAsync(ListControlsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region ListKeywordsForDataSource /// <summary> /// Returns a list of keywords that are pre-mapped to the specified control data source. /// </summary> /// <param name="request">Container for the necessary parameters to execute the ListKeywordsForDataSource service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the ListKeywordsForDataSource service method, as returned by AuditManager.</returns> /// <exception cref="Amazon.AuditManager.Model.AccessDeniedException"> /// Your account isn't registered with Audit Manager. Check the delegated administrator /// setup on the Audit Manager settings page, and try again. /// </exception> /// <exception cref="Amazon.AuditManager.Model.InternalServerException"> /// An internal service error occurred during the processing of your request. Try again /// later. /// </exception> /// <exception cref="Amazon.AuditManager.Model.ValidationException"> /// The request has invalid or missing parameters. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/ListKeywordsForDataSource">REST API Reference for ListKeywordsForDataSource Operation</seealso> Task<ListKeywordsForDataSourceResponse> ListKeywordsForDataSourceAsync(ListKeywordsForDataSourceRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region ListNotifications /// <summary> /// Returns a list of all Audit Manager notifications. /// </summary> /// <param name="request">Container for the necessary parameters to execute the ListNotifications service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the ListNotifications service method, as returned by AuditManager.</returns> /// <exception cref="Amazon.AuditManager.Model.AccessDeniedException"> /// Your account isn't registered with Audit Manager. Check the delegated administrator /// setup on the Audit Manager settings page, and try again. /// </exception> /// <exception cref="Amazon.AuditManager.Model.InternalServerException"> /// An internal service error occurred during the processing of your request. Try again /// later. /// </exception> /// <exception cref="Amazon.AuditManager.Model.ValidationException"> /// The request has invalid or missing parameters. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/ListNotifications">REST API Reference for ListNotifications Operation</seealso> Task<ListNotificationsResponse> ListNotificationsAsync(ListNotificationsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region ListTagsForResource /// <summary> /// Returns a list of tags for the specified resource in Audit Manager. /// </summary> /// <param name="request">Container for the necessary parameters to execute the ListTagsForResource service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the ListTagsForResource service method, as returned by AuditManager.</returns> /// <exception cref="Amazon.AuditManager.Model.InternalServerException"> /// An internal service error occurred during the processing of your request. Try again /// later. /// </exception> /// <exception cref="Amazon.AuditManager.Model.ResourceNotFoundException"> /// The resource that's specified in the request can't be found. /// </exception> /// <exception cref="Amazon.AuditManager.Model.ValidationException"> /// The request has invalid or missing parameters. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/ListTagsForResource">REST API Reference for ListTagsForResource Operation</seealso> Task<ListTagsForResourceResponse> ListTagsForResourceAsync(ListTagsForResourceRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region RegisterAccount /// <summary> /// Enables Audit Manager for the specified Amazon Web Services account. /// </summary> /// <param name="request">Container for the necessary parameters to execute the RegisterAccount service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the RegisterAccount service method, as returned by AuditManager.</returns> /// <exception cref="Amazon.AuditManager.Model.AccessDeniedException"> /// Your account isn't registered with Audit Manager. Check the delegated administrator /// setup on the Audit Manager settings page, and try again. /// </exception> /// <exception cref="Amazon.AuditManager.Model.InternalServerException"> /// An internal service error occurred during the processing of your request. Try again /// later. /// </exception> /// <exception cref="Amazon.AuditManager.Model.ResourceNotFoundException"> /// The resource that's specified in the request can't be found. /// </exception> /// <exception cref="Amazon.AuditManager.Model.ValidationException"> /// The request has invalid or missing parameters. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/RegisterAccount">REST API Reference for RegisterAccount Operation</seealso> Task<RegisterAccountResponse> RegisterAccountAsync(RegisterAccountRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region RegisterOrganizationAdminAccount /// <summary> /// Enables an Amazon Web Services account within the organization as the delegated administrator /// for Audit Manager. /// </summary> /// <param name="request">Container for the necessary parameters to execute the RegisterOrganizationAdminAccount service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the RegisterOrganizationAdminAccount service method, as returned by AuditManager.</returns> /// <exception cref="Amazon.AuditManager.Model.AccessDeniedException"> /// Your account isn't registered with Audit Manager. Check the delegated administrator /// setup on the Audit Manager settings page, and try again. /// </exception> /// <exception cref="Amazon.AuditManager.Model.InternalServerException"> /// An internal service error occurred during the processing of your request. Try again /// later. /// </exception> /// <exception cref="Amazon.AuditManager.Model.ResourceNotFoundException"> /// The resource that's specified in the request can't be found. /// </exception> /// <exception cref="Amazon.AuditManager.Model.ValidationException"> /// The request has invalid or missing parameters. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/RegisterOrganizationAdminAccount">REST API Reference for RegisterOrganizationAdminAccount Operation</seealso> Task<RegisterOrganizationAdminAccountResponse> RegisterOrganizationAdminAccountAsync(RegisterOrganizationAdminAccountRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region StartAssessmentFrameworkShare /// <summary> /// Creates a share request for a custom framework in Audit Manager. /// /// /// <para> /// The share request specifies a recipient and notifies them that a custom framework /// is available. Recipients have 120 days to accept or decline the request. If no action /// is taken, the share request expires. /// </para> /// <important> /// <para> /// When you invoke the <code>StartAssessmentFrameworkShare</code> API, you are about /// to share a custom framework with another Amazon Web Services account. You may not /// share a custom framework that is derived from a standard framework if the standard /// framework is designated as not eligible for sharing by Amazon Web Services, unless /// you have obtained permission to do so from the owner of the standard framework. To /// learn more about which standard frameworks are eligible for sharing, see <a href="https://docs.aws.amazon.com/audit-manager/latest/userguide/share-custom-framework-concepts-and-terminology.html#eligibility">Framework /// sharing eligibility</a> in the <i>Audit Manager User Guide</i>. /// </para> /// </important> /// </summary> /// <param name="request">Container for the necessary parameters to execute the StartAssessmentFrameworkShare service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the StartAssessmentFrameworkShare service method, as returned by AuditManager.</returns> /// <exception cref="Amazon.AuditManager.Model.AccessDeniedException"> /// Your account isn't registered with Audit Manager. Check the delegated administrator /// setup on the Audit Manager settings page, and try again. /// </exception> /// <exception cref="Amazon.AuditManager.Model.InternalServerException"> /// An internal service error occurred during the processing of your request. Try again /// later. /// </exception> /// <exception cref="Amazon.AuditManager.Model.ResourceNotFoundException"> /// The resource that's specified in the request can't be found. /// </exception> /// <exception cref="Amazon.AuditManager.Model.ValidationException"> /// The request has invalid or missing parameters. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/StartAssessmentFrameworkShare">REST API Reference for StartAssessmentFrameworkShare Operation</seealso> Task<StartAssessmentFrameworkShareResponse> StartAssessmentFrameworkShareAsync(StartAssessmentFrameworkShareRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region TagResource /// <summary> /// Tags the specified resource in Audit Manager. /// </summary> /// <param name="request">Container for the necessary parameters to execute the TagResource service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the TagResource service method, as returned by AuditManager.</returns> /// <exception cref="Amazon.AuditManager.Model.InternalServerException"> /// An internal service error occurred during the processing of your request. Try again /// later. /// </exception> /// <exception cref="Amazon.AuditManager.Model.ResourceNotFoundException"> /// The resource that's specified in the request can't be found. /// </exception> /// <exception cref="Amazon.AuditManager.Model.ValidationException"> /// The request has invalid or missing parameters. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/TagResource">REST API Reference for TagResource Operation</seealso> Task<TagResourceResponse> TagResourceAsync(TagResourceRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region UntagResource /// <summary> /// Removes a tag from a resource in Audit Manager. /// </summary> /// <param name="request">Container for the necessary parameters to execute the UntagResource service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the UntagResource service method, as returned by AuditManager.</returns> /// <exception cref="Amazon.AuditManager.Model.InternalServerException"> /// An internal service error occurred during the processing of your request. Try again /// later. /// </exception> /// <exception cref="Amazon.AuditManager.Model.ResourceNotFoundException"> /// The resource that's specified in the request can't be found. /// </exception> /// <exception cref="Amazon.AuditManager.Model.ValidationException"> /// The request has invalid or missing parameters. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/UntagResource">REST API Reference for UntagResource Operation</seealso> Task<UntagResourceResponse> UntagResourceAsync(UntagResourceRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region UpdateAssessment /// <summary> /// Edits an Audit Manager assessment. /// </summary> /// <param name="request">Container for the necessary parameters to execute the UpdateAssessment service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the UpdateAssessment service method, as returned by AuditManager.</returns> /// <exception cref="Amazon.AuditManager.Model.AccessDeniedException"> /// Your account isn't registered with Audit Manager. Check the delegated administrator /// setup on the Audit Manager settings page, and try again. /// </exception> /// <exception cref="Amazon.AuditManager.Model.InternalServerException"> /// An internal service error occurred during the processing of your request. Try again /// later. /// </exception> /// <exception cref="Amazon.AuditManager.Model.ResourceNotFoundException"> /// The resource that's specified in the request can't be found. /// </exception> /// <exception cref="Amazon.AuditManager.Model.ValidationException"> /// The request has invalid or missing parameters. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/UpdateAssessment">REST API Reference for UpdateAssessment Operation</seealso> Task<UpdateAssessmentResponse> UpdateAssessmentAsync(UpdateAssessmentRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region UpdateAssessmentControl /// <summary> /// Updates a control within an assessment in Audit Manager. /// </summary> /// <param name="request">Container for the necessary parameters to execute the UpdateAssessmentControl service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the UpdateAssessmentControl service method, as returned by AuditManager.</returns> /// <exception cref="Amazon.AuditManager.Model.AccessDeniedException"> /// Your account isn't registered with Audit Manager. Check the delegated administrator /// setup on the Audit Manager settings page, and try again. /// </exception> /// <exception cref="Amazon.AuditManager.Model.InternalServerException"> /// An internal service error occurred during the processing of your request. Try again /// later. /// </exception> /// <exception cref="Amazon.AuditManager.Model.ResourceNotFoundException"> /// The resource that's specified in the request can't be found. /// </exception> /// <exception cref="Amazon.AuditManager.Model.ValidationException"> /// The request has invalid or missing parameters. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/UpdateAssessmentControl">REST API Reference for UpdateAssessmentControl Operation</seealso> Task<UpdateAssessmentControlResponse> UpdateAssessmentControlAsync(UpdateAssessmentControlRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region UpdateAssessmentControlSetStatus /// <summary> /// Updates the status of a control set in an Audit Manager assessment. /// </summary> /// <param name="request">Container for the necessary parameters to execute the UpdateAssessmentControlSetStatus service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the UpdateAssessmentControlSetStatus service method, as returned by AuditManager.</returns> /// <exception cref="Amazon.AuditManager.Model.AccessDeniedException"> /// Your account isn't registered with Audit Manager. Check the delegated administrator /// setup on the Audit Manager settings page, and try again. /// </exception> /// <exception cref="Amazon.AuditManager.Model.InternalServerException"> /// An internal service error occurred during the processing of your request. Try again /// later. /// </exception> /// <exception cref="Amazon.AuditManager.Model.ResourceNotFoundException"> /// The resource that's specified in the request can't be found. /// </exception> /// <exception cref="Amazon.AuditManager.Model.ValidationException"> /// The request has invalid or missing parameters. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/UpdateAssessmentControlSetStatus">REST API Reference for UpdateAssessmentControlSetStatus Operation</seealso> Task<UpdateAssessmentControlSetStatusResponse> UpdateAssessmentControlSetStatusAsync(UpdateAssessmentControlSetStatusRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region UpdateAssessmentFramework /// <summary> /// Updates a custom framework in Audit Manager. /// </summary> /// <param name="request">Container for the necessary parameters to execute the UpdateAssessmentFramework service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the UpdateAssessmentFramework service method, as returned by AuditManager.</returns> /// <exception cref="Amazon.AuditManager.Model.AccessDeniedException"> /// Your account isn't registered with Audit Manager. Check the delegated administrator /// setup on the Audit Manager settings page, and try again. /// </exception> /// <exception cref="Amazon.AuditManager.Model.InternalServerException"> /// An internal service error occurred during the processing of your request. Try again /// later. /// </exception> /// <exception cref="Amazon.AuditManager.Model.ResourceNotFoundException"> /// The resource that's specified in the request can't be found. /// </exception> /// <exception cref="Amazon.AuditManager.Model.ValidationException"> /// The request has invalid or missing parameters. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/UpdateAssessmentFramework">REST API Reference for UpdateAssessmentFramework Operation</seealso> Task<UpdateAssessmentFrameworkResponse> UpdateAssessmentFrameworkAsync(UpdateAssessmentFrameworkRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region UpdateAssessmentFrameworkShare /// <summary> /// Updates a share request for a custom framework in Audit Manager. /// </summary> /// <param name="request">Container for the necessary parameters to execute the UpdateAssessmentFrameworkShare service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the UpdateAssessmentFrameworkShare service method, as returned by AuditManager.</returns> /// <exception cref="Amazon.AuditManager.Model.AccessDeniedException"> /// Your account isn't registered with Audit Manager. Check the delegated administrator /// setup on the Audit Manager settings page, and try again. /// </exception> /// <exception cref="Amazon.AuditManager.Model.InternalServerException"> /// An internal service error occurred during the processing of your request. Try again /// later. /// </exception> /// <exception cref="Amazon.AuditManager.Model.ResourceNotFoundException"> /// The resource that's specified in the request can't be found. /// </exception> /// <exception cref="Amazon.AuditManager.Model.ValidationException"> /// The request has invalid or missing parameters. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/UpdateAssessmentFrameworkShare">REST API Reference for UpdateAssessmentFrameworkShare Operation</seealso> Task<UpdateAssessmentFrameworkShareResponse> UpdateAssessmentFrameworkShareAsync(UpdateAssessmentFrameworkShareRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region UpdateAssessmentStatus /// <summary> /// Updates the status of an assessment in Audit Manager. /// </summary> /// <param name="request">Container for the necessary parameters to execute the UpdateAssessmentStatus service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the UpdateAssessmentStatus service method, as returned by AuditManager.</returns> /// <exception cref="Amazon.AuditManager.Model.AccessDeniedException"> /// Your account isn't registered with Audit Manager. Check the delegated administrator /// setup on the Audit Manager settings page, and try again. /// </exception> /// <exception cref="Amazon.AuditManager.Model.InternalServerException"> /// An internal service error occurred during the processing of your request. Try again /// later. /// </exception> /// <exception cref="Amazon.AuditManager.Model.ResourceNotFoundException"> /// The resource that's specified in the request can't be found. /// </exception> /// <exception cref="Amazon.AuditManager.Model.ValidationException"> /// The request has invalid or missing parameters. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/UpdateAssessmentStatus">REST API Reference for UpdateAssessmentStatus Operation</seealso> Task<UpdateAssessmentStatusResponse> UpdateAssessmentStatusAsync(UpdateAssessmentStatusRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region UpdateControl /// <summary> /// Updates a custom control in Audit Manager. /// </summary> /// <param name="request">Container for the necessary parameters to execute the UpdateControl service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the UpdateControl service method, as returned by AuditManager.</returns> /// <exception cref="Amazon.AuditManager.Model.AccessDeniedException"> /// Your account isn't registered with Audit Manager. Check the delegated administrator /// setup on the Audit Manager settings page, and try again. /// </exception> /// <exception cref="Amazon.AuditManager.Model.InternalServerException"> /// An internal service error occurred during the processing of your request. Try again /// later. /// </exception> /// <exception cref="Amazon.AuditManager.Model.ResourceNotFoundException"> /// The resource that's specified in the request can't be found. /// </exception> /// <exception cref="Amazon.AuditManager.Model.ValidationException"> /// The request has invalid or missing parameters. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/UpdateControl">REST API Reference for UpdateControl Operation</seealso> Task<UpdateControlResponse> UpdateControlAsync(UpdateControlRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region UpdateSettings /// <summary> /// Updates Audit Manager settings for the current user account. /// </summary> /// <param name="request">Container for the necessary parameters to execute the UpdateSettings service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the UpdateSettings service method, as returned by AuditManager.</returns> /// <exception cref="Amazon.AuditManager.Model.AccessDeniedException"> /// Your account isn't registered with Audit Manager. Check the delegated administrator /// setup on the Audit Manager settings page, and try again. /// </exception> /// <exception cref="Amazon.AuditManager.Model.InternalServerException"> /// An internal service error occurred during the processing of your request. Try again /// later. /// </exception> /// <exception cref="Amazon.AuditManager.Model.ValidationException"> /// The request has invalid or missing parameters. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/UpdateSettings">REST API Reference for UpdateSettings Operation</seealso> Task<UpdateSettingsResponse> UpdateSettingsAsync(UpdateSettingsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region ValidateAssessmentReportIntegrity /// <summary> /// Validates the integrity of an assessment report in Audit Manager. /// </summary> /// <param name="request">Container for the necessary parameters to execute the ValidateAssessmentReportIntegrity service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the ValidateAssessmentReportIntegrity service method, as returned by AuditManager.</returns> /// <exception cref="Amazon.AuditManager.Model.AccessDeniedException"> /// Your account isn't registered with Audit Manager. Check the delegated administrator /// setup on the Audit Manager settings page, and try again. /// </exception> /// <exception cref="Amazon.AuditManager.Model.InternalServerException"> /// An internal service error occurred during the processing of your request. Try again /// later. /// </exception> /// <exception cref="Amazon.AuditManager.Model.ResourceNotFoundException"> /// The resource that's specified in the request can't be found. /// </exception> /// <exception cref="Amazon.AuditManager.Model.ValidationException"> /// The request has invalid or missing parameters. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/ValidateAssessmentReportIntegrity">REST API Reference for ValidateAssessmentReportIntegrity Operation</seealso> Task<ValidateAssessmentReportIntegrityResponse> ValidateAssessmentReportIntegrityAsync(ValidateAssessmentReportIntegrityRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion } }
57.289474
261
0.680804
[ "Apache-2.0" ]
EbstaLimited/aws-sdk-net
sdk/src/Services/AuditManager/Generated/_netstandard/IAmazonAuditManager.cs
117,562
C#
using System; using System.Linq; namespace FluentAssertions.Execution { /// <summary> /// Represents a chaining object returned from <see cref="AssertionScope.Given{T}"/> to continue the assertion using /// an object returned by a selector. /// </summary> public class GivenSelector<T> { #region Private Definitions private readonly T subject; private readonly bool evaluateCondition; private readonly AssertionScope parentScope; #endregion public GivenSelector(Func<T> selector, bool evaluateCondition, AssertionScope parentScope) { this.evaluateCondition = evaluateCondition; this.parentScope = parentScope; subject = evaluateCondition ? selector() : default(T); } /// <summary> /// Specify the condition that must be satisfied upon the subject selected through a prior selector. /// </summary> /// <param name="predicate"> /// If <c>true</c> the assertion will be treated as successful and no exceptions will be thrown. /// </param> /// <remarks> /// The condition will not be evaluated if the prior assertion failed, /// nor will <see cref="FailWith(string, System.Func{T, object}[])"/> throw any exceptions. /// </remarks> public GivenSelector<T> ForCondition(Func<T, bool> predicate) { if (evaluateCondition) { parentScope.ForCondition(predicate(subject)); } return this; } /// <summary> /// Allows to safely refine the subject for successive assertions, even when the prior assertion has failed. /// </summary> /// <paramref name="selector"> /// Selector which result is passed to successive calls to <see cref="ForCondition"/>. /// </paramref> /// <remarks> /// The selector will not be invoked if the prior assertion failed, /// nor will <see cref="FailWith(string,System.Func{T,object}[])"/> throw any exceptions. /// </remarks> public GivenSelector<TOut> Given<TOut>(Func<T, TOut> selector) { return new GivenSelector<TOut>(() => selector(subject), evaluateCondition, parentScope); } /// <summary> /// Sets the failure message when the assertion is not met, or completes the failure message set to a /// prior call to <see cref="FluentAssertions.Execution.AssertionScope.WithExpectation"/>. /// </summary> /// <remarks> /// If an expectation was set through a prior call to <see cref="FluentAssertions.Execution.AssertionScope.WithExpectation"/>, /// then the failure message is appended to that expectation. /// </remarks> /// <param name="message">The format string that represents the failure message.</param> public ContinuationOfGiven<T> FailWith(string message) { return FailWith(message, new object[0]); } /// <summary> /// Sets the failure message when the assertion is not met, or completes the failure message set to a /// prior call to <see cref="FluentAssertions.Execution.AssertionScope.WithExpectation"/>. /// </summary> /// <remarks> /// In addition to the numbered <see cref="string.Format(string,object[])"/>-style placeholders, messages may contain a few /// specialized placeholders as well. For instance, {reason} will be replaced with the reason of the assertion as passed /// to <see cref="FluentAssertions.Execution.AssertionScope.BecauseOf"/>. Other named placeholders will be replaced with /// the <see cref="FluentAssertions.Execution.AssertionScope.Current"/> scope data passed through /// <see cref="FluentAssertions.Execution.AssertionScope.AddNonReportable"/> and /// <see cref="FluentAssertions.Execution.AssertionScope.AddReportable"/>. Finally, a description of the current subject /// can be passed through the {context:description} placeholder. This is used in the message if no explicit context /// is specified through the <see cref="AssertionScope"/> constructor. /// Note that only 10 <paramref name="args"/> are supported in combination with a {reason}. /// If an expectation was set through a prior call to <see cref="FluentAssertions.Execution.AssertionScope.WithExpectation"/>, /// then the failure message is appended to that expectation. /// </remarks> /// <param name="message">The format string that represents the failure message.</param> /// <param name="args">Optional arguments to any numbered placeholders.</param> public ContinuationOfGiven<T> FailWith(string message, params Func<T, object>[] args) { return FailWith(message, args.Select(a => a(subject)).ToArray()); } /// <summary> /// Sets the failure message when the assertion is not met, or completes the failure message set to a /// prior call to <see cref="FluentAssertions.Execution.AssertionScope.WithExpectation"/>. /// </summary> /// <remarks> /// In addition to the numbered <see cref="string.Format(string, object[])"/>-style placeholders, messages may contain /// a few specialized placeholders as well. For instance, {reason} will be replaced with the reason of the assertion as /// passed to <see cref="FluentAssertions.Execution.AssertionScope.BecauseOf"/>. Other named placeholders will be /// replaced with the <see cref="FluentAssertions.Execution.AssertionScope.Current"/> scope data passed through /// <see cref="FluentAssertions.Execution.AssertionScope.AddNonReportable"/> and /// <see cref="FluentAssertions.Execution.AssertionScope.AddReportable"/>. Finally, a description of the /// current subject can be passed through the {context:description} placeholder. This is used in the message if no /// explicit context is specified through the <see cref="AssertionScope"/> constructor. /// Note that only 10 <paramref name="args"/> are supported in combination with a {reason}. /// If an expectation was set through a prior call to /// <see cref="FluentAssertions.Execution.AssertionScope.WithExpectation"/>, then the failure message is appended /// to that expectation. /// </remarks> /// <param name="message">The format string that represents the failure message.</param> /// <param name="args">Optional arguments to any numbered placeholders.</param> public ContinuationOfGiven<T> FailWith(string message, params object[] args) { bool succeeded = parentScope.Succeeded; if (evaluateCondition) { Continuation continuation = parentScope.FailWith(message, args); succeeded = continuation.SourceSucceeded; } return new ContinuationOfGiven<T>(this, succeeded); } } }
52.688889
134
0.650499
[ "Apache-2.0" ]
nicknijenhuis/fluentassertions
Src/FluentAssertions/Execution/GivenSelector.cs
7,113
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; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Reflection; using JetBrains.Annotations; using Microsoft.EntityFrameworkCore.Internal; using Microsoft.EntityFrameworkCore.Query.NavigationExpansion.Visitors; namespace Microsoft.EntityFrameworkCore.Query.Pipeline { public abstract class QueryableMethodTranslatingExpressionVisitor : ExpressionVisitor { protected override Expression VisitExtension(Expression extensionExpression) { if (extensionExpression is ShapedQueryExpression) { return extensionExpression; } return base.VisitExtension(extensionExpression); } protected override Expression VisitMethodCall(MethodCallExpression methodCallExpression) { if (methodCallExpression.Method.DeclaringType == typeof(Queryable) || methodCallExpression.Method.DeclaringType == typeof(QueryableExtensions)) { var source = Visit(methodCallExpression.Arguments[0]); if (source is ShapedQueryExpression shapedQueryExpression) { var argumentCount = methodCallExpression.Arguments.Count; switch (methodCallExpression.Method.Name) { case nameof(Queryable.Aggregate): // Don't know break; case nameof(Queryable.All): shapedQueryExpression.ResultType = ResultType.Single; return TranslateAll( shapedQueryExpression, methodCallExpression.Arguments[1].UnwrapLambdaFromQuote()); case nameof(Queryable.Any): shapedQueryExpression.ResultType = ResultType.Single; return TranslateAny( shapedQueryExpression, methodCallExpression.Arguments.Count == 2 ? methodCallExpression.Arguments[1].UnwrapLambdaFromQuote() : null); case nameof(Queryable.AsQueryable): // Don't know break; case nameof(Queryable.Average): shapedQueryExpression.ResultType = ResultType.Single; return TranslateAverage( shapedQueryExpression, methodCallExpression.Arguments.Count == 2 ? methodCallExpression.Arguments[1].UnwrapLambdaFromQuote() : null, methodCallExpression.Type); case nameof(Queryable.Cast): return TranslateCast(shapedQueryExpression, methodCallExpression.Method.GetGenericArguments()[0]); case nameof(Queryable.Concat): { var source2 = Visit(methodCallExpression.Arguments[1]); if (source2 is ShapedQueryExpression innerShapedQueryExpression) { return TranslateConcat( shapedQueryExpression, innerShapedQueryExpression); } } break; case nameof(Queryable.Contains) when argumentCount == 2: shapedQueryExpression.ResultType = ResultType.Single; return TranslateContains(shapedQueryExpression, methodCallExpression.Arguments[1]); case nameof(Queryable.Count): shapedQueryExpression.ResultType = ResultType.Single; return TranslateCount( shapedQueryExpression, methodCallExpression.Arguments.Count == 2 ? methodCallExpression.Arguments[1].UnwrapLambdaFromQuote() : null); case nameof(Queryable.DefaultIfEmpty): return TranslateDefaultIfEmpty( shapedQueryExpression, methodCallExpression.Arguments.Count == 2 ? methodCallExpression.Arguments[1] : null); case nameof(Queryable.Distinct) when argumentCount == 1: return TranslateDistinct(shapedQueryExpression); case nameof(Queryable.ElementAt): shapedQueryExpression.ResultType = ResultType.Single; return TranslateElementAtOrDefault(shapedQueryExpression, methodCallExpression.Arguments[1], false); case nameof(Queryable.ElementAtOrDefault): shapedQueryExpression.ResultType = ResultType.SingleWithDefault; return TranslateElementAtOrDefault(shapedQueryExpression, methodCallExpression.Arguments[1], true); case nameof(Queryable.Except) when argumentCount == 2: { var source2 = Visit(methodCallExpression.Arguments[1]); if (source2 is ShapedQueryExpression innerShapedQueryExpression) { return TranslateExcept( shapedQueryExpression, innerShapedQueryExpression); } } break; case nameof(Queryable.First): shapedQueryExpression.ResultType = ResultType.Single; return TranslateFirstOrDefault( shapedQueryExpression, methodCallExpression.Arguments.Count == 2 ? methodCallExpression.Arguments[1].UnwrapLambdaFromQuote() : null, methodCallExpression.Type, false); case nameof(Queryable.FirstOrDefault): shapedQueryExpression.ResultType = ResultType.SingleWithDefault; return TranslateFirstOrDefault( shapedQueryExpression, methodCallExpression.Arguments.Count == 2 ? methodCallExpression.Arguments[1].UnwrapLambdaFromQuote() : null, methodCallExpression.Type, true); case nameof(Queryable.GroupBy): { var keySelector = methodCallExpression.Arguments[1].UnwrapLambdaFromQuote(); if (methodCallExpression.Arguments[argumentCount - 1] is ConstantExpression) { // This means last argument is EqualityComparer on key // which is not supported break; } switch (argumentCount) { case 2: return TranslateGroupBy( shapedQueryExpression, keySelector, null, null); case 3: var lambda = methodCallExpression.Arguments[2].UnwrapLambdaFromQuote(); if (lambda.Parameters.Count == 1) { return TranslateGroupBy( shapedQueryExpression, keySelector, lambda, null); } else { return TranslateGroupBy( shapedQueryExpression, keySelector, null, lambda); } case 4: return TranslateGroupBy( shapedQueryExpression, keySelector, methodCallExpression.Arguments[2].UnwrapLambdaFromQuote(), methodCallExpression.Arguments[3].UnwrapLambdaFromQuote()); } } break; case nameof(Queryable.GroupJoin) when argumentCount == 5: { var innerSource = Visit(methodCallExpression.Arguments[1]); if (innerSource is ShapedQueryExpression innerShapedQueryExpression) { return TranslateGroupJoin( shapedQueryExpression, innerShapedQueryExpression, methodCallExpression.Arguments[2].UnwrapLambdaFromQuote(), methodCallExpression.Arguments[3].UnwrapLambdaFromQuote(), methodCallExpression.Arguments[4].UnwrapLambdaFromQuote()); } } break; case nameof(Queryable.Intersect) when argumentCount == 2: { var source2 = Visit(methodCallExpression.Arguments[1]); if (source2 is ShapedQueryExpression innerShapedQueryExpression) { return TranslateIntersect( shapedQueryExpression, innerShapedQueryExpression); } } break; case nameof(Queryable.Join) when argumentCount == 5: { var innerSource = Visit(methodCallExpression.Arguments[1]); if (innerSource is ShapedQueryExpression innerShapedQueryExpression) { return TranslateJoin( shapedQueryExpression, innerShapedQueryExpression, methodCallExpression.Arguments[2].UnwrapLambdaFromQuote(), methodCallExpression.Arguments[3].UnwrapLambdaFromQuote(), methodCallExpression.Arguments[4].UnwrapLambdaFromQuote()); } } break; case nameof(QueryableExtensions.LeftJoin) when argumentCount == 5: { var innerSource = Visit(methodCallExpression.Arguments[1]); if (innerSource is ShapedQueryExpression innerShapedQueryExpression) { return TranslateLeftJoin( shapedQueryExpression, innerShapedQueryExpression, methodCallExpression.Arguments[2].UnwrapLambdaFromQuote(), methodCallExpression.Arguments[3].UnwrapLambdaFromQuote(), methodCallExpression.Arguments[4].UnwrapLambdaFromQuote()); } } break; case nameof(Queryable.Last): shapedQueryExpression.ResultType = ResultType.Single; return TranslateLastOrDefault( shapedQueryExpression, methodCallExpression.Arguments.Count == 2 ? methodCallExpression.Arguments[1].UnwrapLambdaFromQuote() : null, methodCallExpression.Type, false); case nameof(Queryable.LastOrDefault): shapedQueryExpression.ResultType = ResultType.SingleWithDefault; return TranslateLastOrDefault( shapedQueryExpression, methodCallExpression.Arguments.Count == 2 ? methodCallExpression.Arguments[1].UnwrapLambdaFromQuote() : null, methodCallExpression.Type, true); case nameof(Queryable.LongCount): shapedQueryExpression.ResultType = ResultType.Single; return TranslateLongCount( shapedQueryExpression, methodCallExpression.Arguments.Count == 2 ? methodCallExpression.Arguments[1].UnwrapLambdaFromQuote() : null); case nameof(Queryable.Max): shapedQueryExpression.ResultType = ResultType.Single; return TranslateMax( shapedQueryExpression, methodCallExpression.Arguments.Count == 2 ? methodCallExpression.Arguments[1].UnwrapLambdaFromQuote() : null, methodCallExpression.Type); case nameof(Queryable.Min): shapedQueryExpression.ResultType = ResultType.Single; return TranslateMin( shapedQueryExpression, methodCallExpression.Arguments.Count == 2 ? methodCallExpression.Arguments[1].UnwrapLambdaFromQuote() : null, methodCallExpression.Type); case nameof(Queryable.OfType): return TranslateOfType(shapedQueryExpression, methodCallExpression.Method.GetGenericArguments()[0]); case nameof(Queryable.OrderBy) when argumentCount == 2: return TranslateOrderBy( shapedQueryExpression, methodCallExpression.Arguments[1].UnwrapLambdaFromQuote(), true); case nameof(Queryable.OrderByDescending) when argumentCount == 2: return TranslateOrderBy( shapedQueryExpression, methodCallExpression.Arguments[1].UnwrapLambdaFromQuote(), false); case nameof(Queryable.Reverse): return TranslateReverse(shapedQueryExpression); case nameof(Queryable.Select): return TranslateSelect( shapedQueryExpression, methodCallExpression.Arguments[1].UnwrapLambdaFromQuote()); case nameof(Queryable.SelectMany): return methodCallExpression.Arguments.Count == 2 ? TranslateSelectMany( shapedQueryExpression, methodCallExpression.Arguments[1].UnwrapLambdaFromQuote()) : TranslateSelectMany( shapedQueryExpression, methodCallExpression.Arguments[1].UnwrapLambdaFromQuote(), methodCallExpression.Arguments[2].UnwrapLambdaFromQuote()); case nameof(Queryable.SequenceEqual): // don't know break; case nameof(Queryable.Single): shapedQueryExpression.ResultType = ResultType.Single; return TranslateSingleOrDefault( shapedQueryExpression, methodCallExpression.Arguments.Count == 2 ? methodCallExpression.Arguments[1].UnwrapLambdaFromQuote() : null, methodCallExpression.Type, false); case nameof(Queryable.SingleOrDefault): shapedQueryExpression.ResultType = ResultType.SingleWithDefault; return TranslateSingleOrDefault( shapedQueryExpression, methodCallExpression.Arguments.Count == 2 ? methodCallExpression.Arguments[1].UnwrapLambdaFromQuote() : null, methodCallExpression.Type, true); case nameof(Queryable.Skip): return TranslateSkip(shapedQueryExpression, methodCallExpression.Arguments[1]); case nameof(Queryable.SkipWhile): return TranslateSkipWhile( shapedQueryExpression, methodCallExpression.Arguments[1].UnwrapLambdaFromQuote()); case nameof(Queryable.Sum): shapedQueryExpression.ResultType = ResultType.Single; return TranslateSum( shapedQueryExpression, methodCallExpression.Arguments.Count == 2 ? methodCallExpression.Arguments[1].UnwrapLambdaFromQuote() : null, methodCallExpression.Type); case nameof(Queryable.Take): return TranslateTake(shapedQueryExpression, methodCallExpression.Arguments[1]); case nameof(Queryable.TakeWhile): return TranslateTakeWhile( shapedQueryExpression, methodCallExpression.Arguments[1].UnwrapLambdaFromQuote()); case nameof(Queryable.ThenBy) when argumentCount == 2: return TranslateThenBy( shapedQueryExpression, methodCallExpression.Arguments[1].UnwrapLambdaFromQuote(), true); case nameof(Queryable.ThenByDescending) when argumentCount == 2: return TranslateThenBy( shapedQueryExpression, methodCallExpression.Arguments[1].UnwrapLambdaFromQuote(), false); case nameof(Queryable.Union) when argumentCount == 2: { var source2 = Visit(methodCallExpression.Arguments[1]); if (source2 is ShapedQueryExpression innerShapedQueryExpression) { return TranslateUnion( shapedQueryExpression, innerShapedQueryExpression); } } break; case nameof(Queryable.Where): return TranslateWhere( shapedQueryExpression, methodCallExpression.Arguments[1].UnwrapLambdaFromQuote()); case nameof(Queryable.Zip): // Don't know break; } } throw new NotImplementedException("Unhandled method: " + methodCallExpression.Method.Name); } // TODO: Skip ToOrderedQueryable method. See Issue#15591 if (methodCallExpression.Method.DeclaringType == typeof(NavigationExpansionReducingVisitor) && methodCallExpression.Method.Name == nameof(NavigationExpansionReducingVisitor.ToOrderedQueryable)) { return Visit(methodCallExpression.Arguments[0]); } return base.VisitMethodCall(methodCallExpression); } protected Type CreateTransparentIdentifierType(Type outerType, Type innerType) { return typeof(TransparentIdentifier<,>).MakeGenericType(outerType, innerType); } private class EntityShaperNullableMarkingExpressionVisitor : ExpressionVisitor { protected override Expression VisitExtension(Expression extensionExpression) { if (extensionExpression is EntityShaperExpression entityShaper) { return new EntityShaperExpression(entityShaper.EntityType, entityShaper.ValueBufferExpression, true); } return base.VisitExtension(extensionExpression); } } protected ShapedQueryExpression TranslateResultSelectorForJoin( ShapedQueryExpression outer, LambdaExpression resultSelector, Expression innerShaper, Type transparentIdentifierType, bool innerNullable) { if (innerNullable) { innerShaper = new EntityShaperNullableMarkingExpressionVisitor().Visit(innerShaper); } outer.ShaperExpression = CombineShapers( outer.QueryExpression, outer.ShaperExpression, innerShaper, transparentIdentifierType); var transparentIdentifierParameter = Expression.Parameter(transparentIdentifierType); var newResultSelector = Expression.Lambda( ReplacingExpressionVisitor.Replace( resultSelector.Parameters[0], AccessOuterTransparentField(transparentIdentifierType, transparentIdentifierParameter), resultSelector.Parameters[1], AccessInnerTransparentField(transparentIdentifierType, transparentIdentifierParameter), resultSelector.Body), transparentIdentifierParameter); return TranslateSelect(outer, newResultSelector); } protected ShapedQueryExpression TranslateResultSelectorForGroupJoin( #pragma warning disable IDE0060 // Remove unused parameter ShapedQueryExpression outer, Expression innerShaper, LambdaExpression outerKeySelector, LambdaExpression innerKeySelector, LambdaExpression resultSelector, Type transparentIdentifierType) #pragma warning restore IDE0060 // Remove unused parameter { throw new NotImplementedException(); } private Expression CombineShapers( Expression queryExpression, Expression outerShaper, Expression innerShaper, Type transparentIdentifierType) { var outerMemberInfo = transparentIdentifierType.GetTypeInfo().GetDeclaredField("Outer"); var innerMemberInfo = transparentIdentifierType.GetTypeInfo().GetDeclaredField("Inner"); outerShaper = new MemberAccessShiftingExpressionVisitor(queryExpression, outerMemberInfo).Visit(outerShaper); innerShaper = new MemberAccessShiftingExpressionVisitor(queryExpression, innerMemberInfo).Visit(innerShaper); return Expression.New( transparentIdentifierType.GetTypeInfo().DeclaredConstructors.Single(), new[] { outerShaper, innerShaper }, new[] { outerMemberInfo, innerMemberInfo }); } private class MemberAccessShiftingExpressionVisitor : ExpressionVisitor { private readonly Expression _queryExpression; private readonly MemberInfo _memberShift; public MemberAccessShiftingExpressionVisitor(Expression queryExpression, MemberInfo memberShift) { _queryExpression = queryExpression; _memberShift = memberShift; } protected override Expression VisitExtension(Expression node) { if (node is ProjectionBindingExpression projectionBindingExpression) { return new ProjectionBindingExpression( _queryExpression, projectionBindingExpression.ProjectionMember.ShiftMember(_memberShift), projectionBindingExpression.Type); } return base.VisitExtension(node); } } private static Expression AccessOuterTransparentField( Type transparentIdentifierType, Expression targetExpression) { var fieldInfo = transparentIdentifierType.GetTypeInfo().GetDeclaredField("Outer"); return Expression.Field(targetExpression, fieldInfo); } private static Expression AccessInnerTransparentField( Type transparentIdentifierType, Expression targetExpression) { var fieldInfo = transparentIdentifierType.GetTypeInfo().GetDeclaredField("Inner"); return Expression.Field(targetExpression, fieldInfo); } protected abstract ShapedQueryExpression TranslateAll(ShapedQueryExpression source, LambdaExpression predicate); protected abstract ShapedQueryExpression TranslateAny(ShapedQueryExpression source, LambdaExpression predicate); protected abstract ShapedQueryExpression TranslateAverage(ShapedQueryExpression source, LambdaExpression selector, Type resultType); protected abstract ShapedQueryExpression TranslateCast(ShapedQueryExpression source, Type resultType); protected abstract ShapedQueryExpression TranslateConcat(ShapedQueryExpression source1, ShapedQueryExpression source2); protected abstract ShapedQueryExpression TranslateContains(ShapedQueryExpression source, Expression item); protected abstract ShapedQueryExpression TranslateCount(ShapedQueryExpression source, LambdaExpression predicate); protected abstract ShapedQueryExpression TranslateDefaultIfEmpty(ShapedQueryExpression source, Expression defaultValue); protected abstract ShapedQueryExpression TranslateDistinct(ShapedQueryExpression source); protected abstract ShapedQueryExpression TranslateElementAtOrDefault(ShapedQueryExpression source, Expression index, bool returnDefault); protected abstract ShapedQueryExpression TranslateExcept(ShapedQueryExpression source1, ShapedQueryExpression source2); protected abstract ShapedQueryExpression TranslateFirstOrDefault(ShapedQueryExpression source, LambdaExpression predicate, Type returnType, bool returnDefault); protected abstract ShapedQueryExpression TranslateGroupBy(ShapedQueryExpression source, LambdaExpression keySelector, LambdaExpression elementSelector, LambdaExpression resultSelector); protected abstract ShapedQueryExpression TranslateGroupJoin(ShapedQueryExpression outer, ShapedQueryExpression inner, LambdaExpression outerKeySelector, LambdaExpression innerKeySelector, LambdaExpression resultSelector); protected abstract ShapedQueryExpression TranslateIntersect(ShapedQueryExpression source1, ShapedQueryExpression source2); protected abstract ShapedQueryExpression TranslateJoin(ShapedQueryExpression outer, ShapedQueryExpression inner, LambdaExpression outerKeySelector, LambdaExpression innerKeySelector, LambdaExpression resultSelector); protected abstract ShapedQueryExpression TranslateLeftJoin(ShapedQueryExpression outer, ShapedQueryExpression inner, LambdaExpression outerKeySelector, LambdaExpression innerKeySelector, LambdaExpression resultSelector); protected abstract ShapedQueryExpression TranslateLastOrDefault(ShapedQueryExpression source, LambdaExpression predicate, Type returnType, bool returnDefault); protected abstract ShapedQueryExpression TranslateLongCount(ShapedQueryExpression source, LambdaExpression predicate); protected abstract ShapedQueryExpression TranslateMax(ShapedQueryExpression source, LambdaExpression selector, Type resultType); protected abstract ShapedQueryExpression TranslateMin(ShapedQueryExpression source, LambdaExpression selector, Type resultType); protected abstract ShapedQueryExpression TranslateOfType(ShapedQueryExpression source, Type resultType); protected abstract ShapedQueryExpression TranslateOrderBy(ShapedQueryExpression source, LambdaExpression keySelector, bool ascending); protected abstract ShapedQueryExpression TranslateReverse(ShapedQueryExpression source); protected abstract ShapedQueryExpression TranslateSelect(ShapedQueryExpression source, LambdaExpression selector); protected abstract ShapedQueryExpression TranslateSelectMany(ShapedQueryExpression source, LambdaExpression collectionSelector, LambdaExpression resultSelector); protected abstract ShapedQueryExpression TranslateSelectMany(ShapedQueryExpression source, LambdaExpression selector); protected abstract ShapedQueryExpression TranslateSingleOrDefault(ShapedQueryExpression source, LambdaExpression predicate, Type returnType, bool returnDefault); protected abstract ShapedQueryExpression TranslateSkip(ShapedQueryExpression source, Expression count); protected abstract ShapedQueryExpression TranslateSkipWhile(ShapedQueryExpression source, LambdaExpression predicate); protected abstract ShapedQueryExpression TranslateSum(ShapedQueryExpression source, LambdaExpression selector, Type resultType); protected abstract ShapedQueryExpression TranslateTake(ShapedQueryExpression source, Expression count); protected abstract ShapedQueryExpression TranslateTakeWhile(ShapedQueryExpression source, LambdaExpression predicate); protected abstract ShapedQueryExpression TranslateThenBy(ShapedQueryExpression source, LambdaExpression keySelector, bool ascending); protected abstract ShapedQueryExpression TranslateUnion(ShapedQueryExpression source1, ShapedQueryExpression source2); protected abstract ShapedQueryExpression TranslateWhere(ShapedQueryExpression source, LambdaExpression predicate); public abstract ShapedQueryExpression TranslateSubquery(Expression expression); } public readonly struct TransparentIdentifier<TOuter, TInner> { [UsedImplicitly] #pragma warning disable IDE0051 // Remove unused private members private TransparentIdentifier(TOuter outer, TInner inner) #pragma warning restore IDE0051 // Remove unused private members { Outer = outer; Inner = inner; } [UsedImplicitly] public readonly TOuter Outer; [UsedImplicitly] public readonly TInner Inner; } }
54.08453
229
0.532865
[ "Apache-2.0" ]
CharlieRoseMarie/EntityFrameworkCore
src/EFCore/Query/Pipeline/QueryableMethodTranslatingExpressionVisitor.cs
33,913
C#
/* Copyright 2013-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 MongoDB.Driver.Core.Clusters; using MongoDB.Driver.Core.Connections; using MongoDB.Driver.Core.Servers; namespace MongoDB.Driver.Core.Events { /// <preliminary/> /// <summary> /// Occurs after a connection is checked out of the pool. /// </summary> public struct ConnectionPoolCheckedOutConnectionEvent { private readonly ConnectionId _connectionId; private readonly TimeSpan _duration; private readonly long? _operationId; /// <summary> /// Initializes a new instance of the <see cref="ConnectionPoolCheckedOutConnectionEvent" /> struct. /// </summary> /// <param name="connectionId">The connection identifier.</param> /// <param name="duration">The duration of time it took to check out the connection.</param> /// <param name="operationId">The operation identifier.</param> public ConnectionPoolCheckedOutConnectionEvent(ConnectionId connectionId, TimeSpan duration, long? operationId) { _connectionId = connectionId; _duration = duration; _operationId = operationId; } /// <summary> /// Gets the cluster identifier. /// </summary> public ClusterId ClusterId { get { return _connectionId.ServerId.ClusterId; } } /// <summary> /// Gets the connection identifier. /// </summary> public ConnectionId ConnectionId { get { return _connectionId; } } /// <summary> /// Gets the duration of time it took to check out the connection. /// </summary> public TimeSpan Duration { get { return _duration; } } /// <summary> /// Gets the operation identifier. /// </summary> public long? OperationId { get { return _operationId; } } /// <summary> /// Gets the server identifier. /// </summary> public ServerId ServerId { get { return _connectionId.ServerId; } } } }
31.321839
119
0.622018
[ "MIT" ]
13294029724/ET
Server/ThirdParty/MongoDBDriver/MongoDB.Driver.Core/Core/Events/ConnectionPoolCheckedOutConnectionEvent.cs
2,725
C#
// Copyright (c) Allan Nielsen. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. namespace OurPresence.Modeller.Liquid { /// <summary> /// Interface for tag factory. /// </summary> /// <remarks>Can be usefull when the tag needs a parameter and can't be created with parameterless constructor.</remarks> public interface ITagFactory { /// <summary> /// Name of the tag /// </summary> string TagName { get; } /// <summary> /// Creates the tag /// </summary> /// <returns></returns> Tag Create(Template template, string markup); } }
29.041667
125
0.604017
[ "MIT" ]
Allann/OurPresence
OurPresence.Modeller.Core/OurPresence.Modeller.Liquid/ITagFactory.cs
699
C#
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Data; using System.Data.Entity; using System.Data.Entity.ModelConfiguration; using System.Data.Entity.ModelConfiguration.Conventions; using System.Linq; using System.Globalization; using System.Web; using System.Web.Mvc; using System.Web.Security; using APPBASE.Helpers; using APPBASE.Models; using APPBASE.Svcbiz; namespace APPBASE.Models { public partial class UkuranVM { public int? ID { get; set; } public Byte? DTA_STS { get; set; } public string UKURAN_CODE { get; set; } public string UKURAN_NAME { get; set; } } //End public partial class UkuranVM } //End namespace APPBASE.Models
28.321429
56
0.754098
[ "MIT" ]
arinsuga/posup
APPBASE/ModelsVMs/STOK/CFG/Ukuran/UkuranVM.cs
795
C#
using System; using System.Collections.Generic; using System.Linq; namespace _Lab_04.SpecialWords { public class SpecialWords { public static void Main() { var specialWords = Console.ReadLine().Split(new[] { '(', ')', '[', ']', '<', '>', '-', '!', '?', ' ' }).ToList(); var inputText = Console.ReadLine().Split(new[] { '(', ')', '[', ']', '<', '>', '-', '!', '?', ' ' }).ToList(); var result = new List<string>(); foreach (string word in specialWords) { var count = inputText.Count(x => x == word); result.Add(word + " - " + count); } Console.WriteLine(string.Join("\n", result)); } } }
27.592593
125
0.460403
[ "MIT" ]
nikolaydechev/CSharp-Advanced
05 Manual String Processing/(Lab)04. SpecialWords/SpecialWords.cs
747
C#
using System; using System.Collections.Generic; using System.Text; namespace FytSoa.Service.Interfaces.Recipe { public interface IRecipeSeriesService : IBaseServer<FytSoa.Core.Model.Recipe_Series> { } }
18.166667
88
0.766055
[ "MIT" ]
liwendiao123/FytSoaCms
FytSoa.Service/Interfaces/Recipe/IRecipeSeriesService.cs
220
C#
// ========================================================================== // Squidex Headless CMS // ========================================================================== // Copyright (c) Squidex UG (haftungsbeschraenkt) // All rights reserved. Licensed under the MIT license. // ========================================================================== using System; using System.Net; using System.Net.Mail; using System.Net.Sockets; using System.Threading; using System.Threading.Tasks; using Squidex.Domain.Apps.Core.HandleRules; using Squidex.Domain.Apps.Core.Rules.EnrichedEvents; namespace Squidex.Extensions.Actions.Email { public sealed class EmailActionHandler : RuleActionHandler<EmailAction, EmailJob> { public EmailActionHandler(RuleEventFormatter formatter) : base(formatter) { } protected override async Task<(string Description, EmailJob Data)> CreateJobAsync(EnrichedEvent @event, EmailAction action) { var ruleJob = new EmailJob { ServerHost = action.ServerHost, ServerUseSsl = action.ServerUseSsl, ServerPassword = action.ServerPassword, ServerPort = action.ServerPort, ServerUsername = await FormatAsync(action.ServerUsername, @event), MessageFrom = await FormatAsync(action.MessageFrom, @event), MessageTo = await FormatAsync(action.MessageTo, @event), MessageSubject = await FormatAsync(action.MessageSubject, @event), MessageBody = await FormatAsync(action.MessageBody, @event) }; var description = $"Send an email to {action.MessageTo}"; return (description, ruleJob); } protected override async Task<Result> ExecuteJobAsync(EmailJob job, CancellationToken ct = default) { await CheckConnectionAsync(job, ct); using (var client = new SmtpClient(job.ServerHost, job.ServerPort) { Credentials = new NetworkCredential( job.ServerUsername, job.ServerPassword), EnableSsl = job.ServerUseSsl }) { using (ct.Register(client.SendAsyncCancel)) { await client.SendMailAsync( job.MessageFrom, job.MessageTo, job.MessageSubject, job.MessageBody); } } return Result.Complete(); } private async Task CheckConnectionAsync(EmailJob job, CancellationToken ct) { using (var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { var tcs = new TaskCompletionSource<IAsyncResult>(); var state = socket.BeginConnect(job.ServerHost, job.ServerPort, tcs.SetResult, null); using (ct.Register(() => { tcs.TrySetException(new OperationCanceledException($"Failed to establish a connection to {job.ServerHost}:{job.ServerPort}")); })) { await tcs.Task; } } } } public sealed class EmailJob { public int ServerPort { get; set; } public string ServerHost { get; set; } public string ServerUsername { get; set; } public string ServerPassword { get; set; } public bool ServerUseSsl { get; set; } public string MessageFrom { get; set; } public string MessageTo { get; set; } public string MessageSubject { get; set; } public string MessageBody { get; set; } } }
34.25
146
0.544056
[ "MIT" ]
IainCoSource/squidex
backend/extensions/Squidex.Extensions/Actions/Email/EmailActionHandler.cs
3,838
C#
using DeltaEngine.ScreenSpaces; namespace DeltaNinja.Pages { class PausePage : BasePage { public PausePage(ScreenSpace screen) : base(screen) { SetViewportBackground("PauseBackground"); SetTitle("Pause", 0.25f, 4f, 0.05f); AddButton(MenuButton.Resume, 0.2f, 4f); AddButton(MenuButton.NewGame, 0.2f, 4f); AddButton(MenuButton.Abort, 0.2f, 4f); } } }
23.529412
48
0.6625
[ "Apache-2.0" ]
DeltaEngine/DeltaEngine
Samples/DeltaNinja/Pages/PausePage.cs
402
C#
#pragma checksum "C:\Users\turka\source\repos\EfCoreApp\EfCoreApp\Views\Shared\Error.cshtml" "{ff1816ec-aa5e-4d10-87f7-6f4963833460}" "d6a5625cc8fb4476f348b0fe9041c550465d8bf9" // <auto-generated/> #pragma warning disable 1591 [assembly: global::Microsoft.AspNetCore.Razor.Hosting.RazorCompiledItemAttribute(typeof(AspNetCore.Views_Shared_Error), @"mvc.1.0.view", @"/Views/Shared/Error.cshtml")] namespace AspNetCore { #line hidden using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Rendering; using Microsoft.AspNetCore.Mvc.ViewFeatures; #nullable restore #line 1 "C:\Users\turka\source\repos\EfCoreApp\EfCoreApp\Views\_ViewImports.cshtml" using EfCoreApp; #line default #line hidden #nullable disable #nullable restore #line 2 "C:\Users\turka\source\repos\EfCoreApp\EfCoreApp\Views\_ViewImports.cshtml" using EfCoreApp.Models; #line default #line hidden #nullable disable [global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"d6a5625cc8fb4476f348b0fe9041c550465d8bf9", @"/Views/Shared/Error.cshtml")] [global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"c1de71456280ea1693607f55348ca6f93969b178", @"/Views/_ViewImports.cshtml")] public class Views_Shared_Error : global::Microsoft.AspNetCore.Mvc.Razor.RazorPage<ErrorViewModel> { #pragma warning disable 1998 public async override global::System.Threading.Tasks.Task ExecuteAsync() { #nullable restore #line 2 "C:\Users\turka\source\repos\EfCoreApp\EfCoreApp\Views\Shared\Error.cshtml" ViewData["Title"] = "Error"; #line default #line hidden #nullable disable WriteLiteral("\r\n<h1 class=\"text-danger\">Error.</h1>\r\n<h2 class=\"text-danger\">An error occurred while processing your request.</h2>\r\n\r\n"); #nullable restore #line 9 "C:\Users\turka\source\repos\EfCoreApp\EfCoreApp\Views\Shared\Error.cshtml" if (Model.ShowRequestId) { #line default #line hidden #nullable disable WriteLiteral(" <p>\r\n <strong>Request ID:</strong> <code>"); #nullable restore #line 12 "C:\Users\turka\source\repos\EfCoreApp\EfCoreApp\Views\Shared\Error.cshtml" Write(Model.RequestId); #line default #line hidden #nullable disable WriteLiteral("</code>\r\n </p>\r\n"); #nullable restore #line 14 "C:\Users\turka\source\repos\EfCoreApp\EfCoreApp\Views\Shared\Error.cshtml" } #line default #line hidden #nullable disable WriteLiteral(@" <h3>Development Mode</h3> <p> Swapping to <strong>Development</strong> environment will display more detailed information about the error that occurred. </p> <p> <strong>The Development environment shouldn't be enabled for deployed applications.</strong> It can result in displaying sensitive information from exceptions to end users. For local debugging, enable the <strong>Development</strong> environment by setting the <strong>ASPNETCORE_ENVIRONMENT</strong> environment variable to <strong>Development</strong> and restarting the app. </p> "); } #pragma warning restore 1998 [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.ViewFeatures.IModelExpressionProvider ModelExpressionProvider { get; private set; } [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.IUrlHelper Url { get; private set; } [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.IViewComponentHelper Component { get; private set; } [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.Rendering.IJsonHelper Json { get; private set; } [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.Rendering.IHtmlHelper<ErrorViewModel> Html { get; private set; } } } #pragma warning restore 1591
43.802083
184
0.745541
[ "MIT" ]
TurkanKAYA/EfCoreApp
EfCoreApp/obj/Debug/netcoreapp3.0/Razor/Views/Shared/Error.cshtml.g.cs
4,205
C#
// Copyright 2018 by JCoder58. See License.txt for license // Auto-generated --- Do not modify. using System; using System.Collections.Generic; using System.Runtime.InteropServices; using UE4.Core; using UE4.CoreUObject; using UE4.CoreUObject.Native; using UE4.InputCore; using UE4.Native; #pragma warning disable CS0108 using UE4.AIModule.Native; namespace UE4.AIModule { ///<summary>Env Query Item Type Actor Base</summary> public unsafe partial class EnvQueryItemType_ActorBase : EnvQueryItemType_VectorBase { static EnvQueryItemType_ActorBase() { StaticClass = Main.GetClass("EnvQueryItemType_ActorBase"); } internal unsafe EnvQueryItemType_ActorBase_fields* EnvQueryItemType_ActorBase_ptr => (EnvQueryItemType_ActorBase_fields*) ObjPointer.ToPointer(); ///<summary>Convert from IntPtr to UObject</summary> public static implicit operator EnvQueryItemType_ActorBase(IntPtr p) => UObject.Make<EnvQueryItemType_ActorBase>(p); ///<summary>Get UE4 Class</summary> public static Class StaticClass {get; private set;} ///<summary>Get UE4 Default Object for this Class</summary> public static EnvQueryItemType_ActorBase DefaultObject => Main.GetDefaultObject(StaticClass); ///<summary>Spawn an object of this class</summary> public static EnvQueryItemType_ActorBase New(UObject obj = null, Name name = new Name()) => Main.NewObject(StaticClass, obj, name); } }
44.69697
153
0.742373
[ "MIT" ]
UE4DotNet/Plugin
DotNet/DotNet/UE4/Generated/AIModule/EnvQueryItemType_ActorBase.cs
1,475
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using ApiRouteDescriptor; using ApiRouteDescriptor.EntityFrameworkCore.Extensions; using ApiRouteDescriptor.Extensions; using ApiRouteDescriptor.Resources; using ApiRouteDescriptor.Responders; using AutoMapper; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Routing; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; namespace ApiRouteDescriptorSample { public class Startup { public Startup() { Mapper.Initialize(config => { config.CreateMap<Person, PersonResource>(); }); } // This method gets called by the runtime. Use this method to add services to the container. // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940 public void ConfigureServices(IServiceCollection services) { var connection = @"Server=(localdb)\mssqllocaldb;Database=ApiRouteDescriptorSample;Trusted_Connection=True;"; services.AddApiRouteDescriptor(config => { config .UseEntityFrameworkDataStore<SampleContext>(o => o.UseSqlServer(connection)) .UseResourceMapper<SampleResourceMapper>(); }); services.AddScoped<HomeResponder>(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { loggerFactory.AddConsole(); app.UseApiRouteDescriptor(new SampleApiDefinition()); } public class SampleApiDefinition : ApiDefinition { public SampleApiDefinition() { this.Get["Root", "api"] = this.CustomAction<HomeResponder>(); this.Get["People", "api/people"] = this.Paged<Person, PersonResource>("Name").WithLinkRouteName("People"); this.Get["Person", "api/people/{id}"] = this.Single<Person,PersonResource,string>(); } } public class HomeResponder : CustomActionResponder<HomeResponder> { protected override async Task<Resource> Execute() { return new HomeResource { ApplicationName = "SampleApiApplication", Version = "1.0.0.0", Links = LinkCollection.Self(this.ResolveLink("Root")) .Add("People",this.ResolveLink("People")) }; } public class HomeResource : Resource { public string ApplicationName { get; set; } public string Version { get; set; } } } public class SampleResourceMapper : ResourceMapper { public override void InitializeMappings() { this.Map<Person, PersonResource>().EnrichResource((person, resource, helper) => { resource.Links = LinkCollection.Self(helper.ResolveLink("Person",new {resource.Id})); }); } public SampleResourceMapper(IUrlHelper helper) : base(helper) { } } public class SampleContext : DbContext { public SampleContext(DbContextOptions options) : base(options) { } public DbSet<Person> Persons { get; set; } } public class Person : IHaveId<string> { public string Id { get; set; } public string Name { get; set; } } public class PersonResource : Resource { public string Id { get; set; } public string Name { get; set; } } } }
33.528455
122
0.590204
[ "MIT" ]
Excommunicated/ApiRouteDescriptor
ApiRouteDescriptorSample/Startup.cs
4,126
C#
using System; using System.Collections.Generic; using Cocodrilo.Elements; using System.Runtime.InteropServices; using System.Web.Script.Serialization; using Cocodrilo.ElementProperties; namespace Cocodrilo.UserData { [Guid("9CB19B78-3C1E-4A3C-BD17-71427716A0A2")] public class UserDataBrep : Rhino.DocObjects.Custom.UserData { public int BrepId { get; set; } public UserDataBrep() { BrepId = -1; } #region Rhino methods protected override void OnDuplicate(Rhino.DocObjects.Custom.UserData source) { if (source is UserDataBrep src) { BrepId = src.BrepId; } } #endregion #region Read/Write public override bool ShouldWrite { get { if (BrepId != 0) return true; return false; } } protected override bool Read(Rhino.FileIO.BinaryArchiveReader archive) { var serializer = new JavaScriptSerializer(new SimpleTypeResolver()); var dict = archive.ReadDictionary(); if (dict.ContainsKey("BrepId")) { BrepId = (int) dict["BrepId"]; } return true; } protected override bool Write(Rhino.FileIO.BinaryArchiveWriter archive) { var dict = new Rhino.Collections.ArchivableDictionary(1, "Physical"); dict.Set("BrepId", BrepId); archive.WriteDictionary(dict); return true; } #endregion } }
24.58209
84
0.553127
[ "MIT" ]
CocodriloCAD/Cocodrilo
Cocodrilo/Cocodrilo/UserData/UserDataBrep.cs
1,649
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections; using System.Collections.Generic; using System.Data.Common; using System.Diagnostics; using System.Globalization; using System.Text; using System.Xml; using System.Xml.Serialization; namespace System.Data { internal sealed class XmlDataLoader { private readonly DataSet _dataSet; private XmlToDatasetMap _nodeToSchemaMap; private readonly Hashtable _nodeToRowMap; private readonly Stack<DataRow> _childRowsStack; private readonly bool _fIsXdr; internal bool _isDiffgram; private XmlElement _topMostNode; private readonly bool _ignoreSchema; private readonly DataTable _dataTable; private readonly bool _isTableLevel; private bool _fromInference; internal XmlDataLoader(DataSet dataset, bool IsXdr, bool ignoreSchema) { // Initialization _dataSet = dataset; _nodeToRowMap = new Hashtable(); _fIsXdr = IsXdr; _ignoreSchema = ignoreSchema; } internal XmlDataLoader(DataSet dataset, bool IsXdr, XmlElement topNode, bool ignoreSchema) { // Initialization _dataSet = dataset; _nodeToRowMap = new Hashtable(); _fIsXdr = IsXdr; // Allocate the stack and create the mappings _childRowsStack = new Stack<DataRow>(50); _topMostNode = topNode; _ignoreSchema = ignoreSchema; } internal XmlDataLoader(DataTable datatable, bool IsXdr, bool ignoreSchema) { // Initialization _dataSet = null; _dataTable = datatable; _isTableLevel = true; _nodeToRowMap = new Hashtable(); _fIsXdr = IsXdr; _ignoreSchema = ignoreSchema; } internal XmlDataLoader(DataTable datatable, bool IsXdr, XmlElement topNode, bool ignoreSchema) { // Initialization _dataSet = null; _dataTable = datatable; _isTableLevel = true; _nodeToRowMap = new Hashtable(); _fIsXdr = IsXdr; // Allocate the stack and create the mappings _childRowsStack = new Stack<DataRow>(50); _topMostNode = topNode; _ignoreSchema = ignoreSchema; } internal bool FromInference { get { return _fromInference; } set { _fromInference = value; } } // after loading, all detached DataRows are attached to their tables private void AttachRows(DataRow parentRow, XmlNode parentElement) { if (parentElement == null) return; for (XmlNode n = parentElement.FirstChild; n != null; n = n.NextSibling) { if (n.NodeType == XmlNodeType.Element) { XmlElement e = (XmlElement)n; DataRow r = GetRowFromElement(e); if (r != null && r.RowState == DataRowState.Detached) { if (parentRow != null) r.SetNestedParentRow(parentRow, /*setNonNested*/ false); r.Table.Rows.Add(r); } else if (r == null) { // n is a 'sugar element' AttachRows(parentRow, n); } // attach all detached rows AttachRows(r, n); } } } private int CountNonNSAttributes(XmlNode node) { int count = 0; for (int i = 0; i < node.Attributes.Count; i++) { if (!FExcludedNamespace(node.Attributes[i].NamespaceURI)) count++; } return count; } private string GetValueForTextOnlyColums(XmlNode n) { string value = null; // don't consider whitespace while (n != null && (n.NodeType == XmlNodeType.Whitespace || !IsTextLikeNode(n.NodeType))) { n = n.NextSibling; } if (n != null) { if (IsTextLikeNode(n.NodeType) && (n.NextSibling == null || !IsTextLikeNode(n.NodeType))) { // don't use string builder if only one text node exists value = n.Value; n = n.NextSibling; } else { StringBuilder sb = new StringBuilder(); while (n != null && IsTextLikeNode(n.NodeType)) { sb.Append(n.Value); n = n.NextSibling; } value = sb.ToString(); } } if (value == null) value = string.Empty; return value; } private string GetInitialTextFromNodes(ref XmlNode n) { string value = null; if (n != null) { // don't consider whitespace while (n.NodeType == XmlNodeType.Whitespace) n = n.NextSibling; if (IsTextLikeNode(n.NodeType) && (n.NextSibling == null || !IsTextLikeNode(n.NodeType))) { // don't use string builder if only one text node exists value = n.Value; n = n.NextSibling; } else { StringBuilder sb = new StringBuilder(); while (n != null && IsTextLikeNode(n.NodeType)) { sb.Append(n.Value); n = n.NextSibling; } value = sb.ToString(); } } if (value == null) value = string.Empty; return value; } private DataColumn GetTextOnlyColumn(DataRow row) { DataColumnCollection columns = row.Table.Columns; int cCols = columns.Count; for (int iCol = 0; iCol < cCols; iCol++) { DataColumn c = columns[iCol]; if (IsTextOnly(c)) return c; } return null; } internal DataRow GetRowFromElement(XmlElement e) { return (DataRow)_nodeToRowMap[e]; } internal bool FColumnElement(XmlElement e) { if (_nodeToSchemaMap.GetColumnSchema(e, FIgnoreNamespace(e)) == null) return false; if (CountNonNSAttributes(e) > 0) return false; for (XmlNode tabNode = e.FirstChild; tabNode != null; tabNode = tabNode.NextSibling) if (tabNode is XmlElement) return false; return true; } private bool FExcludedNamespace(string ns) { return ns.Equals(Keywords.XSD_XMLNS_NS); } private bool FIgnoreNamespace(XmlNode node) { XmlNode ownerNode; if (!_fIsXdr) return false; if (node is XmlAttribute) ownerNode = ((XmlAttribute)node).OwnerElement; else ownerNode = node; if (ownerNode.NamespaceURI.StartsWith("x-schema:#", StringComparison.Ordinal)) return true; else return false; } private bool FIgnoreNamespace(XmlReader node) { if (_fIsXdr && node.NamespaceURI.StartsWith("x-schema:#", StringComparison.Ordinal)) return true; else return false; } internal bool IsTextLikeNode(XmlNodeType n) { switch (n) { case XmlNodeType.EntityReference: throw ExceptionBuilder.FoundEntity(); case XmlNodeType.Text: case XmlNodeType.Whitespace: case XmlNodeType.SignificantWhitespace: case XmlNodeType.CDATA: return true; default: return false; } } internal bool IsTextOnly(DataColumn c) { if (c.ColumnMapping != MappingType.SimpleContent) return false; else return true; } internal void LoadData(XmlDocument xdoc) { if (xdoc.DocumentElement == null) return; bool saveEnforce; if (_isTableLevel) { saveEnforce = _dataTable.EnforceConstraints; _dataTable.EnforceConstraints = false; } else { saveEnforce = _dataSet.EnforceConstraints; _dataSet.EnforceConstraints = false; _dataSet._fInReadXml = true; } if (_isTableLevel) { _nodeToSchemaMap = new XmlToDatasetMap(_dataTable, xdoc.NameTable); } else { _nodeToSchemaMap = new XmlToDatasetMap(_dataSet, xdoc.NameTable); } /* // Top level table or dataset ? XmlElement rootElement = xdoc.DocumentElement; Hashtable tableAtoms = new Hashtable(); XmlNode tabNode; if (CountNonNSAttributes (rootElement) > 0) dataSet.fTopLevelTable = true; else { for (tabNode = rootElement.FirstChild; tabNode != null; tabNode = tabNode.NextSibling) { if (tabNode is XmlElement && tabNode.LocalName != Keywords.XSD_SCHEMA) { object value = tableAtoms[QualifiedName (tabNode.LocalName, tabNode.NamespaceURI)]; if (value == null || (bool)value == false) { dataSet.fTopLevelTable = true; break; } } } } */ DataRow topRow = null; if (_isTableLevel || (_dataSet != null && _dataSet._fTopLevelTable)) { XmlElement e = xdoc.DocumentElement; DataTable topTable = (DataTable)_nodeToSchemaMap.GetSchemaForNode(e, FIgnoreNamespace(e)); if (topTable != null) { topRow = topTable.CreateEmptyRow(); //enzol perf _nodeToRowMap[e] = topRow; // get all field values. LoadRowData(topRow, e); topTable.Rows.Add(topRow); } } LoadRows(topRow, xdoc.DocumentElement); AttachRows(topRow, xdoc.DocumentElement); if (_isTableLevel) { _dataTable.EnforceConstraints = saveEnforce; } else { _dataSet._fInReadXml = false; _dataSet.EnforceConstraints = saveEnforce; } } private void LoadRowData(DataRow row, XmlElement rowElement) { XmlNode n; DataTable table = row.Table; if (FromInference) table.Prefix = rowElement.Prefix; // keep a list of all columns that get updated Hashtable foundColumns = new Hashtable(); row.BeginEdit(); // examine all children first n = rowElement.FirstChild; // Look for data to fill the TextOnly column DataColumn column = GetTextOnlyColumn(row); if (column != null) { foundColumns[column] = column; string text = GetValueForTextOnlyColums(n); if (XMLSchema.GetBooleanAttribute(rowElement, Keywords.XSI_NIL, Keywords.XSINS, false) && string.IsNullOrEmpty(text)) row[column] = DBNull.Value; else SetRowValueFromXmlText(row, column, text); } // Walk the region to find elements that map to columns while (n != null && n != rowElement) { if (n.NodeType == XmlNodeType.Element) { XmlElement e = (XmlElement)n; object schema = _nodeToSchemaMap.GetSchemaForNode(e, FIgnoreNamespace(e)); if (schema is DataTable) { if (FColumnElement(e)) schema = _nodeToSchemaMap.GetColumnSchema(e, FIgnoreNamespace(e)); } // if element has its own table mapping, it is a separate region if (schema == null || schema is DataColumn) { // descend to examine child elements n = e.FirstChild; if (schema != null && schema is DataColumn) { DataColumn c = (DataColumn)schema; if (c.Table == row.Table && c.ColumnMapping != MappingType.Attribute && foundColumns[c] == null) { foundColumns[c] = c; string text = GetValueForTextOnlyColums(n); if (XMLSchema.GetBooleanAttribute(e, Keywords.XSI_NIL, Keywords.XSINS, false) && string.IsNullOrEmpty(text)) row[c] = DBNull.Value; else SetRowValueFromXmlText(row, c, text); } } else if ((schema == null) && (n != null)) { continue; } // nothing left down here, continue from element if (n == null) n = e; } } // if no more siblings, ascend back toward original element (rowElement) while (n != rowElement && n.NextSibling == null) { n = n.ParentNode; } if (n != rowElement) n = n.NextSibling; } // // Walk the attributes to find attributes that map to columns. // foreach (XmlAttribute attr in rowElement.Attributes) { object schema = _nodeToSchemaMap.GetColumnSchema(attr, FIgnoreNamespace(attr)); if (schema != null && schema is DataColumn) { DataColumn c = (DataColumn)schema; if (c.ColumnMapping == MappingType.Attribute && foundColumns[c] == null) { foundColumns[c] = c; n = attr.FirstChild; SetRowValueFromXmlText(row, c, GetInitialTextFromNodes(ref n)); } } } // Null all columns values that aren't represented in the tree foreach (DataColumn c in row.Table.Columns) { if (foundColumns[c] == null && XmlToDatasetMap.IsMappedColumn(c)) { if (!c.AutoIncrement) { if (c.AllowDBNull) { row[c] = DBNull.Value; } else { row[c] = c.DefaultValue; } } else { c.Init(row._tempRecord); } } } row.EndEdit(); } // load all data from tree structre into datarows private void LoadRows(DataRow parentRow, XmlNode parentElement) { if (parentElement == null) return; // Skip schema node as well if (parentElement.LocalName == Keywords.XSD_SCHEMA && parentElement.NamespaceURI == Keywords.XSDNS || parentElement.LocalName == Keywords.SQL_SYNC && parentElement.NamespaceURI == Keywords.UPDGNS || parentElement.LocalName == Keywords.XDR_SCHEMA && parentElement.NamespaceURI == Keywords.XDRNS) return; for (XmlNode n = parentElement.FirstChild; n != null; n = n.NextSibling) { if (n is XmlElement) { XmlElement e = (XmlElement)n; object schema = _nodeToSchemaMap.GetSchemaForNode(e, FIgnoreNamespace(e)); if (schema != null && schema is DataTable) { DataRow r = GetRowFromElement(e); if (r == null) { // skip columns which has the same name as another table if (parentRow != null && FColumnElement(e)) continue; r = ((DataTable)schema).CreateEmptyRow(); _nodeToRowMap[e] = r; // get all field values. LoadRowData(r, e); } // recurse down to inner elements LoadRows(r, n); } else { // recurse down to inner elements LoadRows(null, n); } } } } private void SetRowValueFromXmlText(DataRow row, DataColumn col, string xmlText) { row[col] = col.ConvertXmlToObject(xmlText); } private XmlReader _dataReader; private object _XSD_XMLNS_NS; private object _XDR_SCHEMA; private object _XDRNS; private object _SQL_SYNC; private object _UPDGNS; private object _XSD_SCHEMA; private object _XSDNS; private object _DFFNS; private object _MSDNS; private object _DIFFID; private object _HASCHANGES; private object _ROWORDER; private void InitNameTable() { XmlNameTable nameTable = _dataReader.NameTable; _XSD_XMLNS_NS = nameTable.Add(Keywords.XSD_XMLNS_NS); _XDR_SCHEMA = nameTable.Add(Keywords.XDR_SCHEMA); _XDRNS = nameTable.Add(Keywords.XDRNS); _SQL_SYNC = nameTable.Add(Keywords.SQL_SYNC); _UPDGNS = nameTable.Add(Keywords.UPDGNS); _XSD_SCHEMA = nameTable.Add(Keywords.XSD_SCHEMA); _XSDNS = nameTable.Add(Keywords.XSDNS); _DFFNS = nameTable.Add(Keywords.DFFNS); _MSDNS = nameTable.Add(Keywords.MSDNS); _DIFFID = nameTable.Add(Keywords.DIFFID); _HASCHANGES = nameTable.Add(Keywords.HASCHANGES); _ROWORDER = nameTable.Add(Keywords.ROWORDER); } internal void LoadData(XmlReader reader) { _dataReader = DataTextReader.CreateReader(reader); int entryDepth = _dataReader.Depth; // Store current XML element depth so we'll read // correct portion of the XML and no more bool fEnforce = _isTableLevel ? _dataTable.EnforceConstraints : _dataSet.EnforceConstraints; // Keep constraints status for datataset/table InitNameTable(); // Adds DataSet namespaces to reader's nametable if (_nodeToSchemaMap == null) { // Create XML to dataset map _nodeToSchemaMap = _isTableLevel ? new XmlToDatasetMap(_dataReader.NameTable, _dataTable) : new XmlToDatasetMap(_dataReader.NameTable, _dataSet); } if (_isTableLevel) { _dataTable.EnforceConstraints = false; // Disable constraints } else { _dataSet.EnforceConstraints = false; // Disable constraints _dataSet._fInReadXml = true; // We're in ReadXml now } if (_topMostNode != null) { // Do we have top node? if (!_isDiffgram && !_isTableLevel) { // Not a diffgram and not DataSet? DataTable table = _nodeToSchemaMap.GetSchemaForNode(_topMostNode, FIgnoreNamespace(_topMostNode)) as DataTable; // Try to match table in the dataset to this node if (table != null) { // Got the table ? LoadTopMostTable(table); // Load top most node } } _topMostNode = null; // topMostNode is no more. Good riddance. } while (!_dataReader.EOF) { // Main XML parsing loop. Check for EOF just in case. if (_dataReader.Depth < entryDepth) // Stop if we have consumed all elements allowed break; if (reader.NodeType != XmlNodeType.Element) { // Read till Element is found _dataReader.Read(); continue; } DataTable table = _nodeToSchemaMap.GetTableForNode(_dataReader, FIgnoreNamespace(_dataReader)); // Try to get table for node if (table == null) { // Read till table is found if (!ProcessXsdSchema()) // Check for schemas... _dataReader.Read(); // Not found? Read next element. continue; } LoadTable(table, false /* isNested */); // Here goes -- load data for this table // This is a root table, so it's not nested } if (_isTableLevel) { _dataTable.EnforceConstraints = fEnforce; // Restore constraints and return } else { _dataSet._fInReadXml = false; // We're done. _dataSet.EnforceConstraints = fEnforce; // Restore constraints and return } } // Loads a top most table. // This is neded because .NET Framework is capable of loading almost anything into the dataset. // The top node could be a DataSet element or a Table element. To make things worse, // you could have a table with the same name as dataset. // Here's how we're going to dig into this mess: // // TopNode is null ? // / No \ Yes // Table matches TopNode ? Current node is the table start // / No \ Yes (LoadTopMostTable called in this case only) // Current node is the table start DataSet name matches one of the tables ? // TopNode is dataset node / Yes \ No // / TopNode is the table // Current node matches column or nested table in the table ? and current node // / No \ Yes is a column or a // TopNode is DataSet TopNode is table nested table // // Yes, it is terrible and I don't like it also.. private void LoadTopMostTable(DataTable table) { // /------------------------------- This one is in topMostNode (backed up to XML DOM) // <Table> /----------------------------- We are here on entrance // <Column>Value</Column> // <AnotherColumn>Value</AnotherColumn> // </Table> ... // \------------------------------ We are here on exit Debug.Assert(table != null, "Table to be loaded is null on LoadTopMostTable() entry"); Debug.Assert(_topMostNode != null, "topMostNode is null on LoadTopMostTable() entry"); Debug.Assert(!_isDiffgram, "Diffgram mode is on while we have topMostNode table. This is bad."); bool topNodeIsTable = _isTableLevel || (_dataSet.DataSetName != table.TableName); // If table name we have matches dataset // name top node could be a DataSet OR a table. // It's a table overwise. DataRow row = null; // Data row we're going to add to this table bool matchFound = false; // Assume we found no matching elements int entryDepth = _dataReader.Depth - 1; // Store current reader depth so we know when to stop reading // Adjust depth by one as we've read top most element // outside this method. string textNodeValue; // Value of a text node we might have Debug.Assert(entryDepth >= 0, "Wrong entry Depth for top most element."); int entryChild = _childRowsStack.Count; // Memorize child stack level on entry DataColumn c; // Hold column here DataColumnCollection collection = table.Columns; // Hold column collectio here object[] foundColumns = new object[collection.Count]; // This is the columns data we might find XmlNode n; // Need this to pass by reference foreach (XmlAttribute attr in _topMostNode.Attributes) { // Check all attributes in this node c = _nodeToSchemaMap.GetColumnSchema(attr, FIgnoreNamespace(attr)) as DataColumn; // Try to match attribute to column if ((c != null) && (c.ColumnMapping == MappingType.Attribute)) { // If it's a column with attribute mapping n = attr.FirstChild; foundColumns[c.Ordinal] = c.ConvertXmlToObject(GetInitialTextFromNodes(ref n)); // Get value matchFound = true; // and note we found a matching element } } // Now handle elements. This could be columns or nested tables // We'll skip the rest as we have no idea what to do with it. // Note: we do not need to read first as we're already as it has been done by caller. while (entryDepth < _dataReader.Depth) { switch (_dataReader.NodeType) { // Process nodes based on type case XmlNodeType.Element: // It's an element object o = _nodeToSchemaMap.GetColumnSchema(table, _dataReader, FIgnoreNamespace(_dataReader)); // Get dataset element for this XML element c = o as DataColumn; // Perhaps, it's a column? if (c != null) { // Do we have matched column in this table? // Let's load column data if (foundColumns[c.Ordinal] == null) { // If this column was not found before LoadColumn(c, foundColumns); // Get column value. matchFound = true; // Got matched row. } else { _dataReader.Read(); // Advance to next element. } } else { DataTable nestedTable = o as DataTable; // Perhaps, it's a nested table ? if (nestedTable != null) { // Do we have matched table in DataSet ? LoadTable(nestedTable, true /* isNested */); // Yes. Load nested table (recursive) matchFound = true; // Got matched nested table } else if (ProcessXsdSchema()) { // Check for schema. Skip or load if found. continue; // Schema has been found. Process the next element // we're already at (done by schema processing). } else { // Not a table or column in this table ? if (!(matchFound || topNodeIsTable)) { // Could top node be a DataSet? return; // Assume top node is DataSet // and stop top node processing } _dataReader.Read(); // Continue to the next element. } } break; // Oops. Not supported case XmlNodeType.EntityReference: // Oops. No support for Entity Reference throw ExceptionBuilder.FoundEntity(); case XmlNodeType.Text: // It looks like a text. case XmlNodeType.Whitespace: // This actually could be case XmlNodeType.CDATA: // if we have XmlText in our table case XmlNodeType.SignificantWhitespace: textNodeValue = _dataReader.ReadString(); // Get text node value. c = table._xmlText; // Get XML Text column from our table if (c != null && foundColumns[c.Ordinal] == null) { // If XmlText Column is set // and we do not have data already foundColumns[c.Ordinal] = c.ConvertXmlToObject(textNodeValue); // Read and store the data } break; default: _dataReader.Read(); // We don't process that, skip to the next element. break; } } _dataReader.Read(); // Proceed to the next element. // It's the time to populate row with loaded data and add it to the table we'we just read to the table for (int i = foundColumns.Length - 1; i >= 0; --i) { // Check all columns if (null == foundColumns[i]) { // Got data for this column ? c = collection[i]; // No. Get column for this index if (c.AllowDBNull && c.ColumnMapping != MappingType.Hidden && !c.AutoIncrement) { foundColumns[i] = DBNull.Value; // Assign DBNull if possible // table.Rows.Add() below will deal // with default values and autoincrement } } } row = table.Rows.AddWithColumnEvents(foundColumns); // Create, populate and add row while (entryChild < _childRowsStack.Count) { // Process child rows we might have DataRow childRow = _childRowsStack.Pop(); // Get row from the stack bool unchanged = (childRow.RowState == DataRowState.Unchanged); // Is data the same as before? childRow.SetNestedParentRow(row, /*setNonNested*/ false); // Set parent row if (unchanged) // Restore record if child row's unchanged childRow._oldRecord = childRow._newRecord; } } // Loads a table. // Yes, I know it's a big method. This is done to avoid performance penalty of calling methods // with many arguments and to keep recursion within one method only. To make code readable, // this method divided into 3 parts: attribute processing (including diffgram), // nested elements processing and loading data. Please keep it this way. private void LoadTable(DataTable table, bool isNested) { // <DataSet> /--------------------------- We are here on entrance // <Table> // <Column>Value</Column> // <AnotherColumn>Value</AnotherColumn> // </Table> /-------------------------- We are here on exit // <AnotherTable> // ... // </AnotherTable> // ... // </DataSet> Debug.Assert(table != null, "Table to be loaded is null on LoadTable() entry"); DataRow row = null; // Data row we're going to add to this table int entryDepth = _dataReader.Depth; // Store current reader depth so we know when to stop reading int entryChild = _childRowsStack.Count; // Memorize child stack level on entry DataColumn c; // Hold column here DataColumnCollection collection = table.Columns; // Hold column collectio here object[] foundColumns = new object[collection.Count]; // This is the columns data we found // This is used to process diffgramms int rowOrder = -1; // Row to insert data to string diffId = string.Empty; // Diffgram ID string string hasChanges = null; // Changes string bool hasErrors = false; // Set this in case of problem string textNodeValue; // Value of a text node we might have // Process attributes first for (int i = _dataReader.AttributeCount - 1; i >= 0; --i) { // Check all attributes one by one _dataReader.MoveToAttribute(i); // Get this attribute c = _nodeToSchemaMap.GetColumnSchema(table, _dataReader, FIgnoreNamespace(_dataReader)) as DataColumn; // Try to get column for this attribute if ((c != null) && (c.ColumnMapping == MappingType.Attribute)) { // Yep, it is a column mapped as attribute // Get value from XML and store it in the object array foundColumns[c.Ordinal] = c.ConvertXmlToObject(_dataReader.Value); } // Oops. No column for this element if (_isDiffgram) { // Now handle some diffgram attributes if (_dataReader.NamespaceURI == Keywords.DFFNS) { switch (_dataReader.LocalName) { case Keywords.DIFFID: // Is it a diffgeam ID ? diffId = _dataReader.Value; // Store ID break; case Keywords.HASCHANGES: // Has changes attribute ? hasChanges = _dataReader.Value; // Store value break; case Keywords.HASERRORS: // Has errors attribute ? hasErrors = (bool)Convert.ChangeType(_dataReader.Value, typeof(bool), CultureInfo.InvariantCulture); // Store value break; } } else if (_dataReader.NamespaceURI == Keywords.MSDNS) { if (_dataReader.LocalName == Keywords.ROWORDER) { // Is it a row order attribute ? rowOrder = (int)Convert.ChangeType(_dataReader.Value, typeof(int), CultureInfo.InvariantCulture); // Store it } else if (_dataReader.LocalName.StartsWith("hidden", StringComparison.Ordinal)) { // Hidden column ? c = collection[XmlConvert.DecodeName(_dataReader.LocalName.Substring(6))]; // Let's see if we have one. // We have to decode name before we look it up // We could not use XmlToDataSet map as it contains // no hidden columns if ((c != null) && (c.ColumnMapping == MappingType.Hidden)) { // Got column and it is hidden ? foundColumns[c.Ordinal] = c.ConvertXmlToObject(_dataReader.Value); } } } } } // Done with attributes // Now handle elements. This could be columns or nested tables. // <DataSet> /------------------- We are here after dealing with attributes // <Table foo="FooValue" bar="BarValue"> // <Column>Value</Column> // <AnotherColumn>Value</AnotherColumn> // </Table> // </DataSet> if (_dataReader.Read() && entryDepth < _dataReader.Depth) { // Read to the next element and see if we're inside while (entryDepth < _dataReader.Depth) { // Get out as soon as we've processed all nested nodes. switch (_dataReader.NodeType) { // Process nodes based on type case XmlNodeType.Element: // It's an element object o = _nodeToSchemaMap.GetColumnSchema(table, _dataReader, FIgnoreNamespace(_dataReader)); // Get dataset element for this XML element c = o as DataColumn; // Perhaps, it's a column? if (c != null) { // Do we have matched column in this table? // Let's load column data if (foundColumns[c.Ordinal] == null) { // If this column was not found before LoadColumn(c, foundColumns); // Get column value } else { _dataReader.Read(); // Advance to next element. } } else { DataTable nestedTable = o as DataTable; // Perhaps, it's a nested table ? if (nestedTable != null) { // Do we have matched nested table in DataSet ? LoadTable(nestedTable, true /* isNested */); // Yes. Load nested table (recursive) } // Not a table nor column? Check if it's schema. else if (ProcessXsdSchema()) { // Check for schema. Skip or load if found. continue; // Schema has been found. Process the next element // we're already at (done by schema processing). } else { // We've got element which is not supposed to he here according to the schema. // That might be a table which was misplaced. We should've thrown on that, // but we'll try to load it so we could keep compatibility. // We won't try to match to columns as we have no idea // which table this potential column might belong to. DataTable misplacedTable = _nodeToSchemaMap.GetTableForNode(_dataReader, FIgnoreNamespace(_dataReader)); // Try to get table for node if (misplacedTable != null) { // Got some matching table? LoadTable(misplacedTable, false /* isNested */); // While table's XML element is nested, // the table itself is not. Load it this way. } else { _dataReader.Read(); // Not a table? Try next element. } } } break; case XmlNodeType.EntityReference: // Oops. No support for Entity Reference throw ExceptionBuilder.FoundEntity(); case XmlNodeType.Text: // It looks like a text. case XmlNodeType.Whitespace: // This actually could be case XmlNodeType.CDATA: // if we have XmlText in our table case XmlNodeType.SignificantWhitespace: textNodeValue = _dataReader.ReadString(); // Get text node value. c = table._xmlText; // Get XML Text column from our table if (c != null && foundColumns[c.Ordinal] == null) { // If XmlText Column is set // and we do not have data already foundColumns[c.Ordinal] = c.ConvertXmlToObject(textNodeValue); // Read and store the data } break; default: _dataReader.Read(); // We don't process that, skip to the next element. break; } } _dataReader.Read(); // We're done here, proceed to the next element. } // It's the time to populate row with loaded data and add it to the table we'we just read to the table if (_isDiffgram) { // In case of diffgram row = table.NewRow(table.NewUninitializedRecord()); // just create an empty row row.BeginEdit(); // and allow it's population with data for (int i = foundColumns.Length - 1; i >= 0; --i) { // Check all columns c = collection[i]; // Get column for this index c[row._tempRecord] = null != foundColumns[i] ? foundColumns[i] : DBNull.Value; // Set column to loaded value of to // DBNull if value is missing. } row.EndEdit(); // Done with this row table.Rows.DiffInsertAt(row, rowOrder); // insert data to specific location // And do some diff processing if (hasChanges == null) { // No changes ? row._oldRecord = row._newRecord; // Restore old record } if ((hasChanges == Keywords.MODIFIED) || hasErrors) { table.RowDiffId[diffId] = row; } } else { for (int i = foundColumns.Length - 1; i >= 0; --i) { // Check all columns if (null == foundColumns[i]) { // Got data for this column ? c = collection[i]; // No. Get column for this index if (c.AllowDBNull && c.ColumnMapping != MappingType.Hidden && !c.AutoIncrement) { foundColumns[i] = DBNull.Value; // Assign DBNull if possible // table.Rows.Add() below will deal // with default values and autoincrement } } } row = table.Rows.AddWithColumnEvents(foundColumns); // Create, populate and add row } // Data is loaded into the row and row is added to the table at this point while (entryChild < _childRowsStack.Count) { // Process child rows we might have DataRow childRow = _childRowsStack.Pop(); // Get row from the stack bool unchanged = (childRow.RowState == DataRowState.Unchanged); // Is data the same as before? childRow.SetNestedParentRow(row, /*setNonNested*/ false); // Set parent row if (unchanged) // Restore record if child row's unchanged childRow._oldRecord = childRow._newRecord; } if (isNested) // Got parent ? _childRowsStack.Push(row); // Push row to the stack } // Returns column value private void LoadColumn(DataColumn column, object[] foundColumns) { // <DataSet> /--------------------------------- We are here on entrance // <Table> / // <Column>Value</Column> // <AnotherColumn>Value</AnotherColumn> // </Table> \------------------------------ We are here on exit // </DataSet> // <Column> If we have something like this // <Foo>FooVal</Foo> We would grab first text-like node // Value In this case it would be "FooVal" // <Bar>BarVal</Bar> And not "Value" as you might think // </Column> This is how .NET Framework works string text = string.Empty; // Column text. Assume empty string string xsiNilString = null; // Possible NIL attribute string int entryDepth = _dataReader.Depth; // Store depth so we won't read too much if (_dataReader.AttributeCount > 0) // If have attributes xsiNilString = _dataReader.GetAttribute(Keywords.XSI_NIL, Keywords.XSINS); // Try to get NIL attribute // We have to do it before we move to the next element if (column.IsCustomType) { // Custom type column object columnValue = null; // Column value we're after. Assume no value. string xsiTypeString = null; // XSI type name from TYPE attribute string typeName = null; // Type name from MSD_INSTANCETYPE attribute XmlRootAttribute xmlAttrib = null; // Might need this attribute for XmlSerializer if (_dataReader.AttributeCount > 0) { // If have attributes, get attributes we'll need xsiTypeString = _dataReader.GetAttribute(Keywords.TYPE, Keywords.XSINS); typeName = _dataReader.GetAttribute(Keywords.MSD_INSTANCETYPE, Keywords.MSDNS); } // Check if need to use XmlSerializer. We need to do that if type does not implement IXmlSerializable. // We also need to do that if no polymorphism for this type allowed. bool useXmlSerializer = !column.ImplementsIXMLSerializable && !((column.DataType == typeof(object)) || (typeName != null) || (xsiTypeString != null)); // Check if we have an attribute telling us value is null. if ((xsiNilString != null) && XmlConvert.ToBoolean(xsiNilString)) { if (!useXmlSerializer) { // See if need to set typed null. if (typeName != null && typeName.Length > 0) { // Got type name columnValue = SqlUdtStorage.GetStaticNullForUdtType(DataStorage.GetType(typeName)); } } if (null == columnValue) { // If no value, columnValue = DBNull.Value; // change to DBNull; } if (!_dataReader.IsEmptyElement) // In case element is not empty while (_dataReader.Read() && (entryDepth < _dataReader.Depth)) ; // Read current elements _dataReader.Read(); // And start reading next element. } else { // No NIL attribute. Get value bool skipped = false; if (column.Table.DataSet != null && column.Table.DataSet._udtIsWrapped) { _dataReader.Read(); // if UDT is wrapped, skip the wrapper skipped = true; } if (useXmlSerializer) { // Create an attribute for XmlSerializer if (skipped) { xmlAttrib = new XmlRootAttribute(_dataReader.LocalName); xmlAttrib.Namespace = _dataReader.NamespaceURI; } else { xmlAttrib = new XmlRootAttribute(column.EncodedColumnName); xmlAttrib.Namespace = column.Namespace; } } columnValue = column.ConvertXmlToObject(_dataReader, xmlAttrib); // Go get the value if (skipped) { _dataReader.Read(); // if Wrapper is skipped, skip its end tag } } foundColumns[column.Ordinal] = columnValue; // Store value } else { // Not a custom type. if (_dataReader.Read() && entryDepth < _dataReader.Depth) { // Read to the next element and see if we're inside. while (entryDepth < _dataReader.Depth) { switch (_dataReader.NodeType) { // Process nodes based on type case XmlNodeType.Text: // It looks like a text. And we need it. case XmlNodeType.Whitespace: case XmlNodeType.CDATA: case XmlNodeType.SignificantWhitespace: if (0 == text.Length) { // In case we do not have value already text = _dataReader.Value; // Get value. // See if we have other text nodes near. In most cases this loop will not be executed. StringBuilder builder = null; while (_dataReader.Read() && entryDepth < _dataReader.Depth && IsTextLikeNode(_dataReader.NodeType)) { if (builder == null) { builder = new StringBuilder(text); } builder.Append(_dataReader.Value); // Concatenate other sequential text like // nodes we might have. This is rare. // We're using this instead of dataReader.ReadString() // which would do the same thing but slower. } if (builder != null) { text = builder.ToString(); } } else { _dataReader.ReadString(); // We've got column value already. Read this one and ignore it. } break; case XmlNodeType.Element: if (ProcessXsdSchema()) { // Check for schema. Skip or load if found. continue; // Schema has been found. Process the next element // we're already at (done by schema processing). } else { // We've got element which is not supposed to he here. // That might be table which was misplaced. // Or it might be a column inside column (also misplaced). object o = _nodeToSchemaMap.GetColumnSchema(column.Table, _dataReader, FIgnoreNamespace(_dataReader)); // Get dataset element for this XML element DataColumn c = o as DataColumn; // Perhaps, it's a column? if (c != null) { // Do we have matched column in this table? // Let's load column data if (foundColumns[c.Ordinal] == null) { // If this column was not found before LoadColumn(c, foundColumns); // Get column value } else { _dataReader.Read(); // Already loaded, proceed to the next element } } else { DataTable nestedTable = o as DataTable; // Perhaps, it's a nested table ? if (nestedTable != null) { // Do we have matched table in DataSet ? LoadTable(nestedTable, true /* isNested */); // Yes. Load nested table (recursive) } else { // Not a nested column nor nested table. // Let's try other tables in the DataSet DataTable misplacedTable = _nodeToSchemaMap.GetTableForNode(_dataReader, FIgnoreNamespace(_dataReader)); // Try to get table for node if (misplacedTable != null) { // Got some table to match? LoadTable(misplacedTable, false /* isNested */); // While table's XML element is nested, // the table itself is not. Load it this way. } else { _dataReader.Read(); // No match? Try next element } } } } break; case XmlNodeType.EntityReference: // Oops. No support for Entity Reference throw ExceptionBuilder.FoundEntity(); default: _dataReader.Read(); // We don't process that, skip to the next element. break; } } _dataReader.Read(); // We're done here. To the next element. } if (0 == text.Length && xsiNilString != null && XmlConvert.ToBoolean(xsiNilString)) { foundColumns[column.Ordinal] = DBNull.Value; // If no data and NIL attribute is true set value to null } else { foundColumns[column.Ordinal] = column.ConvertXmlToObject(text); } } } // Check for schema and skips or loads XSD schema if found. Returns true if schema found. // DataReader would be set on the first XML element after the schema of schema was found. // If no schema detected, reader's position will not change. private bool ProcessXsdSchema() { if (((object)_dataReader.LocalName == _XSD_SCHEMA && (object)_dataReader.NamespaceURI == _XSDNS)) { // Found XSD schema if (_ignoreSchema) { // Should ignore it? _dataReader.Skip(); // Yes, skip it } else { // Have to load schema. if (_isTableLevel) { // Loading into the DataTable ? _dataTable.ReadXSDSchema(_dataReader, false); // Invoke ReadXSDSchema on a table _nodeToSchemaMap = new XmlToDatasetMap(_dataReader.NameTable, _dataTable); } // Rebuild XML to DataSet map with new schema. else { // Loading into the DataSet ? _dataSet.ReadXSDSchema(_dataReader, false); // Invoke ReadXSDSchema on a DataSet _nodeToSchemaMap = new XmlToDatasetMap(_dataReader.NameTable, _dataSet); } // Rebuild XML to DataSet map with new schema. } } else if (((object)_dataReader.LocalName == _XDR_SCHEMA && (object)_dataReader.NamespaceURI == _XDRNS) || ((object)_dataReader.LocalName == _SQL_SYNC && (object)_dataReader.NamespaceURI == _UPDGNS)) { _dataReader.Skip(); // Skip XDR or SQL sync } else { return false; // No schema found. That means reader's position // is unchganged. Report that to the caller. } return true; // Schema found, reader's position changed. } } }
46.621777
148
0.425466
[ "MIT" ]
06needhamt/runtime
src/libraries/System.Data.Common/src/System/Data/XmlDataLoader.cs
65,084
C#
// // Copyright (c) 2008-2011, Kenneth Bell // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // namespace GDImageBuilder.DiscUtils.Iso9660 { using System; using System.Collections.Generic; using System.Text; internal class PathTable : BuilderExtent { private bool _byteSwap; private Encoding _enc; private List<BuildDirectoryInfo> _dirs; private Dictionary<BuildDirectoryMember, uint> _locations; private byte[] _readCache; public PathTable(bool byteSwap, Encoding enc, List<BuildDirectoryInfo> dirs, Dictionary<BuildDirectoryMember, uint> locations, long start) : base(start, CalcLength(enc, dirs)) { _byteSwap = byteSwap; _enc = enc; _dirs = dirs; _locations = locations; } public override void Dispose() { } internal override void PrepareForRead() { _readCache = new byte[Length]; int pos = 0; List<BuildDirectoryInfo> sortedList = new List<BuildDirectoryInfo>(_dirs); sortedList.Sort(BuildDirectoryInfo.PathTableSortComparison); Dictionary<BuildDirectoryInfo, ushort> dirNumbers = new Dictionary<BuildDirectoryInfo, ushort>(_dirs.Count); ushort i = 1; foreach (BuildDirectoryInfo di in sortedList) { dirNumbers[di] = i++; PathTableRecord ptr = new PathTableRecord(); ptr.DirectoryIdentifier = di.PickName(null, _enc); ptr.LocationOfExtent = _locations[di]; ptr.ParentDirectoryNumber = dirNumbers[di.Parent]; pos += ptr.Write(_byteSwap, _enc, _readCache, pos); } } internal override int Read(long diskOffset, byte[] buffer, int offset, int count) { long relPos = diskOffset - Start; int numRead = (int)Math.Min(count, _readCache.Length - relPos); Array.Copy(_readCache, relPos, buffer, offset, numRead); return numRead; } internal override void DisposeReadState() { _readCache = null; } private static uint CalcLength(Encoding enc, List<BuildDirectoryInfo> dirs) { uint length = 0; foreach (BuildDirectoryInfo di in dirs) { length += di.GetPathTableEntrySize(enc); } return length; } } }
35.059406
146
0.63852
[ "MIT" ]
sizious/gdi-builder
GDImageBuilder/DiscUtils/Iso9660/PathTable.cs
3,541
C#
using System; using UnityEngine; using Random = UnityEngine.Random; namespace CreatorKitCodeInternal { /// <summary> /// Will pick a random time in an animation loop to offset an animator, allowing to avoid lots of object playing the /// same animation loop to look synchronised /// </summary> [RequireComponent(typeof(Animator))] public class RandomLoopOffset : MonoBehaviour { void Start() { var animator = GetComponent<Animator>(); animator.SetFloat("CycleOffset", Random.value); } } }
27.5
121
0.618182
[ "MIT" ]
AdeliaSabirova/gb0122
Assets/Creator Kit - Beginner Code/Scripts/Utility/RandomLoopOffset.cs
607
C#
using System; using System.Collections.Generic; using System.Linq; using NumericalMethods.Core.Extensions; using NumericalMethods.Core.Utils; using NumericalMethods.Core.Utils.Interfaces; using NumericalMethods.Core.Utils.RandomProviders; using NumericalMethods.Task3.Utils; namespace NumericalMethods.Task2 { class Program { private static readonly IRangedRandomProvider<int> _intRandom = new IntegerRandomProvider(); private static readonly IRangedRandomProvider<double> _doubleRandom = new DoubleRandomProvider(); const double NonZeroEps = 1e-5; static double FindAccuracies(int count, int halfRibbonLength, double minValue, double maxValue) { _ = count < 0 ? throw new ArgumentOutOfRangeException(nameof(count), "The number of elements must not be negative.") : true; double[,] matrixWithoutRightSide = _doubleRandom.GenerateBandedSymmetricMatrix(count, count, halfRibbonLength, minValue, maxValue).ToPoorlyConditionedMatrix(); IReadOnlyList<double> expectRandomSolution = _doubleRandom.Repeat(count, minValue, maxValue).ToArray(); var rightSideBuilder = new RightSideBuilder(matrixWithoutRightSide); IReadOnlyList<double> randomRightSide = rightSideBuilder.Build(expectRandomSolution); double[,] decomposition = CholeskyAlgorithm.DecomposeBandedMatrix(matrixWithoutRightSide, halfRibbonLength); IReadOnlyList<double> solution = MatrixDecompositionUtils.Solve(decomposition, randomRightSide); return AccuracyUtils.CalculateAccuracy(expectRandomSolution, solution, NonZeroEps); } static void Main() { const int TestCount = 2; var testCases = new TestCase[] { new TestCase(_intRandom, _intRandom.Next(10, 99), _doubleRandom.Next(10, 99), _doubleRandom.Next(10, 99)), new TestCase(_intRandom, _intRandom.Next(10, 99), _doubleRandom.Next(10, 99), _doubleRandom.Next(10, 99)), new TestCase(_intRandom, _intRandom.Next(100, 999), _doubleRandom.Next(100, 999), _doubleRandom.Next(100, 999)), new TestCase(_intRandom, _intRandom.Next(100, 999), _doubleRandom.Next(100, 999), _doubleRandom.Next(100, 999)) }; foreach (TestCase testCase in testCases) { IReadOnlyList<double> accuracies = Enumerable .Range(1, TestCount) .Select(_ => FindAccuracies(testCase.MatrixLength, testCase.HalfRibbonLength, testCase.MinValue, testCase.MaxValue)) .ToArray(); Console.WriteLine($"N = {testCase.MatrixLength}; HalfRibbonLength = {testCase.HalfRibbonLength}; Min = {testCase.MinValue}; Max = {testCase.MaxValue};"); Console.WriteLine($"Средняя относительная погрешность системы: {accuracies.Average()}"); } Console.ReadKey(true); } } }
47.603175
171
0.679226
[ "Apache-2.0" ]
Niapollab/Numerical_Methods_5-semester
NumericalMethods.Task2/Program.cs
3,039
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. using System; using System.Collections.Generic; using System.Linq; using System.Text; using UnityEditor; using UnityEngine; namespace Microsoft.MixedReality.Toolkit.Editor { /// <summary> /// Base class for all <see cref="Microsoft.MixedReality.Toolkit.BaseMixedRealityProfile"/> Inspectors to inherit from. /// </summary> public abstract class BaseMixedRealityProfileInspector : UnityEditor.Editor { private const string IsCustomProfileProperty = "isCustomProfile"; private static readonly GUIContent NewProfileContent = new GUIContent("+", "Create New Profile"); private static readonly String BaseMixedRealityProfileClassName = typeof(BaseMixedRealityProfile).Name; private static StringBuilder dropdownKeyBuilder = new StringBuilder(); protected virtual void OnEnable() { if (target == null) { // Either when we are recompiling, or the inspector window is hidden behind another one, the target can get destroyed (null) and thereby will raise an ArgumentException when accessing serializedObject. For now, just return. return; } } /// <summary> /// Renders a non-editable object field and an editable dropdown of a profile. /// </summary> /// <param name="property"></param> /// <returns></returns> public static void RenderReadOnlyProfile(SerializedProperty property) { EditorGUILayout.BeginHorizontal(); EditorGUI.BeginDisabledGroup(true); EditorGUILayout.ObjectField(property.objectReferenceValue != null ? "" : property.displayName, property.objectReferenceValue, typeof(BaseMixedRealityProfile), false, GUILayout.ExpandWidth(true)); EditorGUI.EndDisabledGroup(); EditorGUILayout.EndHorizontal(); if (property.objectReferenceValue != null) { UnityEditor.Editor subProfileEditor = UnityEditor.Editor.CreateEditor(property.objectReferenceValue); // If this is a default MRTK configuration profile, ask it to render as a sub-profile if (typeof(BaseMixedRealityToolkitConfigurationProfileInspector).IsAssignableFrom(subProfileEditor.GetType())) { BaseMixedRealityToolkitConfigurationProfileInspector configProfile = (BaseMixedRealityToolkitConfigurationProfileInspector)subProfileEditor; configProfile.RenderAsSubProfile = true; } EditorGUILayout.BeginHorizontal(); EditorGUI.indentLevel++; EditorGUILayout.BeginVertical(EditorStyles.helpBox); subProfileEditor.OnInspectorGUI(); EditorGUILayout.Space(); EditorGUILayout.EndVertical(); EditorGUI.indentLevel--; EditorGUILayout.EndHorizontal(); } } /// <summary> /// Renders a <see cref="Microsoft.MixedReality.Toolkit.BaseMixedRealityProfile"/>. /// </summary> /// <param name="property">the <see cref="Microsoft.MixedReality.Toolkit.BaseMixedRealityProfile"/> property.</param> /// <param name="showAddButton">If true, draw the clone button, if false, don't</param> /// <param name="renderProfileInBox">if true, render box around profile content, if false, don't</param> /// <param name="serviceType">Optional service type to limit available profile types.</param> /// <returns>True, if the profile changed.</returns> protected static bool RenderProfile(SerializedProperty property, Type profileType, bool showAddButton = true, bool renderProfileInBox = false, Type serviceType = null) { return RenderProfileInternal(property, profileType, showAddButton, renderProfileInBox, serviceType); } /// <summary> /// Renders a <see cref="Microsoft.MixedReality.Toolkit.BaseMixedRealityProfile"/>. /// </summary> /// <param name="property">the <see cref="Microsoft.MixedReality.Toolkit.BaseMixedRealityProfile"/> property.</param> /// <param name="showAddButton">If true, draw the clone button, if false, don't</param> /// <param name="renderProfileInBox">if true, render box around profile content, if false, don't</param> /// <param name="serviceType">Optional service type to limit available profile types.</param> /// <returns>True, if the profile changed.</returns> private static bool RenderProfileInternal(SerializedProperty property, Type profileType, bool showAddButton, bool renderProfileInBox, Type serviceType = null) { var profile = property.serializedObject.targetObject as BaseMixedRealityProfile; bool changed = false; var oldObject = property.objectReferenceValue; if (profileType != null && !profileType.IsSubclassOf(typeof(BaseMixedRealityProfile)) && profileType != typeof(BaseMixedRealityProfile)) { // If they've drag-and-dropped a non-profile scriptable object, set it to null. profileType = null; } // If we're constraining this to a service type, check whether the profile is valid // If it isn't, issue a warning. if (serviceType != null && oldObject != null) { if (!IsProfileForService(oldObject.GetType(), serviceType)) { EditorGUILayout.HelpBox("This profile is not supported for " + serviceType.Name + ". Using an unsupported service may result in unexpected behavior.", MessageType.Warning); } } // Find the profile type so we can limit the available object field options if (serviceType != null) { // If GetProfileTypesForService has a count greater than one, then it won't be possible to use // EditorGUILayout.ObjectField to restrict the set of profiles to a single type - in this // case all profiles of BaseMixedRealityProfile will be visible in the picker. // // However in the case where there is just a single profile type for the service, we can improve // upon the user experience by limiting the set of things that show in the picker by restricting // the set of profiles listed to only that type. profileType = GetProfileTypesForService(serviceType).FirstOrDefault(); } // If the profile type is still null, just set it to base profile type if (profileType == null) { profileType = typeof(BaseMixedRealityProfile); } // Begin the horizontal group EditorGUILayout.BeginHorizontal(); // Draw the object field with an empty label - label is kept in the foldout property.objectReferenceValue = EditorGUILayout.ObjectField(oldObject != null ? "" : property.displayName, oldObject, profileType, false, GUILayout.ExpandWidth(true)); changed = (property.objectReferenceValue != oldObject); // Draw the clone button if (property.objectReferenceValue == null) { var profileTypeName = property.type.Replace("PPtr<$", string.Empty).Replace(">", string.Empty); if (showAddButton && IsConcreteProfileType(profileTypeName)) { if (GUILayout.Button(NewProfileContent, EditorStyles.miniButton, GUILayout.Width(20f))) { Debug.Assert(profileTypeName != null, "No Type Found"); ScriptableObject instance = CreateInstance(profileTypeName); var newProfile = instance.CreateAsset(AssetDatabase.GetAssetPath(Selection.activeObject)) as BaseMixedRealityProfile; property.objectReferenceValue = newProfile; property.serializedObject.ApplyModifiedProperties(); changed = true; } } } else { var renderedProfile = property.objectReferenceValue as BaseMixedRealityProfile; Debug.Assert(renderedProfile != null); Debug.Assert(profile != null, "No profile was set in OnEnable. Did you forget to call base.OnEnable in a derived profile class?"); if (GUILayout.Button(new GUIContent("Clone", "Replace with a copy of the default profile."), EditorStyles.miniButton, GUILayout.Width(42f))) { MixedRealityProfileCloneWindow.OpenWindow(profile, renderedProfile, property); } } EditorGUILayout.EndHorizontal(); if (property.objectReferenceValue != null) { UnityEditor.Editor subProfileEditor = UnityEditor.Editor.CreateEditor(property.objectReferenceValue); // If this is a default MRTK configuration profile, ask it to render as a sub-profile if (typeof(BaseMixedRealityToolkitConfigurationProfileInspector).IsAssignableFrom(subProfileEditor.GetType())) { BaseMixedRealityToolkitConfigurationProfileInspector configProfile = (BaseMixedRealityToolkitConfigurationProfileInspector)subProfileEditor; configProfile.RenderAsSubProfile = true; } var subProfile = property.objectReferenceValue as BaseMixedRealityProfile; if (subProfile != null && !subProfile.IsCustomProfile) { EditorGUILayout.HelpBox("Clone this default profile to edit properties below", MessageType.Warning); } if (renderProfileInBox) { EditorGUILayout.BeginVertical(EditorStyles.helpBox); } else { EditorGUILayout.BeginVertical(); } EditorGUILayout.Space(); subProfileEditor.OnInspectorGUI(); EditorGUILayout.Space(); EditorGUILayout.EndVertical(); } return changed; } /// <summary> /// Render Bold/HelpBox style Foldout /// </summary> /// <param name="currentState">reference bool for current visibility state of foldout</param> /// <param name="title">Title in foldout</param> /// <param name="renderContent">code to execute to render inside of foldout</param> protected static void RenderFoldout(ref bool currentState, string title, Action renderContent) { EditorGUILayout.BeginVertical(EditorStyles.helpBox); currentState = EditorGUILayout.Foldout(currentState, title, true, MixedRealityStylesUtility.BoldFoldoutStyle); if (currentState) { renderContent(); } EditorGUILayout.EndVertical(); } private static string GetSubProfileDropdownKey(SerializedProperty property) { if (property.objectReferenceValue == null) { throw new Exception("Can't get sub profile dropdown key for a property that is null."); } dropdownKeyBuilder.Clear(); dropdownKeyBuilder.Append("MRTK_SubProfile_ShowDropdown_"); dropdownKeyBuilder.Append(property.name); dropdownKeyBuilder.Append("_"); dropdownKeyBuilder.Append(property.objectReferenceValue.GetType().Name); return dropdownKeyBuilder.ToString(); } protected static BaseMixedRealityProfile CreateCustomProfile(BaseMixedRealityProfile sourceProfile) { if (sourceProfile == null) { return null; } ScriptableObject newProfile = CreateInstance(sourceProfile.GetType().ToString()); BaseMixedRealityProfile targetProfile = newProfile.CreateAsset("Assets/MixedRealityToolkit.Generated/CustomProfiles") as BaseMixedRealityProfile; Debug.Assert(targetProfile != null); EditorUtility.CopySerialized(sourceProfile, targetProfile); var serializedProfile = new SerializedObject(targetProfile); serializedProfile.FindProperty(IsCustomProfileProperty).boolValue = true; serializedProfile.ApplyModifiedProperties(); AssetDatabase.SaveAssets(); if (!sourceProfile.IsCustomProfile) { // For now we only replace it if it's the master configuration profile. // Sub-profiles are easy to update in the master configuration inspector. if (MixedRealityToolkit.Instance.ActiveProfile.GetType() == targetProfile.GetType()) { UnityEditor.Undo.RecordObject(MixedRealityToolkit.Instance, "Copy & Customize Profile"); MixedRealityToolkit.Instance.ActiveProfile = targetProfile as MixedRealityToolkitConfigurationProfile; } } return targetProfile; } /// <summary> /// Given a service type, finds all sub-classes of BaseMixedRealityProfile that are /// designed to configure that service. /// </summary> private static IReadOnlyCollection<Type> GetProfileTypesForService(Type serviceType) { if (serviceType == null) { return Array.Empty<Type>(); } // This is a little inefficient in that it has to enumerate all of the mixed reality // profiles in order to make this enumeration. It would be possible to cache the results // of this, but then it would be necessary to listen to file/asset creation/destruction // events in order to refresh the cache. If this ends up being a perf bottleneck // in inspectors this would be one possible way to alleviate the issue. HashSet<Type> allTypes = new HashSet<Type>(); BaseMixedRealityProfile[] allProfiles = ScriptableObjectExtensions.GetAllInstances<BaseMixedRealityProfile>(); for (int i = 0; i < allProfiles.Length; i++) { BaseMixedRealityProfile profile = allProfiles[i]; if (IsProfileForService(profile.GetType(), serviceType)) { allTypes.Add(profile.GetType()); } } return allTypes.ToReadOnlyCollection(); } /// <summary> /// Returns true if the given profile type is designed to configure the given service. /// </summary> private static bool IsProfileForService(Type profileType, Type serviceType) { foreach (MixedRealityServiceProfileAttribute serviceProfileAttribute in profileType.GetCustomAttributes(typeof(MixedRealityServiceProfileAttribute), true)) { if (serviceProfileAttribute.ServiceType.IsAssignableFrom(serviceType)) { return true; } } return false; } private static bool IsConcreteProfileType(String profileTypeName) { return profileTypeName != BaseMixedRealityProfileClassName; } /// <summary> /// Checks if the profile is locked /// </summary> /// <param name="target"></param> /// <param name="lockProfile"></param> protected static bool IsProfileLock(BaseMixedRealityProfile profile) { return MixedRealityPreferences.LockProfiles && !profile.IsCustomProfile; } } }
49.826347
240
0.604615
[ "MIT" ]
BrettPyle/MapsSDK-Unity
SampleProject/Assets/MixedRealityToolkit/Inspectors/Profiles/BaseMixedRealityProfileInspector.cs
16,646
C#
// // Copyright 2019 Google LLC // // 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.Threading; using System.Threading.Tasks; namespace Google.Solutions.Compute.Net { /// <summary> /// Base class for a stream that only allows one reader and one writer /// at a time. /// </summary> public abstract class SingleReaderSingleWriterStream : OneTimeUseStream { private readonly SemaphoreSlim readerSemaphore = new SemaphoreSlim(1); private readonly SemaphoreSlim writerSemaphore = new SemaphoreSlim(1); //--------------------------------------------------------------------- // Methods to be overriden //--------------------------------------------------------------------- protected abstract Task<int> ProtectedReadAsync( byte[] buffer, int offset, int count, CancellationToken cancellationToken); protected abstract Task ProtectedWriteAsync( byte[] buffer, int offset, int count, CancellationToken cancellationToken); public abstract Task ProtectedCloseAsync(CancellationToken cancellationToken); //--------------------------------------------------------------------- // Publics //--------------------------------------------------------------------- protected override async Task<int> ReadAsyncWithCloseProtection( byte[] buffer, int offset, int count, CancellationToken cancellationToken) { try { // Acquire semaphore to ensure that only a single // read operation is in flight at a time. await this.readerSemaphore.WaitAsync(cancellationToken).ConfigureAwait(false); return await ProtectedReadAsync( buffer, offset, count, cancellationToken).ConfigureAwait(false); } finally { this.readerSemaphore.Release(); } } protected override async Task WriteAsyncWithCloseProtection(byte[] buffer, int offset, int count, CancellationToken cancellationToken) { try { // Acquire semaphore to ensure that only a single // write/close operation is in flight at a time. await this.writerSemaphore.WaitAsync(cancellationToken).ConfigureAwait(false); await ProtectedWriteAsync( buffer, offset, count, cancellationToken).ConfigureAwait(false); } finally { this.writerSemaphore.Release(); } } protected override async Task CloseAsyncWithCloseProtection(CancellationToken cancellationToken) { try { // Acquire semaphore to ensure that only a single // write/close operation is in flight at a time. await this.writerSemaphore.WaitAsync(cancellationToken).ConfigureAwait(false); await ProtectedCloseAsync(cancellationToken).ConfigureAwait(false); } finally { this.writerSemaphore.Release(); } } protected override void Dispose(bool disposing) { if (disposing) { this.readerSemaphore.Dispose(); this.writerSemaphore.Dispose(); } } } }
34.403101
142
0.55205
[ "Apache-2.0" ]
Mdlglobal-atlassian-net/iap-desktop
Google.Solutions.Compute/Net/SingleReaderSingleWriterStream.cs
4,440
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.SumoLogic.Inputs { public sealed class HierarchyLevelNextLevelNextLevelsWithConditionLevelNextLevelsWithConditionLevelNextLevelsWithConditionLevelNextLevelsWithConditionGetArgs : Pulumi.ResourceArgs { /// <summary> /// Condition to be checked against for level.entityType value, for now full string match. /// </summary> [Input("condition", required: true)] public Input<string> Condition { get; set; } = null!; [Input("level", required: true)] public Input<Inputs.HierarchyLevelNextLevelNextLevelsWithConditionLevelNextLevelsWithConditionLevelNextLevelsWithConditionLevelNextLevelsWithConditionLevelGetArgs> Level { get; set; } = null!; public HierarchyLevelNextLevelNextLevelsWithConditionLevelNextLevelsWithConditionLevelNextLevelsWithConditionLevelNextLevelsWithConditionGetArgs() { } } }
42.068966
200
0.758197
[ "ECL-2.0", "Apache-2.0" ]
pulumi/pulumi-sumologic
sdk/dotnet/Inputs/HierarchyLevelNextLevelNextLevelsWithConditionLevelNextLevelsWithConditionLevelNextLevelsWithConditionLevelNextLevelsWithConditionGetArgs.cs
1,220
C#
// ----- AUTO GENERATED CODE ----- // namespace TheEscapists.Core.Generated { public static class UnityScenes { public enum eUnityScenes { SampleScene }; } }
19.777778
49
0.629213
[ "MIT" ]
The-Escapists/Escape-Room-Loop-V2
EscapeRoomLoopV2Project/Assets/The Escapists/Scripts/Core/Generated/UnityScenes.cs
178
C#
namespace LocalWeatherApp.Services.WeatherService.Models { using Newtonsoft.Json; using System; using System.Collections.Generic; public class WeatherLocationDetail { [JsonProperty("consolidated_weather")] public List<ConsolidatedWeather> ConsolidatedWeather { get; set; } [JsonProperty("time")] public DateTimeOffset Time { get; set; } [JsonProperty("sun_rise")] public DateTimeOffset SunRise { get; set; } [JsonProperty("sun_set")] public DateTimeOffset SunSet { get; set; } [JsonProperty("timezone_name")] public string TimezoneName { get; set; } [JsonProperty("parent")] public Parent Parent { get; set; } [JsonProperty("sources")] public List<Source> Sources { get; set; } [JsonProperty("title"), JsonRequired] public string Title { get; set; } [JsonProperty("location_type")] public string LocationType { get; set; } [JsonProperty("woeid")] public long Woeid { get; set; } [JsonProperty("latt_long")] public string LattLong { get; set; } [JsonProperty("timezone")] public string Timezone { get; set; } } public class ConsolidatedWeather { [JsonProperty("id")] public long Id { get; set; } [JsonProperty("weather_state_name")] public string WeatherStateName { get; set; } [JsonProperty("weather_state_abbr")] public string WeatherStateAbbr { get; set; } [JsonProperty("wind_direction_compass")] public string WindDirectionCompass { get; set; } [JsonProperty("created")] public DateTimeOffset Created { get; set; } [JsonProperty("applicable_date"), JsonRequired] public DateTimeOffset ApplicableDate { get; set; } [JsonProperty("min_temp"), JsonRequired] public float MinTemp { get; set; } [JsonProperty("max_temp"), JsonRequired] public float MaxTemp { get; set; } [JsonProperty("the_temp")] public float TheTemp { get; set; } /// <summary> /// mpf /// </summary> [JsonProperty("wind_speed")] public float WindSpeed { get; set; } /// <summary> /// degrees /// </summary> [JsonProperty("wind_direction")] public float WindDirection { get; set; } [JsonProperty("air_pressure")] public float AirPressure { get; set; } [JsonProperty("humidity")] public long Humidity { get; set; } [JsonProperty("visibility")] public float Visibility { get; set; } [JsonProperty("predictability")] public long Predictability { get; set; } } public class Parent { [JsonProperty("title")] public string Title { get; set; } [JsonProperty("location_type")] public string LocationType { get; set; } [JsonProperty("woeid")] public long Woeid { get; set; } [JsonProperty("latt_long")] public string LattLong { get; set; } } public class Source { [JsonProperty("title")] public string Title { get; set; } [JsonProperty("slug")] public string Slug { get; set; } [JsonProperty("url")] public Uri Url { get; set; } [JsonProperty("crawl_rate")] public long CrawlRate { get; set; } } }
26.623077
74
0.58538
[ "MIT" ]
Feelav/LocalWeatherApp
LocalWeatherApp/Services/WeatherService/Models/WeatherLocationDetail.cs
3,463
C#
using NUnit.Framework; using Okapi.Attributes; using Okapi.Drivers; using Okapi.Elements; using Okapi.Report; using Okapi.Support.Report.NUnit; using TestCase = Okapi.Attributes.TestCaseAttribute; namespace OkapiSampleTests.TestCases { [TestFixture] public class ReportWithNUnitContext { [OneTimeSetUp] public static void ClassInit() { } [OneTimeTearDown] public static void ClassCleanup() { } [SetUp] public void TestInit() { } [TearDown] public void TestCleanup() { TestReport.Report(TestContext.CurrentContext.ToOkapiTestContext()); DriverPool.Instance.QuitActiveDriver(); } [Test] [TestCase] public void Passed_test() { DriverPool.Instance.ActiveDriver.LaunchPage("https://accounts.google.com/signup"); int elementCount = TestObject.New(SearchInfo.New("span", "Next")).ElementCount; TestReport.IsTrue(elementCount == 1); } [Test] [TestCase] public void Failed_test() { DriverPool.Instance.ActiveDriver.LaunchPage("https://accounts.google.com/signup"); int elementCount = TestObject.New(SearchInfo.New("span", "Next")).ElementCount; TestReport.IsTrue(elementCount == 2, $"Number of found elements: {elementCount}"); } } }
26.851852
94
0.607586
[ "Apache-2.0" ]
tamnguyenbbt/Okapi
OkapiSampleTests/TestCases/ReportWithNUnitContext.cs
1,450
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.EventSystems; using UnityEngine.UI; public class Shooting : MonoBehaviour { [SerializeField] private GameObject projectile; [SerializeField] private float projectileSpeed; [SerializeField] private Sprite shootingSprite; [SerializeField] private Vector3 shootingOffset; private GameObject instantiatedProjectile; public bool isShooting = false; private bool movingRight; private float lastY; private float lastShotTime = 0; private SpriteRenderer characterRenderer; private Vector3 shootingOffsetLeft; // Start is called before the first frame update void Start() { characterRenderer = this.GetComponent<SpriteRenderer>(); shootingOffsetLeft = new Vector3(-shootingOffset.x, shootingOffset.y, shootingOffset.z); } // Update is called once per frame void Update() { if(GameState.GetInstance().hasMiles && Input.GetMouseButtonDown(0) && !GameState.GetInstance().gamePaused && !EventSystem.current.IsPointerOverGameObject()) { characterRenderer.sprite = shootingSprite; Shoot(); isShooting = true; lastShotTime = Time.time; } else if(isShooting && Time.time - lastShotTime > 0.5f) { isShooting = false; } } private void Shoot() { Vector3 cursorScreenPosition = Input.mousePosition; cursorScreenPosition.z = 10; Vector3 localCursorPosition = Camera.main.ScreenToWorldPoint(cursorScreenPosition); Vector2 localCursorPosition2D = new Vector2(localCursorPosition.x, localCursorPosition.y); Vector2 playerPosition = new Vector2(transform.position.x, transform.position.y); Vector2 shootingDirection = localCursorPosition2D - playerPosition; float angle = Vector2.Angle(shootingDirection, transform.up); if (shootingDirection.x <= 0) { if(!characterRenderer.flipX) { FMODUnity.RuntimeManager.PlayOneShot("event:/SFX/Player Character/Turn", GetComponent<Transform>().position); } characterRenderer.flipX = true; instantiatedProjectile = GameObject.Instantiate(projectile, transform.position + shootingOffsetLeft, Quaternion.Euler(0, 0, angle)); } else { if(characterRenderer.flipX) { FMODUnity.RuntimeManager.PlayOneShot("event:/SFX/Player Character/Turn", GetComponent<Transform>().position); } characterRenderer.flipX = false; instantiatedProjectile = GameObject.Instantiate(projectile, transform.position + shootingOffset, Quaternion.Euler(0, 0, -angle)); } FMODUnity.RuntimeManager.PlayOneShot("event:/SFX/Miles/Miles Gunshot", GetComponent<Transform>().position); Rigidbody2D rbProjectile = instantiatedProjectile.GetComponent<Rigidbody2D>(); instantiatedProjectile.GetComponent<Projectile>().DegradeProjectile(); rbProjectile.velocity = shootingDirection * projectileSpeed; } }
40.2375
144
0.673812
[ "MIT" ]
Liktoria/Breathe
Assets/Scripts/Player/Shooting.cs
3,219
C#
// --------------------------------------------------------------------------- // <copyright file="ITimeOffCacheService.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> // --------------------------------------------------------------------------- namespace WfmTeams.Adapter.Services { using System; using System.Threading.Tasks; using WfmTeams.Adapter.Models; public interface ITimeOffCacheService { Task DeleteTimeOffAsync(string teamId, DateTime weekStartDate); Task<CacheModel<TimeOffModel>> LoadTimeOffAsync(string teamId, DateTime weekStartDate); Task SaveTimeOffAsync(string teamId, DateTime weekStartDate, CacheModel<TimeOffModel> cacheModel); } }
34.818182
106
0.588773
[ "MIT" ]
Andy65/Microsoft-Teams-Shifts-WFM-Connectors
WFM-Teams-Adapter/src/WfmTeams.Adapter/Services/ITimeOffCacheService.cs
768
C#
// <copyright file="TaskContinuationGenerator.cs" company="Datadog"> // Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. // This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. // </copyright> using System; using System.Runtime.ExceptionServices; using System.Threading.Tasks; namespace Datadog.Trace.ClrProfiler.CallTarget.Handlers.Continuations { internal class TaskContinuationGenerator<TIntegration, TTarget, TReturn> : ContinuationGenerator<TTarget, TReturn> { private static readonly Func<TTarget, object, Exception, CallTargetState, object> _continuation; private static readonly bool _preserveContext; static TaskContinuationGenerator() { var result = IntegrationMapper.CreateAsyncEndMethodDelegate(typeof(TIntegration), typeof(TTarget), typeof(object)); if (result.Method != null) { _continuation = (Func<TTarget, object, Exception, CallTargetState, object>)result.Method.CreateDelegate(typeof(Func<TTarget, object, Exception, CallTargetState, object>)); _preserveContext = result.PreserveContext; } } public override TReturn SetContinuation(TTarget instance, TReturn returnValue, Exception exception, CallTargetState state) { if (_continuation == null) { return returnValue; } if (exception != null || returnValue == null) { _continuation(instance, default, exception, state); return returnValue; } Task previousTask = FromTReturn<Task>(returnValue); if (previousTask.Status == TaskStatus.RanToCompletion) { _continuation(instance, default, null, state); return returnValue; } return ToTReturn(ContinuationAction(previousTask, instance, state)); } private static async Task ContinuationAction(Task previousTask, TTarget target, CallTargetState state) { if (!previousTask.IsCompleted) { await new NoThrowAwaiter(previousTask, _preserveContext); } Exception exception = null; if (previousTask.Status == TaskStatus.Faulted) { exception = previousTask.Exception.GetBaseException(); } else if (previousTask.Status == TaskStatus.Canceled) { try { // The only supported way to extract the cancellation exception is to await the task await previousTask.ConfigureAwait(_preserveContext); } catch (Exception ex) { exception = ex; } } try { // * // Calls the CallTarget integration continuation, exceptions here should never bubble up to the application // * _continuation(target, null, exception, state); } catch (Exception ex) { IntegrationOptions<TIntegration, TTarget>.LogException(ex, "Exception occurred when calling the CallTarget integration continuation."); } // * // If the original task throws an exception we rethrow it here. // * if (exception != null) { ExceptionDispatchInfo.Capture(exception).Throw(); } } } }
37.663265
187
0.587917
[ "Apache-2.0" ]
lucaspimentel/dd-trace-dotnet
tracer/src/Datadog.Trace/ClrProfiler/CallTarget/Handlers/Continuations/TaskContinuationGenerator.cs
3,691
C#
using UnityEngine; namespace Plugboard.Data { // TODO: give this a better name, like EventInfo? [System.Serializable] public struct EventType { /// <summary> /// The human-readable name of this event. /// </summary> [SerializeField, HideInInspector] internal string name; public string Name { get { return name; } } /// <summary> /// The unique ID of this event. /// </summary> [SerializeField, HideInInspector] internal int id; public int ID { get { return id; } } } }
27.681818
54
0.54844
[ "MIT" ]
ntratcliff/plugboard
Scripts/Data/EventType.cs
611
C#
using System; using System.Runtime.Serialization; [Serializable] internal class NetworkEntityFactoryMethodNotFoundException : Exception { public NetworkEntityFactoryMethodNotFoundException() { } public NetworkEntityFactoryMethodNotFoundException(int id) : base (string.Format("Could not found a NetworkEntityFactoryMethod with id: {0}", id) ){ } public NetworkEntityFactoryMethodNotFoundException(string message) : base(message) { } public NetworkEntityFactoryMethodNotFoundException(string message, Exception innerException) : base(message, innerException) { } protected NetworkEntityFactoryMethodNotFoundException(SerializationInfo info, StreamingContext context) : base(info, context) { } }
32.391304
152
0.779866
[ "MIT" ]
Spy-Shifty/BBSNetworkSystem
Utility/NetworkEntityFactoryMethodNotFoundException.cs
747
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Builder : MonoBehaviour { public Transform _planet; public Transform _cratePrefab; public Transform _turretPrefab; public SpriteRenderer _preview; public float _horisontalDistance = -1.2f; public float _buildHigher = 5f; public float _buildLower = 4f; public LayerMask _layerMask; private bool _buildInput; private GameManager gameManager; [SerializeField] Transform buildGroup; void Start() { gameManager = FindObjectOfType<GameManager>(); } void Update () { var spawnTarget = transform.position + transform.right * _horisontalDistance; var upDir = (spawnTarget - _planet.position).normalized; var castOrigin = spawnTarget + upDir * _buildHigher; //_crate.position = transform.position; //var col = _crate.GetComponent<Collider2D> (); DebugPoint (castOrigin, Color.yellow); DebugPoint (upDir, Color.green); var boxRotation = Quaternion.LookRotation (Vector3.forward, upDir); var size = _cratePrefab.GetComponent<BoxCollider2D> ().size * _cratePrefab.localScale.x; var hit = Physics2D.BoxCast (castOrigin, size, boxRotation.eulerAngles.z, -upDir, _buildHigher + _buildLower, _layerMask); var spaceAvaliable = hit.collider != null && hit.distance != 0f; _preview.gameObject.SetActive (spaceAvaliable); var onTopOfTurret = hit.collider != null && LayerMask.LayerToName (hit.collider.gameObject.layer) == "turret"; _preview.color = onTopOfTurret ? Color.red : Color.white; if (!spaceAvaliable) return; var targetPosition = castOrigin - upDir * hit.distance; Debug.DrawLine (castOrigin, targetPosition, Color.magenta); _preview.transform.rotation = boxRotation; _preview.transform.position = targetPosition; if (onTopOfTurret) return; if (Input.GetKeyDown (KeyCode.K)) { Build (_cratePrefab, targetPosition, boxRotation); } if (Input.GetKeyDown (KeyCode.L)) { Build (_turretPrefab, targetPosition, boxRotation); } // if (Input.GetKeyDown (KeyCode.K) && gameManager.Ressources >= _cratePrefab.GetComponent<Buildable>().Cost) { // Instantiate<Transform>(_cratePrefab, targetPosition, boxRotation, buildGroup); // gameManager.Ressources -= _cratePrefab.GetComponent<Buildable>().Cost; // } // // if (Input.GetKeyDown (KeyCode.L) && gameManager.Ressources >= _turretPrefab.GetComponent<Buildable>().Cost) { // Instantiate<Transform>(_turretPrefab, targetPosition, boxRotation, buildGroup); // gameManager.Ressources -= _turretPrefab.GetComponent<Buildable>().Cost; // } } void Build (Transform prefab, Vector3 position, Quaternion rotation) { var buildable = prefab.GetComponent<Buildable> (); var canBuild = gameManager.CanBuild (buildable); if (canBuild) { var newBuilding = Instantiate<Transform>(prefab, position, rotation, buildGroup); gameManager.Build (newBuilding.GetComponent<Buildable>()); } } void DebugPoint (Vector2 point, Color col) { Debug.DrawLine (Vector2.zero, point, col); } }
30.64
124
0.733029
[ "MIT" ]
alexisgea/ludumdare38
PlanetProject/Assets/Scripts/Builder.cs
3,066
C#
using System; using System.Data.Entity; using System.IO; using System.Net; using System.Reflection; using System.Security.Cryptography.X509Certificates; using AutoMapper; using log4net; using Unity; using Unity.Lifetime; using WebMoney.Services.BusinessObjects; using WebMoney.Services.Contracts; using WebMoney.Services.Contracts.BusinessObjects; using WebMoney.Services.DataAccess.EF; using WebMoney.XmlInterfaces.Core; namespace WebMoney.Services { public sealed class ConfigurationService : IConfigurationService { private const string TrustedCertificatesFolder = "TrustedCertificates"; private static readonly ILog Logger = LogManager.GetLogger(typeof(ConfigurationService)); private static string _installationReference; public string InstallationReference { get => _installationReference; set => _installationReference = value; } public void RegisterServices(IUnityContainer unityContainer) { if (null == unityContainer) throw new ArgumentNullException(nameof(unityContainer)); // Первичная конфигурация. Configure(); // Регистрация сервисов unityContainer.RegisterType<IConfigurationService, ConfigurationService>(); unityContainer.RegisterType<IContractService, ContractService>(); unityContainer.RegisterType<ICurrencyService, CurrencyService>(); unityContainer.RegisterType<IEntranceService, EntranceService>(); unityContainer.RegisterType<IIdentifierService, IdentifierService>(); unityContainer.RegisterType<IImportExportService, ImportExportService>(); unityContainer.RegisterType<IInvoiceService, InvoiceService>(); unityContainer.RegisterType<IMessageService, MessageService>(); unityContainer.RegisterType<IPaymentService, PaymentService>(); unityContainer.RegisterType<IPurseService, PurseService>(); unityContainer.RegisterType<ISmsService, SmsService>(); unityContainer.RegisterType<ITransferBundleService, TransferBundleService>(); unityContainer.RegisterType<ITransferService, TransferService>(); unityContainer.RegisterType<ITrustService, TrustService>(); unityContainer.RegisterType<IVerificationService, VerificationService>(); unityContainer.RegisterType<IFormattingService, FormattingService>(); unityContainer.RegisterType<ITransferBundleProcessor, TransferBundleProcessor>( new ContainerControlledLifetimeManager()); unityContainer.RegisterType<IEventBroker, EventBroker>(new ContainerControlledLifetimeManager()); // ExternalServices ExternalServices.Configurator.ConfigureUnityContainer(unityContainer); } private static void Configure() { if (PlatformID.Unix == Environment.OSVersion.Platform) CertificateValidator.DisableValidation = true; else ConfigureCertificateValidator(); ServicePointManager.ServerCertificateValidationCallback = CertificateValidator.RemoteCertificateValidationCallback; // DbConfiguration DbConfiguration.SetConfiguration(new DataConfiguration()); // Mapper Mapper.Initialize(cfg => { cfg.CreateMap<IAuthenticationSettings, AuthenticationSettings>(); cfg.CreateMap<IConnectionSettings, ConnectionSettings>(); cfg.CreateMap<IProxyCredential, ProxyCredential>(); cfg.CreateMap<IProxySettings, ProxySettings>(); cfg.CreateMap<IRequestNumberSettings, RequestNumberSettings>(); cfg.CreateMap<IContractSettings, ContractSettings>(); cfg.CreateMap<IIncomingInvoiceSettings, IncomingInvoiceSettings>(); cfg.CreateMap<IOperationSettings, OperationSettings>(); cfg.CreateMap<IOutgoingInvoiceSettings, OutgoingInvoiceSettings>(); cfg.CreateMap<IPreparedTransferSettings, PreparedTransferSettings>(); cfg.CreateMap<IRequestSettings, RequestSettings>(); cfg.CreateMap<ISettings, Settings>(); cfg.CreateMap<ITransferBundleSettings, TransferBundleSettings>(); cfg.CreateMap<ITransferSettings, TransferSettings>(); }); } private static void ConfigureCertificateValidator() { string assemblyFile = new Uri(Assembly.GetExecutingAssembly().CodeBase).LocalPath; string assemblyDirectory = Path.GetDirectoryName(assemblyFile); string trustedRootCertificatesDirectory = null; if (null != assemblyDirectory && Directory.Exists(assemblyDirectory)) trustedRootCertificatesDirectory = Path.Combine(assemblyDirectory, TrustedCertificatesFolder); if (null == trustedRootCertificatesDirectory || !Directory.Exists(trustedRootCertificatesDirectory)) trustedRootCertificatesDirectory = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, TrustedCertificatesFolder); if (!Directory.Exists(trustedRootCertificatesDirectory)) { Logger.Warn("Certificate validator disabled!"); CertificateValidator.DisableValidation = true; return; } foreach (var file in Directory.GetFiles(trustedRootCertificatesDirectory, "*.cer")) { X509Certificate2 x509Certificate2; try { x509Certificate2 = new X509Certificate2(file); } catch (Exception exception) { Logger.Error(exception.Message, exception); continue; } CertificateValidator.RegisterTrustedCertificate(x509Certificate2); Logger.DebugFormat("Trusted certificate registered [thumbprint={0}].", x509Certificate2.Thumbprint); } } } }
43.426573
116
0.667472
[ "MIT" ]
MarketKernel/webmoney-business-tools
Src/WebMoney.Services/ConfigurationService.cs
6,252
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; using UnityEngine.UI; public class RatinhoJogador : MonoBehaviour { private CharacterController controle; public float speedFrente; public float speedLado; public float jumpHeight; float jumpVelocity; public float gravidade; public GameObject ratinho; RaycastHit hit; public int vida = 3; public int Vida { get { return vida; } set { vida = value; } } void Start() { controle = GetComponent<CharacterController>(); } void Update() { Movimento(); Saude(); } void Movimento() { Vector3 dir = transform.forward * speedFrente; if (transform.position.y < 0.5f) { if (Input.GetKeyDown(KeyCode.Space)) { jumpVelocity = jumpHeight; } } else { jumpVelocity -= gravidade; } dir.y = jumpVelocity; controle.Move(dir * Time.deltaTime); float h = Input.GetAxis("Horizontal"); Vector3 lado = transform.right * speedLado * h; controle.Move(lado * Time.deltaTime); } void Saude() { if(Vida <= 0) { SceneManager.LoadScene("FimDeJogo"); } } void OnTriggerEnter(Collider outro) { if (outro.gameObject.CompareTag("Rotation")) { float grau = outro.gameObject.GetComponent<Colisor>().rotacao; transform.rotation = Quaternion.Euler(0, grau, 0); } if (outro.gameObject.CompareTag("Veneno")) { Vida--; Destroy(outro.gameObject); } if (outro.gameObject.CompareTag("Chegada")) { SceneManager.LoadScene("ParaBens"); } } }
23.193182
75
0.516903
[ "MIT" ]
VitorMiranda27/Projeto_Ratos
Packages/Assets/scripts/RatinhoJogador.cs
2,041
C#
namespace EvidenceApi.V1.Infrastructure.Interfaces { public interface IFileReader<T> { T GetData(); } }
15.5
50
0.653226
[ "MIT" ]
LBHackney-IT/evidence-api
EvidenceApi/V1/Infrastructure/Interfaces/IFileReader.cs
124
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace TickTrader.Algo.Api { public enum Colors { Auto = -1, AliceBlue = 15792383, AntiqueWhite = 16444375, Aqua = 65535, Aquamarine = 8388564, Azure = 15794175, Beige = 16119260, Bisque = 16770244, Black = 0, BlanchedAlmond = 16772045, Blue = 255, BlueViolet = 9055202, Brown = 10824234, BurlyWood = 14596231, CadetBlue = 6266528, Chartreuse = 8388352, Chocolate = 13789470, Coral = 16744272, CornflowerBlue = 6591981, Cornsilk = 16775388, Crimson = 14423100, Cyan = 65535, DarkBlue = 139, DarkCyan = 35723, DarkGoldenrod = 12092939, DarkGray = 11119017, DarkGreen = 25600, DarkKhaki = 12433259, DarkMagenta = 9109643, DarkOliveGreen = 5597999, DarkOrange = 16747520, DarkOrchid = 10040012, DarkRed = 9109504, DarkSalmon = 15308410, DarkSeaGreen = 9419919, DarkSlateBlue = 4734347, DarkSlateGray = 3100495, DarkTurquoise = 52945, DarkViolet = 9699539, DeepPink = 16716947, DeepSkyBlue = 49151, DimGray = 6908265, DodgerBlue = 2003199, Firebrick = 11674146, FloralWhite = 16775920, ForestGreen = 2263842, Fuchsia = 16711935, Gainsboro = 14474460, GhostWhite = 16316671, Gold = 16766720, Goldenrod = 14329120, Gray = 8421504, Green = 32768, GreenYellow = 11403055, Honeydew = 15794160, HotPink = 16738740, IndianRed = 13458524, Indigo = 4915330, Ivory = 16777200, Khaki = 15787660, Lavender = 15132410, LavenderBlush = 16773365, LawnGreen = 8190976, LemonChiffon = 16775885, LightBlue = 11393254, LightCoral = 15761536, LightCyan = 14745599, LightGoldenrodYellow = 16448210, LightGray = 13882323, LightGreen = 9498256, LightPink = 16758465, LightSalmon = 16752762, LightSeaGreen = 2142890, LightSkyBlue = 8900346, LightSlateGray = 7833753, LightSteelBlue = 11584734, LightYellow = 16777184, Lime = 65280, LimeGreen = 3329330, Linen = 16445670, Magenta = 16711935, Maroon = 8388608, MediumAquamarine = 6737322, MediumBlue = 205, MediumOrchid = 12211667, MediumPurple = 9662683, MediumSeaGreen = 3978097, MediumSlateBlue = 8087790, MediumSpringGreen = 64154, MediumTurquoise = 4772300, MediumVioletRed = 13047173, MidnightBlue = 1644912, MintCream = 16121850, MistyRose = 16770273, Moccasin = 16770229, NavajoWhite = 16768685, Navy = 128, OldLace = 16643558, Olive = 8421376, OliveDrab = 7048739, Orange = 16753920, OrangeRed = 16729344, Orchid = 14315734, PaleGoldenrod = 15657130, PaleGreen = 10025880, PaleTurquoise = 11529966, PaleVioletRed = 14381203, PapayaWhip = 16773077, PeachPuff = 16767673, Peru = 13468991, Pink = 16761035, Plum = 14524637, PowderBlue = 11591910, Purple = 8388736, Red = 16711680, RosyBrown = 12357519, RoyalBlue = 4286945, SaddleBrown = 9127187, Salmon = 16416882, SandyBrown = 16032864, SeaGreen = 3050327, SeaShell = 16774638, Sienna = 10506797, Silver = 12632256, SkyBlue = 8900331, SlateBlue = 6970061, SlateGray = 7372944, Snow = 16775930, SpringGreen = 65407, SteelBlue = 4620980, Tan = 13808780, Teal = 32896, Thistle = 14204888, Tomato = 16737095, Transparent = 16777215, Turquoise = 4251856, Violet = 15631086, Wheat = 16113331, White = 16777215, WhiteSmoke = 16119285, Yellow = 16776960, YellowGreen = 10145074, } }
27.883871
40
0.561083
[ "MPL-2.0", "MPL-2.0-no-copyleft-exception" ]
SoftFx/TTAlgo
src/csharp/api/TickTrader.Algo.Api/Colors.cs
4,324
C#
/* Copyright (c) Citrix Systems, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, * with or without modification, are permitted provided * that the following conditions are met: * * * Redistributions of source code must retain the above * copyright notice, this list of conditions and the * following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the * following disclaimer in the documentation and/or other * materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ using System.Collections.Generic; using System.Drawing; using System.Linq; using XenAdmin.Actions; using XenAdmin.Properties; using XenAPI; namespace XenAdmin.Commands { class VappStartCommand : Command { public VappStartCommand() { } public VappStartCommand(IMainWindow mainWindow, IEnumerable<SelectedItem> selection) : base(mainWindow, selection) { } public override string MenuText { get { return Messages.VAPP_START_MENU; } } public override string ContextMenuText { get { return Messages.VAPP_START_CONTEXT_MENU; } } public override Image MenuImage { get { return Images.StaticImages._001_PowerOn_h32bit_16; } } protected override bool CanExecuteCore(SelectedItemCollection selection) { if (selection.AllItemsAre<VM_appliance>()) return selection.AtLeastOneXenObjectCan<VM_appliance>(CanStartAppliance); if (selection.AllItemsAre<VM>()) { var firstVm = (VM)selection.First; if (firstVm.IsAssignedToVapp) { var firstVapp = firstVm.appliance; if (selection.AsXenObjects<VM>().All(vm => vm.appliance != null && vm.appliance.opaque_ref == firstVapp.opaque_ref)) return CanStartAppliance(firstVm.Connection.Resolve(firstVapp)); } } return false; } protected override void ExecuteCore(SelectedItemCollection selection) { var appsToStart = new List<VM_appliance>(); if (selection.AllItemsAre<VM_appliance>()) { appsToStart = (from IXenObject obj in selection.AsXenObjects() let app = (VM_appliance)obj where CanStartAppliance(app) select app).ToList(); } else if (selection.AllItemsAre<VM>()) { var firstVm = (VM)selection.First; appsToStart.Add(firstVm.Connection.Resolve(firstVm.appliance)); } foreach (var app in appsToStart) (new StartApplianceAction(app, false)).RunAsync(); } private bool CanStartAppliance(VM_appliance app) { return app != null && app.allowed_operations.Contains(vm_appliance_operation.start); } } }
39.107843
137
0.627225
[ "BSD-2-Clause" ]
GaborApatiNagy/xenadmin
XenAdmin/Commands/VappStartCommand.cs
3,991
C#
using System; namespace MSBuildExpressionParser { /// <summary> /// Demo of using Sprache to parse MSBuild expression. /// </summary> /// <remarks> /// TODO: Item group and item metadata syntax. /// </remarks> static class Program { /// <summary> /// The main program entry-point. /// </summary> static void Main() { try { const string testData = " 'Foo == Bar' 'a' 'Diddly O\\'Dee' $(Foo) $([MSBuild]::Hello) 'This is $(Me) talking $(BarBaz)' '$([Foo]::Diddly)' ' a ' "; Node node = MSBuildSyntax.ParseExpression(testData); DumpNode(node, depth: 0); } catch (Exception unexpectedError) { Console.WriteLine(unexpectedError); } } /// <summary> /// Dump a <see cref="Node"/>'s details to the console. /// </summary> /// <param name="node"> /// The <see cref="Node"/>. /// </param> /// <param name="depth"> /// The node's depth in the tree. /// </param> static void DumpNode(Node node, int depth) { if (node.Children != null) { Console.WriteLine("{0}{1}:", new String(' ', depth * 2), node.NodeType ); foreach (Node childNode in node.Children) DumpNode(childNode, depth + 1); } else { Console.WriteLine("{0}{1} '{2}' ({3}..{4})", new String(' ', depth * 2), node.NodeType, node.Value, node.Start, node.End ); } } } }
28.892308
171
0.414271
[ "MIT" ]
tintoy/MSBuildExpressionParser
MSBuildExpressionParser/Program.cs
1,880
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.Acs.Model.V20150101 { public class ModifyApiNameInDailyResponse : AcsResponse { private string requestId; public string RequestId { get { return requestId; } set { requestId = value; } } } }
26.44186
63
0.718558
[ "Apache-2.0" ]
sdk-team/aliyun-openapi-net-sdk
aliyun-net-sdk-acs/Acs/Model/V20150101/ModifyApiNameInDailyResponse.cs
1,137
C#
// Copyright (c) 2014-2020 DataStax Inc. // Copyright (c) 2020, Rafael Almeida (ralmsdevelper) // Licensed under the Apache License, Version 2.0. See LICENCE in the project root for license information. using System.Collections.Generic; using System.Linq.Expressions; using System.Text; using Scylla.Net.Mapping; namespace Scylla.Net.Data.Linq.ExpressionParsing { /// <summary> /// Represents an individual condition part of the WHERE or IF clause. /// See CQL relation: http://cassandra.apache.org/doc/latest/cql/dml.html#grammar-token-relation /// </summary> internal interface IConditionItem { PocoColumn Column { get; } /// <summary> /// Sets the operator of the binary condition /// </summary> IConditionItem SetOperator(ExpressionType expressionType); /// <summary> /// Sets the parameter or parameters of the condition /// </summary> IConditionItem SetParameter(object value); /// <summary> /// Sets the column or columns included in this condition. /// </summary> IConditionItem SetColumn(PocoColumn column); /// <summary> /// Determines if its possible to include multiple columns in this condition. /// For example: tuple relations (col1, col2) = ?. /// </summary> IConditionItem AllowMultipleColumns(); /// <summary> /// Determines if its possible to include multiple parameters in this condition /// For example: token function calls token(col1, col2) >= token(?, ?). /// </summary> IConditionItem AllowMultipleParameters(); /// <summary> /// Sets the CQL funcition of the current side of the condition. /// </summary> IConditionItem SetFunctionName(string name); /// <summary> /// Marks this condition as a result of a IComparable.CompareTo() call. /// </summary> IConditionItem SetAsCompareTo(); /// <summary> /// Converts this instance into a query and parameters. /// </summary> void ToCql(PocoData pocoData, StringBuilder query, IList<object> parameters); } }
34.873016
107
0.636322
[ "Apache-2.0" ]
ScyllaNet/ScyllaNet
src/ScyllaNet/Data/Linq/ExpressionParsing/IConditionItem.cs
2,199
C#
using System; using System.Collections.Generic; using System.Linq; using UnityEngine; using Rnd = System.Random; namespace Variety { public class WireMeshGenerator { public const double _wireRadius = .0032; public const double _wireRadiusHighlight = .0064; const double _wireMaxSegmentDeviation = .005; const double _wireMinBézierDeviation = .002; const double _wireMaxBézierDeviation = .005; const double _bottom = -.02; const double _firstControlHeight = .01; const double _interpolateHeight = .005; const double _firstControlHeightHighlight = .005; const double _interpolateHeightHighlight = .003; sealed class CPC { public Pt ControlBefore, Point, ControlAfter; } public enum WirePiece { Uncut, Cut, Copper } public static Mesh GenerateWire(double length, int numSegments, WirePiece piece, bool highlight, int? seed = null) { var rnd = seed == null ? new Rnd() : new Rnd(seed.Value); var thickness = highlight ? _wireRadiusHighlight : _wireRadius; var firstControlHeight = highlight ? _firstControlHeightHighlight : _firstControlHeight; var interpolateHeight = highlight ? _interpolateHeightHighlight : _interpolateHeight; var start = pt(0, _bottom, 0); var startControl = pt(0, firstControlHeight, 0); // x was length / 10 var endControl = pt(length, firstControlHeight, 0); // x was length * 9 / 10 var end = pt(length, _bottom, 0); var bézierSteps = 16; var tubeRevSteps = 16; var interpolateStart = pt(0, interpolateHeight, 0); var interpolateEnd = pt(length, interpolateHeight, 0); var intermediatePoints = newArray(numSegments - 1, i => interpolateStart + (interpolateEnd - interpolateStart) * (i + 1) / numSegments + pt(rnd.NextDouble() - .5, rnd.NextDouble() - .5, rnd.NextDouble() - .5).Normalize() * _wireMaxSegmentDeviation); var deviations = newArray(numSegments - 1, _ => (interpolateEnd - interpolateStart) * (.5 / numSegments) + pt(rnd.NextDouble() - .5, rnd.NextDouble() - .5, rnd.NextDouble() - .5).Normalize() * (rnd.NextDouble() * (_wireMaxBézierDeviation - _wireMinBézierDeviation + _wireMinBézierDeviation))); if (piece == WirePiece.Uncut) { var points = new[] { new { ControlBefore = default(Pt), Point = start, ControlAfter = startControl } } .Concat(intermediatePoints.Select((p, i) => new { ControlBefore = p - deviations[i], Point = p, ControlAfter = p + deviations[i] })) .Concat(new[] { new { ControlBefore = endControl, Point = end, ControlAfter = default(Pt) } }) .SelectConsecutivePairs(false, (one, two) => bézier(one.Point, one.ControlAfter, two.ControlBefore, two.Point, bézierSteps)) .SelectMany((x, i) => i == 0 ? x : x.Skip(1)) .ToArray(); return toMesh(createFaces(false, true, tubeFromCurve(points, thickness, tubeRevSteps))); } var partialWire = new Func<IEnumerable<CPC>, IEnumerable<VertexInfo[]>>(pts => { var points = pts .SelectConsecutivePairs(false, (one, two) => bézier(one.Point, one.ControlAfter, two.ControlBefore, two.Point, bézierSteps)) .SelectMany((x, i) => i == 0 ? x : x.Skip(1)) .ToArray(); var reserveForCopper = 6; var discardCopper = 2; if (piece == WirePiece.Cut) { var tube = tubeFromCurve(points, thickness, tubeRevSteps).SkipLast(reserveForCopper).ToArray(); var capCenter = points[points.Length - 1 - reserveForCopper]; var normal = capCenter - points[points.Length - 2 - reserveForCopper]; var cap = tube[tube.Length - 1].SelectConsecutivePairs(true, (v1, v2) => new[] { capCenter, v2.Point, v1.Point }.Select(p => new VertexInfo { Point = p, Normal = normal }).ToArray()).ToArray(); return createFaces(false, true, tube).Concat(cap); } else { var copper = tubeFromCurve(points.TakeLast(reserveForCopper + 2).SkipLast(discardCopper).ToArray(), thickness / 2, tubeRevSteps).Skip(1).ToArray(); var copperCapCenter = points[points.Length - 1 - discardCopper]; var copperNormal = copperCapCenter - points[points.Length - 2]; var copperCap = copper[copper.Length - 1].SelectConsecutivePairs(true, (v1, v2) => new[] { copperCapCenter, v2.Point, v1.Point }.Select(p => new VertexInfo { Point = p, Normal = copperNormal }).ToArray()).ToArray(); return createFaces(false, true, copper).Concat(copperCap); } }); var cutOffEarly = rnd.Next(2) == 0; var angleForward = rnd.Next(2) == 0; var rotAngle = (rnd.NextDouble() * 5 + 2.5) * (angleForward ? -1 : 1); var rotAxisStart = new Pt(0, 0, 0); var rotAxisEnd = new Pt(rnd.NextDouble() * .01, 1, rnd.NextDouble() * .01); Func<Pt, Pt> rot = p => p.Rotate(rotAxisStart, rotAxisEnd, rotAngle); var beforeCut = new[] { new CPC { ControlBefore = default(Pt), Point = start, ControlAfter = startControl } } .Concat(intermediatePoints.Take((cutOffEarly ? numSegments : numSegments + 1) / 2).Select((p, i) => new CPC { ControlBefore = rot(p - deviations[i]), Point = rot(p), ControlAfter = rot(p + deviations[i]) })); var bcTube = partialWire(beforeCut); var cutOffPoint = (cutOffEarly ? numSegments - 2 : numSegments - 1) / 2; rotAngle = (rnd.NextDouble() * 5 + 2.5) * (angleForward ? -1 : 1); rotAxisStart = new Pt(length, 0, 0); rotAxisEnd = new Pt(length + rnd.NextDouble() * .01, 1, rnd.NextDouble() * .01); var afterCut = new[] { new CPC { ControlBefore = default(Pt), Point = end, ControlAfter = endControl } } .Concat(intermediatePoints.Skip(cutOffPoint).Select((p, i) => new CPC { ControlBefore = rot(p + deviations[i + cutOffPoint]), Point = rot(p), ControlAfter = rot(p - deviations[i + cutOffPoint]) }).Reverse()); var acTube = partialWire(afterCut); return toMesh(bcTube.Concat(acTube).ToArray()); } sealed class VertexInfo { public Pt Point; public Pt Normal; public Vector3 V { get { return new Vector3((float) Point.X, (float) Point.Y, (float) Point.Z); } } public Vector3 N { get { return new Vector3((float) Normal.X, (float) Normal.Y, (float) Normal.Z); } } } private static Mesh toMesh(VertexInfo[][] triangles) { return new Mesh { vertices = triangles.SelectMany(t => t).Select(v => v.V).ToArray(), normals = triangles.SelectMany(t => t).Select(v => v.N).ToArray(), triangles = triangles.SelectMany(t => t).Select((v, i) => i).ToArray() }; } // Converts a 2D array of vertices into triangles by joining each vertex with the next in each dimension private static VertexInfo[][] createFaces(bool closedX, bool closedY, VertexInfo[][] meshData) { var len = meshData[0].Length; return Enumerable.Range(0, meshData.Length).SelectManyConsecutivePairs(closedX, (i1, i2) => Enumerable.Range(0, len).SelectManyConsecutivePairs(closedY, (j1, j2) => new[] { // triangle 1 new[] { meshData[i1][j1], meshData[i2][j1], meshData[i2][j2] }, // triangle 2 new[] { meshData[i1][j1], meshData[i2][j2], meshData[i1][j2] } })) .ToArray(); } private static VertexInfo[][] tubeFromCurve(Pt[] pts, double radius, int revSteps) { var normals = new Pt[pts.Length]; normals[0] = ((pts[1] - pts[0]) * pt(0, 1, 0)).Normalize() * radius; for (int i = 1; i < pts.Length - 1; i++) normals[i] = normals[i - 1].ProjectOntoPlane((pts[i + 1] - pts[i]) + (pts[i] - pts[i - 1])).Normalize() * radius; normals[pts.Length - 1] = normals[pts.Length - 2].ProjectOntoPlane(pts[pts.Length - 1] - pts[pts.Length - 2]).Normalize() * radius; var axes = pts.Select((p, i) => i == 0 ? new { Start = pts[0], End = pts[1] } : i == pts.Length - 1 ? new { Start = pts[pts.Length - 2], End = pts[pts.Length - 1] } : new { Start = p, End = p + (pts[i + 1] - p) + (p - pts[i - 1]) }).ToArray(); return Enumerable.Range(0, pts.Length) .Select(ix => new { Axis = axes[ix], Perp = pts[ix] + normals[ix], Point = pts[ix] }) .Select(inf => Enumerable.Range(0, revSteps) .Select(i => 360 * i / revSteps) .Select(angle => inf.Perp.Rotate(inf.Axis.Start, inf.Axis.End, angle)) .Select(p => new VertexInfo { Point = p, Normal = p - inf.Point }).Reverse().ToArray()) .ToArray(); } private static IEnumerable<Pt> bézier(Pt start, Pt control1, Pt control2, Pt end, int steps) { return Enumerable.Range(0, steps) .Select(i => (double) i / (steps - 1)) .Select(t => pow(1 - t, 3) * start + 3 * pow(1 - t, 2) * t * control1 + 3 * (1 - t) * t * t * control2 + pow(t, 3) * end); } static double sin(double x) { return Math.Sin(x * Math.PI / 180); } static double cos(double x) { return Math.Cos(x * Math.PI / 180); } static double pow(double x, double y) { return Math.Pow(x, y); } static Pt pt(double x, double y, double z) { return new Pt(x, y, z); } static T[] newArray<T>(int size, Func<int, T> initialiser) { var result = new T[size]; for (int i = 0; i < size; i++) { result[i] = initialiser(i); } return result; } } }
50.732057
261
0.548901
[ "MIT" ]
Timwi/KtaneVariety
Assets/Items/Wire/WireMeshGenerator.cs
10,616
C#
// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information. // Ported from um/d3d12sdklayers.h in the Windows SDK for Windows 10.0.19041.0 // Original source is Copyright © Microsoft. All rights reserved. using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; namespace TerraFX.Interop { [Guid("93A665C4-A3B2-4E5D-B692-A26AE14E3374")] [NativeTypeName("struct ID3D12Debug2 : IUnknown")] public unsafe partial struct ID3D12Debug2 { public void** lpVtbl; [MethodImpl(MethodImplOptions.AggressiveInlining)] [return: NativeTypeName("HRESULT")] public int QueryInterface([NativeTypeName("const IID &")] Guid* riid, [NativeTypeName("void **")] void** ppvObject) { return ((delegate* unmanaged<ID3D12Debug2*, Guid*, void**, int>)(lpVtbl[0]))((ID3D12Debug2*)Unsafe.AsPointer(ref this), riid, ppvObject); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [return: NativeTypeName("ULONG")] public uint AddRef() { return ((delegate* unmanaged<ID3D12Debug2*, uint>)(lpVtbl[1]))((ID3D12Debug2*)Unsafe.AsPointer(ref this)); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [return: NativeTypeName("ULONG")] public uint Release() { return ((delegate* unmanaged<ID3D12Debug2*, uint>)(lpVtbl[2]))((ID3D12Debug2*)Unsafe.AsPointer(ref this)); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void SetGPUBasedValidationFlags(D3D12_GPU_BASED_VALIDATION_FLAGS Flags) { ((delegate* unmanaged<ID3D12Debug2*, D3D12_GPU_BASED_VALIDATION_FLAGS, void>)(lpVtbl[3]))((ID3D12Debug2*)Unsafe.AsPointer(ref this), Flags); } } }
40.608696
152
0.682548
[ "MIT" ]
Perksey/terrafx.interop.windows
sources/Interop/Windows/um/d3d12sdklayers/ID3D12Debug2.cs
1,870
C#
using System.Numerics; using Google.Protobuf.Collections; using SC2APIProtocol; // ReSharper disable MemberCanBePrivate.Global namespace Bot { public class Unit { private SC2APIProtocol.Unit original; private UnitTypeData unitTypeData; public string name; public uint unitType; public float integrity; public Vector3 position; public ulong tag; public float buildProgress; public UnitOrder order; public RepeatedField<UnitOrder> orders; public int supply; public bool isVisible; public int idealWorkers; public int assignedWorkers; public Unit(SC2APIProtocol.Unit unit) { this.original = unit; this.unitTypeData = Controller.gameData.Units[(int)unit.UnitType]; this.name = unitTypeData.Name; this.tag = unit.Tag; this.unitType = unit.UnitType; this.position = new Vector3(unit.Pos.X, unit.Pos.Y, unit.Pos.Z); this.integrity = (unit.Health + unit.Shield) / (unit.HealthMax + unit.ShieldMax); this.buildProgress = unit.BuildProgress; this.idealWorkers = unit.IdealHarvesters; this.assignedWorkers = unit.AssignedHarvesters; this.order = unit.Orders.Count > 0 ? unit.Orders[0] : new UnitOrder(); this.orders = unit.Orders; this.isVisible = (unit.DisplayType == DisplayType.Visible); this.supply = (int)unitTypeData.FoodRequired; } public double GetDistance(Unit otherUnit) { return Vector3.Distance(position, otherUnit.position); } public double GetDistance(Vector3 location) { return Vector3.Distance(position, location); } public void Train(uint unitType, bool queue = false) { if (!queue && orders.Count > 0) return; var abilityID = Abilities.GetID(unitType); var action = Controller.CreateRawUnitCommand(abilityID); action.ActionRaw.UnitCommand.UnitTags.Add(tag); Controller.AddAction(action); var targetName = Controller.GetUnitName(unitType); Logger.Info("Started training: {0}", targetName); } private void FocusCamera() { var action = new Action(); action.ActionRaw = new ActionRaw(); action.ActionRaw.CameraMove = new ActionRawCameraMove(); action.ActionRaw.CameraMove.CenterWorldSpace = new Point(); action.ActionRaw.CameraMove.CenterWorldSpace.X = position.X; action.ActionRaw.CameraMove.CenterWorldSpace.Y = position.Y; action.ActionRaw.CameraMove.CenterWorldSpace.Z = position.Z; Controller.AddAction(action); } public void Move(Vector3 target) { var action = Controller.CreateRawUnitCommand(Abilities.MOVE); action.ActionRaw.UnitCommand.TargetWorldSpacePos = new Point2D(); action.ActionRaw.UnitCommand.TargetWorldSpacePos.X = target.X; action.ActionRaw.UnitCommand.TargetWorldSpacePos.Y = target.Y; action.ActionRaw.UnitCommand.UnitTags.Add(tag); Controller.AddAction(action); } public void Smart(Unit unit) { var action = Controller.CreateRawUnitCommand(Abilities.SMART); action.ActionRaw.UnitCommand.TargetUnitTag = unit.tag; action.ActionRaw.UnitCommand.UnitTags.Add(tag); Controller.AddAction(action); } } }
35.278846
93
0.614881
[ "MIT" ]
tonn/SC2-Bot
Bot/Unit.cs
3,669
C#
using EducationProcess.Domain.Validators; using EducationProcess.Domain.Models; using System.Threading.Tasks; using Xunit; namespace EducationProcess.Tests.Domain.Validators { public class IntermediateCertificationFormValidatorTests { [Theory] [InlineData("")] [InlineData(" ")] [InlineData("Dfjgkdhbbhwhslsfoeirutyrpovnvcmqkdfrpqmcvbfuiquuuuhuumcnbqiswefoojfhaepqxmcnskdfjesdjfnoirernbieowvnsjkalqqfqbbbdfjgkervnsmsdhfw")] public void Validate_IntermediateCertificationFormIsNotValid_ShouldHaveErrors(string name) { // arrange IntermediateCertificationForm IntermediateCertificationForm = new IntermediateCertificationForm() { CertificationFormId = 0, Name = name, }; IntermediateCertificationFormValidator validator = new IntermediateCertificationFormValidator(); // act var result = validator.Validate(IntermediateCertificationForm); // assert Assert.False(result.Errors.Count == 0); } [Theory] [InlineData("rrikt")] public void Validate_IntermediateCertificationFormIsValid_ShouldHaveNoErrors(string name) { // arrange IntermediateCertificationForm IntermediateCertificationForm = new IntermediateCertificationForm() { CertificationFormId = 0, Name = name, }; IntermediateCertificationFormValidator validator = new IntermediateCertificationFormValidator(); // act var result = validator.Validate(IntermediateCertificationForm); // assert Assert.True(result.Errors.Count == 0); } } }
33.203704
152
0.652538
[ "MIT" ]
NotKohtpojiep/EducationProcess
src/Api/EducationProcess.Tests/Domain/Validators/IntermediateCertificationFormValidatorTests.cs
1,795
C#
/* * Copyright (c) 2018 THL A29 Limited, a Tencent company. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ namespace TencentCloud.Vod.V20180717.Models { using Newtonsoft.Json; using System.Collections.Generic; using TencentCloud.Common; public class PullUploadRequest : AbstractModel { /// <summary> /// 要拉取的媒体 URL,暂不支持拉取 HLS 和 Dash 格式。 /// 支持的扩展名详见[媒体类型](https://cloud.tencent.com/document/product/266/9760#.E5.AA.92.E4.BD.93.E7.B1.BB.E5.9E.8B)。 /// </summary> [JsonProperty("MediaUrl")] public string MediaUrl{ get; set; } /// <summary> /// 媒体名称。 /// </summary> [JsonProperty("MediaName")] public string MediaName{ get; set; } /// <summary> /// 要拉取的视频封面 URL。仅支持 gif、jpeg、png 三种图片格式。 /// </summary> [JsonProperty("CoverUrl")] public string CoverUrl{ get; set; } /// <summary> /// 媒体后续任务操作,详见[上传指定任务流](https://cloud.tencent.com/document/product/266/9759)。 /// </summary> [JsonProperty("Procedure")] public string Procedure{ get; set; } /// <summary> /// 媒体文件过期时间,格式按照 ISO 8601 标准表示,详见 [ISO 日期格式说明](https://cloud.tencent.com/document/product/266/11732#I)。 /// </summary> [JsonProperty("ExpireTime")] public string ExpireTime{ get; set; } /// <summary> /// 指定上传园区,仅适用于对上传地域有特殊需求的用户(目前仅支持北京、上海和重庆园区)。 /// </summary> [JsonProperty("StorageRegion")] public string StorageRegion{ get; set; } /// <summary> /// 分类ID,用于对媒体进行分类管理,可通过[创建分类](https://cloud.tencent.com/document/product/266/7812)接口,创建分类,获得分类 ID。 /// </summary> [JsonProperty("ClassId")] public long? ClassId{ get; set; } /// <summary> /// 来源上下文,用于透传用户请求信息,当指定 Procedure 任务后,任务流状态变更回调将返回该字段值,最长 1000 个字符。 /// </summary> [JsonProperty("SessionContext")] public string SessionContext{ get; set; } /// <summary> /// 用于去重的识别码,如果七天内曾有过相同的识别码的请求,则本次的请求会返回错误。最长 50 个字符,不带或者带空字符串表示不做去重。 /// </summary> [JsonProperty("SessionId")] public string SessionId{ get; set; } /// <summary> /// 保留字段,特殊用途时使用。 /// </summary> [JsonProperty("ExtInfo")] public string ExtInfo{ get; set; } /// <summary> /// 点播[子应用](/document/product/266/14574) ID。如果要访问子应用中的资源,则将该字段填写为子应用 ID;否则无需填写该字段。 /// </summary> [JsonProperty("SubAppId")] public ulong? SubAppId{ get; set; } /// <summary> /// For internal usage only. DO NOT USE IT. /// </summary> internal override void ToMap(Dictionary<string, string> map, string prefix) { this.SetParamSimple(map, prefix + "MediaUrl", this.MediaUrl); this.SetParamSimple(map, prefix + "MediaName", this.MediaName); this.SetParamSimple(map, prefix + "CoverUrl", this.CoverUrl); this.SetParamSimple(map, prefix + "Procedure", this.Procedure); this.SetParamSimple(map, prefix + "ExpireTime", this.ExpireTime); this.SetParamSimple(map, prefix + "StorageRegion", this.StorageRegion); this.SetParamSimple(map, prefix + "ClassId", this.ClassId); this.SetParamSimple(map, prefix + "SessionContext", this.SessionContext); this.SetParamSimple(map, prefix + "SessionId", this.SessionId); this.SetParamSimple(map, prefix + "ExtInfo", this.ExtInfo); this.SetParamSimple(map, prefix + "SubAppId", this.SubAppId); } } }
36.33913
117
0.607083
[ "Apache-2.0" ]
allenlooplee/tencentcloud-sdk-dotnet
TencentCloud/Vod/V20180717/Models/PullUploadRequest.cs
4,861
C#
using System; using System.Collections.Generic; using System.ComponentModel; using System.Text; namespace SwitchAppDesign.AniListAPI.v2.Types { public enum StaffSort { [Description("ID")] Id = 1, [Description("ID_DESC")] IdDesc = 2, [Description("ROLE")] Role = 3, [Description("ROLE_DESC")] RoleDesc = 4, [Description("LANGUAGE")] Language = 5, [Description("LANGUAGE_DESC")] LanguageDesc = 6 } }
17.689655
45
0.575049
[ "MIT" ]
SwitchAppDesign/AniListApi
PoisonIvy.AniListAPI/SwitchAppDesign.AniListAPI.v2/Types/StaffSort.cs
515
C#
using Drawmasters.LevelsRepository; using System; using TMPro; using UnityEngine; using UnityEngine.UI; namespace Drawmasters.LevelConstructor { public class LevelHeaderPanel : MonoBehaviour { [SerializeField] Image back = default; [SerializeField] Button button = default; [SerializeField] TextMeshProUGUI indexLabel = default; [SerializeField] TextMeshProUGUI titleLabel = default; [SerializeField] TextMeshProUGUI enemiesCountLabel = default; [SerializeField] TextMeshProUGUI weaponTypeLabel = default; public LevelHeader Header { get; private set; } public void Set(int index, LevelHeader value, Action<LevelHeaderPanel> onClick) { indexLabel.text = (index + 1).ToString(); Header = value; button.onClick.AddListener(() => onClick(this)); Refresh(); gameObject.SetActive(true); } public void Select(bool value) => back.color = value ? Color.gray : Color.white; public void Clear() { Header = null; gameObject.SetActive(false); button.onClick.RemoveAllListeners(); Select(false); } void Refresh() { if (Header == null) { return; } indexLabel.color = Header.isDisabled ? Color.gray : Color.black; titleLabel.color = Header.isDisabled ? Color.gray : Color.black; enemiesCountLabel.color = Header.isDisabled ? Color.gray : Color.black; titleLabel.text = Header.title; enemiesCountLabel.text = Header.projectilesCount.ToString(); weaponTypeLabel.text = Header.weaponType.ToString(); } } }
28.887097
88
0.604132
[ "Unlicense" ]
TheProxor/code-samples-from-pg
Assets/LevelConstructor/Scripts/Constructor/LevelsManagement/LevelHeaderPanel.cs
1,793
C#
using System; namespace Triangulation { public static class Program { [STAThread] static void Main() { using (var game = new Game1()) game.Run(); } } }
15.066667
42
0.473451
[ "MIT" ]
JPaja/ConvexTriangulation
Triangulation/Program.cs
228
C#
using System; using System.Collections.Generic; using System.Xml; using EzDbSchema.Core.Extentions; using EzDbSchema.Core.Extentions.Objects; using EzDbSchema.Core.Extentions.Xml; using EzDbSchema.Core.Interfaces; namespace EzDbSchema.Core.Objects { public class PropertyDictionary : Dictionary<string, IProperty>, IPropertyDictionary, IXmlRenderableInternal { internal static string ALIAS = "Properties"; public PropertyDictionary() { this._id = this.GetId(); this.IsEnabled = true; } public int _id { get; set; } public bool IsEnabled { get; set; } = true; public ICustomAttributes CustomAttributes { get; set; } public XmlNode AsXml(XmlDocument doc) { return this.DictionaryAsXmlNode(doc, ALIAS); } public string AsXml() { return AsXml(new XmlDocument()).OuterXml; } public void FromXml(string Xml) { var doc = (new XmlDocument()); doc.LoadXml(Xml); FromXml(doc.FirstChild); } public XmlNode FromXml(XmlNode node) { this.DictionaryFromXmlNodeList(node.ChildNodes, ALIAS); return node; } } public class PropertyList : List<IProperty>, IPropertyList, IXmlRenderableInternal { internal static string ALIAS = "Properties"; public PropertyList() { this._id = this.GetId(); this.IsEnabled = true; } public int _id { get; set; } public bool IsEnabled { get; set; } = true; public ICustomAttributes CustomAttributes { get; set; } public XmlNode AsXml(XmlDocument doc) { return this.ListAsXmlNode(doc, ALIAS); } public string AsXml() { return AsXml(new XmlDocument()).OuterXml; } public void FromXml(string Xml) { var doc = (new XmlDocument()); doc.LoadXml(Xml); FromXml(doc.FirstChild); } public XmlNode FromXml(XmlNode node) { this.ListFromXmlNodeList(node.ChildNodes, ALIAS); return node; } } public class PrimaryKeyProperties : List<IProperty>, IPrimaryKeyProperties, IXmlRenderableInternal { internal static string ALIAS = "PrimaryKeys"; public PrimaryKeyProperties() { this._id = this.GetId(); this.IsEnabled = true; } public int _id { get; set; } public bool IsEnabled { get; set; } = true; public ICustomAttributes CustomAttributes { get; set; } protected IEntity Entity; public PrimaryKeyProperties(IEntity Parent) { this.Entity = Parent; } public XmlNode AsXml(XmlDocument doc) { XmlNode nod = doc.CreateElement(XmlConvert.EncodeName(ALIAS)); foreach (var item in this) { XmlNode refnod = nod.OwnerDocument.CreateElement(Property.ALIAS); ((XmlElement)refnod).SetAttribute("ref", item._id.ToSafeString()); nod.AppendChild(refnod); } return nod; } public string AsXml() { return AsXml(new XmlDocument()).OuterXml; } public void FromXml(string Xml) { var doc = (new XmlDocument()); doc.LoadXml(Xml); FromXml(doc.FirstChild); } public XmlNode FromXml(XmlNode node) { this.ListFromXmlNodeList(node.ChildNodes, ALIAS); return node; } } }
27.279412
109
0.566038
[ "MIT" ]
rvegajr/ez-db-schema
Src/EzDbSchema.Core/Objects/Properties.cs
3,712
C#
using FastVehicles; using SlowVehicles; namespace RacingGame { public class RacecarFactory : IFactory { public IFastVehicle CreateFastRacingVehicle() { return new F1Car(); } public ISlowVehicle CreateSlowRacingVehicle() { return new OffroadCar(); } } }
18.833333
53
0.59292
[ "MIT" ]
dmarkov00/Design-Patterns
AbstractFactoryPattern/RacingGame/RacecarFactory.cs
341
C#
using Neptuo; using Neptuo.Observables.Commands; using System; using System.Collections.Generic; using System.Collections.Specialized; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; namespace PackageManager.ViewModels.Commands { public partial class UpdateAllCommand : AsyncCommand { private readonly IViewModel viewModel; public UpdateAllCommand(IViewModel viewModel) { Ensure.NotNull(viewModel, "viewModel"); this.viewModel = viewModel; viewModel.Packages.CollectionChanged += OnPackagesChanged; } private void OnPackagesChanged(object sender, NotifyCollectionChangedEventArgs e) => RaiseCanExecuteChanged(); protected override bool CanExecuteOverride() => viewModel.Packages.Count > 0; protected async override Task ExecuteAsync(CancellationToken cancellationToken) { PackageUpdateViewModel selfUpdate = null; foreach (PackageUpdateViewModel package in viewModel.Packages.ToList()) { if (package.IsSelf) selfUpdate = package; else await UpdateAsync(package); } if (selfUpdate != null) await UpdateAsync(selfUpdate); } private async Task UpdateAsync(PackageUpdateViewModel package) { if (viewModel.Update.CanExecute(package)) await viewModel.Update.ExecuteAsync(package); } } }
30.222222
90
0.619485
[ "MIT" ]
RussKie/gitextensions.pluginmanager
src/PackageManager/ViewModels/Commands/UpdateAllCommand.cs
1,634
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("Server")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Server")] [assembly: AssemblyCopyright("Copyright © 2014")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("a40ed70b-1a56-4e60-b3d7-71cd6e478f41")] // 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")]
35.435897
85
0.719971
[ "MIT" ]
rtfpessoa/padi-dstm
Server/Properties/AssemblyInfo.cs
1,385
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("4.BinarySearch")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("4.BinarySearch")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("1361d6dc-758f-4b25-91a3-f8b4470c1601")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
38.837838
85
0.725818
[ "MIT" ]
YavorIT/TelerikAcademyHomeworks
C#2/MultidimensionalArrays/4.BinarySearch/Properties/AssemblyInfo.cs
1,440
C#
// <auto-generated /> using System; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Migrations; using Microsoft.EntityFrameworkCore.Storage.ValueConversion; using P01_HospitalDatabase.Data; namespace P01_HospitalDatabase.Migrations { [DbContext(typeof(HospitalContext))] [Migration("20191106181111_VisitationAndDoctorForeignKey")] partial class VisitationAndDoctorForeignKey { protected override void BuildTargetModel(ModelBuilder modelBuilder) { #pragma warning disable 612, 618 modelBuilder .HasAnnotation("ProductVersion", "2.2.0-rtm-35687") .HasAnnotation("Relational:MaxIdentifierLength", 128) .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); modelBuilder.Entity("P01_HospitalDatabase.Data.Models.Diagnose", b => { b.Property<int>("DiagnoseId") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("Comments") .HasMaxLength(250); b.Property<string>("Name") .HasMaxLength(50); b.Property<int>("PatientId"); b.HasKey("DiagnoseId"); b.HasIndex("PatientId"); b.ToTable("Diagnoses"); }); modelBuilder.Entity("P01_HospitalDatabase.Data.Models.Doctor", b => { b.Property<int>("DoctorId") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("Name") .HasMaxLength(100); b.Property<string>("Specialty") .HasMaxLength(100); b.HasKey("DoctorId"); b.ToTable("Doctors"); }); modelBuilder.Entity("P01_HospitalDatabase.Data.Models.Medicament", b => { b.Property<int>("MedicamentId") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("Name") .HasMaxLength(50); b.HasKey("MedicamentId"); b.ToTable("Medicaments"); }); modelBuilder.Entity("P01_HospitalDatabase.Data.Models.Patient", b => { b.Property<int>("PatientId") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("Address") .IsRequired() .HasMaxLength(250); b.Property<string>("Email") .HasMaxLength(80); b.Property<string>("FirstName") .IsRequired() .HasMaxLength(50); b.Property<bool>("HasInsurance"); b.Property<string>("LastName") .IsRequired() .HasMaxLength(50); b.HasKey("PatientId"); b.ToTable("Patients"); }); modelBuilder.Entity("P01_HospitalDatabase.Data.Models.PatientMedicament", b => { b.Property<int>("PatientId"); b.Property<int>("MedicamentId"); b.HasKey("PatientId", "MedicamentId"); b.HasIndex("MedicamentId"); b.ToTable("PatientMedicaments"); }); modelBuilder.Entity("P01_HospitalDatabase.Data.Models.Visitation", b => { b.Property<int>("VisitationId") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("Comments") .HasMaxLength(250); b.Property<DateTime>("Date"); b.Property<int>("DoctorId"); b.Property<int>("PatientId"); b.HasKey("VisitationId"); b.HasIndex("DoctorId"); b.HasIndex("PatientId"); b.ToTable("Visitations"); }); modelBuilder.Entity("P01_HospitalDatabase.Data.Models.Diagnose", b => { b.HasOne("P01_HospitalDatabase.Data.Models.Patient", "Patient") .WithMany("Diagnoses") .HasForeignKey("PatientId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("P01_HospitalDatabase.Data.Models.PatientMedicament", b => { b.HasOne("P01_HospitalDatabase.Data.Models.Medicament", "Medicament") .WithMany("Prescriptions") .HasForeignKey("MedicamentId") .OnDelete(DeleteBehavior.Cascade); b.HasOne("P01_HospitalDatabase.Data.Models.Patient", "Patient") .WithMany("Prescriptions") .HasForeignKey("PatientId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("P01_HospitalDatabase.Data.Models.Visitation", b => { b.HasOne("P01_HospitalDatabase.Data.Models.Doctor", "Doctor") .WithMany("Visitations") .HasForeignKey("DoctorId") .OnDelete(DeleteBehavior.Cascade); b.HasOne("P01_HospitalDatabase.Data.Models.Patient", "Patient") .WithMany("Visitations") .HasForeignKey("PatientId") .OnDelete(DeleteBehavior.Cascade); }); #pragma warning restore 612, 618 } } }
37.044944
125
0.513497
[ "MIT" ]
stanislavstoyanov99/SoftUni-Software-Engineering
DB-with-C#/Labs-And-Homeworks/Entity Framework Core/05. Code-First - Exercise/01HospitalDatabase/Migrations/20191106181111_VisitationAndDoctorForeignKey.Designer.cs
6,596
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; using Aliyun.Acs.Core.Http; using Aliyun.Acs.Core.Transform; using Aliyun.Acs.Core.Utils; using Aliyun.Acs.Cassandra.Transform; using Aliyun.Acs.Cassandra.Transform.V20190101; namespace Aliyun.Acs.Cassandra.Model.V20190101 { public class UpgradeClusterVersionRequest : RpcAcsRequest<UpgradeClusterVersionResponse> { public UpgradeClusterVersionRequest() : base("Cassandra", "2019-01-01", "UpgradeClusterVersion", "Cassandra", "openAPI") { if (this.GetType().GetProperty("ProductEndpointMap") != null && this.GetType().GetProperty("ProductEndpointType") != null) { this.GetType().GetProperty("ProductEndpointMap").SetValue(this, Endpoint.endpointMap, null); this.GetType().GetProperty("ProductEndpointType").SetValue(this, Endpoint.endpointRegionalType, null); } Method = MethodType.POST; } private string clusterId; public string ClusterId { get { return clusterId; } set { clusterId = value; DictionaryUtil.Add(QueryParameters, "ClusterId", value); } } public override UpgradeClusterVersionResponse GetResponse(UnmarshallerContext unmarshallerContext) { return UpgradeClusterVersionResponseUnmarshaller.Unmarshall(unmarshallerContext); } } }
34.765625
134
0.708315
[ "Apache-2.0" ]
AxiosCros/aliyun-openapi-net-sdk
aliyun-net-sdk-cassandra/Cassandra/Model/V20190101/UpgradeClusterVersionRequest.cs
2,225
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using AllYourTextsLib; using AllYourTextsLib.Framework; namespace AllYourTextsTest { public class MockContact : Contact { public const int MockContactId = 42; public MockContact(string firstName, string lastName) : this(firstName, null, lastName, null) { ; } public MockContact(string firstName, string lastName, IPhoneNumber phoneNumber) :this(firstName, null, lastName, phoneNumber) { ; } public MockContact(string firstName, string middleName, string lastName) :this(firstName, middleName, lastName, null) { ; } public MockContact(string firstName, string middleName, string lastName, IPhoneNumber phoneNumber) : base(MockContactId, firstName, middleName, lastName, phoneNumber) { ; } } }
25.538462
106
0.621486
[ "Apache-2.0" ]
AllYourTexts/AllYourTexts
AllYourTextsTest/Mock Objects/MockContact.cs
998
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Simplic.Data { /// <summary> /// A decimal that is precise without rounding failure /// </summary> public struct PreciseDecimal : IComparable, IConvertible, IFormattable { const int N = 8; private readonly double _value; /// <summary> /// Initialize new <see cref="PreciseDecimal"/> /// </summary> /// <param name="value"></param> public PreciseDecimal(double value) { _value = Math.Round(value, N); } /// <summary> /// Initialize new <see cref="PreciseDecimal"/> /// </summary> /// <param name="value"></param> public PreciseDecimal(PreciseDecimal value) { _value = value._value; } // Example of one member of double: public static PreciseDecimal operator *(PreciseDecimal d1, PreciseDecimal d2) { return new PreciseDecimal(d1._value * d2._value); } public static PreciseDecimal operator +(PreciseDecimal d1, PreciseDecimal d2) { return new PreciseDecimal(d1._value + d2._value); } public static PreciseDecimal operator -(PreciseDecimal d1, PreciseDecimal d2) { return new PreciseDecimal(d1._value - d2._value); } public static PreciseDecimal operator /(PreciseDecimal d1, PreciseDecimal d2) { return new PreciseDecimal(d1._value / d2._value); } public override bool Equals(object obj) { if (obj is PreciseDecimal) return ((PreciseDecimal)obj)._value == _value; return _value.Equals(obj); } public override int GetHashCode() { return _value.GetHashCode(); } public int CompareTo(object obj) { if (obj is PreciseDecimal) return _value.CompareTo(((PreciseDecimal)obj)._value); return _value.CompareTo(obj); } public static bool operator ==(PreciseDecimal c1, PreciseDecimal c2) { return c1._value == c2._value; } public static bool operator >=(PreciseDecimal c1, PreciseDecimal c2) { return c1._value >= c2._value; } public static bool operator <=(PreciseDecimal c1, PreciseDecimal c2) { return c1._value <= c2._value; } public static bool operator !=(PreciseDecimal c1, PreciseDecimal c2) { return c1._value != c2._value; } public static bool operator >(PreciseDecimal c1, PreciseDecimal c2) { return c1._value > c2._value; } public static bool operator <(PreciseDecimal c1, PreciseDecimal c2) { return c1._value < c2._value; } /// <summary> /// Implicit conversion from double to PrecisedDecimal. /// Implicit: No cast operator is required. /// </summary> public static implicit operator PreciseDecimal(double value) { return new PreciseDecimal(value); } /// <summary> /// Explicit conversion from PrecisedDecimal to int. /// Explicit: A cast operator is required. /// </summary> public static explicit operator PreciseDecimal(int value) { return new PreciseDecimal(value); } /// <summary> /// Explicit conversion from PrecisedDecimal to decimal?. /// Explicit: A cast operator is required. /// </summary> public static explicit operator PreciseDecimal(decimal value) { return new PreciseDecimal((double)value); } /// <summary> /// Explicit conversion from PrecisedDecimal to int. /// Explicit: A cast operator is required. /// </summary> public static explicit operator int(PreciseDecimal value) { return (int)value._value; } /// <summary> /// Explicit conversion from PrecisedDecimal to float. /// Explicit: A cast operator is required. /// </summary> public static explicit operator float(PreciseDecimal value) { return (float)value._value; } /// <summary> /// Explicit conversion from PrecisedDecimal to double. /// Explicit: A cast operator is required. /// </summary> public static explicit operator double(PreciseDecimal value) { return value._value; } /// <summary> /// Explicit conversion from PrecisedDecimal to long. /// Explicit: A cast operator is required. /// </summary> public static explicit operator long(PreciseDecimal value) { return (long)value._value; } /// <summary> /// Explicit conversion from PrecisedDecimal to uint. /// Explicit: A cast operator is required. /// </summary> public static explicit operator uint(PreciseDecimal value) { return (uint)value._value; } /// <summary> /// Explicit conversion from PrecisedDecimal to ulong. /// Explicit: A cast operator is required. /// </summary> public static explicit operator ulong(PreciseDecimal value) { return (ulong)value._value; } public string ToString(string format) { return _value.ToString(format); } public string ToString(IFormatProvider provider) { return _value.ToString(provider); } public string ToString(string format, IFormatProvider provider) { return _value.ToString(format, provider); } public override string ToString() { return _value.ToString(); } #region [IConvertible Implementation] public TypeCode GetTypeCode() { return TypeCode.Double; } public bool ToBoolean(IFormatProvider provider) { return _value == 1.0; } public char ToChar(IFormatProvider provider) { return Convert.ToChar(_value); } public sbyte ToSByte(IFormatProvider provider) { return Convert.ToSByte(_value); } public byte ToByte(IFormatProvider provider) { return Convert.ToByte(_value); } public short ToInt16(IFormatProvider provider) { return Convert.ToInt16(_value); } public ushort ToUInt16(IFormatProvider provider) { return Convert.ToUInt16(_value); } public int ToInt32(IFormatProvider provider) { return Convert.ToInt32(_value); } public uint ToUInt32(IFormatProvider provider) { return Convert.ToUInt32(_value); } public long ToInt64(IFormatProvider provider) { return Convert.ToInt64(_value); } public ulong ToUInt64(IFormatProvider provider) { return Convert.ToUInt64(_value); } public float ToSingle(IFormatProvider provider) { return Convert.ToSingle(_value); } public double ToDouble(IFormatProvider provider) { return Convert.ToDouble(_value); } public decimal ToDecimal(IFormatProvider provider) { return Convert.ToDecimal(_value); } public DateTime ToDateTime(IFormatProvider provider) { return Convert.ToDateTime(_value); } public object ToType(Type conversionType, IFormatProvider provider) { return Convert.ChangeType(_value, conversionType); } #endregion } /// <summary> /// <see cref="PreciseDecimal"/> extensin methods /// </summary> public static class PreciseDecimalExtension { /// <summary> /// Sum <see cref=PreciseDecimal""/> /// </summary> /// <param name="source"></param> /// <returns></returns> public static PreciseDecimal Sum(this IEnumerable<PreciseDecimal> source) { if (!source.Any()) return source.FirstOrDefault(); return source.Aggregate((x, y) => x + y); } /// <summary> /// Sum <see cref=PreciseDecimal""/> /// </summary> /// <param name="source"></param> /// <returns></returns> public static PreciseDecimal Sum<T>(this IEnumerable<T> source, Func<T, PreciseDecimal> selector) { if (!source.Select(selector).Any()) return source.Select(selector).FirstOrDefault(); return source.Select(selector).Aggregate((x, y) => x + y); } } }
28.145062
105
0.561794
[ "MIT" ]
simplic/simplic-service
simplic-corelib/Simplic.CoreLib/Data/PreciseDecimal.cs
9,121
C#
using MediatR; using VendorCollection.Data; using VendorCollection.Features.Core; using System.Collections.Generic; using System.Threading.Tasks; using System.Linq; using System.Data.Entity; namespace VendorCollection.Features.Documents { public class GetDocumentByIdQuery { public class GetDocumentByIdRequest : IRequest<GetDocumentByIdResponse> { public int Id { get; set; } public int? TenantId { get; set; } } public class GetDocumentByIdResponse { public DocumentApiModel Document { get; set; } } public class GetDocumentByIdHandler : IAsyncRequestHandler<GetDocumentByIdRequest, GetDocumentByIdResponse> { public GetDocumentByIdHandler(VendorCollectionContext context, ICache cache) { _context = context; _cache = cache; } public async Task<GetDocumentByIdResponse> Handle(GetDocumentByIdRequest request) { return new GetDocumentByIdResponse() { Document = DocumentApiModel.FromDocument(await _context.Documents.SingleAsync(x=>x.Id == request.Id && x.TenantId == request.TenantId)) }; } private readonly VendorCollectionContext _context; private readonly ICache _cache; } } }
30.565217
155
0.628734
[ "MIT" ]
QuinntyneBrown/vendor-collection
src/VendorCollection/Features/Documents/GetDocumentByIdQuery.cs
1,406
C#
using System; class BitwiseOperators { static void Main() { int countOfNumbers = int.Parse(Console.ReadLine()); int[] array = new int[countOfNumbers]; for (int i = 0; i < countOfNumbers; i++) { array[i] = int.Parse(Console.ReadLine()); } for (int i = 0; i < array.Length; i++) { string binary = Convert.ToString(array[i], 2); string reverse = string.Empty; for (int j = 0; j < binary.Length; j++) { reverse = binary[j].ToString() + reverse; } Console.WriteLine(Convert.ToUInt32(reverse,2)); } } }
28.083333
59
0.498516
[ "Apache-2.0" ]
genadi60/SoftUni
SoftUni_Exam/C# Basics Sample Exam May 2014/05.BitwiseOperators/BitwiseOperators.cs
676
C#
// This file is auto-generated, don't edit it. Thanks. using System; using System.Collections.Generic; using System.IO; using Tea; namespace AntChain.SDK.Deps.Models { public class CreateServicegroupRequest : TeaModel { [NameInMap("auth_token")] [Validation(Required=false)] public string AuthToken { get; set; } // append [NameInMap("append")] [Validation(Required=false)] public bool? Append { get; set; } // service_group_id [NameInMap("id")] [Validation(Required=false)] public string Id { get; set; } // workspace [NameInMap("workspace")] [Validation(Required=false)] public string Workspace { get; set; } } }
22.088235
55
0.60719
[ "MIT" ]
alipay/antchain-openapi-prod-sdk
deps/csharp/core/Models/CreateServicegroupRequest.cs
751
C#
using System.Linq; using Microsoft.EntityFrameworkCore; using Abp.Authorization; using Abp.Authorization.Roles; using Abp.Authorization.Users; using Abp.MultiTenancy; using GRINTSYS.SAPMiddleware.Authorization; using GRINTSYS.SAPMiddleware.Authorization.Roles; using GRINTSYS.SAPMiddleware.Authorization.Users; using Microsoft.AspNetCore.Identity; using Microsoft.Extensions.Options; namespace GRINTSYS.SAPMiddleware.EntityFrameworkCore.Seed.Host { public class HostRoleAndUserCreator { private readonly SAPMiddlewareDbContext _context; public HostRoleAndUserCreator(SAPMiddlewareDbContext context) { _context = context; } public void Create() { CreateHostRoleAndUsers(); } private void CreateHostRoleAndUsers() { // Admin role for host var adminRoleForHost = _context.Roles.IgnoreQueryFilters().FirstOrDefault(r => r.TenantId == null && r.Name == StaticRoleNames.Host.Admin); if (adminRoleForHost == null) { adminRoleForHost = _context.Roles.Add(new Role(null, StaticRoleNames.Host.Admin, StaticRoleNames.Host.Admin) { IsStatic = true, IsDefault = true }).Entity; _context.SaveChanges(); } // Grant all permissions to admin role for host var grantedPermissions = _context.Permissions.IgnoreQueryFilters() .OfType<RolePermissionSetting>() .Where(p => p.TenantId == null && p.RoleId == adminRoleForHost.Id) .Select(p => p.Name) .ToList(); var permissions = PermissionFinder .GetAllPermissions(new SAPMiddlewareAuthorizationProvider()) .Where(p => p.MultiTenancySides.HasFlag(MultiTenancySides.Host) && !grantedPermissions.Contains(p.Name)) .ToList(); if (permissions.Any()) { _context.Permissions.AddRange( permissions.Select(permission => new RolePermissionSetting { TenantId = null, Name = permission.Name, IsGranted = true, RoleId = adminRoleForHost.Id }) ); _context.SaveChanges(); } // Admin user for host var adminUserForHost = _context.Users.IgnoreQueryFilters().FirstOrDefault(u => u.TenantId == null && u.UserName == AbpUserBase.AdminUserName); if (adminUserForHost == null) { var user = new User { TenantId = null, UserName = AbpUserBase.AdminUserName, Name = "admin", Surname = "admin", EmailAddress = "admin@aspnetboilerplate.com", IsEmailConfirmed = true, IsActive = true }; user.Password = new PasswordHasher<User>(new OptionsWrapper<PasswordHasherOptions>(new PasswordHasherOptions())).HashPassword(user, "123qwe"); user.SetNormalizedNames(); adminUserForHost = _context.Users.Add(user).Entity; _context.SaveChanges(); // Assign Admin role to admin user _context.UserRoles.Add(new UserRole(null, adminUserForHost.Id, adminRoleForHost.Id)); _context.SaveChanges(); _context.SaveChanges(); } } } }
36.616162
171
0.569379
[ "MIT" ]
Grintsys/GRINTSYS.SAPMiddleware
src/GRINTSYS.SAPMiddleware.EntityFrameworkCore/EntityFrameworkCore/Seed/Host/HostRoleAndUserCreator.cs
3,625
C#
using Foodly_new.Data; using Foodly_new.Models.DomainModels; using Foodly_new.Models.EfModels; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Rendering; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Foodly_new.Controllers { public class RestaurantController : Controller { private readonly UserManager<UserIdentity> _userManager; EFContext c = new EFContext(); public RestaurantController(UserManager<UserIdentity> userManager) { _userManager = userManager; } [HttpGet] [Authorize] public IActionResult Create() { return View(); } [HttpPost] [Authorize] public IActionResult Create(string Name, string Type, string Tel, string Web, string Adress,string District, string City) { if (Name != null && Type != null && Tel != null && Adress != null) { try { c.Restaurants.Add( new Restaurant { Name = Name, Type = Type, Web = Web, Tel = Tel, District = District, City = City, Adress = Adress, RestaurantID = Guid.NewGuid().ToString(), StarCount = 0, CreatedByID = _userManager.GetUserId(User), PublishDate = DateTime.Now, IsAccepted = false, Deleted=false }) ; c.SaveChanges(); return View(); } catch { ViewData["Error"] = "Bir şeyler ters gitti!. #30001"; return View(); } } else { ViewData["Error"] = "Boş gönderemezsin #NULLERROR"; return View(); } } [HttpPost] public JsonResult IlIlce(int? ilID, string tip) { //geriye döndüreceğim sonucListim List<SelectListItem> sonuc = new List<SelectListItem>(); //bu işlem başarılı bir şekilde gerçekleşti mi onun kontrolunnü yapıyorum bool basariliMi = true; try { switch (tip) { case "ilGetir": //veritabanımızdaki iller tablomuzdan illerimizi sonuc değişkenimze atıyoruz foreach (var il in c.Iller.ToList()) { sonuc.Add(new SelectListItem { Text = il.Il, Value = il.IlID.ToString() }); } break; case "ilceGetir": //ilcelerimizi getireceğiz ilimizi selecten seçilen ilID sine göre foreach (var ilce in c.Ilceler.Where(il => il.IlID == ilID).ToList()) { sonuc.Add(new SelectListItem { Text = ilce.Ilce, Value = ilce.IlceID.ToString() }); } break; default: break; } } catch (Exception) { //hata ile karşılaşırsak buraya düşüyor basariliMi = false; sonuc = new List<SelectListItem>(); sonuc.Add(new SelectListItem { Text = "Bir hata oluştu :(", Value = "Default" }); } //Oluşturduğum sonucları json olarak geriye gönderiyorum return Json(new { ok = basariliMi, text = sonuc }); } [HttpGet] public IActionResult Profile(string id) { if (id == null) { return RedirectToAction(nameof(Index)); } else { try { var restaurantContext = c.Restaurants.Where(x=> x.RestaurantID==id && x.IsAccepted==true&& x.Deleted==false); return View(restaurantContext); } catch { return Redirect("/Home/Index"); } } } [HttpPost] public IActionResult Profile(string id, string Action) { if(id!=null && id!=""&& Action!=null && Action!="" ) { if (Action == "Delete") { var list = c.Restaurants.Where(x => x.RestaurantID == id).ToList(); foreach (var item in list) { item.IsAccepted = false; item.Deleted = true; c.Restaurants.Update(item); } c.SaveChanges(); } } return View(); } } }
33.879518
129
0.412873
[ "MIT" ]
Meeyzt/Foodly_New
Foodly_new/Controllers/RestaurantController.cs
5,661
C#
using System; using System.Collections.Generic; using System.Net; using System.Text; namespace DailyWallpainter.Helpers { public static class InternetConnection { //http://stackoverflow.com/questions/20309158/c-sharp-checking-internet-connection public static bool IsAvailable() { try { using (var client = new WebClient()) using (var stream = client.OpenRead("http://www.google.com")) { return true; } } catch { return false; } } } }
23.321429
90
0.506891
[ "BSD-3-Clause" ]
iamxail/DailyWallpainter
DailyWallpainter/Helpers/InternetConnection.cs
655
C#
// <auto-generated /> using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Storage.ValueConversion; using PASTRY.Data; namespace PASTRY.Migrations { [DbContext(typeof(MvcCakeContext))] partial class MvcCakeContextModelSnapshot : ModelSnapshot { protected override void BuildModel(ModelBuilder modelBuilder) { #pragma warning disable 612, 618 modelBuilder .HasAnnotation("ProductVersion", "3.1.15") .HasAnnotation("Relational:MaxIdentifierLength", 128) .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); modelBuilder.Entity("PASTRY.Models.Cake", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<int>("IdImage") .HasColumnType("int"); b.Property<string>("Name") .HasColumnType("nvarchar(max)"); b.Property<decimal>("Price") .HasColumnType("decimal(18,2)"); b.Property<int>("Weight") .HasColumnType("int"); b.HasKey("Id"); b.ToTable("Cake"); }); #pragma warning restore 612, 618 } } }
34.375
125
0.574545
[ "MIT" ]
Melaniaift/project_pastry
PASTRY/PASTRY/Migrations/MvcCakeContextModelSnapshot.cs
1,652
C#
//TRE008 using System; using System.Linq; using System.Collections.Generic; using SwissAcademic.Citavi; using SwissAcademic.Citavi.Metadata; using SwissAcademic.Collections; namespace SwissAcademic.Citavi.Citations { public class CustomTemplateCondition : ITemplateConditionMacro { //Consecutive citation (same series) //This applies to in-text and footnote citations only, not bibliography citations. //Contact Citavi support if you require a condition for bibliography citations. public bool IsTemplateForReference(ConditionalTemplate template, Citation citation) { if (citation == null) return false; //Make sure we are dealing with PlaceholderCitations (i.e. in-text and footnote citations, not bibliography entries) var currentPlaceholderCitation = citation as PlaceholderCitation; if (currentPlaceholderCitation == null) return false; var previousPlaceholderCitation = currentPlaceholderCitation.PreviousPlaceholderCitation; if (previousPlaceholderCitation == null) return false; //determine the series of the current reference, if necessary by looking at its parent reference var currentReference = citation.Reference; if (currentReference == null) return false; var currentSeries = currentReference.SeriesTitle; if (currentSeries == null && currentReference.ParentReference != null) currentSeries = currentReference.ParentReference.SeriesTitle; if (currentSeries == null) return false; //determine the series of the previous reference, if necessary by looking at its parent reference //stay within the same rule set, i.e. footnote or in-text Reference previousReference = null; if (currentPlaceholderCitation.CitationType == CitationType.Footnote) { var currentFootnoteCitation = currentPlaceholderCitation as FootnoteCitation; if (currentFootnoteCitation == null) return false; var previousFootnoteCitation = currentFootnoteCitation.PreviousFootnoteCitation; if (previousFootnoteCitation == null) return false; previousReference = previousFootnoteCitation.Reference; } else if (currentPlaceholderCitation.CitationType == CitationType.InText) { var currentInTextCitation = currentPlaceholderCitation as InTextCitation; if (currentInTextCitation == null) return false; var previousInTextCitation = currentInTextCitation.PreviousInTextCitation; if (previousInTextCitation == null) return false; previousReference = previousInTextCitation.Reference; } if (previousReference == null) return false; var previousSeries = previousReference.SeriesTitle; if (previousSeries == null && previousReference.ParentReference != null) previousSeries = previousReference.ParentReference.SeriesTitle; if (previousSeries == null) return false; bool conditionMet = false; conditionMet = currentSeries == previousSeries; if (!conditionMet) return false; //https://github.com/Citavi/Citavi/issues/744 bool noRuleSetOverride = currentPlaceholderCitation.RuleSetOverride == RuleSetOverride.None || (currentPlaceholderCitation.CitationType == CitationType.Footnote && currentPlaceholderCitation.RuleSetOverride == RuleSetOverride.Footcit) || (currentPlaceholderCitation.CitationType == CitationType.InText && currentPlaceholderCitation.RuleSetOverride == RuleSetOverride.Textcit); // currentPlaceholderCitation.PersonOnly: siehe Kommentar bei RepeatingInTextCitation conditionMet = noRuleSetOverride && currentPlaceholderCitation.YearOnly == false && currentPlaceholderCitation.Entry != null; if (!conditionMet) return false; return true; } } }
41.05618
146
0.77723
[ "MIT" ]
Citavi/C6-Citation-Style-Scripts
Templates/TRE008 Consecutive citation - same series/TRE008_Consecutive_citation_-_same_series.cs
3,654
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Realmius.SyncService; using Realms; namespace RealmiusAdvancedExample.RealmEntities { public class ChatMessageRealm : RealmObject, IRealmiusObjectClient { public string MobilePrimaryKey => Id; [PrimaryKey] public string Id { get; set; } public string Text { get; set; } public string AuthorName { get; set; } public DateTimeOffset CreatingDateTime { get; set; } public ChatMessageRealm(string text) { Id = Guid.NewGuid().ToString(); Text = text; AuthorName = App.CurrentUser.Name; CreatingDateTime = DateTimeOffset.Now; } public ChatMessageRealm() { } } }
22.783784
70
0.628707
[ "Apache-2.0" ]
F1nZeR/Realmius
Examples/RealmiusAdvancedExample/RealmiusAdvancedExample/RealmiusAdvancedExample/RealmEntities/ChatMessageRealm.cs
845
C#
#region copyright // Copyright 2015 Habart Thierry // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #endregion using System.Collections.Generic; namespace SimpleIdentityServer.UserManagement.ViewModels { public class ConsentViewModel { public string Id { get; set; } public string ClientDisplayName { get; set; } public ICollection<string> AllowedScopeDescriptions { get; set; } public ICollection<string> AllowedIndividualClaims { get; set; } public string LogoUri { get; set; } public string PolicyUri { get; set; } public string TosUri { get; set; } public string Code { get; set; } } }
36.875
75
0.705932
[ "Apache-2.0" ]
appkins/SimpleIdentityServer
SimpleIdentityServer/src/Apis/SimpleIdServer/SimpleIdentityServer.UserManagement/ViewModels/ConsentViewModel.cs
1,182
C#
#region using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using Spire.Core.Commands.Parsing.Abstractions; using Spire.Core.Commands.Parsing.Abstractions.Parameters; using Spire.Core.Commands.Parsing.Abstractions.Parameters.Options; using Spire.Core.Commands.Parsing.Parameters; #endregion namespace Spire.Core.Commands.Parsing { /// <summary> /// Default implementation of <see cref="ICommandParserBuilder"/>. /// </summary> public class CommandParserBuilder : ICommandParserBuilder { /// <summary> /// Creates new <see cref="ICommandParserBuilder"/>. /// </summary> public static ICommandParserBuilder New => new CommandParserBuilder(); private readonly ICollection<ICommandParameterType> _commandParameterTypes; private readonly ICollection<ICommandParameterOptionHandler> _commandParameterOptionHandlers; private ICommandParserConfiguration _commandParserConfiguration; private CommandParserBuilder() { _commandParameterTypes = new Collection<ICommandParameterType>(); _commandParameterOptionHandlers = new Collection<ICommandParameterOptionHandler>(); } /// <summary> /// Sets default command parser settings. /// </summary> /// <returns>Configured <see cref="ICommandParserBuilder"/> instance.</returns> public ICommandParserBuilder WithDefaults() { _commandParserConfiguration = CommandParserConfiguration.Default; _commandParameterTypes.Clear(); foreach (ICommandParameterType commandParameterType in CommandParameterTypes.All) { _commandParameterTypes.Add(commandParameterType); } return this; } /// <summary> /// Overrides default settings. /// </summary> /// <param name="defaultsOverriderConfigurator">Overrider configurator.</param> /// <returns>Configured <see cref="ICommandParserBuilder"/> instance.</returns> public ICommandParserBuilder WithOverridenDefaults( Action<ICommandParserConfiguration> defaultsOverriderConfigurator) { if (defaultsOverriderConfigurator == null) { throw new ArgumentNullException(nameof(defaultsOverriderConfigurator)); } _commandParserConfiguration ??= CommandParserConfiguration.Default; defaultsOverriderConfigurator(_commandParserConfiguration); return this; } /// <summary> /// Sets command parser configuration. /// </summary> /// <param name="commandParserConfiguration">Command parser configuration.</param> /// <returns>Configured <see cref="ICommandParserBuilder"/> instance.</returns> public ICommandParserBuilder WithConfiguration(ICommandParserConfiguration commandParserConfiguration) { _commandParserConfiguration = commandParserConfiguration ?? throw new ArgumentNullException(nameof(commandParserConfiguration)); return this; } /// <summary> /// Adds parameter type. /// </summary> /// <param name="commandParameterType">Parameter type.</param> /// <returns>Configured <see cref="ICommandParserBuilder"/> instance.</returns> public ICommandParserBuilder WithParameterType(ICommandParameterType commandParameterType) { if (commandParameterType == null) { throw new ArgumentNullException(nameof(commandParameterType)); } if (_commandParameterTypes.Any(existingCommandParameterType => string.Compare(existingCommandParameterType.Name, commandParameterType.Name, StringComparison.Ordinal) == 0)) { throw new ArgumentException( $"Specified command parameter type '{commandParameterType.Name}' already exists.", nameof(commandParameterType)); } _commandParameterTypes.Add(commandParameterType); return this; } /// <summary> /// Adds parameter type. /// </summary> /// <param name="commandParameterType">Parameter type instance.</param> /// <typeparam name="TCommandParameterType">Parameter type.</typeparam> /// <returns>Configured <see cref="ICommandParserBuilder"/> instance.</returns> public ICommandParserBuilder WithParameterType<TCommandParameterType>(TCommandParameterType commandParameterType) where TCommandParameterType : class, ICommandParameterType { return WithParameterType(commandParameterType as ICommandParameterType); } /// <summary> /// Adds parameter type. /// </summary> /// <typeparam name="TCommandParameterType">Parameter type.</typeparam> /// <returns>Configured <see cref="ICommandParserBuilder"/> instance.</returns> public ICommandParserBuilder WithParameterType<TCommandParameterType>() where TCommandParameterType : class, ICommandParameterType, new() { return WithParameterType(new TCommandParameterType()); } /// <summary> /// Adds parameter option handler. /// </summary> /// <param name="commandParameterOptionHandler">Command parameter option handler.</param> /// <returns>Configured <see cref="ICommandParserBuilder"/> instance.</returns> public ICommandParserBuilder WithParameterOptionHandler( ICommandParameterOptionHandler commandParameterOptionHandler) { if (commandParameterOptionHandler == null) { throw new ArgumentNullException(nameof(commandParameterOptionHandler)); } if (_commandParameterOptionHandlers.Any(existingCommandParameterHandler => string.Compare(existingCommandParameterHandler.Name, commandParameterOptionHandler.Name, StringComparison.Ordinal) == 0)) { throw new ArgumentException( $"Specified command parameter option handler '{commandParameterOptionHandler.Name}' already exists.", nameof(commandParameterOptionHandler)); } _commandParameterOptionHandlers.Add(commandParameterOptionHandler); return this; } /// <summary> /// Adds parameter option handler. /// </summary> /// <param name="commandParameterOptionHandler">Command parameter option handler.</param> /// <typeparam name="TCommandParameterOptionHandler">Command parameter option handler type.</typeparam> /// <returns>Configured <see cref="ICommandParserBuilder"/> instance.</returns> public ICommandParserBuilder WithParameterOptionHandler<TCommandParameterOptionHandler>( TCommandParameterOptionHandler commandParameterOptionHandler) where TCommandParameterOptionHandler : class, ICommandParameterOptionHandler { return WithParameterOptionHandler(commandParameterOptionHandler as ICommandParameterOptionHandler); } /// <summary> /// Adds parameter option handler. /// </summary> /// <typeparam name="TCommandParameterOptionHandler">Command parameter option handler type.</typeparam> /// <returns>Configured <see cref="ICommandParserBuilder"/> instance.</returns> public ICommandParserBuilder WithParameterOptionHandler<TCommandParameterOptionHandler>() where TCommandParameterOptionHandler : class, ICommandParameterOptionHandler, new() { return WithParameterOptionHandler(new TCommandParameterOptionHandler()); } /// <summary> /// Builds <see cref="ICommandParser"/> with specified settings. /// </summary> /// <returns>Built <see cref="ICommandParser"/> instance.</returns> public ICommandParser Build() { if (_commandParserConfiguration == null && !_commandParameterTypes.Any()) { WithDefaults(); } return new CommandParser(_commandParserConfiguration, _commandParameterTypes, _commandParameterOptionHandlers); } } }
42.004926
121
0.655213
[ "MIT" ]
avalanche759/Spire
src/core/commands/parsing/Spire.Core.Commands.Parsing/CommandParserBuilder.cs
8,529
C#
// The code is edited from https://github.com/CommunityToolkit/WindowsCommunityToolkit/tree/rel/7.1.2/Microsoft.Toolkit.Mvvm/Input // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.ComponentModel; using System.Runtime.CompilerServices; using System.Threading; using System.Threading.Tasks; using System.Windows.Input; using CommunityToolkit.Mvvm.ComponentModel; using CommunityToolkit.Mvvm.Input; namespace HappyStudio.Mvvm.Input.Wpf { /// <summary> /// A command that mirrors the functionality of <see cref="RelayCommand"/>, with the addition of /// accepting a <see cref="Func{TResult}"/> returning a <see cref="Task"/> as the execute /// action, and providing an <see cref="ExecutionTask"/> property that notifies changes when /// <see cref="ExecuteAsync"/> is invoked and when the returned <see cref="Task"/> completes. /// </summary> public sealed class AsyncRelayCommand : ObservableObject, IAsyncRelayCommand { /// <summary> /// The cached <see cref="PropertyChangedEventArgs"/> for <see cref="CanBeCanceled"/>. /// </summary> internal static readonly PropertyChangedEventArgs CanBeCanceledChangedEventArgs = new(nameof(CanBeCanceled)); /// <summary> /// The cached <see cref="PropertyChangedEventArgs"/> for <see cref="IsCancellationRequested"/>. /// </summary> internal static readonly PropertyChangedEventArgs IsCancellationRequestedChangedEventArgs = new(nameof(IsCancellationRequested)); /// <summary> /// The cached <see cref="PropertyChangedEventArgs"/> for <see cref="IsRunning"/>. /// </summary> internal static readonly PropertyChangedEventArgs IsRunningChangedEventArgs = new(nameof(IsRunning)); /// <summary> /// The <see cref="Func{TResult}"/> to invoke when <see cref="Execute"/> is used. /// </summary> private readonly Func<Task>? execute; /// <summary> /// The cancelable <see cref="Func{T,TResult}"/> to invoke when <see cref="Execute"/> is used. /// </summary> /// <remarks>Only one between this and <see cref="execute"/> is not <see langword="null"/>.</remarks> private readonly Func<CancellationToken, Task>? cancelableExecute; /// <summary> /// The optional action to invoke when <see cref="CanExecute"/> is used. /// </summary> private readonly Func<bool>? canExecute; /// <summary> /// The <see cref="CancellationTokenSource"/> instance to use to cancel <see cref="cancelableExecute"/>. /// </summary> /// <remarks>This is only used when <see cref="cancelableExecute"/> is not <see langword="null"/>.</remarks> private CancellationTokenSource? cancellationTokenSource; /// <inheritdoc/> public event EventHandler? CanExecuteChanged { add => CommandManager.RequerySuggested += value; remove => CommandManager.RequerySuggested -= value; } /// <summary> /// Initializes a new instance of the <see cref="AsyncRelayCommand"/> class that can always execute. /// </summary> /// <param name="execute">The execution logic.</param> public AsyncRelayCommand(Func<Task> execute) { this.execute = execute; } /// <summary> /// Initializes a new instance of the <see cref="AsyncRelayCommand"/> class that can always execute. /// </summary> /// <param name="cancelableExecute">The cancelable execution logic.</param> public AsyncRelayCommand(Func<CancellationToken, Task> cancelableExecute) { this.cancelableExecute = cancelableExecute; } /// <summary> /// Initializes a new instance of the <see cref="AsyncRelayCommand"/> class. /// </summary> /// <param name="execute">The execution logic.</param> /// <param name="canExecute">The execution status logic.</param> public AsyncRelayCommand(Func<Task> execute, Func<bool> canExecute) { this.execute = execute; this.canExecute = canExecute; } /// <summary> /// Initializes a new instance of the <see cref="AsyncRelayCommand"/> class. /// </summary> /// <param name="cancelableExecute">The cancelable execution logic.</param> /// <param name="canExecute">The execution status logic.</param> public AsyncRelayCommand(Func<CancellationToken, Task> cancelableExecute, Func<bool> canExecute) { this.cancelableExecute = cancelableExecute; this.canExecute = canExecute; } private TaskNotifier? executionTask; /// <inheritdoc/> public Task? ExecutionTask { get => this.executionTask; private set { if (SetPropertyAndNotifyOnCompletion(ref this.executionTask, value, _ => { // When the task completes OnPropertyChanged(IsRunningChangedEventArgs); OnPropertyChanged(CanBeCanceledChangedEventArgs); })) { // When setting the task OnPropertyChanged(IsRunningChangedEventArgs); OnPropertyChanged(CanBeCanceledChangedEventArgs); } } } /// <inheritdoc/> public bool CanBeCanceled => this.cancelableExecute is not null && IsRunning; /// <inheritdoc/> public bool IsCancellationRequested => this.cancellationTokenSource?.IsCancellationRequested == true; /// <inheritdoc/> public bool IsRunning => ExecutionTask?.IsCompleted == false; /// <inheritdoc/> public void NotifyCanExecuteChanged() { CommandManager.InvalidateRequerySuggested(); } /// <inheritdoc/> [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool CanExecute(object? parameter) { return this.canExecute?.Invoke() != false; } /// <inheritdoc/> public void Execute(object? parameter) { _ = ExecuteAsync(parameter); } /// <inheritdoc/> public Task ExecuteAsync(object? parameter) { if (CanExecute(parameter)) { // Non cancelable command delegate if (this.execute is not null) { return ExecutionTask = this.execute(); } // Cancel the previous operation, if one is pending this.cancellationTokenSource?.Cancel(); CancellationTokenSource cancellationTokenSource = this.cancellationTokenSource = new(); OnPropertyChanged(IsCancellationRequestedChangedEventArgs); // Invoke the cancelable command delegate with a new linked token return ExecutionTask = this.cancelableExecute!(cancellationTokenSource.Token); } return Task.CompletedTask; } /// <inheritdoc/> public void Cancel() { this.cancellationTokenSource?.Cancel(); OnPropertyChanged(IsCancellationRequestedChangedEventArgs); OnPropertyChanged(CanBeCanceledChangedEventArgs); } } }
39.195876
137
0.615334
[ "MIT" ]
kljzndx/ms-mvvm-wpf
HappyStudio.Mvvm.Input.Wpf/AsyncRelayCommand.cs
7,604
C#
namespace android.net { [global::MonoJavaBridge.JavaClass()] public partial class Credentials : java.lang.Object { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; protected Credentials(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } public new int Uid { get { return getUid(); } } private static global::MonoJavaBridge.MethodId _m0; public virtual int getUid() { return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.net.Credentials.staticClass, "getUid", "()I", ref global::android.net.Credentials._m0); } public new int Pid { get { return getPid(); } } private static global::MonoJavaBridge.MethodId _m1; public virtual int getPid() { return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.net.Credentials.staticClass, "getPid", "()I", ref global::android.net.Credentials._m1); } public new int Gid { get { return getGid(); } } private static global::MonoJavaBridge.MethodId _m2; public virtual int getGid() { return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.net.Credentials.staticClass, "getGid", "()I", ref global::android.net.Credentials._m2); } private static global::MonoJavaBridge.MethodId _m3; public Credentials(int arg0, int arg1, int arg2) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::android.net.Credentials._m3.native == global::System.IntPtr.Zero) global::android.net.Credentials._m3 = @__env.GetMethodIDNoThrow(global::android.net.Credentials.staticClass, "<init>", "(III)V"); global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.net.Credentials.staticClass, global::android.net.Credentials._m3, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); Init(@__env, handle); } static Credentials() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::android.net.Credentials.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/net/Credentials")); } } }
36.870968
309
0.738845
[ "MIT" ]
JeroMiya/androidmono
MonoJavaBridge/android/generated/android/net/Credentials.cs
2,286
C#
using System; using ClearHl7.Extensions; using ClearHl7.Helpers; namespace ClearHl7.V260.Types { /// <summary> /// HL7 Version 2 DLN - Drivers License Number. /// </summary> public class DriversLicenseNumber : IType { /// <inheritdoc/> public bool IsSubcomponent { get; set; } /// <summary> /// DLN.1 - License Number. /// </summary> public string LicenseNumber { get; set; } /// <summary> /// DLN.2 - Issuing State, Province, Country. /// <para>Suggested: 0333 Issuing State, Province, Country</para> /// </summary> public string IssuingStateProvinceCountry { get; set; } /// <summary> /// DLN.3 - Expiration Date. /// </summary> public DateTime? ExpirationDate { get; set; } /// <inheritdoc/> public void FromDelimitedString(string delimitedString) { FromDelimitedString(delimitedString, null); } /// <inheritdoc/> public void FromDelimitedString(string delimitedString, Separators separators) { Separators seps = separators ?? new Separators().UsingConfigurationValues(); string[] separator = IsSubcomponent ? seps.SubcomponentSeparator : seps.ComponentSeparator; string[] segments = delimitedString == null ? Array.Empty<string>() : delimitedString.Split(separator, StringSplitOptions.None); LicenseNumber = segments.Length > 0 && segments[0].Length > 0 ? segments[0] : null; IssuingStateProvinceCountry = segments.Length > 1 && segments[1].Length > 0 ? segments[1] : null; ExpirationDate = segments.Length > 2 && segments[2].Length > 0 ? segments[2].ToNullableDateTime() : null; } /// <inheritdoc/> public string ToDelimitedString() { System.Globalization.CultureInfo culture = System.Globalization.CultureInfo.CurrentCulture; string separator = IsSubcomponent ? Configuration.SubcomponentSeparator : Configuration.ComponentSeparator; return string.Format( culture, StringHelper.StringFormatSequence(0, 3, separator), LicenseNumber, IssuingStateProvinceCountry, ExpirationDate.HasValue ? ExpirationDate.Value.ToString(Consts.DateFormatPrecisionDay, culture) : null ).TrimEnd(separator.ToCharArray()); } } }
38.895522
134
0.585572
[ "MIT" ]
kamlesh-microsoft/clear-hl7-net
src/ClearHl7/V260/Types/DriversLicenseNumber.cs
2,608
C#
/***********************************************************************************************\ * (C) KAL ATM Software GmbH, 2021 * KAL ATM Software GmbH licenses this file to you under the MIT license. * See the LICENSE file in the project root for more information. \***********************************************************************************************/ using XFS4IoT; using XFS4IoTServer; using XFS4IoT.CardReader.Events; using XFS4IoT.Common.Events; namespace CardReader { internal class CardReaderConnection : ICardReaderConnection { private readonly IConnection connection; private readonly string requestId; public CardReaderConnection(IConnection connection, string requestId) { this.connection = connection; Contracts.IsNotNullOrWhitespace(requestId, $"Unexpected request ID is received. {requestId}"); this.requestId = requestId; } public void InsertCardEvent() => connection.SendMessageAsync(new InsertCardEvent(requestId)); public void MediaInsertedEvent() => connection.SendMessageAsync(new MediaInsertedEvent(requestId)); public void MediaRemovedEvent() => connection.SendMessageAsync(new MediaRemovedEvent(requestId)); public void InvalidTrackDataEvent(InvalidTrackDataEvent.PayloadData Payload) => connection.SendMessageAsync(new InvalidTrackDataEvent(requestId, Payload)); public void InvalidMediaEvent() => connection.SendMessageAsync(new InvalidMediaEvent(requestId)); public void TrackDetectedEvent(TrackDetectedEvent.PayloadData Payload) => connection.SendMessageAsync(new TrackDetectedEvent(requestId, Payload)); public void RetainBinThresholdEvent(RetainBinThresholdEvent.PayloadData Payload) => connection.SendMessageAsync(new RetainBinThresholdEvent(requestId, Payload)); public void MediaRetainedEvent() => connection.SendMessageAsync(new MediaRetainedEvent(requestId)); public void MediaDetectedEvent(MediaDetectedEvent.PayloadData Payload) => connection.SendMessageAsync(new MediaDetectedEvent(requestId, Payload)); public void EMVClessReadStatusEvent(EMVClessReadStatusEvent.PayloadData Payload) => connection.SendMessageAsync(new EMVClessReadStatusEvent(requestId, Payload)); public void CardActionEvent(CardActionEvent.PayloadData Payload) => connection.SendMessageAsync(new CardActionEvent(requestId, Payload)); public void PowerSaveChangeEvent(PowerSaveChangeEvent.PayloadData Payload) => connection.SendMessageAsync(new PowerSaveChangeEvent(requestId, Payload)); public void DevicePositionEvent(DevicePositionEvent.PayloadData Payload) => connection.SendMessageAsync(new DevicePositionEvent(requestId, Payload)); public void ServiceDetailEvent(ServiceDetailEvent.PayloadData Payload) => connection.SendMessageAsync(new ServiceDetailEvent(requestId, Payload)); } }
53.290909
169
0.726373
[ "MIT" ]
rajasekaran-ka/KAL
Framework/ServiceClasses/CardReaderServiceProvider/CardReaderConnection.cs
2,933
C#
using System; using System.Collections.Generic; using System.Net; using System.Net.Sockets; using CSharpTools; namespace Core.Net { public static class IPInfo { public static IPAddress[] ips; public static async System.Threading.Tasks.Task<IPAddress[]> GetAddresses() { IPHostEntry Host = default(IPHostEntry); string Hostname = null; Hostname = System.Environment.MachineName; Host = await Dns.GetHostEntryAsync(Hostname); ips = Host.AddressList; return Host.AddressList; } public static void PrintArray() { Console.WriteLine("Printing bindable local IPs"); for (int c = 0; c < ips.Length; c++) { Console.WriteLine("[" + c.ToString() + "] " + ips[c].ToString()); } Console.WriteLine("End of local IPs"); } } public class CSocketInfo { public GUID ipaddress; public int count; } public class CSocketListener { public Socket Server; public GuidMap ClientMap; public int buffSize; public int maxClientsPerIP; public CSocketListener(AddressFamily addressFamily, int buffSize, int MaxClientsPerIP) { Server = new Socket(addressFamily, SocketType.Stream, ProtocolType.Tcp); this.buffSize = buffSize; this.maxClientsPerIP = MaxClientsPerIP; } public CSocketListener(bool ipv6) { Server = new Socket((ipv6 ? AddressFamily.InterNetworkV6 : AddressFamily.InterNetwork), SocketType.Stream, ProtocolType.Tcp); } public void Listen(string bindip, int port, int backlog) { Listen(IPAddress.Parse(bindip), port, backlog); } public SocketException Listen(IPAddress bindip, int port, int backlog) { //The below isnt supported in .NET Core yet, but may help get information regarding the connection before accepting //Server.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.PacketInformation, true); ClientMap = new GuidMap(); try { Server.Bind(new IPEndPoint(bindip, port)); } catch (SocketException se) { Debug.Out(se.Message); return se; } try { Server.Listen(backlog); } catch (SocketException se) { Debug.Out(se.Message); return se; } Debug.Out(String.Format("Listening on {0}:{1} backlog={2}", bindip.ToString(), port, backlog)); return null; } public List<CSocket> Accept() { List<CSocket> AcceptClients = new List<CSocket>(); // Need a break in the below while condition for flood prot // Changing this to IF to not block up the server if being spammed by sockets if (Server.Poll(0, SelectMode.SelectRead)) { //EndPoint ep1 = Server.RemoteEndPoint; CSocket socket = new CSocket(Server.Accept(), buffSize); //EndPoint ep2 = socket.RemoteEndPoint; if (socket != null) { // Check count GuidNode node = ClientMap.AddGuid(socket.Address); if (node.count <= maxClientsPerIP) { AcceptClients.Add(socket); Debug.Out("[" + AcceptClients.Count.ToString() + "]connected " + socket.RemoteEndPoint); Debug.Out("[" + AcceptClients.Count.ToString() + "]socket " + new String8(node.guid.ToHex()).chars + " count = " + node.count.ToString()); } else { Debug.Out("[" + AcceptClients.Count.ToString() + "]dumped socket " + new String8(node.guid.ToHex()).chars + " count = " + node.count.ToString()); socket.Shutdown(SocketShutdown.Both); ClientMap.DecGuid(socket.Address); } } } return AcceptClients; } } public class CSocket { private Socket socket; private StringBuffer buffer; private GUID guid; private bool bTerminateSocket; public GUID Address { get { return guid; } } public bool IsConnected { get { return socket.Connected; } } public String8 RemoteIP { get { return ((IPEndPoint)socket.RemoteEndPoint).Address.ToString(); } } public CSocket(Socket socket, int buffSize) { this.socket = socket; this.socket.Blocking = false; this.socket.LingerState = new LingerOption(true, 1); buffer = new StringBuffer(buffSize); guid = new GUID(); if (socket.RemoteEndPoint.AddressFamily == AddressFamily.InterNetwork) { guid.Data1 = BitConverter.ToUInt32(((IPEndPoint)socket.RemoteEndPoint).Address.GetAddressBytes(), 0); } else { guid.SetBytes(((IPEndPoint)socket.RemoteEndPoint).Address.GetAddressBytes()); } } public EndPoint RemoteEndPoint { get { return socket.RemoteEndPoint; } } public void Shutdown(SocketShutdown both) { Debug.Out(socket.RemoteEndPoint.ToString() + " has been Shutdown (" + (new String8(guid.ToHex()).chars + ")")); try { socket.Shutdown(both); } catch (SocketException se) { } } public void Terminate() { bTerminateSocket = true; } public List<String8> Process() { int bytes = -1; if (socket.Connected) { if (socket.Poll(0, SelectMode.SelectRead)) { byte[] b = new byte[buffer.Capacity]; try { bytes = socket.Receive(b); } catch (SocketException se) { } if (bytes > 0) { buffer.Digest(b, bytes); return buffer.DataIn; } else { Shutdown(SocketShutdown.Both); } } if (socket.Poll(0, SelectMode.SelectWrite)) { if (buffer.bytesOut.Count > 0) { try { bytes = socket.Send(buffer.bytesOut); } catch (SocketException se) { } buffer.bytesOut.Clear(); if (bTerminateSocket) { Shutdown(SocketShutdown.Both); } } } } else { Shutdown(SocketShutdown.Both); } return null; } public void Send(String8 data) { buffer.bytesOut.Add(new ArraySegment<byte>(data.bytes, 0, data.length)); } } }
35.924623
169
0.519653
[ "MIT" ]
IRC7/IRC7
Net/NetCore.cs
7,151
C#
using System.Collections.Generic; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Brash.Infrastructure; using TodoList.Domain.Model; using TodoList.Infrastructure.Sqlite.Service; namespace TodoList.Api.Controllers { [Authorize] [Route("api/[controller]")] [ApiController] public class ToolsRequiredController : ControllerBase { private ToolsRequiredService _toolsRequiredService { get; set; } private Serilog.ILogger _logger { get; set; } public ToolsRequiredController(ToolsRequiredService toolsRequiredService, Serilog.ILogger logger) : base() { _toolsRequiredService = toolsRequiredService; _logger = logger; } // GET /api/ToolsRequired/ [HttpGet] public ActionResult<IEnumerable<ToolsRequired>> Get() { var queryResult = _toolsRequiredService.FindWhere("WHERE 1 = 1 ORDER BY 1 "); if (queryResult.Status == BrashQueryStatus.ERROR) return BadRequest(queryResult.Message); return queryResult.Models; } // GET api/ToolsRequired/5 [HttpGet("{id}")] public ActionResult<ToolsRequired> Get(int id) { var model = new ToolsRequired() { ToolsRequiredId = id }; var serviceResult = _toolsRequiredService.Fetch(model); if (serviceResult.Status == BrashActionStatus.ERROR) return BadRequest(serviceResult.Message); if (serviceResult.Status == BrashActionStatus.NOT_FOUND) return NotFound(serviceResult.Message); return serviceResult.Model; } // POST api/ToolsRequired [HttpPost] public ActionResult<ToolsRequired> Post([FromBody] ToolsRequired model) { var serviceResult = _toolsRequiredService.Create(model); if (serviceResult.Status == BrashActionStatus.ERROR) return BadRequest(serviceResult.Message); return serviceResult.Model; } // PUT api/ToolsRequired/6 [HttpPut("{id}")] public ActionResult<ToolsRequired> Put(int id, [FromBody] ToolsRequired model) { model.ToolsRequiredId = id; var serviceResult = _toolsRequiredService.Update(model); if (serviceResult.Status == BrashActionStatus.ERROR) return BadRequest(serviceResult.Message); if (serviceResult.Status == BrashActionStatus.NOT_FOUND) return NotFound(serviceResult.Message); return serviceResult.Model; } // DELETE api/ToolsRequired/6 [HttpDelete("{id}")] public ActionResult<ToolsRequired> Delete(int id) { var model = new ToolsRequired() { ToolsRequiredId = id }; var serviceResult = _toolsRequiredService.Delete(model); if (serviceResult.Status == BrashActionStatus.ERROR) return BadRequest(serviceResult.Message); return serviceResult.Model; } // GET /api/ToolsRequiredByParent/4 [HttpGet("{id}")] public ActionResult<IEnumerable<ToolsRequired>> GetByParent(int id) { var queryResult = _toolsRequiredService.FindByParent(id); if (queryResult.Status == BrashQueryStatus.ERROR) return BadRequest(queryResult.Message); return queryResult.Models; } } }
27.990654
108
0.734558
[ "Unlicense" ]
randomsilo/modern-web
backends/TodoList/TodoList.Api/Controllers/ToolsRequiredController.cs
2,995
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Core.Tuneles; namespace Core.Negocio.Canchas { public class CanchaResponse : Respuesta<CanchaFutbol> { /// <summary> /// Es la acción realizada de la respuesta específicamente para las canchas /// </summary> public AccionRealizada AccionRealizada { get; set; } } public enum AccionRealizada { /// <summary> /// Crear una cancha /// </summary> CREAR = 0, /// <summary> /// Agregar una división a una cancha /// </summary> AGREGARDIVISION = 1, /// <summary> /// Eliminar una división /// </summary> ELIMINARDIVISION = 2, /// <summary> /// Eliminar la cancha /// </summary> ELIMINAR = 3, /// <summary> /// Habilitar la cancha /// </summary> HABILITAR = 4, /// <summary> /// Deshabilitar la cancha /// </summary> DESHABILITAR = 5, /// <summary> /// Al obtener una/varias canchas /// </summary> OBTENER = 6, /// <summary> /// Al modificar la cancha /// </summary> MODIFICAR = 7, } }
24.909091
84
0.5
[ "MIT" ]
hangardonelli/FC-Cba-services
Core/Negocio/Canchas/CanchaResponse.cs
1,376
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Ioc.Modules; using Ninject; using OwinFramework.Interfaces.Utility; using OwinFramework.Middleware.TestServer.Prius; using Prius.Contracts.Interfaces.External; namespace OwinFramework.Middleware.TestServer { [Package] internal class Package: IPackage { public string Name { get { return "OWIN Framework middleware test server"; } } public IList<IocRegistration> IocRegistrations { get { return new List<IocRegistration> { new IocRegistration().Init<IHostingEnvironment, HostingEnvironment>(), new IocRegistration().Init<IFactory, PriusFactory>(), new IocRegistration().Init<IErrorReporter, PriusErrorReporter>(), }; } } } }
27.705882
90
0.636943
[ "Apache-2.0" ]
Bikeman868/OwinFramework.Middleware
TestServer/Package.cs
944
C#
using System.Runtime.InteropServices; using System.Windows.Media; using HandyControl.Data; using HandyControl.Tools; using HandyControl.Tools.Interop; namespace HandyControl.Controls { public class BlurWindow : Window { public override void OnApplyTemplate() { base.OnApplyTemplate(); EnableBlur(this); } internal static void EnableBlur(Window window) { var version = OSVersionHelper.GetOSVersion(); var versionInfo = new SystemVersionInfo(version.Major, version.Minor, version.Build); if (versionInfo < SystemVersionInfo.Windows10 || versionInfo >= SystemVersionInfo.Windows10_1903) { var colorValue = ResourceHelper.GetResource<uint>(ResourceToken.BlurGradientValue); var color = ColorHelper.ToColor(colorValue); color = Color.FromRgb(color.R, color.G, color.B); window.Background = new SolidColorBrush(color); return; } var accentPolicy = new InteropValues.ACCENTPOLICY(); var accentPolicySize = Marshal.SizeOf(accentPolicy); accentPolicy.AccentState = versionInfo < SystemVersionInfo.Windows10_1809 ? InteropValues.ACCENTSTATE.ACCENT_ENABLE_BLURBEHIND : InteropValues.ACCENTSTATE.ACCENT_ENABLE_ACRYLICBLURBEHIND; accentPolicy.AccentFlags = 2; accentPolicy.GradientColor = ResourceHelper.GetResource<uint>(ResourceToken.BlurGradientValue); var accentPtr = Marshal.AllocHGlobal(accentPolicySize); Marshal.StructureToPtr(accentPolicy, accentPtr, false); var data = new InteropValues.WINCOMPATTRDATA { Attribute = InteropValues.WINDOWCOMPOSITIONATTRIB.WCA_ACCENT_POLICY, DataSize = accentPolicySize, Data = accentPtr }; InteropMethods.Gdip.SetWindowCompositionAttribute(window.GetHandle(), ref data); Marshal.FreeHGlobal(accentPtr); } } }
36.448276
107
0.641438
[ "MIT" ]
nfsmaniac/HandyControls
src/Shared/HandyControl_Shared/Controls/Window/BlurWindow.cs
2,116
C#
using BEDA.CMB.Contracts.Responses; using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Xml.Serialization; namespace BEDA.CMB.Contracts.Requests { /// <summary> /// 23.3.取公司卡详细信息请求主体 /// </summary> [XmlRoot("CMBSDKPGK")] public class RQ23_3 : CMBBase<RQINFO>, IRequest<RS23_3> { /// <summary> /// NTCPRRTV /// </summary> /// <returns></returns> public override string GetFUNNAM() => "NTCPRRTV"; /// <summary> /// 23.3.取公司卡详细信息请求内容 /// </summary> public NTCPRCD1X NTCPRCD1X { get; set; } } /// <summary> /// 23.3.取公司卡详细信息请求内容 /// </summary> public class NTCPRCD1X { /// <summary> /// 公司卡号 C(20) /// </summary> public string PSBNBR { get; set; } /// <summary> /// 分行号 C(2) /// </summary> public string BBKNBR { get; set; } /// <summary> /// 公司结算户 C(35) /// </summary> public string ACCNBR { get; set; } } }
24.170213
59
0.539613
[ "MIT" ]
fdstar/BankEnterpriseDirectAttach
src/BEDA.CMB/Contracts/Requests/23/RQ23_3.cs
1,234
C#
using MaterialDesignThemes.Wpf; using System; using System.Collections.Generic; using System.Linq; using System.Windows; using Youtube_DL.Core; using Youtube_DL.Model; namespace Youtube_DL.ViewModel { internal class AddVideoPopupViewModel : BaseViewModel { private readonly YoutubeVideoService _youtubeservise; public AddVideoPopupViewModel() { _youtubeservise = new YoutubeVideoService(); AddVideoCommand = new Command(AddVideoToList); } public Command AddVideoCommand { get; } public bool IsLoading { get; private set; } private async void AddVideoToList(object s) { if (IsLoading || string.IsNullOrWhiteSpace(s as string)) return; string url = (string)s; try { IsLoading = true; var videos = await _youtubeservise.GetVideosAsync(url); IReadOnlyList<VideoDownloadOption>? videoOptions; string? title = default; if (videos.Length == 1) videoOptions = await _youtubeservise.GetVideoDownloadOptionsAsync(url); else { videoOptions = YoutubeVideoService.GetOptionPlaylist().Reverse().ToArray(); title = await _youtubeservise.GetPlaylistTitle(url); } IsLoading = false; DialogHost.Close("MainDialog", new YoutubeVideoModel(videos, videoOptions, title)); } catch (ArgumentException e) { MessageBox.Show(e.Message); } catch (Exception e) { MessageBox.Show(e.Message); } IsLoading = false; } } }
30.033333
99
0.568812
[ "Apache-2.0" ]
eldiablo-1226/Youtube-DL-NET
src/Youtube-DL/ViewModel/AddVideoPopupViewModel.cs
1,804
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 Microsoft.DataTransfer.CsvFile { using System; /// <summary> /// A strongly-typed resource class, for looking up localized strings, etc. /// </summary> // This class was auto-generated by the StronglyTypedResourceBuilder // class via a tool like ResGen or Visual Studio. // To add or remove a member, edit your .ResX file then rerun ResGen // with the /str option, or rebuild your VS project. [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] public class ConfigurationResources { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal ConfigurationResources() { } /// <summary> /// Returns the cached ResourceManager instance used by this class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] public static global::System.Resources.ResourceManager ResourceManager { get { if (object.ReferenceEquals(resourceMan, null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Microsoft.DataTransfer.CsvFile.ConfigurationResources", typeof(ConfigurationResources).Assembly); resourceMan = temp; } return resourceMan; } } /// <summary> /// Overrides the current thread's CurrentUICulture property for all /// resource lookups using this strongly typed resource class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] public static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } /// <summary> /// Looks up a localized string similar to Optional. If source files should be decompressed with GZip. /// </summary> public static string Source_Decompress { get { return ResourceManager.GetString("Source_Decompress", resourceCulture); } } /// <summary> /// Looks up a localized string similar to One or more file search patterns to read CSV from. /// </summary> public static string Source_Files { get { return ResourceManager.GetString("Source_Files", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Optional. Special character in the column name to indicate that nested document is needed. /// </summary> public static string Source_NestingSeparator { get { return ResourceManager.GetString("Source_NestingSeparator", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Optional. If unquoted NULL string should be treated as string. /// </summary> public static string Source_NoUnquotedNulls { get { return ResourceManager.GetString("Source_NoUnquotedNulls", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Optional. If empty space at the start and end of the quoted value should be removed. /// </summary> public static string Source_TrimQuoted { get { return ResourceManager.GetString("Source_TrimQuoted", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Optional. If system regional settings should be used to parse the files. This includes such settings as list separator, number, date and time format. /// </summary> public static string Source_UseRegionalSettings { get { return ResourceManager.GetString("Source_UseRegionalSettings", resourceCulture); } } } }
43.161017
211
0.604163
[ "MIT" ]
Adrian-Wennberg/azure-documentdb-datamigrationtool
CsvFile/Microsoft.DataTransfer.CsvFile/ConfigurationResources.Designer.cs
5,095
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 cloudfront-2020-05-31.normal.json service model. */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Net; using System.Text; using System.Xml.Serialization; using Amazon.CloudFront.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; namespace Amazon.CloudFront.Model.Internal.MarshallTransformations { /// <summary> /// Response Unmarshaller for TooManyPublicKeysException operation /// </summary> public class TooManyPublicKeysExceptionUnmarshaller : IErrorResponseUnmarshaller<TooManyPublicKeysException, XmlUnmarshallerContext> { /// <summary> /// Unmarshaller the response from the service to the response class. /// </summary> /// <param name="context"></param> /// <returns></returns> public TooManyPublicKeysException Unmarshall(XmlUnmarshallerContext context) { throw new NotImplementedException(); } /// <summary> /// Unmarshaller the response from the service to the response class. /// </summary> /// <param name="context"></param> /// <param name="errorResponse"></param> /// <returns></returns> public TooManyPublicKeysException Unmarshall(XmlUnmarshallerContext context, Amazon.Runtime.Internal.ErrorResponse errorResponse) { TooManyPublicKeysException response = new TooManyPublicKeysException(errorResponse.Message, errorResponse.InnerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, errorResponse.StatusCode); while (context.Read()) { if (context.IsStartElement || context.IsAttribute) { } } return response; } private static TooManyPublicKeysExceptionUnmarshaller _instance = new TooManyPublicKeysExceptionUnmarshaller(); /// <summary> /// Gets the singleton. /// </summary> public static TooManyPublicKeysExceptionUnmarshaller Instance { get { return _instance; } } } }
35.26506
137
0.666894
[ "Apache-2.0" ]
EbstaLimited/aws-sdk-net
sdk/src/Services/CloudFront/Generated/Model/Internal/MarshallTransformations/TooManyPublicKeysExceptionUnmarshaller.cs
2,927
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // <auto-generated/> #nullable disable using System; using System.Collections.Generic; using System.Text.Json; using System.Threading; using System.Threading.Tasks; using Azure; using Azure.Core; using Azure.Core.Pipeline; using Azure.Iot.Hub.Service.Models; namespace Azure.Iot.Hub.Service { internal partial class ConfigurationRestClient { private Uri endpoint; private string apiVersion; private ClientDiagnostics _clientDiagnostics; private HttpPipeline _pipeline; /// <summary> Initializes a new instance of ConfigurationRestClient. </summary> /// <param name="clientDiagnostics"> The handler for diagnostic messaging in the client. </param> /// <param name="pipeline"> The HTTP pipeline for sending and receiving REST requests and responses. </param> /// <param name="endpoint"> server parameter. </param> /// <param name="apiVersion"> Api Version. </param> /// <exception cref="ArgumentNullException"> <paramref name="apiVersion"/> is null. </exception> public ConfigurationRestClient(ClientDiagnostics clientDiagnostics, HttpPipeline pipeline, Uri endpoint = null, string apiVersion = "2020-03-13") { endpoint ??= new Uri("https://fully-qualified-iothubname.azure-devices.net"); if (apiVersion == null) { throw new ArgumentNullException(nameof(apiVersion)); } this.endpoint = endpoint; this.apiVersion = apiVersion; _clientDiagnostics = clientDiagnostics; _pipeline = pipeline; } internal HttpMessage CreateGetRequest(string id) { var message = _pipeline.CreateMessage(); var request = message.Request; request.Method = RequestMethod.Get; var uri = new RawRequestUriBuilder(); uri.Reset(endpoint); uri.AppendPath("/configurations/", false); uri.AppendPath(id, true); uri.AppendQuery("api-version", apiVersion, true); request.Uri = uri; return message; } /// <summary> Gets a configuration on the IoT Hub for automatic device/module management. </summary> /// <param name="id"> The unique identifier of the configuration. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="id"/> is null. </exception> public async Task<Response<TwinConfiguration>> GetAsync(string id, CancellationToken cancellationToken = default) { if (id == null) { throw new ArgumentNullException(nameof(id)); } using var message = CreateGetRequest(id); await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); switch (message.Response.Status) { case 200: { TwinConfiguration value = default; using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, default, cancellationToken).ConfigureAwait(false); value = TwinConfiguration.DeserializeTwinConfiguration(document.RootElement); return Response.FromValue(value, message.Response); } default: throw await _clientDiagnostics.CreateRequestFailedExceptionAsync(message.Response).ConfigureAwait(false); } } /// <summary> Gets a configuration on the IoT Hub for automatic device/module management. </summary> /// <param name="id"> The unique identifier of the configuration. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="id"/> is null. </exception> public Response<TwinConfiguration> Get(string id, CancellationToken cancellationToken = default) { if (id == null) { throw new ArgumentNullException(nameof(id)); } using var message = CreateGetRequest(id); _pipeline.Send(message, cancellationToken); switch (message.Response.Status) { case 200: { TwinConfiguration value = default; using var document = JsonDocument.Parse(message.Response.ContentStream); value = TwinConfiguration.DeserializeTwinConfiguration(document.RootElement); return Response.FromValue(value, message.Response); } default: throw _clientDiagnostics.CreateRequestFailedException(message.Response); } } internal HttpMessage CreateCreateOrUpdateRequest(string id, TwinConfiguration configuration, string ifMatch) { var message = _pipeline.CreateMessage(); var request = message.Request; request.Method = RequestMethod.Put; var uri = new RawRequestUriBuilder(); uri.Reset(endpoint); uri.AppendPath("/configurations/", false); uri.AppendPath(id, true); uri.AppendQuery("api-version", apiVersion, true); request.Uri = uri; if (ifMatch != null) { request.Headers.Add("If-Match", ifMatch); } request.Headers.Add("Content-Type", "application/json"); var content = new Utf8JsonRequestContent(); content.JsonWriter.WriteObjectValue(configuration); request.Content = content; return message; } /// <summary> Creates or updates a configuration on the IoT Hub for automatic device/module management. Configuration identifier and Content cannot be updated. </summary> /// <param name="id"> The unique identifier of the configuration. </param> /// <param name="configuration"> The configuration to be created or updated. </param> /// <param name="ifMatch"> The string representing a weak ETag for configuration, as per RFC7232. This should not be set when creating a configuration, but may be set when updating a configuration. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="id"/> or <paramref name="configuration"/> is null. </exception> public async Task<Response<TwinConfiguration>> CreateOrUpdateAsync(string id, TwinConfiguration configuration, string ifMatch = null, CancellationToken cancellationToken = default) { if (id == null) { throw new ArgumentNullException(nameof(id)); } if (configuration == null) { throw new ArgumentNullException(nameof(configuration)); } using var message = CreateCreateOrUpdateRequest(id, configuration, ifMatch); await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); switch (message.Response.Status) { case 200: case 201: { TwinConfiguration value = default; using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, default, cancellationToken).ConfigureAwait(false); value = TwinConfiguration.DeserializeTwinConfiguration(document.RootElement); return Response.FromValue(value, message.Response); } default: throw await _clientDiagnostics.CreateRequestFailedExceptionAsync(message.Response).ConfigureAwait(false); } } /// <summary> Creates or updates a configuration on the IoT Hub for automatic device/module management. Configuration identifier and Content cannot be updated. </summary> /// <param name="id"> The unique identifier of the configuration. </param> /// <param name="configuration"> The configuration to be created or updated. </param> /// <param name="ifMatch"> The string representing a weak ETag for configuration, as per RFC7232. This should not be set when creating a configuration, but may be set when updating a configuration. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="id"/> or <paramref name="configuration"/> is null. </exception> public Response<TwinConfiguration> CreateOrUpdate(string id, TwinConfiguration configuration, string ifMatch = null, CancellationToken cancellationToken = default) { if (id == null) { throw new ArgumentNullException(nameof(id)); } if (configuration == null) { throw new ArgumentNullException(nameof(configuration)); } using var message = CreateCreateOrUpdateRequest(id, configuration, ifMatch); _pipeline.Send(message, cancellationToken); switch (message.Response.Status) { case 200: case 201: { TwinConfiguration value = default; using var document = JsonDocument.Parse(message.Response.ContentStream); value = TwinConfiguration.DeserializeTwinConfiguration(document.RootElement); return Response.FromValue(value, message.Response); } default: throw _clientDiagnostics.CreateRequestFailedException(message.Response); } } internal HttpMessage CreateDeleteRequest(string id, string ifMatch) { var message = _pipeline.CreateMessage(); var request = message.Request; request.Method = RequestMethod.Delete; var uri = new RawRequestUriBuilder(); uri.Reset(endpoint); uri.AppendPath("/configurations/", false); uri.AppendPath(id, true); uri.AppendQuery("api-version", apiVersion, true); request.Uri = uri; if (ifMatch != null) { request.Headers.Add("If-Match", ifMatch); } return message; } /// <summary> Deletes a configuration on the IoT Hub for automatic device/module management. </summary> /// <param name="id"> The unique identifier of the configuration. </param> /// <param name="ifMatch"> The string representing a weak ETag for configuration, as per RFC7232. The delete operation is performed only if this ETag matches the value maintained by the server, indicating that the configuration has not been modified since it was last retrieved. To force an unconditional delete, set If-Match to the wildcard character (*). </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="id"/> is null. </exception> public async Task<Response> DeleteAsync(string id, string ifMatch = null, CancellationToken cancellationToken = default) { if (id == null) { throw new ArgumentNullException(nameof(id)); } using var message = CreateDeleteRequest(id, ifMatch); await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); switch (message.Response.Status) { case 204: return message.Response; default: throw await _clientDiagnostics.CreateRequestFailedExceptionAsync(message.Response).ConfigureAwait(false); } } /// <summary> Deletes a configuration on the IoT Hub for automatic device/module management. </summary> /// <param name="id"> The unique identifier of the configuration. </param> /// <param name="ifMatch"> The string representing a weak ETag for configuration, as per RFC7232. The delete operation is performed only if this ETag matches the value maintained by the server, indicating that the configuration has not been modified since it was last retrieved. To force an unconditional delete, set If-Match to the wildcard character (*). </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="id"/> is null. </exception> public Response Delete(string id, string ifMatch = null, CancellationToken cancellationToken = default) { if (id == null) { throw new ArgumentNullException(nameof(id)); } using var message = CreateDeleteRequest(id, ifMatch); _pipeline.Send(message, cancellationToken); switch (message.Response.Status) { case 204: return message.Response; default: throw _clientDiagnostics.CreateRequestFailedException(message.Response); } } internal HttpMessage CreateGetConfigurationsRequest(int? top) { var message = _pipeline.CreateMessage(); var request = message.Request; request.Method = RequestMethod.Get; var uri = new RawRequestUriBuilder(); uri.Reset(endpoint); uri.AppendPath("/configurations", false); if (top != null) { uri.AppendQuery("top", top.Value, true); } uri.AppendQuery("api-version", apiVersion, true); request.Uri = uri; return message; } /// <summary> Gets configurations on the IoT Hub for automatic device/module management. Pagination is not supported. </summary> /// <param name="top"> The number of configurations to retrieve. Value will be overridden if greater than the maximum deployment count for the IoT Hub. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> public async Task<Response<IReadOnlyList<TwinConfiguration>>> GetConfigurationsAsync(int? top = null, CancellationToken cancellationToken = default) { using var message = CreateGetConfigurationsRequest(top); await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); switch (message.Response.Status) { case 200: { IReadOnlyList<TwinConfiguration> value = default; using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, default, cancellationToken).ConfigureAwait(false); List<TwinConfiguration> array = new List<TwinConfiguration>(); foreach (var item in document.RootElement.EnumerateArray()) { array.Add(TwinConfiguration.DeserializeTwinConfiguration(item)); } value = array; return Response.FromValue(value, message.Response); } default: throw await _clientDiagnostics.CreateRequestFailedExceptionAsync(message.Response).ConfigureAwait(false); } } /// <summary> Gets configurations on the IoT Hub for automatic device/module management. Pagination is not supported. </summary> /// <param name="top"> The number of configurations to retrieve. Value will be overridden if greater than the maximum deployment count for the IoT Hub. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> public Response<IReadOnlyList<TwinConfiguration>> GetConfigurations(int? top = null, CancellationToken cancellationToken = default) { using var message = CreateGetConfigurationsRequest(top); _pipeline.Send(message, cancellationToken); switch (message.Response.Status) { case 200: { IReadOnlyList<TwinConfiguration> value = default; using var document = JsonDocument.Parse(message.Response.ContentStream); List<TwinConfiguration> array = new List<TwinConfiguration>(); foreach (var item in document.RootElement.EnumerateArray()) { array.Add(TwinConfiguration.DeserializeTwinConfiguration(item)); } value = array; return Response.FromValue(value, message.Response); } default: throw _clientDiagnostics.CreateRequestFailedException(message.Response); } } internal HttpMessage CreateTestQueriesRequest(ConfigurationQueriesTestInput input) { var message = _pipeline.CreateMessage(); var request = message.Request; request.Method = RequestMethod.Post; var uri = new RawRequestUriBuilder(); uri.Reset(endpoint); uri.AppendPath("/configurations/testQueries", false); uri.AppendQuery("api-version", apiVersion, true); request.Uri = uri; request.Headers.Add("Content-Type", "application/json"); var content = new Utf8JsonRequestContent(); content.JsonWriter.WriteObjectValue(input); request.Content = content; return message; } /// <summary> Validates target condition and custom metric queries for a configuration on the IoT Hub. </summary> /// <param name="input"> The configuration for target condition and custom metric queries. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="input"/> is null. </exception> public async Task<Response<ConfigurationQueriesTestResponse>> TestQueriesAsync(ConfigurationQueriesTestInput input, CancellationToken cancellationToken = default) { if (input == null) { throw new ArgumentNullException(nameof(input)); } using var message = CreateTestQueriesRequest(input); await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); switch (message.Response.Status) { case 200: { ConfigurationQueriesTestResponse value = default; using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, default, cancellationToken).ConfigureAwait(false); value = ConfigurationQueriesTestResponse.DeserializeConfigurationQueriesTestResponse(document.RootElement); return Response.FromValue(value, message.Response); } default: throw await _clientDiagnostics.CreateRequestFailedExceptionAsync(message.Response).ConfigureAwait(false); } } /// <summary> Validates target condition and custom metric queries for a configuration on the IoT Hub. </summary> /// <param name="input"> The configuration for target condition and custom metric queries. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="input"/> is null. </exception> public Response<ConfigurationQueriesTestResponse> TestQueries(ConfigurationQueriesTestInput input, CancellationToken cancellationToken = default) { if (input == null) { throw new ArgumentNullException(nameof(input)); } using var message = CreateTestQueriesRequest(input); _pipeline.Send(message, cancellationToken); switch (message.Response.Status) { case 200: { ConfigurationQueriesTestResponse value = default; using var document = JsonDocument.Parse(message.Response.ContentStream); value = ConfigurationQueriesTestResponse.DeserializeConfigurationQueriesTestResponse(document.RootElement); return Response.FromValue(value, message.Response); } default: throw _clientDiagnostics.CreateRequestFailedException(message.Response); } } internal HttpMessage CreateApplyOnEdgeDeviceRequest(string id, ConfigurationContent content) { var message = _pipeline.CreateMessage(); var request = message.Request; request.Method = RequestMethod.Post; var uri = new RawRequestUriBuilder(); uri.Reset(endpoint); uri.AppendPath("/devices/", false); uri.AppendPath(id, true); uri.AppendPath("/applyConfigurationContent", false); uri.AppendQuery("api-version", apiVersion, true); request.Uri = uri; request.Headers.Add("Content-Type", "application/json"); var content0 = new Utf8JsonRequestContent(); content0.JsonWriter.WriteObjectValue(content); request.Content = content0; return message; } /// <summary> Applies the configuration content to an edge device. </summary> /// <param name="id"> The unique identifier of the edge device. </param> /// <param name="content"> The configuration content. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="id"/> or <paramref name="content"/> is null. </exception> public async Task<Response> ApplyOnEdgeDeviceAsync(string id, ConfigurationContent content, CancellationToken cancellationToken = default) { if (id == null) { throw new ArgumentNullException(nameof(id)); } if (content == null) { throw new ArgumentNullException(nameof(content)); } using var message = CreateApplyOnEdgeDeviceRequest(id, content); await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); switch (message.Response.Status) { case 204: return message.Response; default: throw await _clientDiagnostics.CreateRequestFailedExceptionAsync(message.Response).ConfigureAwait(false); } } /// <summary> Applies the configuration content to an edge device. </summary> /// <param name="id"> The unique identifier of the edge device. </param> /// <param name="content"> The configuration content. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="id"/> or <paramref name="content"/> is null. </exception> public Response ApplyOnEdgeDevice(string id, ConfigurationContent content, CancellationToken cancellationToken = default) { if (id == null) { throw new ArgumentNullException(nameof(id)); } if (content == null) { throw new ArgumentNullException(nameof(content)); } using var message = CreateApplyOnEdgeDeviceRequest(id, content); _pipeline.Send(message, cancellationToken); switch (message.Response.Status) { case 204: return message.Response; default: throw _clientDiagnostics.CreateRequestFailedException(message.Response); } } } }
51.15942
373
0.607689
[ "MIT" ]
AbelHu/azure-sdk-for-net
sdk/iot/Azure.Iot.Hub.Service/src/Generated/ConfigurationRestClient.cs
24,710
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Activities; using Microsoft.Sample.Automation.Scheduling.Engine.Entities; namespace Microsoft.Sample.Automation.Scheduling.Engine { public sealed class PollCodeActivity : CodeActivity<bool> { protected override bool Execute(CodeActivityContext context) { bool dodelay = true; if (Dispatcher.PollDispatchReady()) { dodelay = false; } else if (Dispatcher.PollExpiredSchedule()) { dodelay = false; } return dodelay; } } }
22.9
68
0.60262
[ "Apache-2.0" ]
leo-leong/wwt-scheduler
Microsoft.Sample.Automation/DispatchEngineService/Activity/PollCodeActivity.cs
689
C#
namespace Appalachia.Audio.Contextual.Context { public enum Biome_AudioContexts : short { Default = 0, Underwater = 1, River = 2, RiverBanks = 4, HeathAshShrubland = 5, NorthernHardwoodForest = 7, OakHickoryForest = 8, GreatLakesBeechMapleForest = 9, SerpentinitePineForest = 10, CoastalPlainForest = 11, RiparianForest = 12, ShaleAndLimestoneBarrens = 13 } }
24.631579
45
0.602564
[ "MIT" ]
ChristopherSchubert/com.appalachia.unity3d.audio
src/Contextual/Context/Biome_AudioContexts.cs
468
C#
namespace MassTransit.KafkaIntegration.Contexts { using System; using System.Collections.Generic; using System.Diagnostics; using System.Threading.Tasks; using Configuration; using Confluent.Kafka; using Context; using Util; public class ConsumerLockContext<TKey, TValue> : IConsumerLockContext<TKey, TValue> where TValue : class { readonly SingleThreadedDictionary<Partition, PartitionCheckpointData> _data = new SingleThreadedDictionary<Partition, PartitionCheckpointData>(); readonly IHostConfiguration _hostConfiguration; readonly ushort _maxCount; readonly TimeSpan _timeout; public ConsumerLockContext(IHostConfiguration hostConfiguration, ReceiveSettings receiveSettings) { _hostConfiguration = hostConfiguration; _timeout = receiveSettings.CheckpointInterval; _maxCount = receiveSettings.CheckpointMessageCount; } public Task Complete(ConsumeResult<TKey, TValue> result) { LogContext.SetCurrentIfNull(_hostConfiguration.ReceiveLogContext); if (_data.TryGetValue(result.Partition, out var data)) data.TryCheckpoint(result); return TaskUtil.Completed; } public void OnAssigned(IConsumer<TKey, TValue> consumer, IEnumerable<TopicPartition> partitions) { LogContext.SetCurrentIfNull(_hostConfiguration.ReceiveLogContext); foreach (var partition in partitions) { if (_data.TryAdd(partition.Partition, p => new PartitionCheckpointData(partition, consumer, _timeout, _maxCount))) LogContext.Info?.Log("Partition: {PartitionId} was assigned", partition); } } public void OnUnAssigned(IConsumer<TKey, TValue> consumer, IEnumerable<TopicPartitionOffset> partitions) { LogContext.SetCurrentIfNull(_hostConfiguration.ReceiveLogContext); foreach (var partition in partitions) { if (_data.TryRemove(partition.Partition, out var data)) data.Close(partition); } } sealed class PartitionCheckpointData { readonly IConsumer<TKey, TValue> _consumer; readonly object _lock; readonly int _maxCount; readonly TopicPartition _partition; readonly TimeSpan _timeout; readonly Stopwatch _timer; bool _commitIsRequired; Offset _offset; ushort _processed; public PartitionCheckpointData(TopicPartition partition, IConsumer<TKey, TValue> consumer, TimeSpan timeout, ushort maxCount) { _partition = partition; _consumer = consumer; _timeout = timeout; _maxCount = maxCount; _processed = 0; _timer = Stopwatch.StartNew(); _lock = new object(); _commitIsRequired = false; } public bool TryCheckpoint(ConsumeResult<TKey, TValue> result) { void Reset() { _processed = 0; _commitIsRequired = false; _timer.Restart(); } lock (_lock) { if (_offset < result.Offset) { _offset = result.Offset; _commitIsRequired = true; } _processed += 1; if (_processed < _maxCount && _timer.Elapsed < _timeout) return false; CommitIfRequired(); Reset(); return true; } } public void Close(TopicPartitionOffset partition) { try { lock (_lock) CommitIfRequired(); } finally { _timer.Stop(); _offset = default; _commitIsRequired = false; LogContext.Info?.Log("Partition: {PartitionId} was closed", partition.TopicPartition); } } void CommitIfRequired() { if (!_commitIsRequired) return; var offset = _offset + 1; LogContext.Debug?.Log("Partition: {PartitionId} updating checkpoint with offset: {Offset}", _partition, offset); _consumer.Commit(new[] {new TopicPartitionOffset(_partition, offset)}); } } } }
33.699301
153
0.545134
[ "ECL-2.0", "Apache-2.0" ]
AhmedKhalil777/MassTransit
src/Transports/MassTransit.KafkaIntegration/Contexts/ConsumerLockContext.cs
4,819
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. using System.Reflection; using System.Resources; [assembly: AssemblyTitle("Microsoft Azure Data Migration Management Library")] [assembly: AssemblyDescription("Provides management functionality for Microsoft Azure Data Migration Resources.")] [assembly: AssemblyVersion("0.6.0.0")] [assembly: AssemblyFileVersion("0.6.0.0")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Microsoft")] [assembly: AssemblyProduct("Microsoft Azure .NET SDK")] [assembly: AssemblyCopyright("Copyright (c) Microsoft Corporation")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: NeutralResourcesLanguage("en")]
42
114
0.783208
[ "MIT" ]
Sav0966/azure-sdk-for-net
src/SDKs/DataMigration/Management.DataMigration/Properties/AssemblyInfo.cs
798
C#
// Copyright (c) 2007 James Newton-King. All rights reserved. // Use of this source code is governed by The MIT License, // as found in the license.md file. namespace TestObjects; class DictionaryKeyCast { string _name; int _number; public DictionaryKeyCast(string name, int number) { _name = name; _number = number; } public override string ToString() => $"{_name} {_number}"; public static implicit operator DictionaryKeyCast(string dictionaryKey) { var strings = dictionaryKey.Split(' '); return new(strings[0], Convert.ToInt32(strings[1])); } }
24.192308
75
0.656598
[ "MIT" ]
SimonCropp/Argon
src/Tests/TestObjects/DictionaryKeyCast.cs
629
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. using System; namespace Microsoft.VisualStudio.R.Sql.Publish { public sealed class SqlPublishException: Exception { public SqlPublishException(string message): base(message) { } } }
32.181818
91
0.751412
[ "MIT" ]
Bhaskers-Blu-Org2/RTVS
src/Windows/Sql/Impl/Publish/SqlPublishException.cs
356
C#