content
stringlengths
5
1.04M
avg_line_length
float64
1.75
12.9k
max_line_length
int64
2
244k
alphanum_fraction
float64
0
0.98
licenses
list
repository_name
stringlengths
7
92
path
stringlengths
3
249
size
int64
5
1.04M
lang
stringclasses
2 values
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ObjectValidator { public class Class1 { } }
14.153846
33
0.73913
[ "MIT" ]
ChaseWilliamson501/itse1430
Labs/ContactManager.UI/ObjectValidator/Class1.cs
186
C#
using UnityEngine; using System.Collections; public class MouseLock : MonoBehaviour { // Use this for initialization void Start () { } // Update is called once per frame void Update () { #if UNITY_4_1 || UNITY_4_2 || UNITY_4_3 || UNITY_4_5 || UNITY_4_6 Screen.lockCursor = true; #else Cursor.visible = false; #endif } }
16.619048
66
0.670487
[ "MIT" ]
N1gthWind/FPS-Game-Tutorial
FPS Game/Assets/TheKiwiCode/assets/FPS Pack/Scripts/Demo/MouseLock.cs
351
C#
using System; using System.Collections.Generic; using System.Globalization; using System.Linq; namespace DesignPatterns_Proxy { class Program { //original source https://metanit.com/sharp/patterns/4.5.php static void Main(string[] args) { Console.WriteLine("Design Patterns - Proxy!"); ILibrary libraryRepository = new LibraryRepositoryProxy(); libraryRepository.Get("War and Peace"); libraryRepository.Get("Bible"); libraryRepository.Get("American Tragedy"); } } class TownLibraryRepository : ILibrary { private List<Book> _townLibrary; public TownLibraryRepository() { _townLibrary = new List<Book>() { new Book("L.N. Tolstoy", "War and Peace"), new Book("F.M. Dostoevskiy", "Crime and Punishment") }; } public Book Get(string name) { IEnumerable<Book> bookList; bookList = _townLibrary.Where(book => book.Name == name); if (bookList.Any()) { Console.WriteLine($"Book {name} has been found in town library."); return bookList.First(); } return null; } } class StateLibraryRepository : ILibrary { private List<Book> _stateLibrary; public StateLibraryRepository() { _stateLibrary = new List<Book>() { new Book("", "Bible") }; } public Book Get(string name) { IEnumerable<Book> bookList; bookList = _stateLibrary.Where(book => book.Name == name); if (bookList.Any()) { Console.WriteLine($"Book {name} has been found in state library."); return bookList.First(); } return null; } } class LibraryRepositoryProxy : ILibrary { private StateLibraryRepository _stateLibrary; private TownLibraryRepository _townLibrary; public LibraryRepositoryProxy() { _stateLibrary = new StateLibraryRepository(); _townLibrary = new TownLibraryRepository(); } public Book Get(string name) { Book book; book = _townLibrary.Get(name); if (book != null) { return book; } else { book = _stateLibrary.Get(name); if (book != null) { return book; } else { Console.WriteLine($"Book {name} has not been found"); return null; } } } } public interface ILibrary { Book Get(string name); } public class Book { public Book(string author, string name) { Author = author; Name = name; } public string Author { get; set; } public string Name { get; set; } } }
24.960938
83
0.492958
[ "MIT" ]
miroshkin/design-patterns-proxy
DesignPatterns_Proxy/DesignPatterns_Proxy/Program.cs
3,197
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace HyperStrings { class Program { static void Main(string[] args) { var line = Console.ReadLine().Split().Select(x => int.Parse(x)).ToArray(); var n = line[0]; var m = line[1]; var superStrings = new string[n]; for (int i = 0; i < n; i++) { superStrings[i] = Console.ReadLine(); } var memoization = new long[m + 1]; long result = dynamicFunction(m, superStrings, memoization); // for empty string result++; Console.WriteLine(result); } private static long dynamicFunction(int m, string[] superStrings, long[] memoization) { if (m <= 0) { return 0; } if (memoization[m] > 0) { return memoization[m]; } long result = 0; for (int i = 0; i < superStrings.Length; i++) { var currentString = superStrings[i]; if (currentString.Length <= m) { result++; result += dynamicFunction(m - currentString.Length, superStrings, memoization); } } memoization[m] = result % 1000000007; return memoization[m]; } } }
23.861538
99
0.462282
[ "MIT" ]
GeorgiMateev/hacker-rank-charp
HyperStrings/Program.cs
1,553
C#
using System; namespace NetCore.BatchCRUD.Infrastructures.Models { public class BaseModel { public int Id { get; set; } public DateTime CreatedOn { get; set; } public DateTime UpdatedOn { get; set; } } }
20.166667
50
0.628099
[ "MIT" ]
dangtathanh/demo-batch-crud
src/NetCore.BatchCRUD/Infrastructures/Models/BaseModel.cs
244
C#
using System; using System.Collections.Generic; using System.Text; using Newtonsoft.Json; namespace NginxConfTransformer { public static class ConfigProcessor { public static NgxResponse Merge(ref NgxResponse original) { var merged = new NgxResponse(); merged.Status = original.Status; merged.Config.Add(original.Config[0]); for (int i = 0; i < merged.Config[0].Parsed.Count; i++) { NgxDirective directive = merged.Config[0].Parsed[i]; ExpandIncludes(ref directive, ref original); } return merged; } private static void ExpandIncludes(ref NgxDirective directive, ref NgxResponse response) { if (directive.Block == null) { return; } for (int i = 0; i < directive.Block.Count; i++) { NgxDirective childDirective = directive.Block[i]; if (childDirective.Directive == "include") { Console.WriteLine($"Find \"include\" directive in {directive.Directive}"); directive.Block.RemoveAt(i); List<int> configRefList = childDirective.Includes; for (int j = 0; j < configRefList.Count; j++) { int index = configRefList[j]; NgxConfig config = response.Config[index]; Console.WriteLine($"Include {config.File}"); foreach (NgxDirective includedDirective in config.Parsed) { directive.Block.Add(includedDirective); } } } ExpandIncludes(ref childDirective, ref response); } } } }
31.790323
97
0.48554
[ "MIT" ]
bangbingsyb/NginxConfigTransformer
src/ConfigProcessor.cs
1,973
C#
// Copyright 2008 Louis DeJardin - http://whereslou.com // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // using System; using System.Collections.Generic; using System.Web.Mvc; using System.Web.Routing; using Spark; using Spark.Web.Mvc; using Spark.Web.Mvc.Descriptors; namespace AdvancedPartials { public class Application { public void RegisterViewEngine(ICollection<IViewEngine> engines) { SparkEngineStarter.RegisterViewEngine(engines); } public void RegisterRoutes(ICollection<RouteBase> routes) { routes.Add(new Route("{controller}/{action}/{id}", new MvcRouteHandler()) { Defaults = new RouteValueDictionary(new { controller = "Home", action = "Index", id = "" }), }); } } }
34.825
120
0.646088
[ "Apache-2.0" ]
RobertTheGrey/spark
src/Samples/AspNetMvc/AdvancedPartials/Application.cs
1,393
C#
namespace _02.MakeSelectWithToList { using System; using System.Diagnostics; using System.Linq; using _01.SelectEmployeesFromTelerikAcademy; public class Program { public static void Main(string[] args) { var context = new TelerikAcademyEntities(); var sw = new Stopwatch(); sw.Start(); var employeesInSofiaWithList = context.Employees .ToList() .Select(e => e.Address) .ToList() .Select(a => a.Town) .ToList() .Where(t => t.Name == "Sofia").Count(); Console.WriteLine(employeesInSofiaWithList); sw.Stop(); Console.WriteLine(sw.Elapsed); sw.Reset(); sw.Start(); //This makes a single query with joins. var fasterEmployeesInSofia = context.Employees.Where(e => e.Address.Town.Name == "Sofia").Count(); Console.WriteLine(fasterEmployeesInSofia); sw.Stop(); Console.WriteLine(sw.Elapsed); } } }
30.146341
110
0.480583
[ "Apache-2.0" ]
iliantrifonov/TelerikAcademy
Databases/9.EntityFrameworkPerformance/02.MakeSelectWithToList/Program.cs
1,238
C#
using System; namespace GitDeployPack.Model { [Flags] public enum VsProjectType { Undefined = 0, Web = 1, Console = 2, Service = 4, ClassLibrary = 8, Deployment = 16, Database = 32, Test = 64, WindowsApplication = 128, NetCore = 256 } }
17.578947
33
0.502994
[ "Apache-2.0" ]
alivehim/GitDeployPack
src/GitDeployPack.Core/Model/VsProjectType.cs
336
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("2.MessagesInABottle")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("2.MessagesInABottle")] [assembly: AssemblyCopyright("Copyright © 2013")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("37666645-9226-4a38-8eac-3a7fd779cd91")] // 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.135135
84
0.746279
[ "MIT" ]
Ico093/TelerikAcademy
C#2/Exams/C#Part2-7-February-2012/TelerikAcademyExam2@7Feb2012/2.MessagesInABottle/Properties/AssemblyInfo.cs
1,414
C#
using System; using System.Collections.Generic; using System.Threading.Tasks; using Uber.Module.Search.Abstraction.Model; namespace Uber.Module.Search.Abstraction.Store { public interface ISearchItemTargetStore { Task<List<SearchItemTarget>> Find(Guid searchItemKey); Task<List<SearchItemTarget>> Find(IEnumerable<Guid> searchItemKeys); Task Insert(IEnumerable<SearchItemTarget> searchItem); } }
27.1875
76
0.756322
[ "MIT" ]
uber-asido/backend
src/Uber.Module.Search.Abstraction/Store/ISearchItemTargetStore.cs
437
C#
namespace System.DirectoryServices { /// <summary> /// WellKnownDN /// </summary> public enum WellKnownDN { /// <summary> /// RootDSE /// </summary> RootDSE, /// <summary> /// DefaultNamingContext /// </summary> DefaultNamingContext, /// <summary> /// SchemaNamingContext /// </summary> SchemaNamingContext, /// <summary> /// ConfigurationNamingContext /// </summary> ConfigurationNamingContext, /// <summary> /// PartitionsContainer /// </summary> PartitionsContainer, /// <summary> /// SitesContainer /// </summary> SitesContainer, /// <summary> /// SystemContainer /// </summary> SystemContainer, /// <summary> /// RidManager /// </summary> RidManager, /// <summary> /// Infrastructure /// </summary> Infrastructure, /// <summary> /// RootDomainNamingContext /// </summary> RootDomainNamingContext, /// <summary> /// Schema /// </summary> Schema } }
24.169811
39
0.45121
[ "MIT" ]
BclEx/BclEx-Extend
src/System.DirectoryServicesEx/DirectoryServices/WellKnownDN.cs
1,283
C#
/******************************************************************************/ /* This source, or parts thereof, may be used in any software as long the */ /* license of NostalgicPlayer is keep. See the LICENSE file for more */ /* information. */ /* */ /* Copyright (C) 2021 by Polycode / NostalgicPlayer team. */ /* All rights reserved. */ /******************************************************************************/ using System; using Polycode.NostalgicPlayer.Kit.Interfaces; namespace Polycode.NostalgicPlayer.Kit.Containers { /// <summary> /// Holds information about a single format/type in an agent /// </summary> public class AgentInfo { /********************************************************************/ /// <summary> /// Constructor /// </summary> /********************************************************************/ public AgentInfo(IAgent agent, string typeName, string typeDescription, Version version, Guid typeId, bool hasSettings, bool hasDisplay) { Agent = agent; AgentId = agent.AgentId; AgentName = agent.Name; AgentDescription = agent.Description; TypeName = typeName; TypeDescription = typeDescription; Version = version; TypeId = typeId; HasSettings = hasSettings; HasDisplay = hasDisplay; } /********************************************************************/ /// <summary> /// Holds the agent instance /// </summary> /********************************************************************/ public IAgent Agent { get; set; } /********************************************************************/ /// <summary> /// Holds the ID of the agent /// </summary> /********************************************************************/ public Guid AgentId { get; } /********************************************************************/ /// <summary> /// Holds the name of the agent /// </summary> /********************************************************************/ public string AgentName { get; } /********************************************************************/ /// <summary> /// Holds the description of the agent /// </summary> /********************************************************************/ public string AgentDescription { get; } /********************************************************************/ /// <summary> /// Holds the name of the format/type /// </summary> /********************************************************************/ public string TypeName { get; } /********************************************************************/ /// <summary> /// Holds the description of the format/type /// </summary> /********************************************************************/ public string TypeDescription { get; } /********************************************************************/ /// <summary> /// Holds the version of the agent /// </summary> /********************************************************************/ public Version Version { get; } /********************************************************************/ /// <summary> /// Holds the ID of the format/type /// </summary> /********************************************************************/ public Guid TypeId { get; } /********************************************************************/ /// <summary> /// Indicate if the agent has its own settings /// </summary> /********************************************************************/ public bool HasSettings { get; } /********************************************************************/ /// <summary> /// Indicate if the agent has some display window /// </summary> /********************************************************************/ public bool HasDisplay { get; } /********************************************************************/ /// <summary> /// Indicate if this type is enabled or disabled /// </summary> /********************************************************************/ public bool Enabled { get; set; } = true; } }
26.5
139
0.308827
[ "Apache-2.0" ]
neumatho/NostalgicPlayer
Source/NostalgicPlayerKit/Containers/AgentInfo.cs
4,613
C#
using System; namespace MediatR.CommandQuery.Definitions { public interface ITrackHistory { DateTime PeriodStart { get; set; } DateTime PeriodEnd { get; set; } } }
17.636364
42
0.649485
[ "MIT" ]
loresoft/MediatR.CommandQuery
src/MediatR.CommandQuery/Definitions/ITrackHistory.cs
196
C#
using Locust.Caching; using System; using System.Threading.Tasks; using Locust.Model; using Locust.ServiceModel; using Locust.ServiceModel.Babbage; using Locust.Modules.Api.Model; namespace Locust.Modules.Api.Strategies { public partial class ApiClientIPAddStrategy : ApiClientIPAddStrategyBase { public ApiClientIPAddStrategy() { Init(); } public override void Run(ApiClientIPAddContext context) { ExecuteNonQuery(context, ctx => ctx.Request.ApiClientId.ToString()); context.Response.Data = new {context.Request.ApiClientId, context.Request.IP}; // ExecuteNonQuery(context, Func<ApiClientIPAddRequest, string> keySpecifier); } public override async Task RunAsync(ApiClientIPAddContext context) { await ExecuteNonQueryAsync(context, ctx => ctx.Request.ApiClientId.ToString()); context.Response.Data = new { context.Request.ApiClientId, context.Request.IP }; // return ExecuteNonQueryAsync(context, Func<ApiClientIPAddRequest, string> keySpecifier); } } }
33.46875
102
0.723623
[ "MIT" ]
mansoor-omrani/Locust.NET
Modules/Locust.Modules.Api/Service/ApiClientIP/Add/Strategy.cs
1,071
C#
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Configuration; namespace OfficeOAuth { public static class SettingsHelper { public static string ClientID { get { return ConfigurationManager.AppSettings["ida:ClientID"]; } } public static string ClientSecret { get { return ConfigurationManager.AppSettings["ida:ClientSecret"]; } } public static string AADInstance { get { return ConfigurationManager.AppSettings["ida:AADInstance"]; } } public static string TenantId { get { return ConfigurationManager.AppSettings["ida:TenantId"]; } } public static string Authority { get { return AADInstance + TenantId; } } } }
23.243243
80
0.605814
[ "MIT" ]
OfficeDev/TrainingContent-Archive
O3652/O3652-7 Deep Dive into Security and OAuth/Completed Projects/Exercise02/OfficeOAuth/OfficeOAuth/SettingsHelper.cs
862
C#
using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; using GraphQL.Language.AST; using GraphQL.Types; using Microsoft.EntityFrameworkCore; class IncludeAppender { Dictionary<Type, List<Navigation>> navigations; public IncludeAppender(Dictionary<Type, List<Navigation>> navigations) { this.navigations = navigations; } public IQueryable<TItem> AddIncludes<TItem, TSource>(IQueryable<TItem> query, ResolveFieldContext<TSource> context) where TItem : class { var type = typeof(TItem); var navigationProperty = navigations[type]; return AddIncludes(query, context.FieldDefinition, context.SubFields.Values, navigationProperty); } IQueryable<T> AddIncludes<T>(IQueryable<T> query, FieldType fieldType, ICollection<Field> subFields, List<Navigation> navigationProperties) where T : class { var paths = GetPaths(fieldType, subFields, navigationProperties); foreach (var path in paths) { query = query.Include(path); } return query; } List<string> GetPaths(FieldType fieldType, ICollection<Field> fields, List<Navigation> navigationProperty) { var list = new List<string>(); var complexGraph = fieldType.GetComplexGraph(); ProcessSubFields(list, null, fields, complexGraph, navigationProperty); return list; } void AddField(List<string> list, Field field, string? parentPath, FieldType fieldType, List<Navigation> parentNavigationProperties) { if (!fieldType.TryGetComplexGraph(out var complexGraph)) { return; } var subFields = field.SelectionSet.Selections.OfType<Field>().ToList(); if (IsConnectionNode(field)) { if (subFields.Count > 0) { ProcessSubFields(list, parentPath, subFields, complexGraph!, parentNavigationProperties); } return; } if (!fieldType.TryGetEntityTypeForField(out var entityType)) { return; } if (!TryGetIncludeMetadata(fieldType, out var includeNames)) { return; } //todo: do a single check to avoid allocations var paths = GetPaths(parentPath, includeNames).ToList(); foreach (var path in paths) { list.Add(path); } ProcessSubFields(list, paths.First(), subFields, complexGraph!, navigations[entityType!]); } static IEnumerable<string> GetPaths(string? parentPath, string[] includeNames) { if (parentPath == null) { return includeNames; } return includeNames.Select(includeName => $"{parentPath}.{includeName}"); } void ProcessSubFields(List<string> list, string? parentPath, ICollection<Field> subFields, IComplexGraphType complexGraph, List<Navigation> navigationProperties) { foreach (var subField in subFields) { var single = complexGraph.Fields.SingleOrDefault(x => x.Name == subField.Name); if (single != null) { AddField(list, subField, parentPath, single, navigationProperties); } } } static bool IsConnectionNode(Field field) { var name = field.Name.ToLowerInvariant(); return name == "edges" || name == "items" || name == "node"; } public static Dictionary<string, object> GetIncludeMetadata(string fieldName, IEnumerable<string>? includeNames) { var metadata = new Dictionary<string, object>(); SetIncludeMetadata(fieldName, includeNames, metadata); return metadata; } public static void SetIncludeMetadata(FieldType fieldType, string fieldName, IEnumerable<string>? includeNames) { SetIncludeMetadata(fieldName, includeNames, fieldType.Metadata); } static void SetIncludeMetadata(string fieldName, IEnumerable<string>? includeNames, IDictionary<string, object> metadata) { if (includeNames == null) { metadata["_EF_IncludeName"] = FieldNameToArray(fieldName); } else { metadata["_EF_IncludeName"] = includeNames.ToArray(); } } static string[] FieldNameToArray(string fieldName) { return new[] {char.ToUpperInvariant(fieldName[0]) + fieldName.Substring(1)}; } static bool TryGetIncludeMetadata(FieldType fieldType, [NotNullWhen(true)] out string[]? value) { if (fieldType.Metadata.TryGetValue("_EF_IncludeName", out var fieldNameObject)) { value = (string[]) fieldNameObject; return true; } value = null; return false; } }
31.437908
165
0.636175
[ "MIT" ]
andrejohansson/GraphQL.EntityFramework
src/GraphQL.EntityFramework/IncludeAppender.cs
4,812
C#
#region using MaxMind.Db; using Newtonsoft.Json; using System; #endregion namespace MaxMind.GeoIP2.Model { /// <summary> /// Contains data for the traits record associated with an IP address. /// </summary> public class Traits { /// <summary> /// Constructor /// </summary> public Traits() { } /// <summary> /// Constructor /// </summary> [Constructor] public Traits( [Parameter("autonomous_system_number")] long? autonomousSystemNumber = null, [Parameter("autonomous_system_organization")] string? autonomousSystemOrganization = null, [Parameter("connection_type")] string? connectionType = null, string? domain = null, [Inject("ip_address")] string? ipAddress = null, [Parameter("is_anonymous")] bool isAnonymous = false, [Parameter("is_anonymous_proxy")] bool isAnonymousProxy = false, [Parameter("is_anonymous_vpn")] bool isAnonymousVpn = false, [Parameter("is_hosting_provider")] bool isHostingProvider = false, [Parameter("is_legitimate_proxy")] bool isLegitimateProxy = false, [Parameter("is_public_proxy")] bool isPublicProxy = false, [Parameter("is_satellite_provider")] bool isSatelliteProvider = false, [Parameter("is_tor_exit_node")] bool isTorExitNode = false, string? isp = null, string? organization = null, [Parameter("user_type")] string? userType = null, [Network] Network? network = null, [Parameter("static_ip_score")] double? staticIPScore = null, [Parameter("user_count")] int? userCount = null ) { AutonomousSystemNumber = autonomousSystemNumber; AutonomousSystemOrganization = autonomousSystemOrganization; ConnectionType = connectionType; Domain = domain; IPAddress = ipAddress; IsAnonymous = isAnonymous; #pragma warning disable 618 IsAnonymousProxy = isAnonymousProxy; #pragma warning restore 618 IsAnonymousVpn = isAnonymousVpn; IsHostingProvider = isHostingProvider; IsLegitimateProxy = isLegitimateProxy; IsPublicProxy = isPublicProxy; #pragma warning disable 618 IsSatelliteProvider = isSatelliteProvider; #pragma warning restore 618 IsTorExitNode = isTorExitNode; Isp = isp; Network = network; Organization = organization; StaticIPScore = staticIPScore; UserCount = userCount; UserType = userType; } /// <summary> /// The /// <a /// href="http://en.wikipedia.org/wiki/Autonomous_system_(Internet)"> /// autonomous system number /// </a> /// associated with the IP address. /// This value is only set when using the City or Insights web /// service or the Enterprise database. /// </summary> [JsonProperty("autonomous_system_number")] public long? AutonomousSystemNumber { get; internal set; } /// <summary> /// The organization associated with the registered /// <a /// href="http://en.wikipedia.org/wiki/Autonomous_system_(Internet)"> /// autonomous system number /// </a> /// for the IP address. This value is only set when using the City or /// Insights web service or the Enterprise database. /// </summary> [JsonProperty("autonomous_system_organization")] public string? AutonomousSystemOrganization { get; internal set; } /// <summary> /// The connection type of the IP address. This value is only set when /// using the Enterprise database. /// </summary> [JsonProperty("connection_type")] public string? ConnectionType { get; internal set; } /// <summary> /// The second level domain associated with the IP address. This will /// be something like "example.com" or "example.co.uk", not /// "foo.example.com". This value is only set when using the City or /// Insights web service or the Enterprise database. /// </summary> [JsonProperty("domain")] public string? Domain { get; internal set; } /// <summary> /// The IP address that the data in the model is for. If you /// performed a "me" lookup against the web service, this will be the /// externally routable IP address for the system the code is running /// on. If the system is behind a NAT, this may differ from the IP /// address locally assigned to it. /// </summary> [JsonProperty("ip_address")] public string? IPAddress { get; internal set; } /// <summary> /// This is true if the IP address belongs to any sort of anonymous /// network. This value is only available from GeoIP2 Precision /// Insights. /// </summary> [JsonProperty("is_anonymous")] public bool IsAnonymous { get; internal set; } /// <summary> /// This is true if the IP is an anonymous proxy. See /// <a href="https://dev.maxmind.com/faq/geoip#anonproxy"> /// MaxMind's GeoIP /// FAQ /// </a> /// </summary> [JsonProperty("is_anonymous_proxy")] [Obsolete("Use our GeoIP2 Anonymous IP database instead.")] public bool IsAnonymousProxy { get; internal set; } /// <summary> /// This is true if the IP address is registered to an anonymous /// VPN provider. /// This value is only available from GeoIP2 Precision Insights. /// </summary> /// <remarks> /// If a VPN provider does not register subnets under names /// associated with them, we will likely only flag their IP ranges /// using the IsHostingProvider property. /// </remarks> [JsonProperty("is_anonymous_vpn")] public bool IsAnonymousVpn { get; internal set; } /// <summary> /// This is true if the IP address belongs to a hosting or VPN /// provider (see description of IsAnonymousVpn property). /// This value is only available from GeoIP2 Precision Insights. /// </summary> [JsonProperty("is_hosting_provider")] public bool IsHostingProvider { get; internal set; } /// <summary> /// True if MaxMind believes this IP address to be a legitimate /// proxy, such as an internal VPN used by a corporation. This is /// only available in the GeoIP2 Enterprise database. /// </summary> [JsonProperty("is_legitimate_proxy")] public bool IsLegitimateProxy { get; internal set; } /// <summary> /// This is true if the IP address belongs to a public proxy. /// This value is only available from GeoIP2 Precision Insights. /// </summary> [JsonProperty("is_public_proxy")] public bool IsPublicProxy { get; internal set; } /// <summary> /// This is true if the IP belong to a satellite Internet provider. /// </summary> [JsonProperty("is_satellite_provider")] [Obsolete("Due to increased mobile usage, we have insufficient data to maintain this field.")] public bool IsSatelliteProvider { get; internal set; } /// <summary> /// This is true if the IP address belongs to a Tor exit node. /// This value is only available from GeoIP2 Precision Insights. /// </summary> [JsonProperty("is_tor_exit_node")] public bool IsTorExitNode { get; internal set; } /// <summary> /// The name of the ISP associated with the IP address. This value /// is only set when using the City or Insights web service or the /// Enterprise database. /// </summary> [JsonProperty("isp")] public string? Isp { get; internal set; } /// <summary> /// The network associated with the record. In particular, this is /// the largest network where all of the fields besides /// <c>IPAddress</c> have the same value. /// </summary> [JsonProperty("network")] public Network? Network { get; internal set; } /// <summary> /// The name of the organization associated with the IP address. This /// value is only set when using the City or Insights web service or the /// Enterprise database. /// </summary> [JsonProperty("organization")] public string? Organization { get; internal set; } /// <summary> /// An indicator of how static or dynamic an IP address is. The value /// ranges from 0 to 99.99 with higher values meaning a greater static /// association. For example, many IP addresses with a <c>UserType</c> /// of <c>cellular</c> have a lifetime under one. Static Cable/DSL IPs /// typically have a lifetime above thirty. /// </summary> /// <remark> /// This indicator can be useful for deciding whether an IP address /// represents the same user over time. /// </remark> [JsonProperty("static_ip_score")] public double? StaticIPScore { get; internal set; } /// <summary> /// The estimated number of users sharing the IP/network during the past /// 24 hours. For IPv4, the count is for the individual IP. For IPv6, the /// count is for the /64 network. This value is only available from /// GeoIP2 Precision Insights. /// </summary> [JsonProperty("user_count")] public int? UserCount { get; internal set; } /// <summary> /// The user type associated with the IP address. This can be one of /// the following values: /// <list type="bullet"> /// <item> /// <description>business</description> /// </item> /// <item> /// <description>cafe</description> /// </item> /// <item> /// <description>cellular</description> /// </item> /// <item> /// <description>college</description> /// </item> /// <item> /// <description>content_delivery_network</description> /// </item> /// <item> /// <description>dialup</description> /// </item> /// <item> /// <description>government</description> /// </item> /// <item> /// <description>hosting</description> /// </item> /// <item> /// <description>library</description> /// </item> /// <item> /// <description>military</description> /// </item> /// <item> /// <description>residential</description> /// </item> /// <item> /// <description>router</description> /// </item> /// <item> /// <description>school</description> /// </item> /// <item> /// <description>search_engine_spider</description> /// </item> /// <item> /// <description>traveler</description> /// </item> /// </list> /// This value is only set when using the City or Insights web service /// or the Enterprise database. /// </summary> [JsonProperty("user_type")] public string? UserType { get; internal set; } /// <summary> /// Returns a <see cref="string" /> that represents this instance. /// </summary> /// <returns> /// A <see cref="string" /> that represents this instance. /// </returns> public override string ToString() { return $"{nameof(AutonomousSystemNumber)}: {AutonomousSystemNumber}, " + $"{nameof(AutonomousSystemOrganization)}: {AutonomousSystemOrganization}, " + $"{nameof(ConnectionType)}: {ConnectionType}, " + $"{nameof(Domain)}: {Domain}, " + $"{nameof(IPAddress)}: {IPAddress}, " + $"{nameof(IsAnonymous)}: {IsAnonymous}, " + #pragma warning disable 618 $"{nameof(IsAnonymousProxy)}: {IsAnonymousProxy}, " + #pragma warning restore 618 $"{nameof(IsAnonymousVpn)}: {IsAnonymousVpn}, " + $"{nameof(IsHostingProvider)}: {IsHostingProvider}, " + $"{nameof(IsLegitimateProxy)}: {IsLegitimateProxy}, " + $"{nameof(IsPublicProxy)}: {IsPublicProxy}, " + #pragma warning disable 618 $"{nameof(IsSatelliteProvider)}: {IsSatelliteProvider}, " + #pragma warning restore 618 $"{nameof(Isp)}: {Isp}, " + $"{nameof(Organization)}: {Organization}, " + $"{nameof(UserType)}: {UserType}"; } } }
42.229358
102
0.545369
[ "Apache-2.0" ]
lapakio/GeoIP2-dotnet
MaxMind.GeoIP2/Model/Traits.cs
13,811
C#
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.Allocation; using osu.Framework.Audio; using osu.Framework.Audio.Sample; using osu.Framework.Bindables; using osu.Game.Online.API.Requests.Responses; using osu.Game.Online.Multiplayer; namespace osu.Game.Screens.OnlinePlay.Multiplayer { public class MultiplayerRoomSounds : MultiplayerRoomComposite { private Sample hostChangedSample; private Sample userJoinedSample; private Sample userLeftSample; private Sample userKickedSample; [BackgroundDependencyLoader] private void load(AudioManager audio) { hostChangedSample = audio.Samples.Get(@"Multiplayer/host-changed"); userJoinedSample = audio.Samples.Get(@"Multiplayer/player-joined"); userLeftSample = audio.Samples.Get(@"Multiplayer/player-left"); userKickedSample = audio.Samples.Get(@"Multiplayer/player-kicked"); } protected override void LoadComplete() { base.LoadComplete(); Host.BindValueChanged(hostChanged); } protected override void UserJoined(MultiplayerRoomUser user) { base.UserJoined(user); Scheduler.AddOnce(() => userJoinedSample?.Play()); } protected override void UserLeft(MultiplayerRoomUser user) { base.UserLeft(user); Scheduler.AddOnce(() => userLeftSample?.Play()); } protected override void UserKicked(MultiplayerRoomUser user) { base.UserKicked(user); Scheduler.AddOnce(() => userKickedSample?.Play()); } private void hostChanged(ValueChangedEvent<APIUser> value) { // only play sound when the host changes from an already-existing host. if (value.OldValue == null) return; Scheduler.AddOnce(() => hostChangedSample?.Play()); } } }
32.30303
84
0.625235
[ "MIT" ]
Awesome-Of-the-Internet/osu
osu.Game/Screens/OnlinePlay/Multiplayer/MultiplayerRoomSounds.cs
2,067
C#
namespace SoftUni.Models { using System; using System.Collections.Generic; public class Project { public Project() { this.EmployeesProjects = new HashSet<EmployeeProject>(); } public int ProjectId { get; set; } public string Name { get; set; } public string Description { get; set; } public DateTime StartDate { get; set; } public DateTime? EndDate { get; set; } public ICollection<EmployeeProject> EmployeesProjects { get; set; } } }
21.076923
75
0.593066
[ "MIT" ]
Ivelin153/SoftUni
C# DB/C# DB Advanced/IntroEfCore_DbFirst/Models/Project.cs
550
C#
namespace VMS.ClassUtility { public class AnnualReportFileAttr { string fileName; string ext; string newFileName; string path; string absPath; public string FileName { get { return fileName; } set { fileName = value; } } public string Ext { get { return ext; } set { ext = value; } } public string NewFileName { get { return newFileName; } set { newFileName = value; } } public string Path { get { return path; } set { path = value; } } public string AbsPath { get { return absPath; } set { absPath = value; } } } }
16.861111
37
0.298188
[ "MIT" ]
rogermadhu/VMS
VMS/ClassUtility/AnnualReportFileAttr.cs
1,216
C#
using System; using Unity.Entities; using UnityEngine; namespace Improbable.Gdk.TransformSynchronization { [CreateAssetMenu(menuName = "SpatialOS/Transforms/Receive Strategies/Interpolation")] public class InterpolationReceiveStrategy : TransformSynchronizationReceiveStrategy { public int TargetBufferSize = TransformDefaults.InterpolationTargetBufferSize; public int MaxBufferSize = TransformDefaults.InterpolationMaxBufferSize; internal override void Apply(Entity entity, World world, EntityCommandBuffer commandBuffer) { if (MaxBufferSize < TargetBufferSize) { throw new InvalidOperationException( $"In {name} the Max Buffer Size must be larger than the Target Buffer Size"); } commandBuffer.AddSharedComponent(entity, new InterpolationConfig { TargetBufferSize = TargetBufferSize, MaxLoadMatchedBufferSize = MaxBufferSize }); } internal override void Remove(Entity entity, World world, EntityCommandBuffer commandBuffer) { commandBuffer.RemoveComponent<InterpolationConfig>(entity); } } }
36.176471
100
0.681301
[ "MIT" ]
456-Ritwik/gdk-for-unity
workers/unity/Packages/io.improbable.gdk.transformsynchronization/ScriptableObjects/ReceiveStrategies/InterpolationReceiveStrategy.cs
1,230
C#
/* * Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the snowball-2016-06-30.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.Snowball.Model { /// <summary> /// Container for the parameters to the CreateCluster operation. /// Creates an empty cluster. Each cluster supports five nodes. You use the <a>CreateJob</a> /// action separately to create the jobs for each of these nodes. The cluster does not /// ship until these five node jobs have been created. /// </summary> public partial class CreateClusterRequest : AmazonSnowballRequest { private string _addressId; private string _description; private string _forwardingAddressId; private JobType _jobType; private string _kmsKeyARN; private Notification _notification; private JobResource _resources; private string _roleARN; private ShippingOption _shippingOption; private SnowballType _snowballType; private TaxDocuments _taxDocuments; /// <summary> /// Gets and sets the property AddressId. /// <para> /// The ID for the address that you want the cluster shipped to. /// </para> /// </summary> [AWSProperty(Required=true, Min=40, Max=40)] public string AddressId { get { return this._addressId; } set { this._addressId = value; } } // Check to see if AddressId property is set internal bool IsSetAddressId() { return this._addressId != null; } /// <summary> /// Gets and sets the property Description. /// <para> /// An optional description of this specific cluster, for example <code>Environmental /// Data Cluster-01</code>. /// </para> /// </summary> [AWSProperty(Min=1)] public string Description { get { return this._description; } set { this._description = value; } } // Check to see if Description property is set internal bool IsSetDescription() { return this._description != null; } /// <summary> /// Gets and sets the property ForwardingAddressId. /// <para> /// The forwarding address ID for a cluster. This field is not supported in most regions. /// </para> /// </summary> [AWSProperty(Min=40, Max=40)] public string ForwardingAddressId { get { return this._forwardingAddressId; } set { this._forwardingAddressId = value; } } // Check to see if ForwardingAddressId property is set internal bool IsSetForwardingAddressId() { return this._forwardingAddressId != null; } /// <summary> /// Gets and sets the property JobType. /// <para> /// The type of job for this cluster. Currently, the only job type supported for clusters /// is <code>LOCAL_USE</code>. /// </para> /// </summary> [AWSProperty(Required=true)] public JobType JobType { get { return this._jobType; } set { this._jobType = value; } } // Check to see if JobType property is set internal bool IsSetJobType() { return this._jobType != null; } /// <summary> /// Gets and sets the property KmsKeyARN. /// <para> /// The <code>KmsKeyARN</code> value that you want to associate with this cluster. <code>KmsKeyARN</code> /// values are created by using the <a href="https://docs.aws.amazon.com/kms/latest/APIReference/API_CreateKey.html">CreateKey</a> /// API action in AWS Key Management Service (AWS KMS). /// </para> /// </summary> [AWSProperty(Max=255)] public string KmsKeyARN { get { return this._kmsKeyARN; } set { this._kmsKeyARN = value; } } // Check to see if KmsKeyARN property is set internal bool IsSetKmsKeyARN() { return this._kmsKeyARN != null; } /// <summary> /// Gets and sets the property Notification. /// <para> /// The Amazon Simple Notification Service (Amazon SNS) notification settings for this /// cluster. /// </para> /// </summary> public Notification Notification { get { return this._notification; } set { this._notification = value; } } // Check to see if Notification property is set internal bool IsSetNotification() { return this._notification != null; } /// <summary> /// Gets and sets the property Resources. /// <para> /// The resources associated with the cluster job. These resources include Amazon S3 buckets /// and optional AWS Lambda functions written in the Python language. /// </para> /// </summary> [AWSProperty(Required=true)] public JobResource Resources { get { return this._resources; } set { this._resources = value; } } // Check to see if Resources property is set internal bool IsSetResources() { return this._resources != null; } /// <summary> /// Gets and sets the property RoleARN. /// <para> /// The <code>RoleARN</code> that you want to associate with this cluster. <code>RoleArn</code> /// values are created by using the <a href="https://docs.aws.amazon.com/IAM/latest/APIReference/API_CreateRole.html">CreateRole</a> /// API action in AWS Identity and Access Management (IAM). /// </para> /// </summary> [AWSProperty(Required=true, Max=255)] public string RoleARN { get { return this._roleARN; } set { this._roleARN = value; } } // Check to see if RoleARN property is set internal bool IsSetRoleARN() { return this._roleARN != null; } /// <summary> /// Gets and sets the property ShippingOption. /// <para> /// The shipping speed for each node in this cluster. This speed doesn't dictate how soon /// you'll get each Snowball Edge device, rather it represents how quickly each device /// moves to its destination while in transit. Regional shipping speeds are as follows: /// </para> /// <ul> <li> /// <para> /// In Australia, you have access to express shipping. Typically, devices shipped express /// are delivered in about a day. /// </para> /// </li> <li> /// <para> /// In the European Union (EU), you have access to express shipping. Typically, Snowball /// Edges shipped express are delivered in about a day. In addition, most countries in /// the EU have access to standard shipping, which typically takes less than a week, one /// way. /// </para> /// </li> <li> /// <para> /// In India, Snowball Edges are delivered in one to seven days. /// </para> /// </li> <li> /// <para> /// In the US, you have access to one-day shipping and two-day shipping. /// </para> /// </li> </ul> /// </summary> [AWSProperty(Required=true)] public ShippingOption ShippingOption { get { return this._shippingOption; } set { this._shippingOption = value; } } // Check to see if ShippingOption property is set internal bool IsSetShippingOption() { return this._shippingOption != null; } /// <summary> /// Gets and sets the property SnowballType. /// <para> /// The type of AWS Snowball device to use for this cluster. Currently, the only supported /// device type for cluster jobs is <code>EDGE</code>. /// </para> /// /// <para> /// For more information, see <a href="https://docs.aws.amazon.com/snowball/latest/developer-guide/device-differences.html">Snowball /// Edge Device Options</a> in the Snowball Edge Developer Guide. /// </para> /// </summary> public SnowballType SnowballType { get { return this._snowballType; } set { this._snowballType = value; } } // Check to see if SnowballType property is set internal bool IsSetSnowballType() { return this._snowballType != null; } /// <summary> /// Gets and sets the property TaxDocuments. /// <para> /// The tax documents required in your AWS Region. /// </para> /// </summary> public TaxDocuments TaxDocuments { get { return this._taxDocuments; } set { this._taxDocuments = value; } } // Check to see if TaxDocuments property is set internal bool IsSetTaxDocuments() { return this._taxDocuments != null; } } }
34.268707
140
0.574591
[ "Apache-2.0" ]
NGL321/aws-sdk-net
sdk/src/Services/Snowball/Generated/Model/CreateClusterRequest.cs
10,075
C#
using System; using System.Reflection; using Jasper.Http.Model; using LamarCodeGeneration.Frames; using LamarCodeGeneration.Model; namespace Jasper.Http.ContentHandling { public class UseReader : MethodCall { public UseReader(RouteChain chain, bool isLocal) : base(typeof(IRequestReader), selectMethod(chain.InputType)) { if (isLocal) { Target = new Variable(typeof(IRequestReader), nameof(RouteHandler.Reader)); } creates.Add(ReturnVariable); } private static MethodInfo selectMethod(Type inputType) { return typeof(IRequestReader) .GetMethod(nameof(IRequestReader.ReadFromRequest)) .MakeGenericMethod(inputType); } } }
26.833333
91
0.626087
[ "MIT" ]
JasperFx/jasper
src/Jasper.Http/ContentHandling/UseReader.cs
807
C#
namespace JLibrary.PortableExecutable { using System; using System.Runtime.InteropServices; [Serializable, StructLayout(LayoutKind.Sequential)] public struct IMAGE_THUNK_DATA { public U1 u1; } }
17.692308
55
0.7
[ "MIT" ]
4cc3ssD3n13d/CheatsTurkeyX-UI
CTXUI/Others/JLibrary/PortableExecutable/IMAGE_THUNK_DATA.cs
232
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.Events; public class Interactuable1: MonoBehaviour { [Header("Sobre las animaciones al activarse")] [SerializeField] #pragma warning disable 0649 private Animator clickAnimator; #pragma warning restore 0649 public string clickAnimation; [Header("Acciones que realizará")] [SerializeField] protected UnityEvent AccionAlInteractuar_ = new UnityEvent(); public void ActivarAccion() { if (clickAnimator != null) clickAnimator.Play(clickAnimation); AccionAlInteractuar_.Invoke(); } }
23.777778
70
0.732087
[ "MIT" ]
HexStar27/cse-investigaciones
SQL game/Assets/Scripts/Botones/Interactuable1.cs
645
C#
/* *************************************************************************** * This file is part of SharpNEAT - Evolution of Neural Networks. * * Copyright 2004-2016 Colin Green (sharpneat@gmail.com) * * SharpNEAT is free software; you can redistribute it and/or modify * it under the terms of The MIT License (MIT). * * You should have received a copy of the MIT License * along with SharpNEAT; if not, see https://opensource.org/licenses/MIT. */ using Redzen.Random; namespace SharpNeat.Network { /// <summary> /// y = max(-1, x). /// i.e. a rectified linear activation unit (ReLU) variant. /// </summary> public sealed class MaxMinusOne : IActivationFunction { /// <summary> /// Default instance provided as a public static field. /// </summary> public static readonly IActivationFunction __DefaultInstance = new MaxMinusOne(); public string FunctionId => this.GetType().Name; public string FunctionString => "y = max(-1, x)"; public string FunctionDescription => "A variant of Shifted Rectified Linear Unit (ReLU)."; public bool AcceptsAuxArgs => false; public double Calculate(double x, double[] auxArgs) { double y; if (x > -1) { y = x; } else { y = -1; } return y; } public float Calculate(float x, float[] auxArgs) { float y; if (x > -1) { y = x; } else { y = -1; } return y; } public double[] GetRandomAuxArgs(IRandomSource rng, double connectionWeightRange) { throw new SharpNeatException("GetRandomAuxArgs() called on activation function that does not use auxiliary arguments."); } public void MutateAuxArgs(double[] auxArgs, IRandomSource rng, double connectionWeightRange) { throw new SharpNeatException("MutateAuxArgs() called on activation function that does not use auxiliary arguments."); } } }
31.338235
132
0.564054
[ "MIT" ]
235u/proposals
SharpNeatSerialization/SharpNeatLib/Network/ActivationFunctions/Unipolar/MaxMinusOne.cs
2,133
C#
// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. namespace ICSharpCode.AvalonEdit.Document { /// <summary> /// This Interface describes a the basic Undo/Redo operation /// all Undo Operations must implement this interface. /// </summary> public interface IUndoableOperation { /// <summary> /// Undo the last operation /// </summary> void Undo(); /// <summary> /// Redo the last operation /// </summary> void Redo(); } interface IUndoableOperationWithContext : IUndoableOperation { void Undo(UndoStack stack); void Redo(UndoStack stack); } }
37.772727
93
0.744284
[ "MIT" ]
Acorisoft/AvalonEdit
ICSharpCode.AvalonEdit/Document/IUndoableOperation.cs
1,664
C#
using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using System.Threading.Tasks.Dataflow; namespace CParser.Helpers { public class AsyncStreamBlock<TInput, TOutput> : IPropagatorBlock<TInput, TOutput> { // This block's input buffer protected BufferBlock<TInput> TargetBlock { get; } // This block's output buffer protected BufferBlock<TOutput> SourceBlock { get; } protected CancellationToken CancellationToken { get; } protected TInput Sentinel { get; } protected AsyncStreamFunc<TInput, TOutput> Function { get; } public AsyncStreamBlock(AsyncStreamFunc<TInput, TOutput> function, TInput sentinel = default(TInput), CancellationToken cancellation = default) { Function = function; TargetBlock = new BufferBlock<TInput>(); SourceBlock = new BufferBlock<TOutput>(); CancellationToken = cancellation; Sentinel = sentinel; Completion = SourceBlock .PostAllAsync( Function(TargetBlock.ToStream(Sentinel)), CancellationToken).ContinueWith(_ => SourceBlock.Complete()); } public Task Completion { get; } public void Complete() { TargetBlock.Complete(); } public TOutput ConsumeMessage(DataflowMessageHeader messageHeader, ITargetBlock<TOutput> target, out bool messageConsumed) { return (SourceBlock as ISourceBlock<TOutput>)! .ConsumeMessage(messageHeader, target, out messageConsumed); } public void Fault(Exception exception) { (TargetBlock as ITargetBlock<TInput>).Fault(exception); } public IDisposable LinkTo(ITargetBlock<TOutput> target, DataflowLinkOptions linkOptions) { return SourceBlock.LinkTo(target, linkOptions); } public DataflowMessageStatus OfferMessage(DataflowMessageHeader messageHeader, TInput messageValue, ISourceBlock<TInput> source, bool consumeToAccept) { return (TargetBlock as ITargetBlock<TInput>)! .OfferMessage(messageHeader, messageValue, source, consumeToAccept); } public void ReleaseReservation(DataflowMessageHeader messageHeader, ITargetBlock<TOutput> target) { (SourceBlock as ISourceBlock<TOutput>)! .ReleaseReservation(messageHeader, target); } public bool ReserveMessage(DataflowMessageHeader messageHeader, ITargetBlock<TOutput> target) { return (SourceBlock as ISourceBlock<TOutput>) .ReserveMessage(messageHeader, target); } } }
37.986301
158
0.652001
[ "MIT" ]
joshwyant/cscc
CParser/Helpers/AsyncStreamBlock.cs
2,773
C#
using System; using System.Collections.Generic; using System.Globalization; using System.Text; using System.Windows; using System.Windows.Data; using System.Windows.Markup; namespace VRCEventUtil.Converters { class BoolToVisibilityConverter : MarkupExtension, IValueConverter { /// <summary> /// Trueの時のVisibilityの値 /// </summary> public Visibility TrueVisibility { get; set; } = Visibility.Visible; /// <summary> /// Falseの時のVisibilityの値 /// </summary> public Visibility FalseVisibility { get; set; } = Visibility.Hidden; /// <summary> /// bool値を反転してから変換するか /// </summary> public bool Invert { get; set; } = false; public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { if (value is bool bVal) { return (bVal ^ Invert) ? TrueVisibility : FalseVisibility; } else { throw new NotImplementedException(); } } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); } public override object ProvideValue(IServiceProvider serviceProvider) { return this; } } }
27.215686
103
0.59366
[ "MIT" ]
rioil/VRCEventUtil
VRCEventUtil/Converters/BoolToVisibilityConverter.cs
1,436
C#
// ------------------------------------------------------------------------------------------------- // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License (MIT). See LICENSE in the repo root for license information. // ------------------------------------------------------------------------------------------------- using System; using System.Linq; using EnsureThat; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Diagnostics.HealthChecks; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; namespace Microsoft.Health.Api.Features.HealthChecks { public class HealthCheckConfiguration : IPostConfigureOptions<HealthCheckServiceOptions> { private readonly IServiceProvider _serviceProvider; public HealthCheckConfiguration(IServiceProvider serviceProvider) { EnsureArg.IsNotNull(serviceProvider, nameof(serviceProvider)); _serviceProvider = serviceProvider; } public void PostConfigure(string name, HealthCheckServiceOptions options) { HealthCheckRegistration[] list = options.Registrations.ToArray(); options.Registrations.Clear(); var logger = _serviceProvider.GetRequiredService<ILogger<CachedHealthCheck>>(); foreach (HealthCheckRegistration registration in list) { // Wrap health checks with a caching wrapper. var newRegistration = new HealthCheckRegistration( registration.Name, new CachedHealthCheck(_serviceProvider, registration.Factory, logger), registration.FailureStatus, registration.Tags); options.Registrations.Add(newRegistration); } } } }
37.714286
101
0.61039
[ "MIT" ]
KnicKnic/healthcare-shared-components
src/Microsoft.Health.Api/Features/HealthChecks/HealthCheckConfiguration.cs
1,850
C#
using System; using System.Collections.Generic; using System.Text; using System.IO; namespace AutomatasII { class Lexico : Token, IDisposable { private StreamReader archivo; protected StreamWriter bitacora; string nombreArchivo; protected int linea, caracter; const int F = -1; const int E = -2; int[,] trand = { // WS,EF, L, D, ., +, -, E, =, :, ;, &, |, !, >, <, *, /, %, ", ', ?,La, {, },#10 { 0, F, 1, 2,29,17,18, 1, 8, 9,11,12,13,15,26,27,20,32,20,22,24,28,29,30,31, 0 },//0 { F, F, 1, 1, F, F, F, 1, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F },//1 { F, F, F, 2, 3, F, F, 5, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F },//2 { E, E, E, 4, E, E, E, E, E, E, E, E, E, E, E, E, E, E, E, E, E, E, E, E, E, E },//3 { F, F, F, 4, F, F, F, 5, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F },//4 { E, E, E, 7, E, 6, 6, E, E, E, E, E, E, E, E, E, E, E, E, E, E, E, E, E, E, E },//5 { E, E, E, 7, E, E, E, E, E, E, E, E, E, E, E, E, E, E, E, E, E, E, E, E, E, E },//6 { F, F, F, 7, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F },//7 { F, F, F, F, F, F, F, F,16, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F },//8 { F, F, F, F, F, F, F, F,10, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F },//9 { F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F },//10 { F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F },//11 { F, F, F, F, F, F, F, F, F, F, F,14, F, F, F, F, F, F, F, F, F, F, F, F, F, F },//12 { F, F, F, F, F, F, F, F, F, F, F, F,14, F, F, F, F, F, F, F, F, F, F, F, F, F },//13 { F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F },//14 { F, F, F, F, F, F, F, F,16, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F },//15 { F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F },//16 { F, F, F, F, F,19, F, F,19, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F },//17 { F, F, F, F, F, F,19, F,19, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F },//18 { F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F },//19 { F, F, F, F, F, F, F, F,21, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F },//20 { F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F },//21 { 22, E,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,23,22,22,22,22,22, E },//22 { F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F },//23 { 24, E,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,25,24,24,24,24, E },//24 { F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F },//25 { F, F, F, F, F, F, F, F,16, F, F, F, F, F, 36, F, F, F, F, F, F, F, F, F, F, F },//26 { F, F, F, F, F, F, F, F,16, F, F, F, F, F,16,37, F, F, F, F, F, F, F, F, F, F },//27 { F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F },//28 { F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F },//29 { F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F },//30 { F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F },//31 { F, F, F, F, F, F, F, F,21, F, F, F, F, F, F, F,34,33, F, F, F, F, F, F, F, F },//32 { 33, 0,33,33,33,33,33,33,33,33,33,33,33,33,33,33,33,33,33,33,33,33,33,33,33, 0 },//33 { 34, E,34,34,34,34,34,34,34,34,34,34,34,34,34,34,35,34,34,34,34,34,34,34,34,34 },//34 { 34, E,34,34,34,34,34,34,34,34,34,34,34,34,34,34,35, 0,34,34,34,34,34,34,34,34 },//35 { F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F },//36 { F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F },//37 //WS,EF, L, D, ., +, -, E, =, :, ;, &, |, !, >, <, *, /, %, ", ', ?,La, {, },#10 }; public Lexico() { linea = caracter = 1; nombreArchivo = "prueba.cpp"; Console.WriteLine("Compilando prueba.cpp"); Console.WriteLine("Iniciando analisis lexico."); if (File.Exists("C:\\Archivos\\prueba.cpp")) { archivo = new StreamReader("C:\\Archivos\\prueba.cpp"); bitacora = new StreamWriter("C:\\Archivos\\prueba.log"); bitacora.AutoFlush = true; DateTime fechaActual = DateTime.Now; bitacora.WriteLine("Archivo: prueba.cpp"); bitacora.WriteLine("Directorio: C:\\Archivos"); bitacora.WriteLine("Fecha: " + fechaActual); } else { throw new Exception("El archivo prueba.cpp no existe."); } } public Lexico(string nombre) { linea = caracter = 1; nombreArchivo = Path.GetFileName(nombre); string nombreDir = Path.GetDirectoryName(nombre); Console.WriteLine("Compilando " + nombreArchivo); Console.WriteLine("Iniciando analisis lexico."); if (Path.GetExtension(nombre) != ".cpp") { throw new Exception(String.Format("El archivo {0} no es un archivo cpp.", nombreArchivo)); } if (File.Exists(nombre)) { archivo = new StreamReader(nombre); string log = Path.ChangeExtension(nombre, "log"); bitacora = new StreamWriter(log); bitacora.AutoFlush = true; DateTime fechaActual = DateTime.Now; bitacora.WriteLine("Archivo: " + nombreArchivo); bitacora.WriteLine("Directorio: " + nombreDir); bitacora.WriteLine("Fecha: " + fechaActual); } else { string mensaje = String.Format("El archivo {0} no existe.", nombreArchivo); throw new Exception(mensaje); } } //~Lexico() public void Dispose() { Console.WriteLine(""); Console.WriteLine("Finaliza compilacion de " + nombreArchivo); CerrarArchivos(); } private void CerrarArchivos() { archivo.Close(); bitacora.Close(); } protected void NextToken() { char transicion; string palabra = ""; int estado = 0; while (estado >= 0) { transicion = (char)archivo.Peek(); estado = trand[estado, columna(transicion)]; clasificar(estado); if (estado >= 0) { archivo.Read(); caracter++; if (transicion == 10) { linea++; caracter = 1; } if ((estado > 0 && estado < 33) || estado >= 36) { palabra += transicion; } else { palabra = ""; } } } setContenido(palabra); if (estado == -2) { if (getClasificacion() == clasificaciones.cadena) { throw new Error(bitacora, "Error lexico: Se esperaban comillas (\") o comilla (') de cierre. (" + linea + ", " + caracter + ")"); } else if (getClasificacion() == clasificaciones.numero) { throw new Error(bitacora, "Error lexico: Se esperaba un dígito. (" + linea + ", " + caracter + ")"); } else { throw new Error(bitacora, "Error lexico: Se esperaba un cierre de comentario (*/). (" + linea + ", " + caracter + ")"); } } else if (getClasificacion() == clasificaciones.identificador) { switch (palabra) { case "char": case "int": case "float": case "string": setClasificacion(clasificaciones.tipoDato); break; case "private": case "public": case "protected": setClasificacion(clasificaciones.zona); break; case "if": case "else": case "switch": setClasificacion(clasificaciones.condicion); break; case "for": case "while": case "do": setClasificacion(clasificaciones.ciclo); break; } } if (getContenido() != "") { bitacora.WriteLine("Token = " + getContenido()); bitacora.WriteLine("Clasificacion = " + getClasificacion()); } } private void clasificar(int estado) { switch (estado) { case 1: setClasificacion(clasificaciones.identificador); break; case 2: setClasificacion(clasificaciones.numero); break; case 8: setClasificacion(clasificaciones.asignacion); break; case 30: setClasificacion(clasificaciones.inicioBloque); break; case 31: setClasificacion(clasificaciones.finBloque); break; case 9: case 12: case 13: case 29: setClasificacion(clasificaciones.caracter); break; case 10: setClasificacion(clasificaciones.inicializacion); break; case 11: setClasificacion(clasificaciones.finSentencia); break; case 14: case 15: setClasificacion(clasificaciones.operadorLogico); break; case 16: case 26: case 27: setClasificacion(clasificaciones.operadorRelacional); break; case 17: case 18: setClasificacion(clasificaciones.operadorTermino); break; case 19: setClasificacion(clasificaciones.incrementoTermino); break; case 20: case 32: setClasificacion(clasificaciones.operadorFactor); break; case 21: setClasificacion(clasificaciones.incrementoFactor); break; case 22: case 24: setClasificacion(clasificaciones.cadena); break; case 28: setClasificacion(clasificaciones.operadorTernario); break; case 36: setClasificacion(clasificaciones.flujoEntrada); break; case 37: setClasificacion(clasificaciones.flujoSalida); break; } } private int columna(char t) { // WS,EF, L, D, ., +, -, E, =, :, ;, &, |, !, >, <, *, /, %, ", ', ?,La, {, },#10 if (FinDeArchivo()) { return 1; } else if (t == 10) { return 25; } else if (char.IsWhiteSpace(t)) { return 0; } else if (char.ToLower(t) == 'e') { return 7; } else if (char.IsLetter(t)) { return 2; } else if (char.IsDigit(t)) { return 3; } else if (t == '.') { return 4; } else if (t == '+') { return 5; } else if (t == '-') { return 6; } else if (t == '=') { return 8; } else if (t == ':') { return 9; } else if (t == ';') { return 10; } else if (t == '&') { return 11; } else if (t == '|') { return 12; } else if (t == '!') { return 13; } else if (t == '>') { return 14; } else if (t == '<') { return 15; } else if (t == '*') { return 16; } else if (t == '/') { return 17; } else if (t == '%') { return 18; } else if (t == '"') { return 19; } else if (t == '\'') { return 20; } else if (t == '?') { return 21; } else if (t == '{') { return 23; } else if (t == '}') { return 24; } else { return 22; } // WS,EF, L, D, ., +, -, E, =, :, ;, &, |, !, >, <, *, /, %, ", ', ?,La, {, },#10 } public bool FinDeArchivo() { return archivo.EndOfStream; } } }
37.307506
149
0.34547
[ "MIT" ]
AndresEdu/AutomatasII
Lexico.cs
15,411
C#
/* * LambdaSharp (λ#) * Copyright (C) 2018-2021 * lambdasharp.net * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Linq; using System.Security.Cryptography; using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using Amazon.DynamoDBv2; using LambdaSharp.Core.Registrations; using LambdaSharp.Core.RollbarApi; using LambdaSharp.CustomResource; using LambdaSharp.Exceptions; namespace LambdaSharp.Core.RegistrationFunction { public class RegistrationResourceProperties { //--- Properties --- public string? ResourceType { get; set; } #region --- LambdaSharp::Registration::Module --- public string? ModuleId { get; set; } public string? ModuleInfo { get; set; } // NOTE (2020-07-27, bjorg): this property was replaced by `ModuleInfo` public string? Module { get; set; } #endregion #region --- LambdaSharp::Registration::Function --- // public string? ModuleId { get; set; } public string? FunctionId { get; set; } public string? FunctionName { get; set; } public string? FunctionLogGroupName { get; set; } public int FunctionMaxMemory { get; set; } public int FunctionMaxDuration { get; set; } public string? FunctionPlatform { get; set; } public string? FunctionFramework { get; set; } public string? FunctionLanguage { get; set; } #endregion #region --- LambdaSharp::Registration::App --- // public string? ModuleId { get; set; } public string? AppId { get; set; } public string? AppName { get; set; } public string? AppLogGroup { get; set; } public string? AppPlatform { get; set; } public string? AppFramework { get; set; } public string? AppLanguage { get; set; } #endregion //--- Methods --- public string? GetModuleInfo() => ModuleInfo ?? Module; public string? GetModuleFullName() { var moduleInfo = GetModuleInfo(); if(moduleInfo == null) { return null; } var index = moduleInfo.IndexOfAny(new[] { ':', '@' }); if(index < 0) { return moduleInfo; } return moduleInfo.Substring(0, index); } public string? GetModuleNamespace() => GetModuleFullName()?.Split('.', 2)[0]; public string? GetModuleName() => GetModuleFullName()?.Split('.', 2)[1]; } public class RegistrationResourceAttributes { //--- Properties --- public string? Registration { get; set; } } public class RegistrarException : ALambdaException { //--- Constructors --- public RegistrarException(string format, params object[] args) : base(format, args) { } } public sealed class Function : ALambdaCustomResourceFunction<RegistrationResourceProperties, RegistrationResourceAttributes> { //--- Constants --- private const int PROJECT_HASH_LENGTH = 6; //--- Fields --- private RegistrationTable? _registrations; private RollbarClient? _rollbarClient; private string? _rollbarProjectPattern; private string? _coreSecretsKey; //--- Constructors --- public Function() : base(new LambdaSharp.Serialization.LambdaSystemTextJsonSerializer()) { } //--- Properties --- private RegistrationTable Registrations => _registrations ?? throw new InvalidOperationException(); private RollbarClient RollbarClient => _rollbarClient ?? throw new InvalidOperationException(); private string CoreSecretsKey => _coreSecretsKey ?? throw new InvalidOperationException(); private string RollbarProjectPattern => _rollbarProjectPattern ?? throw new InvalidOperationException(); //--- Methods --- public async override Task InitializeAsync(LambdaConfig config) { var tableName = config.ReadDynamoDBTableName("RegistrationTable"); _registrations = new RegistrationTable(new AmazonDynamoDBClient(), tableName); _rollbarClient = new RollbarClient( HttpClient, config.ReadText("RollbarReadAccessToken", defaultValue: null), config.ReadText("RollbarWriteAccessToken", defaultValue: null), message => LogInfo(message) ); _rollbarProjectPattern = config.ReadText("RollbarProjectPattern"); _coreSecretsKey = config.ReadText("CoreSecretsKey"); // set default project pattern if none is specified if(string.IsNullOrEmpty(_rollbarProjectPattern)) { var rollbarProjectPrefix = config.ReadText("RollbarProjectPrefix"); _rollbarProjectPattern = $"{rollbarProjectPrefix}{{ModuleFullName}}"; } } public override async Task<Response<RegistrationResourceAttributes>> ProcessCreateResourceAsync(Request<RegistrationResourceProperties> request, CancellationToken cancellationToken) { var properties = request.ResourceProperties; // request validation if(properties == null) { throw new RegistrarException("missing resource properties"); } if(properties.ModuleId == null) { throw new RegistrarException("missing module ID"); } if(properties.ResourceType == null) { throw new RegistrarException("missing resource type"); } // determine the kind of registration that is requested switch(properties.ResourceType) { case "LambdaSharp::Registration::Module": { LogInfo($"Adding Module: Id={properties.ModuleId}, Info={properties.GetModuleInfo()}"); var owner = PopulateOwnerMetaData(properties); // create new rollbar project var rollbarProject = await RegisterRollbarProject(properties); owner.RollbarProjectId = rollbarProject.ProjectId; owner.RollbarAccessToken = rollbarProject.ProjectAccessToken; // create module record await Registrations.PutOwnerMetaDataAsync($"M:{properties.ModuleId}", owner); return Respond($"registration:module:{properties.ModuleId}"); } case "LambdaSharp::Registration::Function": { if(properties.FunctionId == null) { throw new RegistrarException("missing function ID"); } // create function record LogInfo($"Adding Function: Id={properties.FunctionId}, Name={properties.FunctionName}, ModuleId={properties.ModuleId}"); var owner = await Registrations.GetOwnerMetaDataAsync($"M:{properties.ModuleId}"); if(owner == null) { throw new RegistrarException("no registration found for module {0}", properties.ModuleId); } owner = PopulateOwnerMetaData(properties, owner); await Registrations.PutOwnerMetaDataAsync($"F:{properties.FunctionId}", owner); return Respond($"registration:function:{properties.FunctionId}"); } case "LambdaSharp::Registration::App": { if(properties.AppId == null) { throw new RegistrarException("missing app ID"); } // create function record LogInfo($"Adding App: Id={properties.AppId}, Name={properties.AppName}, ModuleId={properties.ModuleId}"); var owner = await Registrations.GetOwnerMetaDataAsync($"M:{properties.ModuleId}"); if(owner == null) { throw new RegistrarException("no registration found for module {0}", properties.ModuleId); } owner = PopulateOwnerMetaData(properties, owner); await Registrations.PutOwnerMetaDataAsync($"L:{properties.AppLogGroup}", owner); return Respond($"registration:app:{properties.AppId}"); } default: throw new RegistrarException("unrecognized resource type: {0}", properties.ResourceType); } } public override async Task<Response<RegistrationResourceAttributes>> ProcessDeleteResourceAsync(Request<RegistrationResourceProperties> request, CancellationToken cancellationToken) { var properties = request.ResourceProperties; // request validation if(properties == null) { throw new RegistrarException("missing resource properties"); } if(properties.ModuleId == null) { throw new RegistrarException("missing module ID"); } // determine the kind of de-registration that is requested switch(properties.ResourceType) { case "LambdaSharp::Registration::Module": { // delete old rollbar project // TODO (2018-10-22, bjorg): only delete rollbar project if ALL registrations have been deleted // if(_rollbarClient.HasTokens) { // var owner = await _registrations.GetOwnerMetaDataAsync($"M:{properties.ModuleId}"); // try { // if(owner.RollbarProjectId > 0) { // await _rollbarClient.DeleteProject(owner.RollbarProjectId); // } // } catch(Exception e) { // LogErrorAsWarning(e, "failed to delete rollbar project: {0}", owner.RollbarProjectId); // } // } // delete module record LogInfo($"Removing Module: Id={properties.ModuleId}, Info={properties.GetModuleInfo()}"); await Registrations.DeleteOwnerMetaDataAsync($"M:{properties.ModuleId}"); break; } case "LambdaSharp::Registration::Function": { if(properties.FunctionId == null) { throw new RegistrarException("missing function ID"); } // delete function record LogInfo($"Removing Function: Id={properties.FunctionId}, Name={properties.FunctionName}, ModuleId={properties.ModuleId}"); await Registrations.DeleteOwnerMetaDataAsync($"F:{properties.FunctionId}"); break; } case "LambdaSharp::Registration::App": { if(properties.AppId == null) { throw new RegistrarException("missing app ID"); } // delete function record LogInfo($"Removing App: Id={properties.AppId}, Name={properties.AppName}, ModuleId={properties.ModuleId}"); await Registrations.DeleteOwnerMetaDataAsync($"L:{properties.AppLogGroup}"); break; } default: // nothing to do since we didn't process this request successfully in the first place! break; } return new Response<RegistrationResourceAttributes>(); } public override async Task<Response<RegistrationResourceAttributes>> ProcessUpdateResourceAsync(Request<RegistrationResourceProperties> request, CancellationToken cancellationToken) { // request validation if(request.PhysicalResourceId == null) { throw new RegistrarException("missing physical id"); } var properties = request.ResourceProperties; if(properties == null) { throw new RegistrarException("missing resource properties"); } if(properties.ModuleId == null) { throw new RegistrarException("missing module ID"); } if(properties.ResourceType == null) { throw new RegistrarException("missing resource type"); } // determine the kind of registration that is requested switch(properties.ResourceType) { case "LambdaSharp::Registration::Module": { // update module record LogInfo($"Updating Module: Id={properties.ModuleId}, Info={properties.GetModuleInfo()}"); var owner = PopulateOwnerMetaData(properties); await Registrations.PutOwnerMetaDataAsync($"M:{properties.ModuleId}", owner); return Respond(request.PhysicalResourceId); } case "LambdaSharp::Registration::Function": { if(properties.FunctionId == null) { throw new RegistrarException("missing function ID"); } // update function record LogInfo($"Updating Function: Id={properties.FunctionId}, Name={properties.FunctionName}, ModuleId={properties.ModuleId}"); var owner = await Registrations.GetOwnerMetaDataAsync($"M:{properties.ModuleId}"); if(owner == null) { throw new RegistrarException("no registration found for module {0}", properties.ModuleId); } owner = PopulateOwnerMetaData(properties, owner); await Registrations.PutOwnerMetaDataAsync($"F:{properties.FunctionId}", owner); return Respond(request.PhysicalResourceId); } case "LambdaSharp::Registration::App": { if(properties.AppId == null) { throw new RegistrarException("missing app ID"); } // update function record LogInfo($"Updating App: Id={properties.AppId}, Name={properties.AppName}, ModuleId={properties.ModuleId}"); var owner = await Registrations.GetOwnerMetaDataAsync($"M:{properties.ModuleId}"); if(owner == null) { throw new RegistrarException("no registration found for module {0}", properties.ModuleId); } owner = PopulateOwnerMetaData(properties, owner); await Registrations.PutOwnerMetaDataAsync($"L:{properties.AppLogGroup}", owner); return Respond(request.PhysicalResourceId); } default: throw new RegistrarException("unrecognized resource type: {0}", properties.ResourceType); } } private Response<RegistrationResourceAttributes> Respond(string registration) => new Response<RegistrationResourceAttributes> { PhysicalResourceId = registration, Attributes = new RegistrationResourceAttributes { Registration = registration } }; private OwnerMetaData PopulateOwnerMetaData(RegistrationResourceProperties properties, OwnerMetaData? owner = null) { if(owner == null) { owner = new OwnerMetaData(); } // support pre-0.8 notation where only 'Module' is present in the properties (no 'ModuleInfo') string? moduleInfo = null; string? module = null; if(properties.ModuleInfo != null) { moduleInfo = properties.ModuleInfo; module = properties.ModuleInfo.Split(':', 2)[0]; } else if(properties.Module != null) { moduleInfo = properties.Module; module = properties.Module?.Split(':', 2)[0]; } // create/update owner record owner.ModuleId = properties.ModuleId ?? owner.ModuleId; owner.Module = module ?? owner.Module; owner.ModuleInfo = moduleInfo ?? owner.ModuleInfo; // function record owner.FunctionId = properties.FunctionId ?? owner.FunctionId; owner.FunctionName = properties.FunctionName ?? owner.FunctionName; owner.FunctionLogGroupName = properties.FunctionLogGroupName ?? owner.FunctionLogGroupName; owner.FunctionPlatform = properties.FunctionPlatform ?? owner.FunctionPlatform; owner.FunctionFramework = properties.FunctionFramework ?? owner.FunctionFramework; owner.FunctionLanguage = properties.FunctionLanguage ?? owner.FunctionLanguage; owner.FunctionMaxMemory = (properties.FunctionMaxMemory != 0) ? properties.FunctionMaxMemory : owner.FunctionMaxMemory; owner.FunctionMaxDuration = (TimeSpan.FromSeconds(properties.FunctionMaxDuration) != TimeSpan.Zero) ? TimeSpan.FromSeconds(properties.FunctionMaxDuration) : TimeSpan.FromSeconds(owner.FunctionMaxDuration.TotalSeconds); // app record owner.AppId = properties.AppId ?? owner.AppId; owner.AppName = properties.AppName ?? owner.AppName; owner.AppLogGroup = properties.AppLogGroup ?? owner.AppLogGroup; owner.AppPlatform = properties.AppPlatform ?? owner.AppPlatform; owner.AppFramework = properties.AppFramework ?? owner.AppFramework; owner.AppLanguage = properties.AppLanguage ?? owner.AppLanguage; return owner; } private async Task<(int ProjectId, string? ProjectAccessToken)> RegisterRollbarProject(RegistrationResourceProperties properties) { if(!RollbarClient.HasTokens) { return (ProjectId: 0, ProjectAccessToken: null); } // generate the Rollbar project name var name = Regex.Replace(_rollbarProjectPattern, @"\{(?!\!)[^\}]+\}", match => { var value = match.ToString(); switch(value) { case "{ModuleFullName}": return properties.GetModuleFullName(); case "{ModuleNamespace}": return properties.GetModuleNamespace(); case "{ModuleName}": return properties.GetModuleName(); case "{ModuleId}": return properties.ModuleId; case "{ModuleIdNoTierPrefix}": return string.IsNullOrEmpty(Info.DeploymentTier) ? properties.ModuleId : properties.ModuleId?.Substring(Info.DeploymentTier.Length + 1); default: // remove curly braces for unrecognized placeholders return value.Substring(1, value.Length - 2); } }); // NOTE (2020-02-19, bjorg): Rollbar projects cannot exceed 32 characters if(name.Length > 32) { using(var crypto = new SHA256Managed()) { var hash = string.Concat(crypto.ComputeHash(Encoding.UTF8.GetBytes(name)).Select(x => x.ToString("X2"))); // keep first X characters for original project name, append (32-X) characters from the hash name = name.Substring(0, 32 - PROJECT_HASH_LENGTH) + hash.Substring(0, PROJECT_HASH_LENGTH); } } // find or create Rollbar project var project = await RollbarClient.FindProjectByName(name) ?? await RollbarClient.CreateProject(name); // retrieve access token for Rollbar project var tokens = await RollbarClient.ListProjectTokens(project.Id); var token = tokens.FirstOrDefault(t => t.Name == "post_server_item").AccessToken; if(token == null) { throw new RegistrarException("internal error: unable to retrieve token for new Rollbar project"); } return (ProjectId: project.Id, ProjectAccessToken: await EncryptSecretAsync(token, CoreSecretsKey)); } } }
48.023041
191
0.590442
[ "Apache-2.0" ]
LambdaSharp/LambdaSharpTool
Modules/LambdaSharp.Core/RegistrationFunction/Function.cs
20,843
C#
using System.Data; using Orchard.ContentManagement.MetaData; using Orchard.Core.Common.Models; using Orchard.Core.Contents.Extensions; using Orchard.Core.Title.Models; using Orchard.Data; using Orchard.Data.Migration; using Orchard.Localization; using Orchard.Projections.Models; namespace Orchard.Projections { public class Migrations : DataMigrationImpl { private readonly IRepository<MemberBindingRecord> _memberBindingRepository; private readonly IRepository<PropertyRecord> _propertyRecordRepository; public Migrations( IRepository<MemberBindingRecord> memberBindingRepository, IRepository<PropertyRecord> propertyRecordRepository) { _memberBindingRepository = memberBindingRepository; _propertyRecordRepository = propertyRecordRepository; T = NullLocalizer.Instance; } public Localizer T { get; set; } public int Create() { // Properties index SchemaBuilder.CreateTable("StringFieldIndexRecord", table => table .Column<int>("Id", c => c.PrimaryKey().Identity()) .Column<string>("PropertyName") .Column<string>("Value", c => c.WithLength(4000)) .Column<int>("FieldIndexPartRecord_Id") ); SchemaBuilder.CreateTable("IntegerFieldIndexRecord", table => table .Column<int>("Id", c => c.PrimaryKey().Identity()) .Column<string>("PropertyName") .Column<long>("Value") .Column<int>("FieldIndexPartRecord_Id") ); SchemaBuilder.CreateTable("DoubleFieldIndexRecord", table => table .Column<int>("Id", c => c.PrimaryKey().Identity()) .Column<string>("PropertyName") .Column<double>("Value") .Column<int>("FieldIndexPartRecord_Id") ); SchemaBuilder.CreateTable("DecimalFieldIndexRecord", table => table .Column<int>("Id", c => c.PrimaryKey().Identity()) .Column<string>("PropertyName") .Column<decimal>("Value") .Column<int>("FieldIndexPartRecord_Id") ); SchemaBuilder.CreateTable("FieldIndexPartRecord", table => table.ContentPartRecord()); // Query ContentDefinitionManager.AlterTypeDefinition("Query", cfg => cfg .WithPart("QueryPart") .WithPart("TitlePart") .WithIdentity() ); SchemaBuilder.CreateTable("QueryPartRecord", table => table .ContentPartRecord() ); SchemaBuilder.CreateTable("FilterGroupRecord", table => table .Column<int>("Id", c => c.PrimaryKey().Identity()) .Column<int>("QueryPartRecord_id") ); SchemaBuilder.CreateTable("FilterRecord", table => table .Column<int>("Id", c => c.PrimaryKey().Identity()) .Column<string>("Category", c => c.WithLength(64)) .Column<string>("Type", c => c.WithLength(64)) .Column<string>("Description", c => c.WithLength(255)) .Column<string>("State", c => c.Unlimited()) .Column<int>("Position") .Column<int>("FilterGroupRecord_id") ); SchemaBuilder.CreateTable("SortCriterionRecord", table => table .Column<int>("Id", c => c.PrimaryKey().Identity()) .Column<string>("Category", c => c.WithLength(64)) .Column<string>("Type", c => c.WithLength(64)) .Column<string>("Description", c => c.WithLength(255)) .Column<string>("State", c => c.Unlimited()) .Column<int>("Position") .Column<int>("QueryPartRecord_id") ); SchemaBuilder.CreateTable("LayoutRecord", table => table .Column<int>("Id", c => c.PrimaryKey().Identity()) .Column<string>("Category", c => c.WithLength(64)) .Column<string>("Type", c => c.WithLength(64)) .Column<string>("Description", c => c.WithLength(255)) .Column<string>("State", c => c.Unlimited()) .Column<string>("DisplayType", c => c.WithLength(64)) .Column<int>("Display") .Column<int>("QueryPartRecord_id") .Column<int>("GroupProperty_id") ); SchemaBuilder.CreateTable("PropertyRecord", table => table .Column<int>("Id", c => c.PrimaryKey().Identity()) .Column<string>("Category", c => c.WithLength(64)) .Column<string>("Type", c => c.WithLength(64)) .Column<string>("Description", c => c.WithLength(255)) .Column<string>("State", c => c.Unlimited()) .Column<int>("Position") .Column<int>("LayoutRecord_id") .Column<bool>("ExcludeFromDisplay") .Column<bool>("CreateLabel") .Column<string>("Label", c => c.WithLength(255)) .Column<bool>("LinkToContent") .Column<bool>("CustomizePropertyHtml") .Column<string>("CustomPropertyTag", c => c.WithLength(64)) .Column<string>("CustomPropertyCss", c => c.WithLength(64)) .Column<bool>("CustomizeLabelHtml") .Column<string>("CustomLabelTag", c => c.WithLength(64)) .Column<string>("CustomLabelCss", c => c.WithLength(64)) .Column<bool>("CustomizeWrapperHtml") .Column<string>("CustomWrapperTag", c => c.WithLength(64)) .Column<string>("CustomWrapperCss", c => c.WithLength(64)) .Column<string>("NoResultText", c => c.Unlimited()) .Column<bool>("ZeroIsEmpty") .Column<bool>("HideEmpty") .Column<bool>("RewriteOutput") .Column<string>("RewriteText", c => c.Unlimited()) .Column<bool>("StripHtmlTags") .Column<bool>("TrimLength") .Column<bool>("AddEllipsis") .Column<int>("MaxLength") .Column<bool>("TrimOnWordBoundary") .Column<bool>("PreserveLines") .Column<bool>("TrimWhiteSpace") ); SchemaBuilder.CreateTable("ProjectionPartRecord", table => table .ContentPartRecord() .Column<int>("Items") .Column<int>("ItemsPerPage") .Column<int>("Skip") .Column<string>("PagerSuffix", c => c.WithLength(255)) .Column<int>("MaxItems") .Column<bool>("DisplayPager") .Column<int>("QueryPartRecord_id") .Column<int>("LayoutRecord_Id") ); SchemaBuilder.CreateTable("MemberBindingRecord", table => table .Column<int>("Id", c => c.PrimaryKey().Identity()) .Column<string>("Type", c => c.WithLength(255)) .Column<string>("Member", c => c.WithLength(64)) .Column<string>("Description", c => c.WithLength(500)) .Column<string>("DisplayName", c => c.WithLength(64)) ); ContentDefinitionManager.AlterTypeDefinition("ProjectionWidget", cfg => cfg .WithPart("WidgetPart") .WithPart("CommonPart") .WithIdentity() .WithPart("ProjectionPart") .WithSetting("Stereotype", "Widget") ); ContentDefinitionManager.AlterTypeDefinition("ProjectionPage", cfg => cfg .WithPart("CommonPart") .WithPart("TitlePart") .WithPart("AutoroutePart", builder => builder .WithSetting("AutorouteSettings.AllowCustomPattern", "True") .WithSetting("AutorouteSettings.AutomaticAdjustmentOnEdit", "False") .WithSetting("AutorouteSettings.PatternDefinitions", "[{\"Name\":\"Title\",\"Pattern\":\"{Content.Slug}\",\"Description\":\"my-projections\"}]")) .WithPart("MenuPart") .WithPart("ProjectionPart") .WithPart("AdminMenuPart", p => p.WithSetting("AdminMenuPartTypeSettings.DefaultPosition", "5")) .Creatable() .DisplayedAs("Projection") ); // Default Model Bindings - CommonPartRecord _memberBindingRepository.Create(new MemberBindingRecord { Type = typeof(CommonPartRecord).FullName, Member = "CreatedUtc", DisplayName = T("Creation date").Text, Description = T("When the content item was created").Text }); _memberBindingRepository.Create(new MemberBindingRecord { Type = typeof(CommonPartRecord).FullName, Member = "ModifiedUtc", DisplayName = T("Modification date").Text, Description = T("When the content item was modified").Text }); _memberBindingRepository.Create(new MemberBindingRecord { Type = typeof(CommonPartRecord).FullName, Member = "PublishedUtc", DisplayName = T("Publication date").Text, Description = T("When the content item was published").Text }); // Default Model Bindings - TitlePartRecord _memberBindingRepository.Create(new MemberBindingRecord { Type = typeof(TitlePartRecord).FullName, Member = "Title", DisplayName = T("Title Part Title").Text, Description = T("The title assigned using the Title part").Text }); // Default Model Bindings - BodyPartRecord _memberBindingRepository.Create(new MemberBindingRecord { Type = typeof(BodyPartRecord).FullName, Member = "Text", DisplayName = T("Body Part Text").Text, Description = T("The text from the Body part").Text }); SchemaBuilder.AlterTable("StringFieldIndexRecord", table => table .CreateIndex("IDX_Orchard_Projections_StringFieldIndexRecord", "FieldIndexPartRecord_Id") ); SchemaBuilder.AlterTable("IntegerFieldIndexRecord", table => table .CreateIndex("IDX_Orchard_Projections_IntegerFieldIndexRecord", "FieldIndexPartRecord_Id") ); SchemaBuilder.AlterTable("DoubleFieldIndexRecord", table => table .CreateIndex("IDX_Orchard_Projections_DoubleFieldIndexRecord", "FieldIndexPartRecord_Id") ); SchemaBuilder.AlterTable("DecimalFieldIndexRecord", table => table .CreateIndex("IDX_Orchard_Projections_DecimalFieldIndexRecords", "FieldIndexPartRecord_Id") ); return 1; } public int UpdateFrom1() { SchemaBuilder.CreateTable("NavigationQueryPartRecord", table => table.ContentPartRecord() .Column<int>("Items") .Column<int>("Skip") .Column<int>("QueryPartRecord_id") ); ContentDefinitionManager.AlterTypeDefinition("NavigationQueryMenuItem", cfg => cfg .WithPart("NavigationQueryPart") .WithPart("MenuPart") .WithPart("CommonPart") .DisplayedAs("Query Link") .WithSetting("Description", "Injects menu items from a Query") .WithSetting("Stereotype", "MenuItem") ); ContentDefinitionManager.AlterTypeDefinition("ProjectionPage", cfg => cfg.Listable()); return 3; } public int UpdateFrom2() { SchemaBuilder.AlterTable("ProjectionPartRecord", table => table .AlterColumn("PagerSuffix", c => c.WithType(DbType.String).WithLength(255)) ); return 3; } public int UpdateFrom3() { ContentDefinitionManager.AlterTypeDefinition("NavigationQueryMenuItem", cfg => cfg .WithIdentity() ); return 4; } public int UpdateFrom4() { SchemaBuilder.AlterTable("StringFieldIndexRecord", table => table .AddColumn<string>("LatestValue", c => c.WithLength(4000))); SchemaBuilder.AlterTable("IntegerFieldIndexRecord", table => table .AddColumn<long>("LatestValue")); SchemaBuilder.AlterTable("DoubleFieldIndexRecord", table => table .AddColumn<double>("LatestValue")); SchemaBuilder.AlterTable("DecimalFieldIndexRecord", table => table .AddColumn<decimal>("LatestValue")); //Adds indexes for better performances in queries SchemaBuilder.AlterTable("StringFieldIndexRecord", table => table.CreateIndex("IX_PropertyName", new string[] { "PropertyName" })); SchemaBuilder.AlterTable("StringFieldIndexRecord", table => table.CreateIndex("IX_FieldIndexPartRecord_Id", new string[] { "FieldIndexPartRecord_Id" })); SchemaBuilder.AlterTable("IntegerFieldIndexRecord", table => table.CreateIndex("IX_PropertyName", new string[] { "PropertyName" })); SchemaBuilder.AlterTable("IntegerFieldIndexRecord", table => table.CreateIndex("IX_FieldIndexPartRecord_Id", new string[] { "FieldIndexPartRecord_Id" })); SchemaBuilder.AlterTable("DoubleFieldIndexRecord", table => table.CreateIndex("IX_PropertyName", new string[] { "PropertyName" })); SchemaBuilder.AlterTable("DoubleFieldIndexRecord", table => table.CreateIndex("IX_FieldIndexPartRecord_Id", new string[] { "FieldIndexPartRecord_Id" })); SchemaBuilder.AlterTable("DecimalFieldIndexRecord", table => table.CreateIndex("IX_PropertyName", new string[] { "PropertyName" })); SchemaBuilder.AlterTable("DecimalFieldIndexRecord", table => table.CreateIndex("IX_FieldIndexPartRecord_Id", new string[] { "FieldIndexPartRecord_Id" })); SchemaBuilder.AlterTable("QueryPartRecord", table => table .AddColumn<string>("VersionScope", c => c.WithLength(15))); return 5; } public int UpdateFrom5() { SchemaBuilder.AlterTable("PropertyRecord", table => table .AddColumn<string>("RewriteOutputCondition", c => c.Unlimited()) ); foreach (var property in _propertyRecordRepository.Table) if (property.RewriteOutput) property.RewriteOutputCondition = "true"; return 6; } } }
45.18732
169
0.543048
[ "BSD-3-Clause" ]
Lawyerson/Orchard
src/Orchard.Web/Modules/Orchard.Projections/Migrations.cs
15,682
C#
using System.Collections.Generic; namespace MetafileDumper.EmfPlus.Objects { /// <summary> /// Specifies focus scales for the blend pattern of a path gradient brush. /// [MS-EMFPLUS] 2.2.2.18 /// </summary> public class EmfPlusFocusScaleData : ObjectBase { public EmfPlusFocusScaleData(MetafileReader reader) { ScaleCount = reader.ReadUInt32(); ScaleX = reader.ReadSingle(); ScaleY = reader.ReadSingle(); } public override uint Size => 12; /// <summary> /// A 32-bit unsigned integer that specifies the number of focus scales. /// This value MUST be 2. /// </summary> public uint ScaleCount { get; } /// <summary> /// A floating-point value that defines the horizontal focus scale. /// The focus scale MUST be a value between 0.0 and 1.0, exclusive. /// </summary> public float ScaleX { get; } /// <summary> /// A floating-point value that defines the vertical focus scale. /// The focus scale MUST be a value between 0.0 and 1.0, exclusive. /// </summary> public float ScaleY { get; } public override IEnumerable<RecordValues> GetValues() { yield return new RecordValues("Scale Count", 4); yield return new RecordValues("Scale X", 4); yield return new RecordValues("Scale Y", 4); } } }
32.130435
80
0.582544
[ "MIT" ]
hughbe/Metafile-Dumper
src/EmfPlus/Objects/EmfPlusFocusScaleData.cs
1,480
C#
// Project: Daggerfall Tools For Unity // Copyright: Copyright (C) 2009-2018 Daggerfall Workshop // Web Site: http://www.dfworkshop.net // License: MIT License (http://www.opensource.org/licenses/mit-license.php) // Source Code: https://github.com/Interkarma/daggerfall-unity // Original Author: Gavin Clayton (interkarma@dfworkshop.net) // Contributors: // // Notes: // using UnityEngine; using UnityEditor; using System.Collections; using DaggerfallConnect.Arena2; namespace DaggerfallWorkshop { [CustomEditor(typeof(DaggerfallTerrain))] public class DaggerfallTerrainEditor : Editor { private DaggerfallTerrain dfTerrain { get { return target as DaggerfallTerrain; } } SerializedProperty Prop(string name) { return serializedObject.FindProperty(name); } public override void OnInspectorGUI() { // Update serializedObject.Update(); DisplayGUI(); // Save modified properties serializedObject.ApplyModifiedProperties(); if (GUI.changed) EditorUtility.SetDirty(target); } private void DisplayGUI() { DrawDefaultInspector(); //if (GUILayout.Button("Update Terrain")) //{ // dfTerrain.__EditorUpdateTerrain(); //} } } }
27.346154
91
0.609705
[ "MIT" ]
ChristianBasiga/daggerfall-unity
Assets/Scripts/Editor/DaggerfallTerrainEditor.cs
1,424
C#
namespace Lyra.Features.Styles { public class BodyStyle { public string ForegroundColor { get; set; } public string BackgroundColor { get; set; } public float FontSize { get; set; } public string NormalFont { get; set; } public string SpecialFont { get; set; } public string MutedFont { get; set; } public bool UseBackgroundImage { get; set; } public ImageScaling BackgroundImageScaling { get; set; } public string BackgroundImagePath { get; set; } public float BackgroundImageOpacity { get; set; } = 1.0f; public enum ImageScaling { None, Fill, Uniform, UniformToFill, } } }
22.69697
65
0.575434
[ "MIT" ]
ogirard/lyra
src/Lyra/Features/Styles/(Model)/BodyStyle.cs
749
C#
// Copyright (c) Service Stack LLC. All Rights Reserved. // License: https://raw.github.com/ServiceStack/ServiceStack/master/license.txt using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Reflection; using System.Web; using Funq; using ServiceStack.Auth; using ServiceStack.Caching; using ServiceStack.Configuration; using ServiceStack.Formats; using ServiceStack.Host; using ServiceStack.Host.Handlers; using ServiceStack.Html; using ServiceStack.IO; using ServiceStack.Logging; using ServiceStack.Messaging; using ServiceStack.Metadata; using ServiceStack.MiniProfiler.UI; using ServiceStack.NativeTypes; using ServiceStack.Serialization; using ServiceStack.Text; using ServiceStack.VirtualPath; using ServiceStack.Web; using ServiceStack.Redis; namespace ServiceStack { public abstract partial class ServiceStackHost : IAppHost, IFunqlet, IHasContainer, IDisposable { private readonly ILog Log = LogManager.GetLogger(typeof(ServiceStackHost)); public static ServiceStackHost Instance { get; protected set; } public DateTime StartedAt { get; set; } public DateTime? AfterInitAt { get; set; } public DateTime? ReadyAt { get; set; } public bool TestMode { get; set; } public Assembly[] ServiceAssemblies { get; private set; } public bool HasStarted { get { return ReadyAt != null; } } public static bool IsReady() { return Instance != null && Instance.ReadyAt != null; } protected ServiceStackHost(string serviceName, params Assembly[] assembliesWithServices) { this.StartedAt = DateTime.UtcNow; ServiceName = serviceName; AppSettings = new AppSettings(); Container = new Container { DefaultOwner = Owner.External }; ServiceAssemblies = assembliesWithServices; ServiceController = CreateServiceController(assembliesWithServices); ContentTypes = Host.ContentTypes.Instance; RestPaths = new List<RestPath>(); Routes = new ServiceRoutes(this); Metadata = new ServiceMetadata(RestPaths); PreRequestFilters = new List<Action<IRequest, IResponse>>(); RequestConverters = new List<Func<IRequest, object, object>>(); ResponseConverters = new List<Func<IRequest, object, object>>(); GlobalRequestFilters = new List<Action<IRequest, IResponse, object>>(); GlobalTypedRequestFilters = new Dictionary<Type, ITypedFilter>(); GlobalResponseFilters = new List<Action<IRequest, IResponse, object>>(); GlobalTypedResponseFilters = new Dictionary<Type, ITypedFilter>(); GlobalMessageRequestFilters = new List<Action<IRequest, IResponse, object>>(); GlobalTypedMessageRequestFilters = new Dictionary<Type, ITypedFilter>(); GlobalMessageResponseFilters = new List<Action<IRequest, IResponse, object>>(); GlobalTypedMessageResponseFilters = new Dictionary<Type, ITypedFilter>(); ViewEngines = new List<IViewEngine>(); ServiceExceptionHandlers = new List<HandleServiceExceptionDelegate>(); UncaughtExceptionHandlers = new List<HandleUncaughtExceptionDelegate>(); AfterInitCallbacks = new List<Action<IAppHost>>(); OnDisposeCallbacks = new List<Action<IAppHost>>(); OnEndRequestCallbacks = new List<Action<IRequest>>(); RawHttpHandlers = new List<Func<IHttpRequest, IHttpHandler>> { HttpHandlerFactory.ReturnRequestInfo, MiniProfilerHandler.MatchesRequest, }; CatchAllHandlers = new List<HttpHandlerResolverDelegate>(); CustomErrorHttpHandlers = new Dictionary<HttpStatusCode, IServiceStackHandler> { { HttpStatusCode.Forbidden, new ForbiddenHttpHandler() }, { HttpStatusCode.NotFound, new NotFoundHttpHandler() }, }; StartUpErrors = new List<ResponseStatus>(); PluginsLoaded = new List<string>(); Plugins = new List<IPlugin> { new HtmlFormat(), new CsvFormat(), new MarkdownFormat(), new PredefinedRoutesFeature(), new MetadataFeature(), new NativeTypesFeature(), new HttpCacheFeature(), }; ExcludeAutoRegisteringServiceTypes = new HashSet<Type> { typeof(AuthenticateService), typeof(RegisterService), typeof(AssignRolesService), typeof(UnAssignRolesService), typeof(NativeTypesService), typeof(PostmanService), }; JsConfig.InitStatics(); } public abstract void Configure(Container container); protected virtual ServiceController CreateServiceController(params Assembly[] assembliesWithServices) { return new ServiceController(this, assembliesWithServices); //Alternative way to inject Service Resolver strategy //return new ServiceController(this, () => assembliesWithServices.ToList().SelectMany(x => x.GetTypes())); } public virtual void SetConfig(HostConfig config) { Config = config; } public virtual ServiceStackHost Init() { if (Instance != null) { throw new InvalidDataException("ServiceStackHost.Instance has already been set"); } Service.GlobalResolver = Instance = this; Config = HostConfig.ResetInstance(); OnConfigLoad(); Config.DebugMode = GetType().Assembly.IsDebugBuild(); if (Config.DebugMode) { Plugins.Add(new RequestInfoFeature()); } OnBeforeInit(); ServiceController.Init(); Configure(Container); ConfigurePlugins(); List<IVirtualPathProvider> pathProviders = null; if (VirtualFileSources == null) { pathProviders = GetVirtualFileSources().Where(x => x != null).ToList(); VirtualFileSources = pathProviders.Count > 1 ? new MultiVirtualPathProvider(this, pathProviders.ToArray()) : pathProviders.First(); } if (VirtualFiles == null) VirtualFiles = (pathProviders != null ? pathProviders.FirstOrDefault(x => x is FileSystemVirtualPathProvider) : null) as IVirtualFiles ?? GetVirtualFileSources().FirstOrDefault(x => x is FileSystemVirtualPathProvider) as IVirtualFiles; OnAfterInit(); LogInitComplete(); return this; } private void LogInitComplete() { var elapsed = DateTime.UtcNow - StartedAt; var hasErrors = StartUpErrors.Any(); if (hasErrors) { Log.ErrorFormat( "Initializing Application {0} took {1}ms. {2} error(s) detected: {3}", ServiceName, elapsed.TotalMilliseconds, StartUpErrors.Count, StartUpErrors.ToJson()); } else { Log.InfoFormat( "Initializing Application {0} took {1}ms. No errors detected.", ServiceName, elapsed.TotalMilliseconds); } } [Obsolete("Renamed to GetVirtualFileSources")] public virtual List<IVirtualPathProvider> GetVirtualPathProviders() { return GetVirtualFileSources(); } public virtual List<IVirtualPathProvider> GetVirtualFileSources() { var pathProviders = new List<IVirtualPathProvider> { new FileSystemVirtualPathProvider(this, Config.WebHostPhysicalPath) }; pathProviders.AddRange(Config.EmbeddedResourceBaseTypes.Distinct() .Map(x => new ResourceVirtualPathProvider(this, x))); pathProviders.AddRange(Config.EmbeddedResourceSources.Distinct() .Map(x => new ResourceVirtualPathProvider(this, x))); return pathProviders; } public virtual ServiceStackHost Start(string urlBase) { throw new NotImplementedException("Start(listeningAtUrlBase) is not supported by this AppHost"); } /// <summary> /// Retain the same behavior as ASP.NET and redirect requests to directores /// without a trailing '/' /// </summary> public virtual IHttpHandler RedirectDirectory(IHttpRequest request) { var dir = request.GetVirtualNode() as IVirtualDirectory; if (dir != null) { //Only redirect GET requests for directories which don't have services registered at the same path if (!request.PathInfo.EndsWith("/") && request.Verb == HttpMethods.Get && ServiceController.GetRestPathForRequest(request.Verb, request.PathInfo) == null) { return new RedirectHttpHandler { RelativeUrl = request.PathInfo + "/", }; } } return null; } public string ServiceName { get; set; } public IAppSettings AppSettings { get; set; } public ServiceMetadata Metadata { get; set; } public ServiceController ServiceController { get; set; } // Rare for a user to auto register all avaialable services in ServiceStack.dll // But happens when ILMerged, so exclude autoregistering SS services by default // and let them register them manually public HashSet<Type> ExcludeAutoRegisteringServiceTypes { get; set; } /// <summary> /// The AppHost.Container. Note: it is not thread safe to register dependencies after AppStart. /// </summary> public Container Container { get; private set; } public IServiceRoutes Routes { get; set; } public List<RestPath> RestPaths = new List<RestPath>(); public Dictionary<Type, Func<IRequest, object>> RequestBinders { get { return ServiceController.RequestTypeFactoryMap; } } public IContentTypes ContentTypes { get; set; } public List<Action<IRequest, IResponse>> PreRequestFilters { get; set; } public List<Func<IRequest, object, object>> RequestConverters { get; set; } public List<Func<IRequest, object, object>> ResponseConverters { get; set; } public List<Action<IRequest, IResponse, object>> GlobalRequestFilters { get; set; } public Dictionary<Type, ITypedFilter> GlobalTypedRequestFilters { get; set; } public List<Action<IRequest, IResponse, object>> GlobalResponseFilters { get; set; } public Dictionary<Type, ITypedFilter> GlobalTypedResponseFilters { get; set; } public List<Action<IRequest, IResponse, object>> GlobalMessageRequestFilters { get; private set; } public Dictionary<Type, ITypedFilter> GlobalTypedMessageRequestFilters { get; set; } public List<Action<IRequest, IResponse, object>> GlobalMessageResponseFilters { get; private set; } public Dictionary<Type, ITypedFilter> GlobalTypedMessageResponseFilters { get; set; } public List<IViewEngine> ViewEngines { get; set; } public List<HandleServiceExceptionDelegate> ServiceExceptionHandlers { get; set; } public List<HandleUncaughtExceptionDelegate> UncaughtExceptionHandlers { get; set; } public List<Action<IAppHost>> AfterInitCallbacks { get; set; } public List<Action<IAppHost>> OnDisposeCallbacks { get; set; } public List<Action<IRequest>> OnEndRequestCallbacks { get; set; } public List<Func<IHttpRequest, IHttpHandler>> RawHttpHandlers { get; set; } public List<HttpHandlerResolverDelegate> CatchAllHandlers { get; set; } public IServiceStackHandler GlobalHtmlErrorHttpHandler { get; set; } public Dictionary<HttpStatusCode, IServiceStackHandler> CustomErrorHttpHandlers { get; set; } public List<ResponseStatus> StartUpErrors { get; set; } public List<string> PluginsLoaded { get; set; } public List<IPlugin> Plugins { get; set; } public IVirtualFiles VirtualFiles { get; set; } public IVirtualPathProvider VirtualFileSources { get; set; } [Obsolete("Renamed to VirtualFileSources")] public IVirtualPathProvider VirtualPathProvider { get { return VirtualFileSources; } set { VirtualFileSources = value; } } /// <summary> /// Executed immediately before a Service is executed. Use return to change the request DTO used, must be of the same type. /// </summary> public virtual object OnPreExecuteServiceFilter(IService service, object request, IRequest httpReq, IResponse httpRes) { return request; } /// <summary> /// Executed immediately after a service is executed. Use return to change response used. /// </summary> public virtual object OnPostExecuteServiceFilter(IService service, object response, IRequest httpReq, IResponse httpRes) { return response; } /// <summary> /// Occurs when the Service throws an Exception. /// </summary> public virtual object OnServiceException(IRequest httpReq, object request, Exception ex) { object lastError = null; foreach (var errorHandler in ServiceExceptionHandlers) { lastError = errorHandler(httpReq, request, ex) ?? lastError; } return lastError; } /// <summary> /// Occurs when an exception is thrown whilst processing a request. /// </summary> public virtual void OnUncaughtException(IRequest httpReq, IResponse httpRes, string operationName, Exception ex) { if (UncaughtExceptionHandlers.Count > 0) { foreach (var errorHandler in UncaughtExceptionHandlers) { errorHandler(httpReq, httpRes, operationName, ex); } } } public virtual void HandleUncaughtException(IRequest httpReq, IResponse httpRes, string operationName, Exception ex) { //Only add custom error messages to StatusDescription var httpError = ex as IHttpError; var errorMessage = httpError != null ? httpError.Message : null; var statusCode = ex.ToStatusCode(); //httpRes.WriteToResponse always calls .Close in it's finally statement so //if there is a problem writing to response, by now it will be closed httpRes.WriteErrorToResponse(httpReq, httpReq.ResponseContentType, operationName, errorMessage, ex, statusCode); } public virtual void OnStartupException(Exception ex) { this.StartUpErrors.Add(DtoUtils.CreateErrorResponse(null, ex).GetResponseStatus()); } private HostConfig config; public HostConfig Config { get { return config; } set { config = value; OnAfterConfigChanged(); } } public virtual void OnConfigLoad() { } // Config has changed public virtual void OnAfterConfigChanged() { config.ServiceEndpointsMetadataConfig = ServiceEndpointsMetadataConfig.Create(config.HandlerFactoryPath); JsonDataContractSerializer.Instance.UseBcl = config.UseBclJsonSerializers; JsonDataContractSerializer.Instance.UseBcl = config.UseBclJsonSerializers; } public virtual void OnBeforeInit() { Container.Register<IHashProvider>(c => new SaltedHash()); } //After configure called public virtual void OnAfterInit() { AfterInitAt = DateTime.UtcNow; if (config.EnableFeatures != Feature.All) { if ((Feature.Xml & config.EnableFeatures) != Feature.Xml) { config.IgnoreFormatsInMetadata.Add("xml"); Config.PreferredContentTypes.Remove(MimeTypes.Xml); } if ((Feature.Json & config.EnableFeatures) != Feature.Json) { config.IgnoreFormatsInMetadata.Add("json"); Config.PreferredContentTypes.Remove(MimeTypes.Json); } if ((Feature.Jsv & config.EnableFeatures) != Feature.Jsv) { config.IgnoreFormatsInMetadata.Add("jsv"); Config.PreferredContentTypes.Remove(MimeTypes.Jsv); } if ((Feature.Csv & config.EnableFeatures) != Feature.Csv) { config.IgnoreFormatsInMetadata.Add("csv"); Config.PreferredContentTypes.Remove(MimeTypes.Csv); } if ((Feature.Html & config.EnableFeatures) != Feature.Html) { config.IgnoreFormatsInMetadata.Add("html"); Config.PreferredContentTypes.Remove(MimeTypes.Html); } if ((Feature.Soap11 & config.EnableFeatures) != Feature.Soap11) config.IgnoreFormatsInMetadata.Add("soap11"); if ((Feature.Soap12 & config.EnableFeatures) != Feature.Soap12) config.IgnoreFormatsInMetadata.Add("soap12"); } if ((Feature.Html & config.EnableFeatures) != Feature.Html) Plugins.RemoveAll(x => x is HtmlFormat); if ((Feature.Csv & config.EnableFeatures) != Feature.Csv) Plugins.RemoveAll(x => x is CsvFormat); if ((Feature.Markdown & config.EnableFeatures) != Feature.Markdown) Plugins.RemoveAll(x => x is MarkdownFormat); if ((Feature.PredefinedRoutes & config.EnableFeatures) != Feature.PredefinedRoutes) Plugins.RemoveAll(x => x is PredefinedRoutesFeature); if ((Feature.Metadata & config.EnableFeatures) != Feature.Metadata) { Plugins.RemoveAll(x => x is MetadataFeature); Plugins.RemoveAll(x => x is NativeTypesFeature); } if ((Feature.RequestInfo & config.EnableFeatures) != Feature.RequestInfo) Plugins.RemoveAll(x => x is RequestInfoFeature); if ((Feature.Razor & config.EnableFeatures) != Feature.Razor) Plugins.RemoveAll(x => x is IRazorPlugin); //external if ((Feature.ProtoBuf & config.EnableFeatures) != Feature.ProtoBuf) Plugins.RemoveAll(x => x is IProtoBufPlugin); //external if ((Feature.MsgPack & config.EnableFeatures) != Feature.MsgPack) Plugins.RemoveAll(x => x is IMsgPackPlugin); //external if (config.HandlerFactoryPath != null) config.HandlerFactoryPath = config.HandlerFactoryPath.TrimStart('/'); var specifiedContentType = config.DefaultContentType; //Before plugins loaded var plugins = Plugins.ToArray(); delayLoadPlugin = true; LoadPluginsInternal(plugins); AfterPluginsLoaded(specifiedContentType); if (!TestMode && Container.Exists<IAuthSession>()) throw new Exception(ErrorMessages.ShouldNotRegisterAuthSession); if (!Container.Exists<IAppSettings>()) Container.Register(AppSettings); if (!Container.Exists<ICacheClient>()) { if (Container.Exists<IRedisClientsManager>()) Container.Register(c => c.Resolve<IRedisClientsManager>().GetCacheClient()); else Container.Register<ICacheClient>(ServiceExtensions.DefaultCache); } if (!Container.Exists<MemoryCacheClient>()) Container.Register(ServiceExtensions.DefaultCache); if (Container.Exists<IMessageService>() && !Container.Exists<IMessageFactory>()) { Container.Register(c => c.Resolve<IMessageService>().MessageFactory); } if (Container.Exists<IUserAuthRepository>() && !Container.Exists<IAuthRepository>()) { Container.Register<IAuthRepository>(c => c.Resolve<IUserAuthRepository>()); } foreach (var callback in AfterInitCallbacks) { try { callback(this); } catch (Exception ex) { OnStartupException(ex); } } ReadyAt = DateTime.UtcNow; } private void ConfigurePlugins() { //Some plugins need to initialize before other plugins are registered. foreach (var plugin in Plugins) { var preInitPlugin = plugin as IPreInitPlugin; if (preInitPlugin != null) { try { preInitPlugin.Configure(this); } catch (Exception ex) { OnStartupException(ex); } } } } private void AfterPluginsLoaded(string specifiedContentType) { if (!String.IsNullOrEmpty(specifiedContentType)) config.DefaultContentType = specifiedContentType; else if (String.IsNullOrEmpty(config.DefaultContentType)) config.DefaultContentType = MimeTypes.Json; Config.PreferredContentTypes.Remove(Config.DefaultContentType); Config.PreferredContentTypes.Insert(0, Config.DefaultContentType); Config.PreferredContentTypesArray = Config.PreferredContentTypes.ToArray(); foreach (var plugin in Plugins) { var preInitPlugin = plugin as IPostInitPlugin; if (preInitPlugin != null) { try { preInitPlugin.AfterPluginsLoaded(this); } catch (Exception ex) { OnStartupException(ex); } } } ServiceController.AfterInit(); } public virtual void Release(object instance) { try { var iocAdapterReleases = Container.Adapter as IRelease; if (iocAdapterReleases != null) { iocAdapterReleases.Release(instance); } else { var disposable = instance as IDisposable; if (disposable != null) disposable.Dispose(); } } catch (Exception ex) { Log.Error("ServiceStackHost.Release", ex); } } public virtual void OnEndRequest(IRequest request = null) { try { var disposables = RequestContext.Instance.Items.Values; foreach (var item in disposables) { Release(item); } RequestContext.Instance.EndRequest(); foreach (var fn in OnEndRequestCallbacks) { fn(request); } } catch (Exception ex) { Log.Error("Error when Disposing Request Context", ex); } } public virtual void Register<T>(T instance) { this.Container.Register(instance); } public virtual void RegisterAs<T, TAs>() where T : TAs { this.Container.RegisterAutoWiredAs<T, TAs>(); } public virtual T TryResolve<T>() { return this.Container.TryResolve<T>(); } public virtual T Resolve<T>() { return this.Container.Resolve<T>(); } public T GetPlugin<T>() where T : class, IPlugin { return Plugins.FirstOrDefault(x => x is T) as T; } public bool HasPlugin<T>() where T : class, IPlugin { return Plugins.FirstOrDefault(x => x is T) != null; } public virtual IServiceRunner<TRequest> CreateServiceRunner<TRequest>(ActionContext actionContext) { //cached per service action return new ServiceRunner<TRequest>(this, actionContext); } public virtual string ResolveLocalizedString(string text, IRequest request) { return text; } public virtual string ResolveAbsoluteUrl(string virtualPath, IRequest httpReq) { if (httpReq == null) return (Config.WebHostUrl ?? "/").CombineWith(virtualPath.TrimStart('~')); return httpReq.GetAbsoluteUrl(virtualPath); //Http Listener, TODO: ASP.NET overrides } public virtual string ResolvePhysicalPath(string virtualPath, IRequest httpReq) { return VirtualFileSources.CombineVirtualPath(VirtualFileSources.RootDirectory.RealPath, virtualPath); } public virtual IVirtualFile ResolveVirtualFile(string virtualPath, IRequest httpReq) { return VirtualFileSources.GetFile(virtualPath); } public virtual IVirtualDirectory ResolveVirtualDirectory(string virtualPath, IRequest httpReq) { return virtualPath == VirtualFileSources.VirtualPathSeparator ? VirtualFileSources.RootDirectory : VirtualFileSources.GetDirectory(virtualPath); } public virtual IVirtualNode ResolveVirtualNode(string virtualPath, IRequest httpReq) { return (IVirtualNode)ResolveVirtualFile(virtualPath, httpReq) ?? ResolveVirtualDirectory(virtualPath, httpReq); } private bool delayLoadPlugin; public virtual void LoadPlugin(params IPlugin[] plugins) { if (delayLoadPlugin) { LoadPluginsInternal(plugins); Plugins.AddRange(plugins); } else { foreach (var plugin in plugins) { Plugins.Add(plugin); } } } internal virtual void LoadPluginsInternal(params IPlugin[] plugins) { foreach (var plugin in plugins) { try { plugin.Register(this); PluginsLoaded.Add(plugin.GetType().Name); } catch (Exception ex) { OnStartupException(ex); } } } public virtual object ExecuteService(object requestDto) { return ExecuteService(requestDto, RequestAttributes.None); } public virtual object ExecuteService(object requestDto, IRequest req) { return ServiceController.Execute(requestDto, req); } public virtual object ExecuteService(object requestDto, RequestAttributes requestAttributes) { return ServiceController.Execute(requestDto, new BasicRequest(requestDto, requestAttributes)); } public virtual object ExecuteMessage(IMessage mqMessage) { return ServiceController.ExecuteMessage(mqMessage, new BasicRequest(mqMessage)); } public virtual object ExecuteMessage(IMessage dto, IRequest req) { return ServiceController.ExecuteMessage(dto, req); } public virtual void RegisterService(Type serviceType, params string[] atRestPaths) { ServiceController.RegisterService(serviceType); var reqAttr = serviceType.FirstAttribute<DefaultRequestAttribute>(); if (reqAttr != null) { foreach (var atRestPath in atRestPaths) { if (atRestPath == null) continue; this.Routes.Add(reqAttr.RequestType, atRestPath, null); } } } public virtual RouteAttribute[] GetRouteAttributes(Type requestType) { return requestType.AllAttributes<RouteAttribute>(); } public virtual string GenerateWsdl(WsdlTemplateBase wsdlTemplate) { var wsdl = wsdlTemplate.ToString(); wsdl = wsdl.Replace("http://schemas.datacontract.org/2004/07/ServiceStack", Config.WsdlServiceNamespace); if (Config.WsdlServiceNamespace != HostConfig.DefaultWsdlNamespace) { wsdl = wsdl.Replace(HostConfig.DefaultWsdlNamespace, Config.WsdlServiceNamespace); } return wsdl; } public void RegisterTypedRequestFilter<T>(Action<IRequest, IResponse, T> filterFn) { GlobalTypedRequestFilters[typeof(T)] = new TypedFilter<T>(filterFn); } public void RegisterTypedResponseFilter<T>(Action<IRequest, IResponse, T> filterFn) { GlobalTypedResponseFilters[typeof(T)] = new TypedFilter<T>(filterFn); } public void RegisterTypedMessageRequestFilter<T>(Action<IRequest, IResponse, T> filterFn) { GlobalTypedMessageRequestFilters[typeof(T)] = new TypedFilter<T>(filterFn); } public void RegisterTypedMessageResponseFilter<T>(Action<IRequest, IResponse, T> filterFn) { GlobalTypedMessageResponseFilters[typeof(T)] = new TypedFilter<T>(filterFn); } public virtual void Dispose() { foreach (var callback in OnDisposeCallbacks) { callback(this); } if (Container != null) { Container.Dispose(); Container = null; } JsConfig.Reset(); //Clears Runtime Attributes Instance = null; } } }
37.502931
151
0.566177
[ "Apache-2.0" ]
ildarisaev/sandbox2
src/ServiceStack/ServiceStackHost.cs
31,140
C#
 namespace DesktopApp { partial class FormAcercaDe { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(FormAcercaDe)); this.groupBox1 = new System.Windows.Forms.GroupBox(); this.groupBox2 = new System.Windows.Forms.GroupBox(); this.groupBox3 = new System.Windows.Forms.GroupBox(); this.groupBox4 = new System.Windows.Forms.GroupBox(); this.btnClose = new System.Windows.Forms.Button(); this.pictureBox1 = new System.Windows.Forms.PictureBox(); this.label1 = new System.Windows.Forms.Label(); this.label2 = new System.Windows.Forms.Label(); this.label3 = new System.Windows.Forms.Label(); this.pictureBox2 = new System.Windows.Forms.PictureBox(); this.label4 = new System.Windows.Forms.Label(); this.label5 = new System.Windows.Forms.Label(); this.label6 = new System.Windows.Forms.Label(); this.label7 = new System.Windows.Forms.Label(); this.pictureBox3 = new System.Windows.Forms.PictureBox(); this.label8 = new System.Windows.Forms.Label(); this.label9 = new System.Windows.Forms.Label(); this.groupBox1.SuspendLayout(); this.groupBox2.SuspendLayout(); this.groupBox3.SuspendLayout(); this.groupBox4.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.pictureBox2)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.pictureBox3)).BeginInit(); this.SuspendLayout(); // // groupBox1 // this.groupBox1.Controls.Add(this.groupBox4); this.groupBox1.Controls.Add(this.groupBox3); this.groupBox1.Controls.Add(this.groupBox2); this.groupBox1.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(128)))), ((int)(((byte)(0))))); this.groupBox1.Location = new System.Drawing.Point(56, 46); this.groupBox1.Name = "groupBox1"; this.groupBox1.Size = new System.Drawing.Size(805, 404); this.groupBox1.TabIndex = 0; this.groupBox1.TabStop = false; this.groupBox1.Text = "Developers"; // // groupBox2 // this.groupBox2.Controls.Add(this.label3); this.groupBox2.Controls.Add(this.label2); this.groupBox2.Controls.Add(this.label1); this.groupBox2.Controls.Add(this.pictureBox1); this.groupBox2.ForeColor = System.Drawing.Color.White; this.groupBox2.Location = new System.Drawing.Point(33, 58); this.groupBox2.Name = "groupBox2"; this.groupBox2.Size = new System.Drawing.Size(227, 306); this.groupBox2.TabIndex = 0; this.groupBox2.TabStop = false; this.groupBox2.Text = "Edwin A. Roman"; // // groupBox3 // this.groupBox3.Controls.Add(this.label6); this.groupBox3.Controls.Add(this.label5); this.groupBox3.Controls.Add(this.pictureBox2); this.groupBox3.Controls.Add(this.label4); this.groupBox3.ForeColor = System.Drawing.Color.White; this.groupBox3.Location = new System.Drawing.Point(294, 58); this.groupBox3.Name = "groupBox3"; this.groupBox3.Size = new System.Drawing.Size(227, 306); this.groupBox3.TabIndex = 0; this.groupBox3.TabStop = false; this.groupBox3.Text = "Wilker"; // // groupBox4 // this.groupBox4.Controls.Add(this.label9); this.groupBox4.Controls.Add(this.label8); this.groupBox4.Controls.Add(this.label7); this.groupBox4.Controls.Add(this.pictureBox3); this.groupBox4.ForeColor = System.Drawing.Color.White; this.groupBox4.Location = new System.Drawing.Point(545, 58); this.groupBox4.Name = "groupBox4"; this.groupBox4.Size = new System.Drawing.Size(227, 306); this.groupBox4.TabIndex = 0; this.groupBox4.TabStop = false; this.groupBox4.Text = "Edwin L."; // // btnClose // this.btnClose.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.btnClose.FlatStyle = System.Windows.Forms.FlatStyle.Flat; this.btnClose.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.btnClose.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(128)))), ((int)(((byte)(0))))); this.btnClose.Location = new System.Drawing.Point(880, 12); this.btnClose.Name = "btnClose"; this.btnClose.Size = new System.Drawing.Size(26, 26); this.btnClose.TabIndex = 5; this.btnClose.Text = "X"; this.btnClose.UseVisualStyleBackColor = true; this.btnClose.Click += new System.EventHandler(this.btnClose_Click); // // pictureBox1 // this.pictureBox1.Image = ((System.Drawing.Image)(resources.GetObject("pictureBox1.Image"))); this.pictureBox1.Location = new System.Drawing.Point(54, 40); this.pictureBox1.Name = "pictureBox1"; this.pictureBox1.Size = new System.Drawing.Size(110, 110); this.pictureBox1.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage; this.pictureBox1.TabIndex = 0; this.pictureBox1.TabStop = false; // // label1 // this.label1.AutoSize = true; this.label1.Location = new System.Drawing.Point(18, 171); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(188, 13); this.label1.TabIndex = 1; this.label1.Text = "Name: Edwin Alberto Roman Seberino"; // // label2 // this.label2.AutoSize = true; this.label2.Location = new System.Drawing.Point(18, 202); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(116, 13); this.label2.TabIndex = 1; this.label2.Text = "Enrollmen: 2020-10233"; // // label3 // this.label3.AutoSize = true; this.label3.Location = new System.Drawing.Point(18, 236); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(146, 13); this.label3.TabIndex = 1; this.label3.Text = "Mail: 202010233@itla.edu.do"; // // pictureBox2 // this.pictureBox2.Location = new System.Drawing.Point(62, 40); this.pictureBox2.Name = "pictureBox2"; this.pictureBox2.Size = new System.Drawing.Size(110, 110); this.pictureBox2.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage; this.pictureBox2.TabIndex = 0; this.pictureBox2.TabStop = false; // // label4 // this.label4.AutoSize = true; this.label4.Location = new System.Drawing.Point(26, 171); this.label4.Name = "label4"; this.label4.Size = new System.Drawing.Size(92, 13); this.label4.TabIndex = 1; this.label4.Text = "Name: Wilker ------"; // // label5 // this.label5.AutoSize = true; this.label5.Location = new System.Drawing.Point(26, 202); this.label5.Name = "label5"; this.label5.Size = new System.Drawing.Size(104, 13); this.label5.TabIndex = 1; this.label5.Text = "Enrollmen: 2020-------"; // // label6 // this.label6.AutoSize = true; this.label6.Location = new System.Drawing.Point(26, 236); this.label6.Name = "label6"; this.label6.Size = new System.Drawing.Size(119, 13); this.label6.TabIndex = 1; this.label6.Text = "Mail: ---------@itla.edu.do"; // // label7 // this.label7.AutoSize = true; this.label7.Location = new System.Drawing.Point(27, 171); this.label7.Name = "label7"; this.label7.Size = new System.Drawing.Size(79, 13); this.label7.TabIndex = 1; this.label7.Text = "Name: Edwin L"; // // pictureBox3 // this.pictureBox3.Location = new System.Drawing.Point(63, 40); this.pictureBox3.Name = "pictureBox3"; this.pictureBox3.Size = new System.Drawing.Size(110, 110); this.pictureBox3.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage; this.pictureBox3.TabIndex = 0; this.pictureBox3.TabStop = false; // // label8 // this.label8.AutoSize = true; this.label8.Location = new System.Drawing.Point(27, 202); this.label8.Name = "label8"; this.label8.Size = new System.Drawing.Size(110, 13); this.label8.TabIndex = 1; this.label8.Text = "Enrollmen: 2020---------"; // // label9 // this.label9.AutoSize = true; this.label9.Location = new System.Drawing.Point(27, 236); this.label9.Name = "label9"; this.label9.Size = new System.Drawing.Size(125, 13); this.label9.TabIndex = 1; this.label9.Text = "Mail: -----------@itla.edu.do"; // // FormAcercaDe // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(21)))), ((int)(((byte)(48)))), ((int)(((byte)(68))))); this.ClientSize = new System.Drawing.Size(918, 497); this.Controls.Add(this.btnClose); this.Controls.Add(this.groupBox1); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None; this.Name = "FormAcercaDe"; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; this.Text = "Acerca de"; this.groupBox1.ResumeLayout(false); this.groupBox2.ResumeLayout(false); this.groupBox2.PerformLayout(); this.groupBox3.ResumeLayout(false); this.groupBox3.PerformLayout(); this.groupBox4.ResumeLayout(false); this.groupBox4.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.pictureBox2)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.pictureBox3)).EndInit(); this.ResumeLayout(false); } #endregion private System.Windows.Forms.GroupBox groupBox1; private System.Windows.Forms.GroupBox groupBox4; private System.Windows.Forms.GroupBox groupBox3; private System.Windows.Forms.GroupBox groupBox2; private System.Windows.Forms.Button btnClose; private System.Windows.Forms.Label label3; private System.Windows.Forms.Label label2; private System.Windows.Forms.Label label1; private System.Windows.Forms.PictureBox pictureBox1; private System.Windows.Forms.Label label9; private System.Windows.Forms.Label label8; private System.Windows.Forms.Label label7; private System.Windows.Forms.PictureBox pictureBox3; private System.Windows.Forms.Label label6; private System.Windows.Forms.Label label5; private System.Windows.Forms.PictureBox pictureBox2; private System.Windows.Forms.Label label4; } }
47.180212
167
0.578041
[ "MIT" ]
Edwinroman30/Prog_2_PracticaFinal
Prog_2_PracticaFinal(net4.8)/DesktopApp/FormAcercaDe.Designer.cs
13,354
C#
using System; using System.Collections.Generic; namespace CometFlavor.Extensions.Linq; /// <summary> /// IEnumerable{T} に対する拡張メソッド /// </summary> public static class EnumerableExtensions { /// <summary> /// シーケンスのフィルタと条件に適合しない場合のアクションを指定するオペレータ。 /// </summary> /// <typeparam name="TSource">シーケンスの要素型</typeparam> /// <param name="self">対象シーケンス</param> /// <param name="predicate">要素の通過判定処理</param> /// <param name="skipped">要素が通過しない場合に呼び出される処理</param> /// <returns>フィルタされたシーケンス</returns> public static IEnumerable<TSource> WhereElse<TSource>(this IEnumerable<TSource> self, Func<TSource, bool> predicate, Action<TSource> skipped) { foreach (var item in self) { if (predicate(item)) { yield return item; } else { skipped(item); } } } }
26.764706
145
0.593407
[ "MIT" ]
toras9000/CometFlavor
CometFlavor/Extensions/Linq/EnumerableExtensions.cs
1,120
C#
using System; namespace WatsonConnection { public class Class1 { } }
9.222222
26
0.638554
[ "Apache-2.0" ]
juliarezender/api-person
WatsonConnection/Class1.cs
85
C#
//----------------------------------------------------------------------- // Copyright 2017 Roman Tumaykin // // 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.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("SsisBuild.Tests.Helpers")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("SsisBuild.Tests.Helpers")] [assembly: AssemblyCopyright("Copyright © 2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("17afe8ad-f52e-44e5-b0f6-1b24f17edb1b")] // 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")]
41.153846
84
0.685514
[ "Apache-2.0" ]
ConstantineK/ssis-build
src/SsisBuild.Tests.Helpers/Properties/AssemblyInfo.cs
2,143
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using Cake.Common.IO; using Cake.Common.Tools.DotNetCore.Build; using Cake.Common.Tools.DotNetCore.BuildServer; using Cake.Common.Tools.DotNetCore.Clean; using Cake.Common.Tools.DotNetCore.Execute; using Cake.Common.Tools.DotNetCore.MSBuild; using Cake.Common.Tools.DotNetCore.NuGet.Delete; using Cake.Common.Tools.DotNetCore.NuGet.Push; using Cake.Common.Tools.DotNetCore.NuGet.Source; using Cake.Common.Tools.DotNetCore.Pack; using Cake.Common.Tools.DotNetCore.Publish; using Cake.Common.Tools.DotNetCore.Restore; using Cake.Common.Tools.DotNetCore.Run; using Cake.Common.Tools.DotNetCore.Test; using Cake.Common.Tools.DotNetCore.Tool; using Cake.Common.Tools.DotNetCore.VSTest; using Cake.Core; using Cake.Core.Annotations; using Cake.Core.IO; namespace Cake.Common.Tools.DotNetCore { /// <summary> /// <para>Contains functionality related to <see href="https://github.com/dotnet/cli">.NET Core CLI</see>.</para> /// <para> /// In order to use the commands for this alias, the .Net Core CLI tools will need to be installed on the machine where /// the Cake script is being executed. See this <see href="https://www.microsoft.com/net/core">page</see> for information /// on how to install. /// </para> /// </summary> [CakeAliasCategory("DotNetCore")] public static class DotNetCoreAliases { /// <summary> /// Execute an assembly. /// </summary> /// <param name="context">The context.</param> /// <param name="assemblyPath">The assembly path.</param> /// <example> /// <code> /// DotNetCoreExecute("./bin/Debug/app.dll"); /// </code> /// </example> [CakeMethodAlias] [CakeAliasCategory("Execute")] [CakeNamespaceImport("Cake.Common.Tools.DotNetCore.Execute")] public static void DotNetCoreExecute(this ICakeContext context, FilePath assemblyPath) { context.DotNetCoreExecute(assemblyPath, null); } /// <summary> /// Execute an assembly with arguments in the specific path. /// </summary> /// <param name="context">The context.</param> /// <param name="assemblyPath">The assembly path.</param> /// <param name="arguments">The arguments.</param> /// <example> /// <code> /// DotNetCoreExecute("./bin/Debug/app.dll", "--arg"); /// </code> /// </example> [CakeMethodAlias] [CakeAliasCategory("Execute")] [CakeNamespaceImport("Cake.Common.Tools.DotNetCore.Execute")] public static void DotNetCoreExecute(this ICakeContext context, FilePath assemblyPath, ProcessArgumentBuilder arguments) { context.DotNetCoreExecute(assemblyPath, arguments, null); } /// <summary> /// Execute an assembly with arguments in the specific path with settings. /// </summary> /// <param name="context">The context.</param> /// <param name="assemblyPath">The assembly path.</param> /// <param name="arguments">The arguments.</param> /// <param name="settings">The settings.</param> /// <example> /// <code> /// var settings = new DotNetCoreExecuteSettings /// { /// FrameworkVersion = "1.0.3" /// }; /// /// DotNetCoreExecute("./bin/Debug/app.dll", "--arg", settings); /// </code> /// </example> [CakeMethodAlias] [CakeAliasCategory("Execute")] [CakeNamespaceImport("Cake.Common.Tools.DotNetCore.Execute")] public static void DotNetCoreExecute(this ICakeContext context, FilePath assemblyPath, ProcessArgumentBuilder arguments, DotNetCoreExecuteSettings settings) { if (context == null) { throw new ArgumentNullException(nameof(context)); } if (assemblyPath == null) { throw new ArgumentNullException(nameof(assemblyPath)); } if (settings == null) { settings = new DotNetCoreExecuteSettings(); } var executor = new DotNetCoreExecutor(context.FileSystem, context.Environment, context.ProcessRunner, context.Tools); executor.Execute(assemblyPath, arguments, settings); } /// <summary> /// Restore all NuGet Packages. /// </summary> /// <param name="context">The context.</param> /// <example> /// <code> /// DotNetCoreRestore(); /// </code> /// </example> [CakeMethodAlias] [CakeAliasCategory("Restore")] [CakeNamespaceImport("Cake.Common.Tools.DotNetCore.Restore")] public static void DotNetCoreRestore(this ICakeContext context) { context.DotNetCoreRestore(null, null); } /// <summary> /// Restore all NuGet Packages in the specified path. /// </summary> /// <param name="context">The context.</param> /// <param name="root">List of projects and project folders to restore. Each value can be: a path to a project.json or global.json file, or a folder to recursively search for project.json files.</param> /// <example> /// <code> /// DotNetCoreRestore("./src/*"); /// </code> /// </example> [CakeMethodAlias] [CakeAliasCategory("Restore")] [CakeNamespaceImport("Cake.Common.Tools.DotNetCore.Restore")] public static void DotNetCoreRestore(this ICakeContext context, string root) { context.DotNetCoreRestore(root, null); } /// <summary> /// Restore all NuGet Packages with the settings. /// </summary> /// <param name="context">The context.</param> /// <param name="settings">The settings.</param> /// <example> /// <code> /// var settings = new DotNetCoreRestoreSettings /// { /// Sources = new[] {"https://www.example.com/nugetfeed", "https://www.example.com/nugetfeed2"}, /// FallbackSources = new[] {"https://www.example.com/fallbacknugetfeed"}, /// PackagesDirectory = "./packages", /// Verbosity = Information, /// DisableParallel = true, /// InferRuntimes = new[] {"runtime1", "runtime2"} /// }; /// /// DotNetCoreRestore(settings); /// </code> /// </example> [CakeMethodAlias] [CakeAliasCategory("Restore")] [CakeNamespaceImport("Cake.Common.Tools.DotNetCore.Restore")] public static void DotNetCoreRestore(this ICakeContext context, DotNetCoreRestoreSettings settings) { context.DotNetCoreRestore(null, settings); } /// <summary> /// Restore all NuGet Packages in the specified path with settings. /// </summary> /// <param name="context">The context.</param> /// <param name="root">List of projects and project folders to restore. Each value can be: a path to a project.json or global.json file, or a folder to recursively search for project.json files.</param> /// <param name="settings">The settings.</param> /// <example> /// <code> /// var settings = new DotNetCoreRestoreSettings /// { /// Sources = new[] {"https://www.example.com/nugetfeed", "https://www.example.com/nugetfeed2"}, /// FallbackSources = new[] {"https://www.example.com/fallbacknugetfeed"}, /// PackagesDirectory = "./packages", /// Verbosity = Information, /// DisableParallel = true, /// InferRuntimes = new[] {"runtime1", "runtime2"} /// }; /// /// DotNetCoreRestore("./src/*", settings); /// </code> /// </example> [CakeMethodAlias] [CakeAliasCategory("Restore")] [CakeNamespaceImport("Cake.Common.Tools.DotNetCore.Restore")] public static void DotNetCoreRestore(this ICakeContext context, string root, DotNetCoreRestoreSettings settings) { if (context == null) { throw new ArgumentNullException(nameof(context)); } if (settings == null) { settings = new DotNetCoreRestoreSettings(); } var restorer = new DotNetCoreRestorer(context.FileSystem, context.Environment, context.ProcessRunner, context.Tools, context.Log); restorer.Restore(root, settings); } /// <summary> /// Build all projects. /// </summary> /// <param name="context">The context.</param> /// <param name="project">The projects path.</param> /// <example> /// <code> /// DotNetCoreBuild("./src/*"); /// </code> /// </example> [CakeMethodAlias] [CakeAliasCategory("Build")] [CakeNamespaceImport("Cake.Common.Tools.DotNetCore.Build")] public static void DotNetCoreBuild(this ICakeContext context, string project) { context.DotNetCoreBuild(project, null); } /// <summary> /// Build all projects. /// </summary> /// <param name="context">The context.</param> /// <param name="project">The projects path.</param> /// <param name="settings">The settings.</param> /// <example> /// <code> /// var settings = new DotNetCoreBuildSettings /// { /// Framework = "netcoreapp2.0", /// Configuration = "Debug", /// OutputDirectory = "./artifacts/" /// }; /// /// DotNetCoreBuild("./src/*", settings); /// </code> /// </example> [CakeMethodAlias] [CakeAliasCategory("Build")] [CakeNamespaceImport("Cake.Common.Tools.DotNetCore.Build")] public static void DotNetCoreBuild(this ICakeContext context, string project, DotNetCoreBuildSettings settings) { if (context == null) { throw new ArgumentNullException(nameof(context)); } if (settings == null) { settings = new DotNetCoreBuildSettings(); } var builder = new DotNetCoreBuilder(context.FileSystem, context.Environment, context.ProcessRunner, context.Tools); builder.Build(project, settings); } /// <summary> /// Package all projects. /// </summary> /// <param name="context">The context.</param> /// <param name="project">The projects path.</param> /// <example> /// <code> /// DotNetCorePack("./src/*"); /// </code> /// </example> [CakeMethodAlias] [CakeAliasCategory("Pack")] [CakeNamespaceImport("Cake.Common.Tools.DotNetCore.Pack")] public static void DotNetCorePack(this ICakeContext context, string project) { context.DotNetCorePack(project, null); } /// <summary> /// Package all projects. /// </summary> /// <param name="context">The context.</param> /// <param name="project">The projects path.</param> /// <param name="settings">The settings.</param> /// <example> /// <code> /// var settings = new DotNetCorePackSettings /// { /// Configuration = "Release", /// OutputDirectory = "./artifacts/" /// }; /// /// DotNetCorePack("./src/*", settings); /// </code> /// </example> [CakeMethodAlias] [CakeAliasCategory("Pack")] [CakeNamespaceImport("Cake.Common.Tools.DotNetCore.Pack")] public static void DotNetCorePack(this ICakeContext context, string project, DotNetCorePackSettings settings) { if (context == null) { throw new ArgumentNullException(nameof(context)); } if (settings == null) { settings = new DotNetCorePackSettings(); } var packer = new DotNetCorePacker(context.FileSystem, context.Environment, context.ProcessRunner, context.Tools); packer.Pack(project, settings); } /// <summary> /// Run all projects. /// </summary> /// <param name="context">The context.</param> /// <example> /// <code> /// DotNetCoreRun(); /// </code> /// </example> [CakeMethodAlias] [CakeAliasCategory("Run")] [CakeNamespaceImport("Cake.Common.Tools.DotNetCore.Run")] public static void DotNetCoreRun(this ICakeContext context) { context.DotNetCoreRun(null, null, null); } /// <summary> /// Run project. /// </summary> /// <param name="context">The context.</param> /// <param name="project">The project path.</param> /// <example> /// <code> /// DotNetCoreRun("./src/Project"); /// </code> /// </example> [CakeMethodAlias] [CakeAliasCategory("Run")] [CakeNamespaceImport("Cake.Common.Tools.DotNetCore.Run")] public static void DotNetCoreRun(this ICakeContext context, string project) { context.DotNetCoreRun(project, null, null); } /// <summary> /// Run project with path and arguments. /// </summary> /// <param name="context">The context.</param> /// <param name="project">The project path.</param> /// <param name="arguments">The arguments.</param> /// <example> /// <code> /// DotNetCoreRun("./src/Project", "--args"); /// </code> /// </example> [CakeMethodAlias] [CakeAliasCategory("Run")] [CakeNamespaceImport("Cake.Common.Tools.DotNetCore.Run")] public static void DotNetCoreRun(this ICakeContext context, string project, ProcessArgumentBuilder arguments) { context.DotNetCoreRun(project, arguments, null); } /// <summary> /// Run project with settings. /// </summary> /// <param name="context">The context.</param> /// <param name="project">The project path.</param> /// <param name="arguments">The arguments.</param> /// <param name="settings">The settings.</param> /// <example> /// <code> /// var settings = new DotNetCoreRunSettings /// { /// Framework = "netcoreapp2.0", /// Configuration = "Release" /// }; /// /// DotNetCoreRun("./src/Project", "--args", settings); /// </code> /// </example> [CakeMethodAlias] [CakeAliasCategory("Run")] [CakeNamespaceImport("Cake.Common.Tools.DotNetCore.Run")] public static void DotNetCoreRun(this ICakeContext context, string project, ProcessArgumentBuilder arguments, DotNetCoreRunSettings settings) { if (context == null) { throw new ArgumentNullException(nameof(context)); } if (settings == null) { settings = new DotNetCoreRunSettings(); } var runner = new DotNetCoreRunner(context.FileSystem, context.Environment, context.ProcessRunner, context.Tools); runner.Run(project, arguments, settings); } /// <summary> /// Publish all projects. /// </summary> /// <param name="context">The context.</param> /// <param name="project">The projects path.</param> /// <example> /// <code> /// DotNetCorePublish("./src/*"); /// </code> /// </example> [CakeMethodAlias] [CakeAliasCategory("Publish")] [CakeNamespaceImport("Cake.Common.Tools.DotNetCore.Publish")] public static void DotNetCorePublish(this ICakeContext context, string project) { context.DotNetCorePublish(project, null); } /// <summary> /// Publish all projects. /// </summary> /// <param name="context">The context.</param> /// <param name="project">The projects path.</param> /// <param name="settings">The settings.</param> /// <example> /// <code> /// var settings = new DotNetCorePublishSettings /// { /// Framework = "netcoreapp2.0", /// Configuration = "Release", /// OutputDirectory = "./artifacts/" /// }; /// /// DotNetCorePublish("./src/*", settings); /// </code> /// </example> [CakeMethodAlias] [CakeAliasCategory("Publish")] [CakeNamespaceImport("Cake.Common.Tools.DotNetCore.Publish")] public static void DotNetCorePublish(this ICakeContext context, string project, DotNetCorePublishSettings settings) { if (context == null) { throw new ArgumentNullException(nameof(context)); } if (settings == null) { settings = new DotNetCorePublishSettings(); } var publisher = new DotNetCorePublisher(context.FileSystem, context.Environment, context.ProcessRunner, context.Tools); publisher.Publish(project, settings); } /// <summary> /// Test project. /// </summary> /// <param name="context">The context.</param> /// <example> /// <code> /// DotNetCoreTest(); /// </code> /// </example> [CakeMethodAlias] [CakeAliasCategory("Test")] [CakeNamespaceImport("Cake.Common.Tools.DotNetCore.Test")] public static void DotNetCoreTest(this ICakeContext context) { context.DotNetCoreTest(null, null, null); } /// <summary> /// Test project with path. /// </summary> /// <param name="context">The context.</param> /// <param name="project">The project path.</param> /// <example> /// <para>Specify the path to the .csproj file in the test project.</para> /// <code> /// DotNetCoreTest("./test/Project.Tests/Project.Tests.csproj"); /// </code> /// <para>You could also specify a task that runs multiple test projects.</para> /// <para>Cake task:</para> /// <code> /// Task("Test") /// .Does(() => /// { /// var projectFiles = GetFiles("./test/**/*.csproj"); /// foreach(var file in projectFiles) /// { /// DotNetCoreTest(file.FullPath); /// } /// }); /// </code> /// <para>If your test project is using project.json, the project parameter should just be the directory path.</para> /// <code> /// DotNetCoreTest("./test/Project.Tests/"); /// </code> /// </example> [CakeMethodAlias] [CakeAliasCategory("Test")] [CakeNamespaceImport("Cake.Common.Tools.DotNetCore.Test")] public static void DotNetCoreTest(this ICakeContext context, string project) { context.DotNetCoreTest(project, null, null); } /// <summary> /// Test project with settings. /// </summary> /// <param name="context">The context.</param> /// <param name="project">The project path.</param> /// <param name="settings">The settings.</param> /// <example> /// <code> /// var settings = new DotNetCoreTestSettings /// { /// Configuration = "Release" /// }; /// /// DotNetCoreTest("./test/Project.Tests/Project.Tests.csproj", settings); /// </code> /// <para>You could also specify a task that runs multiple test projects.</para> /// <para>Cake task:</para> /// <code> /// Task("Test") /// .Does(() => /// { /// var settings = new DotNetCoreTestSettings /// { /// Configuration = "Release" /// }; /// /// var projectFiles = GetFiles("./test/**/*.csproj"); /// foreach(var file in projectFiles) /// { /// DotNetCoreTest(file.FullPath, settings); /// } /// }); /// </code> /// <para>If your test project is using project.json, the project parameter should just be the directory path.</para> /// <code> /// var settings = new DotNetCoreTestSettings /// { /// Configuration = "Release" /// }; /// /// DotNetCoreTest("./test/Project.Tests/", settings); /// </code> /// </example> [CakeMethodAlias] [CakeAliasCategory("Test")] [CakeNamespaceImport("Cake.Common.Tools.DotNetCore.Test")] public static void DotNetCoreTest(this ICakeContext context, string project, DotNetCoreTestSettings settings) { context.DotNetCoreTest(project, null, settings); } /// <summary> /// Test project with settings. /// </summary> /// <param name="context">The context.</param> /// <param name="project">The project path.</param> /// <param name="arguments">The arguments.</param> /// <param name="settings">The settings.</param> /// <example> /// <code> /// var settings = new DotNetCoreTestSettings /// { /// Configuration = "Release" /// }; /// /// DotNetCoreTest("./test/Project.Tests/Project.Tests.csproj", settings); /// </code> /// <para>You could also specify a task that runs multiple test projects.</para> /// <para>Cake task:</para> /// <code> /// Task("Test") /// .Does(() => /// { /// var settings = new DotNetCoreTestSettings /// { /// Configuration = "Release" /// }; /// /// var projectFiles = GetFiles("./test/**/*.csproj"); /// foreach(var file in projectFiles) /// { /// DotNetCoreTest(file.FullPath, "MSTest.MapInconclusiveToFailed=true", settings); /// } /// }); /// </code> /// <para>If your test project is using project.json, the project parameter should just be the directory path.</para> /// <code> /// var settings = new DotNetCoreTestSettings /// { /// Configuration = "Release" /// }; /// /// DotNetCoreTest("./test/Project.Tests/", "MSTest.MapInconclusiveToFailed=true", settings); /// </code> /// </example> [CakeMethodAlias] [CakeAliasCategory("Test")] [CakeNamespaceImport("Cake.Common.Tools.DotNetCore.Test")] public static void DotNetCoreTest(this ICakeContext context, string project, ProcessArgumentBuilder arguments, DotNetCoreTestSettings settings) { if (context == null) { throw new ArgumentNullException(nameof(context)); } if (settings == null) { settings = new DotNetCoreTestSettings(); } var tester = new DotNetCoreTester(context.FileSystem, context.Environment, context.ProcessRunner, context.Tools); tester.Test(project, arguments, settings); } /// <summary> /// Cleans a project's output. /// </summary> /// <param name="context">The context.</param> /// <param name="project">The project's path.</param> /// <example> /// <code> /// DotNetCoreClean("./src/project"); /// </code> /// </example> [CakeMethodAlias] [CakeAliasCategory("Clean")] [CakeNamespaceImport("Cake.Common.Tools.DotNetCore.Clean")] public static void DotNetCoreClean(this ICakeContext context, string project) { context.DotNetCoreClean(project, null); } /// <summary> /// Cleans a project's output. /// </summary> /// <param name="context">The context.</param> /// <param name="project">The projects path.</param> /// <param name="settings">The settings.</param> /// <example> /// <code> /// var settings = new DotNetCoreCleanSettings /// { /// Framework = "netcoreapp2.0", /// Configuration = "Debug", /// OutputDirectory = "./artifacts/" /// }; /// /// DotNetCoreClean("./src/project", settings); /// </code> /// </example> [CakeMethodAlias] [CakeAliasCategory("Clean")] [CakeNamespaceImport("Cake.Common.Tools.DotNetCore.Clean")] public static void DotNetCoreClean(this ICakeContext context, string project, DotNetCoreCleanSettings settings) { if (context == null) { throw new ArgumentNullException(nameof(context)); } if (settings == null) { settings = new DotNetCoreCleanSettings(); } var cleaner = new DotNetCoreCleaner(context.FileSystem, context.Environment, context.ProcessRunner, context.Tools); cleaner.Clean(project, settings); } /// <summary> /// Delete a NuGet Package from a server. /// </summary> /// <param name="context">The context.</param> /// <example> /// <code> /// DotNetCoreNuGetDelete(); /// </code> /// </example> [CakeMethodAlias] [CakeAliasCategory("NuGet")] [CakeNamespaceImport("Cake.Common.Tools.DotNetCore.NuGet.Delete")] public static void DotNetCoreNuGetDelete(this ICakeContext context) { context.DotNetCoreNuGetDelete(null, null, null); } /// <summary> /// Deletes a package from nuget.org. /// </summary> /// <param name="context">The context.</param> /// <param name="packageName">Name of package to delete.</param> /// <example> /// <code> /// DotNetCoreNuGetDelete("Microsoft.AspNetCore.Mvc"); /// </code> /// </example> [CakeMethodAlias] [CakeAliasCategory("NuGet")] [CakeNamespaceImport("Cake.Common.Tools.DotNetCore.NuGet.Delete")] public static void DotNetCoreNuGetDelete(this ICakeContext context, string packageName) { context.DotNetCoreNuGetDelete(packageName, null, null); } /// <summary> /// Deletes a specific version of a package from nuget.org. /// </summary> /// <param name="context">The context.</param> /// <param name="packageName">Name of package to delete.</param> /// <param name="packageVersion">Version of package to delete.</param> /// <example> /// <code> /// DotNetCoreRestore("Microsoft.AspNetCore.Mvc", "1.0"); /// </code> /// </example> [CakeMethodAlias] [CakeAliasCategory("NuGet")] [CakeNamespaceImport("Cake.Common.Tools.DotNetCore.NuGet.Delete")] public static void DotNetCoreNuGetDelete(this ICakeContext context, string packageName, string packageVersion) { context.DotNetCoreNuGetDelete(packageName, packageVersion, null); } /// <summary> /// Deletes a package from a server. /// </summary> /// <param name="context">The context.</param> /// <param name="packageName">Name of package to delete.</param> /// <param name="settings">The settings.</param> /// <example> /// <code> /// var settings = new DotNetCoreNuGetDeleteSettings /// { /// Source = "https://www.example.com/nugetfeed", /// NonInteractive = true /// }; /// /// DotNetCoreNuGetDelete("Microsoft.AspNetCore.Mvc", settings); /// </code> /// </example> [CakeMethodAlias] [CakeAliasCategory("NuGet")] [CakeNamespaceImport("Cake.Common.Tools.DotNetCore.NuGet.Delete")] public static void DotNetCoreNuGetDelete(this ICakeContext context, string packageName, DotNetCoreNuGetDeleteSettings settings) { context.DotNetCoreNuGetDelete(packageName, null, settings); } /// <summary> /// Deletes a package from a server using the specified settings. /// </summary> /// <param name="context">The context.</param> /// <param name="settings">The settings.</param> /// <example> /// <code> /// var settings = new DotNetCoreNuGetDeleteSettings /// { /// Source = "https://www.example.com/nugetfeed", /// NonInteractive = true /// }; /// /// DotNetCoreNuGetDelete(settings); /// </code> /// </example> [CakeMethodAlias] [CakeAliasCategory("NuGet")] [CakeNamespaceImport("Cake.Common.Tools.DotNetCore.NuGet.Delete")] public static void DotNetCoreNuGetDelete(this ICakeContext context, DotNetCoreNuGetDeleteSettings settings) { context.DotNetCoreNuGetDelete(null, null, settings); } /// <summary> /// Deletes a package from a server using the specified settings. /// </summary> /// <param name="context">The context.</param> /// <param name="packageName">Name of package to delete.</param> /// <param name="packageVersion">Version of package to delete.</param> /// <param name="settings">The settings.</param> /// <example> /// <code> /// var settings = new DotNetCoreNuGetDeleteSettings /// { /// Source = "https://www.example.com/nugetfeed", /// NonInteractive = true /// }; /// /// DotNetCoreNuGetDelete("Microsoft.AspNetCore.Mvc", "1.0", settings); /// </code> /// </example> [CakeMethodAlias] [CakeAliasCategory("NuGet")] [CakeNamespaceImport("Cake.Common.Tools.DotNetCore.NuGet.Delete")] public static void DotNetCoreNuGetDelete(this ICakeContext context, string packageName, string packageVersion, DotNetCoreNuGetDeleteSettings settings) { if (context == null) { throw new ArgumentNullException(nameof(context)); } if (settings == null) { settings = new DotNetCoreNuGetDeleteSettings(); } var nugetDeleter = new DotNetCoreNuGetDeleter(context.FileSystem, context.Environment, context.ProcessRunner, context.Tools); nugetDeleter.Delete(packageName, packageVersion, settings); } /// <summary> /// Pushes one or more packages to a server. /// </summary> /// <param name="context">The context.</param> /// <param name="packageName">Name of package to push.</param> /// <example> /// <code> /// DotNetCoreNuGetPush("*.nupkg"); /// </code> /// </example> [CakeMethodAlias] [CakeAliasCategory("NuGet")] [CakeNamespaceImport("Cake.Common.Tools.DotNetCore.NuGet.Push")] public static void DotNetCoreNuGetPush(this ICakeContext context, string packageName) { context.DotNetCoreNuGetPush(packageName, null); } /// <summary> /// Pushes one or more packages to a server using the specified settings. /// </summary> /// <param name="context">The context.</param> /// <param name="packageName">Name of package to push.</param> /// <param name="settings">The settings.</param> /// <example> /// <code> /// var settings = new DotNetCoreNuGetPushSettings /// { /// Source = "https://www.example.com/nugetfeed", /// ApiKey = "4003d786-cc37-4004-bfdf-c4f3e8ef9b3a" /// }; /// /// DotNetCoreNuGetPush("foo*.nupkg", settings); /// </code> /// </example> [CakeMethodAlias] [CakeAliasCategory("NuGet")] [CakeNamespaceImport("Cake.Common.Tools.DotNetCore.NuGet.Push")] public static void DotNetCoreNuGetPush(this ICakeContext context, string packageName, DotNetCoreNuGetPushSettings settings) { if (context == null) { throw new ArgumentNullException(nameof(context)); } if (settings == null) { settings = new DotNetCoreNuGetPushSettings(); } var restorer = new DotNetCoreNuGetPusher(context.FileSystem, context.Environment, context.ProcessRunner, context.Tools); restorer.Push(packageName, settings); } /// <summary> /// Add the specified NuGet source. /// </summary> /// <param name="context">The context.</param> /// <param name="name">The name of the source.</param> /// <param name="settings">The settings.</param> /// <example> /// <code> /// var settings = new DotNetCoreNuGetSourceSettings /// { /// Source = "https://www.example.com/nugetfeed", /// UserName = "username", /// Password = "password", /// StorePasswordInClearText = true, /// ValidAuthenticationTypes = "basic,negotiate" /// }; /// /// DotNetCoreNuGetAddSource("example", settings); /// </code> /// </example> [CakeMethodAlias] [CakeAliasCategory("NuGet")] [CakeNamespaceImport("Cake.Common.Tools.DotNetCore.NuGet.Source")] public static void DotNetCoreNuGetAddSource(this ICakeContext context, string name, DotNetCoreNuGetSourceSettings settings) { if (context == null) { throw new ArgumentNullException(nameof(context)); } var sourcer = new DotNetCoreNuGetSourcer(context.FileSystem, context.Environment, context.ProcessRunner, context.Tools); sourcer.AddSource(name, settings); } /// <summary> /// Disable the specified NuGet source. /// </summary> /// <param name="context">The context.</param> /// <param name="name">The name of the source.</param> /// <example> /// <code> /// DotNetCoreNuGetDisableSource("example"); /// </code> /// </example> [CakeMethodAlias] [CakeAliasCategory("NuGet")] [CakeNamespaceImport("Cake.Common.Tools.DotNetCore.NuGet.Source")] public static void DotNetCoreNuGetDisableSource(this ICakeContext context, string name) { context.DotNetCoreNuGetDisableSource(name, null); } /// <summary> /// Disable the specified NuGet source. /// </summary> /// <param name="context">The context.</param> /// <param name="name">The name of the source.</param> /// <param name="settings">The settings.</param> /// <example> /// <code> /// var settings = new DotNetCoreNuGetSourceSettings /// { /// ConfigFile = "NuGet.config" /// }; /// /// DotNetCoreNuGetDisableSource("example", settings); /// </code> /// </example> [CakeMethodAlias] [CakeAliasCategory("NuGet")] [CakeNamespaceImport("Cake.Common.Tools.DotNetCore.NuGet.Source")] public static void DotNetCoreNuGetDisableSource(this ICakeContext context, string name, DotNetCoreNuGetSourceSettings settings) { if (context == null) { throw new ArgumentNullException(nameof(context)); } var sourcer = new DotNetCoreNuGetSourcer(context.FileSystem, context.Environment, context.ProcessRunner, context.Tools); sourcer.DisableSource(name, settings ?? new DotNetCoreNuGetSourceSettings()); } /// <summary> /// Enable the specified NuGet source. /// </summary> /// <param name="context">The context.</param> /// <param name="name">The name of the source.</param> /// <example> /// <code> /// DotNetCoreNuGetEnableSource("example"); /// </code> /// </example> [CakeMethodAlias] [CakeAliasCategory("NuGet")] [CakeNamespaceImport("Cake.Common.Tools.DotNetCore.NuGet.Source")] public static void DotNetCoreNuGetEnableSource(this ICakeContext context, string name) { context.DotNetCoreNuGetEnableSource(name, null); } /// <summary> /// Enable the specified NuGet source. /// </summary> /// <param name="context">The context.</param> /// <param name="name">The name of the source.</param> /// <param name="settings">The settings.</param> /// <example> /// <code> /// var settings = new DotNetCoreNuGetSourceSettings /// { /// ConfigFile = "NuGet.config" /// }; /// /// DotNetCoreNuGetEnableSource("example", settings); /// </code> /// </example> [CakeMethodAlias] [CakeAliasCategory("NuGet")] [CakeNamespaceImport("Cake.Common.Tools.DotNetCore.NuGet.Source")] public static void DotNetCoreNuGetEnableSource(this ICakeContext context, string name, DotNetCoreNuGetSourceSettings settings) { if (context == null) { throw new ArgumentNullException(nameof(context)); } var sourcer = new DotNetCoreNuGetSourcer(context.FileSystem, context.Environment, context.ProcessRunner, context.Tools); sourcer.EnableSource(name, settings ?? new DotNetCoreNuGetSourceSettings()); } /// <summary> /// Determines whether the specified NuGet source exists. /// </summary> /// <param name="context">The context.</param> /// <param name="name">The name of the source.</param> /// <returns>Whether the specified NuGet source exists.</returns> /// <example> /// <code> /// var exists = DotNetCoreNuGetHasSource("example"); /// </code> /// </example> [CakeMethodAlias] [CakeAliasCategory("NuGet")] [CakeNamespaceImport("Cake.Common.Tools.DotNetCore.NuGet.Source")] public static bool DotNetCoreNuGetHasSource(this ICakeContext context, string name) { return context.DotNetCoreNuGetHasSource(name, null); } /// <summary> /// Determines whether the specified NuGet source exists. /// </summary> /// <param name="context">The context.</param> /// <param name="name">The name of the source.</param> /// <param name="settings">The settings.</param> /// <returns>Whether the specified NuGet source exists.</returns> /// <example> /// <code> /// var settings = new DotNetCoreNuGetSourceSettings /// { /// ConfigFile = "NuGet.config" /// }; /// /// var exists = DotNetCoreNuGetHasSource("example", settings); /// </code> /// </example> [CakeMethodAlias] [CakeAliasCategory("NuGet")] [CakeNamespaceImport("Cake.Common.Tools.DotNetCore.NuGet.Source")] public static bool DotNetCoreNuGetHasSource(this ICakeContext context, string name, DotNetCoreNuGetSourceSettings settings) { if (context == null) { throw new ArgumentNullException(nameof(context)); } var sourcer = new DotNetCoreNuGetSourcer(context.FileSystem, context.Environment, context.ProcessRunner, context.Tools); return sourcer.HasSource(name, settings ?? new DotNetCoreNuGetSourceSettings()); } /// <summary> /// Remove the specified NuGet source. /// </summary> /// <param name="context">The context.</param> /// <param name="name">The name of the source.</param> /// <example> /// <code> /// DotNetCoreNuGetRemoveSource("example"); /// </code> /// </example> [CakeMethodAlias] [CakeAliasCategory("NuGet")] [CakeNamespaceImport("Cake.Common.Tools.DotNetCore.NuGet.Source")] public static void DotNetCoreNuGetRemoveSource(this ICakeContext context, string name) { context.DotNetCoreNuGetRemoveSource(name, null); } /// <summary> /// Remove the specified NuGet source. /// </summary> /// <param name="context">The context.</param> /// <param name="name">The name of the source.</param> /// <param name="settings">The settings.</param> /// <example> /// <code> /// var settings = new DotNetCoreNuGetSourceSettings /// { /// ConfigFile = "NuGet.config" /// }; /// /// DotNetCoreNuGetRemoveSource("example", settings); /// </code> /// </example> [CakeMethodAlias] [CakeAliasCategory("NuGet")] [CakeNamespaceImport("Cake.Common.Tools.DotNetCore.NuGet.Source")] public static void DotNetCoreNuGetRemoveSource(this ICakeContext context, string name, DotNetCoreNuGetSourceSettings settings) { if (context == null) { throw new ArgumentNullException(nameof(context)); } var sourcer = new DotNetCoreNuGetSourcer(context.FileSystem, context.Environment, context.ProcessRunner, context.Tools); sourcer.RemoveSource(name, settings ?? new DotNetCoreNuGetSourceSettings()); } /// <summary> /// Update the specified NuGet source. /// </summary> /// <param name="context">The context.</param> /// <param name="name">The name of the source.</param> /// <param name="settings">The settings.</param> /// <example> /// <code> /// var settings = new DotNetCoreNuGetSourceSettings /// { /// Source = "https://www.example.com/nugetfeed", /// UserName = "username", /// Password = "password", /// StorePasswordInClearText = true, /// ValidAuthenticationTypes = "basic,negotiate" /// }; /// /// DotNetCoreNuGetUpdateSource("example", settings); /// </code> /// </example> [CakeMethodAlias] [CakeAliasCategory("NuGet")] [CakeNamespaceImport("Cake.Common.Tools.DotNetCore.NuGet.Source")] public static void DotNetCoreNuGetUpdateSource(this ICakeContext context, string name, DotNetCoreNuGetSourceSettings settings) { if (context == null) { throw new ArgumentNullException(nameof(context)); } var sourcer = new DotNetCoreNuGetSourcer(context.FileSystem, context.Environment, context.ProcessRunner, context.Tools); sourcer.UpdateSource(name, settings); } /// <summary> /// Builds the specified targets in a project file found in the current working directory. /// </summary> /// <param name="context">The context.</param> /// <example> /// <code> /// DotNetCoreMSBuild(); /// </code> /// </example> [CakeMethodAlias] [CakeAliasCategory("MSBuild")] [CakeNamespaceImport("Cake.Common.Tools.DotNetCore.MSBuild")] public static void DotNetCoreMSBuild(this ICakeContext context) { context.DotNetCoreMSBuild(null, null); } /// <summary> /// Builds the specified targets in the project file. /// </summary> /// <param name="context">The context.</param> /// <param name="projectOrDirectory">Project file or directory to search for project file.</param> /// <example> /// <code> /// DotNetCoreMSBuild("foobar.proj"); /// </code> /// </example> /// <remarks> /// If a directory is specified, MSBuild searches that directory for a project file. /// </remarks> [CakeMethodAlias] [CakeAliasCategory("MSBuild")] [CakeNamespaceImport("Cake.Common.Tools.DotNetCore.MSBuild")] public static void DotNetCoreMSBuild(this ICakeContext context, string projectOrDirectory) { if (string.IsNullOrWhiteSpace(projectOrDirectory)) { throw new ArgumentNullException(nameof(projectOrDirectory)); } context.DotNetCoreMSBuild(projectOrDirectory, null); } /// <summary> /// Builds the specified targets in a project file found in the current working directory. /// </summary> /// <param name="context">The context.</param> /// <param name="settings">The settings.</param> /// <example> /// <code> /// var settings = new DotNetCoreMSBuildSettings /// { /// NoLogo = true, /// MaxCpuCount = -1 /// }; /// /// DotNetCoreMSBuild(settings); /// </code> /// </example> [CakeMethodAlias] [CakeAliasCategory("MSBuild")] [CakeNamespaceImport("Cake.Common.Tools.DotNetCore.MSBuild")] public static void DotNetCoreMSBuild(this ICakeContext context, DotNetCoreMSBuildSettings settings) { context.DotNetCoreMSBuild(null, settings); } /// <summary> /// Builds the specified targets in the project file. /// </summary> /// <param name="context">The context.</param> /// <param name="projectOrDirectory">Project file or directory to search for project file.</param> /// <param name="settings">The settings.</param> /// <example> /// <code> /// var settings = new DotNetCoreMSBuildSettings /// { /// NoLogo = true, /// MaxCpuCount = -1 /// }; /// /// DotNetCoreMSBuild("foobar.proj", settings); /// </code> /// </example> /// <remarks> /// If a project file is not specified, MSBuild searches the current working directory for a file that has a file /// extension that ends in "proj" and uses that file. If a directory is specified, MSBuild searches that directory for a project file. /// </remarks> [CakeMethodAlias] [CakeAliasCategory("MSBuild")] [CakeNamespaceImport("Cake.Common.Tools.DotNetCore.MSBuild")] public static void DotNetCoreMSBuild(this ICakeContext context, string projectOrDirectory, DotNetCoreMSBuildSettings settings) { if (context == null) { throw new ArgumentNullException(nameof(context)); } if (settings == null) { settings = new DotNetCoreMSBuildSettings(); } var builder = new DotNetCoreMSBuildBuilder(context.FileSystem, context.Environment, context.ProcessRunner, context.Tools); builder.Build(projectOrDirectory, settings); } /// <summary> /// Test one or more projects specified by a path or glob pattern using the VS Test host runner. /// </summary> /// <param name="context">The context.</param> /// <param name="testFile">A path to the test file or glob for one or more test files.</param> /// <example> /// <para>Specify the path to the .csproj file in the test project.</para> /// <code> /// DotNetCoreVSTest("./test/Project.Tests/bin/Release/netcoreapp2.1/Project.Tests.dll"); /// </code> /// <para>You could also specify a glob pattern to run multiple test projects.</para> /// <code> /// DotNetCoreVSTest("./**/bin/Release/netcoreapp2.1/*.Tests.dll"); /// </code> /// </example> [CakeMethodAlias] [CakeAliasCategory("Test")] [CakeNamespaceImport("Cake.Common.Tools.DotNetCore.VSTest")] public static void DotNetCoreVSTest(this ICakeContext context, string testFile) => context.DotNetCoreVSTest(testFile, null); /// <summary> /// Test one or more projects specified by a path or glob pattern with settings using the VS Test host runner. /// </summary> /// <param name="context">The context.</param> /// <param name="testFile">A path to the test file or glob for one or more test files.</param> /// <param name="settings">The settings.</param> /// <example> /// <para>Specify the path to the .csproj file in the test project.</para> /// <code> /// var settings = new DotNetCoreVSTestSettings /// { /// Framework = "FrameworkCore10", /// Platform = "x64" /// }; /// /// DotNetCoreTest("./test/Project.Tests/bin/Release/netcoreapp2.1/Project.Tests.dll", settings); /// </code> /// <para>You could also specify a glob pattern to run multiple test projects.</para> /// <code> /// var settings = new DotNetCoreVSTestSettings /// { /// Framework = "FrameworkCore10", /// Platform = "x64", /// Parallel = true /// }; /// /// DotNetCoreVSTest("./**/bin/Release/netcoreapp2.1/*.Tests.dll", settings); /// </code> /// </example> [CakeMethodAlias] [CakeAliasCategory("Test")] [CakeNamespaceImport("Cake.Common.Tools.DotNetCore.VSTest")] public static void DotNetCoreVSTest(this ICakeContext context, string testFile, DotNetCoreVSTestSettings settings) { var testFiles = context.GetFiles(testFile); context.DotNetCoreVSTest(testFiles, settings); } /// <summary> /// Test one or more specified projects with settings using the VS Test host runner. /// </summary> /// <param name="context">The context.</param> /// <param name="testFiles">The project paths to test.</param> /// <param name="settings">The settings.</param> /// <example> /// <code> /// var settings = new DotNetCoreVSTestSettings /// { /// Framework = "FrameworkCore10", /// Platform = "x64" /// }; /// /// DotNetCoreVSTest(new[] { (FilePath)"./test/Project.Tests/bin/Release/netcoreapp2.1/Project.Tests.dll" }, settings); /// </code> /// <para>You could also specify a task that runs multiple test projects.</para> /// <para>Cake task:</para> /// <code> /// Task("Test") /// .Does(() => /// { /// var settings = new DotNetCoreVSTestSettings /// { /// Framework = "FrameworkCore10", /// Platform = "x64", /// Parallel = true /// }; /// /// var testFiles = GetFiles("./test/**/bin/Release/netcoreapp2.1/*.Test.dll"); /// /// DotNetCoreVSTest(testFiles, settings); /// }); /// </code> /// </example> [CakeMethodAlias] [CakeAliasCategory("Test")] [CakeNamespaceImport("Cake.Common.Tools.DotNetCore.VSTest")] public static void DotNetCoreVSTest(this ICakeContext context, IEnumerable<FilePath> testFiles, DotNetCoreVSTestSettings settings) { if (context == null) { throw new ArgumentNullException(nameof(context)); } if (settings == null) { settings = new DotNetCoreVSTestSettings(); } var tester = new DotNetCoreVSTester(context.FileSystem, context.Environment, context.ProcessRunner, context.Tools); tester.Test(testFiles, settings); } /// <summary> /// Execute an .NET Core Extensibility Tool. /// </summary> /// <param name="context">The context.</param> /// <param name="command">The command to execute.</param> /// <example> /// <code> /// DotNetCoreTool("cake"); /// </code> /// </example> [CakeMethodAlias] [CakeAliasCategory("Tool")] [CakeNamespaceImport("Cake.Common.Tools.DotNetCore.Tool")] public static void DotNetCoreTool(this ICakeContext context, string command) { if (context == null) { throw new ArgumentNullException(nameof(context)); } var arguments = new ProcessArgumentBuilder(); var settings = new DotNetCoreToolSettings(); context.DotNetCoreTool(null, command, arguments, settings); } /// <summary> /// Execute an .NET Core Extensibility Tool. /// </summary> /// <param name="context">The context.</param> /// <param name="command">The command to execute.</param> /// <param name="settings">The settings.</param> /// <example> /// <code> /// var settings = new DotNetCoreToolSettings /// { /// DiagnosticOutput = true /// }; /// /// DotNetCoreTool("cake", settings); /// </code> /// </example> [CakeMethodAlias] [CakeAliasCategory("Tool")] [CakeNamespaceImport("Cake.Common.Tools.DotNetCore.Tool")] public static void DotNetCoreTool(this ICakeContext context, string command, DotNetCoreToolSettings settings) { if (context == null) { throw new ArgumentNullException(nameof(context)); } var arguments = new ProcessArgumentBuilder(); context.DotNetCoreTool(null, command, arguments, settings); } /// <summary> /// Execute an .NET Core Extensibility Tool. /// </summary> /// <param name="context">The context.</param> /// <param name="projectPath">The project path.</param> /// <param name="command">The command to execute.</param> /// <example> /// <code> /// DotNetCoreTool("./src/project", "xunit", "-xml report.xml"); /// </code> /// </example> [CakeMethodAlias] [CakeAliasCategory("Tool")] [CakeNamespaceImport("Cake.Common.Tools.DotNetCore.Tool")] public static void DotNetCoreTool(this ICakeContext context, FilePath projectPath, string command) { if (context == null) { throw new ArgumentNullException(nameof(context)); } var arguments = new ProcessArgumentBuilder(); var settings = new DotNetCoreToolSettings(); context.DotNetCoreTool(projectPath, command, arguments, settings); } /// <summary> /// Execute an .NET Core Extensibility Tool. /// </summary> /// <param name="context">The context.</param> /// <param name="projectPath">The project path.</param> /// <param name="command">The command to execute.</param> /// <param name="arguments">The arguments.</param> /// <example> /// <code> /// DotNetCoreTool("./src/project", "xunit", "-xml report.xml"); /// </code> /// </example> [CakeMethodAlias] [CakeAliasCategory("Tool")] [CakeNamespaceImport("Cake.Common.Tools.DotNetCore.Tool")] public static void DotNetCoreTool(this ICakeContext context, FilePath projectPath, string command, ProcessArgumentBuilder arguments) { if (context == null) { throw new ArgumentNullException(nameof(context)); } var settings = new DotNetCoreToolSettings(); context.DotNetCoreTool(projectPath, command, arguments, settings); } /// <summary> /// Execute an .NET Core Extensibility Tool. /// </summary> /// <param name="context">The context.</param> /// <param name="projectPath">The project path.</param> /// <param name="command">The command to execute.</param> /// <param name="arguments">The arguments.</param> /// <param name="settings">The settings.</param> /// <example> /// <code> /// DotNetCoreTool("./src/project", "xunit", "-xml report.xml"); /// </code> /// </example> [CakeMethodAlias] [CakeAliasCategory("Tool")] [CakeNamespaceImport("Cake.Common.Tools.DotNetCore.Tool")] public static void DotNetCoreTool(this ICakeContext context, FilePath projectPath, string command, ProcessArgumentBuilder arguments, DotNetCoreToolSettings settings) { if (context == null) { throw new ArgumentNullException(nameof(context)); } var runner = new DotNetCoreToolRunner(context.FileSystem, context.Environment, context.ProcessRunner, context.Tools); runner.Execute(projectPath, command, arguments, settings); } /// <summary> /// Shuts down build servers that are started from dotnet. /// </summary> /// <param name="context">The context.</param> /// <example> /// <code> /// DotNetCoreBuildServerShutdown(); /// </code> /// </example> [CakeMethodAlias] [CakeAliasCategory("Build Server")] [CakeNamespaceImport("Cake.Common.Tools.DotNetCore.BuildServer")] public static void DotNetCoreBuildServerShutdown(this ICakeContext context) { context.DotNetCoreBuildServerShutdown(null); } /// <summary> /// Shuts down build servers that are started from dotnet. /// </summary> /// <param name="context">The context.</param> /// <param name="settings">The settings.</param> /// <example> /// <code> /// var settings = new DotNetCoreBuildServerSettings /// { /// MSBuild = true /// }; /// /// DotNetCoreBuildServerShutdown(settings); /// </code> /// </example> [CakeMethodAlias] [CakeAliasCategory("Build Server")] [CakeNamespaceImport("Cake.Common.Tools.DotNetCore.BuildServer")] public static void DotNetCoreBuildServerShutdown(this ICakeContext context, DotNetCoreBuildServerSettings settings) { if (context == null) { throw new ArgumentNullException(nameof(context)); } var buildServer = new DotNetCoreBuildServer(context.FileSystem, context.Environment, context.ProcessRunner, context.Tools); buildServer.Shutdown(settings ?? new DotNetCoreBuildServerSettings()); } } }
38.347436
210
0.561349
[ "MIT" ]
duracellko/cake
src/Cake.Common/Tools/DotNetCore/DotNetCoreAliases.cs
59,824
C#
using System.Linq; using PatchKit.Api.Models.Main; using PatchKit.Unity.Patcher.AppData.Remote; using PatchKit.Unity.Patcher.AppData.Local; namespace PatchKit.Unity.Patcher.AppUpdater.Status { public static class StatusWeightHelper { public static double GetUnarchivePackageWeight(long size) { return BytesToWeight(size)*0.5; } public static double GetUninstallWeight() { return 0.0001; } public static double GetCheckVersionIntegrityWeight(AppContentSummary summary) { return BytesToWeight(summary.Size) * 0.05; } public static double GetCopyContentFilesWeight(AppContentSummary summary) { return BytesToWeight(summary.Size) * 0.5; } public static double GetRepairFilesWeight(Pack1Meta.FileEntry[] files) { var sum = files.Sum(f => f.Size).GetValueOrDefault(); return BytesToWeight(sum) * 0.01; } public static double GetAddDiffFilesWeight(AppDiffSummary summary) { return BytesToWeight(summary.Size) * 0.5; } public static double GetModifyDiffFilesWeight(AppDiffSummary summary) { return BytesToWeight(summary.Size) * 0.5; } public static double GetRemoveDiffFilesWeight(AppDiffSummary summary) { return BytesToWeight(summary.Size) * 0.001; } public static double GetResourceDownloadWeight(RemoteResource resource) { return BytesToWeight(resource.Size); } public static double GetDownloadWeight(long bytes) { return BytesToWeight(bytes); } public static double GetCopyFileWeight(long bytes) { return BytesToWeight(bytes) *0.01; } private static double BytesToWeight(long bytes) { return bytes/1024.0/1024.0; } } }
27.943662
86
0.618448
[ "MIT" ]
SolidClouds/StarbornePatcher
Assets/PatchKit Patcher/Scripts/AppUpdater/Status/StatusWeightHelper.cs
1,986
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("PInvoke")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("PInvoke")] [assembly: AssemblyCopyright("Copyright © 2018")] [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("d73001b8-3b54-487e-8387-9667accf01a7")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
37.351351
84
0.74602
[ "Apache-2.0" ]
MFunction96/MFVolumeCtrl
PInvoke/Properties/AssemblyInfo.cs
1,385
C#
//------------------------------------------------------------------------------ // <auto-generated> // 此代码由工具生成。 // 运行时版本:4.0.30319.42000 // // 对此文件的更改可能会导致不正确的行为,并且如果 // 重新生成代码,这些更改将会丢失。 // </auto-generated> //------------------------------------------------------------------------------ namespace QR_Encode_Decode.Properties { [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "15.9.0.0")] internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase { private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings()))); public static Settings Default { get { return defaultInstance; } } } }
36.37037
151
0.566191
[ "MIT" ]
sndnvaps/QR_C_Sharp
QR_Encode_Decode/Properties/Settings.Designer.cs
1,090
C#
// Decompiled with JetBrains decompiler // Type: Diga.WebView2.Interop.ICoreWebView2Controller3 // Assembly: Diga.WebView2.Interop, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null // MVID: AAF9543A-0FE1-46E7-BB2C-D24EA0535C0F // Assembly location: O:\webview2\v1077444\Diga.WebView2.Interop.dll using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; namespace Diga.WebView2.Interop { [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] [Guid("F9614724-5D2B-41DC-AEF7-73D62B51543B")] [ComImport] public interface ICoreWebView2Controller3 : ICoreWebView2Controller2 { [DispId(1610678272)] new int IsVisible { [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] get; [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] [param: In] set; } [DispId(1610678274)] new tagRECT Bounds { [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] get; [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] [param: In] set; } [DispId(1610678276)] new double ZoomFactor { [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] get; [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] [param: In] set; } [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] new void add_ZoomFactorChanged( [MarshalAs(UnmanagedType.Interface), In] ICoreWebView2ZoomFactorChangedEventHandler eventHandler, out EventRegistrationToken token); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] new void remove_ZoomFactorChanged([In] EventRegistrationToken token); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] new void SetBoundsAndZoomFactor([In] tagRECT Bounds, [In] double ZoomFactor); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] new void MoveFocus([In] COREWEBVIEW2_MOVE_FOCUS_REASON reason); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] new void add_MoveFocusRequested( [MarshalAs(UnmanagedType.Interface), In] ICoreWebView2MoveFocusRequestedEventHandler eventHandler, out EventRegistrationToken token); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] new void remove_MoveFocusRequested([In] EventRegistrationToken token); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] new void add_GotFocus( [MarshalAs(UnmanagedType.Interface), In] ICoreWebView2FocusChangedEventHandler eventHandler, out EventRegistrationToken token); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] new void remove_GotFocus([In] EventRegistrationToken token); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] new void add_LostFocus( [MarshalAs(UnmanagedType.Interface), In] ICoreWebView2FocusChangedEventHandler eventHandler, out EventRegistrationToken token); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] new void remove_LostFocus([In] EventRegistrationToken token); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] new void add_AcceleratorKeyPressed( [MarshalAs(UnmanagedType.Interface), In] ICoreWebView2AcceleratorKeyPressedEventHandler eventHandler, out EventRegistrationToken token); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] new void remove_AcceleratorKeyPressed([In] EventRegistrationToken token); [ComAliasName("Diga.WebView2.Interop.wireHWND")] [DispId(1610678290)] new IntPtr ParentWindow { [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] [return: ComAliasName("Diga.WebView2.Interop.wireHWND")] get; [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] [param: ComAliasName("Diga.WebView2.Interop.wireHWND"), In] set; } [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] new void NotifyParentWindowPositionChanged(); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] new void Close(); [DispId(1610678294)] new ICoreWebView2 CoreWebView2 { [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] [return: MarshalAs(UnmanagedType.Interface)] get; } [DispId(1610743808)] new COREWEBVIEW2_COLOR DefaultBackgroundColor { [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] get; [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] [param: In] set; } [DispId(1610809344)] double RasterizationScale { [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] get; [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] [param: In] set; } [DispId(1610809346)] int ShouldDetectMonitorScaleChanges { [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] get; [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] [param: In] set; } [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] void add_RasterizationScaleChanged( [MarshalAs(UnmanagedType.Interface), In] ICoreWebView2RasterizationScaleChangedEventHandler eventHandler, out EventRegistrationToken token); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] void remove_RasterizationScaleChanged([In] EventRegistrationToken token); [DispId(1610809350)] COREWEBVIEW2_BOUNDS_MODE BoundsMode { [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] get; [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] [param: In] set; } } }
58.252336
330
0.798492
[ "MIT" ]
ITAgnesmeyer/Diga.WebView2
V1090249/Diga.WebView2.Interop.V1090249/ICoreWebView2Controller3.cs
6,235
C#
// **************************************************************** // This is free software licensed under the NUnit license. You // may obtain a copy of the license as well as information regarding // copyright ownership at http://nunit.org/?p=license&r=2.4. // **************************************************************** using System; using NUnit.Framework; using NUnit.Tests.Assemblies; namespace NUnit.Core.Tests { /// <summary> /// Summary description for EventTestFixture. /// </summary> /// [TestFixture(Description="Tests that proper events are generated when running test")] public class EventTestFixture { private string testsDll = "mock-assembly.dll"; internal class EventCounter : EventListener { internal int runStarted = 0; internal int runFinished = 0; internal int testCaseStart = 0; internal int testCaseFinished = 0; internal int suiteStarted = 0; internal int suiteFinished = 0; public void RunStarted(string name, int testCount) { runStarted++; } public void RunFinished(NUnit.Core.TestResult result) { runFinished++; } public void RunFinished(Exception exception) { runFinished++; } public void TestStarted(TestName testName) { testCaseStart++; } public void TestFinished(TestCaseResult result) { testCaseFinished++; } public void SuiteStarted(TestName suiteName) { suiteStarted++; } public void SuiteFinished(TestSuiteResult result) { suiteFinished++; } public void UnhandledException( Exception exception ) { } public void TestOutput(TestOutput testOutput) { } } [Test] public void CheckEventListening() { TestSuiteBuilder builder = new TestSuiteBuilder(); Test testSuite = builder.Build( new TestPackage( testsDll ) ); EventCounter counter = new EventCounter(); testSuite.Run(counter); Assert.AreEqual(testSuite.CountTestCases(TestFilter.Empty), counter.testCaseStart); Assert.AreEqual(testSuite.CountTestCases(TestFilter.Empty), counter.testCaseFinished); Assert.AreEqual(MockAssembly.Suites - MockAssembly.ExplicitFixtures, counter.suiteStarted); Assert.AreEqual(MockAssembly.Suites - MockAssembly.ExplicitFixtures, counter.suiteFinished); } } }
25.73913
96
0.648226
[ "Apache-2.0" ]
assessorgeneral/ConQAT
org.conqat.engine.dotnet/test-data/org.conqat.engine.dotnet.scope/NUnit_Folder/NUnitCore/tests/EventTestFixture.cs
2,368
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. namespace MS.Internal.Xml.XPath { using System; using Microsoft.Xml; using Microsoft.Xml.XPath; using System.Diagnostics; using System.Globalization; internal class Axis : AstNode { private AxisType _axisType; private AstNode _input; private string _prefix; private string _name; private XPathNodeType _nodeType; protected bool abbrAxis; public enum AxisType { Ancestor, AncestorOrSelf, Attribute, Child, Descendant, DescendantOrSelf, Following, FollowingSibling, Namespace, Parent, Preceding, PrecedingSibling, Self, None }; // constructor public Axis(AxisType axisType, AstNode input, string prefix, string name, XPathNodeType nodetype) { Debug.Assert(prefix != null); Debug.Assert(name != null); _axisType = axisType; _input = input; _prefix = prefix; _name = name; _nodeType = nodetype; } // constructor public Axis(AxisType axisType, AstNode input) : this(axisType, input, string.Empty, string.Empty, XPathNodeType.All) { this.abbrAxis = true; } public override AstType Type { get { return AstType.Axis; } } public override XPathResultType ReturnType { get { return XPathResultType.NodeSet; } } public AstNode Input { get { return _input; } set { _input = value; } } public string Prefix { get { return _prefix; } } public string Name { get { return _name; } } public XPathNodeType NodeType { get { return _nodeType; } } public AxisType TypeOfAxis { get { return _axisType; } } public bool AbbrAxis { get { return abbrAxis; } } // Used by AstTree in Schema private string _urn = string.Empty; public string Urn { get { return _urn; } set { _urn = value; } } } }
28.47619
105
0.561873
[ "MIT" ]
Bencargs/wcf
src/dotnet-svcutil/lib/src/FrameworkFork/Microsoft.Xml/Xml/XPath/Internal/Axis.cs
2,392
C#
using System.Linq; using DdfGuide.Core.Filtering; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace DdfGuide.Test.Filtering { [TestClass] public class SpecialAudioDramasOnlyFilterTests { [TestMethod] public void FilterOnlyReturnsOnlyAudioDramasThatDontHaveANumber() { var provider = new SampleAudioDramaProvider(); var audioDramas = provider.Get().ToList(); var expectedFiltered = audioDramas.Where(x => x.AudioDramaDto.NumberEuropa.HasValue == false).ToList(); var filter = new SpecialAudioDramasOnlyFilter(); var filtered = filter.Filter(audioDramas).ToList(); CollectionAssert.AreEqual(expectedFiltered, filtered); } [TestMethod] public void TheFilterHasTheCorrectMode() { var filter = new SpecialAudioDramasOnlyFilter(); Assert.AreEqual(EAudioDramaFilterMode.SpecialsOnly, filter.FilterMode); } } }
32.129032
115
0.670683
[ "MIT" ]
KerstinMaur/DdfGuide
DdfGuide.Test/Filtering/SpecialAudioDramasOnlyFilterTests.cs
998
C#
//------------------------------------------------------------------------------ // <auto-generated> // Dieser Code wurde von einem Tool generiert. // Laufzeitversion:4.0.30319.42000 // // Änderungen an dieser Datei können falsches Verhalten verursachen und gehen verloren, wenn // der Code erneut generiert wird. // </auto-generated> //------------------------------------------------------------------------------ namespace CloudFlareDDNS.Properties { using System; /// <summary> /// Eine stark typisierte Ressourcenklasse zum Suchen von lokalisierten Zeichenfolgen usw. /// </summary> // Diese Klasse wurde von der StronglyTypedResourceBuilder automatisch generiert // -Klasse über ein Tool wie ResGen oder Visual Studio automatisch generiert. // Um einen Member hinzuzufügen oder zu entfernen, bearbeiten Sie die .ResX-Datei und führen dann ResGen // mit der /str-Option erneut aus, oder Sie erstellen Ihr VS-Projekt neu. [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "15.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] internal class Resources { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal Resources() { } /// <summary> /// Gibt die zwischengespeicherte ResourceManager-Instanz zurück, die von dieser Klasse verwendet wird. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Resources.ResourceManager ResourceManager { get { if (object.ReferenceEquals(resourceMan, null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("CloudFlareDDNS.Properties.Resources", typeof(Resources).Assembly); resourceMan = temp; } return resourceMan; } } /// <summary> /// Überschreibt die CurrentUICulture-Eigenschaft des aktuellen Threads für alle /// Ressourcenzuordnungen, die diese stark typisierte Ressourcenklasse verwenden. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } /// <summary> /// Sucht eine lokalisierte Zeichenfolge, die Close ähnelt. /// </summary> internal static string About_Close { get { return ResourceManager.GetString("About_Close", resourceCulture); } } /// <summary> /// Sucht eine lokalisierte Zeichenfolge, die About ähnelt. /// </summary> internal static string About_Title { get { return ResourceManager.GetString("About_Title", resourceCulture); } } /// <summary> /// Sucht eine lokalisierte Ressource vom Typ System.Drawing.Icon ähnlich wie (Symbol). /// </summary> internal static System.Drawing.Icon AppIcon { get { object obj = ResourceManager.GetObject("AppIcon", resourceCulture); return ((System.Drawing.Icon)(obj)); } } /// <summary> /// Sucht eine lokalisierte Ressource vom Typ System.Drawing.Bitmap. /// </summary> internal static System.Drawing.Bitmap application_double { get { object obj = ResourceManager.GetObject("application_double", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } /// <summary> /// Sucht eine lokalisierte Ressource vom Typ System.Drawing.Bitmap. /// </summary> internal static System.Drawing.Bitmap arrow_down { get { object obj = ResourceManager.GetObject("arrow_down", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } /// <summary> /// Sucht eine lokalisierte Ressource vom Typ System.Drawing.Bitmap. /// </summary> internal static System.Drawing.Bitmap arrow_up { get { object obj = ResourceManager.GetObject("arrow_up", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } /// <summary> /// Sucht eine lokalisierte Ressource vom Typ System.Drawing.Bitmap. /// </summary> internal static System.Drawing.Bitmap cog { get { object obj = ResourceManager.GetObject("cog", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } /// <summary> /// Sucht eine lokalisierte Ressource vom Typ System.Drawing.Bitmap. /// </summary> internal static System.Drawing.Bitmap error { get { object obj = ResourceManager.GetObject("error", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } /// <summary> /// Sucht eine lokalisierte Zeichenfolge, die Cant find new IP ähnelt. /// </summary> internal static string Error_CantFindNewIp { get { return ResourceManager.GetString("Error_CantFindNewIp", resourceCulture); } } /// <summary> /// Sucht eine lokalisierte Zeichenfolge, die Cant get ähnelt. /// </summary> internal static string Error_CantGet { get { return ResourceManager.GetString("Error_CantGet", resourceCulture); } } /// <summary> /// Sucht eine lokalisierte Zeichenfolge, die Cant reach: ähnelt. /// </summary> internal static string Error_CantReach { get { return ResourceManager.GetString("Error_CantReach", resourceCulture); } } /// <summary> /// Sucht eine lokalisierte Zeichenfolge, die No network adapters with an IPv4 address in the system! ähnelt. /// </summary> internal static string Error_ExceptionNoNetworkAdapterFound { get { return ResourceManager.GetString("Error_ExceptionNoNetworkAdapterFound", resourceCulture); } } /// <summary> /// Sucht eine lokalisierte Zeichenfolge, die [Exception info below]Exception on request: ähnelt. /// </summary> internal static string Error_ExceptionOnRequest { get { return ResourceManager.GetString("Error_ExceptionOnRequest", resourceCulture); } } /// <summary> /// Sucht eine lokalisierte Zeichenfolge, die [Exception info below]IP Updated failed: ähnelt. /// </summary> internal static string Error_FailedIPUpdate { get { return ResourceManager.GetString("Error_FailedIPUpdate", resourceCulture); } } /// <summary> /// Sucht eine lokalisierte Zeichenfolge, die Failed Updateing: ähnelt. /// </summary> internal static string Error_FailedRecordUpdate { get { return ResourceManager.GetString("Error_FailedRecordUpdate", resourceCulture); } } /// <summary> /// Sucht eine lokalisierte Ressource vom Typ System.Drawing.Bitmap. /// </summary> internal static System.Drawing.Bitmap exit { get { object obj = ResourceManager.GetObject("exit", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } /// <summary> /// Sucht eine lokalisierte Ressource vom Typ System.Drawing.Bitmap. /// </summary> internal static System.Drawing.Bitmap information { get { object obj = ResourceManager.GetObject("information", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } /// <summary> /// Sucht eine lokalisierte Zeichenfolge, die Failed to update ähnelt. /// </summary> internal static string Logger_Failed { get { return ResourceManager.GetString("Logger_Failed", resourceCulture); } } /// <summary> /// Sucht eine lokalisierte Zeichenfolge, die minutes for domain ähnelt. /// </summary> internal static string Logger_Interval { get { return ResourceManager.GetString("Logger_Interval", resourceCulture); } } /// <summary> /// Sucht eine lokalisierte Zeichenfolge, die Starting CloudFlare DDNS updater GUI ähnelt. /// </summary> internal static string Logger_RunGUI { get { return ResourceManager.GetString("Logger_RunGUI", resourceCulture); } } /// <summary> /// Sucht eine lokalisierte Zeichenfolge, die Starting CloudFlare DDNS updater service ähnelt. /// </summary> internal static string Logger_RunService { get { return ResourceManager.GetString("Logger_RunService", resourceCulture); } } /// <summary> /// Sucht eine lokalisierte Zeichenfolge, die Service stopping ähnelt. /// </summary> internal static string Logger_ServiceStop { get { return ResourceManager.GetString("Logger_ServiceStop", resourceCulture); } } /// <summary> /// Sucht eine lokalisierte Zeichenfolge, die Starting auto updates every ähnelt. /// </summary> internal static string Logger_Start { get { return ResourceManager.GetString("Logger_Start", resourceCulture); } } /// <summary> /// Sucht eine lokalisierte Zeichenfolge, die Changing IP... ähnelt. /// </summary> internal static string Main_Change_IP { get { return ResourceManager.GetString("Main_Change_IP", resourceCulture); } } /// <summary> /// Sucht eine lokalisierte Zeichenfolge, die IP Change Failed ähnelt. /// </summary> internal static string Main_Change_IP_Failed { get { return ResourceManager.GetString("Main_Change_IP_Failed", resourceCulture); } } /// <summary> /// Sucht eine lokalisierte Zeichenfolge, die Close ähnelt. /// </summary> internal static string Main_Close { get { return ResourceManager.GetString("Main_Close", resourceCulture); } } /// <summary> /// Sucht eine lokalisierte Zeichenfolge, die Current External IP Address: ähnelt. /// </summary> internal static string Main_ExterrnalAddress { get { return ResourceManager.GetString("Main_ExterrnalAddress", resourceCulture); } } /// <summary> /// Sucht eine lokalisierte Zeichenfolge, die Current External IPv4 Address: ähnelt. /// </summary> internal static string Main_ExterrnalIPv4Address { get { return ResourceManager.GetString("Main_ExterrnalIPv4Address", resourceCulture); } } /// <summary> /// Sucht eine lokalisierte Zeichenfolge, die Current External IPv6 Address: ähnelt. /// </summary> internal static string Main_ExterrnalIPv6Address { get { return ResourceManager.GetString("Main_ExterrnalIPv6Address", resourceCulture); } } /// <summary> /// Sucht eine lokalisierte Zeichenfolge, die Update ähnelt. /// </summary> internal static string Main_HostsList_Header1 { get { return ResourceManager.GetString("Main_HostsList_Header1", resourceCulture); } } /// <summary> /// Sucht eine lokalisierte Zeichenfolge, die Type ähnelt. /// </summary> internal static string Main_HostsList_Header2 { get { return ResourceManager.GetString("Main_HostsList_Header2", resourceCulture); } } /// <summary> /// Sucht eine lokalisierte Zeichenfolge, die Name ähnelt. /// </summary> internal static string Main_HostsList_Header3 { get { return ResourceManager.GetString("Main_HostsList_Header3", resourceCulture); } } /// <summary> /// Sucht eine lokalisierte Zeichenfolge, die Host ähnelt. /// </summary> internal static string Main_HostsList_Header4 { get { return ResourceManager.GetString("Main_HostsList_Header4", resourceCulture); } } /// <summary> /// Sucht eine lokalisierte Zeichenfolge, die Last Change ähnelt. /// </summary> internal static string Main_List_LastChange { get { return ResourceManager.GetString("Main_List_LastChange", resourceCulture); } } /// <summary> /// Sucht eine lokalisierte Zeichenfolge, die Level ähnelt. /// </summary> internal static string Main_LogControl_Header1 { get { return ResourceManager.GetString("Main_LogControl_Header1", resourceCulture); } } /// <summary> /// Sucht eine lokalisierte Zeichenfolge, die Message ähnelt. /// </summary> internal static string Main_LogControl_Header2 { get { return ResourceManager.GetString("Main_LogControl_Header2", resourceCulture); } } /// <summary> /// Sucht eine lokalisierte Zeichenfolge, die About ähnelt. /// </summary> internal static string Main_MenuItem_About { get { return ResourceManager.GetString("Main_MenuItem_About", resourceCulture); } } /// <summary> /// Sucht eine lokalisierte Zeichenfolge, die Exit ähnelt. /// </summary> internal static string Main_MenuItem_Exit { get { return ResourceManager.GetString("Main_MenuItem_Exit", resourceCulture); } } /// <summary> /// Sucht eine lokalisierte Zeichenfolge, die Fetch Records ähnelt. /// </summary> internal static string Main_MenuItem_Fetch { get { return ResourceManager.GetString("Main_MenuItem_Fetch", resourceCulture); } } /// <summary> /// Sucht eine lokalisierte Zeichenfolge, die File ähnelt. /// </summary> internal static string Main_MenuItem_File { get { return ResourceManager.GetString("Main_MenuItem_File", resourceCulture); } } /// <summary> /// Sucht eine lokalisierte Zeichenfolge, die Help ähnelt. /// </summary> internal static string Main_MenuItem_Help { get { return ResourceManager.GetString("Main_MenuItem_Help", resourceCulture); } } /// <summary> /// Sucht eine lokalisierte Zeichenfolge, die Minimise to tray ähnelt. /// </summary> internal static string Main_MenuItem_Minimise { get { return ResourceManager.GetString("Main_MenuItem_Minimise", resourceCulture); } } /// <summary> /// Sucht eine lokalisierte Zeichenfolge, die Settings ähnelt. /// </summary> internal static string Main_MenuItem_Settings { get { return ResourceManager.GetString("Main_MenuItem_Settings", resourceCulture); } } /// <summary> /// Sucht eine lokalisierte Zeichenfolge, die Tools ähnelt. /// </summary> internal static string Main_MenuItem_Tools { get { return ResourceManager.GetString("Main_MenuItem_Tools", resourceCulture); } } /// <summary> /// Sucht eine lokalisierte Zeichenfolge, die Update Records ähnelt. /// </summary> internal static string Main_MenuItem_Update { get { return ResourceManager.GetString("Main_MenuItem_Update", resourceCulture); } } /// <summary> /// Sucht eine lokalisierte Zeichenfolge, die CloudFlare DDNS Updater ähnelt. /// </summary> internal static string Main_Title { get { return ResourceManager.GetString("Main_Title", resourceCulture); } } /// <summary> /// Sucht eine lokalisierte Zeichenfolge, die Settings ähnelt. /// </summary> internal static string Settings { get { return ResourceManager.GetString("Settings", resourceCulture); } } /// <summary> /// Sucht eine lokalisierte Zeichenfolge, die API Key: ähnelt. /// </summary> internal static string Settings_APIKey { get { return ResourceManager.GetString("Settings_APIKey", resourceCulture); } } /// <summary> /// Sucht eine lokalisierte Zeichenfolge, die Apply ähnelt. /// </summary> internal static string Settings_Apply { get { return ResourceManager.GetString("Settings_Apply", resourceCulture); } } /// <summary> /// Sucht eine lokalisierte Zeichenfolge, die Auto Fetch Time (Minutes): ähnelt. /// </summary> internal static string Settings_AutoFetchTime { get { return ResourceManager.GetString("Settings_AutoFetchTime", resourceCulture); } } /// <summary> /// Sucht eine lokalisierte Zeichenfolge, die Close ähnelt. /// </summary> internal static string Settings_Close { get { return ResourceManager.GetString("Settings_Close", resourceCulture); } } /// <summary> /// Sucht eine lokalisierte Zeichenfolge, die Cloudflare API URL ähnelt. /// </summary> internal static string Settings_CloudflareAPIURL { get { return ResourceManager.GetString("Settings_CloudflareAPIURL", resourceCulture); } } /// <summary> /// Sucht eine lokalisierte Zeichenfolge, die Default ähnelt. /// </summary> internal static string Settings_Default { get { return ResourceManager.GetString("Settings_Default", resourceCulture); } } /// <summary> /// Sucht eine lokalisierte Zeichenfolge, die Domain Name: ähnelt. /// </summary> internal static string Settings_Domain { get { return ResourceManager.GetString("Settings_Domain", resourceCulture); } } /// <summary> /// Sucht eine lokalisierte Zeichenfolge, die Email Address: ähnelt. /// </summary> internal static string Settings_EmailAddress { get { return ResourceManager.GetString("Settings_EmailAddress", resourceCulture); } } /// <summary> /// Sucht eine lokalisierte Zeichenfolge, die Hide SRV ähnelt. /// </summary> internal static string Settings_HideSRV { get { return ResourceManager.GetString("Settings_HideSRV", resourceCulture); } } /// <summary> /// Sucht eine lokalisierte Zeichenfolge, die IPv4 Update URL ähnelt. /// </summary> internal static string Settings_IPv4URL { get { return ResourceManager.GetString("Settings_IPv4URL", resourceCulture); } } /// <summary> /// Sucht eine lokalisierte Zeichenfolge, die IPv6 Update URL ähnelt. /// </summary> internal static string Settings_IPv6URL { get { return ResourceManager.GetString("Settings_IPv6URL", resourceCulture); } } /// <summary> /// Sucht eine lokalisierte Zeichenfolge, die Start Minimized: ähnelt. /// </summary> internal static string Settings_StartMinimized { get { return ResourceManager.GetString("Settings_StartMinimized", resourceCulture); } } /// <summary> /// Sucht eine lokalisierte Zeichenfolge, die Settings ähnelt. /// </summary> internal static string Settings_Title { get { return ResourceManager.GetString("Settings_Title", resourceCulture); } } /// <summary> /// Sucht eine lokalisierte Zeichenfolge, die Use Internal IP ähnelt. /// </summary> internal static string Settings_UseInternalIP { get { return ResourceManager.GetString("Settings_UseInternalIP", resourceCulture); } } /// <summary> /// Sucht eine lokalisierte Zeichenfolge, die Use Windows Event Log: ähnelt. /// </summary> internal static string Settings_UseWindowsEventLog { get { return ResourceManager.GetString("Settings_UseWindowsEventLog", resourceCulture); } } /// <summary> /// Sucht eine lokalisierte Zeichenfolge, die Updates will continue in the background ähnelt. /// </summary> internal static string Tooltip_Text { get { return ResourceManager.GetString("Tooltip_Text", resourceCulture); } } /// <summary> /// Sucht eine lokalisierte Ressource vom Typ System.Drawing.Bitmap. /// </summary> internal static System.Drawing.Bitmap warning { get { object obj = ResourceManager.GetObject("warning", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } } }
36.799692
180
0.556756
[ "MIT" ]
DaniGTA/CloudFlare-DDNS-Updater
Properties/Resources.Designer.cs
23,949
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class PlayerStats : MonoBehaviour { public int currentLevel; public int currentExp; public int[] toLevelUp; public int[] HPLevels; public int[] attackLevels; public int[] defenceLevels; public int currentHP; public int currentAttack; public int currentDefence; private PlayerHealthManager thePlayerHealth; // Use this for initialization void Start () { currentHP = HPLevels [1]; currentAttack = attackLevels [1]; currentDefence = defenceLevels [1]; thePlayerHealth = FindObjectOfType<PlayerHealthManager> (); } // Update is called once per frame void Update () { if (currentExp >= toLevelUp [currentLevel]) { //currentLevel++; levelUp(); } } public void AddExperience(int experienceToAdd) { currentExp += experienceToAdd; } public void levelUp() { currentLevel++; currentHP = HPLevels [currentLevel]; thePlayerHealth.playerMaxHealth = currentHP; thePlayerHealth.playerCurrentHealth = currentHP; //thePlayerHealth.playerCurrentHealth += currentHP - HPLevels [currentLevel - 1]; currentAttack = attackLevels [currentLevel]; currentDefence = defenceLevels [currentLevel]; } }
20.311475
83
0.736885
[ "Unlicense" ]
vesche/snippets
c_sharp/Unity_ARPG_SFS_MMO_2/PlayerStats.cs
1,241
C#
namespace KeyMouse { using System; using System.Windows.Forms; using Incode; internal static class Program { /// <summary> /// The main entry point for the application. /// </summary> [STAThread] private static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new IncodeWindow()); } } }
18.380952
56
0.707254
[ "MIT" ]
cschladetsch/Incode
IncodeWindow/Program.cs
388
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("Sitecore.Feature.Teasers.Tests")] [assembly: AssemblyDescription("")] // 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("e2e3e9fc-15eb-4212-a6bd-a0d9590541e4")] // 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: AssemblyFileVersion("1.0.0.0")]
39.133333
85
0.729131
[ "Apache-2.0" ]
26384sunilrana/Habitat
src/Feature/Teasers/tests/Properties/AssemblyInfo.cs
1,176
C#
// ----------------------------------------------------------------------- // <copyright file="MSBuildProjectCollection.cs" company="Ollon, LLC"> // Copyright (c) 2017 Ollon, LLC. All rights reserved. // </copyright> // ----------------------------------------------------------------------- using System.ComponentModel.Composition; using Microsoft.Build.Evaluation; namespace Ollon.VisualStudio.Extensibility.Implementation.Services { [Export] [PartCreationPolicy(CreationPolicy.Shared)] public class MSBuildProjectCollection : ProjectCollection { [ImportingConstructor] public MSBuildProjectCollection() :base(null, null, null, ToolsetDefinitionLocations.Default, 8, false) { } } }
32
81
0.558594
[ "MIT" ]
Ollon/MSBuildTemplates
src/Ollon.VisualStudio.Extensibility.DesignTime.Implementation/Extensibility/Implementation/Services/MSBuildProjectCollection.cs
770
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("Football_Tickets")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Football_Tickets")] [assembly: AssemblyCopyright("Copyright © 2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("4dd9715f-2ae8-4acc-a584-6071b6e2feea")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
37.837838
84
0.749286
[ "MIT" ]
stepan82/Programming-Basics
Exam-Exersises/Football_Tickets/Properties/AssemblyInfo.cs
1,403
C#
using System; using System.Diagnostics; using System.Windows.Input; namespace Fixie.AutoRun.Infrastructure { public class RelayCommand : RelayCommand<object> { public RelayCommand(Action execute) : base(_ => execute()) { } public RelayCommand(Action execute, Func<bool> canExecute) : base(_ => execute(), _ => canExecute()) { } } public class RelayCommand<T> : ICommand { #region Fields readonly Action<T> _execute = null; readonly Predicate<T> _canExecute = null; #endregion // Fields #region Constructors public RelayCommand(Action<T> execute) : this(execute, null) { } /// <summary> /// Creates a new command. /// </summary> /// <param name="execute">The execution logic.</param> /// <param name="canExecute">The execution status logic.</param> public RelayCommand(Action<T> execute, Predicate<T> canExecute) { if (execute == null) throw new ArgumentNullException("execute"); _execute = execute; _canExecute = canExecute; } #endregion // Constructors #region ICommand Members [DebuggerStepThrough] public bool CanExecute(object parameter) { return _canExecute == null ? true : _canExecute((T)parameter); } public event EventHandler CanExecuteChanged { add { CommandManager.RequerySuggested += value; } remove { CommandManager.RequerySuggested -= value; } } public void Execute(object parameter) { _execute((T)parameter); } #endregion // ICommand Members } }
23.369863
71
0.59789
[ "MIT" ]
JonasSamuelsson/fixie.AutoRun
src/Fixie.AutoRun/Infrastructure/RelayCommand.cs
1,708
C#
using System; using System.Collections.Generic; using System.Text; namespace ADASMobileClient.Core { interface ExitAppInterface { void exitApp(); } }
14.333333
33
0.697674
[ "MIT" ]
ajaykeshri/AdasLogin
UserDetailsClient/UserDetailsClient.Core/ExitAppInterface.cs
174
C#
using System; using System.Linq; using System.Net.Http; using System.Threading.Tasks; using DevChatter.Bot.Core; using DevChatter.Bot.Core.GoogleApi; using Newtonsoft.Json; namespace DevChatter.Bot.Infra.GoogleApi { public class GoogleApiTimezoneLookup : ITimezoneLookup { private const string UNKNOWN_LOCATION = "The given location is unknown to Google, well done!"; private readonly GoogleCloudSettings _settings; public GoogleApiTimezoneLookup(GoogleCloudSettings settings) { _settings = settings; } public async Task<(float latitude, float longitude, bool success)> GetLatitudeAndLongitude(HttpClient client, string lookup) { var placeLookupUrl = $"https://maps.googleapis.com/maps/api/place/textsearch/json?query={lookup}&key={_settings.ApiKey}"; string result = await client.GetAsync(placeLookupUrl).Result.Content.ReadAsStringAsync(); var latitudeLongitudeResponse = JsonConvert.DeserializeObject<PlaceResponse>(result); var latitude = latitudeLongitudeResponse.results.FirstOrDefault()?.geometry.location.lat; var longitude = latitudeLongitudeResponse.results.FirstOrDefault()?.geometry.location.lng; if (latitude.HasValue && longitude.HasValue) { return (latitude.Value, longitude.Value, true); } return (default(float), default(float), false); } public async Task<(int, string)> GetTimezoneInfo(HttpClient client, float latitude, float longitude) { long unixTimeSeconds = DateTimeOffset.UtcNow.ToUnixTimeSeconds(); var timezoneLookupUrl = $"https://maps.googleapis.com/maps/api/timezone/json?location={latitude},{longitude}&timestamp={unixTimeSeconds}&key={_settings.ApiKey}"; string result = await client.GetAsync(timezoneLookupUrl).Result.Content.ReadAsStringAsync(); var timezoneResponse = JsonConvert.DeserializeObject<TimezoneResponse>(result); var offsetTimespan = TimeSpan.FromSeconds(timezoneResponse.rawOffset + timezoneResponse.dstOffset); return (offsetTimespan.Hours, timezoneResponse.timeZoneName); } public async Task<TimezoneLookupResult> GetTimezoneInfoAsync(HttpClient client, string lookup) { var result = new TimezoneLookupResult(); var (latitude, longitude, success) = await GetLatitudeAndLongitude(client, lookup); if (success) { (result.Offset, result.TimezoneName) = await GetTimezoneInfo(client, latitude, longitude); result.Success = true; } else { result.Success = false; result.Message = UNKNOWN_LOCATION; } return result; } } }
41.239437
173
0.656079
[ "MIT" ]
DCurtin/devchatterbot
src/DevChatter.Bot.Infra.GoogleApi/GoogleApiTimezoneLookup.cs
2,928
C#
using UnityEngine; using System.Collections.Generic; namespace Effekseer { /// <summary xml:lang="en"> /// Which scale is A scale of effect based on. /// </summary> /// <summary xml:lang="ja"> /// どのスケールをエフェクトのスケールの元にするか /// </summary> public enum EffekseerEmitterScale { Local, Global, } /// <summary xml:lang="en"> /// Timing of the update /// </summary> /// <summary xml:lang="ja"> /// 更新のタイミング /// </summary> public enum EffekseerEmitterTimingOfUpdate { Update, FixedUpdate, } /// <summary xml:lang="en"> /// A emitter of the Effekseer effect /// </summary> /// <summary xml:lang="ja"> /// エフェクトの発生源 /// </summary> [AddComponentMenu("Effekseer/Effekseer Emitter")] public class EffekseerEmitter : MonoBehaviour { float cachedMagnification = 0.0f; /// <summary xml:lang="en"> /// Timing of the update /// </summary> /// <summary xml:lang="ja"> /// 更新のタイミング /// </summary> public EffekseerEmitterTimingOfUpdate TimingOfUpdate = EffekseerEmitterTimingOfUpdate.Update; /// <summary xml:lang="en"> /// Which scale is A scale of effect based on. /// </summary> /// <summary xml:lang="ja"> /// どのスケールをエフェクトのスケールの元にするか /// </summary> public EffekseerEmitterScale EmitterScale = EffekseerEmitterScale.Local; /// <summary xml:lang="en"> /// TimeScale where the effect is played /// </summary> /// <summary xml:lang="ja"> /// エフェクトが再生されるタイムスケール /// </summary> public EffekseerTimeScale TimeScale = EffekseerTimeScale.Scale; /// <summary xml:lang="en"> /// Effect name /// </summary> /// <summary xml:lang="ja"> /// エフェクト名 /// </summary> //public string effectName; /// <summary xml:lang="en"> /// Effect name /// </summary> /// <summary xml:lang="ja"> /// エフェクト名 /// </summary> public EffekseerEffectAsset effectAsset; /// <summary xml:lang="en"> /// Whether it does play the effect on Start() /// </summary> /// <summary xml:lang="ja"> /// Start()時に再生開始するかどうか /// </summary> public bool playOnStart = false; /// <summary xml:lang="ja"> /// Whether it does loop playback when all effects are stopped /// </summary> /// <summary xml:lang="ja"> /// 全てのエフェクトが停止した後に、ループ再生するかどうか /// </summary> public bool isLooping = false; /// <summary xml:lang="en"> /// The last played handle. /// Don't touch it!! /// </summary> /// <summary xml:lang="ja"> /// 最後にPlayされたハンドル /// Effekseer開発者以外は触ってはいけない /// </summary> public List<EffekseerHandle> handles = new List<EffekseerHandle>(); /// <summary xml:lang="en"> /// Plays the effect. /// <param name="name">Effect name</param> /// </summary> /// <summary xml:lang="ja"> /// エフェクトを再生 /// <param name="name">エフェクト名</param> /// </summary> public EffekseerHandle Play(EffekseerEffectAsset effectAsset) { var h = EffekseerSystem.PlayEffect(effectAsset, transform.position); // must run after loading cachedMagnification = effectAsset.Magnification; ApplyRotationAndScale(ref h); h.layer = gameObject.layer; if (speed != 1.0f) h.speed = speed; if (paused) h.paused = paused; if (shown) h.shown = shown; handles.Add(h); return h; } /// <summary xml:lang="en"> /// Plays the effect that has been set. /// </summary> /// <summary xml:lang="ja"> /// 設定されているエフェクトを再生 /// </summary> public EffekseerHandle Play() { return Play(effectAsset); } /// <summary xml:lang="en"> /// Stops the played effect. /// All nodes will be destroyed. /// </summary> /// <summary xml:lang="ja"> /// 再生中のエフェクトを停止 /// 全てのノードが即座に消える /// </summary> public void Stop() { foreach (var handle in handles) { handle.Stop(); } handles.Clear(); } /// <summary> /// Don't touch it!! /// </summary> public void StopImmediate() { foreach (var handle in handles) { handle.Stop(); handle.UpdateHandle(1); } handles.Clear(); Plugin.EffekseerResetTime(); } /// <summary xml:lang="en"> /// Stops the root node of the played effect. /// The root node will be destroyed. Then children also will be destroyed by their lifetime. /// </summary> /// <summary xml:lang="ja"> /// 再生中のエフェクトのルートノードだけを停止 /// ルートノードを削除したことで子ノード生成が停止され寿命で徐々に消える /// </summary> public void StopRoot() { foreach (var handle in handles) { handle.StopRoot(); } handles.Clear(); } /// <summary xml:lang="en"> /// Specify the color of overall effect. /// </summary> /// <summary xml:lang="ja"> /// エフェクト全体の色を指定する。 /// </summary> /// <param name="color">Color</param> public void SetAllColor(Color color) { foreach (var handle in handles) { handle.SetAllColor(color); } } /// <summary xml:lang="en"> /// Sets the target location of the played effects. /// <param name="targetLocation" xml:lang="en">Target location</param> /// </summary> /// <summary xml:lang="ja"> /// 再生中のエフェクトのターゲット位置を設定 /// <param name="targetLocation" xml:lang="ja">ターゲット位置</param> /// </summary> public void SetTargetLocation(Vector3 targetLocation) { foreach (var handle in handles) { handle.SetTargetLocation(targetLocation); } } /// <summary xml:lang="en"> /// get first effect's dynamic parameter, which changes effect parameters dynamically while playing /// </summary> /// <summary xml:lang="ja"> /// 再生中にエフェクトのパラメーターを変更する最初のエフェクトの動的パラメーターを取得する。 /// </summary> /// <param name="index"></param> /// <returns></returns> public float GetDynamicInput(int index) { foreach (var handle in handles) { return handle.GetDynamicInput(index); } return 0.0f; } /// <summary xml:lang="en"> /// specfiy a dynamic parameter, which changes effect parameters dynamically while playing /// </summary> /// <summary xml:lang="ja"> /// 再生中にエフェクトのパラメーターを変更する動的パラメーターを設定する。 /// </summary> /// <param name="index"></param> /// <param name="value"></param> public void SetDynamicInput(int index, float value) { foreach (var handle in handles) { handle.SetDynamicInput(index, value); } } /// <summary xml:lang="en"> /// specify a dynamic parameters x,y,z with a world position converting into local position considering effect magnification. /// </summary> /// <summary xml:lang="ja"> /// エフェクトの拡大率を考慮しつつ、ローカル座標に変換しつつ、ワールド座標で動的パラメーターx,y,zを設定する。 /// </summary> /// <param name="worldPos"></param> public void SetDynamicInputWithWorldPosition(ref Vector3 worldPos) { var localPos = transform.InverseTransformPoint(worldPos); SetDynamicInputWithLocalPosition(ref localPos); } /// <summary xml:lang="en"> /// specify a dynamic parameters x,y,z with a local position considering effect magnification. /// </summary> /// <summary xml:lang="ja"> /// エフェクトの拡大率を考慮しつつ、ローカル座標座標で動的パラメーターx,y,zを設定する。 /// </summary> /// <param name="worldPos"></param> public void SetDynamicInputWithLocalPosition(ref Vector3 localPos) { SetDynamicInput(0, localPos.x / cachedMagnification); SetDynamicInput(1, localPos.y / cachedMagnification); if (EffekseerSettings.Instance.isRightEffekseerHandledCoordinateSystem) { SetDynamicInput(2, localPos.z / cachedMagnification); } else { SetDynamicInput(2, -localPos.z / cachedMagnification); } } /// <summary xml:lang="en"> /// specify a dynamic parameters x with distance to a world position converting into local position considering effect magnification. /// </summary> /// <summary xml:lang="ja"> /// エフェクトの拡大率を考慮しつつ、ローカル座標に変換しつつ、ワールド座標への距離で動的パラメーターxを設定する。 /// </summary> /// <param name="worldPos"></param> public void SetDynamicInputWithWorldDistance(ref Vector3 worldPos) { var localPos = transform.InverseTransformPoint(worldPos); SetDynamicInputWithLocalDistance(ref localPos); } /// <summary xml:lang="en"> /// specify a dynamic parameters x with distance to a world position converting into local position considering effect magnification. /// </summary> /// <summary xml:lang="ja"> /// エフェクトの拡大率を考慮しつつ、ローカル座標への距離で動的パラメーターxを設定する。 /// </summary> /// <param name="localPos"></param> public void SetDynamicInputWithLocalDistance(ref Vector3 localPos) { SetDynamicInput(0, localPos.magnitude / cachedMagnification); } /// <summary xml:lang="en"> /// Pausing the effect /// <para>true: It will update on Update()</para> /// <para>false: It will not update on Update()</para> /// </summary> /// <summary xml:lang="ja"> /// ポーズ設定 /// <para>true: Updateで更新しない</para> /// <para>false: Updateで更新する</para> /// </summary> public bool paused { set { _paused = value; foreach (var handle in handles) { Plugin.EffekseerSetPaused(handle.m_handle, value); } } get { return _paused; } } private bool _paused = false; /// <summary xml:lang="en"> /// Showing the effect /// <para>true: It will be rendering.</para> /// <para>false: It will not be rendering.</para> /// </summary> /// <summary xml:lang="ja"> /// 表示設定 /// <para>true: 描画する</para> /// <para>false: 描画しない</para> /// </summary> public bool shown { set { _shown = value; foreach (var handle in handles) { Plugin.EffekseerSetShown(handle.m_handle, value); } } get { return _shown; } } private bool _shown = true; /// <summary xml:lang="en"> /// Playback speed /// </summary> /// <summary xml:lang="ja"> /// 再生速度 /// </summary> public float speed { set { _speed = value; foreach (var handle in handles) { Plugin.EffekseerSetSpeed(handle.m_handle, value); } } get { return _speed; } } private float _speed = 1.0f; /// <summary xml:lang="en"> /// Existing state /// <para>true: It's existed.</para> /// <para>false: It isn't existed or stopped.</para> /// </summary> /// <summary xml:lang="ja"> /// 再生中のエフェクトが存在しているか /// <para>true: 存在している</para> /// <para>false: 再生終了で破棄。もしくはStopで停止された</para> /// </summary> public bool exists { get { bool res = false; foreach (var handle in handles) { res |= handle.exists; } return res; } } /// <summary xml:lang="en"> /// Get the number of instance which is used in this effect including root /// </summary> /// <summary xml:lang="ja"> /// Rootを含んだエフェクトに使用されているインスタンス数を取得する。 /// </summary> public int instanceCount { get { int res = 0; foreach (var handle in handles) { res += handle.instanceCount; } return res; } } #region Internal Implimentation void OnEnable() { foreach (var handle in handles) { Plugin.EffekseerSetPaused(handle.m_handle, _paused); } foreach (var handle in handles) { Plugin.EffekseerSetShown(handle.m_handle, _shown); } } void OnDisable() { foreach (var handle in handles) { Plugin.EffekseerSetPaused(handle.m_handle, true); } foreach (var handle in handles) { Plugin.EffekseerSetShown(handle.m_handle, false); } } void Start() { if (effectAsset && playOnStart) { Play(); } } void OnDestroy() { Stop(); } /// <summary> /// Don't touch it!! /// </summary> public void UpdateSelf() { for (int i = 0; i < handles.Count;) { var handle = handles[i]; if (handle.exists) { handle.SetLocation(transform.position); ApplyRotationAndScale(ref handle); i++; } else if (isLooping && handles.Count == 1) { handles.RemoveAt(i); var newHandle = Play(); // avoid infinite loop if (!newHandle.exists) { break; } } else { handles.RemoveAt(i); } } } public void Update() { if (TimingOfUpdate == EffekseerEmitterTimingOfUpdate.Update) { UpdateSelf(); } } public void FixedUpdate() { if (TimingOfUpdate == EffekseerEmitterTimingOfUpdate.FixedUpdate) { UpdateSelf(); } } #endregion void ApplyRotationAndScale(ref EffekseerHandle handle) { handle.SetRotation(transform.rotation); if (EmitterScale == EffekseerEmitterScale.Local) { handle.SetScale(transform.localScale); } else if (EmitterScale == EffekseerEmitterScale.Global) { handle.SetScale(transform.lossyScale); } handle.TimeScale = TimeScale; } } }
22.706422
135
0.632646
[ "MIT" ]
effekseer/EffekseerForUnity
Dev/Plugin/Assets/Effekseer/Scripts/EffekseerEmitter.cs
13,739
C#
using Entitas; using System.Collections.Generic; public class FirstBossStageEntry : BossStage { float timeLimit; public float TimeLimit { get { return timeLimit; } } public int Count { get { return 1; } } public FirstBossStageEntry() { timeLimit = 2.0f; } public void Update(Entity e, float deltaTime) { if (!e.hasTween) { e.AddTween(true, new List<Tween>()); e.tween.AddTween(e.position, EaseTypes.quadIn, PositionAccessorType.X, timeLimit) .From(e.position.pos.x + 5.0f) .To(e.position.pos.x) .BlockClear(); e.tween.AddTween(e.position, EaseTypes.quadOut, PositionAccessorType.Y, timeLimit) .From(e.position.pos.y - 4.0f) .To(e.position.pos.y + GameConfig.CAMERA_SPEED * timeLimit) .BlockClear(); } } }
29.40625
95
0.556854
[ "MIT" ]
kicholen/GamePrototype
Assets/Source/Src/System/Enemy/boss/first/Stage/Entry/FirstBossStageEntry.cs
943
C#
// ---------------------------------------------------------------------------------- // // Copyright Microsoft Corporation // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ---------------------------------------------------------------------------------- using System; using System.Collections.Generic; using System.Linq; using System.Management.Automation; using System.Security.Permissions; using Microsoft.Azure.Commands.DataFactoryV2.Models; namespace Microsoft.Azure.Commands.DataFactoryV2 { [Cmdlet(VerbsCommon.Get, Constants.LinkedService, DefaultParameterSetName = ParameterSetNames.ByFactoryName), OutputType(typeof(PSLinkedService))] public class GetAzureDataFactoryLinkedServiceCommand : DataFactoryContextBaseGetCmdlet { [Parameter(ParameterSetName = ParameterSetNames.ByFactoryName, Position = 2, Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = Constants.HelpLinkedServiceName)] [Parameter(ParameterSetName = ParameterSetNames.ByFactoryObject, Position = 1, Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = Constants.HelpLinkedServiceName)] [Alias(Constants.LinkedServiceName)] [ValidateNotNullOrEmpty] public override string Name { get; set; } [EnvironmentPermission(SecurityAction.Demand, Unrestricted = true)] public override void ExecuteCmdlet() { ByResourceId(); ByFactoryObject(); AdfEntityFilterOptions filterOptions = new AdfEntityFilterOptions() { Name = Name, ResourceGroupName = ResourceGroupName, DataFactoryName = DataFactoryName }; if (Name != null) { List<PSLinkedService> linkedServices = DataFactoryClient.FilterPSLinkedServices(filterOptions); if (linkedServices != null && linkedServices.Any()) { WriteObject(linkedServices[0]); } return; } // List all linked services until all pages are fetched. do { WriteObject(DataFactoryClient.FilterPSLinkedServices(filterOptions), true); } while (filterOptions.NextLink.IsNextPageLink()); } } }
43.447761
151
0.623497
[ "MIT" ]
Philippe-Morin/azure-powershell
src/ResourceManager/DataFactoryV2/Commands.DataFactoryV2/LinkedServices/GetAzureDataFactoryLinkedServiceCommand.cs
2,847
C#
using System; using System.Data; using System.Configuration; using System.Collections; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; using ZoomLa.BLL; using ZoomLa.Common; using ZoomLa.Model; using ZoomLa.Components; public partial class manage_Pub_PubView : CustomerPageAction { private B_User buser = new B_User(); private B_ModelField bfield = new B_ModelField(); private B_Model bmodel = new B_Model(); private B_Pub pubBll = new B_Pub(); private M_Pub pubMod = new M_Pub(); B_Admin admin = new B_Admin(); private B_Pub bpub = new B_Pub(); protected void Page_Load(object sender, EventArgs e) { function.AccessRulo(); B_Admin badmin = new B_Admin(); badmin.CheckIsLogin(); if (!this.Page.IsPostBack) { string Pubid = string.IsNullOrEmpty(Request.QueryString["Pubid"].ToString()) ? "0" : Request.QueryString["Pubid"].ToString(); pubMod = pubBll.SelReturnModel(DataConverter.CLng(Pubid)); string prowinfo = B_Role.GetPowerInfoByIDs(badmin.GetAdminLogin().RoleList); if (!badmin.GetAdminLogin().RoleList.Contains(",1,") && !prowinfo.Contains("," + pubMod.PubTableName + ",")) { function.WriteErrMsg("无权限管理该互动模型!!"); } string ModelID = bpub.GetSelect(DataConverter.CLng(Pubid)).PubModelID.ToString(); // int ModelID = string.IsNullOrEmpty(Request.QueryString["ModelID"]) ? 0 : DataConverter.CLng(Request.QueryString["ModelID"]); this.HiddenPubid.Value = Pubid; if (DataConverter.CLng(ModelID) <= 0) function.WriteErrMsg("缺少用户模型ID参数!"); //jc:查找相应模版实体 // M_ModelInfo model = bmodel.GetModelById(ModelID); string small = string.IsNullOrEmpty(Request.QueryString["small"]) ? "0" : Request.QueryString["small"].ToString(); this.HiddenSmall.Value = small; this.HdnModelID.Value = ModelID; M_ModelInfo model = bmodel.GetModelById(DataConverter.CLng(ModelID)); int ID = string.IsNullOrEmpty(Request.QueryString["ID"]) ? 0 : DataConverter.CLng(Request.QueryString["ID"]); this.HiddenID.Value = ID.ToString(); ViewState["ID"] = ID.ToString(); if (ID < 0) function.WriteErrMsg("缺少ID参数!"); DataTable UserData = new DataTable(); DataTable aas = ShowGrid(); int zong = aas.Rows.Count; UserData = buser.GetUserModeInfo(model.TableName, ID, 18); this.ptit.Text = UserData.Rows[0]["PubTitle"].ToString(); DetailsView1.DataSource = UserData.DefaultView; DetailsView1.DataBind(); Call.SetBreadCrumb(Master, "<li><a href='" + CustomerPageAction.customPath2 + "I/Main.aspx'>工作台</a></li><li><a href='pubmanage.aspx'>互动管理</a></li> <li><a href='Pubsinfo.aspx?Pubid=" + Pubid + "&type=0'>互动信息管理</a></li><li>互动信息</li>"); } } private DataTable ShowGrid() { DataTable dt = this.bfield.GetModelFieldList(DataConverter.CLng(this.HdnModelID.Value)).Tables[0]; DetailsView1.AutoGenerateRows = false; DataControlFieldCollection dcfc = DetailsView1.Fields; dcfc.Clear(); BoundField bf2 = new BoundField(); bf2.HeaderText = "ID"; bf2.DataField = "ID"; bf2.HeaderStyle.Width = Unit.Percentage(15); bf2.HeaderStyle.CssClass = "tdbgleft"; bf2.HeaderStyle.HorizontalAlign = HorizontalAlign.Center; bf2.ItemStyle.HorizontalAlign = HorizontalAlign.Left; dcfc.Add(bf2); BoundField bf5 = new BoundField(); bf5.HeaderText = "用户名"; bf5.DataField = "PubUserName"; bf5.HeaderStyle.CssClass = "tdbgleft"; bf5.HeaderStyle.Width = Unit.Percentage(15); bf5.HeaderStyle.HorizontalAlign = HorizontalAlign.Center; bf5.ItemStyle.HorizontalAlign = HorizontalAlign.Left; dcfc.Add(bf5); BoundField bf1 = new BoundField(); bf1.HeaderText = "标题"; bf1.DataField = "PubTitle"; bf1.HeaderStyle.CssClass = "tdbgleft"; bf1.HeaderStyle.Width = Unit.Percentage(15); bf1.HeaderStyle.HorizontalAlign = HorizontalAlign.Center; bf1.ItemStyle.HorizontalAlign = HorizontalAlign.Left; bf1.HtmlEncode = false; dcfc.Add(bf1); BoundField bfa = new BoundField(); bfa.HeaderText = "内容"; bfa.DataField = "PubContent"; bfa.HeaderStyle.CssClass = "tdbgleft"; bfa.HeaderStyle.Width = Unit.Percentage(15); bfa.HeaderStyle.HorizontalAlign = HorizontalAlign.Center; bfa.ItemStyle.HorizontalAlign = HorizontalAlign.Left; bfa.HtmlEncode = false; dcfc.Add(bfa); BoundField bf3 = new BoundField(); bf3.HeaderText = "IP地址"; bf3.DataField = "PubIP"; bf3.HeaderStyle.CssClass = "tdbgleft"; bf3.HeaderStyle.Width = Unit.Percentage(15); bf3.HeaderStyle.HorizontalAlign = HorizontalAlign.Center; bf3.ItemStyle.HorizontalAlign = HorizontalAlign.Left; bf3.HtmlEncode = false; dcfc.Add(bf3); BoundField bf4 = new BoundField(); bf4.HeaderText = "添加时间"; bf4.DataField = "PubAddTime"; bf4.HeaderStyle.CssClass = "tdbgleft"; bf4.HeaderStyle.Width = Unit.Percentage(15); bf4.HeaderStyle.HorizontalAlign = HorizontalAlign.Center; bf4.ItemStyle.HorizontalAlign = HorizontalAlign.Left; bf4.HtmlEncode = false; dcfc.Add(bf4); foreach (DataRow dr in dt.Rows) { BoundField bf = new BoundField(); bf.HeaderText = dr["FieldAlias"].ToString(); bf.DataField = dr["FieldName"].ToString(); bf.HeaderStyle.Width = Unit.Percentage(15); bf.HeaderStyle.CssClass = "tdbgleft"; bf.HeaderStyle.HorizontalAlign = HorizontalAlign.Center; bf.ItemStyle.HorizontalAlign = HorizontalAlign.Left; bf.HtmlEncode = false; dcfc.Add(bf); } return dt; } protected void Button1_Click(object sender, EventArgs e) { if (this.HiddenSmall.Value!="0") Response.Redirect("ViewSmallPub.aspx?pubid=" + this.HiddenPubid.Value + "&ID=" + this.HiddenSmall.Value); else Response.Redirect("Pubsinfo.aspx?pubid=" + this.HiddenPubid.Value + "&type=0"); } protected void Button2_Click(object sender, EventArgs e) { Response.Redirect("AddPub.aspx?Pubid=" + this.HiddenPubid.Value + "&Parentid=" + ViewState["ID"].ToString()); } }
39.208092
245
0.630842
[ "Apache-2.0" ]
zoomlacms/web022
Source-Code-设客网设计师与设计院作品分享与威客门户网站/Manage/Pub/PubView.aspx.cs
6,909
C#
using System; namespace Protobuild { public interface ICommand { void Encounter(Execution pendingExecution, string[] args); int Execute(Execution execution); string GetDescription(); int GetArgCount(); string[] GetArgNames(); } }
15.210526
66
0.622837
[ "MIT" ]
SjB/Protobuild
Protobuild.Internal/CommandLine/ICommand.cs
291
C#
using System; using System.Collections.Generic; using System.Text; namespace Clustering_Iris.DataStructures { public class IrisData { public float Label; public float SepalLength; public float SepalWidth; public float PetalLength; public float PetalWidth; } }
15.9
40
0.672956
[ "MIT" ]
27theworldinurhand/machinelearning-samples
samples/csharp/getting-started/Clustering_Iris/IrisClustering/IrisClusteringConsoleApp/DataStructures/IrisData.cs
320
C#
using System; using System.Collections.Generic; using System.Windows.Forms; namespace AsyncDialog { static class Program { /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new MdiParentDlg()); } } }
26.705882
65
0.614537
[ "Unlicense" ]
SiddharthMishraPersonal/InterviewPreperation
Winforms/asyncdialog-src/AsyncDialog/Program.cs
454
C#
 using pc2x.Application.Repositories.Repositories; using pc2x.Application.Services.Services; using SimpleInjector; using SimpleInjector.Integration.Wcf; using System; using System.Linq; using System.Reflection; using System.ServiceModel; namespace pc2x.Application.WebServices.WCF { public class WcfServiceFactory : SimpleInjectorServiceHostFactory { protected override ServiceHost CreateServiceHost(Type serviceType, Uri[] baseAddresses) { return new SimpleInjectorServiceHost(Bootsrapper.Container, serviceType, baseAddresses); } } public static class Bootsrapper { public static readonly Container Container; static Bootsrapper() { var container = new Container(); container.Options.DefaultLifestyle = new WcfOperationLifestyle(); RegisterDependency(typeof(PaisRepository).Assembly, "pc2x.Application.Repositories.Repositories", ref container); RegisterDependency(typeof(PaisServicio).Assembly, "pc2x.Application.Services.Services", ref container); container.Register<IPaisContract, ApplicationService>(); //manual registration //container.Register<IPaisRepository, PaisRepository>(); //container.Register<IPaisService, PaisServicio>(); //container.Verify(); Container = container; } private static void RegisterDependency(Assembly assembly, string classNameSpace, ref Container container) { var types = assembly.GetExportedTypes().ToList(); var registrations = (from type in types where (!string.IsNullOrEmpty(type.Namespace)) && type.Namespace.Equals(classNameSpace) where type.GetInterfaces().Any() select new { Services = type.GetInterfaces().ToList(), Implementation = type }); foreach (var reg in registrations) { if (Convert.ToString(reg.Implementation.Attributes).ToLower() .Contains("abstract")) continue; foreach (var service in reg.Services.Where(service => !service.ContainsGenericParameters)) { container.Register(service, reg.Implementation); } } } } }
33.643836
113
0.618485
[ "MIT" ]
pc2x/Wcf_WebApi_Test
pc2x.Application/pc2x.Application.WebServices.WCF/WcfServiceFactory.cs
2,458
C#
/* * Hydrogen Nucleus API * * The Hydrogen Nucleus API * * OpenAPI spec version: 1.9.4 * Contact: info@hydrogenplatform.com * Generated by: https://github.com/swagger-api/swagger-codegen.git */ using NUnit.Framework; using System; using System.Linq; using System.IO; using System.Collections.Generic; using Nucleus.Api; using Nucleus.ModelEntity; using Nucleus.Client; using System.Reflection; using Newtonsoft.Json; namespace Nucleus.Test { /// <summary> /// Class for testing PortfolioHoldingAgg /// </summary> /// <remarks> /// This file is automatically generated by Swagger Codegen. /// Please update the test case below to test the model. /// </remarks> [TestFixture] public class PortfolioHoldingAggTests { // TODO uncomment below to declare an instance variable for PortfolioHoldingAgg //private PortfolioHoldingAgg instance; /// <summary> /// Setup before each test /// </summary> [SetUp] public void Init() { // TODO uncomment below to create an instance of PortfolioHoldingAgg //instance = new PortfolioHoldingAgg(); } /// <summary> /// Clean up after each test /// </summary> [TearDown] public void Cleanup() { } /// <summary> /// Test an instance of PortfolioHoldingAgg /// </summary> [Test] public void PortfolioHoldingAggInstanceTest() { // TODO uncomment below to test "IsInstanceOfType" PortfolioHoldingAgg //Assert.IsInstanceOfType<PortfolioHoldingAgg> (instance, "variable 'instance' is a PortfolioHoldingAgg"); } /// <summary> /// Test the property 'Amount' /// </summary> [Test] public void AmountTest() { // TODO unit test for the property 'Amount' } /// <summary> /// Test the property 'CostBasis' /// </summary> [Test] public void CostBasisTest() { // TODO unit test for the property 'CostBasis' } /// <summary> /// Test the property 'CurrencyCode' /// </summary> [Test] public void CurrencyCodeTest() { // TODO unit test for the property 'CurrencyCode' } /// <summary> /// Test the property 'Date' /// </summary> [Test] public void DateTest() { // TODO unit test for the property 'Date' } /// <summary> /// Test the property 'SecurityId' /// </summary> [Test] public void SecurityIdTest() { // TODO unit test for the property 'SecurityId' } /// <summary> /// Test the property 'Shares' /// </summary> [Test] public void SharesTest() { // TODO unit test for the property 'Shares' } /// <summary> /// Test the property 'Weight' /// </summary> [Test] public void WeightTest() { // TODO unit test for the property 'Weight' } } }
24.992248
118
0.543424
[ "Apache-2.0" ]
ShekharPaatni/SDK
atom/nucleus/csharp/src/Nucleus.Test/Model/PortfolioHoldingAggTests.cs
3,224
C#
// ***************************************************************************** // BSD 3-Clause License (https://github.com/ComponentFactory/Krypton/blob/master/LICENSE) // © Component Factory Pty Ltd, 2006 - 2016, All rights reserved. // The software and associated documentation supplied hereunder are the // proprietary information of Component Factory Pty Ltd, 13 Swallows Close, // Mornington, Vic 3931, Australia and are supplied subject to license terms. // // Modifications by Peter Wagner(aka Wagnerp) & Simon Coghlan(aka Smurf-IV) 2017 - 2020. All rights reserved. (https://github.com/Wagnerp/Krypton-NET-5.462) // Version 5.462.0.0 www.ComponentFactory.com // ***************************************************************************** using System.ComponentModel; using System.Diagnostics; namespace ComponentFactory.Krypton.Toolkit { /// <summary> /// Storage for an individual navigator states. /// </summary> public class KryptonPaletteNavigatorState : Storage { #region Instance Fields #endregion #region Identity /// <summary> /// Initialize a new instance of the KryptonPaletteNavigatorState class. /// </summary> /// <param name="redirect">Inheritence redirection instance.</param> /// <param name="needPaint">Delegate for notifying paint requests.</param> public KryptonPaletteNavigatorState(PaletteRedirect redirect, NeedPaintHandler needPaint) { Debug.Assert(redirect != null); // Create the storage objects Bar = new KryptonPaletteNavigatorStateBar(redirect, needPaint); } #endregion #region IsDefault /// <summary> /// Gets a value indicating if all values are default. /// </summary> [Browsable(false)] public override bool IsDefault => Bar.IsDefault; #endregion #region PopulateFromBase /// <summary> /// Populate values from the base palette. /// </summary> public void PopulateFromBase() { Bar.PopulateFromBase(); } #endregion #region Bar /// <summary> /// Gets access to the navigator bar appearance entries. /// </summary> [KryptonPersist] [Category("Visuals")] [Description("Overrides for defining navigator bar appearance entries.")] [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] public KryptonPaletteNavigatorStateBar Bar { get; } private bool ShouldSerializeStateCommon() { return !Bar.IsDefault; } #endregion } }
35.384615
157
0.593478
[ "BSD-3-Clause" ]
Krypton-Suite-Legacy/Krypton-NET-5.462
Source/Krypton Components/ComponentFactory.Krypton.Toolkit/Palette Component/KryptonPaletteNavigatorState.cs
2,763
C#
using System.Collections; using System.Collections.Generic; using System; using NetRuntimeSystem = System; using System.ComponentModel; using NetOffice.Attributes; using NetOffice.CollectionsGeneric; namespace NetOffice.OutlookApi { /// <summary> /// DispatchInterface Actions /// SupportByVersion Outlook, 9,10,11,12,14,15,16 /// </summary> /// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff868574.aspx </remarks> [SupportByVersion("Outlook", 9,10,11,12,14,15,16)] [EntityType(EntityType.IsDispatchInterface), Enumerator(Enumerator.Reference, EnumeratorInvoke.Custom, "Outlook", 9, 10, 11, 12, 14, 15, 16), HasIndexProperty(IndexInvoke.Method, "Item")] [TypeId("0006303E-0000-0000-C000-000000000046")] public interface Actions : ICOMObject, IEnumerableProvider<NetOffice.OutlookApi.Action> { #region Properties /// <summary> /// SupportByVersion Outlook 9, 10, 11, 12, 14, 15, 16 /// Get /// </summary> /// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff867164.aspx </remarks> [SupportByVersion("Outlook", 9,10,11,12,14,15,16)] [BaseResult] NetOffice.OutlookApi._Application Application { get; } /// <summary> /// SupportByVersion Outlook 9, 10, 11, 12, 14, 15, 16 /// Get /// </summary> /// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff870172.aspx </remarks> [SupportByVersion("Outlook", 9,10,11,12,14,15,16)] NetOffice.OutlookApi.Enums.OlObjectClass Class { get; } /// <summary> /// SupportByVersion Outlook 9, 10, 11, 12, 14, 15, 16 /// Get /// </summary> /// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff862236.aspx </remarks> [SupportByVersion("Outlook", 9,10,11,12,14,15,16)] [BaseResult] NetOffice.OutlookApi._NameSpace Session { get; } /// <summary> /// SupportByVersion Outlook 9, 10, 11, 12, 14, 15, 16 /// Get /// Unknown COM Proxy /// </summary> /// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff869068.aspx </remarks> [SupportByVersion("Outlook", 9,10,11,12,14,15,16), ProxyResult] object Parent { get; } /// <summary> /// SupportByVersion Outlook 9, 10, 11, 12, 14, 15, 16 /// Get /// </summary> /// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff860935.aspx </remarks> [SupportByVersion("Outlook", 9,10,11,12,14,15,16)] Int32 Count { get; } #endregion #region Methods /// <summary> /// SupportByVersion Outlook 9, 10, 11, 12, 14, 15, 16 /// </summary> /// <param name="index">object index</param> [SupportByVersion("Outlook", 9,10,11,12,14,15,16)] [NetRuntimeSystem.Runtime.CompilerServices.IndexerName("Item"), IndexProperty] NetOffice.OutlookApi.Action this[object index] { get; } /// <summary> /// SupportByVersion Outlook 9, 10, 11, 12, 14, 15, 16 /// </summary> /// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff868466.aspx </remarks> [SupportByVersion("Outlook", 9,10,11,12,14,15,16)] NetOffice.OutlookApi.Action Add(); /// <summary> /// SupportByVersion Outlook 9, 10, 11, 12, 14, 15, 16 /// </summary> /// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff868324.aspx </remarks> /// <param name="index">Int32 index</param> [SupportByVersion("Outlook", 9,10,11,12,14,15,16)] void Remove(Int32 index); #endregion #region IEnumerable<NetOffice.OutlookApi.Action> /// <summary> /// SupportByVersion Outlook, 9,10,11,12,14,15,16 /// This is a custom enumerator from NetOffice /// </summary> [SupportByVersion("Outlook", 9, 10, 11, 12, 14, 15, 16)] [CustomEnumerator] new IEnumerator<NetOffice.OutlookApi.Action> GetEnumerator(); #endregion } }
35.62963
188
0.674636
[ "MIT" ]
igoreksiz/NetOffice
Source/Outlook/DispatchInterfaces/Actions.cs
3,850
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.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("MixedReality")] [assembly: AssemblyDescription(".NET SDK of Azure Mixed Reality Management APIs")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Microsoft Corporation")] [assembly: AssemblyProduct("MixedReality")] [assembly: AssemblyCopyright("Copyright © 2020 Microsoft Corporation")] [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: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
45.148148
95
0.776046
[ "MIT" ]
0rland0Wats0n/azure-sdk-for-net
sdk/mixedreality/Microsoft.Azure.Management.MixedReality/src/Properties/AssemblyInfo.cs
1,222
C#
using MarkDoc.Core; using MarkDoc.Linkers; using MarkDoc.MVVM.Helpers; namespace MarkDoc.Plugins.GitMarkdown { public sealed class LinkerStep : BasePluginStep { /// <inheritdoc /> public override string Name => "Linker configuration"; /// <inheritdoc /> public override int StepNumber => 3; /// <inheritdoc /> public override IView GetStepView(ILibrarySettings? settings = default) { var view = TypeResolver.Resolve<IStepView<IStepViewModel<ILinkerSettings>, ILinkerSettings>>(); return view; } } }
23.208333
101
0.689408
[ "MIT" ]
hailstorm75/MarkDoc.Core
src/Plugins/MarkDoc.Plugins.GitMarkdown/LinkerStep.cs
559
C#
using System; namespace Otoge { static class Entry { static void Main(string[] args) { Console.WriteLine("Hello World!"); new Game(1280, 720, "Otoge").Run(); } } }
12.857143
38
0.627778
[ "MIT" ]
Xeltica/otoge
src/Entry.cs
180
C#
// <auto-generated /> using System; using IdentitySample.Data; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Storage.ValueConversion; namespace IdentitySample.Data.Migrations { [DbContext(typeof(ApplicationDbContext))] partial class ApplicationDbContextModelSnapshot : ModelSnapshot { protected override void BuildModel(ModelBuilder modelBuilder) { #pragma warning disable 612, 618 modelBuilder .HasAnnotation("ProductVersion", "2.1.0") .HasAnnotation("Relational:MaxIdentifierLength", 128) .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRole", b => { b.Property<string>("Id") .ValueGeneratedOnAdd(); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken(); b.Property<string>("Name") .HasMaxLength(256); b.Property<string>("NormalizedName") .HasMaxLength(256); b.HasKey("Id"); b.HasIndex("NormalizedName") .IsUnique() .HasName("RoleNameIndex") .HasFilter("[NormalizedName] IS NOT NULL"); b.ToTable("AspNetRoles"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<string>", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("ClaimType"); b.Property<string>("ClaimValue"); b.Property<string>("RoleId") .IsRequired(); b.HasKey("Id"); b.HasIndex("RoleId"); b.ToTable("AspNetRoleClaims"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUser", b => { b.Property<string>("Id") .ValueGeneratedOnAdd(); b.Property<int>("AccessFailedCount"); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken(); b.Property<string>("Email") .HasMaxLength(256); b.Property<bool>("EmailConfirmed"); b.Property<bool>("LockoutEnabled"); b.Property<DateTimeOffset?>("LockoutEnd"); b.Property<string>("NormalizedEmail") .HasMaxLength(256); b.Property<string>("NormalizedUserName") .HasMaxLength(256); b.Property<string>("PasswordHash"); b.Property<string>("PhoneNumber"); b.Property<bool>("PhoneNumberConfirmed"); b.Property<string>("SecurityStamp"); b.Property<bool>("TwoFactorEnabled"); b.Property<string>("UserName") .HasMaxLength(256); b.HasKey("Id"); b.HasIndex("NormalizedEmail") .HasName("EmailIndex"); b.HasIndex("NormalizedUserName") .IsUnique() .HasName("UserNameIndex") .HasFilter("[NormalizedUserName] IS NOT NULL"); b.ToTable("AspNetUsers"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<string>", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("ClaimType"); b.Property<string>("ClaimValue"); b.Property<string>("UserId") .IsRequired(); b.HasKey("Id"); b.HasIndex("UserId"); b.ToTable("AspNetUserClaims"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<string>", b => { b.Property<string>("LoginProvider") .HasMaxLength(128); b.Property<string>("ProviderKey") .HasMaxLength(128); b.Property<string>("ProviderDisplayName"); b.Property<string>("UserId") .IsRequired(); b.HasKey("LoginProvider", "ProviderKey"); b.HasIndex("UserId"); b.ToTable("AspNetUserLogins"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<string>", b => { b.Property<string>("UserId"); b.Property<string>("RoleId"); b.HasKey("UserId", "RoleId"); b.HasIndex("RoleId"); b.ToTable("AspNetUserRoles"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<string>", b => { b.Property<string>("UserId"); b.Property<string>("LoginProvider") .HasMaxLength(128); b.Property<string>("Name") .HasMaxLength(128); b.Property<string>("Value"); b.HasKey("UserId", "LoginProvider", "Name"); b.ToTable("AspNetUserTokens"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<string>", b => { b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole") .WithMany() .HasForeignKey("RoleId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<string>", b => { b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser") .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<string>", b => { b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser") .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<string>", b => { b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole") .WithMany() .HasForeignKey("RoleId") .OnDelete(DeleteBehavior.Cascade); b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser") .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<string>", b => { b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser") .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade); }); #pragma warning restore 612, 618 } } }
35.008511
125
0.485232
[ "MIT" ]
IUCrimson/AspNet.Security.CAS
samples/IdentitySample/Data/Migrations/ApplicationDbContextModelSnapshot.cs
8,227
C#
namespace Kapi.API.Core.Extensions { using Kapi.API.Core.Models; using Microsoft.AspNetCore.Authentication.JwtBearer; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Options; using Microsoft.IdentityModel.Tokens; using System; using System.IdentityModel.Tokens.Jwt; using System.Security.Claims; public static class SecurityExtensions { public static void AddJwtConfiguration ( this IServiceCollection services ) { _ = services.AddSingleton<SigningSettings>(); ServiceProvider? provider = services.BuildServiceProvider(); SigningSettings? signingSettings = provider.GetService<SigningSettings>(); IOptions<JwtSettings>? tokenSettings = provider.GetService<IOptions<JwtSettings>>(); _ = services.AddAuthentication(authOptions => { authOptions.DefaultSignInScheme = JwtBearerDefaults.AuthenticationScheme; authOptions.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; authOptions.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; }).AddJwtBearer(options => { options.SaveToken = true; options.RequireHttpsMetadata = false; options.TokenValidationParameters = new TokenValidationParameters { ValidateIssuer = false, ValidIssuer = tokenSettings?.Value.Issuer, ValidateAudience = false, ValidAudience = tokenSettings?.Value.Issuer, ValidateLifetime = true, RequireExpirationTime = true, ValidateIssuerSigningKey = true, IssuerSigningKey = signingSettings?.SigningCredentials.Key, ClockSkew = TimeSpan.Zero, }; }); } public static object CreateJwtToken ( this ClaimsIdentity identity, JwtSettings jwtSettings, SigningSettings signingSettings ) { JwtSecurityTokenHandler tokenHandler = new(); SecurityTokenDescriptor tokenDescriptor = new() { Subject = identity, Issuer = jwtSettings.Issuer, IssuedAt = jwtSettings.IssuedAt, Audience = jwtSettings.Audience, Expires = jwtSettings.Expiration, NotBefore = jwtSettings.NotBefore, SigningCredentials = signingSettings.SigningCredentials, }; SecurityToken token = tokenHandler.CreateToken(tokenDescriptor); return new { access_token = tokenHandler.WriteToken(token), token_type = JwtBearerDefaults.AuthenticationScheme.ToLower(), expires_in = jwtSettings.ValidFor.TotalSeconds, }; } } }
37.493827
96
0.598617
[ "MIT" ]
luca16s/CapybaraFinancePlanner
Kapi.API.Core/Extensions/SecurityExtensions.cs
3,039
C#
using LandWin.Venues.DataCollection.Commands; using NServiceBus; using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; namespace LandWin.Venues.DataCollection.Web.Controllers { [RoutePrefix("api/commands")] public class CommandController : ApiController { private readonly IBus _bus; public CommandController(IBus bus) { if (bus == null) throw new ArgumentNullException("bus"); _bus = bus; } [HttpGet] [Route("SyncProduct/{merchant}")] public void SyncProduct(string merchant) { _bus.Send(new SyncProduct() { MerchantName = merchant }); } } }
21.076923
68
0.587591
[ "MIT" ]
stephsun06/Landwin.Veunue
LandWin.Venues.DataCollection.Web/Controllers/CommandController.cs
824
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace WebApplication1 { public partial class TryCatch { /// <summary> /// form1 control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.HtmlControls.HtmlForm form1; /// <summary> /// TextBox1 control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.TextBox TextBox1; /// <summary> /// TextBox2 control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.TextBox TextBox2; /// <summary> /// EqualButton control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.ImageButton EqualButton; /// <summary> /// Label1 control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.Label Label1; /// <summary> /// lblMessage control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.Label lblMessage; } }
34.585714
85
0.503924
[ "MIT" ]
loozixuan/Degree-RSD-Materials
BAIT2113 Web Application Development/Practical9/TryCatch.aspx.designer.cs
2,423
C#
#nullable disable using System; using System.IO; namespace SharpCompress.Compressors.Xz { [CLSCompliant(false)] public sealed class XZStream : XZReadOnlyStream { public static bool IsXZStream(Stream stream) { try { return null != XZHeader.FromStream(stream); } catch (Exception) { return false; } } private void AssertBlockCheckTypeIsSupported() { switch (Header.BlockCheckType) { case CheckType.NONE: break; case CheckType.CRC32: break; case CheckType.CRC64: break; case CheckType.SHA256: throw new NotImplementedException(); default: throw new NotSupportedException("Check Type unknown to this version of decoder."); } } public XZHeader Header { get; private set; } public XZIndex Index { get; private set; } public XZFooter Footer { get; private set; } public bool HeaderIsRead { get; private set; } private XZBlock _currentBlock; private bool _endOfStream; public XZStream(Stream stream) : base(stream) { } public override int Read(byte[] buffer, int offset, int count) { int bytesRead = 0; if (_endOfStream) { return bytesRead; } if (!HeaderIsRead) { ReadHeader(); } bytesRead = ReadBlocks(buffer, offset, count); if (bytesRead < count) { _endOfStream = true; ReadIndex(); ReadFooter(); } return bytesRead; } private void ReadHeader() { Header = XZHeader.FromStream(BaseStream); AssertBlockCheckTypeIsSupported(); HeaderIsRead = true; } private void ReadIndex() { Index = XZIndex.FromStream(BaseStream, true); // TODO veryfy Index } private void ReadFooter() { Footer = XZFooter.FromStream(BaseStream); // TODO verify footer } private int ReadBlocks(byte[] buffer, int offset, int count) { int bytesRead = 0; if (_currentBlock is null) { NextBlock(); } for (; ; ) { try { if (bytesRead >= count) { break; } int remaining = count - bytesRead; int newOffset = offset + bytesRead; int justRead = _currentBlock.Read(buffer, newOffset, remaining); if (justRead < remaining) { NextBlock(); } bytesRead += justRead; } catch (XZIndexMarkerReachedException) { break; } } return bytesRead; } private void NextBlock() { _currentBlock = new XZBlock(BaseStream, Header.BlockCheckType, Header.BlockCheckSize); } } }
26.268657
102
0.45
[ "MIT" ]
Artentus/sharpcompress
src/SharpCompress/Compressors/Xz/XZStream.cs
3,522
C#
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Reflection; using System.Text; using System.Threading.Tasks; namespace Tests { public class ReflectionHelper { private static Tuple<object, PropertyInfo> GetProperty(object source, string propertyName) { PropertyInfo foundProperty = null; var propertyPath = propertyName.Split('.'); if (propertyPath.Length > 0) { try { foundProperty = source.GetType().GetProperties() .FirstOrDefault( x => x.Name.Equals(propertyPath.FirstOrDefault(), StringComparison.OrdinalIgnoreCase)); } catch (ArgumentNullException) { return null; } } if (foundProperty == null) return new Tuple<object, PropertyInfo>(source, null); propertyName = propertyName.Substring(propertyPath.FirstOrDefault().Length); if (!propertyName.Contains('.')) return new Tuple<object, PropertyInfo>(source, foundProperty); var propertyValue = foundProperty.GetValue(source, null); return GetProperty(propertyValue, propertyName.Substring(1)); } /// <summary> /// Gets value from a property name and object. /// When nested property, use full name eg: Customer.Email /// </summary> /// <param name="source"></param> /// <param name="propertyName"></param> /// <returns></returns> public static object GetPropertyValue(object source, string propertyName) { var foundProperty = GetProperty(source, propertyName); return foundProperty.Item2.GetValue(foundProperty.Item1, null); } /// <summary> /// Sets an object's property value by using reflection /// </summary> /// <param name="source"> source object</param> /// <param name="propertyName">name of the property to check</param> /// <param name="value"></param> /// <returns>true if property's value updated otherwise false</returns> public static bool SetPropertyValue(object source, string propertyName, object value) { var foundProperty = GetProperty(source, propertyName); if (foundProperty == null) return false; foundProperty.Item2.SetValue(foundProperty.Item1, value, null); return true; } /// <summary> /// Creates a property selector expression based on a type /// </summary> /// <typeparam name="T"></typeparam> /// <param name="propertyName"></param> /// <returns></returns> public static Expression<Func<T, dynamic>> CreateExpression<T>(object propertyName) { var param = Expression.Parameter(typeof (T), "x"); var body = propertyName.ToString() .Split('.') .Aggregate<string, Expression>(param, Expression.PropertyOrField); return Expression.Lambda<Func<T, dynamic>>(body, param); } } }
36.988889
115
0.577351
[ "MIT" ]
AJJTEAM/checkou-payment-api-client
Checkout.ApiClient.Tests/Utils/ReflectionHelper.cs
3,331
C#
// *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AzureNative.Cache.Latest.Outputs { [OutputType] public sealed class SkuResponse { /// <summary> /// The size of the RedisEnterprise cluster. Defaults to 2 or 3 depending on SKU. Valid values are (2, 4, 6, ...) for Enterprise SKUs and (3, 9, 15, ...) for Flash SKUs. /// </summary> public readonly int? Capacity; /// <summary> /// The type of RedisEnterprise cluster to deploy. Possible values: (Enterprise_E10, EnterpriseFlash_F300 etc.) /// </summary> public readonly string Name; [OutputConstructor] private SkuResponse( int? capacity, string name) { Capacity = capacity; Name = name; } } }
29.777778
177
0.624067
[ "Apache-2.0" ]
pulumi-bot/pulumi-azure-native
sdk/dotnet/Cache/Latest/Outputs/SkuResponse.cs
1,072
C#
namespace JetBrains.ReSharper.Plugins.Unity.Yaml.Psi { public static class UnityYamlConstants { public static readonly string AssetsFolder = "Assets"; public static readonly string Prefab = ".prefab"; public static readonly string Scene = ".unity"; public static readonly string MonoScript = ".cs"; // Unity components public static readonly string TransformComponent = "Transform"; public static readonly string RectTransformComponent = "RectTransform"; // Yaml file properties public static readonly string GameObjectProperty = "m_GameObject"; public static readonly string RootOrderProperty = "m_RootOrder"; public static readonly string NameProperty = "m_Name"; public static readonly string ScriptProperty = "m_Script"; public static readonly string FatherProperty = "m_Father"; public static readonly string CorrespondingSourceObjectProperty = "m_CorrespondingSourceObject"; public static readonly string CorrespondingSourceObjectProperty2017 = "m_PrefabParentObject"; public static readonly string PrefabInstanceProperty = "m_PrefabInstance"; public static readonly string PrefabInstanceProperty2017 = "m_PrefabInternal"; public static readonly string TransformParentProperty = "m_TransformParent"; public static readonly string ModificationProperty = "m_Modification"; public static readonly string Components = "m_Component"; public static readonly string Children = "m_Children"; public static readonly string ModificationsProperty = "m_Modifications"; public const string StateMachineBehavioursProperty = "m_StateMachineBehaviours"; public const string ChildStateMachinesProperty = "m_ChildStateMachines"; public const string ChildStatesProperty = "m_ChildStates"; public const string StateProperty = "m_State"; public const string StateMachineProperty = "m_StateMachine"; public const string EventsProperty = "m_Events"; // prefab modifications public static readonly string PropertyPathProperty = "propertyPath"; public static readonly string TargetProperty = "target"; public static readonly string ValueProperty = "value"; } }
53.159091
104
0.722959
[ "Apache-2.0" ]
JetBrains/resharper-unity
resharper/resharper-unity/src/Yaml/Psi/UnityYamlConstants.cs
2,339
C#
using System; namespace RocketMQ.Client { public class CloneGroupOffsetRequestHeader : CommandCustomHeader { [CFNotNull] public string srcGroup { get; set; } [CFNotNull] public string destGroup { get; set; } public string topic { get; set; } public bool offline { get; set; } public void checkFields() { } } }
22.411765
68
0.606299
[ "MIT" ]
leeveel/RocketMQ.Client
RocketMQ.Client/Protocal/Header/CloneGroupOffsetRequestHeader.cs
383
C#
namespace GoshoSecurity.Models { public class UserLoginModel { public string Username { get; set; } public string Password { get; set; } } }
18.888889
44
0.617647
[ "MIT" ]
vividmaniac/GoshoSecurity
project/GoshoSecurity/GoshoSecurity/Models/UserLoginModel.cs
172
C#
namespace Dazor.Cli.Commands { internal class SeedApplyCommand { } }
14.6
35
0.739726
[ "MIT" ]
OlsonDev/Dazor
Dazor/Cli/Commands/SeedApplyCommand.cs
73
C#
using System.Collections.Generic; namespace SimplePatch { public class DeltaCollection<TEntity> : List<Delta<TEntity>> where TEntity : class, new() { } }
22.857143
97
0.7375
[ "Apache-2.0" ]
OmarMuscatello/SimplePatch
src/SimplePatch/DeltaCollection.cs
162
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // <auto-generated/> #nullable disable using System.Text.Json; using Azure.Core; using Azure.ResourceManager; namespace Azure.ResourceManager.Resources { public partial class ScriptLogData : IUtf8JsonSerializable { void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) { writer.WriteStartObject(); writer.WritePropertyName("properties"); writer.WriteStartObject(); writer.WriteEndObject(); writer.WriteEndObject(); } internal static ScriptLogData DeserializeScriptLogData(JsonElement element) { ResourceIdentifier id = default; string name = default; ResourceType type = default; Optional<string> log = default; foreach (var property in element.EnumerateObject()) { if (property.NameEquals("id")) { id = property.Value.GetString(); continue; } if (property.NameEquals("name")) { name = property.Value.GetString(); continue; } if (property.NameEquals("type")) { type = property.Value.GetString(); continue; } if (property.NameEquals("properties")) { if (property.Value.ValueKind == JsonValueKind.Null) { property.ThrowNonNullablePropertyIsNull(); continue; } foreach (var property0 in property.Value.EnumerateObject()) { if (property0.NameEquals("log")) { log = property0.Value.GetString(); continue; } } continue; } } return new ScriptLogData(id, name, type, log.Value); } } }
31.771429
83
0.476619
[ "MIT" ]
Cardsareus/azure-sdk-for-net
sdk/resources/Azure.ResourceManager.Resources/src/Generated/Models/ScriptLogData.Serialization.cs
2,224
C#
// // This file was auto-generated using the ChilliConnect SDK Generator. // // The MIT License (MIT) // // Copyright (c) 2015 Tag Games Ltd // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // using System; using System.Collections.Generic; using System.Diagnostics; using SdkCore; namespace ChilliConnect { /// <summary> /// <para>A container for information on any errors that occur during a /// GetZipPackageDefinitionsRequest.</para> /// /// <para>This is immutable after construction and is therefore thread safe.</para> /// </summary> public sealed class GetZipPackageDefinitionsError { /// <summary> /// An enum describing each of the possible error codes that can be returned from a /// CCGetZipPackageDefinitionsRequest. /// </summary> public enum Error { /// <summary> /// A connection could not be established. /// </summary> CouldNotConnect = -2, /// <summary> /// An unexpected, fatal error has occured on the server. /// </summary> UnexpectedError = 1, /// <summary> /// Invalid Request. One of more of the provided fields were not correctly formatted. /// The data property of the response body will contain specific error messages for /// each field. /// </summary> InvalidRequest = 1007, /// <summary> /// Rate Limit Reached. Too many requests. Player has been rate limited. /// </summary> RateLimitReached = 10002, /// <summary> /// Expired Connect Access Token. The Connect Access Token used to authenticate with /// the server has expired and should be renewed. /// </summary> ExpiredConnectAccessToken = 1003, /// <summary> /// Invalid Connect Access Token. The Connect Access Token was not valid and cannot /// be used to authenticate requests. /// </summary> InvalidConnectAccessToken = 1004, /// <summary> /// Catalog Not Published. The game has no published Catalog. /// </summary> CatalogNotPublished = 10105 } private const int SuccessHttpResponseCode = 200; private const int UnexpectedErrorHttpResponseCode = 500; /// <summary> /// A code describing the error that has occurred. /// </summary> public Error ErrorCode { get; private set; } /// <summary> /// A description of the error that as occurred. /// </summary> public string ErrorDescription { get; private set; } /// <summary> /// A dictionary of additional, error specific information. /// </summary> public MultiTypeValue ErrorData { get; private set; } /// <summary> /// Initialises a new instance from the given server response. The server response /// must describe an error otherwise this will throw an error. /// </summary> /// /// <param name="serverResponse">The server response from which to initialise this error. /// The response must describe an error state.</param> public GetZipPackageDefinitionsError(ServerResponse serverResponse) { ReleaseAssert.IsNotNull(serverResponse, "A server response must be supplied."); ReleaseAssert.IsTrue(serverResponse.Result != HttpResult.Success || serverResponse.HttpResponseCode != SuccessHttpResponseCode, "Input server response must describe an error."); switch (serverResponse.Result) { case HttpResult.Success: if (serverResponse.HttpResponseCode == UnexpectedErrorHttpResponseCode) { ErrorCode = Error.UnexpectedError; ErrorData = MultiTypeValue.Null; } else { ErrorCode = GetErrorCode(serverResponse); ErrorData = GetErrorData(serverResponse.Body); } break; case HttpResult.CouldNotConnect: ErrorCode = Error.CouldNotConnect; ErrorData = MultiTypeValue.Null; break; default: throw new ArgumentException("Invalid value for server response result."); } ErrorDescription = GetErrorDescription(ErrorCode); } /// <summary> /// Initialises a new instance from the given error code. /// </summary> /// /// <param name="errorCode">The error code.</param> public GetZipPackageDefinitionsError(Error errorCode) { ErrorCode = errorCode; ErrorData = MultiTypeValue.Null; ErrorDescription = GetErrorDescription(ErrorCode); } /// <summary> /// Parses the response body to get the response code. /// </summary> /// /// <returns>The error code in the given response body.</returns> /// /// <param name="serverResponse">The server response from which to get the error code. This /// must describe an successful response from the server which contains an error in the /// response body.</param> private static Error GetErrorCode(ServerResponse serverResponse) { const string JsonKeyErrorCode = "Code"; ReleaseAssert.IsNotNull(serverResponse, "A server response must be supplied."); ReleaseAssert.IsTrue(serverResponse.Result == HttpResult.Success, "The result must describe a successful server response."); ReleaseAssert.IsTrue(serverResponse.HttpResponseCode != SuccessHttpResponseCode && serverResponse.HttpResponseCode != UnexpectedErrorHttpResponseCode, "Must not be a successful or unexpected HTTP response code."); object errorCodeObject = serverResponse.Body[JsonKeyErrorCode]; ReleaseAssert.IsTrue(errorCodeObject is long, "'Code' must be a long."); long errorCode = (long)errorCodeObject; switch (errorCode) { case 1007: ReleaseAssert.IsTrue(serverResponse.HttpResponseCode == 422, @"Invalid HTTP response code for error code."); return Error.InvalidRequest; case 10002: ReleaseAssert.IsTrue(serverResponse.HttpResponseCode == 429, @"Invalid HTTP response code for error code."); return Error.RateLimitReached; case 1003: ReleaseAssert.IsTrue(serverResponse.HttpResponseCode == 401, @"Invalid HTTP response code for error code."); return Error.ExpiredConnectAccessToken; case 1004: ReleaseAssert.IsTrue(serverResponse.HttpResponseCode == 401, @"Invalid HTTP response code for error code."); return Error.InvalidConnectAccessToken; case 10105: ReleaseAssert.IsTrue(serverResponse.HttpResponseCode == 401, @"Invalid HTTP response code for error code."); return Error.CatalogNotPublished; default: return Error.UnexpectedError; } } /// <summary> /// Extracts the error data json from the given response body. /// </summary> /// /// <returns>The additional error data.<returns/> /// /// <param name="responseBody">The response body containing the error data.</param> private static MultiTypeValue GetErrorData(IDictionary<string, object> responseBody) { const string JsonKeyErrorData = "Data"; ReleaseAssert.IsNotNull(responseBody, "The response body cannot be null."); if (!responseBody.ContainsKey(JsonKeyErrorData)) { return MultiTypeValue.Null; } return new MultiTypeValue(responseBody[JsonKeyErrorData]); } /// <summary> /// Gets the error message for the given error code. /// </summary> /// /// <returns>The error message.</returns> /// /// <param name="errorCode">The error code.</param> private static string GetErrorDescription(Error errorCode) { switch (errorCode) { case Error.CouldNotConnect: return "A connection could not be established."; case Error.InvalidRequest: return "Invalid Request. One of more of the provided fields were not correctly formatted." + " The data property of the response body will contain specific error messages for" + " each field."; case Error.RateLimitReached: return "Rate Limit Reached. Too many requests. Player has been rate limited."; case Error.ExpiredConnectAccessToken: return "Expired Connect Access Token. The Connect Access Token used to authenticate with" + " the server has expired and should be renewed."; case Error.InvalidConnectAccessToken: return "Invalid Connect Access Token. The Connect Access Token was not valid and cannot" + " be used to authenticate requests."; case Error.CatalogNotPublished: return "Catalog Not Published. The game has no published Catalog."; case Error.UnexpectedError: default: return "An unexpected server error occurred."; } } } }
37.195313
180
0.691766
[ "MIT" ]
ChilliConnect/Samples
UnitySamples/CharacterGacha/Assets/ChilliConnect/GeneratedSource/Errors/GetZipPackageDefinitionsError.cs
9,522
C#
using Elastic.Xunit.XunitPlumbing; using Nest; using System.ComponentModel; namespace Examples.Ml.AnomalyDetection.Apis { public class UpdateDatafeedPage : ExampleBase { [U(Skip = "Example not implemented")] [Description("ml/anomaly-detection/apis/update-datafeed.asciidoc:112")] public void Line112() { // tag::df6d5b5f8e1c8785503269ccb7b34763[] var response0 = new SearchResponse<object>(); // end::df6d5b5f8e1c8785503269ccb7b34763[] response0.MatchesExample(@"POST _ml/datafeeds/datafeed-total-requests/_update { ""query"": { ""term"": { ""level"": ""error"" } } }"); } } }
23.777778
80
0.67757
[ "Apache-2.0" ]
adamralph/elasticsearch-net
tests/Examples/Ml/AnomalyDetection/Apis/UpdateDatafeedPage.cs
642
C#
using System; using System.Collections.Generic; using System.Text; using System.Linq; using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using HuaweiCloud.SDK.Core; namespace HuaweiCloud.SDK.Vod.V1.Model { /// <summary> /// /// </summary> public class UpdateWatermarkTemplateReq { /// <summary> /// 水印的位置&lt;br/&gt; /// </summary> /// <value>水印的位置&lt;br/&gt;</value> [JsonConverter(typeof(EnumClassConverter<PositionEnum>))] public class PositionEnum { /// <summary> /// Enum TOPRIGHT for value: TOPRIGHT /// </summary> public static readonly PositionEnum TOPRIGHT = new PositionEnum("TOPRIGHT"); /// <summary> /// Enum TOPLEFT for value: TOPLEFT /// </summary> public static readonly PositionEnum TOPLEFT = new PositionEnum("TOPLEFT"); /// <summary> /// Enum BOTTOMRIGHT for value: BOTTOMRIGHT /// </summary> public static readonly PositionEnum BOTTOMRIGHT = new PositionEnum("BOTTOMRIGHT"); /// <summary> /// Enum BOTTOMLEFT for value: BOTTOMLEFT /// </summary> public static readonly PositionEnum BOTTOMLEFT = new PositionEnum("BOTTOMLEFT"); private static readonly Dictionary<string, PositionEnum> StaticFields = new Dictionary<string, PositionEnum>() { { "TOPRIGHT", TOPRIGHT }, { "TOPLEFT", TOPLEFT }, { "BOTTOMRIGHT", BOTTOMRIGHT }, { "BOTTOMLEFT", BOTTOMLEFT }, }; private string Value; public PositionEnum(string value) { Value = value; } public static PositionEnum FromValue(string value) { if(value == null){ return null; } if (StaticFields.ContainsKey(value)) { return StaticFields[value]; } return null; } public string GetValue() { return Value; } public override string ToString() { return $"{Value}"; } public override int GetHashCode() { return this.Value.GetHashCode(); } public override bool Equals(object obj) { if (obj == null) { return false; } if (ReferenceEquals(this, obj)) { return true; } if (this.Equals(obj as PositionEnum)) { return true; } return false; } public bool Equals(PositionEnum obj) { if ((object)obj == null) { return false; } return StringComparer.OrdinalIgnoreCase.Equals(this.Value, obj.Value); } public static bool operator ==(PositionEnum a, PositionEnum b) { if (System.Object.ReferenceEquals(a, b)) { return true; } if ((object)a == null) { return false; } return a.Equals(b); } public static bool operator !=(PositionEnum a, PositionEnum b) { return !(a == b); } } /// <summary> /// 水印类型,当前只支持Image(图片水印)&lt;br/&gt; /// </summary> /// <value>水印类型,当前只支持Image(图片水印)&lt;br/&gt;</value> [JsonConverter(typeof(EnumClassConverter<WatermarkTypeEnum>))] public class WatermarkTypeEnum { /// <summary> /// Enum IMAGE for value: IMAGE /// </summary> public static readonly WatermarkTypeEnum IMAGE = new WatermarkTypeEnum("IMAGE"); /// <summary> /// Enum TEXT for value: TEXT /// </summary> public static readonly WatermarkTypeEnum TEXT = new WatermarkTypeEnum("TEXT"); private static readonly Dictionary<string, WatermarkTypeEnum> StaticFields = new Dictionary<string, WatermarkTypeEnum>() { { "IMAGE", IMAGE }, { "TEXT", TEXT }, }; private string Value; public WatermarkTypeEnum(string value) { Value = value; } public static WatermarkTypeEnum FromValue(string value) { if(value == null){ return null; } if (StaticFields.ContainsKey(value)) { return StaticFields[value]; } return null; } public string GetValue() { return Value; } public override string ToString() { return $"{Value}"; } public override int GetHashCode() { return this.Value.GetHashCode(); } public override bool Equals(object obj) { if (obj == null) { return false; } if (ReferenceEquals(this, obj)) { return true; } if (this.Equals(obj as WatermarkTypeEnum)) { return true; } return false; } public bool Equals(WatermarkTypeEnum obj) { if ((object)obj == null) { return false; } return StringComparer.OrdinalIgnoreCase.Equals(this.Value, obj.Value); } public static bool operator ==(WatermarkTypeEnum a, WatermarkTypeEnum b) { if (System.Object.ReferenceEquals(a, b)) { return true; } if ((object)a == null) { return false; } return a.Equals(b); } public static bool operator !=(WatermarkTypeEnum a, WatermarkTypeEnum b) { return !(a == b); } } /// <summary> /// type设置为Image时有效。 目前包括: - Original:只做简单缩放,不做其他处理 - Transparent:图片底色透明 - Grayed:彩色图片变灰 /// </summary> /// <value>type设置为Image时有效。 目前包括: - Original:只做简单缩放,不做其他处理 - Transparent:图片底色透明 - Grayed:彩色图片变灰</value> [JsonConverter(typeof(EnumClassConverter<ImageProcessEnum>))] public class ImageProcessEnum { /// <summary> /// Enum ORIGINAL for value: ORIGINAL /// </summary> public static readonly ImageProcessEnum ORIGINAL = new ImageProcessEnum("ORIGINAL"); /// <summary> /// Enum TRANSPARENT for value: TRANSPARENT /// </summary> public static readonly ImageProcessEnum TRANSPARENT = new ImageProcessEnum("TRANSPARENT"); /// <summary> /// Enum GRAYED for value: GRAYED /// </summary> public static readonly ImageProcessEnum GRAYED = new ImageProcessEnum("GRAYED"); private static readonly Dictionary<string, ImageProcessEnum> StaticFields = new Dictionary<string, ImageProcessEnum>() { { "ORIGINAL", ORIGINAL }, { "TRANSPARENT", TRANSPARENT }, { "GRAYED", GRAYED }, }; private string Value; public ImageProcessEnum(string value) { Value = value; } public static ImageProcessEnum FromValue(string value) { if(value == null){ return null; } if (StaticFields.ContainsKey(value)) { return StaticFields[value]; } return null; } public string GetValue() { return Value; } public override string ToString() { return $"{Value}"; } public override int GetHashCode() { return this.Value.GetHashCode(); } public override bool Equals(object obj) { if (obj == null) { return false; } if (ReferenceEquals(this, obj)) { return true; } if (this.Equals(obj as ImageProcessEnum)) { return true; } return false; } public bool Equals(ImageProcessEnum obj) { if ((object)obj == null) { return false; } return StringComparer.OrdinalIgnoreCase.Equals(this.Value, obj.Value); } public static bool operator ==(ImageProcessEnum a, ImageProcessEnum b) { if (System.Object.ReferenceEquals(a, b)) { return true; } if ((object)a == null) { return false; } return a.Equals(b); } public static bool operator !=(ImageProcessEnum a, ImageProcessEnum b) { return !(a == b); } } /// <summary> /// 水印模板配置id&lt;br/&gt; /// </summary> [JsonProperty("id", NullValueHandling = NullValueHandling.Ignore)] public string Id { get; set; } /// <summary> /// 水印模板名称&lt;br/&gt; /// </summary> [JsonProperty("name", NullValueHandling = NullValueHandling.Ignore)] public string Name { get; set; } /// <summary> /// 水印图片相对输出视频的水平偏移量,默认值是0&lt;br/&gt; /// </summary> [JsonProperty("dx", NullValueHandling = NullValueHandling.Ignore)] public string Dx { get; set; } /// <summary> /// 水印图片相对输出视频的垂直偏移量,默认值是0&lt;br/&gt; /// </summary> [JsonProperty("dy", NullValueHandling = NullValueHandling.Ignore)] public string Dy { get; set; } /// <summary> /// 水印的位置&lt;br/&gt; /// </summary> [JsonProperty("position", NullValueHandling = NullValueHandling.Ignore)] public PositionEnum Position { get; set; } /// <summary> /// 水印图片宽&lt;br/&gt; /// </summary> [JsonProperty("width", NullValueHandling = NullValueHandling.Ignore)] public string Width { get; set; } /// <summary> /// 水印图片高&lt;br/&gt; /// </summary> [JsonProperty("height", NullValueHandling = NullValueHandling.Ignore)] public string Height { get; set; } /// <summary> /// 水印类型,当前只支持Image(图片水印)&lt;br/&gt; /// </summary> [JsonProperty("watermark_type", NullValueHandling = NullValueHandling.Ignore)] public WatermarkTypeEnum WatermarkType { get; set; } /// <summary> /// type设置为Image时有效。 目前包括: - Original:只做简单缩放,不做其他处理 - Transparent:图片底色透明 - Grayed:彩色图片变灰 /// </summary> [JsonProperty("image_process", NullValueHandling = NullValueHandling.Ignore)] public ImageProcessEnum ImageProcess { get; set; } /// <summary> /// 水印开始时间&lt;br/&gt; /// </summary> [JsonProperty("timeline_start", NullValueHandling = NullValueHandling.Ignore)] public string TimelineStart { get; set; } /// <summary> /// 水印持续时间&lt;br/&gt; /// </summary> [JsonProperty("timeline_duration", NullValueHandling = NullValueHandling.Ignore)] public string TimelineDuration { get; set; } /// <summary> /// Get the string /// </summary> public override string ToString() { var sb = new StringBuilder(); sb.Append("class UpdateWatermarkTemplateReq {\n"); sb.Append(" id: ").Append(Id).Append("\n"); sb.Append(" name: ").Append(Name).Append("\n"); sb.Append(" dx: ").Append(Dx).Append("\n"); sb.Append(" dy: ").Append(Dy).Append("\n"); sb.Append(" position: ").Append(Position).Append("\n"); sb.Append(" width: ").Append(Width).Append("\n"); sb.Append(" height: ").Append(Height).Append("\n"); sb.Append(" watermarkType: ").Append(WatermarkType).Append("\n"); sb.Append(" imageProcess: ").Append(ImageProcess).Append("\n"); sb.Append(" timelineStart: ").Append(TimelineStart).Append("\n"); sb.Append(" timelineDuration: ").Append(TimelineDuration).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns true if objects are equal /// </summary> public override bool Equals(object input) { return this.Equals(input as UpdateWatermarkTemplateReq); } /// <summary> /// Returns true if objects are equal /// </summary> public bool Equals(UpdateWatermarkTemplateReq input) { if (input == null) return false; return ( this.Id == input.Id || (this.Id != null && this.Id.Equals(input.Id)) ) && ( this.Name == input.Name || (this.Name != null && this.Name.Equals(input.Name)) ) && ( this.Dx == input.Dx || (this.Dx != null && this.Dx.Equals(input.Dx)) ) && ( this.Dy == input.Dy || (this.Dy != null && this.Dy.Equals(input.Dy)) ) && ( this.Position == input.Position || (this.Position != null && this.Position.Equals(input.Position)) ) && ( this.Width == input.Width || (this.Width != null && this.Width.Equals(input.Width)) ) && ( this.Height == input.Height || (this.Height != null && this.Height.Equals(input.Height)) ) && ( this.WatermarkType == input.WatermarkType || (this.WatermarkType != null && this.WatermarkType.Equals(input.WatermarkType)) ) && ( this.ImageProcess == input.ImageProcess || (this.ImageProcess != null && this.ImageProcess.Equals(input.ImageProcess)) ) && ( this.TimelineStart == input.TimelineStart || (this.TimelineStart != null && this.TimelineStart.Equals(input.TimelineStart)) ) && ( this.TimelineDuration == input.TimelineDuration || (this.TimelineDuration != null && this.TimelineDuration.Equals(input.TimelineDuration)) ); } /// <summary> /// Get hash code /// </summary> public override int GetHashCode() { unchecked // Overflow is fine, just wrap { int hashCode = 41; if (this.Id != null) hashCode = hashCode * 59 + this.Id.GetHashCode(); if (this.Name != null) hashCode = hashCode * 59 + this.Name.GetHashCode(); if (this.Dx != null) hashCode = hashCode * 59 + this.Dx.GetHashCode(); if (this.Dy != null) hashCode = hashCode * 59 + this.Dy.GetHashCode(); if (this.Position != null) hashCode = hashCode * 59 + this.Position.GetHashCode(); if (this.Width != null) hashCode = hashCode * 59 + this.Width.GetHashCode(); if (this.Height != null) hashCode = hashCode * 59 + this.Height.GetHashCode(); if (this.WatermarkType != null) hashCode = hashCode * 59 + this.WatermarkType.GetHashCode(); if (this.ImageProcess != null) hashCode = hashCode * 59 + this.ImageProcess.GetHashCode(); if (this.TimelineStart != null) hashCode = hashCode * 59 + this.TimelineStart.GetHashCode(); if (this.TimelineDuration != null) hashCode = hashCode * 59 + this.TimelineDuration.GetHashCode(); return hashCode; } } } }
31.764706
112
0.457464
[ "Apache-2.0" ]
cnblogs/huaweicloud-sdk-net-v3
Services/Vod/V1/Model/UpdateWatermarkTemplateReq.cs
18,338
C#
/* Copyright (c) 2006 Google 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 Google.GData.Extensions; namespace Google.GData.ContentForShopping.Elements { public class Color : SimpleElement { /// <summary> /// default constructor for scp:color /// </summary> public Color() : base(ContentForShoppingNameTable.Color, ContentForShoppingNameTable.scpDataPrefix, ContentForShoppingNameTable.ProductsNamespace) { } /// <summary> /// Constructs a new Color instance with the specified value. /// </summary> /// <param name="value">The color's value.</param> public Color(string value) : base(ContentForShoppingNameTable.Color, ContentForShoppingNameTable.scpDataPrefix, ContentForShoppingNameTable.ProductsNamespace) { this.Value = value; } } }
34.133333
76
0.635417
[ "Apache-2.0" ]
michael-jia-sage/libgoogle
src/contentforshopping/elements/color.cs
1,538
C#
using DAM2_DI_U5_EJ_Agenda.dto; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DAM2_DI_U5_EJ_Agenda.logica { public class Logica { // Colección que usaremos para carar TODAS las tareas public ObservableCollection<Tarea> listaTareas { get; set; } // Colección para las tareas de una determinada fecha public ObservableCollection<Tarea> tareasFecha { get; set; } // Constructor public Logica(){ listaTareas = new ObservableCollection<Tarea>(); tareasFecha = new ObservableCollection<Tarea>(); // Creamos unas entradas de pruebas listaTareas.Add(new Tarea("Examen PSP", new DateTime(2018, 02, 24), "Ejercicios pendientes de la asignatura PSP.", "Sotrondio")); listaTareas.Add(new Tarea("Examen SGE", new DateTime(2018, 02, 25), "Ejercicios pendientes de la asignatura SGE para el Martes.", "Sotrondio")); listaTareas.Add(new Tarea("Examen EIE", new DateTime(2018, 02, 26), "Hacer examen de la primera evaluación de PSP.", "Sotrondio")); } /** * Añadir una tarea nueva */ public void addTarea(Tarea tarea) { listaTareas.Add(tarea); } /** * Modificar una tarea */ public void modTarea(Tarea tarea, int posicion) { // Recuperamos la tarea que seleccionamos para editar mediante su posición Tarea tareaAEditar = tareasFecha[posicion]; // Buscamos y modificamos la tarea de la listaTareas for (int i = 0; i < listaTareas.Count; i++) { // Comparamos la tarea antes de ser modificada con la tarea de la ListaTareas if (listaTareas.ElementAt(i).Fecha.Equals(tareaAEditar.Fecha) && listaTareas.ElementAt(i).Nombre.Equals(tareaAEditar.Nombre)) { // Sobreescribimos la tarea de la listaTareas // con los datos actualizados mediante el formulario listaTareas[i] = tarea; Console.WriteLine("MOD. " + tarea.Nombre); } else { Console.WriteLine("NO COINCIDE"); } } // Ahora actualizamos las tareas de la lista tareasFecha cargarTareas(tarea.Fecha); } /** * Eliminar una tarea */ public void delTarea(Tarea tarea) { // Buscamos y eliminamos la tarea de la listaTareas for (int i = 0; i < listaTareas.Count; i++) { if (listaTareas.ElementAt(i).Fecha.Equals(tarea.Fecha) && listaTareas.ElementAt(i).Nombre.Equals(tarea.Nombre)) { listaTareas.RemoveAt(i); } } // Ahora actualizamos las tareas de la lista tareasFecha cargarTareas(tarea.Fecha); } /** * Cargar las tareas que hay para una fecha determinada */ public void cargarTareas(DateTime fecha) { // Reseteamos la lista tareasFecha.Clear(); // Recorremos TODAS las tareas foreach (Tarea tarea in listaTareas) { // Y añadimos las que coinciden con la fecha seleccionada // Gracias al binding del DataGrid, se cogeran automáticamente de la colección // Y así al cambiar una fecha en el calendario, se verán las tareas en el DataGrid if( tarea.Fecha.Equals(fecha) ){ tareasFecha.Add(tarea); //Console.WriteLine("cargarTareas --> " + tarea.Nombre); } } } } }
34.710526
156
0.556735
[ "MIT" ]
alexiscv/DAM2_DI
DAM2_DI_U5_EJ_Agenda/DAM2_DI_U5_EJ_Agenda/logica/Logica.cs
3,969
C#
//----------------------------------------------------------------------- // <copyright file="AssemblyInfo.cs" company="Akka.NET Project"> // Copyright (C) 2009-2018 Lightbend Inc. <http://www.lightbend.com> // Copyright (C) 2013-2018 .NET Foundation <https://github.com/akkadotnet/akka.net> // </copyright> //----------------------------------------------------------------------- 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. using Xunit; [assembly: CollectionBehavior(CollectionBehavior.CollectionPerAssembly, DisableTestParallelization = true)]
45.058824
107
0.624021
[ "Apache-2.0" ]
cuteant/akka.net
test/Akka.TestKit.Tests/Properties/AssemblyInfo.cs
768
C#
using LocalCinema.Data.Model; using System; using System.Collections.Generic; using System.Data; using System.Text; using System.Threading.Tasks; namespace LocalCinema.Data.Repository.Interfaces { public interface IDbConnectionContext : IDisposable { IDbConnection GetOpenConnection(string connectionString = null); } public interface IUnitOfWork : IDisposable { /// <summary> /// Executes a unit of work wrapped in a transaction. /// </summary> /// <param name="unitOfWork">Unit of work to execute</param> /// <param name="isolationLevel">Specify transaction isolation level</param> /// <returns></returns> Task<T> ExecuteWithTransactionAsync<T>(Func<IDbConnection, Action, Action, Task<T>> unitOfWork, IsolationLevel isolationLevel = IsolationLevel.ReadCommitted); /// <summary> /// Executes a unit of work wrapped in a transaction. /// </summary> /// <param name="unitOfWork"></param> /// <param name="isolationLevel"></param> /// <returns></returns> Task ExecuteWithTransactionAsync(Func<IDbConnection, Action, Action, Task> unitOfWork, IsolationLevel isolationLevel = IsolationLevel.ReadCommitted); } public interface ILocalCinemaRepo { Task UpdateMoviePriceAndTime(string id, UpdateMovieCatalog updateMovieCatalog); Task<OperationResult> GetMovieTimes(string movieName, string date); } }
36.634146
103
0.6751
[ "Apache-2.0" ]
vikashCoach/LocalCinema
LocalCinema.Data.Repository/Interfaces/IDbConnectionContext.cs
1,504
C#
using System; using System.Collections.Generic; using System.Drawing; using System.Text; namespace LedGameDisplayLibrary { public class Character { public string Name { get; set; } public char Char { get; set; } public string File { get; set; } public Color[,] Pixels { get; set; } public int Width { get; set; } public int Height { get; set; } public Character(int width, int height) { Width = width; Height = height; Pixels = new Color[width,height]; } } }
23.28
47
0.56701
[ "MIT" ]
Hunv/LedGameDisplay
LedGameDisplayLibrary/Character.cs
584
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Xml; using System.Diagnostics.CodeAnalysis; namespace System.ServiceModel.Syndication { // NOTE: This class implements Clone so if you add any members, please update the copy ctor public class SyndicationPerson : IExtensibleSyndicationObject { private ExtensibleSyndicationObject _extensions; public SyndicationPerson() : this((string)null) { } public SyndicationPerson(string email) : this(email, null, null) { } public SyndicationPerson(string email, string name, string uri) { Name = name; Email = email; Uri = uri; } protected SyndicationPerson(SyndicationPerson source) { if (source == null) { throw new ArgumentNullException(nameof(source)); } Email = source.Email; Name = source.Name; Uri = source.Uri; _extensions = source._extensions.Clone(); } public Dictionary<XmlQualifiedName, string> AttributeExtensions => _extensions.AttributeExtensions; public SyndicationElementExtensionCollection ElementExtensions => _extensions.ElementExtensions; public string Email { get; set; } public string Name { get; set; } public string Uri { get; set; } public virtual SyndicationPerson Clone() => new SyndicationPerson(this); protected internal virtual bool TryParseAttribute(string name, string ns, string value, string version) { return false; } protected internal virtual bool TryParseElement(XmlReader reader, string version) { return false; } protected internal virtual void WriteAttributeExtensions(XmlWriter writer, string version) { _extensions.WriteAttributeExtensions(writer); } protected internal virtual void WriteElementExtensions(XmlWriter writer, string version) { _extensions.WriteElementExtensions(writer); } internal void LoadElementExtensions(XmlReader readerOverUnparsedExtensions, int maxExtensionSize) { _extensions.LoadElementExtensions(readerOverUnparsedExtensions, maxExtensionSize); } internal void LoadElementExtensions(XmlBuffer buffer) { _extensions.LoadElementExtensions(buffer); } } }
31.057471
111
0.649149
[ "MIT" ]
06needhamt/runtime
src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/SyndicationPerson.cs
2,702
C#
using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; using System.Reflection; using System.Text; using System.Xml; using System.Xml.Linq; using System.Xml.XPath; using JetBrains.Annotations; namespace Rocks.Helpers { public static class XmlExtensions { /// <summary> /// Get the element with specified name. /// If element is not exist it will be created. /// </summary> /// <param name="e">Root element.</param> /// <param name="name">Element name.</param> [NotNull] public static XElement GetElement ([NotNull] this XElement e, [NotNull] string name) { if (e == null) throw new ArgumentNullException ("e"); if (string.IsNullOrEmpty (name)) throw new ArgumentNullException ("name"); var n = e.Element (name); if (n == null) { n = new XElement (name); e.Add (n); } return n; } /// <summary> /// Get the element with specified path (as list of <paramref name="names" />). /// If element is not exist it will be created. /// </summary> /// <param name="e">Root element.</param> /// <param name="names">A path of the required element as a list of element's names.</param> [NotNull] public static XElement GetElement ([NotNull] this XElement e, [NotNull] params string[] names) { if (e == null) throw new ArgumentNullException ("e"); if (names == null) throw new ArgumentNullException ("names"); return e.GetElement ((IEnumerable<string>) names); } /// <summary> /// Get the element with specified path (as list of <paramref name="elementNames" />). /// If element is not exist it will be created. /// </summary> /// <param name="e">Root element.</param> /// <param name="elementNames">A path of the required element as a list of element's names.</param> [NotNull] public static XElement GetElement ([NotNull] this XElement e, [NotNull] IEnumerable<string> elementNames) { if (e == null) throw new ArgumentNullException ("e"); if (elementNames == null) throw new ArgumentNullException ("elementNames"); foreach (var name in elementNames) { var n = e.Element (name); if (n == null) { n = new XElement (name); e.Add (n); } e = n; } return e; } /// <summary> /// Removes XML elements node by specified path (if it exists). /// </summary> /// <param name="e">Root element.</param> /// <param name="xpath">XPath to element.</param> public static void RemoveElement ([NotNull] this XNode e, [NotNull] string xpath) { if (e == null) throw new ArgumentNullException ("e"); if (string.IsNullOrEmpty (xpath)) throw new ArgumentNullException ("xpath"); var node = e.XPathSelectElement (xpath); if (node != null) node.Remove (); } /// <summary> /// Adds specified <paramref name="xml" /> to the source element if <paramref name="xml" /> is not null or empty. /// Returns source element. /// </summary> /// <param name="e">Source element.</param> /// <param name="xml">XML (can be null).</param> [NotNull] public static XElement AddXml ([NotNull] this XElement e, [CanBeNull] string xml) { if (e == null) throw new ArgumentNullException ("e"); if (!string.IsNullOrEmpty (xml)) e.Add (XElement.Parse (xml)); return e; } /// <summary> /// Removes all elements that matched specified <paramref name="xpath" />. /// </summary> /// <param name="e">Source element.</param> /// <param name="xpath">XPath of the element(s) to be removed.</param> [NotNull] public static XElement Remove ([NotNull] this XElement e, [NotNull] string xpath) { if (e == null) throw new ArgumentNullException ("e"); if (string.IsNullOrEmpty (xpath)) throw new ArgumentNullException ("xpath"); foreach (var node in e.XPathSelectElements (xpath).ToArray ()) node.Remove (); return e; } /// <summary> /// Creates a copy of XML element with new name. /// </summary> /// <param name="e">Source element.</param> /// <param name="newName">New name.</param> [NotNull] public static XElement Rename ([NotNull] this XElement e, [NotNull] string newName) { if (e == null) throw new ArgumentNullException ("e"); if (string.IsNullOrEmpty (newName)) throw new ArgumentNullException ("newName"); return new XElement (newName, e.Attributes (), e.Elements ()); } /// <summary> /// Returns XML elements's text by specified path or null if no such element present. /// </summary> /// <param name="e">Root element.</param> /// <param name="xpath">XPath to element (can be null).</param> [CanBeNull] public static string GetValue ([CanBeNull] this XElement e, [CanBeNull] string xpath = null) { if (e == null) return null; if (xpath == null) return e.Value; var node = e.XPathSelectElement (xpath); if (node != null) return node.Value; return null; } /// <summary> /// Gets XML element attribute text. Returns null if no such attribute present. /// </summary> /// <param name="e">Source xml element.</param> /// <param name="attributeName">Name of the attribute.</param> [CanBeNull] public static string GetAttributeValue ([NotNull] this XElement e, [NotNull] string attributeName) { if (e == null) throw new ArgumentNullException ("e"); if (string.IsNullOrEmpty (attributeName)) throw new ArgumentNullException ("attributeName"); var a = e.Attribute (attributeName); if (a != null) return a.Value; return null; } /// <summary> /// Gets XML element attribute text. Returns null if no such attribute present. /// </summary> /// <param name="e">Source xml element.</param> /// <param name="xpath">XPath to element with attribute.</param> /// <param name="attributeName">Name of the attribute.</param> [CanBeNull] public static string GetAttributeValue ([NotNull] this XElement e, [NotNull] string xpath, [NotNull] string attributeName) { if (e == null) throw new ArgumentNullException ("e"); if (xpath == null) throw new ArgumentNullException ("xpath"); if (string.IsNullOrEmpty (attributeName)) throw new ArgumentNullException ("attributeName"); e = e.XPathSelectElement (xpath); if (e == null) return null; var a = e.Attribute (attributeName); if (a != null) return a.Value; return null; } /// <summary> /// Gets XML element attribute text. Returns null if no such attribute present. /// </summary> /// <param name="e">Source xml element.</param> /// <param name="elementNames">A path of the required element as a list of element's names.</param> /// <param name="attributeName">Name of the attribute.</param> [CanBeNull] public static string GetAttributeValue ([NotNull] this XElement e, [NotNull] IEnumerable<string> elementNames, [NotNull] string attributeName) { if (e == null) throw new ArgumentNullException ("e"); if (string.IsNullOrEmpty (attributeName)) throw new ArgumentNullException ("attributeName"); if (elementNames == null) throw new ArgumentNullException ("elementNames"); foreach (var name in elementNames) { var n = e.Element (name); if (n == null) return null; e = n; } var a = e.Attribute (attributeName); if (a != null) return a.Value; return null; } /// <summary> /// Sets the value of the element with name <paramref name="name" /> to <paramref name="value" />. /// If element is not present it will be created. /// If <paramref name="value" /> is null the element will be removed (if it exist). /// </summary> /// <param name="e">Root element.</param> /// <param name="name">Element name.</param> /// <param name="value">Element value.</param> /// <param name="culture"> /// Culture to be used when converting <paramref name="value" /> to string. If null the /// <see cref="CultureInfo.InvariantCulture" /> will be used. /// </param> [NotNull] public static XElement SetValue ([NotNull] this XElement e, [NotNull] string name, [CanBeNull] object value, CultureInfo culture = null) { if (e == null) throw new ArgumentNullException ("e"); if (string.IsNullOrEmpty (name)) throw new ArgumentNullException ("name"); var n = e.Element (name); if (n == null) { if (value != null) e.Add (new XElement (name, Convert.ToString (value, culture ?? CultureInfo.InvariantCulture))); } else { var str = value != null ? Convert.ToString (value, culture ?? CultureInfo.InvariantCulture) : null; if (!string.IsNullOrEmpty (str)) n.Value = str; else n.Remove (); } return e; } /// <summary> /// Sets XML element attribute text. /// If attribute is not present it will be created. /// If <paramref name="value" /> is null or empty the attribute will be removed (if it exist). /// </summary> /// <param name="e">Source xml element.</param> /// <param name="attributeName">Name of the attribute.</param> /// <param name="value">New value.</param> /// <param name="culture"> /// Culture to be used when converting <paramref name="value" /> to string. If null the /// <see cref="CultureInfo.InvariantCulture" /> will be used. /// </param> [NotNull] public static XElement SetAttribute ([NotNull] this XElement e, [NotNull] string attributeName, [CanBeNull] object value, CultureInfo culture = null) { if (e == null) throw new ArgumentNullException ("e"); if (string.IsNullOrEmpty (attributeName)) throw new ArgumentNullException ("attributeName"); var a = e.Attribute (attributeName); if (a == null) { if (value != null) e.Add (new XAttribute (attributeName, value)); } else { var str = value != null ? Convert.ToString (value, culture ?? CultureInfo.InvariantCulture) : null; if (!string.IsNullOrEmpty (str)) a.Value = str; else a.Remove (); } return e; } #region ToXElement /// <summary> /// Generates new <see cref="XElement" /> with specified <paramref name="name" /> if <paramref name="value" /> is not /// null. /// </summary> /// <param name="value">Value.</param> /// <param name="name">Name of the <see cref="XElement" />.</param> /// <param name="format">Format that will be used when converting <paramref name="value" /> to string.</param> /// <param name="culture"> /// Culture that will be used when converting <paramref name="value" /> to string. If null the /// <see cref="CultureInfo.InvariantCulture" /> will be used. /// </param> [CanBeNull, ContractAnnotation ("value:null => null")] public static XElement ToXElement (this byte? value, string name, string format = null, CultureInfo culture = null) { return value != null ? value.Value.ToXElement (name, format, culture) : null; } /// <summary> /// Generates new <see cref="XElement" /> with specified <paramref name="name" />. /// </summary> /// <param name="value">Value.</param> /// <param name="name">Name of the <see cref="XElement" />.</param> /// <param name="format">Format that will be used when converting <paramref name="value" /> to string.</param> /// <param name="culture"> /// Culture that will be used when converting <paramref name="value" /> to string. If null the /// <see cref="CultureInfo.InvariantCulture" /> will be used. /// </param> [NotNull] public static XElement ToXElement (this byte value, string name, string format = null, CultureInfo culture = null) { return new XElement (name, value.ToString (format, culture ?? CultureInfo.InvariantCulture)); } /// <summary> /// Generates new <see cref="XElement" /> with specified <paramref name="name" /> if <paramref name="value" /> is not /// null. /// </summary> /// <param name="value">Value.</param> /// <param name="name">Name of the <see cref="XElement" />.</param> /// <param name="format">Format that will be used when converting <paramref name="value" /> to string.</param> /// <param name="culture"> /// Culture that will be used when converting <paramref name="value" /> to string. If null the /// <see cref="CultureInfo.InvariantCulture" /> will be used. /// </param> [CanBeNull, ContractAnnotation ("value:null => null")] public static XElement ToXElement (this short? value, string name, string format = null, CultureInfo culture = null) { return value != null ? value.Value.ToXElement (name, format, culture) : null; } /// <summary> /// Generates new <see cref="XElement" /> with specified <paramref name="name" />. /// </summary> /// <param name="value">Value.</param> /// <param name="name">Name of the <see cref="XElement" />.</param> /// <param name="format">Format that will be used when converting <paramref name="value" /> to string.</param> /// <param name="culture"> /// Culture that will be used when converting <paramref name="value" /> to string. If null the /// <see cref="CultureInfo.InvariantCulture" /> will be used. /// </param> [NotNull] public static XElement ToXElement (this short value, string name, string format = null, CultureInfo culture = null) { return new XElement (name, value.ToString (format, culture ?? CultureInfo.InvariantCulture)); } /// <summary> /// Generates new <see cref="XElement" /> with specified <paramref name="name" /> if <paramref name="value" /> is not /// null. /// </summary> /// <param name="value">Value.</param> /// <param name="name">Name of the <see cref="XElement" />.</param> /// <param name="format">Format that will be used when converting <paramref name="value" /> to string.</param> /// <param name="culture"> /// Culture that will be used when converting <paramref name="value" /> to string. If null the /// <see cref="CultureInfo.InvariantCulture" /> will be used. /// </param> [CanBeNull, ContractAnnotation ("value:null => null")] public static XElement ToXElement (this int? value, string name, string format = null, CultureInfo culture = null) { return value != null ? value.Value.ToXElement (name, format, culture) : null; } /// <summary> /// Generates new <see cref="XElement" /> with specified <paramref name="name" />. /// </summary> /// <param name="value">Value.</param> /// <param name="name">Name of the <see cref="XElement" />.</param> /// <param name="format">Format that will be used when converting <paramref name="value" /> to string.</param> /// <param name="culture"> /// Culture that will be used when converting <paramref name="value" /> to string. If null the /// <see cref="CultureInfo.InvariantCulture" /> will be used. /// </param> [NotNull] public static XElement ToXElement (this int value, string name, string format = null, CultureInfo culture = null) { return new XElement (name, value.ToString (format, culture ?? CultureInfo.InvariantCulture)); } /// <summary> /// Generates new <see cref="XElement" /> with specified <paramref name="name" /> if <paramref name="value" /> is not /// null. /// </summary> /// <param name="value">Value.</param> /// <param name="name">Name of the <see cref="XElement" />.</param> /// <param name="format">Format that will be used when converting <paramref name="value" /> to string.</param> /// <param name="culture"> /// Culture that will be used when converting <paramref name="value" /> to string. If null the /// <see cref="CultureInfo.InvariantCulture" /> will be used. /// </param> [CanBeNull, ContractAnnotation ("value:null => null")] public static XElement ToXElement (this long? value, string name, string format = null, CultureInfo culture = null) { return value != null ? value.Value.ToXElement (name, format, culture) : null; } /// <summary> /// Generates new <see cref="XElement" /> with specified <paramref name="name" />. /// </summary> /// <param name="value">Value.</param> /// <param name="name">Name of the <see cref="XElement" />.</param> /// <param name="format">Format that will be used when converting <paramref name="value" /> to string.</param> /// <param name="culture"> /// Culture that will be used when converting <paramref name="value" /> to string. If null the /// <see cref="CultureInfo.InvariantCulture" /> will be used. /// </param> [NotNull] public static XElement ToXElement (this long value, string name, string format = null, CultureInfo culture = null) { return new XElement (name, value.ToString (format, culture ?? CultureInfo.InvariantCulture)); } /// <summary> /// Generates new <see cref="XElement" /> with specified <paramref name="name" /> if <paramref name="value" /> is not /// null. /// </summary> /// <param name="value">Value.</param> /// <param name="name">Name of the <see cref="XElement" />.</param> /// <param name="format">Format that will be used when converting <paramref name="value" /> to string.</param> /// <param name="culture"> /// Culture that will be used when converting <paramref name="value" /> to string. If null the /// <see cref="CultureInfo.InvariantCulture" /> will be used. /// </param> [CanBeNull, ContractAnnotation ("value:null => null")] public static XElement ToXElement (this float? value, string name, string format = null, CultureInfo culture = null) { return value != null ? value.Value.ToXElement (name, format, culture) : null; } /// <summary> /// Generates new <see cref="XElement" /> with specified <paramref name="name" />. /// </summary> /// <param name="value">Value.</param> /// <param name="name">Name of the <see cref="XElement" />.</param> /// <param name="format">Format that will be used when converting <paramref name="value" /> to string.</param> /// <param name="culture"> /// Culture that will be used when converting <paramref name="value" /> to string. If null the /// <see cref="CultureInfo.InvariantCulture" /> will be used. /// </param> [NotNull] public static XElement ToXElement (this float value, string name, string format = null, CultureInfo culture = null) { return new XElement (name, value.ToString (format, culture ?? CultureInfo.InvariantCulture)); } /// <summary> /// Generates new <see cref="XElement" /> with specified <paramref name="name" /> if <paramref name="value" /> is not /// null. /// </summary> /// <param name="value">Value.</param> /// <param name="name">Name of the <see cref="XElement" />.</param> /// <param name="format">Format that will be used when converting <paramref name="value" /> to string.</param> /// <param name="culture"> /// Culture that will be used when converting <paramref name="value" /> to string. If null the /// <see cref="CultureInfo.InvariantCulture" /> will be used. /// </param> [CanBeNull, ContractAnnotation ("value:null => null")] public static XElement ToXElement (this double? value, string name, string format = null, CultureInfo culture = null) { return value != null ? value.Value.ToXElement (name, format, culture) : null; } /// <summary> /// Generates new <see cref="XElement" /> with specified <paramref name="name" />. /// </summary> /// <param name="value">Value.</param> /// <param name="name">Name of the <see cref="XElement" />.</param> /// <param name="format">Format that will be used when converting <paramref name="value" /> to string.</param> /// <param name="culture"> /// Culture that will be used when converting <paramref name="value" /> to string. If null the /// <see cref="CultureInfo.InvariantCulture" /> will be used. /// </param> [NotNull] public static XElement ToXElement (this double value, string name, string format = null, CultureInfo culture = null) { return new XElement (name, value.ToString (format, culture ?? CultureInfo.InvariantCulture)); } /// <summary> /// Generates new <see cref="XElement" /> with specified <paramref name="name" /> if <paramref name="value" /> is not /// null. /// </summary> /// <param name="value">Value.</param> /// <param name="name">Name of the <see cref="XElement" />.</param> /// <param name="format">Format that will be used when converting <paramref name="value" /> to string.</param> /// <param name="culture"> /// Culture that will be used when converting <paramref name="value" /> to string. If null the /// <see cref="CultureInfo.InvariantCulture" /> will be used. /// </param> [CanBeNull, ContractAnnotation ("value:null => null")] public static XElement ToXElement (this decimal? value, string name, string format = "G29", CultureInfo culture = null) { return value != null ? value.Value.ToXElement (name, format, culture) : null; } /// <summary> /// Generates new <see cref="XElement" /> with specified <paramref name="name" />. /// </summary> /// <param name="value">Value.</param> /// <param name="name">Name of the <see cref="XElement" />.</param> /// <param name="format">Format that will be used when converting <paramref name="value" /> to string.</param> /// <param name="culture"> /// Culture that will be used when converting <paramref name="value" /> to string. If null the /// <see cref="CultureInfo.InvariantCulture" /> will be used. /// </param> [NotNull] public static XElement ToXElement (this decimal value, string name, string format = "G29", CultureInfo culture = null) { return new XElement (name, value.ToString (format, culture ?? CultureInfo.InvariantCulture)); } /// <summary> /// Generates new <see cref="XElement" /> with specified <paramref name="name" /> if <paramref name="value" /> is not /// null. /// </summary> /// <param name="value">Value.</param> /// <param name="name">Name of the <see cref="XElement" />.</param> /// <param name="format">Format that will be used when converting <paramref name="value" /> to string.</param> /// <param name="culture"> /// Culture that will be used when converting <paramref name="value" /> to string. If null the /// <see cref="CultureInfo.InvariantCulture" /> will be used. /// </param> [CanBeNull, ContractAnnotation ("value:null => null")] public static XElement ToXElement (this TimeSpan? value, string name, string format = null, CultureInfo culture = null) { return value != null ? value.Value.ToXElement (name, format, culture) : null; } /// <summary> /// Generates new <see cref="XElement" /> with specified <paramref name="name" />. /// </summary> /// <param name="value">Value.</param> /// <param name="name">Name of the <see cref="XElement" />.</param> /// <param name="format">Format that will be used when converting <paramref name="value" /> to string.</param> /// <param name="culture"> /// Culture that will be used when converting <paramref name="value" /> to string. If null the /// <see cref="CultureInfo.InvariantCulture" /> will be used. /// </param> [NotNull] public static XElement ToXElement (this TimeSpan value, string name, string format = null, CultureInfo culture = null) { return new XElement (name, value.ToString (format, culture ?? CultureInfo.InvariantCulture)); } /// <summary> /// Generates new <see cref="XElement" /> with specified <paramref name="name" /> if <paramref name="value" /> is not /// null. /// </summary> /// <param name="value">Value.</param> /// <param name="name">Name of the <see cref="XElement" />.</param> /// <param name="format">Format that will be used when converting <paramref name="value" /> to string.</param> /// <param name="culture"> /// Culture that will be used when converting <paramref name="value" /> to string. If null the /// <see cref="CultureInfo.InvariantCulture" /> will be used. /// </param> [CanBeNull, ContractAnnotation ("value:null => null")] public static XElement ToXElement (this DateTime? value, string name, string format = null, CultureInfo culture = null) { return value != null ? value.Value.ToXElement (name, format, culture) : null; } /// <summary> /// Generates new <see cref="XElement" /> with specified <paramref name="name" />. /// </summary> /// <param name="value">Value.</param> /// <param name="name">Name of the <see cref="XElement" />.</param> /// <param name="format">Format that will be used when converting <paramref name="value" /> to string.</param> /// <param name="culture"> /// Culture that will be used when converting <paramref name="value" /> to string. If null the /// <see cref="CultureInfo.InvariantCulture" /> will be used. /// </param> [NotNull] public static XElement ToXElement (this DateTime value, string name, string format = null, CultureInfo culture = null) { return new XElement (name, value.ToString (format, culture ?? CultureInfo.InvariantCulture)); } /// <summary> /// Generates new <see cref="XElement" /> with specified <paramref name="name" /> if <paramref name="value" /> is not /// null or empty. /// </summary> /// <param name="value">Value.</param> /// <param name="name">Name of the <see cref="XElement" />.</param> [CanBeNull, ContractAnnotation ("value:null => null")] public static XElement ToXElement (this string value, string name) { return !string.IsNullOrEmpty (value) ? new XElement (name, value) : null; } /// <summary> /// Generates new <see cref="XElement" /> with specified <paramref name="name" /> if <paramref name="value" /> is not /// null. /// </summary> /// <param name="value">Value.</param> /// <param name="name">Name of the <see cref="XElement" />.</param> /// <param name="culture"> /// Culture that will be used when converting <paramref name="value" /> to string. If null the /// <see cref="CultureInfo.InvariantCulture" /> will be used. /// </param> [CanBeNull, ContractAnnotation ("value:null => null")] public static XElement ToXElement (this object value, string name, CultureInfo culture = null) { return value != null ? new XElement (name, Convert.ToString (value, culture ?? CultureInfo.InvariantCulture)) : null; } #endregion /// <summary> /// Loads new <see cref="XElement" /> object instance from <paramref name="assembly" /> resource (should be XML file). /// </summary> /// <param name="assembly">Assembly with the resource.</param> /// <param name="resourceName">Resource name.</param> [NotNull] public static XElement LoadFromResource ([NotNull] Assembly assembly, [NotNull] string resourceName) { if (assembly == null) throw new ArgumentNullException ("assembly"); if (string.IsNullOrEmpty (resourceName)) throw new ArgumentNullException ("resourceName"); var stream = assembly.GetManifestResourceStream (resourceName); if (stream == null) throw new InvalidOperationException ("Resource '" + resourceName + "' not found in assmebly " + assembly.FullName); using (var xml_stream = new StreamReader (stream)) return XElement.Load (xml_stream); } /// <summary> /// Converts XML to string with formatted output. /// </summary> /// <param name="xml">Source xml.</param> /// <param name="format">True if result needs to be formatted.</param> [NotNull] public static string ToString ([NotNull] this XNode xml, bool format) { if (xml == null) throw new ArgumentNullException ("xml"); return xml.ToString (format, null); } /// <summary> /// Converts XML to string with formatted output. /// </summary> /// <param name="xml">Source xml.</param> /// <param name="format">True if result needs to be formatted.</param> /// <param name="encoding">Result string encoding. If null UTF-16 will be used.</param> [NotNull] public static string ToString ([NotNull] this XNode xml, bool format, Encoding encoding) { if (xml == null) throw new ArgumentNullException ("xml"); encoding = encoding ?? Encoding.Unicode; var settings = new XmlWriterSettings { Encoding = encoding }; if (format) { settings.Indent = true; settings.IndentChars = "\t"; } var stream = new EncodeSpecifiedStringWriter (encoding); using (var xw = XmlWriter.Create (stream, settings)) { xml.WriteTo (xw); xw.Flush (); return stream.ToString (); } } /// <summary> /// Converts XML to string. /// </summary> /// <param name="xml">Source xml.</param> /// <param name="format">True if result needs to be formatted.</param> [NotNull] public static string ToString ([NotNull] this XDocument xml, bool format) { if (xml == null) throw new ArgumentNullException ("xml"); return xml.ToString (format, null); } /// <summary> /// Converts XML to string. /// </summary> /// <param name="xml">Source xml.</param> /// <param name="format">True if result needs to be formatted.</param> /// <param name="encoding">Result string encoding. If null UTF-16 will be used.</param> [NotNull] public static string ToString ([NotNull] this XDocument xml, bool format, Encoding encoding) { if (xml == null) throw new ArgumentNullException ("xml"); using (var stream = new EncodeSpecifiedStringWriter (encoding ?? Encoding.Unicode)) { xml.Save (stream, format ? SaveOptions.None : SaveOptions.DisableFormatting); return stream.ToString (); } } /// <summary> /// Returns new dettached element if source element is null. /// </summary> /// <param name="e">Source element.</param> /// <param name="name">Newly created element name.</param> [NotNull] public static XElement NewIfNull (this XElement e, [NotNull] string name = "element") { if (e != null) return e; if (string.IsNullOrEmpty (name)) throw new ArgumentNullException ("name"); return new XElement (name); } /// <summary> /// Returns new dettached attribute if source attribute is null. /// </summary> /// <param name="attribute">Source attribute.</param> /// <param name="name">Newly created attribute name.</param> /// <param name="value">Newly created attribute value.</param> [NotNull] public static XAttribute NewIfNull (this XAttribute attribute, [NotNull] string name = "attr", object value = null) { if (attribute != null) return attribute; if (string.IsNullOrEmpty (name)) throw new ArgumentNullException ("name"); return new XAttribute (name, value ?? true); } } }
36.105634
151
0.647422
[ "MIT" ]
MichaelLogutov/Rocks.Helpers
src/Rocks.Helpers/XmlExtensions.cs
30,764
C#
namespace Foxkit { public interface IProductHeaderValue { /// <summary> /// The name of the product, the GitHub Organization, or the GitHub Username that's using Octokit (in that order of preference) /// </summary> string Name { get; } /// <summary> /// The version of the product. /// </summary> string Version { get; } } }
25.1875
135
0.563275
[ "MIT" ]
ThymonA/Foxkit.net
Foxkit/Interfaces/Http/Headers/IProductHeaderValue.cs
405
C#
using System; using System.Net.Mail; namespace Postal { /// <summary> /// Parses raw string output of email views into <see cref="MailMessage"/>. /// </summary> public interface IEmailParser { /// <summary> /// Creates a <see cref="MailMessage"/> from the string output of an email view. /// </summary> /// <param name="emailViewOutput">The string output of the email view.</param> /// <param name="email">The email data used to render the view.</param> /// <returns>The created <see cref="MailMessage"/></returns> MailMessage Parse(string emailViewOutput, Email email); } }
33.8
89
0.60503
[ "MIT" ]
Ravinia/postal
src/Postal/IEmailParser.cs
678
C#
// *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AzureNative.Synapse.V20201201.Outputs { /// <summary> /// Details of the customer managed key associated with the workspace /// </summary> [OutputType] public sealed class WorkspaceKeyDetailsResponse { /// <summary> /// Workspace Key sub-resource key vault url /// </summary> public readonly string? KeyVaultUrl; /// <summary> /// Workspace Key sub-resource name /// </summary> public readonly string? Name; [OutputConstructor] private WorkspaceKeyDetailsResponse( string? keyVaultUrl, string? name) { KeyVaultUrl = keyVaultUrl; Name = name; } } }
26.641026
81
0.625602
[ "Apache-2.0" ]
polivbr/pulumi-azure-native
sdk/dotnet/Synapse/V20201201/Outputs/WorkspaceKeyDetailsResponse.cs
1,039
C#
using UnityEngine; using System; using System.Collections; using System.Collections.Generic; using EasyMobile.Internal; namespace EasyMobile { [AddComponentMenu("")] public class Advertising : MonoBehaviour { public static Advertising Instance { get; private set; } // Supported ad clients. private static AdColonyClientImpl sAdColonyClient; private static AdMobClientImpl sAdMobClient; private static AppLovinClientImpl sAppLovinClient; private static ChartboostClientImpl sChartboostClient; private static AudienceNetworkClientImpl sAudienceNetworkClient; private static FairBidClientImpl sFairBidClient; private static MoPubClientImpl sMoPubClient; private static IronSourceClientImpl sIronSourceClient; private static TapjoyClientImpl sTapjoyClient; private static UnityAdsClientImpl sUnityAdsClient; private static VungleClientImpl sVungleClient; // Default ad clients for each ad types. // private static AdClientImpl sDefaultBannerAdClient; // private static AdClientImpl sDefaultInterstitialAdClient; // private static AdClientImpl sDefaultRewardedAdClient; // For storing removeAds status. private const string AD_REMOVE_STATUS_PPKEY = "EM_REMOVE_ADS"; private const int AD_ENABLED = 1; private const int AD_DISABLED = -1; // Initialization warning private const string INITIALIZATION_WARNING = "You need to initialize the Advertising module first"; // Auto load ads. private static readonly float DEFAULT_TIMESTAMP = -1000; private static IEnumerator autoLoadAdsCoroutine; private static AutoAdLoadingMode currentAutoLoadAdsMode = AutoAdLoadingMode.None; private static float lastDefaultInterstitialAdLoadTimestamp = DEFAULT_TIMESTAMP; private static float lastDefaultRewardedAdLoadTimestamp = DEFAULT_TIMESTAMP; private static Dictionary<string, float> lastCustomInterstitialAdsLoadTimestamp = new Dictionary<string, float>(); private static Dictionary<string, float> lastCustomRewardedAdsLoadTimestamp = new Dictionary<string, float>(); /// <summary> /// Since <see cref="AutoLoadAdsMode"/> can be changed in both <see cref="Update"/> method and from outside script, /// there are chances that its value will be updated twice. We use this flag to prevent that. /// </summary> private static bool isUpdatingAutoLoadMode = false; // Currently shown banner ads. private static Dictionary<AdNetwork, List<AdPlacement>> activeBannerAds = new Dictionary<AdNetwork, List<AdPlacement>>(); // a flag to check if Init() has been called private static bool initialized = false; #region Ad Events /// <summary> /// Occurs when an interstitial ad is closed. /// </summary> public static event Action<InterstitialAdNetwork, AdPlacement> InterstitialAdCompleted; /// <summary> /// Occurs when a rewarded ad is skipped (the user didn't complete watching /// the ad and therefore is not entitled to the reward). /// </summary> public static event Action<RewardedAdNetwork, AdPlacement> RewardedAdSkipped; /// <summary> /// Occurs when a rewarded ad completed and the user should be rewarded. /// </summary> public static event Action<RewardedAdNetwork, AdPlacement> RewardedAdCompleted; /// <summary> /// Occurs when ads have been removed. /// </summary> public static event Action AdsRemoved; #endregion #region Ad Clients /// <summary> /// Gets the AdColony client. /// </summary> /// <value>The ad colony client.</value> public static AdColonyClientImpl AdColonyClient { get { if (!InitializationClientCheck()) return null; if (sAdColonyClient == null) sAdColonyClient = SetupAdClient(AdNetwork.AdColony) as AdColonyClientImpl; return sAdColonyClient; } } /// <summary> /// Gets the AdMob client. /// </summary> /// <value>The ad mob client.</value> public static AdMobClientImpl AdMobClient { get { if (!InitializationClientCheck()) return null; if (sAdMobClient == null) sAdMobClient = SetupAdClient(AdNetwork.AdMob) as AdMobClientImpl; return sAdMobClient; } } /// <summary> /// Gets the AppLovin client. /// </summary> /// <value>The AppLovin client.</value> public static AppLovinClientImpl AppLovinClient { get { if (!InitializationClientCheck()) return null; if (sAppLovinClient == null) sAppLovinClient = SetupAdClient(AdNetwork.AppLovin) as AppLovinClientImpl; return sAppLovinClient; } } /// <summary> /// Gets the Chartboost client. /// </summary> /// <value>The chartboost client.</value> public static ChartboostClientImpl ChartboostClient { get { if (!InitializationClientCheck()) return null; if (sChartboostClient == null) sChartboostClient = SetupAdClient(AdNetwork.Chartboost) as ChartboostClientImpl; return sChartboostClient; } } /// <summary> /// Gets the Facebook Audience Network client. /// </summary> /// <value>The audience network client.</value> public static AudienceNetworkClientImpl AudienceNetworkClient { get { if (!InitializationClientCheck()) return null; if (sAudienceNetworkClient == null) sAudienceNetworkClient = SetupAdClient(AdNetwork.AudienceNetwork) as AudienceNetworkClientImpl; return sAudienceNetworkClient; } } /// <summary> /// Gets the FairBid client. /// </summary> /// <value>The FairBid client.</value> public static FairBidClientImpl FairBidClient { get { if (!InitializationClientCheck()) return null; if (sFairBidClient == null) sFairBidClient = SetupAdClient(AdNetwork.FairBid) as FairBidClientImpl; return sFairBidClient; } } /// <summary> /// Gets the MoPub client. /// </summary> /// <value>The mo pub client.</value> public static MoPubClientImpl MoPubClient { get { if (!InitializationClientCheck()) return null; if (sMoPubClient == null) sMoPubClient = SetupAdClient(AdNetwork.MoPub) as MoPubClientImpl; return sMoPubClient; } } /// <summary> /// Gets the ironSource client. /// </summary> /// <value>The iron source client.</value> public static IronSourceClientImpl IronSourceClient { get { if (!InitializationClientCheck()) return null; if (sIronSourceClient == null) sIronSourceClient = SetupAdClient(AdNetwork.IronSource) as IronSourceClientImpl; return sIronSourceClient; } } /// <summary> /// Gets the Tapjoy client. /// </summary> /// <value>The tap joy client.</value> public static TapjoyClientImpl TapjoyClient { get { if (!InitializationClientCheck()) return null; if (sTapjoyClient == null) sTapjoyClient = SetupAdClient(AdNetwork.TapJoy) as TapjoyClientImpl; return sTapjoyClient; } } /// <summary> /// Gets the Unity Ads client. /// </summary> /// <value>The unity ads client.</value> public static UnityAdsClientImpl UnityAdsClient { get { if (!InitializationClientCheck()) return null; if (sUnityAdsClient == null) sUnityAdsClient = SetupAdClient(AdNetwork.UnityAds) as UnityAdsClientImpl; return sUnityAdsClient; } } public static VungleClientImpl VungleClient { get { if (!InitializationClientCheck()) return null; if (sVungleClient == null) sVungleClient = SetupAdClient(AdNetwork.Vungle) as VungleClientImpl; return sVungleClient; } } private static AdClientImpl DefaultBannerAdClient { get { #if UNITY_IOS return GetWorkableAdClient((AdNetwork)EM_Settings.Advertising.IosDefaultAdNetworks.bannerAdNetwork); #elif UNITY_ANDROID return GetWorkableAdClient((AdNetwork)EM_Settings.Advertising.AndroidDefaultAdNetworks.bannerAdNetwork); #else return GetWorkableAdClient(AdNetwork.None); #endif } } private static AdClientImpl DefaultInterstitialAdClient { get { #if UNITY_IOS return GetWorkableAdClient((AdNetwork)EM_Settings.Advertising.IosDefaultAdNetworks.interstitialAdNetwork); #elif UNITY_ANDROID return GetWorkableAdClient((AdNetwork)EM_Settings.Advertising.AndroidDefaultAdNetworks.interstitialAdNetwork); #else return GetWorkableAdClient(AdNetwork.None); #endif } } private static AdClientImpl DefaultRewardedAdClient { get { #if UNITY_IOS return GetWorkableAdClient((AdNetwork)EM_Settings.Advertising.IosDefaultAdNetworks.rewardedAdNetwork); #elif UNITY_ANDROID return GetWorkableAdClient((AdNetwork)EM_Settings.Advertising.AndroidDefaultAdNetworks.rewardedAdNetwork); #else return GetWorkableAdClient(AdNetwork.None); #endif } } private static bool InitializationClientCheck() { if (!IsInitialized()) { Debug.LogError(INITIALIZATION_WARNING); return false; } return true; } #endregion #region MonoBehaviour Events void Awake() { if (Instance != null) Destroy(this); else Instance = this; } void Start() { if (EM_Settings.Advertising.AutoInit) Initialize(); } void Update() { if(!IsInitialized()) return; // Always track EM_Settings.Advertising.AutoLoadAdsMode so that we can adjust // accordingly if it was changed elsewhere. if (!isUpdatingAutoLoadMode && currentAutoLoadAdsMode != EM_Settings.Advertising.AutoAdLoadingMode) { AutoAdLoadingMode = EM_Settings.Advertising.AutoAdLoadingMode; } } #endregion #region Consent Management API /// <summary> /// Raised when the module-level data privacy consent is changed. /// </summary> public static event Action<ConsentStatus> DataPrivacyConsentUpdated { add { AdvertisingConsentManager.Instance.DataPrivacyConsentUpdated += value; } remove { AdvertisingConsentManager.Instance.DataPrivacyConsentUpdated -= value; } } /// <summary> /// The module-level data privacy consent status, /// default to ConsentStatus.Unknown. /// </summary> public static ConsentStatus DataPrivacyConsent { get { return AdvertisingConsentManager.Instance.DataPrivacyConsent; } } /// <summary> /// Grants module-level data privacy consent. /// This consent persists across app launches. /// </summary> /// <remarks> /// This method is a wrapper of <c>AdvertisingConsentManager.Instance.GrantDataPrivacyConsent</c>. /// </remarks> public static void GrantDataPrivacyConsent() { AdvertisingConsentManager.Instance.GrantDataPrivacyConsent(); } /// <summary> /// Grants the provider-level data privacy consent for the specified ad network. /// </summary> /// <param name="adNetwork">Ad network.</param> public static void GrantDataPrivacyConsent(AdNetwork adNetwork) { // Use GetAdClient so the client won't be initialized (until it's actually used). // This is necessary as the consent should be set prior initialization for most networks. GetAdClient(adNetwork).GrantDataPrivacyConsent(); } /// <summary> /// Revokes the module-level data privacy consent. /// This consent persists across app launches. /// </summary> /// <remarks> /// This method is a wrapper of <c>AdvertisingConsentManager.Instance.RevokeDataPrivacyConsent</c>. /// </remarks> public static void RevokeDataPrivacyConsent() { AdvertisingConsentManager.Instance.RevokeDataPrivacyConsent(); } /// <summary> /// Revokes the provider-level data privacy consent of the specified ad network. /// </summary> /// <param name="adNetwork">Ad network.</param> public static void RevokeDataPrivacyConsent(AdNetwork adNetwork) { GetAdClient(adNetwork).RevokeDataPrivacyConsent(); } /// <summary> /// Gets the data privacy consent status for the specified ad network. /// </summary> /// <returns>The data privacy consent.</returns> /// <param name="adNetwork">Ad network.</param> public static ConsentStatus GetDataPrivacyConsent(AdNetwork adNetwork) { return GetAdClient(adNetwork).DataPrivacyConsent; } #endregion #region Ads API //------------------------------------------------------------ // Initialization. //------------------------------------------------------------ /// <summary> /// Initialize the Advertising module. Once initialized, auto ad-loading will start if enabled. /// </summary> public static void Initialize() { initialized = true; // Show FairBid Test Suite if needed. if (EM_Settings.Advertising.FairBid.ShowTestSuite) FairBidClient.ShowTestSuite(); AutoAdLoadingMode = EM_Settings.Advertising.AutoAdLoadingMode; } /// <summary> /// Whether the Advertising module has been initalized. /// </summary> /// <returns></returns> public static bool IsInitialized() { return initialized; } //------------------------------------------------------------ // Auto Ad-Loading. //------------------------------------------------------------ /// <summary> /// Gets or sets auto ad-loading mode. /// </summary> public static AutoAdLoadingMode AutoAdLoadingMode { get { return currentAutoLoadAdsMode; } set { if (value == currentAutoLoadAdsMode) return; isUpdatingAutoLoadMode = true; EM_Settings.Advertising.AutoAdLoadingMode = value; currentAutoLoadAdsMode = value; isUpdatingAutoLoadMode = false; if (autoLoadAdsCoroutine != null) Instance.StopCoroutine(autoLoadAdsCoroutine); switch (value) { case AutoAdLoadingMode.LoadDefaultAds: { autoLoadAdsCoroutine = CRAutoLoadDefaultAds(); Instance.StartCoroutine(autoLoadAdsCoroutine); break; } case AutoAdLoadingMode.LoadAllDefinedPlacements: { autoLoadAdsCoroutine = CRAutoLoadAllAds(); Instance.StartCoroutine(autoLoadAdsCoroutine); break; } case AutoAdLoadingMode.None: default: autoLoadAdsCoroutine = null; break; } } } //------------------------------------------------------------ // Banner Ads. //------------------------------------------------------------ /// <summary> /// Shows the default banner ad at the specified position. /// </summary> /// <param name="position">Position.</param> public static void ShowBannerAd(BannerAdPosition position) { ShowBannerAd(DefaultBannerAdClient, AdPlacement.Default, position, BannerAdSize.SmartBanner); } /// <summary> /// Shows a banner ad of the default banner ad network /// at the specified position and size using the default placement. /// </summary> /// <param name="position">Position.</param> /// <param name="size">Banner ad size.</param> public static void ShowBannerAd(BannerAdPosition position, BannerAdSize size) { ShowBannerAd(DefaultBannerAdClient, AdPlacement.Default, position, size); } /// <summary> /// Shows a banner ad of the specified ad network at the specified position and size /// using the default placement. /// </summary> /// <param name="adNetwork">Ad network.</param> /// <param name="position">Position.</param> /// <param name="size">Ad size, applicable for AdMob banner only.</param> public static void ShowBannerAd(BannerAdNetwork adNetwork, BannerAdPosition position, BannerAdSize size) { ShowBannerAd(GetWorkableAdClient((AdNetwork)adNetwork), AdPlacement.Default, position, size); } /// <summary> /// Shows the banner ad with the specified parameters. /// </summary> /// <param name="adNetwork">Ad network.</param> /// <param name="placement">Placement.</param> /// <param name="position">Position.</param> /// <param name="size">Size.</param> public static void ShowBannerAd(BannerAdNetwork adNetwork, AdPlacement placement, BannerAdPosition position, BannerAdSize size) { ShowBannerAd(GetWorkableAdClient((AdNetwork)adNetwork), placement, position, size); } /// <summary> /// Hides the default banner ad. /// </summary> public static void HideBannerAd() { HideBannerAd(DefaultBannerAdClient, AdPlacement.Default); } /// <summary> /// Hides the banner ad of the specified ad network at the specified placement. /// </summary> /// <param name="adNetwork">Ad network.</param> /// <param name="placement">Placement. Pass <c>AdPlacement.Default</c> to specify the default placement.</param> public static void HideBannerAd(BannerAdNetwork adNetwork, AdPlacement placement) { HideBannerAd(GetWorkableAdClient((AdNetwork)adNetwork), placement); } /// <summary> /// Destroys the default banner ad. /// </summary> public static void DestroyBannerAd() { DestroyBannerAd(DefaultBannerAdClient, AdPlacement.Default); } /// <summary> /// Destroys the banner ad of the specified ad network at the specified placement. /// </summary> /// <param name="adNetwork">Ad network.</param> /// <param name="placement">Placement. Pass <c>AdPlacement.Default</c> to specify the default placement.</param> public static void DestroyBannerAd(BannerAdNetwork adNetwork, AdPlacement placement) { DestroyBannerAd(GetWorkableAdClient((AdNetwork)adNetwork), placement); } //------------------------------------------------------------ // Interstitial Ads. //------------------------------------------------------------ /// <summary> /// Loads the default interstitial ad. /// </summary> public static void LoadInterstitialAd() { LoadInterstitialAd(DefaultInterstitialAdClient, AdPlacement.Default); } /// <summary> /// Loads the interstitial ad of the default interstitial ad network at the specified placement. /// </summary> /// <param name="placement">Placement.</param> public static void LoadInterstitialAd(AdPlacement placement) { LoadInterstitialAd(DefaultInterstitialAdClient, placement); } /// <summary> /// Loads the interstitial ad of the specified ad network at the specified placement. /// </summary> /// <param name="adNetwork">Ad network.</param> /// <param name="placement">Placement. Pass <c>AdPlacement.Default</c> to specify the default placement.</param> public static void LoadInterstitialAd(InterstitialAdNetwork adNetwork, AdPlacement placement) { LoadInterstitialAd(GetWorkableAdClient((AdNetwork)adNetwork), placement); } /// <summary> /// Determines whether the default interstitial ad is ready to show. /// </summary> /// <returns><c>true</c> if the ad is ready; otherwise, <c>false</c>.</returns> public static bool IsInterstitialAdReady() { if (!IsInitialized()) return false; return IsInterstitialAdReady(DefaultInterstitialAdClient, AdPlacement.Default); } /// <summary> /// Determines whether the interstitial ad of the default interstitial ad network /// at the specified placement is ready to show. /// </summary> /// <returns><c>true</c> if the ad is ready; otherwise, <c>false</c>.</returns> /// <param name="placement">Placement.</param> public static bool IsInterstitialAdReady(AdPlacement placement) { if (!IsInitialized()) return false; return IsInterstitialAdReady(DefaultInterstitialAdClient, placement); } /// <summary> /// Determines whether the interstitial ad of the specified ad network /// at the specified placement is ready to show. /// </summary> /// <returns><c>true</c> if the ad is ready; otherwise, <c>false</c>.</returns> /// <param name="adNetwork">Ad network.</param> /// <param name="placement">Placement. Pass <c>AdPlacement.Default</c> to specify the default placement.</param> public static bool IsInterstitialAdReady(InterstitialAdNetwork adNetwork, AdPlacement placement) { if (!IsInitialized()) return false; return IsInterstitialAdReady(GetWorkableAdClient((AdNetwork)adNetwork), placement); } /// <summary> /// Shows the default interstitial ad. /// </summary> public static void ShowInterstitialAd() { ShowInterstitialAd(DefaultInterstitialAdClient, AdPlacement.Default); } /// <summary> /// Shows the interstitial ad of the default interstitial ad network at the specified placement. /// </summary> /// <param name="placement">Placement.</param> public static void ShowInterstitialAd(AdPlacement placement) { ShowInterstitialAd(DefaultInterstitialAdClient, placement); } /// <summary> /// Shows the interstitial ad of the specified ad network at the specified placement. /// </summary> /// <param name="adNetwork">Ad network.</param> /// <param name="placement">Placement. Pass <c>AdPlacement.Default</c> to specify the default placement.</param> public static void ShowInterstitialAd(InterstitialAdNetwork adNetwork, AdPlacement placement) { ShowInterstitialAd(GetWorkableAdClient((AdNetwork)adNetwork), placement); } //------------------------------------------------------------ // Rewarded Ads. //------------------------------------------------------------ /// <summary> /// Loads the default rewarded ad. /// </summary> public static void LoadRewardedAd() { LoadRewardedAd(DefaultRewardedAdClient, AdPlacement.Default); } /// <summary> /// Loads the rewarded ad of the default rewarded ad network at the specified placement. /// </summary> /// <param name="placement">Placement.</param> public static void LoadRewardedAd(AdPlacement placement) { LoadRewardedAd(DefaultRewardedAdClient, placement); } /// <summary> /// Loads the rewarded ad of the specified ad network at the specified placement. /// </summary> /// <param name="adNetwork">Ad network.</param> /// <param name="placement">Placement. Pass <c>AdPlacement.Default</c> to specify the default placement.</param> public static void LoadRewardedAd(RewardedAdNetwork adNetwork, AdPlacement placement) { LoadRewardedAd(GetWorkableAdClient((AdNetwork)adNetwork), placement); } /// <summary> /// Determines whether the default rewarded ad is ready to show. /// </summary> /// <returns><c>true</c> if the ad is ready; otherwise, <c>false</c>.</returns> public static bool IsRewardedAdReady() { if (!IsInitialized()) return false; return IsRewardedAdReady(DefaultRewardedAdClient, AdPlacement.Default); } /// <summary> /// Determines whether the rewarded ad of the default rewarded ad network /// at the specified placement is ready to show. /// </summary> /// <returns><c>true</c> if the ad is ready; otherwise, <c>false</c>.</returns> /// <param name="placement">Placement.</param> public static bool IsRewardedAdReady(AdPlacement placement) { if (!IsInitialized()) return false; return IsRewardedAdReady(DefaultRewardedAdClient, placement); } /// <summary> /// Determines whether the rewarded ad of the specified ad network /// at the specified placement is ready to show. /// </summary> /// <returns><c>true</c> if the ad is ready; otherwise, <c>false</c>.</returns> /// <param name="adNetwork">Ad network.</param> /// <param name="placement">Placement. Pass <c>AdPlacement.Default</c> to specify the default placement.</param> public static bool IsRewardedAdReady(RewardedAdNetwork adNetwork, AdPlacement placement) { if (!IsInitialized()) return false; return IsRewardedAdReady(GetWorkableAdClient((AdNetwork)adNetwork), placement); } /// <summary> /// Shows the default rewarded ad. /// </summary> public static void ShowRewardedAd() { ShowRewardedAd(DefaultRewardedAdClient, AdPlacement.Default); } /// <summary> /// Shows the rewarded ad of the default rewarded ad network at the specified placement. /// </summary> /// <param name="placement">Placement.</param> public static void ShowRewardedAd(AdPlacement placement) { ShowRewardedAd(DefaultRewardedAdClient, placement); } /// <summary> /// Shows the rewarded ad of the specified ad network at the specified placement. /// </summary> /// <param name="adNetwork">Ad network.</param> /// <param name="placement">Placement. Pass <c>AdPlacement.Default</c> to specify the default placement.</param> public static void ShowRewardedAd(RewardedAdNetwork adNetwork, AdPlacement placement) { ShowRewardedAd(GetWorkableAdClient((AdNetwork)adNetwork), placement); } //------------------------------------------------------------ // Ads Removal. //------------------------------------------------------------ /// <summary> /// Determines whether ads were removed. /// </summary> /// <returns><c>true</c> if ads were removed; otherwise, <c>false</c>.</returns> public static bool IsAdRemoved() { return (StorageUtil.GetInt(AD_REMOVE_STATUS_PPKEY, AD_ENABLED) == AD_DISABLED); } /// <summary> /// Removes ads permanently. This is intended to be used with the "Remove Ads" button. /// This will hide any banner ad if it is being shown and /// prohibit future loading and showing of all ads, except rewarded ads. /// You can pass <c>true</c> to <c>revokeConsents</c> to also revoke the data privacy consent /// of the Advertising module and all supported networks (which may be desirable as rewarded ads are still available). /// Note that this method uses PlayerPrefs to store the ad removal status with no encryption/scrambling. /// </summary> /// <param name="revokeConsents">If set to <c>true</c> revoke consents.</param> public static void RemoveAds(bool revokeConsents = false) { // Destroy banner ad if any. DestroyAllBannerAds(); // Revoke all clients' consent if needed. if (revokeConsents) { RevokeAllNetworksDataPrivacyConsent(); RevokeDataPrivacyConsent(); } // Store ad removal status. StorageUtil.SetInt(AD_REMOVE_STATUS_PPKEY, AD_DISABLED); StorageUtil.Save(); // Fire event if (AdsRemoved != null) AdsRemoved(); Debug.Log("Ads were removed."); } /// <summary> /// Resets the ads removal status and allows showing ads again. /// This is intended for testing purpose only. Note that this method /// doesn't restore the data privacy consent of the Advertising module /// and the supported networks. /// </summary> public static void ResetRemoveAds() { // Update ad removal status. StorageUtil.SetInt(AD_REMOVE_STATUS_PPKEY, AD_ENABLED); StorageUtil.Save(); Debug.Log("Ads were re-enabled."); } #endregion // Public API #region Deprecated API [Obsolete("This method was deprecated. Please use AutoAdLoadingMode property instead.")] public static bool IsAutoLoadDefaultAds() { return EM_Settings.Advertising.AutoAdLoadingMode == AutoAdLoadingMode.LoadDefaultAds; } [Obsolete("This method was deprecated. Please use AutoAdLoadingMode property instead.")] public static void EnableAutoLoadDefaultAds(bool isAutoLoad) { EM_Settings.Advertising.AutoAdLoadingMode = isAutoLoad ? AutoAdLoadingMode.LoadDefaultAds : AutoAdLoadingMode.None; } [Obsolete("This method was deprecated. Please use AutoAdLoadingMode property instead.")] public static void SetAutoLoadDefaultAds(bool isAutoLoad) { EnableAutoLoadDefaultAds(isAutoLoad); } [Obsolete("This method was deprecated. Please use " + "LoadInterstitialAd(InterstitialAdNetwork adNetwork, AdPlacement placement) instead.")] public static void LoadInterstitialAd(InterstitialAdNetwork adNetwork, AdLocation location) { LoadInterstitialAd(adNetwork, location.ToAdPlacement()); } [Obsolete("This method was deprecated. Please use " + "IsInterstitialAdReady(InterstitialAdNetwork adNetwork, AdPlacement placement) instead.")] public static bool IsInterstitialAdReady(InterstitialAdNetwork adNetwork, AdLocation location) { return IsInterstitialAdReady(adNetwork, location.ToAdPlacement()); } [Obsolete("This method was deprecated. Please use " + "ShowInterstitialAd(InterstitialAdNetwork adNetwork, AdPlacement placement) instead.")] public static void ShowInterstitialAd(InterstitialAdNetwork adNetwork, AdLocation location) { ShowInterstitialAd(adNetwork, location.ToAdPlacement()); } [Obsolete("This method was deprecated. Please use " + "LoadRewardedAd(RewardedAdNetwork adNetwork, AdPlacement placement) instead.")] public static void LoadRewardedAd(RewardedAdNetwork adNetwork, AdLocation location) { LoadRewardedAd(adNetwork, location.ToAdPlacement()); } [Obsolete("This method was deprecated. Please use " + "IsRewardedAdReady(RewardedAdNetwork adNetwork, AdPlacement placement) instead.")] public static bool IsRewardedAdReady(RewardedAdNetwork adNetwork, AdLocation location) { return IsRewardedAdReady(adNetwork, location.ToAdPlacement()); } [Obsolete("This method was deprecated. Please use " + "ShowRewardedAd(RewardedAdNetwork adNetwork, AdPlacement placement) instead.")] public static void ShowRewardedAd(RewardedAdNetwork adNetwork, AdLocation location) { ShowRewardedAd(adNetwork, location.ToAdPlacement()); } #endregion #region Internal Stuff #region Auto-Load ads // This coroutine regularly checks if intersititial and rewarded ads are loaded, if they aren't // it will automatically perform loading. // If ads were removed, other ads will no longer be loaded except rewarded ads since they are // shown under user discretion and therefore can still possibly be used even if ads were removed. private static IEnumerator CRAutoLoadDefaultAds(float delay = 0) { if (delay > 0) yield return new WaitForSeconds(delay); while (true) { foreach (AdType type in Enum.GetValues(typeof(AdType))) { switch (type) { case AdType.Interstitial: if (!IsInterstitialAdReady() && !IsAdRemoved()) { if (Time.realtimeSinceStartup - lastDefaultInterstitialAdLoadTimestamp >= EM_Settings.Advertising.AdLoadingInterval) { LoadInterstitialAd(); lastDefaultInterstitialAdLoadTimestamp = Time.realtimeSinceStartup; } } break; case AdType.Rewarded: if (!IsRewardedAdReady()) { if (Time.realtimeSinceStartup - lastDefaultRewardedAdLoadTimestamp >= EM_Settings.Advertising.AdLoadingInterval) { LoadRewardedAd(); lastDefaultRewardedAdLoadTimestamp = Time.realtimeSinceStartup; } } break; default: break; } } yield return new WaitForSeconds(EM_Settings.Advertising.AdCheckingInterval); } } /// <summary> /// This coroutine load all available ads (default and custom) of all imported networks. /// </summary> /// <param name="delay">Delay time when starting the coroutine.</param> private static IEnumerator CRAutoLoadAllAds(float delay = 0) { if (delay > 0) yield return new WaitForSeconds(delay); List<IAdClient> availableInterstitialNetworks = GetAvailableNetworks<InterstitialAdNetwork>(); List<IAdClient> availableRewardedNetworks = GetAvailableNetworks<RewardedAdNetwork>(); while (true) { LoadAllInterstitialAds(availableInterstitialNetworks); LoadAllRewardedAds(availableRewardedNetworks); yield return new WaitForSeconds(EM_Settings.Advertising.AdCheckingInterval); } } /// <summary> /// Load all available interstitial ads of specific clients. /// </summary> private static void LoadAllInterstitialAds(List<IAdClient> clients) { if (IsAdRemoved()) return; foreach (var client in clients) { /// Load all defined interstitial ad placements. var customPlacements = client.DefinedCustomInterstitialAdPlacements; if (customPlacements == null) { customPlacements = new List<AdPlacement>(); } if (!customPlacements.Contains(AdPlacement.Default)) customPlacements.Add(AdPlacement.Default); // always load the Default placement. foreach (var placement in customPlacements) { if (!client.IsValidPlacement(placement, AdType.Interstitial)) continue; string tempIndex = client.Network.ToString() + placement.ToString(); if (IsInterstitialAdReady(client, placement)) continue; if (!lastCustomInterstitialAdsLoadTimestamp.ContainsKey(tempIndex)) lastCustomInterstitialAdsLoadTimestamp.Add(tempIndex, DEFAULT_TIMESTAMP); if (Time.realtimeSinceStartup - lastCustomInterstitialAdsLoadTimestamp[tempIndex] < EM_Settings.Advertising.AdLoadingInterval) continue; LoadInterstitialAd(client, placement); lastCustomInterstitialAdsLoadTimestamp[tempIndex] = Time.realtimeSinceStartup; } } } /// <summary> /// Load all available rewarded ads of specific clients. /// </summary> private static void LoadAllRewardedAds(List<IAdClient> clients) { foreach (var client in clients) { /// Load all custom rewarded ads if available. var customPlacements = client.DefinedCustomRewardedAdPlacements; if (customPlacements == null) { customPlacements = new List<AdPlacement>(); } // Add the Default placement to the loading list. Some networks // may only allow loading one rewarded ad at a time (subsequent loadings can // only be done if previous ad has been consumed), so we make sure the // Default placement is always loaded first by inserting it at the first index. if (!customPlacements.Contains(AdPlacement.Default)) customPlacements.Insert(0, AdPlacement.Default); foreach (var placement in customPlacements) { if (!client.IsValidPlacement(placement, AdType.Rewarded)) continue; string tempIndex = client.Network.ToString() + placement.ToString(); if (IsRewardedAdReady(client, placement)) continue; if (!lastCustomRewardedAdsLoadTimestamp.ContainsKey(tempIndex)) lastCustomRewardedAdsLoadTimestamp.Add(tempIndex, DEFAULT_TIMESTAMP); if (Time.realtimeSinceStartup - lastCustomRewardedAdsLoadTimestamp[tempIndex] < EM_Settings.Advertising.AdLoadingInterval) continue; LoadRewardedAd(client, placement); lastCustomRewardedAdsLoadTimestamp[tempIndex] = Time.realtimeSinceStartup; } } } /// <summary> /// Returns all imported ads networks. /// </summary> private static List<IAdClient> GetAvailableNetworks<T>() { List<IAdClient> availableNetworks = new List<IAdClient>(); foreach (T network in Enum.GetValues(typeof(T))) { AdClientImpl client = GetAdClient((AdNetwork)(Enum.Parse(typeof(T), network.ToString()))); if (client.IsSdkAvail) { var workableClient = GetWorkableAdClient((AdNetwork)(Enum.Parse(typeof(T), network.ToString()))); availableNetworks.Add(workableClient); } } return availableNetworks; } #endregion private static void ShowBannerAd(IAdClient client, AdPlacement placement, BannerAdPosition position, BannerAdSize size) { if (IsAdRemoved()) { Debug.Log("Could not show banner ad: ads were removed."); return; } client.ShowBannerAd(placement, position, size); AddActiveBannerAd(client.Network, placement); } private static void HideBannerAd(IAdClient client, AdPlacement placement) { client.HideBannerAd(placement); RemoveActiveBannerAd(client.Network, placement); } private static void DestroyBannerAd(IAdClient client, AdPlacement placement) { client.DestroyBannerAd(placement); RemoveActiveBannerAd(client.Network, placement); } private static void DestroyAllBannerAds() { foreach (KeyValuePair<AdNetwork, List<AdPlacement>> pair in activeBannerAds) { if (pair.Value != null && pair.Value.Count > 0) { var client = GetWorkableAdClient(pair.Key); foreach (var placement in pair.Value) client.DestroyBannerAd(placement); } } activeBannerAds.Clear(); } private static void LoadInterstitialAd(IAdClient client, AdPlacement placement) { if (IsAdRemoved()) return; client.LoadInterstitialAd(placement); } private static bool IsInterstitialAdReady(IAdClient client, AdPlacement placement) { if (!IsInitialized()) return false; if (IsAdRemoved()) return false; return client.IsInterstitialAdReady(placement); } private static void ShowInterstitialAd(IAdClient client, AdPlacement placement) { if (IsAdRemoved()) { Debug.Log("Could not show interstitial ad: ads were disabled by RemoveAds()."); return; } client.ShowInterstitialAd(placement); } // Note that rewarded ads should still be available after ads removal. // which is why we don't check if ads were removed in the following methods. private static void LoadRewardedAd(IAdClient client, AdPlacement placement) { client.LoadRewardedAd(placement); } private static bool IsRewardedAdReady(IAdClient client, AdPlacement placement) { if (!IsInitialized()) return false; return client.IsRewardedAdReady(placement); } private static void ShowRewardedAd(IAdClient client, AdPlacement placement) { client.ShowRewardedAd(placement); } /// <summary> /// Adds the given network and placement to the dict of currently shown banner ads, /// if the dict hasn't contained them already. /// </summary> /// <param name="network">Network.</param> /// <param name="placement">Placement.</param> private static void AddActiveBannerAd(AdNetwork network, AdPlacement placement) { List<AdPlacement> bannerAdPlacements; activeBannerAds.TryGetValue(network, out bannerAdPlacements); // This network already has some active placements // (rarely happens but logically possible). if (bannerAdPlacements != null) { if (!bannerAdPlacements.Contains(placement)) bannerAdPlacements.Add(placement); } // This network hasn't had any active placements yet. else { activeBannerAds[network] = new List<AdPlacement>() { placement }; } } /// <summary> /// Removes the given network and placement from the dict of currently shown banner ads, /// if they exists in the dict. /// </summary> /// <param name="network">Network.</param> /// <param name="placement">Placement.</param> private static void RemoveActiveBannerAd(AdNetwork network, AdPlacement placement) { List<AdPlacement> bannerAdPlacements; activeBannerAds.TryGetValue(network, out bannerAdPlacements); if (bannerAdPlacements != null) { bannerAdPlacements.Remove(placement); } } /// <summary> /// Grants the data privacy consent to all supported networks. Use with care. /// </summary> private static void GrantAllNetworksDataPrivacyConsent() { foreach (AdNetwork network in Enum.GetValues(typeof(AdNetwork))) { if (network != AdNetwork.None) GrantDataPrivacyConsent(network); } } /// <summary> /// Revokes the data privacy consent of all supported networks. Use with care. /// </summary> private static void RevokeAllNetworksDataPrivacyConsent() { foreach (AdNetwork network in Enum.GetValues(typeof(AdNetwork))) { if (network != AdNetwork.None) RevokeDataPrivacyConsent(network); } } /// <summary> /// Gets the singleton ad client of the specified network. /// This may or may not be initialized. /// </summary> /// <returns>The ad client.</returns> /// <param name="network">Network.</param> private static AdClientImpl GetAdClient(AdNetwork network) { switch (network) { case AdNetwork.AdColony: return AdColonyClientImpl.CreateClient(); case AdNetwork.AdMob: return AdMobClientImpl.CreateClient(); case AdNetwork.AppLovin: return AppLovinClientImpl.CreateClient(); case AdNetwork.Chartboost: return ChartboostClientImpl.CreateClient(); case AdNetwork.AudienceNetwork: return AudienceNetworkClientImpl.CreateClient(); case AdNetwork.FairBid: return FairBidClientImpl.CreateClient(); case AdNetwork.IronSource: return IronSourceClientImpl.CreateClient(); case AdNetwork.MoPub: return MoPubClientImpl.CreateClient(); case AdNetwork.TapJoy: return TapjoyClientImpl.CreateClient(); case AdNetwork.UnityAds: return UnityAdsClientImpl.CreateClient(); case AdNetwork.None: return NoOpClientImpl.CreateClient(); case AdNetwork.Vungle: return VungleClientImpl.CreateClient(); default: throw new NotImplementedException("No client implemented for the network:" + network.ToString()); } } /// <summary> /// Grabs the singleton ad client for the specified network and performs /// necessary setup for it, including initializing it and subscribing to its events. /// </summary> /// <returns>The ad client.</returns> /// <param name="network">Network.</param> private static AdClientImpl SetupAdClient(AdNetwork network) { AdClientImpl client = GetAdClient(network); if (client != null && client.Network != AdNetwork.None) { // Subscribe client's events. SubscribeAdClientEvents(client); // Initialize ad client. if (!client.IsInitialized) client.Init(); } return client; } /// <summary> /// Grabs the ready to work (done initialization, setup, etc.) /// ad client for the specified network. /// </summary> /// <returns>The workable ad client.</returns> /// <param name="network">Network.</param> private static AdClientImpl GetWorkableAdClient(AdNetwork network) { if (!InitializationClientCheck()) return NoOpClientImpl.CreateClient(); switch (network) { case AdNetwork.AdColony: return AdColonyClient; case AdNetwork.AdMob: return AdMobClient; case AdNetwork.AppLovin: return AppLovinClient; case AdNetwork.Chartboost: return ChartboostClient; case AdNetwork.AudienceNetwork: return AudienceNetworkClient; case AdNetwork.FairBid: return FairBidClient; case AdNetwork.MoPub: return MoPubClient; case AdNetwork.IronSource: return IronSourceClient; case AdNetwork.UnityAds: return UnityAdsClient; case AdNetwork.TapJoy: return TapjoyClient; case AdNetwork.None: return NoOpClientImpl.CreateClient(); case AdNetwork.Vungle: return VungleClient; default: throw new NotImplementedException("No client found for the network:" + network.ToString()); } } private static void SubscribeAdClientEvents(IAdClient client) { if (client == null) return; client.InterstitialAdCompleted += OnInternalInterstitialAdCompleted; client.RewardedAdSkipped += OnInternalRewardedAdSkipped; client.RewardedAdCompleted += OnInternalRewardedAdCompleted; } private static void OnInternalInterstitialAdCompleted(IAdClient client, AdPlacement placement) { if (InterstitialAdCompleted != null) InterstitialAdCompleted((InterstitialAdNetwork)client.Network, placement); } private static void OnInternalRewardedAdSkipped(IAdClient client, AdPlacement placement) { if (RewardedAdSkipped != null) RewardedAdSkipped((RewardedAdNetwork)client.Network, placement); } private static void OnInternalRewardedAdCompleted(IAdClient client, AdPlacement placement) { if (RewardedAdCompleted != null) RewardedAdCompleted((RewardedAdNetwork)client.Network, placement); } #endregion } }
38.827359
148
0.571905
[ "MIT" ]
Guillemsc/Playground
Assets/EasyMobile/Scripts/Modules/Advertising/Advertising.cs
53,079
C#