content stringlengths 5 1.04M | avg_line_length float64 1.75 12.9k | max_line_length int64 2 244k | alphanum_fraction float64 0 0.98 | licenses list | repository_name stringlengths 7 92 | path stringlengths 3 249 | size int64 5 1.04M | lang stringclasses 2
values |
|---|---|---|---|---|---|---|---|---|
using System.Collections;
using System.Collections.Generic;
namespace RsaPpkManager
{
/// <summary>Extension methods</summary>
public static class ExtensionMethods
{
#region ICollection<T>
/// <summary>Adds the elements of the specified enumerable to the end of the collection.</summary>
/// <typeparam name="T">The type of elements in the collection.</typeparam>
/// <param name="collection">The collection to add items to.</param>
/// <param name="enumerable">The items to add to the collection.</param>
public static void AddRange<T>(this ICollection<T> collection, IEnumerable<T> enumerable)
{
foreach (T t in enumerable)
{
collection.Add(t);
}
}
/// <summary>Removes the specified elements from the collection.</summary>
/// <typeparam name="T">The type of elements in the collection.</typeparam>
/// <param name="collection">The collection to remove items from.</param>
/// <param name="enumerable">The items to remove from the collection.</param>
public static void RemoveRange<T>(this ICollection<T> collection, IEnumerable<T> enumerable)
{
foreach (T t in enumerable)
{
collection.Remove(t);
}
}
#endregion
#region IList
/// <summary>Adds the elements of the specified enumerable to the end of the list.</summary>
/// <param name="list">The list to add items to.</param>
/// <param name="enumerable">The items to add to the list.</param>
public static void AddRange<T>(this IList list, IEnumerable<T> enumerable)
{
foreach (T t in enumerable)
{
list.Add(t);
}
}
/// <summary>Removes the specified elements from the list.</summary>
/// <param name="list">The list to remove items from.</param>
/// <param name="enumerable">The items to remove from the list.</param>
public static void RemoveRange<T>(this IList list, IEnumerable<T> enumerable)
{
foreach (T t in enumerable)
{
list.Remove(t);
}
}
#endregion
}
}
| 35.8125 | 106 | 0.585951 | [
"MIT"
] | AaronAmberman/RSAPPK | RSAPPK/RsaPpkManager/ExtensionMethods.cs | 2,294 | C# |
#pragma checksum "G:\lil\IdentityServer4.Samples.Test\QuickStarts\1_ClientCredentials\src\QuickstartIdentityServer\Views\Account\Logout.cshtml" "{ff1816ec-aa5e-4d10-87f7-6f4963833460}" "43db1622951c9cdde4dad74af954beb52e19d6f2"
// <auto-generated/>
#pragma warning disable 1591
[assembly: global::Microsoft.AspNetCore.Razor.Hosting.RazorCompiledItemAttribute(typeof(AspNetCore.Views_Account_Logout), @"mvc.1.0.view", @"/Views/Account/Logout.cshtml")]
[assembly:global::Microsoft.AspNetCore.Mvc.Razor.Compilation.RazorViewAttribute(@"/Views/Account/Logout.cshtml", typeof(AspNetCore.Views_Account_Logout))]
namespace AspNetCore
{
#line hidden
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
#line 1 "G:\lil\IdentityServer4.Samples.Test\QuickStarts\1_ClientCredentials\src\QuickstartIdentityServer\Views\_ViewImports.cshtml"
using IdentityServer4.Quickstart.UI;
#line default
#line hidden
[global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"43db1622951c9cdde4dad74af954beb52e19d6f2", @"/Views/Account/Logout.cshtml")]
[global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"57b49bb18fbe88f2fb7e20eb130e64338d7f2c37", @"/Views/_ViewImports.cshtml")]
public class Views_Account_Logout : global::Microsoft.AspNetCore.Mvc.Razor.RazorPage<LogoutViewModel>
{
private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_0 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("asp-action", "Logout", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
#line hidden
#pragma warning disable 0169
private string __tagHelperStringValueBuffer;
#pragma warning restore 0169
private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperExecutionContext __tagHelperExecutionContext;
private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperRunner __tagHelperRunner = new global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperRunner();
private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperScopeManager __backed__tagHelperScopeManager = null;
private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperScopeManager __tagHelperScopeManager
{
get
{
if (__backed__tagHelperScopeManager == null)
{
__backed__tagHelperScopeManager = new global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperScopeManager(StartTagHelperWritingScope, EndTagHelperWritingScope);
}
return __backed__tagHelperScopeManager;
}
}
private global::Microsoft.AspNetCore.Mvc.TagHelpers.FormTagHelper __Microsoft_AspNetCore_Mvc_TagHelpers_FormTagHelper;
private global::Microsoft.AspNetCore.Mvc.TagHelpers.RenderAtEndOfFormTagHelper __Microsoft_AspNetCore_Mvc_TagHelpers_RenderAtEndOfFormTagHelper;
#pragma warning disable 1998
public async override global::System.Threading.Tasks.Task ExecuteAsync()
{
BeginContext(24, 230, true);
WriteLiteral("\r\n<div class=\"logout-page\">\r\n <div class=\"page-header\">\r\n <h1>Logout</h1>\r\n </div>\r\n\r\n <div class=\"row\">\r\n <div class=\"col-sm-6\">\r\n <p>Would you like to logout of IdentityServer?</p>\r\n ");
EndContext();
BeginContext(254, 330, false);
__tagHelperExecutionContext = __tagHelperScopeManager.Begin("form", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "7f2e67d7a04643eda2a8b5147a9717c2", async() => {
BeginContext(280, 54, true);
WriteLiteral("\r\n <input type=\"hidden\" name=\"logoutId\"");
EndContext();
BeginWriteAttribute("value", " value=\"", 334, "\"", 357, 1);
#line 12 "G:\lil\IdentityServer4.Samples.Test\QuickStarts\1_ClientCredentials\src\QuickstartIdentityServer\Views\Account\Logout.cshtml"
WriteAttributeValue("", 342, Model.LogoutId, 342, 15, false);
#line default
#line hidden
EndWriteAttribute();
BeginContext(358, 219, true);
WriteLiteral(" />\r\n <fieldset>\r\n <div class=\"form-group\">\r\n <button class=\"btn btn-primary\">Yes</button>\r\n </div>\r\n </fieldset>\r\n ");
EndContext();
}
);
__Microsoft_AspNetCore_Mvc_TagHelpers_FormTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.FormTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_FormTagHelper);
__Microsoft_AspNetCore_Mvc_TagHelpers_RenderAtEndOfFormTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.RenderAtEndOfFormTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_RenderAtEndOfFormTagHelper);
__Microsoft_AspNetCore_Mvc_TagHelpers_FormTagHelper.Action = (string)__tagHelperAttribute_0.Value;
__tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_0);
await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);
if (!__tagHelperExecutionContext.Output.IsContentModified)
{
await __tagHelperExecutionContext.SetOutputContentAsync();
}
Write(__tagHelperExecutionContext.Output);
__tagHelperExecutionContext = __tagHelperScopeManager.End();
EndContext();
BeginContext(584, 36, true);
WriteLiteral("\r\n </div>\r\n </div>\r\n</div>");
EndContext();
}
#pragma warning restore 1998
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.ViewFeatures.IModelExpressionProvider ModelExpressionProvider { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.IUrlHelper Url { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.IViewComponentHelper Component { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.Rendering.IJsonHelper Json { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.Rendering.IHtmlHelper<LogoutViewModel> Html { get; private set; }
}
}
#pragma warning restore 1591
| 70.287129 | 299 | 0.713763 | [
"Apache-2.0"
] | leili-ncut/IdentityServer4.Samples.Test | QuickStarts/1_ClientCredentials/src/QuickstartIdentityServer/obj/Debug/netcoreapp2.1/Razor/Views/Account/Logout.g.cshtml.cs | 7,099 | C# |
using Windows.UI.Xaml.Controls;
namespace SplitViewMenuUWP.Scenario1
{
public sealed partial class Scenario1Page1 : Page
{
public Scenario1Page1()
{
InitializeComponent();
}
}
} | 18.916667 | 53 | 0.621145 | [
"MIT"
] | deanchalk/SplitViewMenuUWP | SplitViewMenuUWP/Scenario1/Scenario1Page1.xaml.cs | 229 | C# |
namespace Domain.Common
{
public class IAggregateRoot
{
}
} | 12 | 31 | 0.638889 | [
"MIT"
] | komorowski-seba/QLApi | QLApi/Domain/Common/IAggregateRoot.cs | 74 | C# |
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Copyright (c) Microsoft Corporation. All rights reserved.
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
using System;
using System.Reflection;
using Microsoft.SPOT.Platform.Test;
namespace Microsoft.SPOT.Platform.Tests
{
public class Master
{
public static void Main()
{
string[] args = { "AttributesTests1", "AttributesTests2" };
MFTestRunner runner = new MFTestRunner(args);
}
}
}
| 41.2 | 201 | 0.315534 | [
"Apache-2.0"
] | AustinWise/Netduino-Micro-Framework | Test/Platform/Tests/CLR/mscorlib/attributes/Master.cs | 824 | C# |
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// $Id: List.java,v 1.6 2004/07/05 14:17:35 belaban Exp $
using System;
using Alachisoft.NCache.Runtime.Serialization.IO;
using Alachisoft.NCache.Runtime.Serialization;
namespace Alachisoft.NGroups.Util
{
/// <summary> Doubly-linked list. Elements can be added at head or tail and removed from head/tail.
/// This class is tuned for element access at either head or tail, random access to elements
/// is not very fast; in this case use Vector. Concurrent access is supported: a thread is blocked
/// while another thread adds/removes an object. When no objects are available, removal returns null.
/// </summary>
/// <author> Bela Ban
/// </author>
[Serializable]
internal class List : ICloneable, ICompactSerializable
{
public System.Collections.ArrayList Contents
{
get
{
System.Collections.ArrayList retval = System.Collections.ArrayList.Synchronized(new System.Collections.ArrayList(_size));
Element el;
lock (mutex)
{
el = head;
while (el != null)
{
retval.Add(el.obj);
el = el.next;
}
}
return retval;
}
}
protected internal Element head = null, tail = null;
protected internal int _size = 0;
protected internal object mutex = new object();
[Serializable]
protected internal class Element
{
private void InitBlock(List enclosingInstance)
{
this.enclosingInstance = enclosingInstance;
}
private List enclosingInstance;
public List Enclosing_Instance
{
get
{
return enclosingInstance;
}
}
internal object obj = null;
internal Element next = null;
internal Element prev = null;
internal Element(List enclosingInstance, object o)
{
InitBlock(enclosingInstance);
obj = o;
}
}
public List()
{
}
/// <summary>Adds an object at the tail of the list.</summary>
public virtual void add(object obj)
{
Element el = new Element(this, obj);
lock (mutex)
{
if (head == null)
{
head = el;
tail = head;
_size = 1;
}
else
{
el.prev = tail;
tail.next = el;
tail = el;
_size++;
}
}
}
/// <summary>Adds an object at the head of the list.</summary>
public virtual void addAtHead(object obj)
{
Element el = new Element(this, obj);
lock (mutex)
{
if (head == null)
{
head = el;
tail = head;
_size = 1;
}
else
{
el.next = head;
head.prev = el;
head = el;
_size++;
}
}
}
/// <summary>Removes an object from the tail of the list. Returns null if no elements available</summary>
public object remove()
{
Element retval = null;
lock (mutex)
{
if (tail == null)
return null;
retval = tail;
if (head == tail)
{
// last element
head = null;
tail = null;
}
else
{
tail.prev.next = null;
tail = tail.prev;
retval.prev = null;
}
_size--;
}
return retval.obj;
}
/// <summary>Removes an object from the head of the list. Returns null if no elements available </summary>
public object removeFromHead()
{
Element retval = null;
lock (mutex)
{
if (head == null)
return null;
retval = head;
if (head == tail)
{
// last element
head = null;
tail = null;
}
else
{
head = head.next;
head.prev = null;
retval.next = null;
}
_size--;
}
return retval.obj;
}
/// <summary>Returns element at the tail (if present), but does not remove it from list.</summary>
public object peek()
{
lock (mutex)
{
return tail != null?tail.obj:null;
}
}
/// <summary>Returns element at the head (if present), but does not remove it from list.</summary>
public object peekAtHead()
{
lock (mutex)
{
return head != null?head.obj:null;
}
}
/// <summary>Removes element <code>obj</code> from the list, checking for equality using the <code>equals</code>
/// operator. Only the first duplicate object is removed. Returns the removed object.
/// </summary>
public object removeElement(object obj)
{
Element el = null;
object retval = null;
lock (mutex)
{
el = head;
while (el != null)
{
if (el.obj.Equals(obj))
{
retval = el.obj;
if (head == tail)
{
// only 1 element left in the list
head = null;
tail = null;
}
else if (el.prev == null)
{
// we're at the head
head = el.next;
head.prev = null;
el.next = null;
}
else if (el.next == null)
{
// we're at the tail
tail = el.prev;
tail.next = null;
el.prev = null;
}
else
{
// we're somewhere in the middle of the list
el.prev.next = el.next;
el.next.prev = el.prev;
el.next = null;
el.prev = null;
}
_size--;
break;
}
el = el.next;
}
}
return retval;
}
public void removeAll()
{
lock (mutex)
{
_size = 0;
head = null;
tail = null;
}
}
public int size()
{
return _size;
}
public override string ToString()
{
System.Text.StringBuilder ret = new System.Text.StringBuilder("[");
Element el = head;
while (el != null)
{
if (el.obj != null)
{
ret.Append(el.obj + " ");
}
el = el.next;
}
ret.Append(']');
return ret.ToString();
}
public string dump()
{
System.Text.StringBuilder ret = new System.Text.StringBuilder("[");
for (Element el = head; el != null; el = el.next)
{
ret.Append(el.obj + " ");
}
return ret.ToString() + ']';
}
public System.Collections.IEnumerator elements()
{
return new ListEnumerator(this, head);
}
public bool contains(object obj)
{
Element el = head;
while (el != null)
{
if (el.obj != null && el.obj.Equals(obj))
return true;
el = el.next;
}
return false;
}
public List copy()
{
List retval = new List();
lock (mutex)
{
for (Element el = head; el != null; el = el.next)
retval.add(el.obj);
}
return retval;
}
public object Clone()
{
return copy();
}
internal class ListEnumerator : System.Collections.IEnumerator
{
private void InitBlock(List enclosingInstance)
{
this.enclosingInstance = enclosingInstance;
}
private object tempAuxObj;
public bool MoveNext()
{
bool result = hasMoreElements();
if (result)
{
tempAuxObj = nextElement();
}
return result;
}
public void Reset()
{
tempAuxObj = null;
}
public object Current
{
get
{
return tempAuxObj;
}
}
private List enclosingInstance;
public List Enclosing_Instance
{
get
{
return enclosingInstance;
}
}
internal Element curr = null;
internal ListEnumerator(List enclosingInstance, Element start)
{
InitBlock(enclosingInstance);
curr = start;
}
public bool hasMoreElements()
{
return curr != null;
}
public object nextElement()
{
object retval;
if (curr == null)
throw new System.ArgumentOutOfRangeException();
retval = curr.obj;
curr = curr.next;
return retval;
}
}
#region ICompactSerializable Members
void ICompactSerializable.Deserialize(CompactReader reader)
{
object obj;
int new_size = reader.ReadInt32();
if (new_size == 0)
return;
for (int i = 0; i < new_size; i++)
{
obj = reader.ReadObject();
add(obj);
}
}
void ICompactSerializable.Serialize(CompactWriter writer)
{
Element el;
lock (mutex)
{
el = head;
writer.Write(_size);
for (int i = 0; i < _size; i++)
{
writer.WriteObject(el.obj);
el = el.next;
}
}
}
#endregion
}
}
| 18.758772 | 125 | 0.582651 | [
"Apache-2.0"
] | NCacheDev/NCache | Src/NCCluster/Util/List.cs | 8,554 | C# |
/******************************************************************************
* The MIT License
* Copyright (c) 2003 Novell Inc. www.novell.com
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the Software), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED AS IS, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*******************************************************************************/
//
// Novell.Directory.Ldap.LdapReferralHandler.cs
//
// Author:
// Sunil Kumar (Sunilk@novell.com)
//
// (C) 2003 Novell, Inc (http://www.novell.com)
//
namespace Novell.Directory.Ldap
{
/// <summary>
/// Shared ancestor to the two types of referral objects - LdapBindHandler and
/// LdapAuthHandler.
/// </summary>
/// <seealso cref="ILdapBindHandler">
/// </seealso>
/// <seealso cref="ILdapAuthHandler">
/// </seealso>
public interface ILdapReferralHandler
{
}
} | 39.282609 | 86 | 0.662424 | [
"MIT"
] | AlliterativeAlice/Novell.Directory.Ldap.NETStandard | src/Novell.Directory.Ldap.NETStandard/LdapReferralHandler.cs | 1,807 | C# |
#if !NET451
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
using RockLib.Configuration;
using RockLib.Configuration.ObjectFactory;
using System;
using System.Collections.Generic;
using System.Linq;
namespace RockLib.Messaging.DependencyInjection
{
/// <summary>
/// Extension methods for dependency injection and messaging.
/// </summary>
public static class MessagingExtensions
{
/// <summary>The default lifetime of messaging services.</summary>
private const ServiceLifetime _defaultLifetime = ServiceLifetime.Singleton;
/// <summary>
/// Adds an <see cref="ISender"/> to the service collection where the sender is
/// created from the 'RockLib_Messaging' / 'RockLib.Messaging' composite section
/// of the registered <see cref="IConfiguration"/>.
/// </summary>
/// <param name="services">The <see cref="IServiceCollection"/>.</param>
/// <param name="senderName">
/// The name that identifies which sender from configuration to create.
/// </param>
/// <param name="lifetime">The <see cref="ServiceLifetime"/> of the sender.</param>
/// <returns>A new <see cref="ISenderBuilder"/> for decorating the <see cref="ISender"/>.</returns>
public static ISenderBuilder AddSender(this IServiceCollection services, string senderName,
ServiceLifetime lifetime = _defaultLifetime)
{
if (services is null)
throw new ArgumentNullException(nameof(services));
if (senderName is null)
throw new ArgumentNullException(nameof(senderName));
return services.AddSender(serviceProvider =>
{
var messagingSection = GetMessagingSection(serviceProvider);
var resolver = new Resolver(serviceProvider.GetService, CanResolve);
return messagingSection.CreateSender(senderName, resolver: resolver);
}, lifetime);
bool CanResolve(Type type) =>
type != typeof(ISender)
&& type != typeof(SenderLookup)
&& services.Any(s => s.ServiceType == type);
}
/// <summary>
/// Adds an <see cref="ISender"/> to the service collection where the sender is created
/// with options obtained by name from an <see cref="IOptionsMonitor{TOptions}"/> using
/// the specified factory method.
/// <para>If <paramref name="reloadOnChange"/> is true, then the sender will automatically
/// reload itself whenever its options
/// changes.</para>
/// </summary>
/// <typeparam name="TSenderOptions">The type of options used to create the sender.</typeparam>
/// <param name="services">The <see cref="IServiceCollection"/>.</param>
/// <param name="senderName">
/// The name that identifies which named options to use from the <see cref=
/// "IOptionsMonitor{TOptions}"/>.
/// </param>
/// <param name="createSender">
/// A function that creates the instance of <see cref="ISender"/> using options obtained
/// from the <see cref="IOptionsMonitor{TOptions}"/>.
/// </param>
/// <param name="configureOptions">
/// An optional callback for configuring the <typeparamref name="TSenderOptions"/>. If
/// provided, invoking this callback is the <em>last</em> step in creating and configuring
/// the options used to create the sender.
/// </param>
/// <param name="reloadOnChange">
/// Whether to create a sender that automatically reloads itself when its configuration
/// or options change.
/// </param>
/// <param name="lifetime">The <see cref="ServiceLifetime"/> of the sender.</param>
/// <returns>A new <see cref="ISenderBuilder"/> for decorating the <see cref="ISender"/>.</returns>
public static ISenderBuilder AddSender<TSenderOptions>(this IServiceCollection services, string senderName,
Func<TSenderOptions, IServiceProvider, ISender> createSender, Action<TSenderOptions> configureOptions = null,
bool reloadOnChange = true, ServiceLifetime lifetime = _defaultLifetime)
where TSenderOptions : class, new()
{
if (services is null)
throw new ArgumentNullException(nameof(services));
if (senderName is null)
throw new ArgumentNullException(nameof(senderName));
if (createSender is null)
throw new ArgumentNullException(nameof(createSender));
return services.AddSender(serviceProvider =>
{
var optionsMonitor = serviceProvider.GetService<IOptionsMonitor<TSenderOptions>>();
if (reloadOnChange && optionsMonitor != null)
{
return new ReloadingSender<TSenderOptions>(senderName,
options => createSender.Invoke(options, serviceProvider),
optionsMonitor, configureOptions);
}
var senderOptions = optionsMonitor.GetOptions(senderName, configureOptions);
return createSender.Invoke(senderOptions, serviceProvider);
}, lifetime);
}
/// <summary>
/// Adds an <see cref="ISender"/> to the service collection.
/// </summary>
/// <param name="services">The <see cref="IServiceCollection"/>.</param>
/// <param name="registration">
/// The registration delegate that is responsible for creating the <see cref="ISender"/>.
/// </param>
/// <param name="lifetime">The <see cref="ServiceLifetime"/> of the sender.</param>
/// <returns>A new <see cref="ISenderBuilder"/> for decorating the <see cref="ISender"/>.</returns>
public static ISenderBuilder AddSender(this IServiceCollection services, SenderRegistration registration,
ServiceLifetime lifetime = _defaultLifetime)
{
if (services is null)
throw new ArgumentNullException(nameof(services));
if (registration is null)
throw new ArgumentNullException(nameof(registration));
var builder = new SenderBuilder(registration);
services.Add(new ServiceDescriptor(typeof(ISender), builder.Build, lifetime));
services.SetSenderLookupDescriptor();
return builder;
}
/// <summary>
/// Adds an <see cref="ITransactionalSender"/> to the service collection where the sender is
/// created from the 'RockLib_Messaging' / 'RockLib.Messaging' composite section
/// of the registered <see cref="IConfiguration"/>.
/// </summary>
/// <param name="services">The <see cref="IServiceCollection"/>.</param>
/// <param name="senderName">
/// The name that identifies which sender from configuration to create.
/// </param>
/// <param name="lifetime">The <see cref="ServiceLifetime"/> of the transactional sender.</param>
/// <returns>A new <see cref="ITransactionalSender"/> for decorating the <see cref="ITransactionalSender"/>.</returns>
public static ITransactionalSenderBuilder AddTransactionalSender(this IServiceCollection services, string senderName,
ServiceLifetime lifetime = _defaultLifetime)
{
if (services is null)
throw new ArgumentNullException(nameof(services));
if (senderName is null)
throw new ArgumentNullException(nameof(senderName));
return services.AddTransactionalSender(serviceProvider =>
{
var messagingSection = GetMessagingSection(serviceProvider);
var resolver = new Resolver(serviceProvider.GetService, CanResolve);
return (ITransactionalSender)messagingSection.CreateSender(senderName, resolver: resolver);
}, lifetime);
bool CanResolve(Type type) =>
type != typeof(ITransactionalSender)
&& type != typeof(TransactionalSenderLookup)
&& services.Any(s => s.ServiceType == type);
}
/// <summary>
/// Adds an <see cref="ITransactionalSender"/> to the service collection.
/// </summary>
/// <param name="services">The <see cref="IServiceCollection"/>.</param>
/// <param name="registration">
/// The registration delegate that is responsible for creating the <see cref="ITransactionalSender"/>.
/// </param>
/// <param name="lifetime">The <see cref="ServiceLifetime"/> of the transactional sender.</param>
/// <returns>A new <see cref="ITransactionalSenderBuilder"/> for decorating the <see cref="ITransactionalSender"/>.</returns>
public static ITransactionalSenderBuilder AddTransactionalSender(this IServiceCollection services,
TransactionalSenderRegistration registration, ServiceLifetime lifetime = _defaultLifetime)
{
if (services is null)
throw new ArgumentNullException(nameof(services));
if (registration is null)
throw new ArgumentNullException(nameof(registration));
var builder = new TransactionalSenderBuilder(registration);
services.Add(new ServiceDescriptor(typeof(ITransactionalSender), builder.Build, lifetime));
services.SetTransactionalSenderLookupDescriptor();
services.SetSenderLookupDescriptor();
return builder;
}
/// <summary>
/// Adds an <see cref="IReceiver"/> to the service collection where the receiver is
/// created from the 'RockLib_Messaging' / 'RockLib.Messaging' composite section
/// of the registered <see cref="IConfiguration"/>.
/// </summary>
/// <param name="services">The <see cref="IServiceCollection"/>.</param>
/// <param name="receiverName">
/// The name that identifies which receiver from configuration to create.
/// </param>
/// <param name="lifetime">The <see cref="ServiceLifetime"/> of the receiver.</param>
/// <returns>A new <see cref="IReceiverBuilder"/> for decorating the <see cref="IReceiver"/>.</returns>
public static IReceiverBuilder AddReceiver(this IServiceCollection services, string receiverName,
ServiceLifetime lifetime = _defaultLifetime)
{
if (services is null)
throw new ArgumentNullException(nameof(services));
if (receiverName is null)
throw new ArgumentNullException(nameof(receiverName));
return services.AddReceiver(serviceProvider =>
{
var messagingSection = GetMessagingSection(serviceProvider);
var resolver = new Resolver(serviceProvider.GetService, CanResolve);
return messagingSection.CreateReceiver(receiverName, resolver: resolver);
}, lifetime);
bool CanResolve(Type type) =>
type != typeof(IReceiver)
&& type != typeof(ReceiverLookup)
&& services.Any(s => s.ServiceType == type);
}
/// <summary>
/// Adds an <see cref="IReceiver"/> to the service collection where the receiver is created
/// with options obtained by name from an <see cref="IOptionsMonitor{TOptions}"/> using
/// the specified factory method.
/// <para>If <paramref name="reloadOnChange"/> is true, then the receiver will automatically
/// reload itself whenever its options changes.</para>
/// </summary>
/// <typeparam name="TReceiverOptions">The type of options used to create the receiver.</typeparam>
/// <param name="services">The <see cref="IServiceCollection"/>.</param>
/// <param name="receiverName">
/// The name that identifies which named options to use from the <see cref=
/// "IOptionsMonitor{TOptions}"/>.
/// </param>
/// <param name="createReceiver">
/// A function that creates the instance of <see cref="IReceiver"/> using options obtained
/// from the <see cref="IOptionsMonitor{TOptions}"/>.
/// </param>
/// <param name="configureOptions">
/// An optional callback for configuring the <typeparamref name="TReceiverOptions"/>. If
/// provided, invoking this callback is the <em>last</em> step in creating and configuring
/// the options used to create the receiver.
/// </param>
/// <param name="reloadOnChange">
/// Whether to create a receiver that automatically reloads itself when its configuration
/// or options change.
/// </param>
/// <param name="lifetime">The <see cref="ServiceLifetime"/> of the receiver.</param>
/// <returns>A new <see cref="IReceiverBuilder"/> for decorating the <see cref="IReceiver"/>.</returns>
public static IReceiverBuilder AddReceiver<TReceiverOptions>(this IServiceCollection services, string receiverName,
Func<TReceiverOptions, IServiceProvider, IReceiver> createReceiver, Action<TReceiverOptions> configureOptions = null,
bool reloadOnChange = true, ServiceLifetime lifetime = _defaultLifetime)
where TReceiverOptions : class, new()
{
if (services is null)
throw new ArgumentNullException(nameof(services));
if (receiverName is null)
throw new ArgumentNullException(nameof(receiverName));
if (createReceiver is null)
throw new ArgumentNullException(nameof(createReceiver));
return services.AddReceiver(serviceProvider =>
{
var optionsMonitor = serviceProvider.GetService<IOptionsMonitor<TReceiverOptions>>();
if (reloadOnChange && optionsMonitor != null)
{
return new ReloadingReceiver<TReceiverOptions>(receiverName,
options => createReceiver.Invoke(options, serviceProvider),
optionsMonitor, configureOptions);
}
var receiverOptions = optionsMonitor.GetOptions(receiverName, configureOptions);
return createReceiver.Invoke(receiverOptions, serviceProvider);
}, lifetime);
}
/// <summary>
/// Adds an <see cref="IReceiver"/> to the service collection.
/// </summary>
/// <param name="services">The <see cref="IServiceCollection"/>.</param>
/// <param name="registration">
/// The registration delegate that is responsible for creating the <see cref="IReceiver"/>.
/// </param>
/// <param name="lifetime">The <see cref="ServiceLifetime"/> of the receiver.</param>
/// <returns>A new <see cref="IReceiverBuilder"/> for decorating the <see cref="IReceiver"/>.</returns>
public static IReceiverBuilder AddReceiver(this IServiceCollection services, ReceiverRegistration registration,
ServiceLifetime lifetime = _defaultLifetime)
{
if (services is null)
throw new ArgumentNullException(nameof(services));
if (registration is null)
throw new ArgumentNullException(nameof(registration));
var builder = new ReceiverBuilder(registration);
services.Add(new ServiceDescriptor(typeof(IReceiver), builder.Build, lifetime));
services.SetReceiverLookupDescriptor();
return builder;
}
internal static TOptions GetOptions<TOptions>(this IOptionsMonitor<TOptions> optionsMonitor,
string name, Action<TOptions> configureOptions)
where TOptions : class, new()
{
var options = optionsMonitor?.Get(name) ?? new TOptions();
configureOptions?.Invoke(options);
return options;
}
private static IConfigurationSection GetMessagingSection(IServiceProvider serviceProvider)
{
var configuration = serviceProvider.GetRequiredService<IConfiguration>();
return configuration.GetCompositeSection("RockLib_Messaging", "RockLib.Messaging");
}
private static bool NamesEqual(string messagingServiceName, string lookupName)
{
if (string.Equals(messagingServiceName, lookupName, StringComparison.OrdinalIgnoreCase))
return true;
if (lookupName is null)
return string.Equals(messagingServiceName, "default", StringComparison.OrdinalIgnoreCase);
return false;
}
private static void SetSenderLookupDescriptor(this IServiceCollection services)
{
// Clear the existing SenderLookup descriptor, if it exists.
for (int i = 0; i < services.Count; i++)
if (services[i].ServiceType == typeof(SenderLookup))
services.RemoveAt(i--);
// Capture which senders and which transactional senders are singleton according to index.
IReadOnlyList<bool> isSingletonSender = services.Where(service => service.ServiceType == typeof(ISender))
.Select(service => service.Lifetime == ServiceLifetime.Singleton)
.ToArray();
IReadOnlyList<bool> isSingletonTransactionalSender = services.Where(service => service.ServiceType == typeof(ITransactionalSender))
.Select(service => service.Lifetime == ServiceLifetime.Singleton)
.ToArray();
SenderLookup SenderFactory(IServiceProvider serviceProvider) => name =>
{
// Find the first sender that has a matching name.
var senders = serviceProvider.GetServices<ISender>().ToArray();
var selectedSender = senders.FirstOrDefault(sender => NamesEqual(sender.Name, name));
if (selectedSender != null)
{
// Immediately dispose any non-singleton senders that weren't selected.
for (int i = 0; i < senders.Length; i++)
if (!isSingletonSender[i] && !ReferenceEquals(senders[i], selectedSender))
senders[i].Dispose();
}
else
{
// Immediately dispose of all non-singleton senders, since none were selected.
for (int i = 0; i < senders.Length; i++)
if (!isSingletonSender[i])
senders[i].Dispose();
// Find the first transactional sender that has a matching name.
var transactionalSenders = serviceProvider.GetServices<ITransactionalSender>().ToArray();
selectedSender = transactionalSenders.FirstOrDefault(sender => NamesEqual(sender.Name, name));
// Immediately dispose any non-singleton transactional senders that weren't selected.
for (int i = 0; i < transactionalSenders.Length; i++)
if (!isSingletonTransactionalSender[i] && !ReferenceEquals(transactionalSenders[i], selectedSender))
transactionalSenders[i].Dispose();
}
return selectedSender;
};
services.AddSingleton(SenderFactory);
}
private static void SetTransactionalSenderLookupDescriptor(this IServiceCollection services)
{
// Clear the existing TransactionalSenderLookup descriptor, if it exists.
for (int i = 0; i < services.Count; i++)
if (services[i].ServiceType == typeof(TransactionalSenderLookup))
services.RemoveAt(i--);
// Capture which transactional senders are singleton according to index.
IReadOnlyList<bool> isSingletonTransactionalSender = services.Where(service => service.ServiceType == typeof(ITransactionalSender))
.Select(service => service.Lifetime == ServiceLifetime.Singleton)
.ToArray();
TransactionalSenderLookup TransactionalSenderFactory(IServiceProvider serviceProvider) => name =>
{
// Find the first transactional sender that has a matching name.
var transactionalSenders = serviceProvider.GetServices<ITransactionalSender>().ToArray();
var selectedTransactionalSender = transactionalSenders.FirstOrDefault(sender => NamesEqual(sender.Name, name));
// Immediately dispose any non-singleton transactional senders that weren't selected.
for (int i = 0; i < transactionalSenders.Length; i++)
if (!isSingletonTransactionalSender[i] && !ReferenceEquals(transactionalSenders[i], selectedTransactionalSender))
transactionalSenders[i].Dispose();
return selectedTransactionalSender;
};
services.AddSingleton(TransactionalSenderFactory);
}
private static void SetReceiverLookupDescriptor(this IServiceCollection services)
{
// Clear the existing ReceiverLookup descriptor, if it exists.
for (int i = 0; i < services.Count; i++)
if (services[i].ServiceType == typeof(ReceiverLookup))
services.RemoveAt(i--);
// Capture which receivers are singleton according to index.
IReadOnlyList<bool> isSingletonReceiver = services.Where(service => service.ServiceType == typeof(IReceiver))
.Select(service => service.Lifetime == ServiceLifetime.Singleton)
.ToArray();
ReceiverLookup ReceiverLookupFactory(IServiceProvider serviceProvider) => name =>
{
// Find the first receiver that has a matching name.
var receivers = serviceProvider.GetServices<IReceiver>().ToArray();
var selectedReceiver = receivers.FirstOrDefault(receiver => NamesEqual(receiver.Name, name));
// Immediately dispose any non-singleton receivers that weren't selected.
for (int i = 0; i < receivers.Length; i++)
if (!isSingletonReceiver[i] && !ReferenceEquals(receivers[i], selectedReceiver))
receivers[i].Dispose();
return selectedReceiver;
};
services.AddSingleton(ReceiverLookupFactory);
}
}
}
#endif
| 51.047085 | 143 | 0.623007 | [
"MIT"
] | RockLib/RockLib.Messaging | RockLib.Messaging/DependencyInjection/MessagingExtensions.cs | 22,769 | C# |
namespace NuPattern.Runtime
{
/// <summary>
/// A command used in automation
/// </summary>
[Command]
public abstract class Command : ICommand
{
/// <summary>
/// Executes the command
/// </summary>
public abstract void Execute();
}
} | 21.071429 | 44 | 0.545763 | [
"Apache-2.0"
] | dbremner/nupattern | Src/Runtime/Source/Runtime.Extensibility/Command.cs | 297 | C# |
/*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the mediaconvert-2017-08-29.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using System.Net;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.MediaConvert.Model
{
/// <summary>
/// Required when you set (Type) under (OutputGroups)>(OutputGroupSettings) to HLS_GROUP_SETTINGS.
/// </summary>
public partial class HlsGroupSettings
{
private List<HlsAdditionalManifest> _additionalManifests = new List<HlsAdditionalManifest>();
private List<string> _adMarkers = new List<string>();
private HlsAudioOnlyHeader _audioOnlyHeader;
private string _baseUrl;
private List<HlsCaptionLanguageMapping> _captionLanguageMappings = new List<HlsCaptionLanguageMapping>();
private HlsCaptionLanguageSetting _captionLanguageSetting;
private HlsClientCache _clientCache;
private HlsCodecSpecification _codecSpecification;
private string _destination;
private DestinationSettings _destinationSettings;
private HlsDirectoryStructure _directoryStructure;
private HlsEncryptionSettings _encryption;
private HlsManifestCompression _manifestCompression;
private HlsManifestDurationFormat _manifestDurationFormat;
private double? _minFinalSegmentLength;
private int? _minSegmentLength;
private HlsOutputSelection _outputSelection;
private HlsProgramDateTime _programDateTime;
private int? _programDateTimePeriod;
private HlsSegmentControl _segmentControl;
private int? _segmentLength;
private int? _segmentsPerSubdirectory;
private HlsStreamInfResolution _streamInfResolution;
private HlsTimedMetadataId3Frame _timedMetadataId3Frame;
private int? _timedMetadataId3Period;
private int? _timestampDeltaMilliseconds;
/// <summary>
/// Gets and sets the property AdditionalManifests. By default, the service creates one
/// top-level .m3u8 HLS manifest for each HLS output group in your job. This default manifest
/// references every output in the output group. To create additional top-level manifests
/// that reference a subset of the outputs in the output group, specify a list of them
/// here.
/// </summary>
public List<HlsAdditionalManifest> AdditionalManifests
{
get { return this._additionalManifests; }
set { this._additionalManifests = value; }
}
// Check to see if AdditionalManifests property is set
internal bool IsSetAdditionalManifests()
{
return this._additionalManifests != null && this._additionalManifests.Count > 0;
}
/// <summary>
/// Gets and sets the property AdMarkers. Choose one or more ad marker types to decorate
/// your Apple HLS manifest. This setting does not determine whether SCTE-35 markers appear
/// in the outputs themselves.
/// </summary>
public List<string> AdMarkers
{
get { return this._adMarkers; }
set { this._adMarkers = value; }
}
// Check to see if AdMarkers property is set
internal bool IsSetAdMarkers()
{
return this._adMarkers != null && this._adMarkers.Count > 0;
}
/// <summary>
/// Gets and sets the property AudioOnlyHeader. Ignore this setting unless you are using
/// FairPlay DRM with Verimatrix and you encounter playback issues. Keep the default value,
/// Include (INCLUDE), to output audio-only headers. Choose Exclude (EXCLUDE) to remove
/// the audio-only headers from your audio segments.
/// </summary>
public HlsAudioOnlyHeader AudioOnlyHeader
{
get { return this._audioOnlyHeader; }
set { this._audioOnlyHeader = value; }
}
// Check to see if AudioOnlyHeader property is set
internal bool IsSetAudioOnlyHeader()
{
return this._audioOnlyHeader != null;
}
/// <summary>
/// Gets and sets the property BaseUrl. A partial URI prefix that will be prepended to
/// each output in the media .m3u8 file. Can be used if base manifest is delivered from
/// a different URL than the main .m3u8 file.
/// </summary>
public string BaseUrl
{
get { return this._baseUrl; }
set { this._baseUrl = value; }
}
// Check to see if BaseUrl property is set
internal bool IsSetBaseUrl()
{
return this._baseUrl != null;
}
/// <summary>
/// Gets and sets the property CaptionLanguageMappings. Language to be used on Caption
/// outputs
/// </summary>
public List<HlsCaptionLanguageMapping> CaptionLanguageMappings
{
get { return this._captionLanguageMappings; }
set { this._captionLanguageMappings = value; }
}
// Check to see if CaptionLanguageMappings property is set
internal bool IsSetCaptionLanguageMappings()
{
return this._captionLanguageMappings != null && this._captionLanguageMappings.Count > 0;
}
/// <summary>
/// Gets and sets the property CaptionLanguageSetting. Applies only to 608 Embedded output
/// captions. Insert: Include CLOSED-CAPTIONS lines in the manifest. Specify at least
/// one language in the CC1 Language Code field. One CLOSED-CAPTION line is added for
/// each Language Code you specify. Make sure to specify the languages in the order in
/// which they appear in the original source (if the source is embedded format) or the
/// order of the caption selectors (if the source is other than embedded). Otherwise,
/// languages in the manifest will not match up properly with the output captions. None:
/// Include CLOSED-CAPTIONS=NONE line in the manifest. Omit: Omit any CLOSED-CAPTIONS
/// line from the manifest.
/// </summary>
public HlsCaptionLanguageSetting CaptionLanguageSetting
{
get { return this._captionLanguageSetting; }
set { this._captionLanguageSetting = value; }
}
// Check to see if CaptionLanguageSetting property is set
internal bool IsSetCaptionLanguageSetting()
{
return this._captionLanguageSetting != null;
}
/// <summary>
/// Gets and sets the property ClientCache. Disable this setting only when your workflow
/// requires the #EXT-X-ALLOW-CACHE:no tag. Otherwise, keep the default value Enabled
/// (ENABLED) and control caching in your video distribution set up. For example, use
/// the Cache-Control http header.
/// </summary>
public HlsClientCache ClientCache
{
get { return this._clientCache; }
set { this._clientCache = value; }
}
// Check to see if ClientCache property is set
internal bool IsSetClientCache()
{
return this._clientCache != null;
}
/// <summary>
/// Gets and sets the property CodecSpecification. Specification to use (RFC-6381 or the
/// default RFC-4281) during m3u8 playlist generation.
/// </summary>
public HlsCodecSpecification CodecSpecification
{
get { return this._codecSpecification; }
set { this._codecSpecification = value; }
}
// Check to see if CodecSpecification property is set
internal bool IsSetCodecSpecification()
{
return this._codecSpecification != null;
}
/// <summary>
/// Gets and sets the property Destination. Use Destination (Destination) to specify the
/// S3 output location and the output filename base. Destination accepts format identifiers.
/// If you do not specify the base filename in the URI, the service will use the filename
/// of the input file. If your job has multiple inputs, the service uses the filename
/// of the first input file.
/// </summary>
public string Destination
{
get { return this._destination; }
set { this._destination = value; }
}
// Check to see if Destination property is set
internal bool IsSetDestination()
{
return this._destination != null;
}
/// <summary>
/// Gets and sets the property DestinationSettings. Settings associated with the destination.
/// Will vary based on the type of destination
/// </summary>
public DestinationSettings DestinationSettings
{
get { return this._destinationSettings; }
set { this._destinationSettings = value; }
}
// Check to see if DestinationSettings property is set
internal bool IsSetDestinationSettings()
{
return this._destinationSettings != null;
}
/// <summary>
/// Gets and sets the property DirectoryStructure. Indicates whether segments should be
/// placed in subdirectories.
/// </summary>
public HlsDirectoryStructure DirectoryStructure
{
get { return this._directoryStructure; }
set { this._directoryStructure = value; }
}
// Check to see if DirectoryStructure property is set
internal bool IsSetDirectoryStructure()
{
return this._directoryStructure != null;
}
/// <summary>
/// Gets and sets the property Encryption. DRM settings.
/// </summary>
public HlsEncryptionSettings Encryption
{
get { return this._encryption; }
set { this._encryption = value; }
}
// Check to see if Encryption property is set
internal bool IsSetEncryption()
{
return this._encryption != null;
}
/// <summary>
/// Gets and sets the property ManifestCompression. When set to GZIP, compresses HLS playlist.
/// </summary>
public HlsManifestCompression ManifestCompression
{
get { return this._manifestCompression; }
set { this._manifestCompression = value; }
}
// Check to see if ManifestCompression property is set
internal bool IsSetManifestCompression()
{
return this._manifestCompression != null;
}
/// <summary>
/// Gets and sets the property ManifestDurationFormat. Indicates whether the output manifest
/// should use floating point values for segment duration.
/// </summary>
public HlsManifestDurationFormat ManifestDurationFormat
{
get { return this._manifestDurationFormat; }
set { this._manifestDurationFormat = value; }
}
// Check to see if ManifestDurationFormat property is set
internal bool IsSetManifestDurationFormat()
{
return this._manifestDurationFormat != null;
}
/// <summary>
/// Gets and sets the property MinFinalSegmentLength. Keep this setting at the default
/// value of 0, unless you are troubleshooting a problem with how devices play back the
/// end of your video asset. If you know that player devices are hanging on the final
/// segment of your video because the length of your final segment is too short, use this
/// setting to specify a minimum final segment length, in seconds. Choose a value that
/// is greater than or equal to 1 and less than your segment length. When you specify
/// a value for this setting, the encoder will combine any final segment that is shorter
/// than the length that you specify with the previous segment. For example, your segment
/// length is 3 seconds and your final segment is .5 seconds without a minimum final segment
/// length; when you set the minimum final segment length to 1, your final segment is
/// 3.5 seconds.
/// </summary>
public double MinFinalSegmentLength
{
get { return this._minFinalSegmentLength.GetValueOrDefault(); }
set { this._minFinalSegmentLength = value; }
}
// Check to see if MinFinalSegmentLength property is set
internal bool IsSetMinFinalSegmentLength()
{
return this._minFinalSegmentLength.HasValue;
}
/// <summary>
/// Gets and sets the property MinSegmentLength. When set, Minimum Segment Size is enforced
/// by looking ahead and back within the specified range for a nearby avail and extending
/// the segment size if needed.
/// </summary>
[AWSProperty(Min=0, Max=2147483647)]
public int MinSegmentLength
{
get { return this._minSegmentLength.GetValueOrDefault(); }
set { this._minSegmentLength = value; }
}
// Check to see if MinSegmentLength property is set
internal bool IsSetMinSegmentLength()
{
return this._minSegmentLength.HasValue;
}
/// <summary>
/// Gets and sets the property OutputSelection. Indicates whether the .m3u8 manifest file
/// should be generated for this HLS output group.
/// </summary>
public HlsOutputSelection OutputSelection
{
get { return this._outputSelection; }
set { this._outputSelection = value; }
}
// Check to see if OutputSelection property is set
internal bool IsSetOutputSelection()
{
return this._outputSelection != null;
}
/// <summary>
/// Gets and sets the property ProgramDateTime. Includes or excludes EXT-X-PROGRAM-DATE-TIME
/// tag in .m3u8 manifest files. The value is calculated as follows: either the program
/// date and time are initialized using the input timecode source, or the time is initialized
/// using the input timecode source and the date is initialized using the timestamp_offset.
/// </summary>
public HlsProgramDateTime ProgramDateTime
{
get { return this._programDateTime; }
set { this._programDateTime = value; }
}
// Check to see if ProgramDateTime property is set
internal bool IsSetProgramDateTime()
{
return this._programDateTime != null;
}
/// <summary>
/// Gets and sets the property ProgramDateTimePeriod. Period of insertion of EXT-X-PROGRAM-DATE-TIME
/// entry, in seconds.
/// </summary>
[AWSProperty(Min=0, Max=3600)]
public int ProgramDateTimePeriod
{
get { return this._programDateTimePeriod.GetValueOrDefault(); }
set { this._programDateTimePeriod = value; }
}
// Check to see if ProgramDateTimePeriod property is set
internal bool IsSetProgramDateTimePeriod()
{
return this._programDateTimePeriod.HasValue;
}
/// <summary>
/// Gets and sets the property SegmentControl. When set to SINGLE_FILE, emits program
/// as a single media resource (.ts) file, uses #EXT-X-BYTERANGE tags to index segment
/// for playback.
/// </summary>
public HlsSegmentControl SegmentControl
{
get { return this._segmentControl; }
set { this._segmentControl = value; }
}
// Check to see if SegmentControl property is set
internal bool IsSetSegmentControl()
{
return this._segmentControl != null;
}
/// <summary>
/// Gets and sets the property SegmentLength. Length of MPEG-2 Transport Stream segments
/// to create (in seconds). Note that segments will end on the next keyframe after this
/// number of seconds, so actual segment length may be longer.
/// </summary>
[AWSProperty(Min=1, Max=2147483647)]
public int SegmentLength
{
get { return this._segmentLength.GetValueOrDefault(); }
set { this._segmentLength = value; }
}
// Check to see if SegmentLength property is set
internal bool IsSetSegmentLength()
{
return this._segmentLength.HasValue;
}
/// <summary>
/// Gets and sets the property SegmentsPerSubdirectory. Number of segments to write to
/// a subdirectory before starting a new one. directoryStructure must be SINGLE_DIRECTORY
/// for this setting to have an effect.
/// </summary>
[AWSProperty(Min=1, Max=2147483647)]
public int SegmentsPerSubdirectory
{
get { return this._segmentsPerSubdirectory.GetValueOrDefault(); }
set { this._segmentsPerSubdirectory = value; }
}
// Check to see if SegmentsPerSubdirectory property is set
internal bool IsSetSegmentsPerSubdirectory()
{
return this._segmentsPerSubdirectory.HasValue;
}
/// <summary>
/// Gets and sets the property StreamInfResolution. Include or exclude RESOLUTION attribute
/// for video in EXT-X-STREAM-INF tag of variant manifest.
/// </summary>
public HlsStreamInfResolution StreamInfResolution
{
get { return this._streamInfResolution; }
set { this._streamInfResolution = value; }
}
// Check to see if StreamInfResolution property is set
internal bool IsSetStreamInfResolution()
{
return this._streamInfResolution != null;
}
/// <summary>
/// Gets and sets the property TimedMetadataId3Frame. Indicates ID3 frame that has the
/// timecode.
/// </summary>
public HlsTimedMetadataId3Frame TimedMetadataId3Frame
{
get { return this._timedMetadataId3Frame; }
set { this._timedMetadataId3Frame = value; }
}
// Check to see if TimedMetadataId3Frame property is set
internal bool IsSetTimedMetadataId3Frame()
{
return this._timedMetadataId3Frame != null;
}
/// <summary>
/// Gets and sets the property TimedMetadataId3Period. Timed Metadata interval in seconds.
/// </summary>
[AWSProperty(Min=-2147483648, Max=2147483647)]
public int TimedMetadataId3Period
{
get { return this._timedMetadataId3Period.GetValueOrDefault(); }
set { this._timedMetadataId3Period = value; }
}
// Check to see if TimedMetadataId3Period property is set
internal bool IsSetTimedMetadataId3Period()
{
return this._timedMetadataId3Period.HasValue;
}
/// <summary>
/// Gets and sets the property TimestampDeltaMilliseconds. Provides an extra millisecond
/// delta offset to fine tune the timestamps.
/// </summary>
[AWSProperty(Min=-2147483648, Max=2147483647)]
public int TimestampDeltaMilliseconds
{
get { return this._timestampDeltaMilliseconds.GetValueOrDefault(); }
set { this._timestampDeltaMilliseconds = value; }
}
// Check to see if TimestampDeltaMilliseconds property is set
internal bool IsSetTimestampDeltaMilliseconds()
{
return this._timestampDeltaMilliseconds.HasValue;
}
}
} | 39.611219 | 113 | 0.631671 | [
"Apache-2.0"
] | PureKrome/aws-sdk-net | sdk/src/Services/MediaConvert/Generated/Model/HlsGroupSettings.cs | 20,479 | C# |
// Copyright 2007-2016 Chris Patterson, Dru Sellers, Travis Smith, et. al.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed
// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
// CONDITIONS OF ANY KIND, either express or implied. See the License for the
// specific language governing permissions and limitations under the License.
namespace MassTransit.AutofacIntegration
{
using Autofac;
/// <summary>
/// A lifetime scope registry contains an indexed set of lifetime scopes that can be used on
/// a per-index basis as the root for additional lifetime scopes (per request, etc.)
/// </summary>
public interface ILifetimeScopeRegistry<TId> :
ILifetimeScope
{
/// <summary>
/// Returns the lifetime scope for the specified scopeId
/// </summary>
/// <param name="scopeId">The scope identifier</param>
/// <returns>The lifetime scope</returns>
ILifetimeScope GetLifetimeScope(TId scopeId);
/// <summary>
/// Specify the configuration method for a lifetime scope
/// </summary>
/// <param name="scopeId">The switch identifier</param>
/// <param name="configureCallback">The configuration action for the switch</param>
void ConfigureLifetimeScope(TId scopeId, LifetimeScopeConfigurator<TId> configureCallback);
}
} | 43.538462 | 100 | 0.671378 | [
"Apache-2.0"
] | andymac4182/MassTransit | src/Containers/MassTransit.AutoFacIntegration/ILifetimeScopeRegistry.cs | 1,700 | C# |
namespace MAVN.Service.WAMPHost.DomainServices
{
static class Topic
{
public const string Balance = "balance";
public const string WalletStatus = "wallet-status";
}
static class Topics
{
public static readonly string[] WithAuth = {Topic.Balance, Topic.WalletStatus};
}
}
| 22.857143 | 87 | 0.65625 | [
"MIT"
] | HannaAndreevna/MAVN.Service.WAMPHost | src/MAVN.Service.WAMPHost.DomainServices/Topics.cs | 320 | C# |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Linq;
using Microsoft.WindowsAzure.Management.Sql.Models;
namespace Microsoft.WindowsAzure.Management.Sql.Models
{
/// <summary>
/// Represents a Firewall Rule for an Azure SQL Database Server.
/// </summary>
public partial class FirewallRule : SqlModelCommon
{
private string _endIPAddress;
/// <summary>
/// Optional. Gets the ending IP address for this Firewall Rule.
/// </summary>
public string EndIPAddress
{
get { return this._endIPAddress; }
set { this._endIPAddress = value; }
}
private string _startIPAddress;
/// <summary>
/// Optional. Gets the starting IP address for this Firewall Rule.
/// </summary>
public string StartIPAddress
{
get { return this._startIPAddress; }
set { this._startIPAddress = value; }
}
/// <summary>
/// Initializes a new instance of the FirewallRule class.
/// </summary>
public FirewallRule()
{
}
}
}
| 30.555556 | 76 | 0.634286 | [
"Apache-2.0"
] | CerebralMischief/azure-sdk-for-net | src/ServiceManagement/Sql/SqlManagement/Generated/Models/FirewallRule.cs | 1,925 | C# |
namespace CrossPlatformApp
{
using Shared.Infrastructure.Services;
using Shared.ViewModels;
using System;
using System.Threading.Tasks;
using System.Windows.Input;
using Xamarin.Forms;
public partial class ToDoList
{
public ToDoList()
{
try
{
InitializeComponent();
}
catch (System.Exception ex)
{
}
ItemsList.RefreshCommand = new Command(DoRefresh);
Title = "My Tasks";
}
public IMessageService MessageService { get; set; }
public TodoListViewModel ViewModel { get { return BindingContext as TodoListViewModel; } }
public string Title { get; set; }
public void LoadItemsAsync()
{
DoRefresh();
}
private void DoRefresh()
{
if (IsFaulted)
{
StartTrying(1);
}
if (ViewModel == null)
{
return;
}
ViewModel.LoadItemsAsync().ContinueWith<TodoItemViewModel[]>(HandleResult);
}
public bool IsFaulted { get; set; }
public bool IsTrying { get; set; }
private TodoItemViewModel[] HandleResult(Task<TodoItemViewModel[]> task)
{
if (task.Exception != null)
{
IsFaulted = true;
if (IsTrying == false)
{
StartTrying(5);
return new TodoItemViewModel[0];
}
return new TodoItemViewModel[0];
}
IsFaulted = false;
IsTrying = false;
var result = task.Result;
SetupCommands(result);
if (ItemsList.IsRefreshing)
{
try
{
ItemsList.IsRefreshing = false;
ItemsList.EndRefresh();
}
catch (Exception ex)
{
}
}
return result;
}
private void StartTrying(int tries)
{
IsTrying = true;
Task.Factory.StartNew(new Action(async delegate
{
int _retryCount = 0;
while (_retryCount < tries && IsFaulted)
{
_retryCount++;
await Task.Delay(3000).ContinueWith(task =>
{
ViewModel.LoadItemsAsync().ContinueWith<TodoItemViewModel[]>(HandleResult);
});
}
IsTrying = false;
}));
}
private void SetupCommands(TodoItemViewModel[] elements)
{
foreach (var item in elements)
{
SetupCommands(item);
}
}
private void SetupCommands(TodoItemViewModel item)
{
item.NavigateCommand = new Command(() => ViewModel.NavigateTo(item));
item.SaveCommand = new Command(() => ViewModel.Save(item) );
item.CancelEditCommand = new Command(() => ViewModel.CancelEdit(item));
item.ToggleCommand = new Command(() => OnToggle(item));
item.ShowOptionsCommand = new Command(() => OnShowOptionsCommand(item));
item.DeleteCommand = new Command(() => OnDeletePrompt(item));
item.DuplicateCommand = new Command(() => ViewModel.Duplicate(item));
item.EditCommand = new Command(() => ViewModel.Edit(item));
}
private async void OnShowOptionsCommand(TodoItemViewModel item)
{
if (MessageService == null)
{
return;
}
var selected = await MessageService.PickChoiceFrom(item.AsMenuOptions());
if (selected != null)
{
selected.Command.Execute(item);
}
}
private async void OnDeletePrompt(TodoItemViewModel item)
{
var result = await MessageService.ShowYesNo("Confirm delete", "Do you really want to delete it?", "Yes", "No");
if (result)
{
ViewModel.Elements.Remove(item);
}
}
private void OnToggle(TodoItemViewModel item)
{
item.Toggle();
}
internal void ScrollTo(TodoItemViewModel newItem)
{
ItemsList.ScrollTo(newItem, ScrollToPosition.End, true);
ItemsList.SelectedItem = newItem;
}
internal TodoItemViewModel CreateNew()
{
var newItem = ViewModel.CreateNew();
SetupCommands(newItem);
return newItem;
}
internal void EnableCreateFloatingButton(ICommand command)
{
CreateAction.IsVisible = true;
CreateAction.Command = command;
}
}
} | 28.261628 | 123 | 0.506892 | [
"MIT"
] | katherinsanta/crossPlatformDevelopment | FeaturedApps/ToDoApp/CrossPlatformApp/CrossPlatformApp/Views/ToDoList.xaml.cs | 4,863 | C# |
using UnityEngine;
using System.Collections;
public class PlayerController : MonoBehaviour
{
public float TurnSpeed = 0.2f;
public AudioClip DieSound;
public float ShotDelay = 0.5f;
public GameObject Shot;
public Transform ShotSpawner;
private Transform killer;
private int shotVelocityMultipier = 40;
private float randomValue = 0.02f;
private float shotSpawnerYOffset = 0.5f;
void Update()
{
if (killer == null)
return;
transform.rotation = Quaternion.LookRotation(killer.position - transform.position);
}
private float lastShot = 0;
public void Shoot()
{
if (Time.time - lastShot < ShotDelay)
return;
Fire();
lastShot = Time.time;
}
private void Fire()
{
var shotSpawnerPositionX = Random.Range(-randomValue, randomValue);
var shotSpawnerPositionY = Random.Range(-randomValue, randomValue) - shotSpawnerYOffset;
var shotSpawnPosition = new Vector3(ShotSpawner.position.x + shotSpawnerPositionX, ShotSpawner.position.y + shotSpawnerPositionY, ShotSpawner.position.z);
var shot = (GameObject) Instantiate(Shot, shotSpawnPosition, ShotSpawner.rotation);
shot.GetComponent<Rigidbody>().velocity = (ShotSpawner.position - transform.position).normalized * shotVelocityMultipier;
}
void OnCollisionEnter(Collision collision)
{
if (killer != null)
return;
var other = collision.gameObject;
var enemyController = other.GetComponent<EnemyController>();
if (enemyController == null)
return;
enemyController.Stop = true;
DisableGyroController();
PlayDieSound(other);
killer = other.transform;
StartCoroutine(Restart());
}
private void DisableGyroController()
{
GetComponent<GyroControlled>().enabled = false;
}
private void PlayDieSound(GameObject audioSource)
{
var killerAudioSource = audioSource.GetComponent<AudioSource>();
killerAudioSource.clip = DieSound;
killerAudioSource.Play();
}
private IEnumerator Restart()
{
yield return new WaitForSeconds(3);
Application.LoadLevel(Application.loadedLevel);
}
}
| 29.525641 | 162 | 0.657403 | [
"MIT"
] | codernb/GyroShooter | Assets/Scripts/PlayerController.cs | 2,305 | C# |
namespace AggregateSource.Testing
{
/// <summary>
/// Enumeration of possible states a test specification result can be in.
/// </summary>
public enum TestResultState
{
/// <summary>
/// The test specification passed
/// </summary>
Passed,
/// <summary>
/// The test specification failed
/// </summary>
Failed
}
} | 22.388889 | 77 | 0.545906 | [
"BSD-3-Clause"
] | ChrisMcKee/AggregateSource | src/Testing/AggregateSource.Testing/TestResultState.cs | 405 | C# |
//
// NumberConstructor.cs:
//
// Author: Cesar Octavio Lopez Nataren
//
// (C) 2003, Cesar Octavio Lopez Nataren, <cesar@ciencias.unam.mx>
//
//
// 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;
namespace Microsoft.JScript {
public class NumberConstructor : ScriptFunction {
internal static NumberConstructor Ctr = new NumberConstructor ();
internal NumberConstructor ()
{
_prototype = NumberPrototype.Proto;
_length = 1;
name = "Number";
}
public const double MAX_VALUE = Double.MaxValue;
public const double MIN_VALUE = Double.Epsilon;
public const double NaN = Double.NaN;
public const double NEGATIVE_INFINITY = Double.NegativeInfinity;
public const double POSITIVE_INFINITY = Double.PositiveInfinity;
[JSFunctionAttribute (JSFunctionAttributeEnum.HasVarArgs)]
public new NumberObject CreateInstance (params Object [] args)
{
double value = 0;
if (args.Length > 0)
value = Convert.ToNumber (args [0]);
return new NumberObject (value);
}
public double Invoke (object arg)
{
if (arg is Object []) {
Object [] args = (Object []) arg;
if (args.Length == 0)
return 0;
else
return Convert.ToNumber (args [0]);
}
return Convert.ToNumber (arg);
}
}
}
| 30.171053 | 73 | 0.723942 | [
"MIT"
] | zlxy/Genesis-3D | Engine/extlibs/IosLibs/mono-2.6.7/mcs/class/Microsoft.JScript/Microsoft.JScript/NumberConstructor.cs | 2,293 | C# |
using UnityEngine;
using System.Collections;
public class PongGameSetup : MonoBehaviour {
public Camera mainCam;
public BoxCollider2D topBorder;
public BoxCollider2D bottomBorder;
public BoxCollider2D leftBorder;
public BoxCollider2D rightBorder;
public Transform PlayerA;
public Transform PlayerB;
// Update is called once per frame
//void Start () {
void Update () {
//Move each wall to its pos.
topBorder.size = new Vector2 (mainCam.ScreenToWorldPoint (new Vector3 (Screen.width * 2.0f, 0.0f,0.0f)).x, 1.0f);
topBorder.center = new Vector2 (0.0f, mainCam.ScreenToWorldPoint (new Vector3 (0.0f, Screen.height, 0.0f)).y + 0.5f);
bottomBorder.size = new Vector2 (mainCam.ScreenToWorldPoint (new Vector3 (Screen.width * 2.0f, 0.0f,0.0f)).x, 1.0f);
bottomBorder.center = new Vector2 (0.0f, mainCam.ScreenToWorldPoint (new Vector3 (0.0f, 0.0f, 0.0f)).y - 0.5f);
leftBorder.size = new Vector2 (1.0f, mainCam.ScreenToWorldPoint (new Vector3 (0.0f, Screen.height * 2.0f, 0.0f)).y);
leftBorder.center = new Vector2 (mainCam.ScreenToWorldPoint (new Vector3 (0.0f, 0.0f, 0.0f)).x - 0.5f, 0.0f);
rightBorder.size = new Vector2 (1.0f, mainCam.ScreenToWorldPoint (new Vector3 (0.0f, Screen.height * 2.0f, 0.0f)).y);
rightBorder.center = new Vector2 (mainCam.ScreenToWorldPoint (new Vector3 (Screen.width, 0.0f, 0.0f)).x + 0.5f, 0.0f);
this.PlayerA.position = new Vector2(mainCam.ScreenToWorldPoint (new Vector3 (75.0f, 0.0f, 0.0f)).x, 0.0f);
this.PlayerB.position = new Vector2(mainCam.ScreenToWorldPoint (new Vector3 (Screen.width -75.0f, 0.0f, 0.0f)).x, 0.0f);
}
}
| 44.416667 | 122 | 0.719825 | [
"Unlicense"
] | ManyRaynolds/SP4 | SP4/Assets/Scripts/PongScripts/PongGameSetup.cs | 1,601 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Text;
namespace Sample.Entity
{
public class Department
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public string Name { get; set; }
public ICollection<Student> Students { get; set; }
}
}
| 22.4 | 61 | 0.694196 | [
"MIT"
] | altinburak/Fop | sample/Sample.Entity/Department.cs | 450 | C# |
namespace Dota2GSI.Nodes
{
/// <summary>
/// Class representing item information
/// </summary>
public class Item : Node
{
/// <summary>
/// Item name
/// </summary>
public readonly string Name;
/// <summary>
/// Item purchaser
/// </summary>
public readonly int Purchaser;
/// <summary>
/// The name of the rune contained inside this item.
/// <note type="note">Possible rune names: empty, arcane, bounty, double_damage, haste, illusion, invisibility, regen</note>
/// </summary>
public readonly string ContainsRune;
/// <summary>
/// A boolean representing whether this item can be casted
/// </summary>
public readonly bool CanCast;
/// <summary>
/// Item's cooldown
/// </summary>
public readonly int Cooldown;
/// <summary>
/// A boolean representing whether this item is passive
/// </summary>
public readonly bool IsPassive;
/// <summary>
/// The amount of charges on this item
/// </summary>
public readonly int Charges;
internal Item(string json_data) : base(json_data)
{
Name = GetString("name");
Purchaser = GetInt("purchaser");
ContainsRune = GetString("contains_rune");
CanCast = GetBool("can_cast");
Cooldown = GetInt("cooldown");
IsPassive = GetBool("passive");
Charges = GetInt("charges");
}
}
}
| 27 | 126 | 0.564815 | [
"MIT"
] | carebe01/Dota2GSI | Dota2GSI/Nodes/Item.cs | 1,514 | C# |
// ------------------------------------------------------------------------------
// <auto-generated>
// This file was generated by Extensibility Tools v1.10.211
// </auto-generated>
// ------------------------------------------------------------------------------
namespace OpenInXamarinStudio
{
static class Vsix
{
public const string Id = "4ED1099A-F28F-4E06-A2C8-8C3D3277B9A7";
public const string Name = "Open in Xamarin Studio";
public const string Description = @"Open multiple files simultaneously in Xamarin Studio directly from Solution Explorer or Code Editor window.";
public const string Language = "en-US";
public const string Version = "1.1.51";
public const string Author = "GregTrevellick";
public const string Tags = "open, open in, Xamarin, Xamarin Studio, studio";
}
}
| 45.315789 | 153 | 0.555168 | [
"MIT"
] | GregTrevellick/OpenInApp.Launcher | src/OpenInXamarinStudio/source.extension.cs | 861 | C# |
using System.Runtime.CompilerServices;
[assembly: InternalsVisibleTo("Firestorm.Stems.Tests")] | 32 | 55 | 0.822917 | [
"MIT"
] | connellw/Firestorm | src/Firestorm.Stems.Core/Properties/InternalsVisibleTo.cs | 98 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using JetBrains.Annotations;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Diagnostics;
using Microsoft.EntityFrameworkCore.Query;
using Microsoft.EntityFrameworkCore.Query.SqlExpressions;
using Microsoft.EntityFrameworkCore.Storage;
using Newtonsoft.Json.Linq;
using Pomelo.EntityFrameworkCore.MySql.Query.Expressions.Internal;
using Pomelo.EntityFrameworkCore.MySql.Query.ExpressionTranslators.Internal;
using Pomelo.EntityFrameworkCore.MySql.Query.Internal;
using Pomelo.EntityFrameworkCore.MySql.Storage.Internal;
namespace Pomelo.EntityFrameworkCore.MySql.Json.Newtonsoft.Query.Internal
{
public class MySqlJsonNewtonsoftDomTranslator : IMemberTranslator, IMethodCallTranslator
{
private static readonly MethodInfo _enumerableAnyWithoutPredicate = typeof(Enumerable).GetTypeInfo()
.GetMethods(BindingFlags.Public | BindingFlags.Static | BindingFlags.DeclaredOnly)
.Single(mi => mi.Name == nameof(Enumerable.Any) && mi.GetParameters().Length == 1);
private readonly IRelationalTypeMappingSource _typeMappingSource;
private readonly MySqlSqlExpressionFactory _sqlExpressionFactory;
private readonly MySqlJsonPocoTranslator _jsonPocoTranslator;
public MySqlJsonNewtonsoftDomTranslator(
[NotNull] MySqlSqlExpressionFactory sqlExpressionFactory,
[NotNull] IRelationalTypeMappingSource typeMappingSource,
[NotNull] MySqlJsonPocoTranslator jsonPocoTranslator)
{
_sqlExpressionFactory = sqlExpressionFactory;
_typeMappingSource = typeMappingSource;
_jsonPocoTranslator = jsonPocoTranslator;
}
public SqlExpression Translate(SqlExpression instance, MemberInfo member, Type returnType, IDiagnosticsLogger<DbLoggerCategory.Query> logger)
{
if (instance?.Type.IsGenericList() == true &&
member.Name == nameof(List<object>.Count) &&
instance.TypeMapping is null)
{
return _jsonPocoTranslator.TranslateArrayLength(instance);
}
if (!typeof(JToken).IsAssignableFrom(member.DeclaringType))
{
return null;
}
if (member.Name == nameof(JToken.Root) &&
instance is ColumnExpression column &&
column.TypeMapping is MySqlJsonTypeMapping)
{
// Simply get rid of the RootElement member access
return column;
}
var traversal = GetTraversalExpression(instance);
if (traversal == null)
{
return null;
}
// Support for JContainer.Count property (e.g. for JArray):
if (typeof(JContainer).IsAssignableFrom(member.DeclaringType) &&
member.Name == nameof(JContainer.Count))
{
return _jsonPocoTranslator.TranslateArrayLength(traversal);
}
return null;
}
public SqlExpression Translate(SqlExpression instance, MethodInfo method, IReadOnlyList<SqlExpression> arguments, IDiagnosticsLogger<DbLoggerCategory.Query> logger)
{
var traversal = GetTraversalExpression(instance, arguments);
if (traversal == null)
{
return null;
}
if (typeof(JToken).IsAssignableFrom(method.DeclaringType) &&
method.Name == "get_Item" &&
arguments.Count == 1)
{
var indexExpression = _sqlExpressionFactory.ApplyDefaultTypeMapping(arguments[0]);
if (method.DeclaringType == typeof(JArray) ||
indexExpression.Type == typeof(int))
{
// Try translating indexing inside json column.
return _jsonPocoTranslator.TranslateMemberAccess(
traversal,
_sqlExpressionFactory.JsonArrayIndex(indexExpression),
method.ReturnType);
}
return traversal.Append(
ApplyPathLocationTypeMapping(arguments[0]),
method.DeclaringType,
_typeMappingSource.FindMapping(method.DeclaringType));
}
// Support for .Value<T>() and .Value<U, T>():
if (instance == null &&
method.Name == nameof(global::Newtonsoft.Json.Linq.Extensions.Value) &&
method.DeclaringType == typeof(global::Newtonsoft.Json.Linq.Extensions) &&
method.IsGenericMethod &&
method.GetParameters().Length == 1 &&
arguments.Count == 1)
{
return ConvertFromJsonExtract(
traversal.Clone(
method.ReturnType == typeof(string),
method.ReturnType,
_typeMappingSource.FindMapping(method.ReturnType)
),
method.ReturnType);
}
// Support for Count()
if (instance == null &&
method.Name == nameof(Enumerable.Count) &&
method.DeclaringType == typeof(Enumerable) &&
method.IsGenericMethod &&
method.GetParameters().Length == 1 &&
arguments.Count == 1)
{
return _jsonPocoTranslator.TranslateArrayLength(traversal);
}
// Predicate-less Any - translate to a simple length check.
if (method.IsClosedFormOf(_enumerableAnyWithoutPredicate) &&
arguments.Count == 1 &&
arguments[0].Type.TryGetElementType(out _) &&
arguments[0].TypeMapping is MySqlJsonTypeMapping)
{
return _sqlExpressionFactory.GreaterThan(
_jsonPocoTranslator.TranslateArrayLength(arguments[0]),
_sqlExpressionFactory.Constant(0));
}
return null;
}
// The traversal expression can be the instance of the method that is being called, or the first
// argument, if the method called is an extension method.
private MySqlJsonTraversalExpression GetTraversalExpression(SqlExpression instance, IReadOnlyList<SqlExpression> arguments = null)
=> instance == null
? arguments?.Count >= 1
? GetJsonRootExpression(arguments[0])
: null
: GetJsonRootExpression(instance);
// The root of the JSON expression is a ColumnExpression. We wrap that with an empty traversal
// expression (col->'$'); subsequent traversals will gradually append the path into that.
// Note that it's possible to call methods such as GetString() directly on the root, and the
// empty traversal is necessary to properly convert it to a text.
private MySqlJsonTraversalExpression GetJsonRootExpression(SqlExpression instance)
=> instance is ColumnExpression columnExpression &&
instance.TypeMapping is MySqlJsonTypeMapping mapping
? _sqlExpressionFactory.JsonTraversal(
columnExpression, returnsText: false, typeof(string), mapping)
: instance as MySqlJsonTraversalExpression;
private SqlExpression ConvertFromJsonExtract(SqlExpression expression, Type returnType)
=> returnType == typeof(bool)
? _sqlExpressionFactory.NonOptimizedEqual(
expression,
_sqlExpressionFactory.Constant(true, _typeMappingSource.FindMapping(typeof(bool))))
: expression;
private SqlExpression ApplyPathLocationTypeMapping(SqlExpression expression)
{
var pathLocation = _sqlExpressionFactory.ApplyDefaultTypeMapping(expression);
// Path locations are usually made of strings. And they should be rendered without surrounding quotes.
if (pathLocation is SqlConstantExpression sqlConstantExpression &&
sqlConstantExpression.TypeMapping is MySqlStringTypeMapping stringTypeMapping &&
!stringTypeMapping.IsUnquoted)
{
pathLocation = sqlConstantExpression.ApplyTypeMapping(stringTypeMapping.Clone(true));
}
return pathLocation;
}
}
}
| 44.786458 | 172 | 0.619607 | [
"MIT"
] | Artrilogic/Pomelo.EntityFrameworkCore.MySql | src/EFCore.MySql.Json.Newtonsoft/Query/Internal/MySqlJsonNewtonsoftDomTranslator.cs | 8,601 | C# |
using System.IO;
using CP77.CR2W.Reflection;
using FastMember;
using static CP77.CR2W.Types.Enums;
namespace CP77.CR2W.Types
{
[REDMeta]
public class gamedataAIGoToCoverCond_Record : gamedataAIActionSubCondition_Record
{
public gamedataAIGoToCoverCond_Record(CR2WFile cr2w, CVariable parent, string name) : base(cr2w, parent, name) { }
}
}
| 24.133333 | 117 | 0.762431 | [
"MIT"
] | Eingin/CP77Tools | CP77.CR2W/Types/cp77/gamedataAIGoToCoverCond_Record.cs | 348 | C# |
using System;
using System.Collections.Generic;
using System.Text;
namespace Grains.Library.Enums
{
public enum Inclusions { Circular, Square }
}
| 16.888889 | 47 | 0.763158 | [
"MIT"
] | TMaj/MultiScaleGrainsGrowth | Grains.Library/Enums/Incusions.cs | 154 | C# |
using System;
using System.ComponentModel;
using Microsoft.Windows.Design;
namespace Xamarin.Forms.Xaml.Design
{
class AttributeTableBuilder : Microsoft.Windows.Design.Metadata.AttributeTableBuilder
{
public AttributeTableBuilder()
{
AddCustomAttributes(typeof(ArrayExtension).Assembly,
new XmlnsSupportsValidationAttribute("http://xamarin.com/schemas/2014/forms", false));
AddCallback(typeof(OnPlatformExtension), builder => builder.AddCustomAttributes(new Attribute[] {
new System.Windows.Markup.MarkupExtensionReturnTypeAttribute (),
}));
AddCallback(typeof(OnIdiomExtension), builder => builder.AddCustomAttributes(new Attribute[] {
new System.Windows.Markup.MarkupExtensionReturnTypeAttribute (),
}));
}
}
} | 34.136364 | 100 | 0.780293 | [
"MIT"
] | AlleSchonWeg/Xamarin.Forms | Xamarin.Forms.Xaml.Design/AttributeTableBuilder.cs | 753 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// このコードはツールによって生成されました。
// ランタイム バージョン:4.0.30319.42000
//
// このファイルへの変更は、正しくない動作の原因になったり、
// コードが再生成されるときに失われたりします。
// </auto-generated>
//------------------------------------------------------------------------------
namespace samplewpf.Properties
{
/// <summary>
/// ローカライズされた文字列などを検索するための、厳密に型指定されたリソース クラスです。
/// </summary>
// このクラスは StronglyTypedResourceBuilder クラスによって ResGen
// または Visual Studio のようなツールを使用して自動生成されました。
// メンバーを追加または削除するには、.ResX ファイルを編集して、/str オプションと共に
// ResGen を実行し直すか、または VS プロジェクトをリビルドします。
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class Resources
{
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Resources()
{
}
/// <summary>
/// このクラスで使用されるキャッシュされた ResourceManager インスタンスを返します。
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager
{
get
{
if ((resourceMan == null))
{
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("samplewpf.Properties.Resources", typeof(Resources).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// すべてについて、現在のスレッドの CurrentUICulture プロパティをオーバーライドします
/// 現在のスレッドの CurrentUICulture プロパティをオーバーライドします。
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture
{
get
{
return resourceCulture;
}
set
{
resourceCulture = value;
}
}
}
}
| 35.986111 | 175 | 0.60054 | [
"MIT"
] | densan-razuma/sample-wpf | Properties/Resources.Designer.cs | 3,213 | C# |
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
namespace HairSalon
{
public class Startup
{
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddEnvironmentVariables();
Configuration = builder.Build();
}
public IConfigurationRoot Configuration { get;}
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
}
public void Configure(IApplicationBuilder app)
{
app.UseStaticFiles();
app.UseDeveloperExceptionPage();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
app.Run(async (context) =>
{
await context.Response.WriteAsync("Sorry, this page isn't working quite right.");
});
}
}
public static class DBConfiguration
{
public static string ConnectionString = "server=localhost;user id=root;password=root;port=8889;database=dillon_titcomb;";
}
}
| 25.553191 | 125 | 0.694421 | [
"MIT"
] | dillontitcomb/hair-salon | HairSalon/Startup.cs | 1,201 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ShipMoveControl : MonoBehaviour
{
float rotationY;
bool left = true;
// Start is called before the first frame update
void Start()
{
rotationY = transform.rotation.y;
}
// Update is called once per frame
void Update()
{
//var directionVector = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));
float h = Input.GetAxis("Horizontal");//ad
float v = Input.GetAxis("Vertical");//ws
//向前不为零
if (v > 0 && h != 0)
{
rotationY += h * 0.3f;
}
if (v < 0 && h != 0)
{
rotationY -= h * 0.3f;
}
if (v != 0)
{
GetComponent<Rigidbody>().AddForce(transform.forward * v * 60);
transform.rotation = Quaternion.Slerp(transform.rotation, Quaternion.Euler(0, rotationY, 0), Time.deltaTime);
}
else
{
rotationY = transform.rotation.y;
}
}
}
| 25.44186 | 121 | 0.534735 | [
"MIT"
] | ChopperYY/UnityProject | Doria-V2.0/Assets/Script/sea1/ShipMoveControl.cs | 1,106 | 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.HDInsight.V20180601Preview.Outputs
{
/// <summary>
/// The HDInsight cluster application GET response.
/// </summary>
[OutputType]
public sealed class ApplicationPropertiesResponse
{
/// <summary>
/// The application state.
/// </summary>
public readonly string ApplicationState;
/// <summary>
/// The application type.
/// </summary>
public readonly string? ApplicationType;
/// <summary>
/// The list of roles in the cluster.
/// </summary>
public readonly Outputs.ComputeProfileResponse? ComputeProfile;
/// <summary>
/// The application create date time.
/// </summary>
public readonly string CreatedDate;
/// <summary>
/// The list of errors.
/// </summary>
public readonly ImmutableArray<Outputs.ErrorsResponse> Errors;
/// <summary>
/// The list of application HTTPS endpoints.
/// </summary>
public readonly ImmutableArray<Outputs.ApplicationGetHttpsEndpointResponse> HttpsEndpoints;
/// <summary>
/// The list of install script actions.
/// </summary>
public readonly ImmutableArray<Outputs.RuntimeScriptActionResponse> InstallScriptActions;
/// <summary>
/// The marketplace identifier.
/// </summary>
public readonly string MarketplaceIdentifier;
/// <summary>
/// The provisioning state of the application.
/// </summary>
public readonly string ProvisioningState;
/// <summary>
/// The list of application SSH endpoints.
/// </summary>
public readonly ImmutableArray<Outputs.ApplicationGetEndpointResponse> SshEndpoints;
/// <summary>
/// The list of uninstall script actions.
/// </summary>
public readonly ImmutableArray<Outputs.RuntimeScriptActionResponse> UninstallScriptActions;
[OutputConstructor]
private ApplicationPropertiesResponse(
string applicationState,
string? applicationType,
Outputs.ComputeProfileResponse? computeProfile,
string createdDate,
ImmutableArray<Outputs.ErrorsResponse> errors,
ImmutableArray<Outputs.ApplicationGetHttpsEndpointResponse> httpsEndpoints,
ImmutableArray<Outputs.RuntimeScriptActionResponse> installScriptActions,
string marketplaceIdentifier,
string provisioningState,
ImmutableArray<Outputs.ApplicationGetEndpointResponse> sshEndpoints,
ImmutableArray<Outputs.RuntimeScriptActionResponse> uninstallScriptActions)
{
ApplicationState = applicationState;
ApplicationType = applicationType;
ComputeProfile = computeProfile;
CreatedDate = createdDate;
Errors = errors;
HttpsEndpoints = httpsEndpoints;
InstallScriptActions = installScriptActions;
MarketplaceIdentifier = marketplaceIdentifier;
ProvisioningState = provisioningState;
SshEndpoints = sshEndpoints;
UninstallScriptActions = uninstallScriptActions;
}
}
}
| 35.156863 | 99 | 0.645008 | [
"Apache-2.0"
] | polivbr/pulumi-azure-native | sdk/dotnet/HDInsight/V20180601Preview/Outputs/ApplicationPropertiesResponse.cs | 3,586 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using Microsoft.Bot.Builder.Dialogs.Declarative.Resources;
namespace Microsoft.Bot.Builder.Runtime.Tests.Resources
{
public abstract class MemoryResource : Resource
{
protected MemoryResource(string id)
{
if (string.IsNullOrEmpty(id))
{
throw new ArgumentNullException(nameof(id));
}
this.FullName = id;
this.Id = id;
}
}
}
| 23.913043 | 61 | 0.614545 | [
"MIT"
] | Alpharceus/botbuilder-dotnet | tests/Microsoft.Bot.Builder.Dialogs.Adaptive.Runtime.Tests/Resources/MemoryResource.cs | 552 | C# |
using System;
using System.Collections.Concurrent;
using System.Threading;
using JetBrains.Annotations;
using JetBrains.Collections.Viewable;
using JetBrains.Diagnostics;
using JetBrains.Lifetimes;
using JetBrains.Rd.Base;
using JetBrains.Rd.Util;
using JetBrains.Serialization;
using JetBrains.Util.Util;
namespace JetBrains.Rd.Impl
{
public class InternRoot<TBase> : IInternRoot<TBase>
{
private readonly ConcurrentDictionary<InternId, TBase> myDirectMap =
new ConcurrentDictionary<InternId, TBase>();
private readonly ConcurrentDictionary<TBase, IdPair> myInverseMap = new ConcurrentDictionary<TBase, IdPair>();
private int myInternedIdCounter;
private readonly CtxReadDelegate<TBase> myReadDelegate;
private readonly CtxWriteDelegate<TBase> myWriteDelegate;
public InternId TryGetInterned(TBase value)
{
var hasValue = myInverseMap.TryGetValue(value, out var pair);
if (hasValue)
return pair.Id;
return InternId.Invalid;
}
public InternId Intern(TBase value)
{
IdPair pair;
if (myInverseMap.TryGetValue(value, out pair))
return pair.Id;
pair.Id = pair.ExtraId = InternId.Invalid;
if (myInverseMap.TryAdd(value, pair))
{
InternId allocatedId = new InternId(Interlocked.Increment(ref myInternedIdCounter) * 2);
Assertion.Assert(allocatedId.IsLocal, "Newly allocated ID must be local");
RdReactiveBase.SendTrace?.Log($"InternRoot `{Location}` ({RdId}):: {allocatedId} = {value}");
myDirectMap[allocatedId] = value;
using(Proto.Contexts.CreateSendWithoutContextsCookie())
Proto.Wire.Send(RdId, writer =>
{
myWriteDelegate(SerializationContext, writer, value);
InternId.Write(writer, allocatedId);
});
while (true)
{
var oldPair = myInverseMap[value];
var modifiedPair = oldPair;
modifiedPair.Id = allocatedId;
if (myInverseMap.TryUpdate(value, modifiedPair, oldPair)) break;
}
}
return myInverseMap[value].Id;
}
private object TryGetValue(InternId id)
{
myDirectMap.TryGetValue(id, out var value);
return value;
}
public bool TryUnIntern<T>(InternId id, out T result) where T : TBase
{
var value = TryGetValue(id);
if (value != null)
{
result = (T) value;
return true;
}
result = default;
return false;
}
public void Remove(TBase value)
{
if (myInverseMap.TryRemove(value, out var pair))
{
myDirectMap.TryRemove(pair.Id, out _);
myDirectMap.TryRemove(pair.ExtraId, out _);
}
}
public T UnIntern<T>(InternId id) where T : TBase
{
return (T) TryGetValue(id);
}
[CanBeNull] private IRdDynamic myParent;
public InternRoot([CanBeNull] CtxReadDelegate<TBase> readDelegate = null, [CanBeNull] CtxWriteDelegate<TBase> writeDelegate = null)
{
myReadDelegate = readDelegate ?? Polymorphic<TBase>.Read;
myWriteDelegate = writeDelegate ?? Polymorphic<TBase>.Write;
}
public IProtocol Proto => myParent.NotNull(this).Proto;
public SerializationCtx SerializationContext => myParent.NotNull(this).SerializationContext;
public RName Location { get; private set; } = new RName("<<not bound>>");
public void Print(PrettyPrinter printer)
{
printer.Print(ToString());
printer.Print("(");
printer.Print(RdId.ToString());
printer.Print(")");
}
public override string ToString()
{
return GetType().ToString(false, true) + ": `" + Location + "`";
}
public RdId RdId { get; set; }
public void Bind(Lifetime lf, IRdDynamic parent, string name)
{
if (myParent != null)
{
Assertion.Fail($"Trying to bound already bound {this} to {parent.Location}");
}
//todo uncomment when fix InterningTest
//Assertion.Require(RdId != RdId.Nil, "Must be identified first");
lf.Bracket(() =>
{
myParent = parent;
Location = parent.Location.Sub(name);
},
() =>
{
Location = Location.Sub("<<unbound>>", "::");
myParent = null;
RdId = RdId.Nil;
}
);
myDirectMap.Clear();
myInverseMap.Clear();
Proto.Wire.Advise(lf, this);
}
public void Identify(IIdentities identities, RdId id)
{
Assertion.Require(RdId.IsNil, "Already has RdId: {0}, entity: {1}", RdId, this);
Assertion.Require(!id.IsNil, "Assigned RdId mustn't be null, entity: {0}", this);
RdId = id;
}
public bool Async
{
get => true;
set => throw new NotSupportedException("Intern Roots are always async");
}
public IScheduler WireScheduler => InternRootScheduler.Instance;
public void OnWireReceived(UnsafeReader reader)
{
var value = myReadDelegate(SerializationContext, reader);
var id = InternId.Read(reader);
Assertion.Require(!id.IsLocal, "Other side sent us id of our own side?");
Assertion.Require(id.IsValid, "Other side sent us invalid id?");
RdReactiveBase.ReceiveTrace?.Log($"InternRoot `{Location}` ({RdId}):: {id} = {value}");
myDirectMap[id] = value;
var pair = new IdPair() { Id = id, ExtraId = InternId.Invalid };
if (!myInverseMap.TryAdd(value, pair))
{
while (true)
{
var oldPair = myInverseMap[value];
Assertion.Assert(!oldPair.ExtraId.IsValid, "Remote send duplicated IDs for value {0}", value);
var modifiedPair = oldPair;
modifiedPair.ExtraId = id;
if (myInverseMap.TryUpdate(value, modifiedPair, oldPair)) break;
}
}
}
private struct IdPair : IEquatable<IdPair>
{
public InternId Id;
public InternId ExtraId;
public bool Equals(IdPair other)
{
return Id.Equals(other.Id) && ExtraId.Equals(other.ExtraId);
}
public override bool Equals(object obj)
{
return obj is IdPair other && Equals(other);
}
public override int GetHashCode()
{
unchecked
{
return (Id.GetHashCode() * 397) ^ ExtraId.GetHashCode();
}
}
public static bool operator ==(IdPair left, IdPair right)
{
return left.Equals(right);
}
public static bool operator !=(IdPair left, IdPair right)
{
return !left.Equals(right);
}
}
}
class InternRootScheduler : IScheduler
{
internal static readonly InternRootScheduler Instance = new InternRootScheduler();
private int myActive = 0;
public void Queue(Action action)
{
Interlocked.Increment(ref myActive);
try
{
action();
}
finally
{
Interlocked.Decrement(ref myActive);
}
}
public bool IsActive => myActive > 0;
public bool OutOfOrderExecution => true;
}
} | 28.171315 | 135 | 0.619573 | [
"Apache-2.0"
] | DecoyRS/rd | rd-net/RdFramework/Impl/InternRoot.cs | 7,073 | C# |
using Microsoft.Azure.Search.Models;
using Sitecore.ContentSearch;
using Sitecore.ContentSearch.Azure;
using Sitecore.Diagnostics;
using Sitecore.HabitatHome.Foundation.Search.Services;
namespace Sitecore.HabitatHome.Foundation.Search
{
// See Sitecore.ContentSearch.SolrProvider.SolrNetIntegration.SolrNetProxy
public static class AzureNetProxy
{
public static DocumentSuggestResult<Document> Suggest(this IProviderSearchContext context, AzureSuggestQuery q, string suggeterName, SuggestParameters options)
{
ICloudSearchIndex index = context.Index as CloudSearchProviderSuggestionIndex;
Assert.IsNotNull(index, "index");
return ((CompositeSearchService)index.SearchService).Suggest(q, suggeterName, options);
}
public static AutocompleteResult AutoComplete(this IProviderSearchContext context, AzureSuggestQuery q, string suggeterName, AutocompleteParameters options)
{
ICloudSearchIndex index = context.Index as CloudSearchProviderSuggestionIndex;
Assert.IsNotNull(index, "index");
return ((CompositeSearchService)index.SearchService).Autocomplete(q, suggeterName, options);
}
}
} | 48.84 | 167 | 0.755119 | [
"MIT"
] | moo2u2/Sitecore-Azure-Search-Suggestions | src/Foundation/Search/code/Http/AzureNetProxy.cs | 1,223 | C# |
using System;
using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Diagnosers;
using BenchmarkDotNet.Running;
namespace BenchApp
{
[WarmupCount(1)]
[IterationCount(5)]
//[EventPipeProfiler(EventPipeProfile.GcVerbose)]
[MemoryDiagnoser]
public class Program
{
private static void Main(string[] args)
{
BenchmarkRunner.Run<Program>();
}
[Params(500, 1000, 2000, 4000, 8000, 16000)]
public int IterCount { get; set; }
[Params(5000, 10000, 20000, 40000, 80000, 160000)]
public int MessageNum { get; set; }
[Benchmark]
public void RunWithObjects()
{
var domain = new Domain();
for (int i = 0; i < IterCount; i++)
{
RunWithObjectsInternal(domain);
}
GC.Collect();
GC.WaitForPendingFinalizers();
}
private void RunWithObjectsInternal(Domain domain)
{
// init
object[] objBuffer = new object[Domain.ObjectNumber * MessageNum];
int objBufferCurrentIndex = 0;
domain.Reset();
while (objBufferCurrentIndex != objBuffer.Length)
{
domain.Increment();
domain.WriteMessageToObjectBuffer(
objBuffer.AsSpan(objBufferCurrentIndex, Domain.ObjectNumber));
objBufferCurrentIndex += Domain.ObjectNumber;
}
}
[Benchmark]
public void RunWithBytes()
{
var domain = new Domain();
for (int i = 0; i < IterCount; i++)
{
RunWithBytesInternal(domain);
}
GC.Collect();
GC.WaitForPendingFinalizers();
}
private void RunWithBytesInternal(Domain domain)
{
// init
Span<byte> byteBuffer = new byte[Domain.MessageSize * MessageNum];
var byteBufferCurrentIndex = 0;
domain.Reset();
while (byteBufferCurrentIndex != byteBuffer.Length)
{
domain.Increment();
domain.WriteMessageToByteBuffer(
byteBuffer.Slice(byteBufferCurrentIndex, Domain.MessageSize));
byteBufferCurrentIndex += Domain.MessageSize;
}
}
}
internal sealed class Domain
{
public const int MessageSize = 8 + 8 + 8;
public const int ObjectNumber = 3;
private readonly Field<long> LongField = new Field<long>(0L);
private readonly Field<DateTimeOffset> DateTimeOffsetField = new Field<DateTimeOffset>(new DateTimeOffset());
private readonly Field<double> DoubleField = new Field<double>(0.0d);
public void Increment()
{
LongField.Value++;
DateTimeOffsetField.Value = DateTimeOffsetField.Value.AddTicks(1);
DoubleField.Value += 0.001;
}
public void Reset()
{
LongField.Value = 0L;
DateTimeOffsetField.Value = new DateTimeOffset();
DoubleField.Value = 0.0d;
}
public void WriteMessageToObjectBuffer(Span<object> objBuffer)
{
objBuffer[0] = LongField.Value;
objBuffer[1] = DateTimeOffsetField.Value.Ticks;
objBuffer[2] = DoubleField.Value;
}
public void WriteMessageToByteBuffer(Span<byte> byteBuffer)
{
BitConverter.TryWriteBytes(byteBuffer, LongField.Value);
BitConverter.TryWriteBytes(byteBuffer, DateTimeOffsetField.Value.Ticks);
BitConverter.TryWriteBytes(byteBuffer, DoubleField.Value);
}
}
internal sealed class Field<T>
{
public Field(T value)
{
Value = value;
}
public T Value { get; set; }
}
}
| 27.602837 | 117 | 0.562436 | [
"MIT"
] | astef/benchmark-dotnet-boxing | BenchApp/Program.cs | 3,894 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Common.Log;
using Lykke.Common.Log;
using Lykke.Job.ChainalysisHistoryExporter.AddressNormalization;
using Lykke.Job.ChainalysisHistoryExporter.Common;
using Lykke.Job.ChainalysisHistoryExporter.Reporting;
using Polly;
namespace Lykke.Job.ChainalysisHistoryExporter.Deposits
{
public class DepositsExporter : IDisposable
{
private readonly ILog _log;
private readonly AddressNormalizer _addressNormalizer;
private readonly IReadOnlyCollection<IDepositWalletsProvider> _depositWalletsProviders;
private readonly IReadOnlyCollection<IDepositsHistoryProvider> _depositsHistoryProviders;
private readonly SemaphoreSlim _concurrencySemaphore;
private int _processedWalletsCount;
private int _exportedDepositsCount;
private int _totalDepositWalletsCount;
public DepositsExporter(
ILogFactory logFactory,
AddressNormalizer addressNormalizer,
IReadOnlyCollection<IDepositWalletsProvider> depositWalletsProviders,
IReadOnlyCollection<IDepositsHistoryProvider> depositsHistoryProviders)
{
_log = logFactory.CreateLog(this);
_addressNormalizer = addressNormalizer;
_depositWalletsProviders = depositWalletsProviders;
_depositsHistoryProviders = depositsHistoryProviders;
_concurrencySemaphore = new SemaphoreSlim(8);
}
public async Task ExportAsync(TransactionsReportBuilder reportBuilder)
{
var depositWallets = await LoadDepositWalletsAsync();
_totalDepositWalletsCount = depositWallets.Count;
var tasks = new List<Task>(512);
_log.Info("Exporting deposits...", new
{
DepositsHistoryProvider = _depositsHistoryProviders.Select(x => x.GetType().Name)
});
foreach (var wallet in depositWallets)
{
await _concurrencySemaphore.WaitAsync();
tasks.Add(ProcessDepositWalletAsync(reportBuilder, wallet));
if (tasks.Count >= 500)
{
await Task.WhenAll(tasks);
tasks.Clear();
}
}
await Task.WhenAll(tasks);
_log.Info($"Deposits exporting done. {_processedWalletsCount} deposit wallets processed. {_exportedDepositsCount} deposits exported");
}
public void Dispose()
{
_concurrencySemaphore?.Dispose();
}
private async Task<ISet<DepositWallet>> LoadDepositWalletsAsync()
{
_log.Info("Loading deposit wallets...", new
{
DepositWalletsProviders = _depositWalletsProviders.Select(x => x.GetType().Name)
});
var allWallets = new HashSet<DepositWallet>(131072); // 2 ^ 17
var loadedDepositWalletsCount = 0;
async Task<IReadOnlyCollection<DepositWallet>> LoadProviderWalletsAsync(IDepositWalletsProvider provider)
{
PaginatedList<DepositWallet> wallets = null;
var allWalletsOfProvider = new List<DepositWallet>(65536);
do
{
wallets = await Policy
.Handle<Exception>(ex =>
{
_log.Warning($"Failed to get deposits wallets using {provider.GetType().Name}. Operation will be retried.",
ex);
return true;
})
.WaitAndRetryForeverAsync(i => TimeSpan.FromSeconds(Math.Min(i, 5)))
// ReSharper disable once AccessToModifiedClosure
.ExecuteAsync(async () => await provider.GetWalletsAsync(wallets?.Continuation));
foreach (var wallet in wallets.Items)
{
var normalizedWallet = NormalizeWalletOrDefault(wallet);
if (normalizedWallet == null)
{
continue;
}
allWalletsOfProvider.Add(normalizedWallet);
var currentLoadedDepositWalletsCount = Interlocked.Increment(ref loadedDepositWalletsCount);
if (currentLoadedDepositWalletsCount % 1000 == 0)
{
_log.Info($"{currentLoadedDepositWalletsCount} deposit wallets loaded so far");
}
}
} while (wallets.Continuation != null);
return allWalletsOfProvider;
}
var tasks = new List<Task<IReadOnlyCollection<DepositWallet>>>();
foreach (var provider in _depositWalletsProviders)
{
tasks.Add(LoadProviderWalletsAsync(provider));
}
await Task.WhenAll(tasks);
foreach (var task in tasks)
{
foreach (var wallet in task.Result)
{
allWallets.Add(wallet);
}
}
_log.Info($"Deposit wallets loading done. {allWallets.Count} unique deposit wallets loaded");
return allWallets;
}
private DepositWallet NormalizeWalletOrDefault(DepositWallet wallet)
{
if (string.IsNullOrWhiteSpace(wallet.Address) ||
string.IsNullOrWhiteSpace(wallet.CryptoCurrency) ||
wallet.UserId == Guid.Empty)
{
return null;
}
var address = _addressNormalizer.NormalizeOrDefault(wallet.Address, wallet.CryptoCurrency);
if (address == null)
{
_log.Warning
(
"It is not a valid address, skipping",
context: new
{
Address = wallet.Address,
CryptoCurrency = wallet.CryptoCurrency
}
);
return null;
}
return new DepositWallet(wallet.UserId, address, wallet.CryptoCurrency);
}
private async Task ProcessDepositWalletAsync(TransactionsReportBuilder reportBuilder, DepositWallet wallet)
{
try
{
foreach (var historyProvider in _depositsHistoryProviders)
{
if (!historyProvider.CanProvideHistoryFor(wallet))
{
continue;
}
PaginatedList<Transaction> transactions = null;
var processedWalletTransactionsCount = 0;
do
{
transactions = await Policy
.Handle<Exception>(ex =>
{
_log.Warning
(
"Failed to get deposits history. Operation will be retried.",
context: new
{
Address = wallet.Address,
CryptoCurrency = wallet.CryptoCurrency,
HistoryProvider = historyProvider.GetType().Name
},
exception: ex
);
return true;
})
.WaitAndRetryForeverAsync(i => TimeSpan.FromSeconds(Math.Min(i, 5)))
.ExecuteAsync(async () => await historyProvider.GetHistoryAsync(wallet, transactions?.Continuation));
foreach (var tx in transactions.Items)
{
var normalizedTransaction = NormalizeTransactionOrDefault(tx);
if (normalizedTransaction == null)
{
continue;
}
reportBuilder.AddTransaction(normalizedTransaction);
Interlocked.Increment(ref _exportedDepositsCount);
++processedWalletTransactionsCount;
if (processedWalletTransactionsCount % 100 == 0)
{
_log.Info($"{processedWalletTransactionsCount} deposits processed so far of {wallet.CryptoCurrency}:{wallet.Address} wallet using {historyProvider.GetType().Name}");
}
}
} while (transactions.Continuation != null);
}
}
catch (Exception ex)
{
throw new InvalidOperationException($"Failed to process deposit wallet: {wallet.CryptoCurrency}:{wallet.Address}:{wallet.UserId}", ex);
}
finally
{
var processedWalletsCount = Interlocked.Increment(ref _processedWalletsCount);
if (processedWalletsCount % 100 == 0)
{
var completedPercent = processedWalletsCount * 100 / _totalDepositWalletsCount;
_log.Info($"{processedWalletsCount} wallets processed so far ({completedPercent}%). {_exportedDepositsCount} deposits exported so far.");
}
_concurrencySemaphore.Release();
}
}
private Transaction NormalizeTransactionOrDefault(Transaction tx)
{
if (string.IsNullOrWhiteSpace(tx.Hash) ||
string.IsNullOrWhiteSpace(tx.CryptoCurrency) ||
tx.UserId == Guid.Empty)
{
return null;
}
var outputAddress = _addressNormalizer.NormalizeOrDefault(tx.OutputAddress, tx.CryptoCurrency, isTransactionNormalization: true);
if (outputAddress == null)
{
_log.Warning
(
"It is not a valid address, skipping",
context: new
{
Address = tx.OutputAddress,
CryptoCurrency = tx.CryptoCurrency
}
);
return null;
}
return new Transaction(tx.CryptoCurrency, tx.Hash, tx.UserId, outputAddress, tx.Type);
}
}
}
| 38.725 | 197 | 0.519229 | [
"MIT"
] | LykkeCity/Lykke.Job.ChainalysisHistoryExporter | src/Lykke.Job.ChainalysisHistoryExporter/Deposits/DepositsExporter.cs | 10,845 | C# |
using System;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using Microsoft.Msagl.Drawing;
using Microsoft.Msagl.Core.Geometry.Curves;
using Microsoft.Msagl.Core.DataStructures;
using MsaglRectangle = Microsoft.Msagl.Core.Geometry.Rectangle;
using Color = System.Windows.Media.Color;
using DrawingGraph = Microsoft.Msagl.Drawing.Graph;
using GeometryEdge = Microsoft.Msagl.Core.Layout.Edge;
using GeometryNode = Microsoft.Msagl.Core.Layout.Node;
using DrawingEdge = Microsoft.Msagl.Drawing.Edge;
using DrawingNode = Microsoft.Msagl.Drawing.Node;
using MsaglPoint = Microsoft.Msagl.Core.Geometry.Point;
using WinPoint = System.Windows.Point;
using MsaglStyle = Microsoft.Msagl.Drawing.Style;
using MsaglLineSegment = Microsoft.Msagl.Core.Geometry.Curves.LineSegment;
using WinLineSegment = System.Windows.Media.LineSegment;
using WinSize = System.Windows.Size;
namespace Microsoft.Msagl.GraphControlSilverlight
{
/// <summary>
/// exposes some drawing functionality
/// </summary>
public sealed class Draw
{
/// <summary>
/// private constructor
/// </summary>
Draw()
{
}
static double doubleCircleOffsetRatio = 0.9;
internal static double DoubleCircleOffsetRatio
{
get { return doubleCircleOffsetRatio; }
}
internal static float dashSize = 0.05f; //inches
/// <summary>
/// A color converter
/// </summary>
/// <param name="gleeColor"></param>
/// <returns></returns>
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Msagl")]
public static Color MsaglColorToDrawingColor(Drawing.Color gleeColor)
{
return Color.FromArgb(gleeColor.A, gleeColor.R, gleeColor.G, gleeColor.B);
}
internal static void DrawUnderlyingPolyline(PathGeometry pg, DEdge edge)
{
IEnumerable<WinPoint> points = edge.GeometryEdge.UnderlyingPolyline.Select(p => WinPoint(p));
PathFigure pf = new PathFigure() { IsFilled = false, IsClosed = false, StartPoint = points.First() };
foreach (WinPoint p in points)
{
if (p != points.First())
pf.Segments.Add(new WinLineSegment() { Point = p });
PathFigure circle = new PathFigure() { IsFilled = false, IsClosed = true, StartPoint = new WinPoint(p.X - edge.RadiusOfPolylineCorner, p.Y) };
circle.Segments.Add(
new ArcSegment()
{
Size = new WinSize(edge.RadiusOfPolylineCorner, edge.RadiusOfPolylineCorner),
SweepDirection = SweepDirection.Clockwise,
Point = new WinPoint(p.X + edge.RadiusOfPolylineCorner, p.Y)
});
circle.Segments.Add(
new ArcSegment()
{
Size = new WinSize(edge.RadiusOfPolylineCorner, edge.RadiusOfPolylineCorner),
SweepDirection = SweepDirection.Clockwise,
Point = new WinPoint(p.X - edge.RadiusOfPolylineCorner, p.Y)
});
pg.Figures.Add(circle);
}
pg.Figures.Add(pf);
}
internal static void DrawEdgeArrows(PathGeometry pg, DrawingEdge edge, bool fillAtSource, bool fillAtTarget)
{
ArrowAtTheEnd(pg, edge, fillAtTarget);
ArrowAtTheBeginning(pg, edge, fillAtSource);
}
private static void ArrowAtTheBeginning(PathGeometry pg, DrawingEdge edge, bool fill)
{
if (edge.GeometryEdge != null && edge.Attr.ArrowAtSource)
DrawArrowAtTheBeginningWithControlPoints(pg, edge, fill);
}
private static void DrawArrowAtTheBeginningWithControlPoints(PathGeometry pg, DrawingEdge edge, bool fill)
{
if (edge.EdgeCurve != null)
if (edge.Attr.ArrowheadAtSource == ArrowStyle.None)
DrawLine(pg, edge.EdgeCurve.Start, edge.ArrowAtSourcePosition);
else
DrawArrow(pg, edge.EdgeCurve.Start, edge.ArrowAtSourcePosition, edge.Attr.LineWidth, edge.Attr.ArrowheadAtSource, fill);
}
private static void ArrowAtTheEnd(PathGeometry pg, DrawingEdge edge, bool fill)
{
if (edge.GeometryEdge != null && edge.Attr.ArrowAtTarget)
DrawArrowAtTheEndWithControlPoints(pg, edge, fill);
}
const float toDegrees = 180 / (float)Math.PI;
static void DrawArrowAtTheEndWithControlPoints(PathGeometry pg, DrawingEdge edge, bool fill)
{
if (edge.EdgeCurve != null)
if (edge.Attr.ArrowheadAtTarget == ArrowStyle.None)
DrawLine(pg, edge.EdgeCurve.End,
edge.ArrowAtTargetPosition);
else
DrawArrow(pg, edge.EdgeCurve.End,
edge.ArrowAtTargetPosition, edge.Attr.LineWidth, edge.Attr.ArrowheadAtTarget, fill);
}
internal static WinPoint WinPoint(MsaglPoint p)
{
return new WinPoint(p.X, p.Y);
}
internal static void CreateGraphicsPathFromCurve(PathFigure pathFigure, Curve curve)
{
foreach (ICurve seg in curve.Segments)
{
if (seg is CubicBezierSegment)
{
var bezSeg = seg as CubicBezierSegment;
pathFigure.Segments.Add(new BezierSegment
{
Point1 = WinPoint(bezSeg.B(1)),
Point2 = WinPoint(bezSeg.B(2)),
Point3 = WinPoint(bezSeg.B(3))
});
}
else if (seg is Ellipse)
{
var ellipse = seg as Ellipse;
pathFigure.Segments.Add(new ArcSegment()
{
Size = new WinSize(ellipse.AxisA.Length, ellipse.AxisB.Length),
SweepDirection = ellipse.OrientedCounterclockwise() ? SweepDirection.Clockwise : SweepDirection.Counterclockwise,
Point = WinPoint(ellipse.End)
});
}
else
pathFigure.Segments.Add(new WinLineSegment() { Point = WinPoint(seg.End) });
}
}
internal static PathFigure CreateGraphicsPath(ICurve iCurve)
{
var pathFigure = new PathFigure { StartPoint = WinPoint(iCurve.Start), IsFilled = false, IsClosed = false };
if (iCurve is Curve)
{
CreateGraphicsPathFromCurve(pathFigure, iCurve as Curve);
}
else if (iCurve is Polyline)
{
var polyline = iCurve as Polyline;
pathFigure.IsClosed = polyline.Closed;
foreach (var p in polyline.PolylinePoints)
{
pathFigure.Segments.Add(new WinLineSegment() { Point = WinPoint(p.Point) });
}
}
else if (iCurve is CubicBezierSegment)
{
var bezSeg = iCurve as CubicBezierSegment;
pathFigure.Segments.Add(new BezierSegment
{
Point1 = WinPoint(bezSeg.B(1)),
Point2 = WinPoint(bezSeg.B(2)),
Point3 = WinPoint(bezSeg.B(3))
});
}
else if (iCurve is MsaglLineSegment)
{
var segment = iCurve as MsaglLineSegment;
pathFigure.Segments.Add(
new WinLineSegment()
{
Point = WinPoint(segment.End)
});
}
else if (iCurve is Ellipse)
{
var ellipse = iCurve as Ellipse;
pathFigure.Segments.Add(
new ArcSegment()
{
Size = new WinSize(ellipse.BoundingBox.Width / 2, ellipse.BoundingBox.Height / 2),
SweepDirection = SweepDirection.Clockwise,
Point = WinPoint(ellipse[Math.PI])
});
pathFigure.Segments.Add(
new ArcSegment()
{
Size = new WinSize(ellipse.BoundingBox.Width / 2, ellipse.BoundingBox.Height / 2),
SweepDirection = SweepDirection.Clockwise,
Point = WinPoint(ellipse.Start)
});
}
else if (iCurve is RoundedRect)
{
CreateGraphicsPathFromCurve(pathFigure, (iCurve as RoundedRect).Curve);
}
return pathFigure;
}
const double arrowAngle = 25.0; //degrees
internal static void DrawArrow(PathGeometry pg, MsaglPoint start, MsaglPoint end, double thickness, ArrowStyle arrowStyle, bool fill)
{
switch (arrowStyle)
{
case ArrowStyle.NonSpecified:
case ArrowStyle.Normal:
DrawNormalArrow(pg, start, end, thickness, fill);
break;
case ArrowStyle.Tee:
DrawTeeArrow(pg, start, end, fill);
break;
case ArrowStyle.Diamond:
DrawDiamondArrow(pg, start, end);
break;
case ArrowStyle.ODiamond:
throw new NotImplementedException();
case ArrowStyle.Generalization:
throw new NotImplementedException();
default:
throw new InvalidOperationException();
}
}
internal static void DrawNormalArrow(PathGeometry pg, MsaglPoint start, MsaglPoint end, double thickness, bool fill)
{
MsaglPoint dir = end - start;
MsaglPoint h = dir;
dir /= dir.Length;
// compensate for line thickness
end -= dir * thickness / ((double)Math.Tan(arrowAngle * (Math.PI / 180.0)));
var s = new MsaglPoint(-dir.Y, dir.X);
s *= h.Length * ((double)Math.Tan(arrowAngle * 0.5 * (Math.PI / 180.0)));
PathFigure pf = new PathFigure() { IsFilled = fill, IsClosed = true };
pf.StartPoint = WinPoint(start + s);
pf.Segments.Add(new WinLineSegment() { Point = WinPoint(end) });
pf.Segments.Add(new WinLineSegment() { Point = WinPoint(start - s) });
pg.Figures.Add(pf);
}
// For tee arrows, "fill" indicates whether the line should continue up to the node's boundary.
static void DrawTeeArrow(PathGeometry pg, MsaglPoint start, MsaglPoint end, bool fill)
{
MsaglPoint dir = end - start;
MsaglPoint h = dir;
dir /= dir.Length;
if (fill)
{
PathFigure pf = new PathFigure();
pf.StartPoint = WinPoint(start);
pf.Segments.Add(new WinLineSegment() { Point = WinPoint(end) });
pg.Figures.Add(pf);
}
var s = new MsaglPoint(-dir.Y, dir.X);
s *= 2 * h.Length * ((float)Math.Tan(arrowAngle * 0.5f * (Math.PI / 180.0)));
s += s.Normalize();
PathFigure pf2 = new PathFigure();
pf2.StartPoint = WinPoint(start + s);
pf2.Segments.Add(new WinLineSegment() { Point = WinPoint(start - s) });
pg.Figures.Add(pf2);
}
internal static void DrawDiamondArrow(PathGeometry pg, MsaglPoint start, MsaglPoint end)
{
MsaglPoint dir = end - start;
MsaglPoint h = dir;
dir /= dir.Length;
var s = new MsaglPoint(-dir.Y, dir.X);
PathFigure pf = new PathFigure();
pf.StartPoint = WinPoint(start - dir);
pf.Segments.Add(new WinLineSegment() { Point = WinPoint(start + (h / 2) + s * (h.Length / 3)) });
pf.Segments.Add(new WinLineSegment() { Point = WinPoint(end) });
pf.Segments.Add(new WinLineSegment() { Point = WinPoint(start + (h / 2) - s * (h.Length / 3)) });
pf.IsClosed = true;
pg.Figures.Add(pf);
}
internal static void DrawLine(PathGeometry pg, MsaglPoint start, MsaglPoint end)
{
PathFigure pf = new PathFigure() { StartPoint = WinPoint(start) };
pf.Segments.Add(new WinLineSegment() { Point = WinPoint(end) });
pg.Figures.Add(pf);
}
}
} | 40.45625 | 158 | 0.550672 | [
"MIT"
] | 0xbeecaffe/MSAGL | GraphLayout/GraphControlSilverlight/GraphControlSilverlight/Draw.cs | 12,946 | C# |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Diagnostics.ContractsLight;
using System.Diagnostics.Tracing;
using System.IO;
using System.Linq;
using System.Text;
using BuildXL.Scheduler;
using BuildXL.Tracing;
using BuildXL.Tracing.CloudBuild;
using BuildXL.Utilities;
using BuildXL.Utilities.Configuration;
using BuildXL.Utilities.Instrumentation.Common;
using BuildXL.Utilities.Tracing;
using static BuildXL.Scheduler.ExecutionSampler;
#pragma warning disable 1591
namespace BuildXL.App.Tracing
{
/// <summary>
/// Logging for bxl.exe.
/// </summary>
[EventKeywordsType(typeof(Keywords))]
[EventTasksType(typeof(Tasks))]
public abstract partial class Logger
{
/// <summary>
/// Returns the logger instance
/// </summary>
public static Logger Log => m_log;
[SuppressMessage("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
private const string AppInvocationMessage = "{ShortProductName} Startup Command Line Arguments: '{commandLine}' \r\n{ShortProductName} version:{buildInfo.CommitId}, Build: {buildInfo.Build}, Session ID:{sessionIdentifier}, Related Session:{relatedSessionIdentifier}, MachineInfo: CPU count: {machineInfo.ProcessorCount}, Physical Memory: {machineInfo.InstalledMemoryMB}MB, Current Drive seek penalty: {machineInfo.CurrentDriveHasSeekPenalty}, OS: {machineInfo.OsVersion}, .NETFramework: {machineInfo.DotNetFrameworkVersion}, Processor:{machineInfo.ProcessorIdentifier} - {machineInfo.ProcessorName}, CLR Version: {machineInfo.EnvironmentVersion}, Starup directory: {startupDirectory}, Main configuration file: {mainConfig}";
/// <summary>
/// CAUTION!!
///
/// WDG has Asimov telemetry listening to this event. Any change to an existing field will require a breaking change announcement
///
/// This event is only used for ETW and telemetry. The commandLine must be scrubbed so it doesn't overflow
/// </summary>
[GeneratedEvent(
(ushort)EventId.DominoInvocation,
EventGenerators = EventGenerators.LocalAndTelemetry,
EventLevel = Level.Verbose,
EventOpcode = (byte)EventOpcode.Start,
// Prevent this from going to the log. It is only for ETW and telemetry. DominoInvocationForLocalLog is for the log.
Keywords = (int)Keywords.SelectivelyEnabled,
Message = AppInvocationMessage)]
public abstract void DominoInvocation(LoggingContext context, string commandLine, BuildInfo buildInfo, MachineInfo machineInfo, string sessionIdentifier, string relatedSessionIdentifier, string startupDirectory, string mainConfig);
/// <summary>
/// This is the event that populates the local log file. It differs from DominoInvocation in that it contains the raw commandline without any truncation
/// </summary>
[GeneratedEvent(
(ushort)EventId.DominoInvocationForLocalLog,
EventGenerators = EventGenerators.LocalOnly,
EventLevel = Level.Verbose,
EventOpcode = (byte)EventOpcode.Start,
Message = AppInvocationMessage)]
public abstract void DominoInvocationForLocalLog(LoggingContext context, string commandLine, BuildInfo buildInfo, MachineInfo machineInfo, string sessionIdentifier, string relatedSessionIdentifier, string startupDirectory, string mainConfig);
[GeneratedEvent(
(ushort)EventId.StartupTimestamp,
EventGenerators = EventGenerators.LocalOnly,
EventLevel = Level.Verbose,
Message = "{ShortProductName} Startup began at: '{0}' UTC time, '{1}' Local time")]
public abstract void StartupTimestamp(LoggingContext context, string timestamp, string localTimestamp);
[GeneratedEvent(
(ushort)EventId.StartupCurrentDirectory,
EventGenerators = EventGenerators.LocalOnly,
EventLevel = Level.Verbose,
Message = "{ShortProductName} Startup Current Directory: '{0}'")]
public abstract void StartupCurrentDirectory(LoggingContext context, string startupDirectory);
/// <summary>
/// CAUTION!!
///
/// WDG has Asimov telemetry listening to this event. Any change to an existing field will require a breaking change announcement
/// </summary>
[GeneratedEvent(
(ushort)EventId.DominoCompletion,
EventGenerators = EventGenerators.LocalAndTelemetry,
EventLevel = Level.Verbose,
EventOpcode = (byte)EventOpcode.Stop,
Message = "{ShortProductName} process exited with: ExitCode:'{0}', ExitType:{1}, ErrorBucket:{errorBucket}")]
public abstract void DominoCompletion(LoggingContext context, int exitCode, string exitKind, string errorBucket, string bucketMessage, int processRunningTime);
[GeneratedEvent(
(ushort)EventId.DominoPerformanceSummary,
// All data that goes into this is already sent to telemetry in other places. This event is just here for
// sake of creating a pretty summary. Hence it is LocalOnly
EventGenerators = EventGenerators.LocalOnly,
EventLevel = Level.Verbose,
Message = "Performance Summary:\r\n" +
"Time breakdown:\r\n" +
" Application Initialization: {appInitializationPercent}\r\n" +
" Graph Construction: {graphConstructionPercent}\r\n" +
" Checking for pip graph reuse: {checkingForPipGraphReusePercent}\r\n" +
" Reloading pip graph: {reloadingPipGraphPercent}\r\n" +
" Create graph: {createGraphPercent}\r\n" +
" Other: {graphConstructionOtherPercent}%\r\n" +
" Scrubbing: {scrubbingPercent}\r\n" +
" Scheduler Initialization: {schedulerInitPercent}\r\n" +
" Execute Phase: {executePhasePercent}\r\n" +
" Executing processes {processExecutePercent}%\r\n" +
"{telemetryTagsPercent}" +
" Process running overhead: {processRunningPercent}%\r\n" +
" Hashing inputs: {hashingInputs}%\r\n" +
" Checking for cache hits: {checkingForCacheHit}%\r\n" +
" Processing outputs: {processOutputs}%\r\n" +
" Replay outputs from cache: {replayFromCache}%\r\n" +
" Prepare process sandbox: {prepareSandbox}%\r\n" +
" Non-process pips: {nonProcessPips}%\r\n" +
" Other: {processOverheadOther}%\r\n" +
" Other: {highLevelOtherPercent}%\r\n\r\n" +
"Process pip cache hits: {cacheHitRate}% ({processPipsCacheHit}/{totalProcessPips})\r\n" +
"Incremental scheduling up to date rate: {incrementalSchedulingPruneRate}% ({incrementalSchedulingPrunedPips}/{totalProcessPips})\r\n" +
"Server mode used: {serverUsed}\r\n" +
"Execute phase utilization: Avg CPU:{averageCpu}% Min Available Ram MB:{minAvailableMemoryMb} Avg Disk Active:{diskUsage}\r\n" +
"Factors limiting concurrency by build time: CPU:{limitingResourcePercentages.CPU}%, Graph shape:{limitingResourcePercentages.GraphShape}%, Disk:{limitingResourcePercentages.Disk}%, Memory:{limitingResourcePercentages.Memory}%, ProjectedMemory:{limitingResourcePercentages.ProjectedMemory}%, Semaphore:{limitingResourcePercentages.Semaphore}%, Concurrency limit:{limitingResourcePercentages.ConcurrencyLimit}%, Other:{limitingResourcePercentages.Other}%")]
public abstract void DominoPerformanceSummary(LoggingContext context, int processPipsCacheHit, int cacheHitRate, int incrementalSchedulingPrunedPips, int incrementalSchedulingPruneRate, int totalProcessPips, bool serverUsed,
string appInitializationPercent, string graphConstructionPercent, string scrubbingPercent, string schedulerInitPercent, string executePhasePercent, int highLevelOtherPercent,
string checkingForPipGraphReusePercent, string reloadingPipGraphPercent, string createGraphPercent, int graphConstructionOtherPercent,
int processExecutePercent, string telemetryTagsPercent, int processRunningPercent, int hashingInputs, int checkingForCacheHit, int processOutputs, int replayFromCache, int prepareSandbox, int processOverheadOther, int nonProcessPips,
int averageCpu, int minAvailableMemoryMb, string diskUsage,
LimitingResourcePercentages limitingResourcePercentages);
/// <summary>
/// Analyzes and logs a performance summary. All of the data logged in this message is available in various places in
/// the standard and stats log. This just consolidates it together in a human consumable format
/// </summary>
public void AnalyzeAndLogPerformanceSummary(LoggingContext context, ICommandLineConfiguration config, AppPerformanceInfo perfInfo)
{
// Don't bother logging this stuff if we don't actually have the data
if (perfInfo == null || perfInfo.EnginePerformanceInfo == null || perfInfo.EnginePerformanceInfo.SchedulerPerformanceInfo == null)
{
return;
}
// Various heuristics for what caused the build to be slow.
using (var sbPool = Pools.GetStringBuilder())
{
SchedulerPerformanceInfo schedulerInfo = perfInfo.EnginePerformanceInfo.SchedulerPerformanceInfo;
long loadOrConstructGraph = perfInfo.EnginePerformanceInfo.GraphCacheCheckDurationMs +
perfInfo.EnginePerformanceInfo.GraphReloadDurationMs +
perfInfo.EnginePerformanceInfo.GraphConstructionDurationMs;
// Log the summary
// High level
var graphConstruction = ComputeTimePercentage(loadOrConstructGraph, perfInfo.EngineRunDurationMs);
var appInitialization = ComputeTimePercentage(perfInfo.AppInitializationDurationMs, perfInfo.EngineRunDurationMs);
var scrubbing = ComputeTimePercentage(perfInfo.EnginePerformanceInfo.ScrubbingDurationMs, perfInfo.EngineRunDurationMs);
var schedulerInit = ComputeTimePercentage(perfInfo.EnginePerformanceInfo.SchedulerInitDurationMs, perfInfo.EngineRunDurationMs);
var executePhase = ComputeTimePercentage(perfInfo.EnginePerformanceInfo.ExecutePhaseDurationMs, perfInfo.EngineRunDurationMs);
var highLevelOther = Math.Max(0, 100 - appInitialization.Item1 - graphConstruction.Item1 - scrubbing.Item1 - schedulerInit .Item1 - executePhase.Item1);
// Graph construction
var checkingForPipGraphReuse = ComputeTimePercentage(perfInfo.EnginePerformanceInfo.GraphCacheCheckDurationMs, loadOrConstructGraph);
var reloadingPipGraph = ComputeTimePercentage(perfInfo.EnginePerformanceInfo.GraphReloadDurationMs, loadOrConstructGraph);
var createGraph = ComputeTimePercentage(perfInfo.EnginePerformanceInfo.GraphConstructionDurationMs, loadOrConstructGraph);
var graphConstructionOtherPercent = Math.Max(0, 100 - checkingForPipGraphReuse.Item1 - reloadingPipGraph.Item1 - createGraph.Item1);
// Process Overhead
long allStepsDuration = 0;
foreach (PipExecutionStep step in Enum.GetValues(typeof(PipExecutionStep)))
{
allStepsDuration += (long)schedulerInfo.PipExecutionStepCounters.GetElapsedTime(step).TotalMilliseconds;
}
// ExecuteProcessDuration comes from the PipExecutionCounters and is a bit tighter around the actual external
// process invocation than the corresponding counter in PipExecutionStepCounters;
long allStepsMinusPipExecution = allStepsDuration - schedulerInfo.ExecuteProcessDurationMs;
var hashingInputs = ComputeTimePercentage(
(long)schedulerInfo.PipExecutionStepCounters.GetElapsedTime(PipExecutionStep.Start).TotalMilliseconds,
allStepsMinusPipExecution);
var checkingForCacheHit = ComputeTimePercentage(
(long)schedulerInfo.PipExecutionStepCounters.GetElapsedTime(PipExecutionStep.CacheLookup).TotalMilliseconds +
(long)schedulerInfo.PipExecutionStepCounters.GetElapsedTime(PipExecutionStep.CheckIncrementalSkip).TotalMilliseconds,
allStepsMinusPipExecution);
var processOutputs = ComputeTimePercentage(
(long)schedulerInfo.PipExecutionStepCounters.GetElapsedTime(PipExecutionStep.PostProcess).TotalMilliseconds,
allStepsMinusPipExecution);
var replayFromCache = ComputeTimePercentage(
(long)schedulerInfo.PipExecutionStepCounters.GetElapsedTime(PipExecutionStep.RunFromCache).TotalMilliseconds +
(long)schedulerInfo.PipExecutionStepCounters.GetElapsedTime(PipExecutionStep.MaterializeOutputs).TotalMilliseconds +
(long)schedulerInfo.PipExecutionStepCounters.GetElapsedTime(PipExecutionStep.MaterializeInputs).TotalMilliseconds,
allStepsMinusPipExecution);
var prepareSandbox = ComputeTimePercentage(
schedulerInfo.SandboxedProcessPrepDurationMs,
allStepsMinusPipExecution);
var nonProcessPips = ComputeTimePercentage(
(long)schedulerInfo.PipExecutionStepCounters.GetElapsedTime(PipExecutionStep.ExecuteNonProcessPip).TotalMilliseconds,
allStepsMinusPipExecution);
var processOverheadOther = Math.Max(0, 100 - hashingInputs.Item1 - checkingForCacheHit.Item1 - processOutputs.Item1 - replayFromCache.Item1 - prepareSandbox.Item1 - nonProcessPips.Item1);
StringBuilder sb = new StringBuilder();
if (schedulerInfo.DiskStatistics != null)
{
foreach (var item in schedulerInfo.DiskStatistics)
{
sb.AppendFormat("{0}:{1}% ", item.Drive, item.CalculateActiveTime(lastOnly: false));
}
}
// The performance summary looks at counters that don't get aggregated and sent back to the master from
// all workers. So it only applies to single machine builds.
if (config.Distribution.BuildWorkers == null || config.Distribution.BuildWorkers.Count == 0)
{
DominoPerformanceSummary(
context,
processPipsCacheHit: (int)schedulerInfo.ProcessPipCacheHits,
cacheHitRate: ComputeTimePercentage(schedulerInfo.ProcessPipCacheHits, schedulerInfo.TotalProcessPips).Item1,
incrementalSchedulingPrunedPips: (int)schedulerInfo.ProcessPipIncrementalSchedulingPruned,
incrementalSchedulingPruneRate: ComputeTimePercentage(schedulerInfo.ProcessPipIncrementalSchedulingPruned, schedulerInfo.TotalProcessPips).Item1,
totalProcessPips: (int)schedulerInfo.TotalProcessPips,
serverUsed: perfInfo.ServerModeUsed,
graphConstructionPercent: graphConstruction.Item3,
appInitializationPercent: appInitialization.Item3,
scrubbingPercent: scrubbing.Item3,
schedulerInitPercent: schedulerInit.Item3,
executePhasePercent: executePhase.Item3,
highLevelOtherPercent: highLevelOther,
checkingForPipGraphReusePercent: checkingForPipGraphReuse.Item3,
reloadingPipGraphPercent: reloadingPipGraph.Item3,
createGraphPercent: createGraph.Item3,
graphConstructionOtherPercent: graphConstructionOtherPercent,
processExecutePercent: ComputeTimePercentage(schedulerInfo.ExecuteProcessDurationMs, allStepsDuration).Item1,
telemetryTagsPercent: ComputeTelemetryTagsPerformanceSummary(schedulerInfo),
processRunningPercent: ComputeTimePercentage(allStepsMinusPipExecution, allStepsDuration).Item1,
hashingInputs: hashingInputs.Item1,
checkingForCacheHit: checkingForCacheHit.Item1,
processOutputs: processOutputs.Item1,
replayFromCache: replayFromCache.Item1,
prepareSandbox: prepareSandbox.Item1,
processOverheadOther: processOverheadOther,
nonProcessPips: nonProcessPips.Item1,
averageCpu: schedulerInfo.AverageMachineCPU,
minAvailableMemoryMb: (int)schedulerInfo?.MachineMinimumAvailablePhysicalMB,
diskUsage: sb.ToString(),
limitingResourcePercentages: perfInfo.EnginePerformanceInfo.LimitingResourcePercentages ?? new LimitingResourcePercentages());
}
if (schedulerInfo.ProcessPipsUncacheable > 0)
{
LogPerfSmell(context, () => ProcessPipsUncacheable(context, schedulerInfo.ProcessPipsUncacheable));
}
// Make sure there were some misses since a complete noop with incremental scheduling shouldn't cause this to trigger
if (schedulerInfo.CriticalPathTableHits == 0 && schedulerInfo.CriticalPathTableMisses != 0)
{
LogPerfSmell(context, () => NoCriticalPathTableHits(context));
}
// Make sure some source files were hashed since a complete noop build with incremental scheduling shouldn't cause this to trigger
if (schedulerInfo.FileContentStats.SourceFilesUnchanged == 0 && schedulerInfo.FileContentStats.SourceFilesHashed != 0)
{
LogPerfSmell(context, () => NoSourceFilesUnchanged(context));
}
if (!perfInfo.ServerModeEnabled)
{
LogPerfSmell(context, () => ServerModeDisabled(context));
}
if (!perfInfo.EnginePerformanceInfo.GraphCacheCheckJournalEnabled)
{
LogPerfSmell(context, () => GraphCacheCheckJournalDisabled(context));
}
if (perfInfo.EnginePerformanceInfo.CacheInitializationDurationMs > 5000)
{
LogPerfSmell(context, () => SlowCacheInitialization(context, perfInfo.EnginePerformanceInfo.CacheInitializationDurationMs));
}
if (perfInfo.EnginePerformanceInfo.SchedulerPerformanceInfo.HitLowMemorySmell)
{
LogPerfSmell(context, () => Scheduler.Tracing.Logger.Log.LowMemory(context, perfInfo.EnginePerformanceInfo.SchedulerPerformanceInfo.MachineMinimumAvailablePhysicalMB));
}
if (config.Sandbox.LogProcesses)
{
LogPerfSmell(context, () => LogProcessesEnabled(context));
}
if (perfInfo.EnginePerformanceInfo.FrontEndIOWeight > 5)
{
LogPerfSmell(context, () => FrontendIOSlow(context, perfInfo.EnginePerformanceInfo.FrontEndIOWeight));
}
}
}
private static string ComputeTelemetryTagsPerformanceSummary(SchedulerPerformanceInfo schedulerInfo)
{
string telemetryTagPerformanceSummary = string.Empty;
if (schedulerInfo != null && schedulerInfo.ProcessPipCountersByTelemetryTag != null && schedulerInfo.ExecuteProcessDurationMs > 0)
{
var elapsedTimesByTelemetryTag = schedulerInfo.ProcessPipCountersByTelemetryTag.GetElapsedTimes(PipCountersByGroup.ExecuteProcessDuration);
telemetryTagPerformanceSummary = string.Join(Environment.NewLine, elapsedTimesByTelemetryTag.Select(elapedTime => string.Format("{0,-12}{1,-39}{2}%", string.Empty, elapedTime.Key, ComputeTimePercentage((long)elapedTime.Value.TotalMilliseconds, schedulerInfo.ExecuteProcessDurationMs).Item1)));
if (elapsedTimesByTelemetryTag.Count > 0)
{
var otherTime = ComputeTimePercentage(Math.Max(0, schedulerInfo.ExecuteProcessDurationMs - elapsedTimesByTelemetryTag.Sum(elapedTime => (long)elapedTime.Value.TotalMilliseconds)), schedulerInfo.ExecuteProcessDurationMs);
telemetryTagPerformanceSummary += string.Format("{0}{1,-12}{2,-39}{3}%{0}", Environment.NewLine, string.Empty, "Other:", otherTime.Item1);
}
}
return telemetryTagPerformanceSummary;
}
private void LogPerfSmell(LoggingContext context, Action action)
{
if (m_firstSmell)
{
BuildHasPerfSmells(context);
m_firstSmell = false;
}
action();
}
private bool m_firstSmell = true;
private static Tuple<int, string, string> ComputeTimePercentage(long numerator, long denominator)
{
int percent = 0;
if (denominator > 0)
{
percent = (int)(100.0 * numerator / denominator);
}
string time = (int)TimeSpan.FromMilliseconds(numerator).TotalSeconds + "sec";
string combined = percent + "% (" + time + ")";
return new Tuple<int, string, string>(percent, time, combined);
}
[GeneratedEvent(
(ushort)EventId.DominoCatastrophicFailure,
EventGenerators = EventGenerators.TelemetryOnly,
EventLevel = Level.Critical,
Message = "Telemetry Only")]
public abstract void DominoCatastrophicFailure(LoggingContext context,
string exception,
BuildInfo buildInfo,
ExceptionRootCause rootCause,
bool wasServer,
string firstUserError,
string lastUserError,
string firstInsfrastructureError,
string lastInfrastructureError,
string firstInternalError,
string lastInternalError);
[GeneratedEvent(
(ushort)LogEventId.DominoMacOSCrashReport,
EventGenerators = EventGenerators.TelemetryOnly,
EventLevel = Level.Critical,
Message = "Telemetry Only")]
public abstract void DominoMacOSCrashReport(LoggingContext context, string crashSessionId, string content, string type, string filename);
[GeneratedEvent(
(ushort)EventId.UsingExistingServer,
EventGenerators = EventGenerators.LocalOnly,
EventLevel = Level.Verbose,
Keywords = (int)Keywords.UserMessage,
Message = EventConstants.PhasePrefix + "Running from existing {ShortProductName} server process.")]
public abstract void UsingExistingServer(LoggingContext context, ServerModeBuildStarted serverModeBuildStarted);
[GeneratedEvent(
(ushort)EventId.AppServerBuildStart,
EventGenerators = EventGenerators.LocalAndTelemetry,
EventLevel = Level.Verbose,
Message = "Starting build from server process: UniqueServerName:{uniqueAppServerName}, PID: {serverModeBuildStarted.PID}, Times process reused: {serverModeBuildStarted.TimesPreviouslyUsed}, ThreadCount:{serverModeBuildStarted.StartPerformance.ThreadCount}, HandleCount:{serverModeBuildStarted.StartPerformance.HandleCount}")]
public abstract void ServerModeBuildStarted(LoggingContext context, ServerModeBuildStarted serverModeBuildStarted, string uniqueAppServerName);
[GeneratedEvent(
(ushort)EventId.AppServerBuildFinish,
EventGenerators = EventGenerators.LocalOnly,
EventLevel = Level.Verbose,
Message = "Finished build from server process: ThreadCount:{serverModeBuildCompleted.EndPerformance.ThreadCount} HandleCount:{serverModeBuildCompleted.EndPerformance.HandleCount}")]
public abstract void ServerModeBuildCompleted(LoggingContext context, ServerModeBuildCompleted serverModeBuildCompleted);
[GeneratedEvent(
(ushort)EventId.StartingNewServer,
EventGenerators = EventGenerators.LocalOnly,
EventLevel = Level.Verbose,
Keywords = (int)Keywords.UserMessage,
Message = EventConstants.PhasePrefix + "Starting new {ShortProductName} server process.")]
public abstract void StartingNewServer(LoggingContext context, ServerModeBuildStarted serverModeBuildStarted);
[GeneratedEvent(
(ushort)EventId.CannotStartServer,
EventGenerators = EventGenerators.LocalAndTelemetry,
EventLevel = Level.Verbose,
Keywords = (int)(Keywords.UserMessage | Keywords.Progress),
Message = "Server mode was requested but cannot be started. {serverModeCannotStart.Reason}.")]
public abstract void CannotStartServer(LoggingContext context, ServerModeCannotStart serverModeCannotStart);
[GeneratedEvent(
(ushort)EventId.DeploymentUpToDateCheckPerformed,
EventGenerators = EventGenerators.LocalAndTelemetry,
EventLevel = Level.Verbose,
Keywords = (int)(Keywords.UserMessage | Keywords.Progress),
Message = "{ShortProductName} binary deployment up-to-date check performed in {deploymentUpToDateCheck.TimeToUpToDateCheckMilliseconds}ms. Deployment cache created:{deploymentCacheCreated}, deployment duration:{serverDeploymentCacheCreated.TimeToCreateServerCacheMilliseconds}ms.")]
public abstract void DeploymentUpToDateCheckPerformed(LoggingContext context, ServerDeploymentUpToDateCheck deploymentUpToDateCheck, bool deploymentCacheCreated, ServerDeploymentCacheCreated serverDeploymentCacheCreated);
[GeneratedEvent(
(ushort)EventId.DeploymentCacheCreated,
EventGenerators = EventGenerators.LocalOnly,
EventLevel = Level.Verbose,
Keywords = (int)(Keywords.UserMessage | Keywords.Progress),
EventTask = (ushort)Tasks.HostApplication,
Message = "{ShortProductName} deployment cache was created. This means this is the first time {ShortProductName} is requested to run in server mode or {ShortProductName} binaries changed. Duration: {serverDeploymentCacheCreated.TimeToCreateServerCacheMilliseconds}ms.")]
public abstract void DeploymentCacheCreated(LoggingContext context, ServerDeploymentCacheCreated serverDeploymentCacheCreated);
[GeneratedEvent(
(ushort)EventId.TelemetryEnabledHideNotification,
EventGenerators = EventGenerators.LocalOnly,
EventLevel = Level.Verbose,
Message = EventConstants.PhasePrefix + "Telemetry is enabled. SessionId: {sessionId}",
Keywords = (int)Keywords.UserMessage)]
public abstract void TelemetryEnabledHideNotification(LoggingContext context, string sessionId);
[GeneratedEvent(
(ushort)EventId.MemoryLoggingEnabled,
EventGenerators = EventGenerators.LocalOnly,
EventLevel = Level.Warning,
Message = "Memory logging is enabled (/logmemory). This has a negative performance impact and should only be used for performing memory analysis.",
Keywords = (int)Keywords.UserMessage)]
public abstract void MemoryLoggingEnabled(LoggingContext context);
[GeneratedEvent(
(ushort)EventId.TelemetryEnabledNotifyUser,
EventGenerators = EventGenerators.LocalOnly,
EventLevel = Level.Informational,
Message = EventConstants.PhasePrefix + "Telemetry is enabled. SessionId: {sessionId}",
Keywords = (int)Keywords.UserMessage)]
public abstract void TelemetryEnabledNotifyUser(LoggingContext context, string sessionId);
[GeneratedEvent(
(ushort)EventId.MappedRoot,
EventGenerators = EventGenerators.LocalOnly,
EventLevel = Level.Informational,
Keywords = (int)Keywords.UserMessage,
EventTask = (ushort)Tasks.HostApplication,
Message = "Mapped root drive '{rootDrive}' to directory '{directory}'")]
public abstract void MappedRoot(LoggingContext context, string rootDrive, string directory);
[GeneratedEvent(
(ushort)EventId.CatastrophicFailure,
EventGenerators = EventGenerators.LocalOnly,
EventLevel = Level.Critical,
Keywords = (int)Keywords.UserMessage,
EventTask = (ushort)Tasks.HostApplication,
Message = "Catastrophic {ShortProductName} Failure.\nBuild:{build}{commitId}.\nException:{message}")]
public abstract void CatastrophicFailure(LoggingContext context, string message, string commitId, string build);
[GeneratedEvent(
(ushort)EventId.CatastrophicFailureCausedByDiskSpaceExhaustion,
EventGenerators = EventGenerators.LocalOnly,
EventLevel = Level.Critical,
Keywords = (int)Keywords.UserMessage,
EventTask = (ushort)Tasks.HostApplication,
Message = "One or more I/O operations have failed since a volume is out of space. Ensure that the volumes containing build outputs, logs, or the build cache have sufficient free space, and try again.")]
public abstract void CatastrophicFailureCausedByDiskSpaceExhaustion(LoggingContext context);
[GeneratedEvent(
(ushort)EventId.StorageCatastrophicFailureDriveError,
EventGenerators = EventGenerators.LocalOnly,
EventLevel = Level.Critical,
Keywords = (int)Keywords.UserMessage,
EventTask = (ushort)Tasks.HostApplication,
Message = "One or more I/O operations have failed due to a disk error. Check your disk drives for errors.")]
public abstract void StorageCatastrophicFailureCausedByDriveError(LoggingContext context);
[GeneratedEvent(
(ushort)EventId.CatastrophicFailureMissingRuntimeDependency,
EventGenerators = EventGenerators.LocalOnly,
EventLevel = Level.Critical,
Keywords = (int)Keywords.UserMessage,
EventTask = (ushort)Tasks.HostApplication,
Message = "A runtime dependency was not found. This usually indicates one or more assemblies were not correctly copied with the {MainExecutableName} deployment. Details: {message}")]
public abstract void CatastrophicFailureMissingRuntimeDependency(LoggingContext context, string message);
[GeneratedEvent(
(ushort)EventId.CatastrophicFailureCausedByCorruptedCache,
EventGenerators = EventGenerators.LocalOnly,
EventLevel = Level.Critical,
Keywords = (int)Keywords.UserMessage,
EventTask = (ushort)Tasks.HostApplication,
Message = "{ShortProductName} cache is potentially corrupted. Please restart the build. {ShortProductName} will try to recover from this corruption in the next run. If this issue persists, please email domdev@microsoft.com")]
public abstract void CatastrophicFailureCausedByCorruptedCache(LoggingContext context);
[GeneratedEvent(
(ushort)EventId.Channel,
EventGenerators = EventGenerators.LocalOnly,
EventLevel = Level.Informational,
Keywords = (int)Keywords.UserMessage,
EventTask = (ushort)Tasks.Engine,
Message = "Listen channel is '{channelName}'")]
public abstract void Channel(LoggingContext context, string channelName);
[GeneratedEvent(
(ushort)EventId.CancellationRequested,
EventGenerators = EventGenerators.LocalOnly,
EventLevel = Level.Error,
Keywords = (int)(Keywords.UserMessage | Keywords.UserError),
EventTask = (ushort)Tasks.HostApplication,
EventOpcode = (byte)EventOpcode.Info,
Message = "Graceful cancellation requested.\r\n" + "Use ctrl-break for immediate termination. CAUTION! This may slow down the next build.")]
public abstract void CancellationRequested(LoggingContext context);
[GeneratedEvent(
(ushort)EventId.TelemetryShutDown,
EventGenerators = EventGenerators.LocalOnly,
EventLevel = Level.Verbose,
Keywords = (int)Keywords.UserMessage,
EventTask = (ushort)Tasks.HostApplication,
Message = "Telemetry shut down completed in {0}ms")]
public abstract void TelemetryShutDown(LoggingContext context, long telemetryShutdownDurationMs);
[GeneratedEvent(
(ushort)EventId.TelemetryShutDownException,
EventGenerators = EventGenerators.LocalOnly,
EventLevel = Level.Error,
Keywords = (int)Keywords.UserMessage,
EventTask = (ushort)Tasks.HostApplication,
Message = "Telemetry shut down results in an exception: {0}")]
public abstract void TelemetryShutDownException(LoggingContext context, string message);
[GeneratedEvent(
(ushort)EventId.TelemetryShutdownTimeout,
EventGenerators = EventGenerators.LocalOnly,
EventLevel = Level.Informational,
Keywords = (int)Keywords.UserMessage,
EventTask = (ushort)Tasks.HostApplication,
Message = "Telemetry timed out after {0} milliseconds. This session will have incomplete telemetry data")]
public abstract void TelemetryShutdownTimeout(LoggingContext context, long milliseconds);
[GeneratedEvent(
(ushort)EventId.ServerDeploymentDirectoryHashMismatch,
EventGenerators = EventGenerators.LocalOnly,
EventLevel = Level.Error,
Keywords = (int)Keywords.UserMessage,
EventTask = (ushort)Tasks.HostApplication,
Message = "ServerDeploymentDirectory hash mismatch: {ShortProductName} AppServer hash, {0} != ServerDeploymentDirectory hash, {1}. Re-running {ShortProductName} will fix the issue.")]
public abstract void ServerDeploymentDirectoryHashMismatch(LoggingContext context, string hashInMemory, string hashInFile);
[GeneratedEvent(
(ushort)EventId.EventCount,
EventGenerators = EventGenerators.TelemetryOnly,
EventLevel = Level.Verbose,
Message = "N/A")]
public abstract void EventCounts(LoggingContext context, IDictionary<string, int> entryMatches);
[GeneratedEvent(
(ushort)EventId.FailedToEnumerateLogDirsForCleanup,
EventGenerators = EventGenerators.LocalOnly,
Message = "Failed to enumerate log directories for cleanup '{logsRoot}': {message}",
EventLevel = Level.Informational,
EventTask = (ushort)Tasks.HostApplication,
Keywords = (int)Keywords.UserMessage)]
public abstract void FailedToEnumerateLogDirsForCleanup(LoggingContext context, string logsRoot, string message);
[GeneratedEvent(
(ushort)EventId.FailedToCleanupLogDir,
EventGenerators = EventGenerators.LocalOnly,
Message = "Failed to delete log directory '{logDirectory}': {message}",
EventLevel = Level.Informational,
EventTask = (ushort)Tasks.HostApplication,
Keywords = (int)Keywords.UserMessage)]
public abstract void FailedToCleanupLogDir(LoggingContext context, string logDirectory, string message);
[GeneratedEvent(
(ushort)EventId.WaitingCleanupLogDir,
EventGenerators = EventGenerators.LocalOnly,
Message = "Waiting for the log cleanup thread to finish...",
EventLevel = Level.Informational,
EventTask = (ushort)Tasks.HostApplication,
Keywords = (int)Keywords.UserMessage)]
public abstract void WaitingCleanupLogDir(LoggingContext context);
[GeneratedEvent(
(ushort)EventId.WaitingClientDebugger,
EventGenerators = EventGenerators.LocalOnly,
Message = @"Waiting for a debugger to connect (blocking). Configure VSCode by adding \""debugServer\"": {port} to your '.vscode/launch.json' and choose \""Attach to running {ShortScriptName}\"".",
EventLevel = Level.LogAlways,
EventTask = (ushort)Tasks.HostApplication,
Keywords = (int)Keywords.UserMessage)]
public abstract void WaitingForClientDebuggerToConnect(LoggingContext context, int port);
[GeneratedEvent(
(int)EventId.EventWriteFailuresOccurred,
EventGenerators = EventGenerators.LocalOnly,
EventLevel = Level.Warning,
Keywords = (int)Keywords.Diagnostics,
EventTask = (int)Tasks.HostApplication,
Message = "One or more event-write failures occurred. ETW trace sessions (including produced trace files) may be incomplete.")]
public abstract void EventWriteFailuresOccurred(LoggingContext context);
[GeneratedEvent(
(int)EventId.DisplayHelpLink,
EventGenerators = EventGenerators.LocalOnly,
EventLevel = Level.Informational,
Keywords = (int)Keywords.UserMessage,
EventTask = (int)Tasks.HostApplication,
Message = "{helpLinkPrefix} {helpLink}")]
public abstract void DisplayHelpLink(LoggingContext context, string helpLinkPrefix, string helpLink);
[GeneratedEvent(
(int)EventId.CoreDumpNoPermissions,
EventGenerators = EventGenerators.LocalOnly,
EventLevel = Level.Warning,
Keywords = (int)Keywords.UserMessage,
EventTask = (int)Tasks.HostApplication,
Message = "Setting up core dump creation for abnormal program exits has failed. Make sure you have permissions to read and write the core dump directory at '{directory}'.")]
public abstract void DisplayCoreDumpDirectoryNoPermissionsWarning(LoggingContext context, string directory);
[GeneratedEvent(
(int)EventId.CrashReportProcessing,
EventGenerators = EventGenerators.LocalOnly,
EventLevel = Level.Warning,
Keywords = (int)Keywords.UserMessage,
EventTask = (int)Tasks.HostApplication,
Message = "Crash reports could not be processed and uploaded, make sure the state file '{stateFilePath}' is not malformed and accessible. Error: {message}.")]
public abstract void DisplayCrashReportProcessingFailedWarning(LoggingContext context, string stateFilePath, string message);
[GeneratedEvent(
(ushort)EventId.ChangeJournalServiceReady,
EventGenerators = EventGenerators.LocalOnly,
EventLevel = Level.Informational,
Message = EventConstants.PhasePrefix + "{ShortProductName} JournalService is properly set up and you are ready to use {ShortProductName} with graph-caching enabled.",
Keywords = (int)Keywords.UserMessage)]
public abstract void ChangeJournalServiceReady(LoggingContext context);
[GeneratedEvent(
(ushort)EventId.MaterializingProfilerReport,
EventGenerators = EventGenerators.LocalOnly,
EventLevel = Level.LogAlways,
EventTask = (ushort)Tasks.HostApplication,
Message = EventConstants.PhasePrefix + "Writing profiler report to '{destination}'.",
Keywords = (int)Keywords.UserMessage)]
public abstract void MaterializingProfilerReport(LoggingContext context, string destination);
[GeneratedEvent(
(ushort)EventId.ErrorMaterializingProfilerReport,
EventGenerators = EventGenerators.LocalOnly,
EventLevel = Level.LogAlways,
EventTask = (ushort)Tasks.HostApplication,
Message = EventConstants.PhasePrefix + "Profiler report could not be written. Error code {errorCode:X8}: {message}.",
Keywords = (int)Keywords.UserMessage)]
public abstract void ErrorMaterializingProfilerReport(LoggingContext context, int errorCode, string message);
[GeneratedEvent(
(ushort)EventId.BuildHasPerfSmells,
EventGenerators = EventGenerators.LocalOnly,
EventLevel = Level.Verbose,
EventTask = (ushort)Tasks.HostApplication,
Message = "---------- PERFORMANCE SMELLS ----------",
Keywords = (int)Keywords.UserMessage)]
public abstract void BuildHasPerfSmells(LoggingContext context);
[GeneratedEvent(
(ushort)EventId.ProcessPipsUncacheable,
EventGenerators = EventGenerators.LocalOnly,
EventLevel = Level.Verbose,
EventTask = (ushort)Tasks.HostApplication,
Message = "Uncacheable Pips: This build had {count} pips that are not cacheable and will be unconditionally run. See related DX0269 messages earlier in the log for details.",
Keywords = (int)Keywords.UserMessage)]
public abstract void ProcessPipsUncacheable(LoggingContext context, long count);
[GeneratedEvent(
(ushort)EventId.NoCriticalPathTableHits,
EventGenerators = EventGenerators.LocalOnly,
EventLevel = Level.Verbose,
EventTask = (ushort)Tasks.HostApplication,
Message = "No critical path info: This build could not optimize the critical path based on previous runtime information. Either this was the first build on a machine or the engine cache directory was deleted.",
Keywords = (int)Keywords.UserMessage)]
public abstract void NoCriticalPathTableHits(LoggingContext context);
[GeneratedEvent(
(ushort)EventId.NoSourceFilesUnchanged,
EventGenerators = EventGenerators.LocalOnly,
EventLevel = Level.Verbose,
EventTask = (ushort)Tasks.HostApplication,
Message = "No FileContentTable: This build had to rehash all files instead of leveraging the USN journal to skip hashing of previously seen files. Either this was the first build on a machine or the engine cache directory was deleted.",
Keywords = (int)Keywords.UserMessage)]
public abstract void NoSourceFilesUnchanged(LoggingContext context);
[GeneratedEvent(
(ushort)EventId.ServerModeDisabled,
EventGenerators = EventGenerators.LocalOnly,
EventLevel = Level.Verbose,
EventTask = (ushort)Tasks.HostApplication,
Message = "Server mode disabled: This build disabled server mode. Unless this is a lab build, server mode should be enabled to speed up back to back builds.",
Keywords = (int)Keywords.UserMessage)]
public abstract void ServerModeDisabled(LoggingContext context);
[GeneratedEvent(
(ushort)EventId.GraphCacheCheckJournalDisabled,
EventGenerators = EventGenerators.LocalOnly,
EventLevel = Level.Verbose,
EventTask = (ushort)Tasks.HostApplication,
Message = "Change journal scan disabled: This build didn't utilize the change journal scan when checking for pip graph reuse. This significantly degrades I/O performance on spinning disk drives. The journal requires running as admin or installation of the change journal service. Check the warning log for details.",
Keywords = (int)Keywords.UserMessage)]
public abstract void GraphCacheCheckJournalDisabled(LoggingContext context);
[GeneratedEvent(
(ushort)EventId.SlowCacheInitialization,
EventGenerators = EventGenerators.LocalOnly,
EventLevel = Level.Verbose,
EventTask = (ushort)Tasks.HostApplication,
Message = "Cache initialization took {cacheInitializationDurationMs}ms. This long of an initialization may mean that cache metadata needed to be reconstructed because {ShortProductName} was not shut down cleanly in the previous build. Make sure to allow {ShortProductName} to shut down cleanly (single ctrl-c).",
Keywords = (int)Keywords.UserMessage)]
public abstract void SlowCacheInitialization(LoggingContext context, long cacheInitializationDurationMs);
[GeneratedEvent(
(ushort)EventId.LogProcessesEnabled,
EventGenerators = EventGenerators.LocalOnly,
EventLevel = Level.Verbose,
EventTask = (ushort)Tasks.HostApplication,
Message = "The /logprocesses option is enabled which causes {ShortProductName} to capture data about all child processes and all file accesses. This is helpful for diagnosing problems, but slows down builds and should be selectively be enabled only when that data is needed.",
Keywords = (int)Keywords.UserMessage)]
public abstract void LogProcessesEnabled(LoggingContext context);
[GeneratedEvent(
(ushort)EventId.FrontendIOSlow,
EventGenerators = EventGenerators.LocalOnly,
EventLevel = Level.Verbose,
EventTask = (ushort)Tasks.HostApplication,
Message = "Reading build specifications was {0:N1}x more expensive as evaluating them. This is generally a sign that IO performance is degraded. This could be due to GVFS needing to materialize remote files.",
Keywords = (int)Keywords.UserMessage)]
public abstract void FrontendIOSlow(LoggingContext context, double factor);
/// <summary>
/// Logging DominoCompletion with an extra CloudBuild event
/// </summary>
public static void LogDominoCompletion(LoggingContext context, int exitCode, ExitKind exitKind, ExitKind cloudBuildExitKind, string errorBucket, string bucketMessage, int processRunningTime, long utcTicks, bool inCloudBuild)
{
Log.DominoCompletion(context,
exitCode,
exitKind.ToString(),
errorBucket,
// This isn't a command line but it should still be sanatized for sake of not overflowing in telemetry
ScrubCommandLine(bucketMessage, 1000, 1000),
processRunningTime);
// Sending a different event to CloudBuild ETW listener.
if (inCloudBuild)
{
BuildXL.Tracing.CloudBuildEventSource.Log.DominoCompletedEvent(new DominoCompletedEvent
{
ExitCode = exitCode,
UtcTicks = utcTicks,
ExitKind = cloudBuildExitKind,
});
}
}
/// <summary>
/// Logging DominoInvocation with an extra CloudBuild event
/// </summary>
public static void LogDominoInvocation(
LoggingContext context,
string commandLine,
BuildInfo buildInfo,
MachineInfo machineInfo,
string sessionIdentifier,
string relatedSessionIdentifier,
ExecutionEnvironment environment,
long utcTicks,
string logDirectory,
bool inCloudBuild,
string startupDirectory,
string mainConfigurationFile)
{
Log.DominoInvocation(context, ScrubCommandLine(commandLine, 100000, 100000), buildInfo, machineInfo, sessionIdentifier, relatedSessionIdentifier, startupDirectory, mainConfigurationFile);
Log.DominoInvocationForLocalLog(context, commandLine, buildInfo, machineInfo, sessionIdentifier, relatedSessionIdentifier, startupDirectory, mainConfigurationFile);
if (inCloudBuild)
{
// Sending a different event to CloudBuild ETW listener.
BuildXL.Tracing.CloudBuildEventSource.Log.DominoInvocationEvent(new DominoInvocationEvent
{
UtcTicks = utcTicks,
// Truncate the command line that gets to the CB event to avoid exceeding the max event payload of 64kb
CommandLineArgs = commandLine?.Substring(0, Math.Min(commandLine.Length, 4 * 1024)),
DominoVersion = buildInfo.CommitId,
Environment = environment,
LogDirectory = logDirectory,
});
}
}
/// <summary>
/// Scrubs the command line to make it amenable (short enough) to be sent to telemetry
/// </summary>
internal static string ScrubCommandLine(string rawCommandLine, int leadingChars, int trailingChars)
{
Contract.Requires(rawCommandLine != null);
Contract.Requires(leadingChars >= 0);
Contract.Requires(trailingChars >= 0);
if (rawCommandLine.Length < leadingChars + trailingChars)
{
return rawCommandLine;
}
int indexOfBreakWithinPrefix = rawCommandLine.LastIndexOf(' ', leadingChars);
string prefix = indexOfBreakWithinPrefix == -1 ? rawCommandLine.Substring(0, leadingChars) : rawCommandLine.Substring(0, indexOfBreakWithinPrefix);
string breakMarker = indexOfBreakWithinPrefix == -1 ? "[...]" : " [...]";
int indexOfBreakWithinSuffix = rawCommandLine.IndexOf(' ', rawCommandLine.Length - trailingChars);
string suffix = indexOfBreakWithinSuffix == -1 ? rawCommandLine.Substring(rawCommandLine.Length - trailingChars) : rawCommandLine.Substring(indexOfBreakWithinSuffix, rawCommandLine.Length - indexOfBreakWithinSuffix);
return prefix + breakMarker + suffix;
}
}
/// <summary>
/// Start of a build connecting to a server process
/// </summary>
[SuppressMessage("Microsoft.Performance", "CA1815")]
public struct ServerModeBuildStarted
{
/// <summary>
/// The server's process ID
/// </summary>
public int PID { get; set; }
/// <summary>
/// Number of times the server process was used in previous builds
/// </summary>
public int TimesPreviouslyUsed { get; set; }
/// <summary>
/// Time the server mode has been idle since its previous use
/// </summary>
public int TimeIdleSeconds { get; set; }
/// <summary>
/// Performance info from when the build started
/// </summary>
public PerformanceSnapshot StartPerformance { get; set; }
}
/// <summary>
/// Snapshot of process
/// </summary>
[SuppressMessage("Microsoft.Performance", "CA1815")]
public struct PerformanceSnapshot
{
/// <summary>
/// Process ID
/// </summary>
public int PID { get; set; }
/// <summary>
/// Number of active threads
/// </summary>
public int ThreadCount { get; set; }
/// <summary>
/// Handles in current process
/// </summary>
public int HandleCount { get; set; }
/// <summary>
/// Gets the performance info from the current process
/// </summary>
public static PerformanceSnapshot CreateFromCurrentProcess()
{
Process me = Process.GetCurrentProcess();
return new PerformanceSnapshot()
{
PID = me.Id,
HandleCount = me.HandleCount,
ThreadCount = me.Threads.Count,
};
}
/// <summary>
/// Compares two performance info objects by subtracting each field in the first from each field in the second
/// </summary>
public static PerformanceSnapshot Compare(PerformanceSnapshot first, PerformanceSnapshot second)
{
return new PerformanceSnapshot()
{
HandleCount = second.HandleCount - first.HandleCount,
ThreadCount = second.ThreadCount - first.ThreadCount,
};
}
}
/// <summary>
/// Data for when the server mode build is completed
/// </summary>
[SuppressMessage("Microsoft.Performance", "CA1815")]
public struct ServerModeBuildCompleted
{
/// <summary>
/// Performance info from when the build started
/// </summary>
public PerformanceSnapshot EndPerformance { get; set; }
/// <summary>
/// Difference between start and finish
/// </summary>
public PerformanceSnapshot PerformanceDifference { get; set; }
}
/// <summary>
/// End of BuildXL invocation
/// </summary>
[SuppressMessage("Microsoft.Performance", "CA1815")]
// $Rename: Due to telemetry backend scripts this cannot be renamed to BuildXL
public struct DominoInvocationEnd
{
/// <summary>
/// The exit code returned on the command line
/// </summary>
public int ExitCode { get; set; }
/// <summary>
/// Details of how the process exited
/// </summary>
/// <remarks>
/// This is separate from ExitCode because we may decide to expand exit codes to ex
/// </remarks>
public ExitKind ExitKind { get; set; }
/// <summary>
/// Total duration the process was open
/// </summary>
public int ProcessRunningTime { get; set; }
}
/// <summary>
/// Reasons for not being able to start server mode
/// </summary>
[Serializable]
public enum ServerCannotStartKind
{
/// <summary>
/// Connecting to the server timed out
/// </summary>
Timeout,
/// <summary>
/// An exception when trying to create the server deployment
/// </summary>
Exception,
/// <summary>
/// The server process was started, but could not be used (startup crash?)
/// </summary>
ServerFailedToStart,
/// <summary>
/// The server process failed to start
/// </summary>
ServerProcessCreationFailed,
}
/// <summary>
/// Server mode cannot be started
/// </summary>
[SuppressMessage("Microsoft.Performance", "CA1815")]
[Serializable]
public struct ServerModeCannotStart
{
/// <summary>
/// Kind
/// </summary>
public ServerCannotStartKind Kind { get; set; }
/// <summary>
/// Reason
/// </summary>
public string Reason { get; set; }
}
/// <summary>
/// Up to date check of BuildXL deployment binaries
/// </summary>
[SuppressMessage("Microsoft.Performance", "CA1815")]
[Serializable]
// $Rename: Due to telemetry backend scripts this cannot be renamed to BuildXL
public struct ServerDeploymentUpToDateCheck
{
/// <summary>
/// Time it takes to compute the deployment up to date hash
/// </summary>
public long TimeToUpToDateCheckMilliseconds { get; set; }
}
/// <summary>
/// Deployment cache created
/// </summary>
[SuppressMessage("Microsoft.Performance", "CA1815")]
[Serializable]
public struct ServerDeploymentCacheCreated
{
/// <summary>
/// Time it takes to create BuildXL deployment cache
/// </summary>
public long TimeToCreateServerCacheMilliseconds { get; set; }
}
/// <summary>
/// Summarizes status and perf data when BuildXL is started in server mode
/// There is always an up to date check involved when server mode is requested
/// There may be a cache creation involved and the server mode may not be able to start properly
/// </summary>
[SuppressMessage("Microsoft.Performance", "CA1815")]
[Serializable]
public struct ServerModeStatusAndPerf
{
/// <summary>
/// Up to date check for getting a hash of the deployed binaries
/// </summary>
public ServerDeploymentUpToDateCheck UpToDateCheck { get; set; }
// TODO:for an owner: why the type is serializable? We're not using BinaryFormatter here.
#pragma warning disable CA2235 // Mark all non-serializable fields
/// <summary>
/// Server mode couldn't be started
/// </summary>
public ServerModeCannotStart? ServerModeCannotStart { get; set; }
#pragma warning restore CA2235 // Mark all non-serializable fields
// TODO:for an owner: why the type is serializable? We're not using BinaryFormatter here.
#pragma warning disable CA2235 // Mark all non-serializable fields
/// <summary>
/// The server cache was created
/// </summary>
public ServerDeploymentCacheCreated? CacheCreated { get; set; }
#pragma warning restore CA2235 // Mark all non-serializable fields
public void Write(BinaryWriter writer)
{
writer.Write(UpToDateCheck.TimeToUpToDateCheckMilliseconds);
writer.Write(ServerModeCannotStart.HasValue);
if (ServerModeCannotStart.HasValue)
{
writer.Write((int)ServerModeCannotStart.Value.Kind);
writer.Write(ServerModeCannotStart.Value.Reason);
}
writer.Write(CacheCreated.HasValue);
if (CacheCreated.HasValue)
{
writer.Write(CacheCreated.Value.TimeToCreateServerCacheMilliseconds);
}
}
public static ServerModeStatusAndPerf Read(BinaryReader reader)
{
ServerModeStatusAndPerf ret = default(ServerModeStatusAndPerf);
ret.UpToDateCheck = new ServerDeploymentUpToDateCheck()
{
TimeToUpToDateCheckMilliseconds = reader.ReadInt64(),
};
if (reader.ReadBoolean())
{
ret.ServerModeCannotStart = new ServerModeCannotStart()
{
Kind = (ServerCannotStartKind)reader.ReadInt32(),
Reason = reader.ReadString(),
};
}
else
{
ret.ServerModeCannotStart = null;
}
if (reader.ReadBoolean())
{
ret.CacheCreated = new ServerDeploymentCacheCreated()
{
TimeToCreateServerCacheMilliseconds = reader.ReadInt64(),
};
}
else
{
ret.CacheCreated = null;
}
return ret;
}
}
}
| 55.063291 | 733 | 0.641297 | [
"MIT"
] | buildxl-team-collab/BuildXL | Public/Src/App/Bxl/Tracing/Log.cs | 60,900 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace OSSC.Model
{
/// <summary>
/// SoundController's Database.
/// </summary>
[CreateAssetMenu(fileName = "NewSoundControllerData", menuName = "Sound Controller/New SoundControllerData")]
public class SoundControllerData : ScriptableObject
{
/// <summary>
/// Stores all created Categories.
/// </summary>
public CategoryItem[] items;
/// <summary>
/// Checks in editor whether the categories should fold out or not.
/// </summary>
public bool foldOutCategories = false;
/// <summary>
/// check if editor should fold out the tags or not.
/// </summary>
public bool foldOutTags = false;
/// <summary>
/// Database name.
/// </summary>
public string assetName;
/// <summary>
/// Stores the Created tags from Editor.
/// </summary>
public SoundTags soundTags;
}
} | 30.441176 | 113 | 0.592271 | [
"MIT"
] | dimixar/audio-controller-unity | AudioController/Assets/OSSC/Source/Model/SoundControllerData.cs | 1,037 | 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("MemoryEngine")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("MemoryEngine")]
[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("ec05c4c8-19bf-4210-88f0-d40eea69f0c6")]
// 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.756757 | 84 | 0.745168 | [
"MIT"
] | Wizmann/Rotown | MemoryEngine/Properties/AssemblyInfo.cs | 1,400 | C# |
using IdentityServer4.Extensions;
using Microsoft.AspNetCore.Authorization;
using Microsoft.Extensions.DependencyInjection;
namespace Jp.Management.Configuration
{
public static class ConfigurePolicy
{
public static void AddPolicies(this IServiceCollection services)
{
services.AddAuthorization(options =>
{
options.AddPolicy("Admin",
policy => policy.RequireAssertion(c =>
c.User.HasClaim("is4-rights", "manager") ||
c.User.IsInRole("Administrador")));
options.AddPolicy("ReadOnly", policy =>
policy.RequireAssertion(c =>
c.User.IsAuthenticated() ||
c.User.HasClaim("is4-rights", "manager") ||
c.User.IsInRole("Administrador")));
options.AddPolicy("UserManagement", policy =>
policy.RequireAuthenticatedUser());
});
}
}
}
| 33.354839 | 72 | 0.544487 | [
"MIT"
] | EatonEvents/JPProject.IdentityServer4.AdminUI | src/Backend/Jp.UserManagement/Configuration/ConfigurePolicy.cs | 1,036 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace Sabio.Web.Domain
{
public class AnnouncementAndCategory
{
public List<AnnouncementCategoryTotal> CategoriesWithTotals { get; set; }
public List<Announcement> Announcements { get; set; }
}
} | 22.5 | 81 | 0.72381 | [
"MIT"
] | entrotech/deployapp | Sabio.Web/Domain/AnnouncementAndCategory.cs | 317 | C# |
using System;
using Android.App;
using Android.Content.PM;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.OS;
using Prism;
using Prism.Ioc;
using DependencyCustomInXamarnFroms.Droid.Services;
using DependencyCustomInXamarnFroms.Services;
namespace DependencyCustomInXamarnFroms.Droid
{
[Activity(Label = "DependencyCustomInXamarnFroms", Icon = "@mipmap/icon", Theme = "@style/MainTheme", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation | ConfigChanges.UiMode | ConfigChanges.ScreenLayout | ConfigChanges.SmallestScreenSize )]
public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity
{
protected override void OnCreate(Bundle savedInstanceState)
{
TabLayoutResource = Resource.Layout.Tabbar;
ToolbarResource = Resource.Layout.Toolbar;
base.OnCreate(savedInstanceState);
Xamarin.Essentials.Platform.Init(this, savedInstanceState);
global::Xamarin.Forms.Forms.Init(this, savedInstanceState);
LoadApplication(new App(new AndroidInitializar()));
}
public override void OnRequestPermissionsResult(int requestCode, string[] permissions, [GeneratedEnum] Android.Content.PM.Permission[] grantResults)
{
Xamarin.Essentials.Platform.OnRequestPermissionsResult(requestCode, permissions, grantResults);
base.OnRequestPermissionsResult(requestCode, permissions, grantResults);
}
public class AndroidInitializar : IPlatformInitializer
{
public void RegisterTypes(IContainerRegistry containerRegistry)
{
containerRegistry.Register<IDeviceOrientationService, DeviceOrientationService>();
}
}
}
} | 40.8 | 292 | 0.727124 | [
"MIT"
] | walase01/PlatformServicesInXamarinForms | DependencyCustomInXamarnFroms/DependencyCustomInXamarnFroms.Android/MainActivity.cs | 1,838 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated from a template.
//
// Manual changes to this file may cause unexpected behavior in your application.
// Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace IM_PJ.Models
{
using System;
using System.Collections.Generic;
public partial class PreOrderDetail
{
public long PreOrderId { get; set; }
public long Id { get; set; }
public int ProductId { get; set; }
public Nullable<int> VariationId { get; set; }
public string SKU { get; set; }
public string Name { get; set; }
public string Avatar { get; set; }
public string Color { get; set; }
public string Size { get; set; }
public decimal CostOfGoods { get; set; }
public decimal Price { get; set; }
public Nullable<decimal> OldPrice { get; set; }
public int Quantity { get; set; }
public Nullable<decimal> TotalCostOfGoods { get; set; }
public Nullable<decimal> TotalPrice { get; set; }
public string CreatedBy { get; set; }
public System.DateTime CreatedDate { get; set; }
public string ModifiedBy { get; set; }
public System.DateTime ModifiedDate { get; set; }
public byte[] Timestamp { get; set; }
public decimal Discount { get; set; }
public decimal Total { get; set; }
public virtual PreOrder PreOrder { get; set; }
public virtual tbl_Product tbl_Product { get; set; }
public virtual tbl_ProductVariable tbl_ProductVariable { get; set; }
}
}
| 40.088889 | 85 | 0.567627 | [
"Apache-2.0"
] | phanhoanganh9x/ANNsys | IM_PJ/Models/PreOrderDetail.cs | 1,804 | C# |
// This file is part of Core WF which is licensed under the MIT license.
// See LICENSE file in the project root for full license information.
namespace CoreWf.Statements
{
using System.Collections.Generic;
using CoreWf;
using System.ComponentModel;
using Portable.Xaml.Markup;
[ContentProperty("Action")]
public sealed class FlowStep : FlowNode
{
public FlowStep()
{
}
[DefaultValue(null)]
public Activity Action
{
get;
set;
}
[DefaultValue(null)]
[DependsOn("Action")]
public FlowNode Next
{
get;
set;
}
internal override void OnOpen(Flowchart owner, NativeActivityMetadata metadata)
{
}
internal override void GetConnectedNodes(IList<FlowNode> connections)
{
if (Next != null)
{
connections.Add(Next);
}
}
internal override Activity ChildActivity
{
get { return Action; }
}
internal bool Execute(NativeActivityContext context, CompletionCallback onCompleted, out FlowNode nextNode)
{
if (Next == null)
{
if (TD.FlowchartNextNullIsEnabled())
{
TD.FlowchartNextNull(this.Owner.DisplayName);
}
}
if (Action == null)
{
nextNode = Next;
return true;
}
else
{
context.ScheduleActivity(Action, onCompleted);
nextNode = null;
return false;
}
}
}
}
| 23.931507 | 115 | 0.500286 | [
"MIT"
] | OIgnat/corewf | src/CoreWf/Statements/FlowStep.cs | 1,747 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// Этот код создан по шаблону.
//
// Изменения, вносимые в этот файл вручную, могут привести к непредвиденной работе приложения.
// Изменения, вносимые в этот файл вручную, будут перезаписаны при повторном создании кода.
// </auto-generated>
//------------------------------------------------------------------------------
namespace uzPro
{
using System;
using System.Collections.Generic;
public partial class Client
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public Client()
{
this.Protocols = new HashSet<Protocol>();
}
public int Id { get; set; }
public string Name { get; set; }
public System.DateTime BirthDate { get; set; }
public string Pasport { get; set; }
public string Reg { get; set; }
public string Tel { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<Protocol> Protocols { get; set; }
}
}
| 36.705882 | 128 | 0.571314 | [
"Apache-2.0"
] | galkin33rus/uzPro | uzPro/Client.cs | 1,421 | C# |
using System;
using System.Data.Entity.SqlServer;
using System.IO;
using System.Linq;
using System.Reflection;
using Kravat.EntityFramework6;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Newtonsoft.Json;
namespace Kravat.Tests
{
[TestClass]
public class DbContextReaderTests
{
private SqlProviderServices _instance = System.Data.Entity.SqlServer.SqlProviderServices.Instance;
[TestMethod]
public void ReadEntities_ReturnsReadEntityList()
{
var reader = new DbContextReader(@"path", "dllPath");
var entities = reader.ReadEntities();
var jsonData = JsonConvert.SerializeObject(entities, Formatting.Indented);
File.WriteAllText("types.json", jsonData);
}
}
}
| 25.966667 | 106 | 0.700899 | [
"MIT"
] | jaredswarts55/Kravat | Kravat.Tests/DbContextReaderTests.cs | 781 | C# |
using Holon.Security;
using Holon.Services;
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Text;
namespace Holon.Remoting
{
/// <summary>
/// Provides secure proxy extensions.
/// </summary>
public static class SecureExtensions
{
/// <summary>
/// Gets a secure RPC proxy for the provided interface.
/// </summary>
/// <typeparam name="IT">The interface type.</typeparam>
/// <param name="node">The node.</param>
/// <param name="address">The service address.</param>
/// <param name="configuration">The configuration.</param>
/// <returns></returns>
public static IT SecureProxy<IT>(this Node node, ServiceAddress address, SecureChannelConfiguration configuration) {
// create channel
SecureClientChannel channel = new SecureClientChannel(configuration);
channel.Reset(node, address);
// create proxy
return channel.Proxy<IT>();
}
/// <summary>
/// Gets a secure RPC proxy for the provided interface.
/// </summary>
/// <typeparam name="IT">The interface type.</typeparam>
/// <param name="node">The node.</param>
/// <param name="address">The service address.</param>
/// <param name="configuration">The configuration.</param>
/// <returns></returns>
public static IT SecureProxy<IT>(this Node node, string address, SecureChannelConfiguration configuration) {
return SecureProxy<IT>(node, new ServiceAddress(address), configuration);
}
}
}
| 36.466667 | 124 | 0.621572 | [
"Apache-2.0"
] | alandoherty/holon-net | src/Holon/Remoting/SecureExtensions.cs | 1,643 | C# |
/*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the acm-2015-12-08.normal.json service model.
*/
using System;
using System.Collections.Generic;
using Amazon.Runtime;
using Amazon.CertificateManager.Model;
namespace Amazon.CertificateManager
{
/// <summary>
/// Interface for accessing CertificateManager
///
/// Amazon Web Services Certificate Manager
/// <para>
/// You can use Amazon Web Services Certificate Manager (ACM) to manage SSL/TLS certificates
/// for your Amazon Web Services-based websites and applications. For more information
/// about using ACM, see the <a href="https://docs.aws.amazon.com/acm/latest/userguide/">Amazon
/// Web Services Certificate Manager User Guide</a>.
/// </para>
/// </summary>
public partial interface IAmazonCertificateManager : IAmazonService, IDisposable
{
#if BCL45 || AWS_ASYNC_ENUMERABLES_API
/// <summary>
/// Paginators for the service
/// </summary>
ICertificateManagerPaginatorFactory Paginators { get; }
#endif
#region AddTagsToCertificate
/// <summary>
/// Adds one or more tags to an ACM certificate. Tags are labels that you can use to identify
/// and organize your Amazon Web Services resources. Each tag consists of a <code>key</code>
/// and an optional <code>value</code>. You specify the certificate on input by its Amazon
/// Resource Name (ARN). You specify the tag by using a key-value pair.
///
///
/// <para>
/// You can apply a tag to just one certificate if you want to identify a specific characteristic
/// of that certificate, or you can apply the same tag to multiple certificates if you
/// want to filter for a common relationship among those certificates. Similarly, you
/// can apply the same tag to multiple resources if you want to specify a relationship
/// among those resources. For example, you can add the same tag to an ACM certificate
/// and an Elastic Load Balancing load balancer to indicate that they are both used by
/// the same website. For more information, see <a href="https://docs.aws.amazon.com/acm/latest/userguide/tags.html">Tagging
/// ACM certificates</a>.
/// </para>
///
/// <para>
/// To remove one or more tags, use the <a>RemoveTagsFromCertificate</a> action. To view
/// all of the tags that have been applied to the certificate, use the <a>ListTagsForCertificate</a>
/// action.
/// </para>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the AddTagsToCertificate service method.</param>
///
/// <returns>The response from the AddTagsToCertificate service method, as returned by CertificateManager.</returns>
/// <exception cref="Amazon.CertificateManager.Model.InvalidArnException">
/// The requested Amazon Resource Name (ARN) does not refer to an existing resource.
/// </exception>
/// <exception cref="Amazon.CertificateManager.Model.InvalidParameterException">
/// An input parameter was invalid.
/// </exception>
/// <exception cref="Amazon.CertificateManager.Model.InvalidTagException">
/// One or both of the values that make up the key-value pair is not valid. For example,
/// you cannot specify a tag value that begins with <code>aws:</code>.
/// </exception>
/// <exception cref="Amazon.CertificateManager.Model.ResourceNotFoundException">
/// The specified certificate cannot be found in the caller's account or the caller's
/// account cannot be found.
/// </exception>
/// <exception cref="Amazon.CertificateManager.Model.TagPolicyException">
/// A specified tag did not comply with an existing tag policy and was rejected.
/// </exception>
/// <exception cref="Amazon.CertificateManager.Model.ThrottlingException">
/// The request was denied because it exceeded a quota.
/// </exception>
/// <exception cref="Amazon.CertificateManager.Model.TooManyTagsException">
/// The request contains too many tags. Try the request again with fewer tags.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/acm-2015-12-08/AddTagsToCertificate">REST API Reference for AddTagsToCertificate Operation</seealso>
AddTagsToCertificateResponse AddTagsToCertificate(AddTagsToCertificateRequest request);
/// <summary>
/// Initiates the asynchronous execution of the AddTagsToCertificate operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the AddTagsToCertificate operation on AmazonCertificateManagerClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndAddTagsToCertificate
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/acm-2015-12-08/AddTagsToCertificate">REST API Reference for AddTagsToCertificate Operation</seealso>
IAsyncResult BeginAddTagsToCertificate(AddTagsToCertificateRequest request, AsyncCallback callback, object state);
/// <summary>
/// Finishes the asynchronous execution of the AddTagsToCertificate operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginAddTagsToCertificate.</param>
///
/// <returns>Returns a AddTagsToCertificateResult from CertificateManager.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/acm-2015-12-08/AddTagsToCertificate">REST API Reference for AddTagsToCertificate Operation</seealso>
AddTagsToCertificateResponse EndAddTagsToCertificate(IAsyncResult asyncResult);
#endregion
#region DeleteCertificate
/// <summary>
/// Deletes a certificate and its associated private key. If this action succeeds, the
/// certificate no longer appears in the list that can be displayed by calling the <a>ListCertificates</a>
/// action or be retrieved by calling the <a>GetCertificate</a> action. The certificate
/// will not be available for use by Amazon Web Services services integrated with ACM.
///
///
/// <note>
/// <para>
/// You cannot delete an ACM certificate that is being used by another Amazon Web Services
/// service. To delete a certificate that is in use, the certificate association must
/// first be removed.
/// </para>
/// </note>
/// </summary>
/// <param name="certificateArn">String that contains the ARN of the ACM certificate to be deleted. This must be of the form: <code>arn:aws:acm:region:123456789012:certificate/12345678-1234-1234-1234-123456789012</code> For more information about ARNs, see <a href="https://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html">Amazon Resource Names (ARNs)</a>.</param>
///
/// <returns>The response from the DeleteCertificate service method, as returned by CertificateManager.</returns>
/// <exception cref="Amazon.CertificateManager.Model.InvalidArnException">
/// The requested Amazon Resource Name (ARN) does not refer to an existing resource.
/// </exception>
/// <exception cref="Amazon.CertificateManager.Model.ResourceInUseException">
/// The certificate is in use by another Amazon Web Services service in the caller's account.
/// Remove the association and try again.
/// </exception>
/// <exception cref="Amazon.CertificateManager.Model.ResourceNotFoundException">
/// The specified certificate cannot be found in the caller's account or the caller's
/// account cannot be found.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/acm-2015-12-08/DeleteCertificate">REST API Reference for DeleteCertificate Operation</seealso>
DeleteCertificateResponse DeleteCertificate(string certificateArn);
/// <summary>
/// Deletes a certificate and its associated private key. If this action succeeds, the
/// certificate no longer appears in the list that can be displayed by calling the <a>ListCertificates</a>
/// action or be retrieved by calling the <a>GetCertificate</a> action. The certificate
/// will not be available for use by Amazon Web Services services integrated with ACM.
///
///
/// <note>
/// <para>
/// You cannot delete an ACM certificate that is being used by another Amazon Web Services
/// service. To delete a certificate that is in use, the certificate association must
/// first be removed.
/// </para>
/// </note>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the DeleteCertificate service method.</param>
///
/// <returns>The response from the DeleteCertificate service method, as returned by CertificateManager.</returns>
/// <exception cref="Amazon.CertificateManager.Model.InvalidArnException">
/// The requested Amazon Resource Name (ARN) does not refer to an existing resource.
/// </exception>
/// <exception cref="Amazon.CertificateManager.Model.ResourceInUseException">
/// The certificate is in use by another Amazon Web Services service in the caller's account.
/// Remove the association and try again.
/// </exception>
/// <exception cref="Amazon.CertificateManager.Model.ResourceNotFoundException">
/// The specified certificate cannot be found in the caller's account or the caller's
/// account cannot be found.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/acm-2015-12-08/DeleteCertificate">REST API Reference for DeleteCertificate Operation</seealso>
DeleteCertificateResponse DeleteCertificate(DeleteCertificateRequest request);
/// <summary>
/// Initiates the asynchronous execution of the DeleteCertificate operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the DeleteCertificate operation on AmazonCertificateManagerClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndDeleteCertificate
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/acm-2015-12-08/DeleteCertificate">REST API Reference for DeleteCertificate Operation</seealso>
IAsyncResult BeginDeleteCertificate(DeleteCertificateRequest request, AsyncCallback callback, object state);
/// <summary>
/// Finishes the asynchronous execution of the DeleteCertificate operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginDeleteCertificate.</param>
///
/// <returns>Returns a DeleteCertificateResult from CertificateManager.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/acm-2015-12-08/DeleteCertificate">REST API Reference for DeleteCertificate Operation</seealso>
DeleteCertificateResponse EndDeleteCertificate(IAsyncResult asyncResult);
#endregion
#region DescribeCertificate
/// <summary>
/// Returns detailed metadata about the specified ACM certificate.
/// </summary>
/// <param name="certificateArn">The Amazon Resource Name (ARN) of the ACM certificate. The ARN must have the following form: <code>arn:aws:acm:region:123456789012:certificate/12345678-1234-1234-1234-123456789012</code> For more information about ARNs, see <a href="https://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html">Amazon Resource Names (ARNs)</a>.</param>
///
/// <returns>The response from the DescribeCertificate service method, as returned by CertificateManager.</returns>
/// <exception cref="Amazon.CertificateManager.Model.InvalidArnException">
/// The requested Amazon Resource Name (ARN) does not refer to an existing resource.
/// </exception>
/// <exception cref="Amazon.CertificateManager.Model.ResourceNotFoundException">
/// The specified certificate cannot be found in the caller's account or the caller's
/// account cannot be found.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/acm-2015-12-08/DescribeCertificate">REST API Reference for DescribeCertificate Operation</seealso>
DescribeCertificateResponse DescribeCertificate(string certificateArn);
/// <summary>
/// Returns detailed metadata about the specified ACM certificate.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the DescribeCertificate service method.</param>
///
/// <returns>The response from the DescribeCertificate service method, as returned by CertificateManager.</returns>
/// <exception cref="Amazon.CertificateManager.Model.InvalidArnException">
/// The requested Amazon Resource Name (ARN) does not refer to an existing resource.
/// </exception>
/// <exception cref="Amazon.CertificateManager.Model.ResourceNotFoundException">
/// The specified certificate cannot be found in the caller's account or the caller's
/// account cannot be found.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/acm-2015-12-08/DescribeCertificate">REST API Reference for DescribeCertificate Operation</seealso>
DescribeCertificateResponse DescribeCertificate(DescribeCertificateRequest request);
/// <summary>
/// Initiates the asynchronous execution of the DescribeCertificate operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the DescribeCertificate operation on AmazonCertificateManagerClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndDescribeCertificate
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/acm-2015-12-08/DescribeCertificate">REST API Reference for DescribeCertificate Operation</seealso>
IAsyncResult BeginDescribeCertificate(DescribeCertificateRequest request, AsyncCallback callback, object state);
/// <summary>
/// Finishes the asynchronous execution of the DescribeCertificate operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginDescribeCertificate.</param>
///
/// <returns>Returns a DescribeCertificateResult from CertificateManager.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/acm-2015-12-08/DescribeCertificate">REST API Reference for DescribeCertificate Operation</seealso>
DescribeCertificateResponse EndDescribeCertificate(IAsyncResult asyncResult);
#endregion
#region ExportCertificate
/// <summary>
/// Exports a private certificate issued by a private certificate authority (CA) for use
/// anywhere. The exported file contains the certificate, the certificate chain, and the
/// encrypted private 2048-bit RSA key associated with the public key that is embedded
/// in the certificate. For security, you must assign a passphrase for the private key
/// when exporting it.
///
///
/// <para>
/// For information about exporting and formatting a certificate using the ACM console
/// or CLI, see <a href="https://docs.aws.amazon.com/acm/latest/userguide/gs-acm-export-private.html">Export
/// a Private Certificate</a>.
/// </para>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the ExportCertificate service method.</param>
///
/// <returns>The response from the ExportCertificate service method, as returned by CertificateManager.</returns>
/// <exception cref="Amazon.CertificateManager.Model.InvalidArnException">
/// The requested Amazon Resource Name (ARN) does not refer to an existing resource.
/// </exception>
/// <exception cref="Amazon.CertificateManager.Model.RequestInProgressException">
/// The certificate request is in process and the certificate in your account has not
/// yet been issued.
/// </exception>
/// <exception cref="Amazon.CertificateManager.Model.ResourceNotFoundException">
/// The specified certificate cannot be found in the caller's account or the caller's
/// account cannot be found.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/acm-2015-12-08/ExportCertificate">REST API Reference for ExportCertificate Operation</seealso>
ExportCertificateResponse ExportCertificate(ExportCertificateRequest request);
/// <summary>
/// Initiates the asynchronous execution of the ExportCertificate operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the ExportCertificate operation on AmazonCertificateManagerClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndExportCertificate
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/acm-2015-12-08/ExportCertificate">REST API Reference for ExportCertificate Operation</seealso>
IAsyncResult BeginExportCertificate(ExportCertificateRequest request, AsyncCallback callback, object state);
/// <summary>
/// Finishes the asynchronous execution of the ExportCertificate operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginExportCertificate.</param>
///
/// <returns>Returns a ExportCertificateResult from CertificateManager.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/acm-2015-12-08/ExportCertificate">REST API Reference for ExportCertificate Operation</seealso>
ExportCertificateResponse EndExportCertificate(IAsyncResult asyncResult);
#endregion
#region GetAccountConfiguration
/// <summary>
/// Returns the account configuration options associated with an Amazon Web Services account.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the GetAccountConfiguration service method.</param>
///
/// <returns>The response from the GetAccountConfiguration service method, as returned by CertificateManager.</returns>
/// <exception cref="Amazon.CertificateManager.Model.AccessDeniedException">
/// You do not have access required to perform this action.
/// </exception>
/// <exception cref="Amazon.CertificateManager.Model.ThrottlingException">
/// The request was denied because it exceeded a quota.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/acm-2015-12-08/GetAccountConfiguration">REST API Reference for GetAccountConfiguration Operation</seealso>
GetAccountConfigurationResponse GetAccountConfiguration(GetAccountConfigurationRequest request);
/// <summary>
/// Initiates the asynchronous execution of the GetAccountConfiguration operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the GetAccountConfiguration operation on AmazonCertificateManagerClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndGetAccountConfiguration
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/acm-2015-12-08/GetAccountConfiguration">REST API Reference for GetAccountConfiguration Operation</seealso>
IAsyncResult BeginGetAccountConfiguration(GetAccountConfigurationRequest request, AsyncCallback callback, object state);
/// <summary>
/// Finishes the asynchronous execution of the GetAccountConfiguration operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginGetAccountConfiguration.</param>
///
/// <returns>Returns a GetAccountConfigurationResult from CertificateManager.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/acm-2015-12-08/GetAccountConfiguration">REST API Reference for GetAccountConfiguration Operation</seealso>
GetAccountConfigurationResponse EndGetAccountConfiguration(IAsyncResult asyncResult);
#endregion
#region GetCertificate
/// <summary>
/// Retrieves an Amazon-issued certificate and its certificate chain. The chain consists
/// of the certificate of the issuing CA and the intermediate certificates of any other
/// subordinate CAs. All of the certificates are base64 encoded. You can use <a href="https://wiki.openssl.org/index.php/Command_Line_Utilities">OpenSSL</a>
/// to decode the certificates and inspect individual fields.
/// </summary>
/// <param name="certificateArn">String that contains a certificate ARN in the following format: <code>arn:aws:acm:region:123456789012:certificate/12345678-1234-1234-1234-123456789012</code> For more information about ARNs, see <a href="https://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html">Amazon Resource Names (ARNs)</a>.</param>
///
/// <returns>The response from the GetCertificate service method, as returned by CertificateManager.</returns>
/// <exception cref="Amazon.CertificateManager.Model.InvalidArnException">
/// The requested Amazon Resource Name (ARN) does not refer to an existing resource.
/// </exception>
/// <exception cref="Amazon.CertificateManager.Model.RequestInProgressException">
/// The certificate request is in process and the certificate in your account has not
/// yet been issued.
/// </exception>
/// <exception cref="Amazon.CertificateManager.Model.ResourceNotFoundException">
/// The specified certificate cannot be found in the caller's account or the caller's
/// account cannot be found.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/acm-2015-12-08/GetCertificate">REST API Reference for GetCertificate Operation</seealso>
GetCertificateResponse GetCertificate(string certificateArn);
/// <summary>
/// Retrieves an Amazon-issued certificate and its certificate chain. The chain consists
/// of the certificate of the issuing CA and the intermediate certificates of any other
/// subordinate CAs. All of the certificates are base64 encoded. You can use <a href="https://wiki.openssl.org/index.php/Command_Line_Utilities">OpenSSL</a>
/// to decode the certificates and inspect individual fields.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the GetCertificate service method.</param>
///
/// <returns>The response from the GetCertificate service method, as returned by CertificateManager.</returns>
/// <exception cref="Amazon.CertificateManager.Model.InvalidArnException">
/// The requested Amazon Resource Name (ARN) does not refer to an existing resource.
/// </exception>
/// <exception cref="Amazon.CertificateManager.Model.RequestInProgressException">
/// The certificate request is in process and the certificate in your account has not
/// yet been issued.
/// </exception>
/// <exception cref="Amazon.CertificateManager.Model.ResourceNotFoundException">
/// The specified certificate cannot be found in the caller's account or the caller's
/// account cannot be found.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/acm-2015-12-08/GetCertificate">REST API Reference for GetCertificate Operation</seealso>
GetCertificateResponse GetCertificate(GetCertificateRequest request);
/// <summary>
/// Initiates the asynchronous execution of the GetCertificate operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the GetCertificate operation on AmazonCertificateManagerClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndGetCertificate
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/acm-2015-12-08/GetCertificate">REST API Reference for GetCertificate Operation</seealso>
IAsyncResult BeginGetCertificate(GetCertificateRequest request, AsyncCallback callback, object state);
/// <summary>
/// Finishes the asynchronous execution of the GetCertificate operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginGetCertificate.</param>
///
/// <returns>Returns a GetCertificateResult from CertificateManager.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/acm-2015-12-08/GetCertificate">REST API Reference for GetCertificate Operation</seealso>
GetCertificateResponse EndGetCertificate(IAsyncResult asyncResult);
#endregion
#region ImportCertificate
/// <summary>
/// Imports a certificate into Amazon Web Services Certificate Manager (ACM) to use with
/// services that are integrated with ACM. Note that <a href="https://docs.aws.amazon.com/acm/latest/userguide/acm-services.html">integrated
/// services</a> allow only certificate types and keys they support to be associated with
/// their resources. Further, their support differs depending on whether the certificate
/// is imported into IAM or into ACM. For more information, see the documentation for
/// each service. For more information about importing certificates into ACM, see <a href="https://docs.aws.amazon.com/acm/latest/userguide/import-certificate.html">Importing
/// Certificates</a> in the <i>Amazon Web Services Certificate Manager User Guide</i>.
///
///
/// <note>
/// <para>
/// ACM does not provide <a href="https://docs.aws.amazon.com/acm/latest/userguide/acm-renewal.html">managed
/// renewal</a> for certificates that you import.
/// </para>
/// </note>
/// <para>
/// Note the following guidelines when importing third party certificates:
/// </para>
/// <ul> <li>
/// <para>
/// You must enter the private key that matches the certificate you are importing.
/// </para>
/// </li> <li>
/// <para>
/// The private key must be unencrypted. You cannot import a private key that is protected
/// by a password or a passphrase.
/// </para>
/// </li> <li>
/// <para>
/// The private key must be no larger than 5 KB (5,120 bytes).
/// </para>
/// </li> <li>
/// <para>
/// If the certificate you are importing is not self-signed, you must enter its certificate
/// chain.
/// </para>
/// </li> <li>
/// <para>
/// If a certificate chain is included, the issuer must be the subject of one of the certificates
/// in the chain.
/// </para>
/// </li> <li>
/// <para>
/// The certificate, private key, and certificate chain must be PEM-encoded.
/// </para>
/// </li> <li>
/// <para>
/// The current time must be between the <code>Not Before</code> and <code>Not After</code>
/// certificate fields.
/// </para>
/// </li> <li>
/// <para>
/// The <code>Issuer</code> field must not be empty.
/// </para>
/// </li> <li>
/// <para>
/// The OCSP authority URL, if present, must not exceed 1000 characters.
/// </para>
/// </li> <li>
/// <para>
/// To import a new certificate, omit the <code>CertificateArn</code> argument. Include
/// this argument only when you want to replace a previously imported certificate.
/// </para>
/// </li> <li>
/// <para>
/// When you import a certificate by using the CLI, you must specify the certificate,
/// the certificate chain, and the private key by their file names preceded by <code>fileb://</code>.
/// For example, you can specify a certificate saved in the <code>C:\temp</code> folder
/// as <code>fileb://C:\temp\certificate_to_import.pem</code>. If you are making an HTTP
/// or HTTPS Query request, include these arguments as BLOBs.
/// </para>
/// </li> <li>
/// <para>
/// When you import a certificate by using an SDK, you must specify the certificate, the
/// certificate chain, and the private key files in the manner required by the programming
/// language you're using.
/// </para>
/// </li> <li>
/// <para>
/// The cryptographic algorithm of an imported certificate must match the algorithm of
/// the signing CA. For example, if the signing CA key type is RSA, then the certificate
/// key type must also be RSA.
/// </para>
/// </li> </ul>
/// <para>
/// This operation returns the <a href="https://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html">Amazon
/// Resource Name (ARN)</a> of the imported certificate.
/// </para>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the ImportCertificate service method.</param>
///
/// <returns>The response from the ImportCertificate service method, as returned by CertificateManager.</returns>
/// <exception cref="Amazon.CertificateManager.Model.InvalidArnException">
/// The requested Amazon Resource Name (ARN) does not refer to an existing resource.
/// </exception>
/// <exception cref="Amazon.CertificateManager.Model.InvalidParameterException">
/// An input parameter was invalid.
/// </exception>
/// <exception cref="Amazon.CertificateManager.Model.InvalidTagException">
/// One or both of the values that make up the key-value pair is not valid. For example,
/// you cannot specify a tag value that begins with <code>aws:</code>.
/// </exception>
/// <exception cref="Amazon.CertificateManager.Model.LimitExceededException">
/// An ACM quota has been exceeded.
/// </exception>
/// <exception cref="Amazon.CertificateManager.Model.ResourceNotFoundException">
/// The specified certificate cannot be found in the caller's account or the caller's
/// account cannot be found.
/// </exception>
/// <exception cref="Amazon.CertificateManager.Model.TagPolicyException">
/// A specified tag did not comply with an existing tag policy and was rejected.
/// </exception>
/// <exception cref="Amazon.CertificateManager.Model.TooManyTagsException">
/// The request contains too many tags. Try the request again with fewer tags.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/acm-2015-12-08/ImportCertificate">REST API Reference for ImportCertificate Operation</seealso>
ImportCertificateResponse ImportCertificate(ImportCertificateRequest request);
/// <summary>
/// Initiates the asynchronous execution of the ImportCertificate operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the ImportCertificate operation on AmazonCertificateManagerClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndImportCertificate
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/acm-2015-12-08/ImportCertificate">REST API Reference for ImportCertificate Operation</seealso>
IAsyncResult BeginImportCertificate(ImportCertificateRequest request, AsyncCallback callback, object state);
/// <summary>
/// Finishes the asynchronous execution of the ImportCertificate operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginImportCertificate.</param>
///
/// <returns>Returns a ImportCertificateResult from CertificateManager.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/acm-2015-12-08/ImportCertificate">REST API Reference for ImportCertificate Operation</seealso>
ImportCertificateResponse EndImportCertificate(IAsyncResult asyncResult);
#endregion
#region ListCertificates
/// <summary>
/// Retrieves a list of certificate ARNs and domain names. You can request that only certificates
/// that match a specific status be listed. You can also filter by specific attributes
/// of the certificate. Default filtering returns only <code>RSA_2048</code> certificates.
/// For more information, see <a>Filters</a>.
/// </summary>
///
/// <returns>The response from the ListCertificates service method, as returned by CertificateManager.</returns>
/// <exception cref="Amazon.CertificateManager.Model.InvalidArgsException">
/// One or more of of request parameters specified is not valid.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/acm-2015-12-08/ListCertificates">REST API Reference for ListCertificates Operation</seealso>
ListCertificatesResponse ListCertificates();
/// <summary>
/// Retrieves a list of certificate ARNs and domain names. You can request that only certificates
/// that match a specific status be listed. You can also filter by specific attributes
/// of the certificate. Default filtering returns only <code>RSA_2048</code> certificates.
/// For more information, see <a>Filters</a>.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the ListCertificates service method.</param>
///
/// <returns>The response from the ListCertificates service method, as returned by CertificateManager.</returns>
/// <exception cref="Amazon.CertificateManager.Model.InvalidArgsException">
/// One or more of of request parameters specified is not valid.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/acm-2015-12-08/ListCertificates">REST API Reference for ListCertificates Operation</seealso>
ListCertificatesResponse ListCertificates(ListCertificatesRequest request);
/// <summary>
/// Initiates the asynchronous execution of the ListCertificates operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the ListCertificates operation on AmazonCertificateManagerClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndListCertificates
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/acm-2015-12-08/ListCertificates">REST API Reference for ListCertificates Operation</seealso>
IAsyncResult BeginListCertificates(ListCertificatesRequest request, AsyncCallback callback, object state);
/// <summary>
/// Finishes the asynchronous execution of the ListCertificates operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginListCertificates.</param>
///
/// <returns>Returns a ListCertificatesResult from CertificateManager.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/acm-2015-12-08/ListCertificates">REST API Reference for ListCertificates Operation</seealso>
ListCertificatesResponse EndListCertificates(IAsyncResult asyncResult);
#endregion
#region ListTagsForCertificate
/// <summary>
/// Lists the tags that have been applied to the ACM certificate. Use the certificate's
/// Amazon Resource Name (ARN) to specify the certificate. To add a tag to an ACM certificate,
/// use the <a>AddTagsToCertificate</a> action. To delete a tag, use the <a>RemoveTagsFromCertificate</a>
/// action.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the ListTagsForCertificate service method.</param>
///
/// <returns>The response from the ListTagsForCertificate service method, as returned by CertificateManager.</returns>
/// <exception cref="Amazon.CertificateManager.Model.InvalidArnException">
/// The requested Amazon Resource Name (ARN) does not refer to an existing resource.
/// </exception>
/// <exception cref="Amazon.CertificateManager.Model.ResourceNotFoundException">
/// The specified certificate cannot be found in the caller's account or the caller's
/// account cannot be found.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/acm-2015-12-08/ListTagsForCertificate">REST API Reference for ListTagsForCertificate Operation</seealso>
ListTagsForCertificateResponse ListTagsForCertificate(ListTagsForCertificateRequest request);
/// <summary>
/// Initiates the asynchronous execution of the ListTagsForCertificate operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the ListTagsForCertificate operation on AmazonCertificateManagerClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndListTagsForCertificate
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/acm-2015-12-08/ListTagsForCertificate">REST API Reference for ListTagsForCertificate Operation</seealso>
IAsyncResult BeginListTagsForCertificate(ListTagsForCertificateRequest request, AsyncCallback callback, object state);
/// <summary>
/// Finishes the asynchronous execution of the ListTagsForCertificate operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginListTagsForCertificate.</param>
///
/// <returns>Returns a ListTagsForCertificateResult from CertificateManager.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/acm-2015-12-08/ListTagsForCertificate">REST API Reference for ListTagsForCertificate Operation</seealso>
ListTagsForCertificateResponse EndListTagsForCertificate(IAsyncResult asyncResult);
#endregion
#region PutAccountConfiguration
/// <summary>
/// Adds or modifies account-level configurations in ACM.
///
///
/// <para>
/// The supported configuration option is <code>DaysBeforeExpiry</code>. This option specifies
/// the number of days prior to certificate expiration when ACM starts generating <code>EventBridge</code>
/// events. ACM sends one event per day per certificate until the certificate expires.
/// By default, accounts receive events starting 45 days before certificate expiration.
/// </para>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the PutAccountConfiguration service method.</param>
///
/// <returns>The response from the PutAccountConfiguration service method, as returned by CertificateManager.</returns>
/// <exception cref="Amazon.CertificateManager.Model.AccessDeniedException">
/// You do not have access required to perform this action.
/// </exception>
/// <exception cref="Amazon.CertificateManager.Model.ConflictException">
/// You are trying to update a resource or configuration that is already being created
/// or updated. Wait for the previous operation to finish and try again.
/// </exception>
/// <exception cref="Amazon.CertificateManager.Model.ThrottlingException">
/// The request was denied because it exceeded a quota.
/// </exception>
/// <exception cref="Amazon.CertificateManager.Model.ValidationException">
/// The supplied input failed to satisfy constraints of an Amazon Web Services service.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/acm-2015-12-08/PutAccountConfiguration">REST API Reference for PutAccountConfiguration Operation</seealso>
PutAccountConfigurationResponse PutAccountConfiguration(PutAccountConfigurationRequest request);
/// <summary>
/// Initiates the asynchronous execution of the PutAccountConfiguration operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the PutAccountConfiguration operation on AmazonCertificateManagerClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndPutAccountConfiguration
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/acm-2015-12-08/PutAccountConfiguration">REST API Reference for PutAccountConfiguration Operation</seealso>
IAsyncResult BeginPutAccountConfiguration(PutAccountConfigurationRequest request, AsyncCallback callback, object state);
/// <summary>
/// Finishes the asynchronous execution of the PutAccountConfiguration operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginPutAccountConfiguration.</param>
///
/// <returns>Returns a PutAccountConfigurationResult from CertificateManager.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/acm-2015-12-08/PutAccountConfiguration">REST API Reference for PutAccountConfiguration Operation</seealso>
PutAccountConfigurationResponse EndPutAccountConfiguration(IAsyncResult asyncResult);
#endregion
#region RemoveTagsFromCertificate
/// <summary>
/// Remove one or more tags from an ACM certificate. A tag consists of a key-value pair.
/// If you do not specify the value portion of the tag when calling this function, the
/// tag will be removed regardless of value. If you specify a value, the tag is removed
/// only if it is associated with the specified value.
///
///
/// <para>
/// To add tags to a certificate, use the <a>AddTagsToCertificate</a> action. To view
/// all of the tags that have been applied to a specific ACM certificate, use the <a>ListTagsForCertificate</a>
/// action.
/// </para>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the RemoveTagsFromCertificate service method.</param>
///
/// <returns>The response from the RemoveTagsFromCertificate service method, as returned by CertificateManager.</returns>
/// <exception cref="Amazon.CertificateManager.Model.InvalidArnException">
/// The requested Amazon Resource Name (ARN) does not refer to an existing resource.
/// </exception>
/// <exception cref="Amazon.CertificateManager.Model.InvalidParameterException">
/// An input parameter was invalid.
/// </exception>
/// <exception cref="Amazon.CertificateManager.Model.InvalidTagException">
/// One or both of the values that make up the key-value pair is not valid. For example,
/// you cannot specify a tag value that begins with <code>aws:</code>.
/// </exception>
/// <exception cref="Amazon.CertificateManager.Model.ResourceNotFoundException">
/// The specified certificate cannot be found in the caller's account or the caller's
/// account cannot be found.
/// </exception>
/// <exception cref="Amazon.CertificateManager.Model.TagPolicyException">
/// A specified tag did not comply with an existing tag policy and was rejected.
/// </exception>
/// <exception cref="Amazon.CertificateManager.Model.ThrottlingException">
/// The request was denied because it exceeded a quota.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/acm-2015-12-08/RemoveTagsFromCertificate">REST API Reference for RemoveTagsFromCertificate Operation</seealso>
RemoveTagsFromCertificateResponse RemoveTagsFromCertificate(RemoveTagsFromCertificateRequest request);
/// <summary>
/// Initiates the asynchronous execution of the RemoveTagsFromCertificate operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the RemoveTagsFromCertificate operation on AmazonCertificateManagerClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndRemoveTagsFromCertificate
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/acm-2015-12-08/RemoveTagsFromCertificate">REST API Reference for RemoveTagsFromCertificate Operation</seealso>
IAsyncResult BeginRemoveTagsFromCertificate(RemoveTagsFromCertificateRequest request, AsyncCallback callback, object state);
/// <summary>
/// Finishes the asynchronous execution of the RemoveTagsFromCertificate operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginRemoveTagsFromCertificate.</param>
///
/// <returns>Returns a RemoveTagsFromCertificateResult from CertificateManager.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/acm-2015-12-08/RemoveTagsFromCertificate">REST API Reference for RemoveTagsFromCertificate Operation</seealso>
RemoveTagsFromCertificateResponse EndRemoveTagsFromCertificate(IAsyncResult asyncResult);
#endregion
#region RenewCertificate
/// <summary>
/// Renews an eligible ACM certificate. At this time, only exported private certificates
/// can be renewed with this operation. In order to renew your ACM PCA certificates with
/// ACM, you must first <a href="https://docs.aws.amazon.com/acm-pca/latest/userguide/PcaPermissions.html">grant
/// the ACM service principal permission to do so</a>. For more information, see <a href="https://docs.aws.amazon.com/acm/latest/userguide/manual-renewal.html">Testing
/// Managed Renewal</a> in the ACM User Guide.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the RenewCertificate service method.</param>
///
/// <returns>The response from the RenewCertificate service method, as returned by CertificateManager.</returns>
/// <exception cref="Amazon.CertificateManager.Model.InvalidArnException">
/// The requested Amazon Resource Name (ARN) does not refer to an existing resource.
/// </exception>
/// <exception cref="Amazon.CertificateManager.Model.ResourceNotFoundException">
/// The specified certificate cannot be found in the caller's account or the caller's
/// account cannot be found.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/acm-2015-12-08/RenewCertificate">REST API Reference for RenewCertificate Operation</seealso>
RenewCertificateResponse RenewCertificate(RenewCertificateRequest request);
/// <summary>
/// Initiates the asynchronous execution of the RenewCertificate operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the RenewCertificate operation on AmazonCertificateManagerClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndRenewCertificate
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/acm-2015-12-08/RenewCertificate">REST API Reference for RenewCertificate Operation</seealso>
IAsyncResult BeginRenewCertificate(RenewCertificateRequest request, AsyncCallback callback, object state);
/// <summary>
/// Finishes the asynchronous execution of the RenewCertificate operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginRenewCertificate.</param>
///
/// <returns>Returns a RenewCertificateResult from CertificateManager.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/acm-2015-12-08/RenewCertificate">REST API Reference for RenewCertificate Operation</seealso>
RenewCertificateResponse EndRenewCertificate(IAsyncResult asyncResult);
#endregion
#region RequestCertificate
/// <summary>
/// Requests an ACM certificate for use with other Amazon Web Services services. To request
/// an ACM certificate, you must specify a fully qualified domain name (FQDN) in the <code>DomainName</code>
/// parameter. You can also specify additional FQDNs in the <code>SubjectAlternativeNames</code>
/// parameter.
///
///
/// <para>
/// If you are requesting a private certificate, domain validation is not required. If
/// you are requesting a public certificate, each domain name that you specify must be
/// validated to verify that you own or control the domain. You can use <a href="https://docs.aws.amazon.com/acm/latest/userguide/gs-acm-validate-dns.html">DNS
/// validation</a> or <a href="https://docs.aws.amazon.com/acm/latest/userguide/gs-acm-validate-email.html">email
/// validation</a>. We recommend that you use DNS validation. ACM issues public certificates
/// after receiving approval from the domain owner.
/// </para>
/// <note>
/// <para>
/// ACM behavior differs from the <a href="https://tools.ietf.org/html/rfc6125#appendix-B.2">https://tools.ietf.org/html/rfc6125#appendix-B.2</a>RFC
/// 6125 specification of the certificate validation process. first checks for a subject
/// alternative name, and, if it finds one, ignores the common name (CN)
/// </para>
/// </note>
/// </summary>
/// <param name="domainName"> Fully qualified domain name (FQDN), such as www.example.com, that you want to secure with an ACM certificate. Use an asterisk (*) to create a wildcard certificate that protects several sites in the same domain. For example, *.example.com protects www.example.com, site.example.com, and images.example.com. The first domain name you enter cannot exceed 64 octets, including periods. Each subsequent Subject Alternative Name (SAN), however, can be up to 253 octets in length. </param>
///
/// <returns>The response from the RequestCertificate service method, as returned by CertificateManager.</returns>
/// <exception cref="Amazon.CertificateManager.Model.InvalidArnException">
/// The requested Amazon Resource Name (ARN) does not refer to an existing resource.
/// </exception>
/// <exception cref="Amazon.CertificateManager.Model.InvalidDomainValidationOptionsException">
/// One or more values in the <a>DomainValidationOption</a> structure is incorrect.
/// </exception>
/// <exception cref="Amazon.CertificateManager.Model.InvalidParameterException">
/// An input parameter was invalid.
/// </exception>
/// <exception cref="Amazon.CertificateManager.Model.InvalidTagException">
/// One or both of the values that make up the key-value pair is not valid. For example,
/// you cannot specify a tag value that begins with <code>aws:</code>.
/// </exception>
/// <exception cref="Amazon.CertificateManager.Model.LimitExceededException">
/// An ACM quota has been exceeded.
/// </exception>
/// <exception cref="Amazon.CertificateManager.Model.TagPolicyException">
/// A specified tag did not comply with an existing tag policy and was rejected.
/// </exception>
/// <exception cref="Amazon.CertificateManager.Model.TooManyTagsException">
/// The request contains too many tags. Try the request again with fewer tags.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/acm-2015-12-08/RequestCertificate">REST API Reference for RequestCertificate Operation</seealso>
RequestCertificateResponse RequestCertificate(string domainName);
/// <summary>
/// Requests an ACM certificate for use with other Amazon Web Services services. To request
/// an ACM certificate, you must specify a fully qualified domain name (FQDN) in the <code>DomainName</code>
/// parameter. You can also specify additional FQDNs in the <code>SubjectAlternativeNames</code>
/// parameter.
///
///
/// <para>
/// If you are requesting a private certificate, domain validation is not required. If
/// you are requesting a public certificate, each domain name that you specify must be
/// validated to verify that you own or control the domain. You can use <a href="https://docs.aws.amazon.com/acm/latest/userguide/gs-acm-validate-dns.html">DNS
/// validation</a> or <a href="https://docs.aws.amazon.com/acm/latest/userguide/gs-acm-validate-email.html">email
/// validation</a>. We recommend that you use DNS validation. ACM issues public certificates
/// after receiving approval from the domain owner.
/// </para>
/// <note>
/// <para>
/// ACM behavior differs from the <a href="https://tools.ietf.org/html/rfc6125#appendix-B.2">https://tools.ietf.org/html/rfc6125#appendix-B.2</a>RFC
/// 6125 specification of the certificate validation process. first checks for a subject
/// alternative name, and, if it finds one, ignores the common name (CN)
/// </para>
/// </note>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the RequestCertificate service method.</param>
///
/// <returns>The response from the RequestCertificate service method, as returned by CertificateManager.</returns>
/// <exception cref="Amazon.CertificateManager.Model.InvalidArnException">
/// The requested Amazon Resource Name (ARN) does not refer to an existing resource.
/// </exception>
/// <exception cref="Amazon.CertificateManager.Model.InvalidDomainValidationOptionsException">
/// One or more values in the <a>DomainValidationOption</a> structure is incorrect.
/// </exception>
/// <exception cref="Amazon.CertificateManager.Model.InvalidParameterException">
/// An input parameter was invalid.
/// </exception>
/// <exception cref="Amazon.CertificateManager.Model.InvalidTagException">
/// One or both of the values that make up the key-value pair is not valid. For example,
/// you cannot specify a tag value that begins with <code>aws:</code>.
/// </exception>
/// <exception cref="Amazon.CertificateManager.Model.LimitExceededException">
/// An ACM quota has been exceeded.
/// </exception>
/// <exception cref="Amazon.CertificateManager.Model.TagPolicyException">
/// A specified tag did not comply with an existing tag policy and was rejected.
/// </exception>
/// <exception cref="Amazon.CertificateManager.Model.TooManyTagsException">
/// The request contains too many tags. Try the request again with fewer tags.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/acm-2015-12-08/RequestCertificate">REST API Reference for RequestCertificate Operation</seealso>
RequestCertificateResponse RequestCertificate(RequestCertificateRequest request);
/// <summary>
/// Initiates the asynchronous execution of the RequestCertificate operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the RequestCertificate operation on AmazonCertificateManagerClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndRequestCertificate
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/acm-2015-12-08/RequestCertificate">REST API Reference for RequestCertificate Operation</seealso>
IAsyncResult BeginRequestCertificate(RequestCertificateRequest request, AsyncCallback callback, object state);
/// <summary>
/// Finishes the asynchronous execution of the RequestCertificate operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginRequestCertificate.</param>
///
/// <returns>Returns a RequestCertificateResult from CertificateManager.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/acm-2015-12-08/RequestCertificate">REST API Reference for RequestCertificate Operation</seealso>
RequestCertificateResponse EndRequestCertificate(IAsyncResult asyncResult);
#endregion
#region ResendValidationEmail
/// <summary>
/// Resends the email that requests domain ownership validation. The domain owner or an
/// authorized representative must approve the ACM certificate before it can be issued.
/// The certificate can be approved by clicking a link in the mail to navigate to the
/// Amazon certificate approval website and then clicking <b>I Approve</b>. However, the
/// validation email can be blocked by spam filters. Therefore, if you do not receive
/// the original mail, you can request that the mail be resent within 72 hours of requesting
/// the ACM certificate. If more than 72 hours have elapsed since your original request
/// or since your last attempt to resend validation mail, you must request a new certificate.
/// For more information about setting up your contact email addresses, see <a href="https://docs.aws.amazon.com/acm/latest/userguide/setup-email.html">Configure
/// Email for your Domain</a>.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the ResendValidationEmail service method.</param>
///
/// <returns>The response from the ResendValidationEmail service method, as returned by CertificateManager.</returns>
/// <exception cref="Amazon.CertificateManager.Model.InvalidArnException">
/// The requested Amazon Resource Name (ARN) does not refer to an existing resource.
/// </exception>
/// <exception cref="Amazon.CertificateManager.Model.InvalidDomainValidationOptionsException">
/// One or more values in the <a>DomainValidationOption</a> structure is incorrect.
/// </exception>
/// <exception cref="Amazon.CertificateManager.Model.InvalidStateException">
/// Processing has reached an invalid state.
/// </exception>
/// <exception cref="Amazon.CertificateManager.Model.ResourceNotFoundException">
/// The specified certificate cannot be found in the caller's account or the caller's
/// account cannot be found.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/acm-2015-12-08/ResendValidationEmail">REST API Reference for ResendValidationEmail Operation</seealso>
ResendValidationEmailResponse ResendValidationEmail(ResendValidationEmailRequest request);
/// <summary>
/// Initiates the asynchronous execution of the ResendValidationEmail operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the ResendValidationEmail operation on AmazonCertificateManagerClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndResendValidationEmail
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/acm-2015-12-08/ResendValidationEmail">REST API Reference for ResendValidationEmail Operation</seealso>
IAsyncResult BeginResendValidationEmail(ResendValidationEmailRequest request, AsyncCallback callback, object state);
/// <summary>
/// Finishes the asynchronous execution of the ResendValidationEmail operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginResendValidationEmail.</param>
///
/// <returns>Returns a ResendValidationEmailResult from CertificateManager.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/acm-2015-12-08/ResendValidationEmail">REST API Reference for ResendValidationEmail Operation</seealso>
ResendValidationEmailResponse EndResendValidationEmail(IAsyncResult asyncResult);
#endregion
#region UpdateCertificateOptions
/// <summary>
/// Updates a certificate. Currently, you can use this function to specify whether to
/// opt in to or out of recording your certificate in a certificate transparency log.
/// For more information, see <a href="https://docs.aws.amazon.com/acm/latest/userguide/acm-bestpractices.html#best-practices-transparency">
/// Opting Out of Certificate Transparency Logging</a>.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the UpdateCertificateOptions service method.</param>
///
/// <returns>The response from the UpdateCertificateOptions service method, as returned by CertificateManager.</returns>
/// <exception cref="Amazon.CertificateManager.Model.InvalidArnException">
/// The requested Amazon Resource Name (ARN) does not refer to an existing resource.
/// </exception>
/// <exception cref="Amazon.CertificateManager.Model.InvalidStateException">
/// Processing has reached an invalid state.
/// </exception>
/// <exception cref="Amazon.CertificateManager.Model.LimitExceededException">
/// An ACM quota has been exceeded.
/// </exception>
/// <exception cref="Amazon.CertificateManager.Model.ResourceNotFoundException">
/// The specified certificate cannot be found in the caller's account or the caller's
/// account cannot be found.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/acm-2015-12-08/UpdateCertificateOptions">REST API Reference for UpdateCertificateOptions Operation</seealso>
UpdateCertificateOptionsResponse UpdateCertificateOptions(UpdateCertificateOptionsRequest request);
/// <summary>
/// Initiates the asynchronous execution of the UpdateCertificateOptions operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the UpdateCertificateOptions operation on AmazonCertificateManagerClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndUpdateCertificateOptions
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/acm-2015-12-08/UpdateCertificateOptions">REST API Reference for UpdateCertificateOptions Operation</seealso>
IAsyncResult BeginUpdateCertificateOptions(UpdateCertificateOptionsRequest request, AsyncCallback callback, object state);
/// <summary>
/// Finishes the asynchronous execution of the UpdateCertificateOptions operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginUpdateCertificateOptions.</param>
///
/// <returns>Returns a UpdateCertificateOptionsResult from CertificateManager.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/acm-2015-12-08/UpdateCertificateOptions">REST API Reference for UpdateCertificateOptions Operation</seealso>
UpdateCertificateOptionsResponse EndUpdateCertificateOptions(IAsyncResult asyncResult);
#endregion
}
} | 62.214651 | 522 | 0.679545 | [
"Apache-2.0"
] | ChristopherButtars/aws-sdk-net | sdk/src/Services/CertificateManager/Generated/_bcl35/IAmazonCertificateManager.cs | 73,040 | C# |
namespace Eshopworld.Telemetry
{
using System;
using Core;
public static class MessagingConfigurationExtensions
{
/// <summary>
/// Sets up telemetry to use topics to stream some <see cref="DomainEvent"/> types.
/// </summary>
/// <param name="bb">The <see cref="BigBrother"/> instance we are configuring.</param>
/// <param name="publisher">The event publisher we are using to send events onto topics.</param>
public static void PublishEventsToTopics(this IBigBrother bb, IPublishEvents publisher)
{
var bbImpl = bb as BigBrother ?? throw new InvalidOperationException($"Couldn't cast this instance of {nameof(IBigBrother)} to a concrete implementation of {nameof(BigBrother)}");
bbImpl.TopicPublisher = publisher;
}
}
} | 44.684211 | 192 | 0.648999 | [
"MIT"
] | eShopWorld/common-telemetry | src/Eshopworld.Telemetry/MessagingConfigurationExtensions.cs | 851 | C# |
namespace ZWave.Serial;
public enum FrameType
{
/// <summary>
/// The ACK frame indicates that the receiving end received a valid Data frame.
/// </summary>
ACK,
/// <summary>
/// The NAK frame indicates that the receiving end received a Data frame with errors.
/// </summary>
NAK,
/// <summary>
/// The CAN frame indicates that the receiving end discarded an otherwise valid Data frame.
/// The CAN frame is used to resolve race conditions, where both ends send a Data frame and
/// subsequently expects an ACK frame from the other end.
/// </summary>
CAN,
/// <summary>
/// A data frame contains the Serial API command including parameters for the command in question.
/// </summary>
Data
}
| 28.518519 | 102 | 0.653247 | [
"MIT"
] | dfederm/ZWave.NET | src/ZWave/Serial/FrameType.cs | 772 | C# |
namespace WinFormsSample.Test.Dispose
{
partial class View
{
/// <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 Component Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.SuspendLayout();
//
// View
//
this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.Name = "View";
this.Size = new System.Drawing.Size(427, 375);
this.ResumeLayout(false);
}
#endregion
}
}
| 29.065217 | 107 | 0.538519 | [
"MIT"
] | Muzsor/LiveCharts2 | samples/WinFormsSample/Test/Dispose/View.Designer.cs | 1,339 | C# |
using FSO.Client.UI.Panels.Neighborhoods;
using FSO.Common.DataService;
using FSO.Common.DataService.Model;
using FSO.Server.DataService.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FSO.Client.Controllers.Panels
{
public class RatingListController : IDisposable
{
private Network.Network Network;
private IClientDataService DataService;
private UIRatingList View;
public RatingListController(UIRatingList view, IClientDataService dataService, Network.Network network)
{
this.Network = network;
this.DataService = dataService;
this.View = view;
}
public void SetAvatar(uint avatarID)
{
DataService.Request(MaskedStruct.MayorInfo_Avatar, avatarID).ContinueWith(x =>
{
View.CurrentAvatar.Value = (x.Result as Avatar);
});
}
public void Dispose()
{
View.CurrentAvatar.Dispose();
}
}
}
| 27.05 | 111 | 0.649723 | [
"MPL-2.0",
"MPL-2.0-no-copyleft-exception"
] | Blayer98/FreeSO | TSOClient/tso.client/Controllers/Panels/RatingListController.cs | 1,084 | C# |
// *** WARNING: this file was generated by the Pulumi SDK Generator. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.AzureNextGen.Network.V20190701
{
public static class GetVirtualNetworkGatewayLearnedRoutes
{
public static Task<GetVirtualNetworkGatewayLearnedRoutesResult> InvokeAsync(GetVirtualNetworkGatewayLearnedRoutesArgs args, InvokeOptions? options = null)
=> Pulumi.Deployment.Instance.InvokeAsync<GetVirtualNetworkGatewayLearnedRoutesResult>("azure-nextgen:network/v20190701:getVirtualNetworkGatewayLearnedRoutes", args ?? new GetVirtualNetworkGatewayLearnedRoutesArgs(), options.WithVersion());
}
public sealed class GetVirtualNetworkGatewayLearnedRoutesArgs : Pulumi.InvokeArgs
{
/// <summary>
/// The name of the resource group.
/// </summary>
[Input("resourceGroupName", required: true)]
public string ResourceGroupName { get; set; } = null!;
/// <summary>
/// The name of the virtual network gateway.
/// </summary>
[Input("virtualNetworkGatewayName", required: true)]
public string VirtualNetworkGatewayName { get; set; } = null!;
public GetVirtualNetworkGatewayLearnedRoutesArgs()
{
}
}
[OutputType]
public sealed class GetVirtualNetworkGatewayLearnedRoutesResult
{
/// <summary>
/// List of gateway routes.
/// </summary>
public readonly ImmutableArray<Outputs.GatewayRouteResponseResult> Value;
[OutputConstructor]
private GetVirtualNetworkGatewayLearnedRoutesResult(ImmutableArray<Outputs.GatewayRouteResponseResult> value)
{
Value = value;
}
}
}
| 35.425926 | 252 | 0.698902 | [
"Apache-2.0"
] | test-wiz-sec/pulumi-azure-nextgen | sdk/dotnet/Network/V20190701/GetVirtualNetworkGatewayLearnedRoutes.cs | 1,913 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PlayAroundwithImages2
{
class permission
{
public enum Extension
{
jpg,
jpeg,
png,
ai,
psd,
bmp,
eps,
ico,
webp,
gif,
tif,
pdf,
heic,
svg,
blend,
hdr,
exr,
ps,
}
}
}
| 16.058824 | 33 | 0.395604 | [
"MIT"
] | falxala/Play-Around-with-Images-2 | Convert/permission.cs | 548 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace craftersmine.EtherEngine.Input
{
/// <summary>
/// Represents gamepad trigger state
/// </summary>
public struct GamepadTriggerState
{
}
}
| 18.1875 | 40 | 0.707904 | [
"MIT"
] | craftersmine/EtherEngine | craftersmine.EtherEngine.Core/Input/GamepadTriggerState.cs | 293 | C# |
using System.Configuration;
using Should.Fluent;
namespace Backpack.Features.Tests
{
public class FeatureConfigurationTests
{
public void Current_LoadsCorrectConfigurationSection()
{
var configurationSection = ConfigurationManager.GetSection("backpack.features") as FeatureConfiguration;
var configuration = FeatureConfiguration.Current;
configuration.Should().Equal(configurationSection);
}
}
} | 29.375 | 116 | 0.712766 | [
"MIT",
"Unlicense"
] | zepedrosilva/Backpack.Features | Backpack.Features.Tests/FeatureConfigurationTests.cs | 472 | C# |
using System;
using xServer.Core.Networking;
using xServer.Enums;
namespace xServer.Core.Packets.ServerPackets
{
[Serializable]
public class DoPathDelete : IPacket
{
public string Path { get; set; }
public PathType PathType { get; set; }
public DoPathDelete()
{
}
public DoPathDelete(string path, PathType pathtype)
{
this.Path = path;
this.PathType = pathtype;
}
public void Execute(Client client)
{
client.Send(this);
}
}
} | 20.655172 | 60 | 0.539232 | [
"MIT"
] | pavitra14/Xtremis-V2.0 | Server/Core/Packets/ServerPackets/DoPathDelete.cs | 601 | C# |
using System.Windows.Controls;
namespace MicroStationTagExplorer.Views
{
public partial class ErrorsControl : UserControl
{
public ErrorsControl()
{
InitializeComponent();
}
}
}
| 17.538462 | 52 | 0.627193 | [
"MIT"
] | wieslawsoltes/MicroStationTagExplorer | src/MicroStationTagExplorer/Views/ErrorsControl.xaml.cs | 230 | C# |
using System;
using System.Collections;
using UnityEngine;
namespace OregoFramework.Util
{
public sealed class Routine
{
#region Event
public event Action OnFinishedEvent;
public event Action OnCanceledEvent;
#endregion
private readonly MonoBehaviour dispatcher;
private Coroutine routine;
public Routine(MonoBehaviour dispatcher)
{
this.dispatcher = dispatcher;
}
#region Run
public void Run(IEnumerator enumerator)
{
if (this.IsRunning())
{
throw new Exception("Routine is already running!");
}
var wrappedEnumerator = this.GetWrappedEnumerator(enumerator);
var routine = this.dispatcher.StartCoroutine(wrappedEnumerator);
this.routine = routine;
}
private IEnumerator GetWrappedEnumerator(IEnumerator enumerator)
{
yield return enumerator;
this.routine = null;
this.OnFinishedEvent?.Invoke();
}
#endregion
public bool Cancel()
{
if (!this.IsRunning())
{
return false;
}
this.dispatcher.StopCoroutine(this.routine);
this.routine = null;
this.OnCanceledEvent?.Invoke();
return true;
}
public bool IsRunning()
{
return this.routine != null && this.dispatcher.isActiveAndEnabled;
}
}
public static partial class Extensions
{
#region Join
public static IEnumerator Join(this Routine routine, Func<IEnumerator> func)
{
var enumerator = func.Invoke();
yield return routine.Join(enumerator);
}
public static IEnumerator Join(this Routine routine, IEnumerator enumerator)
{
routine.Run(enumerator);
yield return new WaitWhile(routine.IsRunning);
}
public static IEnumerator TryJoin(this Routine routine, Func<IEnumerator> func)
{
var enumerator = func.Invoke();
yield return routine.TryJoin(enumerator);
}
public static IEnumerator TryJoin(this Routine routine, IEnumerator enumerator)
{
if (routine.IsRunning())
{
yield break;
}
yield return routine.Join(enumerator);
}
public static IEnumerator ForceJoin(this Routine routine, Func<IEnumerator> func)
{
var enumerator = func.Invoke();
yield return routine.ForceJoin(enumerator);
}
public static IEnumerator ForceJoin(this Routine routine, IEnumerator enumerator)
{
routine.ForceRun(enumerator);
yield return new WaitWhile(routine.IsRunning);
}
#endregion
#region Run
public static void Run(this Routine routine, Func<IEnumerator> func)
{
var enumerator = func.Invoke();
routine.Run(enumerator);
}
public static void TryRun(this Routine routine, Func<IEnumerator> func)
{
var enumerator = func.Invoke();
routine.TryRun(enumerator);
}
public static void TryRun(this Routine routine, IEnumerator enumerator)
{
if (routine.IsRunning())
{
return;
}
routine.Run(enumerator);
}
public static void ForceRun(this Routine routine, Func<IEnumerator> func)
{
var enumerator = func?.Invoke();
routine.ForceRun(enumerator);
}
public static void ForceRun(this Routine routine, IEnumerator enumerator)
{
if (routine.IsRunning())
{
routine.Cancel();
}
routine.Run(enumerator);
}
#endregion
}
} | 25.711538 | 89 | 0.554974 | [
"Apache-2.0"
] | StarKRE/Orego | Utils/Scripts/Unity/Routine/Routine.cs | 4,011 | C# |
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DataAccess
{
/// <summary>
/// Wraps the internal settings-file to provide access to settings,
/// and automatically generates a deviceId for each install.
///
/// Also does locking, but the settings-file _should_ be thread-safe already,
/// so that part probably doesn't matter...
/// </summary>
public class SettingsAccess : ISettingsManager
{
private static readonly object _sync = new object();
private static SettingsAccess Instance;
private SettingsAccess() { }
public static SettingsAccess GetInstance()
{
lock (_sync)
{
return Instance ?? (Instance = new SettingsAccess());
}
}
public string GetVersionNumber()
{
lock (_sync)
{
return Properties.Settings.Default.VersionNumber;
}
}
public int GetFallbackWidth()
{
lock (_sync)
{
return Properties.Settings.Default.FallbackDimensionWidth;
}
}
public void SetFallbackWidth(int value)
{
lock (_sync)
{
Properties.Settings.Default.FallbackDimensionWidth = value;
}
}
public int GetFallbackHeight()
{
lock (_sync)
{
return Properties.Settings.Default.FallbackDimensionHeight;
}
}
public void SetFallbackHeight(int value)
{
lock (_sync)
{
Properties.Settings.Default.FallbackDimensionHeight = value;
}
}
public string GetBuiltinImgurClientID()
{
lock (_sync)
{
return Properties.Settings.Default.ImgurClientIDDefault;
}
}
public string GetImgurClientID()
{
lock (_sync)
{
return Properties.Settings.Default.ImgurClientID;
}
}
public void SetImgurClientID(string value)
{
lock (_sync)
{
Properties.Settings.Default.ImgurClientID = value;
}
}
public StringCollection GetSupportedExtensions()
{
lock (_sync)
{
return Properties.Settings.Default.SupportedExtensions;
}
}
public void SetSupportedExtensions(StringCollection value)
{
lock (_sync)
{
Properties.Settings.Default.SupportedExtensions = value;
}
}
public string GetRedditUserAgent()
{
lock (_sync)
{
return Properties.Settings.Default.RedditUserAgent;
}
}
public string GetRedditAppId()
{
lock (_sync)
{
return Properties.Settings.Default.RedditAppId;
}
}
public string GetDeviantartUserAgent()
{
lock (_sync)
{
return Properties.Settings.Default.DeviantartUserAgent;
}
}
public string GetGitHubUserAgent()
{
lock (_sync)
{
return Properties.Settings.Default.GitHubUserAgent;
}
}
public string GetDeviceId()
{
lock (_sync)
{
if (string.IsNullOrWhiteSpace(Properties.Settings.Default.DeviceId))
{
//Limit the length of the GUID since the reddit api wants a 20-30 length device id.
Properties.Settings.Default.DeviceId = Guid.NewGuid().ToString("N").Substring(0, 25);
Properties.Settings.Default.Save();
}
return Properties.Settings.Default.DeviceId;
}
}
public void Save()
{
lock (_sync)
{
Properties.Settings.Default.Save();
}
}
public void ResetDefaults()
{
lock (_sync)
{
Properties.Settings.Default.Reset();
}
}
}
} | 25.448864 | 105 | 0.50614 | [
"MIT"
] | Jameak/ImageDownloader | src/DataAccess/SettingsAccess.cs | 4,481 | C# |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using OpenMetaverse;
using Amib.Threading;
using OpenSim.Region.ScriptEngine.Shared;
using OpenSim.Region.ScriptEngine.Shared.Api;
using Action = System.Action;
namespace OpenSim.Region.ScriptEngine.Shared.Api.Plugins
{
public class Dataserver
{
private SmartThreadPool m_ThreadPool;
public AsyncCommandManager m_CmdManager;
public int DataserverRequestsCount
{
get
{
lock (DataserverRequests)
return DataserverRequests.Count;
}
}
private Dictionary<string, DataserverRequest> DataserverRequests = new Dictionary<string, DataserverRequest>();
public Dataserver(AsyncCommandManager CmdManager)
{
m_CmdManager = CmdManager;
STPStartInfo startInfo = new STPStartInfo();
startInfo.ThreadPoolName = "ScriptV";
startInfo.IdleTimeout = 1000;
startInfo.MaxWorkerThreads = 4;
startInfo.MinWorkerThreads = 0;
startInfo.ThreadPriority = ThreadPriority.Normal;
startInfo.StartSuspended = true;
m_ThreadPool = new SmartThreadPool(startInfo);
m_ThreadPool.Start();
}
private class DataserverRequest
{
public uint localID;
public UUID itemID;
public UUID ID;
public string handle;
public DateTime startTime;
public Action<string> action;
}
public string RequestWithImediatePost(uint localID, UUID itemID, string reply)
{
string ID = UUID.Random().ToString();
m_CmdManager.m_ScriptEngine.PostObjectEvent(localID,
new EventParams("dataserver", new Object[]
{ new LSL_Types.LSLString(ID),
new LSL_Types.LSLString(reply)},
new DetectParams[0]));
return ID;
}
//legacy
public UUID RegisterRequest(uint localID, UUID itemID, string identifier)
{
lock (DataserverRequests)
{
if (DataserverRequests.ContainsKey(identifier))
return UUID.Zero;
DataserverRequest ds = new DataserverRequest()
{
localID = localID,
itemID = itemID,
ID = UUID.Random(),
handle = identifier,
startTime = DateTime.UtcNow,
action = null
};
DataserverRequests[identifier] = ds;
return ds.ID;
}
}
// action, if provided, is executed async
// its code pattern should be:
//Action<string> act = eventID =>
//{
// need operations to get reply string
// m_AsyncCommands.DataserverPlugin.DataserverReply(eventID, reply);
//}
// eventID is the event id, provided by this on Invoque
// see ProcessActions below
// temporary don't use
public UUID RegisterRequest(uint localID, UUID itemID, string identifier, Action<string> action)
{
lock (DataserverRequests)
{
if (DataserverRequests.ContainsKey(identifier))
return UUID.Zero;
DataserverRequest ds = new DataserverRequest()
{
localID = localID,
itemID = itemID,
ID = UUID.Random(),
handle = identifier,
startTime = DateTime.UtcNow,
action = action
};
DataserverRequests[identifier] = ds;
if (action != null)
m_ThreadPool.QueueWorkItem((WorkItemCallback)ProcessActions, identifier);
return ds.ID;
}
}
public UUID RegisterRequest(uint localID, UUID itemID, Action<string> action)
{
lock (DataserverRequests)
{
string identifier = UUID.Random().ToString();
DataserverRequest ds = new DataserverRequest()
{
localID = localID,
itemID = itemID,
ID = UUID.Random(),
handle = identifier,
startTime = DateTime.MaxValue,
action = action
};
DataserverRequests[identifier] = ds;
if (action != null)
m_ThreadPool.QueueWorkItem((WorkItemCallback)ProcessActions, identifier);
return ds.ID;
}
}
public object ProcessActions(object st)
{
string id = st as string;
if(string.IsNullOrEmpty(id))
return null;
DataserverRequest ds = null;
lock (DataserverRequests)
{
if (!DataserverRequests.TryGetValue(id, out ds))
return null;
}
if (ds == null || ds.action == null)
return null;
try
{
ds.action.Invoke(ds.handle);
}
catch { }
ds.action = null;
lock (DataserverRequests)
{
if (DataserverRequests.TryGetValue(id, out ds))
DataserverRequests.Remove(id);
}
return null;
}
//legacy ?
public void DataserverReply(string identifier, string reply)
{
DataserverRequest ds;
lock (DataserverRequests)
{
if (!DataserverRequests.ContainsKey(identifier))
return;
ds = DataserverRequests[identifier];
DataserverRequests.Remove(identifier);
}
m_CmdManager.m_ScriptEngine.PostObjectEvent(ds.localID,
new EventParams("dataserver", new Object[]
{ new LSL_Types.LSLString(ds.ID.ToString()),
new LSL_Types.LSLString(reply)},
new DetectParams[0]));
}
public void RemoveEvents(uint localID, UUID itemID)
{
lock (DataserverRequests)
{
List<string> toremove = new List<string>(DataserverRequests.Count);
foreach (DataserverRequest ds in DataserverRequests.Values)
{
if (ds.itemID == itemID)
toremove.Add(ds.handle);
}
foreach (string s in toremove)
{
DataserverRequests.Remove(s);
}
}
}
public void ExpireRequests()
{
lock (DataserverRequests)
{
List<string> toremove = new List<string>(DataserverRequests.Count);
DateTime expirebase = DateTime.UtcNow.AddSeconds(-30);
foreach (DataserverRequest ds in DataserverRequests.Values)
{
if (ds.action == null && ds.startTime < expirebase)
toremove.Add(ds.handle);
}
foreach (string s in toremove)
{
DataserverRequests.Remove(s);
}
}
}
}
}
| 33.689781 | 120 | 0.54967 | [
"BSD-3-Clause"
] | BillBlight/consortium | OpenSim/Region/ScriptEngine/Shared/Api/Implementation/Plugins/Dataserver.cs | 9,231 | C# |
using System;
using System.Collections.Generic;
using System.Data;
using CRM.Business.Entity;
using CDK.Integration;
using CDK.Data;
//------------------------------------------------------------------------------
// <generado automáticamente>
// Este código fue generado por una herramienta.
//
// Los cambios en este archivo podrían causar un comportamiento incorrecto y se perderán si
// se vuelve a generar el código.
// </generado automáticamente>
//------------------------------------------------------------------------------
namespace CRM.Business.Data
{
/// <summary>
/// Clase Acceso de Datos PreguntaDataAccess
/// </summary>
/// <author>@Charly</author>
/// <created>07-03-2018 10:58:18</created>
/// <remarks>
/// Esta clase fué generada automáticamente por una herramienta.
/// </remarks>
public class PreguntaDataAccess
{
#region metodos base
/// <summary>
/// Guarda la entidad de dominio <see cref="PreguntaEntity"/> en la Base de Datos
/// </summary>
/// <author>@Charly</author>
/// <created>07-03-2018 10:58:18</created>
/// <param name="pregunta">Referencia a una clase <see cref="PreguntaEntity"/>.</param>
/// <returns>Clave primaria resultante de la operación</returns>
public static int Guardar(PreguntaEntity pregunta)
{
Parametros parametros = new Parametros
{
new Parametro("@preg_id", pregunta.preg_id),
new Parametro("@cuestionario_id", pregunta.cuestionario_id),
new Parametro("@titulo", pregunta.titulo),
new Parametro("@item", pregunta.item),
new Parametro("@pregunta_relacionada", pregunta.pregunta_relacionada),
};
return DBHelper.InstanceCRM.ObtenerEscalar<int>("fichas.spFicha_Pregunta_Guardar", parametros);
}
/// <summary>
/// Recupera una entidad <see cref="PreguntaEntity"/> de la Base de Datos dado un ID de PreguntaEntity
/// </summary>
/// <author>@Charly</author>
/// <created>07-03-2018 10:58:18</created>
/// <param name="preg_id">ID de PreguntaEntity.</param>
/// <returns>Referencia a una clase <see cref="PreguntaEntity"/>.</returns>
public static PreguntaEntity ObtenerPorID(int preg_id)
{
Parametro parametro = new Parametro("@preg_id", preg_id);
return DBHelper.InstanceCRM.ObtenerEntidad("fichas.spFicha_Pregunta_ObtenerPorID", parametro, ConstructorEntidad);
}
/// <summary>
/// Lista todas las entidades <see cref="PreguntaEntity"/> de la Base de Datos
/// </summary>
/// <author>@Charly</author>
/// <created>07-03-2018 10:58:18</created>
/// <returns><see cref="DataTable"/> con todos los objetos.</returns>
public static DataTable Listar()
{
return DBHelper.InstanceCRM.ObtenerDataTable("fichas.spFicha_Pregunta_Listar");
}
/// <summary>
/// Recupera todas las entidades <see cref="PreguntaEntity"/> de la Base de Datos
/// </summary>
/// <author>@Charly</author>
/// <created>07-03-2018 10:58:18</created>
/// <returns>Lista con todas las entidades <see cref="PreguntaEntity"/>.</returns>
public static List<PreguntaEntity> ObtenerEntidades()
{
return DBHelper.InstanceCRM.ObtenerColeccion("fichas.spFicha_Pregunta_Listar", ConstructorEntidad);
}
#endregion
#region metodos adicionales
#endregion
#region constructor
private static PreguntaEntity ConstructorEntidad(DataRow row)
{
return new PreguntaEntity
{
preg_id = row["preg_id"] != DBNull.Value ? Convert.ToInt32(row["preg_id"]) : 0,
cuestionario_id = row["cuestionario_id"] != DBNull.Value ? Convert.ToInt32(row["cuestionario_id"]) : 0,
titulo = row["titulo"] != DBNull.Value ? row["titulo"].ToString() : string.Empty,
item = row["item"] != DBNull.Value ? row["item"].ToString() : string.Empty,
pregunta_relacionada = row["pregunta_relacionada"] != DBNull.Value ? Convert.ToInt32(row["pregunta_relacionada"]) : 0,
};
}
#endregion
}
}
| 39.9 | 134 | 0.590112 | [
"MIT"
] | araucanosland/MDN | CRM.Business.Data/PreguntaDataAccess.cs | 4,400 | C# |
namespace libplctag
{
public enum PlcType
{
/// <summary>
/// Control Logix-class PLC. Synonym for lgx, logix, controllogix, contrologix, compactlogix, clgx.
/// </summary>
ControlLogix,
/// <summary>
/// PLC/5 PLC. Synonym for plc5, plc.
/// </summary>
Plc5,
/// <summary>
/// SLC 500 PLC. Synonym for slc500, slc.
/// </summary>
Slc500,
/// <summary>
/// Control Logix-class PLC using the PLC/5 protocol. Synonym for lgxpccc, logixpccc, lgxplc5, lgx_pccc, logix_pccc, lgx_plc5.
/// </summary>
LogixPccc,
/// <summary>
/// Micro800-class PLC. Synonym for micrologix800, mlgx800, micro800.
/// </summary>
Micro800,
/// <summary>
/// MicroLogix PLC. Synonym for micrologix, mlgx.
/// </summary>
MicroLogix,
/// <summary>
/// Omron PLC. Synonym for omron-njnx, omron-nj, omron-nx, njnx, nx1p2
/// </summary>
Omron,
}
} | 26.475 | 134 | 0.525024 | [
"MPL-2.0",
"MPL-2.0-no-copyleft-exception"
] | chrisbbb/libplctag.NET | src/libplctag/PlcType.cs | 1,061 | C# |
using System.Collections.Generic;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Authorization;
using Users.Models;
using Microsoft.AspNetCore.Identity;
using System.Threading.Tasks;
using System.ComponentModel.DataAnnotations;
namespace Users.Controllers {
public class HomeController : Controller {
private UserManager<AppUser> userManager;
public HomeController(UserManager<AppUser> userMgr) {
userManager = userMgr;
}
[Authorize]
public IActionResult Index() => View(GetData(nameof(Index)));
//[Authorize(Roles = "Users")]
[Authorize(Policy = "DCUsers")]
public IActionResult OtherAction() => View("Index",
GetData(nameof(OtherAction)));
[Authorize(Policy = "NotBob")]
public IActionResult NotBob() => View("Index", GetData(nameof(NotBob)));
private Dictionary<string, object> GetData(string actionName) =>
new Dictionary<string, object> {
["Action"] = actionName,
["User"] = HttpContext.User.Identity.Name,
["Authenticated"] = HttpContext.User.Identity.IsAuthenticated,
["Auth Type"] = HttpContext.User.Identity.AuthenticationType,
["In Users Role"] = HttpContext.User.IsInRole("Users"),
["City"] = CurrentUser.Result.City,
["Qualification"] = CurrentUser.Result.Qualifications
};
[Authorize]
public async Task<IActionResult> UserProps() {
return View(await CurrentUser);
}
[Authorize]
[HttpPost]
public async Task<IActionResult> UserProps(
[Required]Cities city,
[Required]QualificationLevels qualifications) {
if (ModelState.IsValid) {
AppUser user = await CurrentUser;
user.City = city;
user.Qualifications = qualifications;
await userManager.UpdateAsync(user);
return RedirectToAction("Index");
}
return View(await CurrentUser);
}
private Task<AppUser> CurrentUser =>
userManager.FindByNameAsync(HttpContext.User.Identity.Name);
}
}
| 35.265625 | 80 | 0.607444 | [
"Unlicense"
] | Vladimir-Zakharenkov/AdamFreemanMVC2 | Freeman A. projects with GitHub/30 - Advanced Identity/Users/Users/Controllers/HomeController.cs | 2,259 | 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("02. FloatOrDouble")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("02. FloatOrDouble")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("e49e1f4d-2a7a-4621-bd28-29b396d8597c")]
// 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.027027 | 84 | 0.744136 | [
"MIT"
] | EmilMitev/Telerik-Academy | CSharp - part 1/2.PrimitiveDataTypesAndVariables/02. FloatOrDouble/Properties/AssemblyInfo.cs | 1,410 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Immutable;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Shared.Collections;
using Microsoft.CodeAnalysis.Structure;
namespace Microsoft.CodeAnalysis.Editor.UnitTests.Structure
{
public abstract class AbstractSyntaxTriviaStructureProviderTests : AbstractSyntaxStructureProviderTests
{
internal abstract AbstractSyntaxStructureProvider CreateProvider();
internal sealed override async Task<ImmutableArray<BlockSpan>> GetBlockSpansWorkerAsync(Document document, BlockStructureOptions options, int position)
{
var root = await document.GetSyntaxRootAsync();
var trivia = root.FindTrivia(position, findInsideTrivia: true);
var outliner = CreateProvider();
using var actualRegions = TemporaryArray<BlockSpan>.Empty;
outliner.CollectBlockSpans(trivia, ref actualRegions.AsRef(), options, CancellationToken.None);
// TODO: Determine why we get null outlining spans.
return actualRegions.ToImmutableAndClear();
}
}
}
| 40.212121 | 159 | 0.746044 | [
"MIT"
] | BillWagner/roslyn | src/EditorFeatures/TestUtilities/Structure/AbstractSyntaxTriviaStructureProviderTests.cs | 1,329 | C# |
#if WITH_GAME
#if PLATFORM_32BITS
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
namespace UnrealEngine
{
public partial class UMaterialInstance
{
static readonly int PhysMaterial__Offset;
public UPhysicalMaterial PhysMaterial
{
get{ CheckIsValid(); IntPtr v = Marshal.ReadIntPtr(_this.Get() + PhysMaterial__Offset); if (v == IntPtr.Zero)return null; UPhysicalMaterial retValue = new UPhysicalMaterial(); retValue._this = v; return retValue; }
set{ CheckIsValid(); if (value == null)Marshal.WriteIntPtr(_this.Get() + PhysMaterial__Offset, IntPtr.Zero);else Marshal.WriteIntPtr(_this.Get() + PhysMaterial__Offset, value._this.Get()); }
}
static readonly int Parent__Offset;
public UMaterialInterface Parent
{
get{ CheckIsValid(); IntPtr v = Marshal.ReadIntPtr(_this.Get() + Parent__Offset); if (v == IntPtr.Zero)return null; UMaterialInterface retValue = new UMaterialInterface(); retValue._this = v; return retValue; }
set{ CheckIsValid(); if (value == null)Marshal.WriteIntPtr(_this.Get() + Parent__Offset, IntPtr.Zero);else Marshal.WriteIntPtr(_this.Get() + Parent__Offset, value._this.Get()); }
}
static readonly int bHasStaticPermutationResource__Offset;
public bool bHasStaticPermutationResource
{
get{ CheckIsValid();return BoolWrap.Get(_this.Get(), bHasStaticPermutationResource__Offset, 1, 0, 1, 1);}
}
static readonly int bOverrideSubsurfaceProfile__Offset;
public bool bOverrideSubsurfaceProfile
{
get{ CheckIsValid();return BoolWrap.Get(_this.Get(), bOverrideSubsurfaceProfile__Offset, 1, 0, 4, 4);}
set{ CheckIsValid();BoolWrap.Set(value,_this.Get(), bOverrideSubsurfaceProfile__Offset, 1,0,4,4);}
}
static readonly int FontParameterValues__Offset;
public TStructArray<FFontParameterValue> FontParameterValues
{
get{ CheckIsValid();return new TStructArray<FFontParameterValue>((FScriptArray)Marshal.PtrToStructure(_this.Get()+FontParameterValues__Offset, typeof(FScriptArray)));}
set{ CheckIsValid();Marshal.StructureToPtr(value.InterArray, _this.Get()+FontParameterValues__Offset, false);}
}
static readonly int ScalarParameterValues__Offset;
public TStructArray<FScalarParameterValue> ScalarParameterValues
{
get{ CheckIsValid();return new TStructArray<FScalarParameterValue>((FScriptArray)Marshal.PtrToStructure(_this.Get()+ScalarParameterValues__Offset, typeof(FScriptArray)));}
set{ CheckIsValid();Marshal.StructureToPtr(value.InterArray, _this.Get()+ScalarParameterValues__Offset, false);}
}
static readonly int TextureParameterValues__Offset;
public TStructArray<FTextureParameterValue> TextureParameterValues
{
get{ CheckIsValid();return new TStructArray<FTextureParameterValue>((FScriptArray)Marshal.PtrToStructure(_this.Get()+TextureParameterValues__Offset, typeof(FScriptArray)));}
set{ CheckIsValid();Marshal.StructureToPtr(value.InterArray, _this.Get()+TextureParameterValues__Offset, false);}
}
static readonly int VectorParameterValues__Offset;
public TStructArray<FVectorParameterValue> VectorParameterValues
{
get{ CheckIsValid();return new TStructArray<FVectorParameterValue>((FScriptArray)Marshal.PtrToStructure(_this.Get()+VectorParameterValues__Offset, typeof(FScriptArray)));}
set{ CheckIsValid();Marshal.StructureToPtr(value.InterArray, _this.Get()+VectorParameterValues__Offset, false);}
}
static readonly int bOverrideBaseProperties__Offset;
public bool bOverrideBaseProperties
{
get{ CheckIsValid();return BoolWrap.Get(_this.Get(), bOverrideBaseProperties__Offset, 1, 0, 1, 255);}
}
static readonly int BasePropertyOverrides__Offset;
public FMaterialInstanceBasePropertyOverrides BasePropertyOverrides
{
get{ CheckIsValid();return (FMaterialInstanceBasePropertyOverrides)Marshal.PtrToStructure(_this.Get()+BasePropertyOverrides__Offset, typeof(FMaterialInstanceBasePropertyOverrides));}
set{ CheckIsValid();Marshal.StructureToPtr(value, _this.Get()+BasePropertyOverrides__Offset, false);}
}
static UMaterialInstance()
{
IntPtr NativeClassPtr=GetNativeClassFromName("MaterialInstance");
PhysMaterial__Offset=GetPropertyOffset(NativeClassPtr,"PhysMaterial");
Parent__Offset=GetPropertyOffset(NativeClassPtr,"Parent");
bHasStaticPermutationResource__Offset=GetPropertyOffset(NativeClassPtr,"bHasStaticPermutationResource");
bOverrideSubsurfaceProfile__Offset=GetPropertyOffset(NativeClassPtr,"bOverrideSubsurfaceProfile");
FontParameterValues__Offset=GetPropertyOffset(NativeClassPtr,"FontParameterValues");
ScalarParameterValues__Offset=GetPropertyOffset(NativeClassPtr,"ScalarParameterValues");
TextureParameterValues__Offset=GetPropertyOffset(NativeClassPtr,"TextureParameterValues");
VectorParameterValues__Offset=GetPropertyOffset(NativeClassPtr,"VectorParameterValues");
bOverrideBaseProperties__Offset=GetPropertyOffset(NativeClassPtr,"bOverrideBaseProperties");
BasePropertyOverrides__Offset=GetPropertyOffset(NativeClassPtr,"BasePropertyOverrides");
}
}
}
#endif
#endif
| 46.981651 | 217 | 0.795743 | [
"MIT"
] | RobertAcksel/UnrealCS | Engine/Plugins/UnrealCS/UECSharpDomain/UnrealEngine/GeneratedScriptFile_Game_32bits/UMaterialInstance_FixSize.cs | 5,121 | C# |
// This file is generated from IGeometry.cs. Update the source file to change its contents.
using Microsoft.StandardUI.Media;
using DependencyProperty = Microsoft.UI.Xaml.DependencyProperty;
namespace Microsoft.StandardUI.WinUI.Media
{
public class Geometry : StandardUIDependencyObject, IGeometry
{
public static readonly DependencyProperty StandardFlatteningToleranceProperty = PropertyUtils.Register(nameof(StandardFlatteningTolerance), typeof(double), typeof(Geometry), 0.25);
public static readonly DependencyProperty TransformProperty = PropertyUtils.Register(nameof(Transform), typeof(Transform), typeof(Geometry), null);
public double StandardFlatteningTolerance
{
get => (double) GetValue(StandardFlatteningToleranceProperty);
set => SetValue(StandardFlatteningToleranceProperty, value);
}
public Transform Transform
{
get => (Transform) GetValue(TransformProperty);
set => SetValue(TransformProperty, value);
}
ITransform IGeometry.Transform
{
get => Transform;
set => Transform = (Transform) value;
}
}
}
| 38.967742 | 188 | 0.687914 | [
"MIT"
] | dotnet-standard-ui/standard-ui | src/StandardUI.WinUI/generated/Media/Geometry.cs | 1,208 | C# |
using System.Collections.Generic;
namespace Keen.Core.Query
{
/// <summary>
/// Represents the values from a query performed with a groupby.
/// </summary>
/// <typeparam name="T"></typeparam>
public sealed class QueryGroupValue<T>
{
/// <summary>
/// The value for the group. Varies with the type of query performed.
/// </summary>
public T Value { get; private set; }
/// <summary>
/// The value of the groupby field for this value.
/// </summary>
public string Group { get; private set; }
public QueryGroupValue(T value, string group)
{
Value = value;
Group = group;
}
public override bool Equals(object obj)
{
var value = obj as QueryGroupValue<T>;
return value != null &&
EqualityComparer<T>.Default.Equals(Value, value.Value) &&
Group == value.Group;
}
public override int GetHashCode()
{
var hashCode = -1845644250;
hashCode = hashCode * -1521134295 + EqualityComparer<T>.Default.GetHashCode(Value);
hashCode = hashCode * -1521134295 + EqualityComparer<string>.Default.GetHashCode(Group);
return hashCode;
}
}
}
| 29.422222 | 100 | 0.557402 | [
"MIT"
] | IshamMohamed/keen-sdk-net | Keen.NetStandard/Query/QueryGroupValue.cs | 1,324 | C# |
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using QuantConnect.Interfaces;
using QuantConnect.Packets;
namespace QuantConnect.Brokerages
{
/// <summary>
/// Provides a base implementation of IBrokerageFactory that provides a helper for reading data from a job's brokerage data dictionary
/// </summary>
public abstract class BrokerageFactory : IBrokerageFactory
{
private readonly Type _brokerageType;
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
/// </summary>
/// <filterpriority>2</filterpriority>
public abstract void Dispose();
/// <summary>
/// Gets the type of brokerage produced by this factory
/// </summary>
public Type BrokerageType
{
get { return _brokerageType; }
}
/// <summary>
/// Gets the brokerage data required to run the brokerage from configuration/disk
/// </summary>
/// <remarks>
/// The implementation of this property will create the brokerage data dictionary required for
/// running live jobs. See <see cref="IJobQueueHandler.NextJob"/>
/// </remarks>
public abstract Dictionary<string, string> BrokerageData { get; }
/// <summary>
/// Gets a brokerage model that can be used to model this brokerage's unique
/// behaviors
/// </summary>
public abstract IBrokerageModel BrokerageModel { get; }
/// <summary>
/// Creates a new IBrokerage instance
/// </summary>
/// <param name="job">The job packet to create the brokerage for</param>
/// <param name="algorithm">The algorithm instance</param>
/// <returns>A new brokerage instance</returns>
public abstract IBrokerage CreateBrokerage(LiveNodePacket job, IAlgorithm algorithm);
/// <summary>
/// Initializes a new instance of the <see cref="BrokerageFactory"/> class for the specified <paramref name="brokerageType"/>
/// </summary>
/// <param name="brokerageType">The type of brokerage created by this factory</param>
protected BrokerageFactory(Type brokerageType)
{
_brokerageType = brokerageType;
}
/// <summary>
/// Reads a value from the brokerage data, adding an error if the key is not found
/// </summary>
protected static T Read<T>(IReadOnlyDictionary<string, string> brokerageData, string key, ICollection<string> errors)
where T : IConvertible
{
string value;
if (!brokerageData.TryGetValue(key, out value))
{
errors.Add("BrokerageFactory.CreateBrokerage(): Missing key: " + key);
return default(T);
}
try
{
return value.ConvertTo<T>();
}
catch (Exception err)
{
errors.Add(string.Format("BrokerageFactory.CreateBrokerage(): Error converting key '{0}' with value '{1}'. {2}", key, value, err.Message));
return default(T);
}
}
}
} | 39.46 | 155 | 0.629752 | [
"Apache-2.0"
] | CircleOnCircles/Lean | Brokerages/BrokerageFactory.cs | 3,946 | 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.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Game.Graphics;
using osu.Game.Graphics.Sprites;
namespace osu.Game.Screens.Multi.Components
{
public class ParticipantCountDisplay : MultiplayerComposite
{
private const float text_size = 30;
private const float transition_duration = 100;
private OsuSpriteText slash, maxText;
public ParticipantCountDisplay()
{
AutoSizeAxes = Axes.Both;
}
[BackgroundDependencyLoader]
private void load()
{
OsuSpriteText count;
InternalChild = new FillFlowContainer
{
AutoSizeAxes = Axes.Both,
Direction = FillDirection.Horizontal,
LayoutDuration = transition_duration,
Children = new[]
{
count = new OsuSpriteText
{
Font = OsuFont.GetFont(weight: FontWeight.Bold, size: text_size)
},
slash = new OsuSpriteText
{
Text = @"/",
Font = OsuFont.GetFont(weight: FontWeight.Light, size: text_size)
},
maxText = new OsuSpriteText
{
Font = OsuFont.GetFont(weight: FontWeight.Light, size: text_size)
},
}
};
MaxParticipants.BindValueChanged(_ => updateMax(), true);
ParticipantCount.BindValueChanged(c => count.Text = c.NewValue.ToString("#,0"), true);
}
private void updateMax()
{
if (MaxParticipants.Value == null)
{
slash.FadeOut(transition_duration);
maxText.FadeOut(transition_duration);
}
else
{
slash.FadeIn(transition_duration);
maxText.Text = MaxParticipants.Value.ToString();
maxText.FadeIn(transition_duration);
}
}
}
}
| 32.944444 | 99 | 0.514755 | [
"MIT"
] | 123tris/osu | osu.Game/Screens/Multi/Components/ParticipantCountDisplay.cs | 2,303 | C# |
//--------------------------------------------------------------------------
// <copyright file="RasIkeV2Info.cs" company="Jeff Winn">
// Copyright (c) Jeff Winn. All rights reserved.
//
// The use and distribution terms for this software is covered by the
// GNU Library General Public License (LGPL) v2.1 which can be found
// in the License.rtf at the root of this distribution.
// By using this software in any fashion, you are agreeing to be bound by
// the terms of this license.
//
// You must not remove this notice, or any other, from this software.
// </copyright>
//--------------------------------------------------------------------------
namespace DotRas
{
using System;
using System.Collections.ObjectModel;
using System.Net;
#if (WIN7 || WIN8)
/// <summary>
/// Contains the result of an Internet Key Exchange (IKEv2) projection operation. This class cannot be inherited.
/// </summary>
/// <remarks>
/// <para>
/// This object is created from an <see cref="RasProjectionType.IkeV2"/> projection operation on a connection.
/// </para>
/// <para>
/// <b>Known Limitations:</b>
/// <list type="bullet">
/// <item>This type is only available on Windows 7 and later operating systems.</item>
/// </list>
/// </para>
/// </remarks>
/// <example>
/// This example shows how to perform an IKEv2 projection operation on an active connection.
/// <code lang="C#">
/// <![CDATA[
/// RasConnection connection = RasConnection.GetActiveConnectionByName("My Connection", @"C:\Test.pbk");
/// if (connection != null)
/// {
/// RasIkeV2Info info = (RasIkeV2Info)connection.GetProjectionInfo(RasProjectionType.IkeV2);
/// if (info != null)
/// {
/// // info now contains the IKEv2 projection data.
/// }
/// }
/// ]]>
/// </code>
/// <code lang="VB.NET">
/// <![CDATA[
/// Dim connection As RasConnection = RasConnection.GetActiveConnectionByName("My Connection", "C:\Test.pbk")
/// If connection IsNot Nothing Then
/// Dim info As RasIkeV2Info = CType(connection.GetProjectionInfo(RasProjectionType.IkeV2), RasIkeV2Info)
/// If info IsNot Nothing Then
/// ' info now contains the IKEv2 projection data.
/// End If
/// End If
/// ]]>
/// </code>
/// </example>
[Serializable]
public sealed class RasIkeV2Info
{
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="DotRas.RasIkeV2Info"/> class.
/// </summary>
/// <param name="ipv4NegotiationErrorCode">The result of a PPP IPv4 network control protocol negotiation.</param>
/// <param name="ipv4Address">The IP address of the local client.</param>
/// <param name="serverIPv4Address">The IP address of the remote server.</param>
/// <param name="ipv6NegotiationErrorCode">The result of a PPP IPv6 network control protocol negotiation.</param>
/// <param name="ipv6Address">The IPv6 address of the local client.</param>
/// <param name="serverIPv6Address">The IPv6 address of the remote server.</param>
/// <param name="prefixLength">The length of the IPv6 prefix.</param>
/// <param name="authenticationProtocol">The authentication protocol used to authenticate the remote server.</param>
/// <param name="eapTypeId">The type identifier of the Extensible Authentication Protocol (EAP) used to authenticate the client.</param>
/// <param name="options">The IKEv2 options.</param>
/// <param name="encryptionMethod">The encryption method used by the connection.</param>
/// <param name="serverIPv4Addresses">The collection of available IPv4 addresses the server can switch to on the IKEv2 connection.</param>
/// <param name="serverIPv6Addresses">The collection of available IPv6 addresses the server can switch to on the IKEv2 connection.</param>
internal RasIkeV2Info(int ipv4NegotiationErrorCode, IPAddress ipv4Address, IPAddress serverIPv4Address, int ipv6NegotiationErrorCode, IPAddress ipv6Address, IPAddress serverIPv6Address, int prefixLength, RasIkeV2AuthenticationType authenticationProtocol, int eapTypeId, RasIkeV2Options options, RasIPSecEncryptionType encryptionMethod, Collection<IPAddress> serverIPv4Addresses, Collection<IPAddress> serverIPv6Addresses)
{
this.IPv4NegotiationErrorCode = ipv4NegotiationErrorCode;
this.IPv4Address = ipv4Address;
this.ServerIPv4Address = serverIPv4Address;
this.IPv6NegotiationErrorCode = ipv6NegotiationErrorCode;
this.IPv6Address = ipv6Address;
this.ServerIPv6Address = serverIPv6Address;
this.PrefixLength = prefixLength;
this.AuthenticationProtocol = authenticationProtocol;
this.EapTypeId = eapTypeId;
this.Options = options;
this.EncryptionMethod = encryptionMethod;
this.ServerIPv4Addresses = serverIPv4Addresses;
this.ServerIPv6Addresses = serverIPv6Addresses;
}
#endregion
#region Properties
/// <summary>
/// Gets the result of a PPP IPv4 network control protocol negotiation.
/// </summary>
public int IPv4NegotiationErrorCode
{
get;
private set;
}
/// <summary>
/// Gets the IPv4 address of the local client.
/// </summary>
public IPAddress IPv4Address
{
get;
private set;
}
/// <summary>
/// Gets the IPv4 address of the remote server.
/// </summary>
public IPAddress ServerIPv4Address
{
get;
private set;
}
/// <summary>
/// Gets the result of a PPP IPv6 network control protocol negotiation.
/// </summary>
public int IPv6NegotiationErrorCode
{
get;
private set;
}
/// <summary>
/// Gets the IPv6 address of the local client.
/// </summary>
public IPAddress IPv6Address
{
get;
private set;
}
/// <summary>
/// Gets the IPv6 address of the remote server.
/// </summary>
public IPAddress ServerIPv6Address
{
get;
private set;
}
/// <summary>
/// Gets the length of the IPv6 prefix.
/// </summary>
public int PrefixLength
{
get;
private set;
}
/// <summary>
/// Gets the authentication protocol used to authenticate the remote server.
/// </summary>
public RasIkeV2AuthenticationType AuthenticationProtocol
{
get;
private set;
}
/// <summary>
/// Gets the type identifier of the Extensible Authentication Protocol (EAP) used to authenticate the client.
/// </summary>
/// <remarks>This member is only valid if <see cref="RasIkeV2Info.AuthenticationProtocol"/> is <see cref="RasIkeV2AuthenticationType.Eap"/>.</remarks>
public int EapTypeId
{
get;
private set;
}
/// <summary>
/// Gets the IKEv2 options.
/// </summary>
public RasIkeV2Options Options
{
get;
private set;
}
/// <summary>
/// Gets the encryption method used by the connection.
/// </summary>
public RasIPSecEncryptionType EncryptionMethod
{
get;
private set;
}
/// <summary>
/// Gets the collection of available IPv4 addresses the server can switch to on the IKEv2 connection.
/// </summary>
public Collection<IPAddress> ServerIPv4Addresses
{
get;
private set;
}
/// <summary>
/// Gets the collection of available IPv6 addresses the server can switch to on the IKEv2 connection.
/// </summary>
public Collection<IPAddress> ServerIPv6Addresses
{
get;
private set;
}
#endregion
}
#endif
} | 36.688596 | 429 | 0.590556 | [
"Apache-2.0"
] | kangwl/xk | DotRas/RasIkeV2Info.cs | 8,367 | C# |
using addon365.Database.Entity.Inventory.Catalog;
using addon365.Domain.Entity.Paging;
using addon365.IService;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
namespace addon365.Web.API.Controllers
{
/// <inheritdoc />
[Produces("application/json")]
[Route("api/{license:license}/v{version:apiVersion}/[controller]")]
public class ProductController : Controller
{
private readonly IProductService _productService;
/// <inheritdoc />
///
public ProductController(IProductService productService)
{
_productService = productService;
}
/// <summary>
/// Returns a list of all active referrer spammers
/// </summary>
///<remarks>
///</remarks>
[HttpGet]
public Threenine.Data.Paging.IPaginate<CatalogItem> Get(int PageNumber = 0, int PageSize = 30)
{
PagingParams pagingParams = new PagingParams();
pagingParams.PageNumber = PageNumber;
pagingParams.PageSize = PageSize;
return _productService.GetAllActive(pagingParams);
}
/// <summary>
/// Returns Details of a selected Referrer
/// </summary>
///<remarks>
///
///</remarks>
[HttpGet("{Id}")]
public IEnumerable<CatalogItem> Get(int Id)
{
return _productService.GetProductByType(Id);
}
[AllowAnonymous]
[Route("Companies")]
[HttpGet]
public IEnumerable<CatalogBrand> GetCompanies()
{
return _productService.GetCompanies();
}
[AllowAnonymous]
[Route("Types")]
[HttpGet]
public IEnumerable<CatalogType> GetTypes()
{
return _productService.GetTypes();
}
/// <summary>
/// Returns a collection of values
/// </summary>
///<remarks>
/// This is a remark to add additional information about this method
///</remarks>
[HttpPost]
public IActionResult ProductPost([FromBody] CatalogItem referrer)
{
if (referrer == null)
{
return BadRequest();
}
var identifier = _productService.Insert(referrer);
return Ok();
}
[HttpPost("accessories")]
public IActionResult AccessoriesPost([FromBody] CatalogItem referrer)
{
if (referrer == null)
{
return BadRequest();
}
var identifier = _productService.Insert(referrer);
return Ok();
}
[AllowAnonymous]
[Route("Delete")]
[HttpPost]
public IActionResult Delete([FromBody] CatalogItem product)
{
if (product == null)
{
return BadRequest();
}
_productService.Delete(product);
return Ok();
}
/// <summary>
/// Returns Details of a selected Referrer
/// </summary>
///<remarks>
///
///</remarks>
[HttpGet]
[Route("{identifier}", Name = "ProductDetail")]
public IActionResult Detail(string identifier)
{
var referer = _productService.GetProduct(identifier);
if (referer == null) return NotFound();
return Ok(referer);
}
}
}
| 25.816176 | 102 | 0.544574 | [
"Apache-2.0"
] | addon365/b1ke-sh0wr00m | src/DotNet/Should be removed/addon365.Web.API/Controllers/ProductController.cs | 3,513 | C# |
// Copyright (c) Six Labors.
// Licensed under the Apache License, Version 2.0.
using System;
using System.Buffers.Binary;
using System.Collections.Generic;
using System.Text;
namespace SixLabors.ImageSharp.Metadata.Profiles.Exif
{
/// <summary>
/// Contains methods for writing EXIF metadata.
/// </summary>
internal sealed class ExifWriter
{
/// <summary>
/// Which parts will be written.
/// </summary>
private readonly ExifParts allowedParts;
private readonly IList<IExifValue> values;
private List<int> dataOffsets;
private readonly List<IExifValue> ifdValues;
private readonly List<IExifValue> exifValues;
private readonly List<IExifValue> gpsValues;
/// <summary>
/// Initializes a new instance of the <see cref="ExifWriter"/> class.
/// </summary>
/// <param name="values">The values.</param>
/// <param name="allowedParts">The allowed parts.</param>
public ExifWriter(IList<IExifValue> values, ExifParts allowedParts)
{
this.values = values;
this.allowedParts = allowedParts;
this.ifdValues = this.GetPartValues(ExifParts.IfdTags);
this.exifValues = this.GetPartValues(ExifParts.ExifTags);
this.gpsValues = this.GetPartValues(ExifParts.GpsTags);
}
/// <summary>
/// Returns the EXIF data.
/// </summary>
/// <returns>
/// The <see cref="T:byte[]"/>.
/// </returns>
public byte[] GetData()
{
const uint startIndex = 0;
uint length;
IExifValue exifOffset = GetOffsetValue(this.ifdValues, this.exifValues, ExifTag.SubIFDOffset);
IExifValue gpsOffset = GetOffsetValue(this.ifdValues, this.gpsValues, ExifTag.GPSIFDOffset);
if (this.ifdValues.Count == 0 && this.exifValues.Count == 0 && this.gpsValues.Count == 0)
{
return Array.Empty<byte>();
}
uint ifdLength = this.GetLength(this.ifdValues) + 4U;
uint exifLength = this.GetLength(this.exifValues);
uint gpsLength = this.GetLength(this.gpsValues);
length = ifdLength + exifLength + gpsLength;
if (length == 4U)
{
return Array.Empty<byte>();
}
// two bytes for the byte Order marker 'II' or 'MM', followed by the number 42 (0x2A) and a 0, making 4 bytes total
length += (uint)ExifConstants.LittleEndianByteOrderMarker.Length;
length += 4 + 2;
var result = new byte[length];
int i = 0;
// The byte order marker for little-endian, followed by the number 42 and a 0
ExifConstants.LittleEndianByteOrderMarker.CopyTo(result.AsSpan(start: i));
i += ExifConstants.LittleEndianByteOrderMarker.Length;
uint ifdOffset = ((uint)i - startIndex) + 4U;
uint thumbnailOffset = ifdOffset + ifdLength + exifLength + gpsLength;
exifOffset?.TrySetValue(ifdOffset + ifdLength);
gpsOffset?.TrySetValue(ifdOffset + ifdLength + exifLength);
i = WriteUInt32(ifdOffset, result, i);
i = this.WriteHeaders(this.ifdValues, result, i);
i = WriteUInt32(thumbnailOffset, result, i);
i = this.WriteData(startIndex, this.ifdValues, result, i);
if (exifLength > 0)
{
i = this.WriteHeaders(this.exifValues, result, i);
i = this.WriteData(startIndex, this.exifValues, result, i);
}
if (gpsLength > 0)
{
i = this.WriteHeaders(this.gpsValues, result, i);
i = this.WriteData(startIndex, this.gpsValues, result, i);
}
WriteUInt16(0, result, i);
return result;
}
private static unsafe int WriteSingle(float value, Span<byte> destination, int offset)
{
BinaryPrimitives.WriteInt32LittleEndian(destination.Slice(offset, 4), *((int*)&value));
return offset + 4;
}
private static unsafe int WriteDouble(double value, Span<byte> destination, int offset)
{
BinaryPrimitives.WriteInt64LittleEndian(destination.Slice(offset, 8), *((long*)&value));
return offset + 8;
}
private static int Write(ReadOnlySpan<byte> source, Span<byte> destination, int offset)
{
source.CopyTo(destination.Slice(offset, source.Length));
return offset + source.Length;
}
private static int WriteInt16(short value, Span<byte> destination, int offset)
{
BinaryPrimitives.WriteInt16LittleEndian(destination.Slice(offset, 2), value);
return offset + 2;
}
private static int WriteUInt16(ushort value, Span<byte> destination, int offset)
{
BinaryPrimitives.WriteUInt16LittleEndian(destination.Slice(offset, 2), value);
return offset + 2;
}
private static int WriteUInt32(uint value, Span<byte> destination, int offset)
{
BinaryPrimitives.WriteUInt32LittleEndian(destination.Slice(offset, 4), value);
return offset + 4;
}
private static int WriteInt64(long value, Span<byte> destination, int offset)
{
BinaryPrimitives.WriteInt64LittleEndian(destination.Slice(offset, 8), value);
return offset + 8;
}
private static int WriteUInt64(ulong value, Span<byte> destination, int offset)
{
BinaryPrimitives.WriteUInt64LittleEndian(destination.Slice(offset, 8), value);
return offset + 8;
}
private static int WriteInt32(int value, Span<byte> destination, int offset)
{
BinaryPrimitives.WriteInt32LittleEndian(destination.Slice(offset, 4), value);
return offset + 4;
}
private static IExifValue GetOffsetValue(List<IExifValue> ifdValues, List<IExifValue> values, ExifTag offset)
{
int index = -1;
for (int i = 0; i < ifdValues.Count; i++)
{
if (ifdValues[i].Tag == offset)
{
index = i;
}
}
if (values.Count > 0)
{
if (index != -1)
{
return ifdValues[index];
}
ExifValue result = ExifValues.Create(offset);
ifdValues.Add(result);
return result;
}
else if (index != -1)
{
ifdValues.RemoveAt(index);
}
return null;
}
private List<IExifValue> GetPartValues(ExifParts part)
{
var result = new List<IExifValue>();
if (!EnumUtils.HasFlag(this.allowedParts, part))
{
return result;
}
foreach (IExifValue value in this.values)
{
if (!HasValue(value))
{
continue;
}
if (ExifTags.GetPart(value.Tag) == part)
{
result.Add(value);
}
}
return result;
}
private static bool HasValue(IExifValue exifValue)
{
object value = exifValue.GetValue();
if (value is null)
{
return false;
}
if (exifValue.DataType == ExifDataType.Ascii)
{
string stringValue = (string)value;
return stringValue.Length > 0;
}
if (value is Array arrayValue)
{
return arrayValue.Length > 0;
}
return true;
}
private uint GetLength(IList<IExifValue> values)
{
if (values.Count == 0)
{
return 0;
}
uint length = 2;
foreach (IExifValue value in values)
{
uint valueLength = GetLength(value);
length += 2 + 2 + 4 + 4;
if (valueLength > 4)
{
length += valueLength;
}
}
return length;
}
internal static uint GetLength(IExifValue value) => GetNumberOfComponents(value) * ExifDataTypes.GetSize(value.DataType);
internal static uint GetNumberOfComponents(IExifValue exifValue)
{
object value = exifValue.GetValue();
if (exifValue.DataType == ExifDataType.Ascii)
{
return (uint)Encoding.UTF8.GetBytes((string)value).Length + 1;
}
if (value is Array arrayValue)
{
return (uint)arrayValue.Length;
}
return 1;
}
private static int WriteArray(IExifValue value, Span<byte> destination, int offset)
{
if (value.DataType == ExifDataType.Ascii)
{
return WriteValue(ExifDataType.Ascii, value.GetValue(), destination, offset);
}
int newOffset = offset;
foreach (object obj in (Array)value.GetValue())
{
newOffset = WriteValue(value.DataType, obj, destination, newOffset);
}
return newOffset;
}
private int WriteData(uint startIndex, List<IExifValue> values, Span<byte> destination, int offset)
{
if (this.dataOffsets.Count == 0)
{
return offset;
}
int newOffset = offset;
int i = 0;
foreach (IExifValue value in values)
{
if (GetLength(value) > 4)
{
WriteUInt32((uint)(newOffset - startIndex), destination, this.dataOffsets[i++]);
newOffset = WriteValue(value, destination, newOffset);
}
}
return newOffset;
}
private int WriteHeaders(List<IExifValue> values, Span<byte> destination, int offset)
{
this.dataOffsets = new List<int>();
int newOffset = WriteUInt16((ushort)values.Count, destination, offset);
if (values.Count == 0)
{
return newOffset;
}
foreach (IExifValue value in values)
{
newOffset = WriteUInt16((ushort)value.Tag, destination, newOffset);
newOffset = WriteUInt16((ushort)value.DataType, destination, newOffset);
newOffset = WriteUInt32(GetNumberOfComponents(value), destination, newOffset);
uint length = GetLength(value);
if (length > 4)
{
this.dataOffsets.Add(newOffset);
}
else
{
WriteValue(value, destination, newOffset);
}
newOffset += 4;
}
return newOffset;
}
private static void WriteRational(Span<byte> destination, in Rational value)
{
BinaryPrimitives.WriteUInt32LittleEndian(destination.Slice(0, 4), value.Numerator);
BinaryPrimitives.WriteUInt32LittleEndian(destination.Slice(4, 4), value.Denominator);
}
private static void WriteSignedRational(Span<byte> destination, in SignedRational value)
{
BinaryPrimitives.WriteInt32LittleEndian(destination.Slice(0, 4), value.Numerator);
BinaryPrimitives.WriteInt32LittleEndian(destination.Slice(4, 4), value.Denominator);
}
private static int WriteValue(ExifDataType dataType, object value, Span<byte> destination, int offset)
{
switch (dataType)
{
case ExifDataType.Ascii:
offset = Write(Encoding.UTF8.GetBytes((string)value), destination, offset);
destination[offset] = 0;
return offset + 1;
case ExifDataType.Byte:
case ExifDataType.Undefined:
destination[offset] = (byte)value;
return offset + 1;
case ExifDataType.DoubleFloat:
return WriteDouble((double)value, destination, offset);
case ExifDataType.Short:
if (value is Number shortNumber)
{
return WriteUInt16((ushort)shortNumber, destination, offset);
}
return WriteUInt16((ushort)value, destination, offset);
case ExifDataType.Long:
if (value is Number longNumber)
{
return WriteUInt32((uint)longNumber, destination, offset);
}
return WriteUInt32((uint)value, destination, offset);
case ExifDataType.Long8:
return WriteUInt64((ulong)value, destination, offset);
case ExifDataType.SignedLong8:
return WriteInt64((long)value, destination, offset);
case ExifDataType.Rational:
WriteRational(destination.Slice(offset, 8), (Rational)value);
return offset + 8;
case ExifDataType.SignedByte:
destination[offset] = unchecked((byte)((sbyte)value));
return offset + 1;
case ExifDataType.SignedLong:
return WriteInt32((int)value, destination, offset);
case ExifDataType.SignedShort:
return WriteInt16((short)value, destination, offset);
case ExifDataType.SignedRational:
WriteSignedRational(destination.Slice(offset, 8), (SignedRational)value);
return offset + 8;
case ExifDataType.SingleFloat:
return WriteSingle((float)value, destination, offset);
default:
throw new NotImplementedException();
}
}
internal static int WriteValue(IExifValue value, Span<byte> destination, int offset)
{
if (value.IsArray && value.DataType != ExifDataType.Ascii)
{
return WriteArray(value, destination, offset);
}
return WriteValue(value.DataType, value.GetValue(), destination, offset);
}
}
}
| 33.511312 | 129 | 0.536254 | [
"Apache-2.0"
] | br3aker/ImageSharp | src/ImageSharp/Metadata/Profiles/Exif/ExifWriter.cs | 14,812 | C# |
using Mono.Options;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace ffcut
{
public class Options
{
public class TimeRange
{
public string From { get; set; }
public string To { get; set; }
}
public bool Help { get; set; }
public bool Verbose { get; set; }
public bool Force { get; set; }
public string InputPath { get; set; }
public List<TimeRange> Times { get; set; } = new List<TimeRange>();
public static Options Parse(string[] args)
{
var options = new Options();
var flags = new OptionSet
{
{ "h|?|help", v => options.Help = true },
{ "v|verbose", v => options.Verbose = true },
{ "f|force", v => options.Force = true },
};
var unprocessed = flags.Parse(args);
foreach (var arg in unprocessed)
{
ProcessArg(arg, options);
}
return options;
}
private static void ProcessArg(string arg, Options options)
{
if (arg.StartsWith("-") && arg.Length > 1 && !char.IsDigit(arg[1]))
{
throw new OptionException("Unknown command line option", arg);
}
if (options.InputPath == null)
{
options.InputPath = arg;
return;
}
if (arg.Count(c => { return c == '-'; }) != 1)
{
throw new OptionException("Invalid time interval", arg);
}
var range = new TimeRange();
var timeParts = arg.Split('-');
if (timeParts.Length > 0 && !string.IsNullOrEmpty(timeParts[0]))
{
range.From = timeParts[0];
if (!IsTimeSpan(range.From))
{
throw new OptionException($"Invalid start time '{range.From}' of interval", arg);
}
}
if (timeParts.Length > 1 && !string.IsNullOrEmpty(timeParts[1]))
{
range.To = timeParts[1];
if (!IsTimeSpan(range.To))
{
throw new OptionException("Invalid end time '{range.To}' of interval", arg);
}
}
options.Times.Add(range);
}
private static bool IsTimeSpan(string s)
{
if (new Regex(@"^\d?\d:\d?\d:\d?\d$").IsMatch(s))
{
return true;
}
if (new Regex(@"^\d?\d:\d?\d$").IsMatch(s))
{
return true;
}
if (new Regex(@"^\d?\d$").IsMatch(s))
{
return true;
}
return false;
}
}
}
| 28.171429 | 101 | 0.455375 | [
"MIT"
] | dewaffled/ffcut | Options.cs | 2,960 | C# |
using System;
using System.Collections.Generic;
using System.Data.CarsonDatabase;
using System.IO;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace CarsonDBTest
{
[TestClass]
public class AnimalCrcUnitTest
{
private string _legacySourcePath = Path.Combine(Directory.GetCurrentDirectory(), "LEGACY");
private string _modernSourcePath = Path.Combine(Directory.GetCurrentDirectory(), "MODERN");
[TestInitialize]
public void AnimalCrcTestInit()
{
Shared.CreateDatabaseFiles();
}
[TestMethod]
public void AnimalCrcTest()
{
using (Animal animal1 = new Animal(_legacySourcePath))
using (Animal animal2 = new Animal(_modernSourcePath))
{
animal1.CreateTableCRC("animal1.crc", Shared.GetFields(typeof(Animal.AnimalFields)));
animal2.CreateTableCRC("animal2.crc", Shared.GetFields(typeof(Animal.AnimalFields)));
Shared.UpdateAnimalFiles();
List<Animal.AnimalData> animalRecordsChanged1 = animal1.FindChangedRecords("animal1.crc", Animal.DifferentialData.NewAndModifiedRecords).ConvertAll(x => (Animal.AnimalData)x);
List<Animal.AnimalData> animalRecordsChanged2 = animal2.FindChangedRecords("animal2.crc", Animal.DifferentialData.NewAndModifiedRecords).ConvertAll(x => (Animal.AnimalData)x);
string updatedRecords = File.ReadAllText("updated.csv");
updatedRecords = updatedRecords.Replace("\r\n", "");
string[] records = updatedRecords.Split(',');
if (records.Length != animalRecordsChanged1.Count || records.Length != animalRecordsChanged2.Count)
{
Assert.Fail("Record Lengths do not match. Found: " + animalRecordsChanged1.Count.ToString() + ", " + animalRecordsChanged2.Count.ToString() + ". Expected: " + records.Length.ToString());
}
for (int x = 0; x < records.Length; x++)
{
int recordId = Convert.ToInt32(records[x]);
if (!animalRecordsChanged1.Any(i => i.AnimalId == recordId))
{
Assert.Fail("Record: " + recordId.ToString() + " Not found when expected.");
}
}
}
Assert.IsTrue(true, "Successfull CRC Check on Animal Table");
}
}
}
| 36.610169 | 193 | 0.705556 | [
"MIT"
] | petabyte-technology/CarsonDB | CarsonDBTest/AnimalCrcUnitTest.cs | 2,162 | C# |
/* Copyright (c) 2009-11, ReactionGrid Inc. http://reactiongrid.com
* See License.txt for full licence information.
*
* SingleSceneConfiguration.cs Revision 1.4.1106.11
* Used to provide single scene configuration Jibe instances */
using UnityEngine;
using System;
using System.Collections;
using ReactionGrid.JibeAPI;
using ReactionGrid.Jibe;
public class SingleSceneConfiguration : MonoBehaviour
{
private bool runSingleSceneConfig = false;
public GUISkin guiSkin;
// external data
private string username = "";
private string dynamicRoomId = ""; // integer to add to the name of the rooms to which the users are connecting - used for dynamic room support (coming in next release)
private int selected = -1;
private IJibeServer jibeServerInstance;
private IJibePlayer localPlayer;
private string infoMessage = "Ready for login";
private string headerMessage = "Connecting to server...";
private bool isGuest = false;
// Headshots
public Texture2D[] avatarHeadPics;
// Full pics of avatars
public Texture2D[] avatarFullPics;
public float fullPicWidth = 128;
public float fullPicHeight = 128;
private Color guiColor;
// When an avatar thumbnail is selected a preview is shown of the full model on the right
public float avatarPreviewTransparency = 0.7f;
// The image to show for the login / start button (optional)
public Texture2D loginButtonImage;
public Texture2D backgroundImage;
GameObject jibeGUI;
GameObject previewCamera;
public float fadeSpeed = 0.3f;
private int drawDepth = -1000;
private float alpha = 1.0f;
private float fadeDir = -1;
void Update()
{
if (runSingleSceneConfig)
{
if (jibeServerInstance == null)
{
return;
}
jibeServerInstance.Update();
}
}
public void RunConfiguration()
{
selected = PlayerPrefs.GetInt("avatar", -1);
if (selected >= avatarHeadPics.Length)
{
selected = -1;
}
runSingleSceneConfig = true;
ShowPreviewCamera(true);
previewCamera = GameObject.Find("PreviewCameraForDesignModeOnly");
jibeGUI = GameObject.Find("JibeGUI");
ToggleGUIElements(false);
alpha = 1;
fadeIn();
Debug.Log("Configuring Jibe");
Cursor.visible = true;
username = PlayerPrefs.GetString("username");
if (string.IsNullOrEmpty(username) || username == "Unknown user")
{
username = "Guest" + UnityEngine.Random.Range(0, 999);
isGuest = true;
PlayerPrefs.SetString("username", username);
}
Application.runInBackground = true;
// Gather configuration
JibeConfig config = GetComponent<JibeConfig>();
// add the id to each room name for the class for use in dynamic rooms
if (string.IsNullOrEmpty(dynamicRoomId)) dynamicRoomId = "1";
PlayerPrefs.SetInt("DynamicRoomId", int.Parse(dynamicRoomId));
Debug.Log(config.Room + " " + config.Zone + " " + config.ServerIP + " " + config.ServerPort.ToString() + " " + config.RoomPassword + " " + config.ServerPlatform.ToString());
// Prefetch policy from designated socket server
// only for web clients
if (Application.platform == RuntimePlatform.WindowsWebPlayer ||
Application.platform == RuntimePlatform.OSXWebPlayer ||
Application.platform == RuntimePlatform.WindowsEditor ||
Application.platform == RuntimePlatform.OSXEditor)
{
bool success = Security.PrefetchSocketPolicy(config.ServerIP, config.ServerPort);
if (!success)
{
Debug.Log("Prefetch policy from network server failed, trying standard policy server port " + config.PolicyServerPort);
Security.PrefetchSocketPolicy(config.ServerIP, config.PolicyServerPort);
}
else
{
Debug.Log("Prefetch policy succeeded from " + config.ServerPort);
}
}
if (!JibeComms.IsInitialized())
{
try
{
Debug.Log("Generate new Jibe instance");
// Initialize backend server
switch (config.ServerPlatform)
{
case SupportedServers.JibePhoton:
jibeServerInstance = new JibePhotonServer(config.ServerIP, config.ServerPort, config.Zone, config.Room, config.DataSendRate, config.DataSendRate, config.debugLevel, Debug.Log, Debug.LogWarning, Debug.LogError);
break;
case SupportedServers.JibeSFS2X:
jibeServerInstance = new JibeSFS2XServer(config.ServerIP, config.ServerPort, config.Zone, config.Room, config.RoomPassword, false, config.DataSendRate, config.DataSendRate, config.debugLevel, Debug.Log, Debug.LogWarning, Debug.LogError, config.HttpPort);
break;
}
JibeComms.Initialize(config.Room, config.Zone, config.ServerIP, config.ServerPort, config.RoomPassword, config.RoomList, config.Version, jibeServerInstance);
}
catch (Exception e)
{
Debug.Log(e.Message);
}
}
jibeServerInstance.LoginResult += new LoginResultEventHandler(LoginResult);
string message = "Connecting to server, please wait...";
headerMessage = message;
Debug.Log(message);
try
{
// Connect to Jibe
localPlayer = jibeServerInstance.Connect();
}
catch (Exception ex)
{
Debug.Log("Failed to connect!" + ex.Message + ex.StackTrace);
infoMessage = ex.Message;
}
}
void OnGUI()
{
if (runSingleSceneConfig)
{
GUI.skin = guiSkin;
GUILayout.BeginArea(new Rect(0, 0, Screen.width, Screen.height));
GUILayout.BeginVertical();
GUILayout.Space(5);
// Welcome prompt / header message - will show whatever text is set in headerMessage
GUILayout.Label(headerMessage, "WelcomePrompt");
try
{
if (jibeServerInstance.IsConnected)
{
headerMessage = "Choose an avatar";
// Choose avatar - arrange GUI elements in an area (sized here) using layout tools
GUILayout.BeginArea(new Rect(5, 30, 600, 180));
GUILayout.BeginHorizontal();
// Show the choice of avatars - default is pics laid out in rows up to 7 icons per row
selected = GUILayout.SelectionGrid(selected, avatarHeadPics, 7, "PictureButtonsSmall");
GUILayout.EndHorizontal();
GUILayout.EndArea();
// we're back to vertical layout - the space here controls vertical displacement for next GUI elements (offset from top)
GUILayout.Space(290);
GUILayout.BeginHorizontal();
// horizontal offset from left
GUILayout.Space(2);
// Give the player the option to change their name
GUILayoutOption[] nameoptions = { GUILayout.Width(120), GUILayout.Height(22) };
username = GUILayout.TextField(username, "UserNameField", nameoptions);
if (isGuest || Application.platform == RuntimePlatform.WindowsEditor)
GUILayout.Label("Edit your name here!", "InstructionLabel");
GUILayout.EndHorizontal();
GUIContent content = new GUIContent("Start", "Start!");
// check the player has selected an avatar, then show button
if (selected >= 0 && GUI.Button(new Rect(2, 350, 80, 22), content, "LoginButton"))
{
DoLogin(selected);
}
}
guiColor = GUI.color;
guiColor.a = avatarPreviewTransparency;
GUI.color = guiColor;
if (selected > -1 && selected < avatarFullPics.Length)
{
GUI.DrawTexture(new Rect(420, 10, fullPicWidth, fullPicHeight), avatarFullPics[selected]);
}
guiColor.a = 1.0f;
GUI.color = guiColor;
// camera fade
alpha += fadeDir * fadeSpeed * Time.deltaTime;
alpha = Mathf.Clamp01(alpha);
guiColor.a = alpha;
GUI.color = guiColor;
GUI.depth = drawDepth;
GUI.DrawTexture(new Rect(0, 0, Screen.width, Screen.height), backgroundImage);
guiColor.a = 1.0f;
GUI.color = guiColor;
}
catch (Exception ex)
{
infoMessage = ex.Message + ": " + ex.StackTrace;
Debug.Log(infoMessage);
}
GUILayout.Space(50);
GUILayout.BeginHorizontal();
GUILayout.Space(120);
GUILayout.Label(infoMessage, "InstructionLabel");
// Must always end all GUILayout elements - missing closing tags do not make unity happy
GUILayout.EndHorizontal();
GUILayout.EndVertical();
GUILayout.EndArea();
}
}
private void DoLogin(int selected)
{
RetrieveClothingPreference();
Debug.Log("DoLogin");
jibeServerInstance.RequestLogin(username);
}
private void RetrieveClothingPreference()
{
// try to re-use previous clothing options
string skin = PlayerPrefs.GetString("skin");
if (!string.IsNullOrEmpty(skin))
localPlayer.Skin = skin;
string hair = PlayerPrefs.GetString("hair");
if (!string.IsNullOrEmpty(hair))
localPlayer.Hair = hair;
}
private string GetSkinName(string normalTextureName)
{
// We rely on naming conventions for getting the name of a skin - all assets in the resources folder must be named according to convention
// and all headshots and full previews too.
string skinName = normalTextureName;
skinName = skinName.Substring(0, skinName.IndexOf("Head"));
return skinName + "_skin";
}
private void LoginResult(object sender, LoginResultEventArgs e)
{
if (e.Success)
{
fadeOut();
// Player has logged in successfully! Store some prefs
PlayerPrefs.SetString("username", username);
PlayerPrefs.SetInt("avatar", selected);
// Update localPlayer
localPlayer.AvatarModel = selected;
localPlayer.Name = username;
if (string.IsNullOrEmpty(localPlayer.Skin))
{
localPlayer.Skin = GetSkinName(avatarHeadPics[selected].name);
}
// Unwire event handlers
jibeServerInstance.LoginResult -= new LoginResultEventHandler(LoginResult);
// Now should be ready to spawn avatars and join the room
runSingleSceneConfig = false;
ToggleGUIElements(true);
LogLoginEvent();
GetComponent<NetworkController>().DoInitialization();
}
else
{
Debug.Log("Login FAIL " + e.Message);
infoMessage = e.Message;
}
}
private void LogLoginEvent()
{
GameObject jibeObject = GameObject.Find("Jibe");
JibeActivityLog jibeLog = jibeObject.GetComponent<JibeActivityLog>();
if (jibeLog != null && jibeLog.logEnabled)
{
if (Application.platform == RuntimePlatform.WindowsWebPlayer || Application.platform == RuntimePlatform.OSXWebPlayer)
{
Debug.Log(jibeLog.TrackEvent(JibeEventType.Login, Application.absoluteURL, 0.0f, 0.0f, 0.0f, username, username, "Web Player Login"));
}
else if (Application.platform == RuntimePlatform.WindowsEditor || Application.platform == RuntimePlatform.OSXEditor)
{
Debug.Log(jibeLog.TrackEvent(JibeEventType.Login, Application.dataPath, 0.0f, 0.0f, 0.0f, username, username, "Editor login"));
}
else if (Application.platform == RuntimePlatform.WindowsPlayer || Application.platform == RuntimePlatform.OSXPlayer)
{
Debug.Log(jibeLog.TrackEvent(JibeEventType.Login, Application.dataPath, 0.0f, 0.0f, 0.0f, username, username, "Standalone Client login"));
}
else
{
Debug.Log(jibeLog.TrackEvent(JibeEventType.Login, Application.dataPath, 0.0f, 0.0f, 0.0f, username, username, "Other Client login"));
}
}
}
private void ToggleGUIElements(bool enabled)
{
if (jibeGUI != null)
{
jibeGUI.SetActiveRecursively(enabled);
}
GameObject miniMap = GameObject.Find("MiniMapCamera");
if (miniMap != null)
{
miniMap.GetComponent<Camera>().enabled = enabled;
}
}
private void ShowPreviewCamera(bool enabled)
{
if (previewCamera != null)
{
Debug.Log("Preview Camera found, setting active to " + enabled);
previewCamera.GetComponent<PreviewCamera>().SetActive(enabled);
}
}
private void fadeIn()
{
fadeDir = -1;
}
private void fadeOut()
{
fadeDir = 1;
}
}
| 38.188172 | 279 | 0.567929 | [
"Apache-2.0"
] | RutgersUniversityVirtualWorlds/FreshTherapyOffice | Assets/RGScripts/SingleSceneConfiguration.cs | 14,206 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
namespace System.Runtime.CompilerServices
{
[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true, Inherited = false)]
public sealed class InternalsVisibleToAttribute : Attribute
{
public InternalsVisibleToAttribute(string assemblyName)
{
AssemblyName = assemblyName;
}
public string AssemblyName { get; }
public bool AllInternalsVisible { get; set; } = true;
}
}
| 32.277778 | 88 | 0.698795 | [
"MIT"
] | 2m0nd/runtime | src/libraries/System.Private.CoreLib/src/System/Runtime/CompilerServices/InternalsVisibleToAttribute.cs | 581 | C# |
// ==================================================================================================================
// ,::i BBB
// BBBBBi EBBB
// MBBNBBU BBB,
// BBB. BBB BBB,BBBBM BBB UBBB MBB, LBBBBBO, :BBG,BBB :BBB .BBBU kBBBBBF
// BBB, BBB 7BBBBS2BBBO BBB iBBBB YBBJ :BBBMYNBBB: FBBBBBB: OBB: 5BBB, BBBi ,M,
// MBBY BBB. 8BBB :BBB BBB .BBUBB BB1 BBBi kBBB BBBM BBBjBBBr BBB1
// BBBBBBBBBBBu BBB FBBP MBM BB. BB BBM 7BBB MBBY .BBB 7BBGkBB1 JBBBBi
// PBBBFE0GkBBBB 7BBX uBBB MBBMBu .BBOBB rBBB kBBB ZBBq BBB: BBBJ . iBBB
//BBBB iBBB BBBBBBBBBE EBBBB ,BBBB MBBBBBBBM BBB, iBBB .BBB2 :BBBBBBB7
//vr7 777 BBBu8O5: .77r Lr7 .7EZk; L77 .Y7r irLY JNMMF:
// LBBj
//
// Apworks Application Development Framework
// Copyright (C) 2009-2018 by daxnet.
// 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.Net;
namespace Apworks.Integration.AspNetCore.DataServices
{
/// <summary>
/// Represents the error that occurs when the requested entity cannot be found in the repository.
/// </summary>
/// <seealso cref="Apworks.Integration.AspNetCore.DataServices.DataServiceException" />
public sealed class EntityNotFoundException : DataServiceException
{
#region Ctor
/// <summary>
/// Initializes a new instance of the <see cref="EntityNotFoundException"/> class.
/// </summary>
/// <param name="message">The message that describes the error.</param>
public EntityNotFoundException(string message)
: base(HttpStatusCode.NotFound, message)
{ }
/// <summary>
/// Initializes a new instance of the <see cref="EntityNotFoundException"/> class.
/// </summary>
/// <param name="format">The format of the error message.</param>
/// <param name="args">The arguments to be used for constructing the error message.</param>
public EntityNotFoundException(string format, params object[] args)
: base(HttpStatusCode.NotFound, format, args)
{ }
#endregion
}
}
| 55.052632 | 208 | 0.528999 | [
"Apache-2.0"
] | dahaoniuniu/apworks-core | src/Apworks.Integration.AspNetCore/DataServices/EntityNotFoundException.cs | 3,140 | C# |
/*
* MIT License
*
* Copyright (c) Microsoft Corporation.
*
* 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 Microsoft.Playwright.NUnit;
using NUnit.Framework;
namespace Microsoft.Playwright.Tests
{
public class LoggerTests : PlaywrightTestEx
{
[PlaywrightTest("logger.spec.ts", "should log")]
[Ignore("We don't test CHANNEL")]
public void ShouldLog()
{
}
[PlaywrightTest("logger.spec.ts", "should log context-level")]
[Ignore("We don't test CHANNEL")]
public void ShouldLogContextLevel()
{
}
}
}
| 36.244444 | 81 | 0.713059 | [
"MIT"
] | Archish27/playwright-dotnet | src/Playwright.Tests/LoggerTests.cs | 1,631 | C# |
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
// **NOTE** This file was generated by a tool and any changes will be overwritten.
namespace Microsoft.Graph
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Http;
using System.Threading;
/// <summary>
/// The interface IWorkbookFunctionsDbRequest.
/// </summary>
public partial interface IWorkbookFunctionsDbRequest : IBaseRequest
{
/// <summary>
/// Gets the request body.
/// </summary>
WorkbookFunctionsDbRequestBody RequestBody { get; }
/// <summary>
/// Issues the POST request.
/// </summary>
System.Threading.Tasks.Task<WorkbookFunctionResult> PostAsync();
/// <summary>
/// Issues the POST request.
/// </summary>
/// <param name=""cancellationToken"">The <see cref=""CancellationToken""/> for the request.</param>
/// <returns>The task to await for async call.</returns>
System.Threading.Tasks.Task<WorkbookFunctionResult> PostAsync(
CancellationToken cancellationToken);
/// <summary>
/// Adds the specified expand value to the request.
/// </summary>
/// <param name="value">The expand value.</param>
/// <returns>The request object to send.</returns>
IWorkbookFunctionsDbRequest Expand(string value);
/// <summary>
/// Adds the specified select value to the request.
/// </summary>
/// <param name="value">The select value.</param>
/// <returns>The request object to send.</returns>
IWorkbookFunctionsDbRequest Select(string value);
}
}
| 32.622951 | 153 | 0.572864 | [
"MIT"
] | twsouthwick/msgraph-sdk-dotnet | src/Microsoft.Graph/Requests/Generated/IWorkbookFunctionsDbRequest.cs | 1,990 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.1
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace Sample2.Properties {
using System;
/// <summary>
/// A strongly-typed resource class, for looking up localized strings, etc.
/// </summary>
// This class was auto-generated by the StronglyTypedResourceBuilder
// class via a tool like ResGen or Visual Studio.
// To add or remove a member, edit your .ResX file then rerun ResGen
// with the /str option, or rebuild your VS project.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
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>
/// Returns the cached ResourceManager instance used by this class.
/// </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("Sample2.Properties.Resources", typeof(Resources).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// Overrides the current thread's CurrentUICulture property for all
/// resource lookups using this strongly typed resource class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture {
get {
return resourceCulture;
}
set {
resourceCulture = value;
}
}
}
}
| 44.3125 | 174 | 0.598025 | [
"Unlicense"
] | JeremyDurnell/ChromeTabs | Version1.3/Sample2/Properties/Resources.Designer.cs | 2,838 | C# |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging.Testing;
using Xunit.Abstractions;
namespace Microsoft.Extensions.Logging
{
public static class XunitLoggerFactoryExtensions
{
public static ILoggingBuilder AddXunit(this ILoggingBuilder builder, ITestOutputHelper output)
{
builder.Services.AddSingleton<ILoggerProvider>(new XunitLoggerProvider(output));
return builder;
}
public static ILoggingBuilder AddXunit(this ILoggingBuilder builder, ITestOutputHelper output, LogLevel minLevel)
{
builder.Services.AddSingleton<ILoggerProvider>(new XunitLoggerProvider(output, minLevel));
return builder;
}
public static ILoggerFactory AddXunit(this ILoggerFactory loggerFactory, ITestOutputHelper output)
{
loggerFactory.AddProvider(new XunitLoggerProvider(output));
return loggerFactory;
}
public static ILoggerFactory AddXunit(this ILoggerFactory loggerFactory, ITestOutputHelper output, LogLevel minLevel)
{
loggerFactory.AddProvider(new XunitLoggerProvider(output, minLevel));
return loggerFactory;
}
}
}
| 37.5 | 125 | 0.717193 | [
"Apache-2.0"
] | couven92/aspnet-Logging | src/Microsoft.Extensions.Logging.Testing/XunitLoggerFactoryExtensions.cs | 1,427 | C# |
/* =======================================================================
Copyright 2017 Technische Universitaet Darmstadt, Fachgebiet fuer Stroemungsdynamik (chair of fluid dynamics)
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;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using BoSSS.Platform;
using BoSSS.Platform.Utils.Geom;
using ilPSP;
using ilPSP.Tracing;
using ilPSP.Utils;
using MPI.Wrappers;
using BoSSS.Platform.LinAlg;
namespace BoSSS.Foundation.Grid.Classic {
partial class GridData {
/// <summary>
/// See <see cref="Vertices"/>
/// </summary>
private VertexData m_VerticeData;
/// <summary>
/// Information about the vertices of the grid elements, see
/// <see cref="VertexData"/>
/// </summary>
public VertexData Vertices {
get {
return m_VerticeData;
}
}
/// <summary>
/// Information about the vertices of the grid elements, see
/// <see cref="IVertexData"/>.
/// </summary>
public IVertexData iVertices {
get {
return m_VerticeData;
}
}
/// <summary>
/// Data about the vertices
/// </summary>
public class VertexData : IVertexData {
/// <summary>
/// ctor
/// </summary>
internal VertexData(GridData owner) {
m_owner = owner;
}
/// <summary>
/// pointer to owner object
/// </summary>
private GridData m_owner;
/// <summary>
/// all vertices/nodes of the gird;
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item>1st index: vertex index</item>
/// <item>2nd index: spatial dimension</item>
/// </list>
/// The vertices are sorted in a specific order:
/// <list type="bullet">
/// <item>
/// First, all pure local vertices, see
/// <see cref="NoOfPurelyLocal"/>
/// </item>
/// <item>
/// Second, all shared vertices owned by this MPI process,
/// see <see cref="NoOfRelayed"/>
/// </item>
/// <item>
/// Third, all shared vertices owned by other MPI processes,
/// see <see cref="NoOfBorrowed"/>
/// </item>
/// <item>
/// Fourth, all external vertices, see
/// <see cref="NoOfExternal"/>
/// </item>
/// </list>
/// </remarks>
public MultidimensionalArray Coordinates {
get;
internal set;
}
/// <summary>
/// Number of Vertices on local MPI process
/// </summary>
public int Count {
get {
return Coordinates.GetLength(0);
}
}
/// <summary>
/// Number of vertices which are used only by locally updated cells;
/// </summary>
public int NoOfPurelyLocal {
get;
private set;
}
/// <summary>
/// Number of shared vertices (used by locally updated cells AND
/// external cells) which are 'owned' by the current MPI process.
/// </summary>
public int NoOfRelayed {
get;
private set;
}
/// <summary>
/// Number of vertices which are 'owned' by the current MPI process
/// </summary>
public int NoOfOwned {
get {
return NoOfPurelyLocal + NoOfRelayed;
}
}
/// <summary>
/// Number of shared vertices (used by locally updated cells AND
/// external cells) which are 'owned' by other MPI process.
/// </summary>
public int NoOfBorrowed {
get;
private set;
}
/// <summary>
/// Number of Vertices which are used only by external cells;
/// </summary>
public int NoOfExternal {
get;
private set;
}
/// <summary>
/// Number of nodes which are identical to others via the peridicity relations of the grid.
/// </summary>
public int NoOfPeriodicElim {
get;
private set;
}
/// <summary>
/// Number of nodes that are used by locally updated cells.
/// </summary>
public int NoOfNodes4LocallyUpdatedCells {
get {
int R = (this.Count - this.NoOfExternal);
Debug.Assert(R == (NoOfPurelyLocal + NoOfBorrowed + NoOfRelayed + NoOfPeriodicElim));
return R;
}
}
private Partitioning m_NodePartitioning = null;
/// <summary>
/// partitioning of nodes across MPI processes
/// </summary>
public Partitioning NodePartitioning {
get {
if (m_NodePartitioning == null) {
m_NodePartitioning =
new Partitioning(this.NoOfPurelyLocal + this.NoOfRelayed);
}
return m_NodePartitioning;
}
}
/// <summary>
/// content: which of the relayed vertices must be send to
/// other processors
/// - 1st index: MPI rank of target processor 'R'
/// - 2nd index: enumeration
/// </summary>
public int[][] VertexSendLists {
get;
private set;
}
/// <summary>
/// content: where the borrowed vertices received by other
/// processors must be inserted
/// - 1st index: MPI rank of target processor 'R'
/// - 2nd index: enumeration
/// </summary>
public int[][] VertexInsertLists {
get;
private set;
}
/// <summary>
/// Computes a unique list of all nodes/vertices of all cells.
/// </summary>
/// <param name="vertice">
/// output: the merged vertices, i.e. each vertex from the
/// </param>
/// <param name="cellVertices">
/// output: indices into the <paramref name="vertice"/>-array.
/// 1st index: cell index;
/// 2nd index: vertex index within cell;
/// </param>
/// <param name="grdDat"></param>
/// <param name="h">
/// cell measure
/// </param>
/// <param name="IncludeExt">
/// true, if also external cells should be considered
/// </param>
internal static void CollectVertices(GridData grdDat, out int[][] cellVertices, out MultidimensionalArray vertice, double[] h, bool IncludeExt = false) {
using (var tr = new FuncTrace()) {
// fk: bemerkung: sollte einegermaßen skalieren;
// Test am 10sept10: Gitter mit 400x400 dauert cd 8 sec., Gitter mit 800x400 dauert 16 sekunden
int D = grdDat.SpatialDimension;
int J;
J = IncludeExt ? grdDat.Cells.Count : grdDat.Cells.NoOfLocalUpdatedCells;
//int NV = celVtx.GetLength(1);
var Krefs = grdDat.Grid.RefElements;
// collect vertices
// ================
int No = 0;
{
int a, b;
for (int i = 0; i < Krefs.Length; i++) {
grdDat.GetLocalNoOfCellsRefElement(i, out a, out b);
No += (a + (IncludeExt ? b : 0)) * Krefs[i].NoOfVertices;
}
}
MultidimensionalArray Verts = MultidimensionalArray.Create(No, D);
// loop over all cells...
MultidimensionalArray[] vertsGlobal = (
from Kref in Krefs
select MultidimensionalArray.Create(1, Kref.NoOfVertices, D)).ToArray();
int cnt = 0;
for (int j = 0; j < J; j++) {
int iKref = grdDat.Cells.GetRefElementIndex(j);
var Kref = Krefs[iKref];
var Kj = grdDat.Cells.GetCell(j);
var vertsGlobal_iKref = vertsGlobal[iKref];
//Kref.TransformLocal2Global(Kref.Vertices, vertsGlobal_iKref, 0, Kj.Type, Kj.TransformationParams);
grdDat.TransformLocal2Global(Kref.Vertices, j, 1, vertsGlobal_iKref, 0);
int NV = Kref.NoOfVertices;
// loop over cell vertices...
for (int iv = 0; iv < NV; iv++) {
for (int d = 0; d < D; d++) {
Verts[cnt, d] = vertsGlobal_iKref[0, iv, d];
}
cnt++;
}
}
// build tree
// ==========
BoundingBox bb = new BoundingBox(Verts);
bb.ExtendByFactor(0.005);
int[] Perm = new int[Verts.GetLength(0)];
PointLocalization locTree = new PointLocalization(Verts, bb, Perm);
Verts = locTree.Points;
// eliminate duplicate points
// ==========================
double[] pt = new double[D];
int N = No;
List<int> foundPoints = new List<int>();
int[] AliasPts = new int[No];
AliasPts.SetAll(int.MinValue);
int NewVertice = 0;
List<int> VerticeTmp = new List<int>();
using (new BlockTrace("duplicate Point elimination", tr)) {
int n = -1;
for (int j = 0; j < J; j++) {
int iKref = grdDat.Cells.GetRefElementIndex(j);
var Kref = Krefs[iKref];
int NV = Kref.NoOfVertices;
for (int _n = 0; _n < NV; _n++) {
n++;
if (AliasPts[n] >= 0)
continue; // point is already assigned.
Verts.GetRow(n, pt); // pt = Verts[n,*]
double eps = h[j] * 1.0e-6;
locTree.FindNearPoints(foundPoints, eps, pt);
if (foundPoints.Count < 1)
throw new ApplicationException("error in algorithm");
if (!foundPoints.Contains(n)) {
throw new ApplicationException("error in algorithm");
}
VerticeTmp.Add(n);
for (int k = 0; k < foundPoints.Count; k++) {
AliasPts[foundPoints[k]] = NewVertice;
}
NewVertice++;
}
}
}
// test
// ====
for (int i = 0; i < AliasPts.Length; i++)
if (AliasPts[i] < 0)
throw new ApplicationException("error in alg");
// store results
// =============
int[] PermInv = new int[Perm.Length];
for (int i = 0; i < PermInv.Length; i++)
PermInv[Perm[i]] = i;
cellVertices = new int[J][];
int m = 0;
for (int j = 0; j < J; j++) {
int iKref = grdDat.Cells.GetRefElementIndex(j);
var Kref = Krefs[iKref];
int NV = Kref.NoOfVertices;
cellVertices[j] = new int[NV];
for (int _n = 0; _n < NV; _n++) {
cellVertices[j][_n] = AliasPts[PermInv[m]];
m++;
}
}
vertice = MultidimensionalArray.Create(VerticeTmp.Count, D);
for (int i = 0; i < NewVertice; i++) {
int n = VerticeTmp[i];
for (int d = 0; d < D; d++) {
vertice[i, d] = Verts[n, d];
}
}
}
}
/// <summary>
/// For each vertex, the local indices of the adjacent cells;
/// - 1st index: local vertex index
/// - 2nd index: collection
/// </summary>
public int[][] VerticeToCell {
get;
internal set;
}
/// <summary>
/// init code for <see cref="VerticeToCell"/>.
/// </summary>
internal void Init_VerticeToCell() {
Debug.Assert(VerticeToCell == null);
int K = this.Count;
int J = this.m_owner.Cells.Count;
var CellVertices = this.m_owner.Cells.CellVertices;
VerticeToCell = new int[K][];
for (int j = 0; j < J; j++) { // loop over cells
var CellVertices_j = CellVertices[j];
foreach (int k in CellVertices_j) {
ArrayTools.AddToArray(j, ref VerticeToCell[k]);
}
}
}
public SortedDictionary<int, int> PeriodicEliminatedPoints {
get;
private set;
}
List<Tuple<int, int>> PeriodicIdenitiesTmp;
internal void Init_PeriodicPairings() {
int NoOfEdges = this.m_owner.Edges.Count;
int NoOfVtx = this.Count;
var EdgeTags = this.m_owner.Edges.EdgeTags;
var E2C = this.m_owner.Edges.CellIndices;
var E2F = this.m_owner.Edges.FaceIndices;
var C2V = this.m_owner.Cells.CellVertices;
var Krefs = this.m_owner.Grid.RefElements;
// find points which are identic due to periodicity
// ================================================
List<int>[] PeriodicPeer = new List<int>[NoOfVtx];
bool AnythingPeriodic = false;
for (int iEdg = 0; iEdg < NoOfEdges; iEdg++) { // loop over edges
if (EdgeTags[iEdg] >= GridCommons.FIRST_PERIODIC_BC_TAG) {
// found some periodic edge
// ++++++++++++++++++++++++
if (!(this.m_owner.Edges.IsEdgeConformalWithCell1(iEdg) && this.m_owner.Edges.IsEdgeConformalWithCell2(iEdg))) {
throw new NotImplementedException("Periodicity on non-conformal edges not suported yet.");
}
int jCell1 = E2C[iEdg, 0];
int jCell2 = E2C[iEdg, 1];
var Cell1 = this.m_owner.Cells.GetCell(jCell1);
var Cell2 = this.m_owner.Cells.GetCell(jCell1);
int iFace1 = E2F[iEdg, 0];
int iFace2 = E2F[iEdg, 1];
var Kref1 = m_owner.Cells.GetRefElement(jCell1);
var Kref2 = m_owner.Cells.GetRefElement(jCell2);
var FVtx1 = Kref1.GetFaceVertices(iFace1); // periodic nodes in local coordinates of first cell
var FVtx2 = Kref2.GetFaceVertices(iFace2); // "peers due to periodicity", in local coordinates of second cell
var FVtx1G = this.m_owner.GlobalNodes.GetValue_Cell(FVtx1, jCell1, 1).ExtractSubArrayShallow(0, -1, -1);
var FVtx2G = this.m_owner.GlobalNodes.GetValue_Cell(FVtx2, jCell2, 1).ExtractSubArrayShallow(0, -1, -1);
Debug.Assert(object.ReferenceEquals(this.m_owner.Edges.GetRefElement(iEdg), Kref1.FaceRefElement));
Debug.Assert(object.ReferenceEquals(this.m_owner.Edges.GetRefElement(iEdg), Kref2.FaceRefElement));
Debug.Assert(FVtx1.NoOfNodes == FVtx2.NoOfNodes);
int L = FVtx1.NoOfNodes;
int[] GlobIdxFace1 = new int[FVtx1.NoOfNodes];
int[] GlobIdxFace2 = new int[FVtx2.NoOfNodes];
Debug.Assert(Kref1.FaceToVertexIndices.GetLength(1) == L);
Debug.Assert(Kref2.FaceToVertexIndices.GetLength(1) == L);
for (int i = 0; i < L; i++) {
GlobIdxFace1[i] = C2V[jCell1][Kref1.FaceToVertexIndices[iFace1, i]];
GlobIdxFace2[i] = C2V[jCell2][Kref2.FaceToVertexIndices[iFace2, i]];
}
var Trafo = this.m_owner.Edges.GetPeriodicTrafo(iEdg, true);
double Tol = Math.Min(FVtx1G.MindistBetweenRows(), FVtx1G.MindistBetweenRows()) * 1.0e-3;
int[] R = NodeCorrespondence(FVtx1G, Trafo, FVtx2G, Tol);
// Es sollte gelten:
// GlobIdxFace1[R[k]] <==periodic==> GlobIdxFace2[k]
for (int k = 0; k < L; k++) {
int iVtx1 = GlobIdxFace1[R[k]];
int iVtx2 = GlobIdxFace2[k];
if (PeriodicPeer[iVtx1] == null)
PeriodicPeer[iVtx1] = new List<int>();
if (PeriodicPeer[iVtx2] == null)
PeriodicPeer[iVtx2] = new List<int>();
if (!PeriodicPeer[iVtx1].Contains(iVtx2))
PeriodicPeer[iVtx1].Add(iVtx2);
if (!PeriodicPeer[iVtx2].Contains(iVtx1))
PeriodicPeer[iVtx2].Add(iVtx1);
}
AnythingPeriodic = true;
}
}
// eliminate periodic
// ==================
if (AnythingPeriodic) {
this.PeriodicIdenitiesTmp = new List<Tuple<int, int>>();
for (int iVtx = 0; iVtx < NoOfVtx; iVtx++) {
List<int> pp = PeriodicPeer[iVtx];
if (pp != null) {
if (!pp.Contains(iVtx))
pp.Add(iVtx);
for (int i0 = 0; i0 < pp.Count; i0++) {
for (int i1 = i0 + 1; i1 < pp.Count; i1++) {
var T = new Tuple<int, int>(pp[i0], pp[i1]);
if(!this.PeriodicIdenitiesTmp.Contains(T, (A,B) => (
(A.Item1 == B.Item1 && A.Item2 == B.Item2)
|| (A.Item2 == B.Item1 && A.Item1 == B.Item2) ))) {
this.PeriodicIdenitiesTmp.Add(T);
}
}
}
}
}
}
csMPI.Raw.Barrier(csMPI.Raw._COMM.WORLD);
}
/// <summary>
/// Geometrical matching of nodes.
/// </summary>
/// <param name="NodesIn">
/// First set of nodes.
/// </param>
/// <param name="ict"></param>
/// <param name="NodesOut">
/// second set of nodes.
/// </param>
/// <param name="Tol">
/// Some tolerance
/// </param>
/// <returns>
/// A permutation R, so that for all valid indices k,
/// <paramref name="NodesOut"/>[R[k]] == <paramref name="ict"/>(<paramref name="NodesIn"/>[k]).
/// </returns>
static int[] NodeCorrespondence(MultidimensionalArray NodesIn, AffineTrafo ict, MultidimensionalArray NodesOut, double Tol) {
var NodesInTrf = MultidimensionalArray.Create(NodesIn.Lengths);
ict.Transform(NodesIn, NodesInTrf);
if (!ArrayTools.ListEquals(NodesInTrf.Lengths, NodesOut.Lengths))
throw new ApplicationException("Error in algorithm.");
int NoOfNodes = NodesIn.GetLength(0);
var R = new int[NoOfNodes];
for (int kOut = 0; kOut < NoOfNodes; kOut++) {
var vOut = NodesOut.GetRow(kOut);
bool bFound = false;
for (int kIn = 0; kIn < NoOfNodes; kIn++) {
var vIn = NodesInTrf.GetRow(kIn);
if (GenericBlas.L2Dist(vOut, vIn) < Tol) {
bFound = true;
R[kOut] = kIn;
break;
}
}
if (bFound == false)
throw new ApplicationException("Error in algorithm.");
}
return R;
}
/// <summary>
/// Work-around for a bug in Mono that has problems
/// (de)serializing staggered arrays
/// </summary>
[Serializable]
class VertexSharingData {
/// <summary>
/// 1st index: cell
/// 2nd index: cell vertex
/// 3rd index: collection
/// </summary>
public Tuple<int, int>[][][] Data;
}
internal void NegogiateSharing() {
int J = this.m_owner.Cells.NoOfLocalUpdatedCells;
int[][] SendLists = m_owner.Parallel.SendCommLists;
int[] InsertIndex = m_owner.Parallel.RcvCommListsInsertIndex;
int[] RcvNoOfItems = m_owner.Parallel.RcvCommListsNoOfItems;
int size = this.m_owner.MpiSize;
int myRank = this.m_owner.MpiRank;
var Celldat = m_owner.Cells;
int K = this.Count; // including purly external!
bool containsPeriodic = this.PeriodicEliminatedPoints != null;
// PHASE 1: determine vertex indices on other processors
// =====================================================
// 1st index: local vertex index
// 2nd index: enum
// Item1: processor rank 'R'
// Item2: local vertex index on processor 'R'
Tuple<int, int>[][] VertexIndicesOnOtherProcessors = new Tuple<int, int>[K][];
BitArray NonExternalMarker = new BitArray(K); // false on all vertices that are "pure external" (only used by external cells)
{
// mark all vertices on locally updated cells
for (int j = 0; j < J; j++) {
int[] CV = Celldat.CellVertices[j];
foreach (int k in CV)
NonExternalMarker[k] = true;
}
// add the vertex index on this processor
for (int k = 0; k < K; k++) {
if (NonExternalMarker[k])
VertexIndicesOnOtherProcessors[k] = new Tuple<int, int>[] { new Tuple<int, int>(myRank, k) };
else
VertexIndicesOnOtherProcessors[k] = new Tuple<int, int>[0];
}
if (this.PeriodicIdenitiesTmp != null) {
foreach (var kv in this.PeriodicIdenitiesTmp) {
int iVtx1 = kv.Item1;
int iVtx2 = kv.Item2;
// 'iVtx1' and 'iVtx2' are identical due to periodicity
if (NonExternalMarker[iVtx2])
(new Tuple<int, int>(myRank, iVtx2)).AddToArray(ref VertexIndicesOnOtherProcessors[iVtx1]);
if (NonExternalMarker[iVtx1])
(new Tuple<int, int>(myRank, iVtx1)).AddToArray(ref VertexIndicesOnOtherProcessors[iVtx2]);
}
}
// send vertex indices to other processors
// =======================================
int SomeChange;
do {
// This has to be done repetitive:
// e.g. the center vertex x may be shared by 4 processes,
//
// *-------*-------*
// | rank0 | rank1 |
// *-------x-------*
// | rank2 | rank3 |
// *-------*-------*
//
// but each process has only two neighbours (with respect to cell-neighbourship).
// Thus, in one pass e.g. rank 0 only gets to know that it shares x with rank 1 and rank 2,
// while rank 1 gets to know that it shares x with rank 0 and rank 3.
// In the secon pass, rank 1 informs rank 0 that x is also shared by rank 3, and vice-versa.
SomeChange = 0;
Dictionary<int, VertexSharingData> SendData = new Dictionary<int, VertexSharingData>();
for (int proc = 0; proc < size; proc++) { // loop over MPI process ranks
int[] SendList = SendLists[proc];
if (SendList == null)
continue;
var SndItem = new VertexSharingData();
SndItem.Data = new Tuple<int, int>[SendList.Length][][];
for (int jj = 0; jj < SendList.Length; jj++) { // loop over all cells that will be send to processor #'proc'
int jCell = SendList[jj];
//var Kref = Celldat.GetRefElement(jCell);
int[] CellVtx = Celldat.CellVertices[jCell];
SndItem.Data[jj] = new Tuple<int, int>[CellVtx.Length][];
for (int i = 0; i < CellVtx.Length; i++) { // loop over cell vertices
SndItem.Data[jj][i] = VertexIndicesOnOtherProcessors[CellVtx[i]];
}
}
SendData.Add(proc, SndItem);
}
var RcvData = SerialisationMessenger.ExchangeData(SendData, csMPI.Raw._COMM.WORLD);
foreach (var kv in RcvData) {
int proc = kv.Key;
VertexSharingData RcvItem = kv.Value;
int jCell0 = InsertIndex[proc];
int L = RcvItem.Data.Length;
Debug.Assert(L == RcvNoOfItems[proc]);
for (int l = 0; l < L; l++) { // loop over received cells
int jCell = jCell0 + l;
int[] CellVtx = Celldat.CellVertices[jCell];
var VtxIndex_jCell = RcvItem.Data[l];
Debug.Assert(VtxIndex_jCell.Length == Celldat.GetRefElement(jCell).NoOfVertices);
for (int i = 0; i < VtxIndex_jCell.Length; i++) { // loop over cell vertices
foreach (Tuple<int, int> ProcIvtx in VtxIndex_jCell[i]) {
int k = CellVtx[i];
bool contains = VertexIndicesOnOtherProcessors[k].Contains(ProcIvtx, delegate (Tuple<int, int> a, Tuple<int, int> b) {
bool ret1 = a.Item1 == b.Item1; // equal processor rank
bool ret2 = a.Item2 == b.Item2; // equal vertex index
//Debug.Assert((ret1 == false || a.Item2 == b.Item2)
// || (containsPeriodic && (this.PeriodicEliminatedPoints.Keys.Contains(a.Item2) || this.PeriodicEliminatedPoints.Keys.Contains(b.Item2))));
return ret1 && ret2;
});
if (!contains) {
SomeChange = 0xFFF;
ProcIvtx.AddToArray(ref VertexIndicesOnOtherProcessors[k]);
}
}
}
}
}
if (this.PeriodicIdenitiesTmp != null) {
// ++++++++++++++++++
// periodic exchange
// ++++++++++++++++++
foreach (var kv in this.PeriodicIdenitiesTmp) {
int iVtx1 = kv.Item1;
int iVtx2 = kv.Item2;
// 'iVtx1' and 'iVtx2' are identical due to periodicity
// ensure that 'list1' and 'list2' are equal in a set-sense, i.e.
// contain the same elements; the sequence does not matter.
for (int iii = 0; iii <= 2; iii++) {
foreach (var T in VertexIndicesOnOtherProcessors[iVtx2]) {
bool contains = VertexIndicesOnOtherProcessors[iVtx1].Contains(T, delegate (Tuple<int, int> a, Tuple<int, int> b) {
bool ret1 = a.Item1 == b.Item1; // equal processor rank
bool ret2 = a.Item2 == b.Item2; // equal vertex index
return ret1 && ret2;
});
if (!contains) {
SomeChange = 0xFFF;
T.AddToArray(ref VertexIndicesOnOtherProcessors[iVtx1]);
}
}
// swap the indices for the second run of the 'iii'-loop
int iv1tmp = iVtx1;
iVtx1 = iVtx2;
iVtx2 = iv1tmp;
}
}
}
unsafe {
int globSomeChange = 0;
csMPI.Raw.Allreduce((IntPtr)(&SomeChange), (IntPtr)(&globSomeChange), 1, csMPI.Raw._DATATYPE.INT, csMPI.Raw._OP.MAX, csMPI.Raw._COMM.WORLD);
SomeChange = globSomeChange;
}
} while (SomeChange != 0);
this.PeriodicIdenitiesTmp = null;
}
// PHASE2: negotiate Ownership
// ===========================
// VERTEX OWNERSHIP NEGOGIATION:
// * if a vertex is owned by more than two processors, than the process with the lowest MPI rank will be the owner
// (these won't be a lot, so it should produce no significant load imbalance)
// * vertices shared by exactly two processors are shared between them in zu gleichen Teilen
// Arten von Vertices
// (A) purly local
// (B) shared/gehört mir == relayed
// (C) shared/gehört wem anderen == borrowed
// (D) external (nur von external cells benutzt);
// Was will ich wissen?
// Für jeden (C): Welcher Prozessor besitzt ihn? Welchen Index hat er dort?
int[] VerticePermuation;
int NoOfPureLocal;
int NoOfRelayed;
int NoOfBorrowed;
int NoOfExternal;
int NoOfPeriodicElim;
int[][] VtxSendLists;
int[][] VtxInsertLists;
Tuple<int, int>[] PeriodicElim;
/*
using (var diag = new System.IO.StreamWriter("NegOwInput-Proc" + m_owner.MyRank + ".txt")) {
for (int k = 0; k < K; k++) {
diag.Write(k);
diag.Write(" ");
diag.Write(this.Coordinates[k, 0] + " " + this.Coordinates[k, 1]);
diag.Write(" ");
diag.Write(NonExternalMarker[k]);
diag.Write(" ");
foreach (var t in VertexIndicesOnOtherProcessors[k]) {
diag.Write("(" + t.Item1 + "," + t.Item2 + ") ");
}
diag.WriteLine();
}
}
*/
NegogiateOwnership(csMPI.Raw._COMM.WORLD, VertexIndicesOnOtherProcessors,
out VerticePermuation,
out NoOfPureLocal, out NoOfRelayed, out NoOfBorrowed, out NoOfPeriodicElim, out NoOfExternal,
out VtxSendLists, out VtxInsertLists,
out PeriodicElim);
// PHASE 4: apply permutation of vertices
// ======================================
{
int[] invVerticePermuation = new int[K];
for (int k = 0; k < K; k++) {
invVerticePermuation[VerticePermuation[k]] = k;
}
MultidimensionalArray _vertice = this.Coordinates;
MultidimensionalArray newVertice = MultidimensionalArray.Create(_vertice.Lengths);
Debug.Assert(newVertice.Dimension == 2);
int[][] _Vertice2Cell = this.VerticeToCell;
int[][] newVertice2Cell = new int[K][];
for (int k = 0; k < K; k++) {
newVertice2Cell[k] = _Vertice2Cell[VerticePermuation[k]];
newVertice.ExtractSubArrayShallow(k, -1).Set(_vertice.ExtractSubArrayShallow(VerticePermuation[k], -1));
}
this.Coordinates = newVertice;
this.VerticeToCell = newVertice2Cell;
var CV = this.m_owner.Cells.CellVertices;
for (int j = 0; j < CV.Length; j++) {
CV[j] = CV[j].Select(k => invVerticePermuation[k]).ToArray();
}
if (PeriodicElim.Count() > 0) {
int i0_Src = NoOfPureLocal + NoOfBorrowed + NoOfRelayed;
int iE_Src = i0_Src + NoOfPeriodicElim;
int i0_Trg = 0;
int iE_Trg = NoOfPureLocal + NoOfBorrowed + NoOfRelayed;
//Debugger.Launch();
SortedDictionary<int, int> newPeriodicEliminatedPoints = new SortedDictionary<int, int>();
foreach (var t in PeriodicElim) {
int elimSrc = invVerticePermuation[t.Item1];
int elimTrg = invVerticePermuation[t.Item2];
Debug.Assert(elimSrc >= i0_Src);
Debug.Assert(elimSrc < iE_Src);
Debug.Assert(elimTrg >= i0_Trg);
Debug.Assert(elimTrg < iE_Trg);
//if (newPeriodicEliminatedPoints.Keys.Contains(elimSrc))
// Debugger.Launch();
newPeriodicEliminatedPoints.Add(elimSrc, elimTrg);
}
this.PeriodicEliminatedPoints = newPeriodicEliminatedPoints;
} else {
PeriodicEliminatedPoints = new SortedDictionary<int, int>();
}
// transform send lists (based on un-permuded indices)
for (int rnk = 0; rnk < size; rnk++) {
if (VtxSendLists[rnk] != null) {
VtxSendLists[rnk] = VtxSendLists[rnk].Select(k => invVerticePermuation[k]).ToArray();
}
}
// transform insert lists
for (int rnk = 0; rnk < size; rnk++) {
if (VtxInsertLists[rnk] != null) {
VtxInsertLists[rnk] = VtxInsertLists[rnk].Select(k => invVerticePermuation[k]).ToArray();
}
}
}
// set data
// ========
this.NoOfPurelyLocal = NoOfPureLocal;
this.NoOfRelayed = NoOfRelayed;
this.NoOfBorrowed = NoOfBorrowed;
this.NoOfExternal = NoOfExternal;
this.NoOfPeriodicElim = NoOfPeriodicElim;
this.VertexSendLists = VtxSendLists;
this.VertexInsertLists = VtxInsertLists;
// write data (debugging)
// ======================
/*
{
int D = this.m_owner.SpatialDimension;
using (var stw = new System.IO.StreamWriter("Vertex_" + myRank + ".txt")) {
stw.WriteLine("Rank: " + myRank);
stw.WriteLine("NoOf pure local: {0}", NoOfPureLocal);
stw.WriteLine("NoOf relayed: {0}", NoOfRelayed);
stw.WriteLine("NoOf borrowed: {0}", NoOfBorrowed);
stw.WriteLine("NoOf periodic elim: {0}", NoOfPeriodicElim);
stw.WriteLine("NoOf external: {0}", NoOfExternal);
stw.WriteLine("Vertex List:");
for (int k = 0; k < K; k++) {
stw.Write(k);
stw.Write("\t");
for (int d = 0; d < D; d++) {
stw.Write(this.Coordinates[k, d]);
stw.Write("\t");
}
int OwnerProcess;
if (k < NoOfPureLocal + NoOfRelayed) {
OwnerProcess = myRank;
} else if (k < NoOfPureLocal + NoOfRelayed + NoOfBorrowed) {
OwnerProcess = 22; // BorrowedOwnership[k - (NoOfPureLocal + NoOfRelayed)];
} else {
OwnerProcess = -1;
}
stw.Write(OwnerProcess);
//stw.Write("\t");
stw.WriteLine();
}
stw.WriteLine("-----------------------");
stw.WriteLine("Send Lists:");
for (int rnk = 0; rnk < size; rnk++) {
if (VtxSendLists[rnk] == null) {
continue;
}
stw.Write(rnk + ":\t");
for (int i = 0; i < VtxSendLists[rnk].Length; i++) {
stw.Write(VtxSendLists[rnk][i]);
if( i < (VtxSendLists[rnk].Length - 1))
stw.Write(",");
else
stw.Write(";");
}
stw.WriteLine();
}
stw.WriteLine("-----------------------");
stw.WriteLine("Insert Lists:");
for (int rnk = 0; rnk < size; rnk++) {
if (VtxInsertLists[rnk] == null) {
continue;
}
stw.Write(rnk + ":\t");
for (int i = 0; i < VtxInsertLists[rnk].Length; i++) {
stw.Write(VtxInsertLists[rnk][i]);
if (i < (VtxInsertLists[rnk].Length - 1))
stw.Write(",");
else
stw.Write(";");
}
stw.WriteLine();
}
stw.WriteLine("-----------------------");
stw.WriteLine("Local periodic elminiations: {0}", this.PeriodicEliminatedPoints.Count);
foreach (var kv in this.PeriodicEliminatedPoints) {
stw.WriteLine("{0} -> {1}", kv.Key, kv.Value);
}
}
} // */
}
}
/// <summary>
/// Negogiation of MPI-Ownership for 'items' (e.g. vertices or edges).
/// </summary>
private static void NegogiateOwnership(MPI_Comm comm, Tuple<int, int>[][] ItemIndicesOnOtherProcessors,
out int[] ItemPermutation,
out int NoOfPureLocal, out int NoOfRelayed, out int NoOfBorrowed, out int NoOfPeriodicElim, out int NoOfExternal,
out int[][] SendLists, out int[][] InsertLists,
out Tuple<int,int>[] LocalDuplicates
) {
using (var tr = new FuncTrace()) {
int size, myRank;
csMPI.Raw.Comm_Rank(comm, out myRank);
csMPI.Raw.Comm_Size(comm, out size);
int K = ItemIndicesOnOtherProcessors.Length; //
BitArray ActiveItemsMarker = new BitArray(K);
for (int k = 0; k < K; k++) {
if (ItemIndicesOnOtherProcessors[k] == null || ItemIndicesOnOtherProcessors[k].Length <= 0) {
ActiveItemsMarker[k] = false;
} else {
var Test = ItemIndicesOnOtherProcessors[k].SingleOrDefault(t => t.Item1 == myRank && t.Item2 == k);
ActiveItemsMarker[k] = (Test != null);
}
}
ItemPermutation = new int[K];
NoOfPureLocal = 0;
NoOfRelayed = 0;
// marks all vertices which are owned by this process
BitArray Owned = new BitArray(K);
BitArray LocalElim = new BitArray(K); // item 'k' where the 'LocalElim[k]'-flag is set will be moved
// to the end, i.e. after the borrowed items.
// It marks representants that are redundant locally.
List<Tuple<int, int>> LocalIdentities = new List<Tuple<int, int>>();
// find the local identities
// =========================
for (int k = 0; k < K; k++) { // loop over items...
if (!ActiveItemsMarker[k])
// don't bother
continue;
if (LocalElim[k]) {
// already eliminated
Debug.Assert(LocalIdentities.Where(T => T.Item1 == k).Count() == 1); // the 'LocalIdentities' must already contain item 'k'
continue;
}
var Equivals = ItemIndicesOnOtherProcessors[k]; // equivalences of item 'k'
if (Equivals.Length <= 0)
throw new ArgumentException();
if (Equivals.Length == 1) {
Debug.Assert(Equivals[0].Item1 == myRank);
// no known equivalences
continue;
}
foreach (var T in Equivals) {
if (T.Item1 == myRank && T.Item2 != k) {
LocalElim[T.Item2] = true;
var lid = new Tuple<int, int>(T.Item2, k);
Debug.Assert(lid.Item1 > lid.Item2); // the eliminated representative 'lid.Item2' of some item must be higher than the representative 'k' which is kept
Debug.Assert(LocalIdentities.Contains(lid, (A, B) => A.Item1 == B.Item1 && A.Item2 == B.Item2) == false);
LocalIdentities.Add(lid); // 'T.Item2' is equivalent to 'k': we select 'k' as a representative of the item.
}
}
}
// for each MPI process,
// collect the vertices that are shared with this process
// ======================================================
HashSet<int>[] _SharedVertices = new HashSet<int>[size];
for (int k = 0; k < K; k++) {
if (!ActiveItemsMarker[k])
// don't consider representative k
continue;
if (LocalElim[k])
// already eliminated
continue;
var VS_k = ItemIndicesOnOtherProcessors[k];
Debug.Assert(VS_k.Length > 0);
if (VS_k.Length == 1 || VS_k.Select(T => T.Item1).ToSet().Count == 1) {
// Vertex is purly local
Debug.Assert(VS_k[0].Item1 == myRank); // 'k's without 'myRank' should already be excluded by 'ActiveItemsMarker'
ItemPermutation[NoOfPureLocal] = k;
NoOfPureLocal++;
Owned[k] = true;
} else {
foreach (Tuple<int, int> t in VS_k) {
int proc = t.Item1;
if (proc == myRank)
continue;
if (_SharedVertices[proc] == null) {
_SharedVertices[proc] = new HashSet<int>();
}
_SharedVertices[proc].Add(k);
}
}
}
// sort the shared vertices
// (i am not sure if that is really necessary)
List<int>[] SharedVertices = _SharedVertices.Select(hs => hs != null ? (new List<int>(hs)) : default(List<int>)).ToArray();
foreach (var lst in SharedVertices) {
if (lst != null)
lst.Sort();
}
Debug.Assert(SharedVertices[myRank] == null);
// determine 'RELAYED' and 'BORROWED' items,
// i.e. determine ownership of shared items
// ================================================
BitArray RankDetermined = new BitArray(K);
List<int> RelayedItems = new List<int>();
Dictionary<int, int[]> SendData2 = new Dictionary<int, int[]>();
for (int otherRank = myRank + 1; otherRank < size; otherRank++) {
List<int> SV_proc = SharedVertices[otherRank];
if (SV_proc == null)
// sharing no vertex with processor 'otherRank'
continue;
// List of items for which this process is responsible to
// distribute
List<int> ItemsToDistribute = new List<int>();
foreach (int kItem in SV_proc) { // loop over all items shared with processor 'otherRank'...
if (LocalElim[kItem])
continue;
if (!ActiveItemsMarker[kItem])
continue;
if (RankDetermined[kItem])
// this item is shared by more than two processors,
// but an owner was already assigned.
continue;
Debug.Assert(Owned[kItem] == false);
var OnOther = ItemIndicesOnOtherProcessors[kItem];
int minProc = OnOther.Select(T => T.Item1).Min();
Debug.Assert(OnOther.Select(T => T.Item1).Max() > minProc); // if not at least two different process ranks, something is worng with the sharing.
if (minProc == myRank) {
// ++++++++++++++++++++++++++++++++++++++++++++
// This process is responsible for determining
// the ownership of the item represented by 'k'
// ++++++++++++++++++++++++++++++++++++++++++++
Debug.Assert(!ItemsToDistribute.Contains(kItem));
Debug.Assert(LocalElim[kItem] == false);
ItemsToDistribute.Add(kItem);
RankDetermined[kItem] = true; // the owner rank of this item will be determined immediately (see below)!
// 'kItem' will be owned either by 'myRank' or 'otherRank'
}
}
// keep the first half of items for myself... (RELAYED)
int L2 = ItemsToDistribute.Count / 2;
int l;
for (l = 0; l < L2; l++) {
int kItem = ItemsToDistribute[l];
bool found = false;
foreach (var T in ItemIndicesOnOtherProcessors[kItem]) {
if (T.Item1 == myRank && ActiveItemsMarker[T.Item2] == true) {
if (T.Item2 == kItem) {
found = true;
Debug.Assert(Owned[kItem] == false);
Owned[kItem] = true;
Debug.Assert(LocalElim[kItem] == false);
ItemPermutation[NoOfPureLocal + NoOfRelayed] = kItem;
RelayedItems.Add(kItem);
NoOfRelayed++;
} else {
Debug.Assert(LocalIdentities.Contains(new Tuple<int, int>(T.Item2, kItem), (A, B) => A.Item1 == B.Item1 && A.Item2 == B.Item2) == true);
Debug.Assert(LocalElim[T.Item2] == true);
}
}
}
Debug.Assert(found == true);
}
// ... and hand the second half of items to the other process (BORROWED)
int[] OwnedByOther = new int[ItemsToDistribute.Count - L2];
for (; l < ItemsToDistribute.Count; l++) {
int k_myRank = ItemsToDistribute[l];
var OnOther = ItemIndicesOnOtherProcessors[k_myRank];
RankDetermined[k_myRank] = true;
int k_otherRank = OnOther.Where(T => T.Item1 == otherRank).Min(T => T.Item2); // pick the minimum representative 'k_otherRank' on processor 'otherRank'
// for the item represented by 'k_myRank' on this processor
OwnedByOther[l - L2] = k_otherRank;
}
SendData2.Add(otherRank, OwnedByOther);
}
csMPI.Raw.Barrier(csMPI.Raw._COMM.WORLD);
// andere prozesse senden uns Indices,
// mein schatz,
// die nur uns gehören.
var RcvData2 = SerialisationMessenger.ExchangeData(SendData2, comm);
foreach (var kv in RcvData2) {
int rcvProc = kv.Key; // data was received from process 'rcvProc'
int[] OurVertices = kv.Value;
foreach (int k_mein in OurVertices) { // loop over all items that belong to me!
Debug.Assert(ItemIndicesOnOtherProcessors[k_mein].Where(T => T.Item1 == rcvProc).Count() >= 1);
Debug.Assert(ItemIndicesOnOtherProcessors[k_mein].Where(T => T.Item1 == myRank && T.Item2 == k_mein).Count() >= 1);
Debug.Assert(LocalElim[k_mein] == false);
Debug.Assert(ActiveItemsMarker[k_mein] == true);
bool found = false;
foreach (var T in ItemIndicesOnOtherProcessors[k_mein]) {
if (T.Item1 == myRank && ActiveItemsMarker[T.Item2] == true) {
Debug.Assert(Owned[T.Item2] == false);
if (T.Item2 == k_mein) {
found = true;
ItemPermutation[NoOfPureLocal + NoOfRelayed] = k_mein;
NoOfRelayed++;
Debug.Assert(Owned[k_mein] == false);
RelayedItems.Add(k_mein);
Owned[k_mein] = true;
Debug.Assert(LocalElim[k_mein] == false);
} else {
Debug.Assert(LocalIdentities.Contains(new Tuple<int, int>(T.Item2, k_mein), (A, B) => A.Item1 == B.Item1 && A.Item2 == B.Item2) == true);
Debug.Assert(LocalElim[T.Item2] == true);
}
}
}
Debug.Assert(found == true);
}
}
// ++++++++
// Nun sollten alle Items genau einen Besitzer haben!
// ++++++++
// collect borrowed vertices
// =========================
{
NoOfBorrowed = 0;
for (int k = 0; k < K; k++) { // loop over vertices...
if (Owned[k] || !ActiveItemsMarker[k] || LocalElim[k]) // ignore: owned, external, periodic eliminations
continue;
// if we reach this point, 'k' is (representing) a borrowed item
ItemPermutation[NoOfPureLocal + NoOfRelayed + NoOfBorrowed] = k;// sharedForeign[i].Item1;
NoOfBorrowed++;
}
}
// determine send lists
// ====================
{
List<int>[] _VtxSendLists = new List<int>[size];
List<int>[] TargetIndices = new List<int>[size];
foreach (int k in RelayedItems) {
Debug.Assert(Owned[k]);
Debug.Assert(ActiveItemsMarker[k]);
Debug.Assert(!LocalElim[k]);
var OnOther = ItemIndicesOnOtherProcessors[k];
ISet<int> Processores = OnOther.Select(T => T.Item1).ToSet();
Debug.Assert(Processores.Contains(myRank));
Processores.Remove(myRank);
foreach (int TargetRank in Processores) {
int k_Target = OnOther.Where(T => T.Item1 == TargetRank).Min(T => T.Item2);
if (_VtxSendLists[TargetRank] == null) {
_VtxSendLists[TargetRank] = new List<int>();
TargetIndices[TargetRank] = new List<int>();
}
_VtxSendLists[TargetRank].Add(k);
TargetIndices[TargetRank].Add(k_Target);
}
}
SendLists = _VtxSendLists.Select(list => list != null ? list.ToArray() : null).ToArray();
Dictionary<int, int[]> TargetIndicesBla = new Dictionary<int, int[]>();
for (int p = 0; p < size; p++) {
if (TargetIndices[p] != null)
TargetIndicesBla.Add(p, TargetIndices[p].ToArray());
}
var ReceiveIndices = SerialisationMessenger.ExchangeData(TargetIndicesBla, comm);
InsertLists = new int[size][];
foreach (var kv in ReceiveIndices) {
int rcvRank = kv.Key;
int[] InsList = kv.Value;
InsertLists[rcvRank] = InsList;
Debug.Assert(InsList.Where(k_Item => Owned[k_Item] == true).Count() <= 0);
Debug.Assert(InsList.Where(k_Item => LocalElim[k_Item] == true).Count() <= 0);
Debug.Assert(InsList.Where(k_Item => ActiveItemsMarker[k_Item] == false).Count() <= 0);
}
}
// sorting of periodic eliminations
// ================================
{
int ii = 0;
for (int k = 0; k < K; k++) {
if (LocalElim[k] && ActiveItemsMarker[k]) {
// vertex k is eliminated due to a periodic identity
ItemPermutation[NoOfPureLocal + NoOfRelayed + NoOfBorrowed + ii] = k;
ii++;
}
}
NoOfPeriodicElim = ii;
LocalDuplicates = LocalIdentities.ToArray();
}
// sorting of purly external
// =========================
{
int ii = 0;
for (int k = 0; k < K; k++) {
if (ActiveItemsMarker != null && !ActiveItemsMarker[k]) {
// vertex k is used purly by external cells
ItemPermutation[NoOfPureLocal + NoOfRelayed + NoOfBorrowed + NoOfPeriodicElim + ii] = k;
ii++;
}
}
NoOfExternal = ii;
}
}
}
}
}
| 45.420595 | 240 | 0.409148 | [
"Apache-2.0"
] | FDYdarmstadt/BoSSS | src/L2-foundation/BoSSS.Foundation/GridData_Vertice.cs | 61,264 | C# |
using System;
using System.Collections.Generic;
namespace Xms.Business.SerialNumber
{
public interface ISerialNumberRuleUpdater
{
bool Update(Domain.SerialNumberRule entity);
bool UpdateState(IEnumerable<Guid> ids, bool isEnabled);
}
} | 24.090909 | 64 | 0.735849 | [
"MIT"
] | feilingdeng/xms | Libraries/Business/Xms.Business.SerialNumber/ISerialNumberRuleUpdater.cs | 267 | C# |
using CleanArchitecture.Services.Pipeline;
namespace CleanArchitecture.Services.Infrastructure
{
public class BusinessRuleValidatorUseCaseElement<TValidationResult> : IUseCaseElement where TValidationResult : IValidationResult
{
#region - - - - - - Fields - - - - - -
private readonly UseCaseServiceResolver m_ServiceResolver;
#endregion Fields
#region - - - - - - Constructors - - - - - -
public BusinessRuleValidatorUseCaseElement(UseCaseServiceResolver serviceResolver)
=> this.m_ServiceResolver = serviceResolver;
#endregion Constructors
#region - - - - - - IUseCaseElement Implementation - - - - - -
public async Task HandleAsync<TUseCaseInputPort, TUseCaseOutputPort>(
TUseCaseInputPort inputPort,
TUseCaseOutputPort outputPort,
UseCaseElementHandleAsync nextUseCaseElementHandle,
CancellationToken cancellationToken)
{
if (outputPort is IBusinessRuleValidationOutputPort<TValidationResult> _OutputPort)
{
var _ValidationResultAsync = this.GetValidationResultAsync(inputPort, cancellationToken);
if (_ValidationResultAsync != null && !(await _ValidationResultAsync).IsValid)
{
await _OutputPort.PresentBusinessRuleValidationFailureAsync(await _ValidationResultAsync, cancellationToken).ConfigureAwait(false);
return;
}
}
await nextUseCaseElementHandle().ConfigureAwait(false);
}
#endregion IUseCaseElement Implementation
#region - - - - - - Methods - - - - - -
private Task<TValidationResult>? GetValidationResultAsync<TUseCaseInputPort>(TUseCaseInputPort inputPort, CancellationToken cancellationToken)
=> inputPort is IUseCaseInputPort<IBusinessRuleValidationOutputPort<TValidationResult>>
? this.GetValidationInvoker(inputPort)?.GetValidationResultAsync(cancellationToken)
: null;
private ValidationInvoker? GetValidationInvoker<TUseCaseInputPort>(TUseCaseInputPort inputPort)
=> (ValidationInvoker?)Activator.CreateInstance(
typeof(ValidationInvoker<>).MakeGenericType(typeof(TValidationResult), typeof(TUseCaseInputPort)),
inputPort,
this.m_ServiceResolver);
#endregion Methods
#region - - - - - - Nested Classes - - - - - -
private abstract class ValidationInvoker
{
#region - - - - - - Methods - - - - - -
public abstract Task<TValidationResult>? GetValidationResultAsync(CancellationToken cancellationToken);
#endregion Methods
}
private class ValidationInvoker<TUseCaseInputPort> : ValidationInvoker
where TUseCaseInputPort : IUseCaseInputPort<IBusinessRuleValidationOutputPort<TValidationResult>>
{
#region - - - - - - Fields - - - - - -
private readonly TUseCaseInputPort m_InputPort;
private readonly UseCaseServiceResolver m_ServiceResolver;
#endregion Fields
#region - - - - - - Constructors - - - - - -
public ValidationInvoker(TUseCaseInputPort inputPort, UseCaseServiceResolver serviceResolver)
{
this.m_InputPort = inputPort;
this.m_ServiceResolver = serviceResolver;
}
#endregion Constructors
#region - - - - - - Methods - - - - - -
public override Task<TValidationResult>? GetValidationResultAsync(CancellationToken cancellationToken)
=> this.m_ServiceResolver
.GetService<IUseCaseBusinessRuleValidator<TUseCaseInputPort, TValidationResult>>()?
.ValidateAsync(this.m_InputPort, cancellationToken);
#endregion Methods
}
#endregion Nested Classes
}
}
| 36.4 | 151 | 0.643107 | [
"MIT"
] | Robertscorp/clean-architecture-services | CleanArchitecture.Services/Infrastructure/BusinessRuleValidatorUseCaseElement.cs | 4,006 | C# |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
using Aliyun.Acs.Core.Transform;
using Aliyun.Acs.R_kvstore.Model.V20150101;
using System;
using System.Collections.Generic;
namespace Aliyun.Acs.R_kvstore.Transform.V20150101
{
public class DescribeInstanceSSLResponseUnmarshaller
{
public static DescribeInstanceSSLResponse Unmarshall(UnmarshallerContext context)
{
DescribeInstanceSSLResponse describeInstanceSSLResponse = new DescribeInstanceSSLResponse();
describeInstanceSSLResponse.HttpResponse = context.HttpResponse;
describeInstanceSSLResponse.RequestId = context.StringValue("DescribeInstanceSSL.RequestId");
describeInstanceSSLResponse.InstanceId = context.StringValue("DescribeInstanceSSL.InstanceId");
describeInstanceSSLResponse.SSLEnabled = context.StringValue("DescribeInstanceSSL.SSLEnabled");
describeInstanceSSLResponse.CertCommonName = context.StringValue("DescribeInstanceSSL.CertCommonName");
describeInstanceSSLResponse.SSLExpiredTime = context.StringValue("DescribeInstanceSSL.SSLExpiredTime");
return describeInstanceSSLResponse;
}
}
} | 45.214286 | 107 | 0.784623 | [
"Apache-2.0"
] | brightness007/unofficial-aliyun-openapi-net-sdk | aliyun-net-sdk-r-kvstore/R_kvstore/Transform/V20150101/DescribeInstanceSSLResponseUnmarshaller.cs | 1,899 | C# |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
using System.Collections.Generic;
using Aliyun.Acs.Core;
namespace Aliyun.Acs.Ess.Model.V20140828
{
public class DisableScalingGroupResponse : AcsResponse
{
private string requestId;
public string RequestId
{
get
{
return requestId;
}
set
{
requestId = value;
}
}
}
}
| 26.418605 | 63 | 0.71831 | [
"Apache-2.0"
] | AxiosCros/aliyun-openapi-net-sdk | aliyun-net-sdk-ess/Ess/Model/V20140828/DisableScalingGroupResponse.cs | 1,136 | C# |
using System.Collections.Generic;
using CustomJSONData;
using CustomJSONData.CustomBeatmap;
using HarmonyLib;
using JetBrains.Annotations;
using static NoodleExtensions.NoodleController;
namespace NoodleExtensions.HarmonyPatches.LeftHanded
{
[HarmonyPatch(typeof(BeatmapDataMirrorTransform))]
[HarmonyPatch("CreateTransformedData")]
internal static class BeatDataMirrorTransformCreateTransformedData
{
[UsedImplicitly]
private static void Postfix(IReadonlyBeatmapData __result)
{
foreach (BeatmapEventData beatmapEventData in __result.beatmapEventsData)
{
if (!beatmapEventData.type.IsRotationEvent() || beatmapEventData is not CustomBeatmapEventData customData)
{
continue;
}
Dictionary<string, object?> dynData = customData.customData;
float? rotation = dynData.Get<float?>(ROTATION);
if (rotation.HasValue)
{
dynData["_rotation"] = rotation * -1;
}
}
}
}
}
| 32 | 122 | 0.633929 | [
"MIT"
] | Aeroluna/Heck | NoodleExtensions/HarmonyPatches/LeftHanded/BeatmapDataMirrorTransform.cs | 1,122 | 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 System.Reflection
{
[Flags]
public enum ResourceAttributes
{
Public = 0x0001,
Private = 0x0002,
}
}
| 24.714286 | 71 | 0.690751 | [
"MIT"
] | 06needhamt/runtime | src/libraries/System.Private.CoreLib/src/System/Reflection/ResourceAttributes.cs | 346 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace FlowChartVarialbe
{
public partial class AddVariableForm : DevComponents.DotNetBar.Office2007Form
{
public AddVariableForm()
{
InitializeComponent();
}
public AddVariableForm(string strLabelTip, string strVariableName)
{
InitializeComponent();
lbTip.Text = strLabelTip;
tbxVariable.Text = strVariableName;
}
public string GetNewVariableName()
{
return tbxVariable.Text;
}
private void btnOK_Click(object sender, EventArgs e)
{
this.DialogResult = DialogResult.OK;
}
private void btnCancle_Click(object sender, EventArgs e)
{
this.DialogResult = DialogResult.Cancel;
}
}
} | 25.35 | 82 | 0.597633 | [
"MIT"
] | RivenZoo/FullSource | Jx3Full/Source/Source/Tools/GameDesignerEditor/FlowChartEditor/Plugins/FlowChartVarialbe/AddVariableForm.cs | 975 | C# |
#region License
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
#endregion
using System;
using System.Collections;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace Gremlin.Net.Process.Traversal
{
/// <summary>
/// Represents the basic information for a walk over a graph.
/// </summary>
/// <seealso cref="ITraversal{SType, EType}"/>
public interface ITraversal: IEnumerator
{
/// <summary>
/// Gets the <see cref="Bytecode" /> representation of this traversal.
/// </summary>
Bytecode Bytecode { get; }
/// <summary>
/// Gets or sets the <see cref="ITraversalSideEffects" /> of this traversal.
/// </summary>
ITraversalSideEffects SideEffects { get; set; }
/// <summary>
/// Gets or sets the <see cref="Traverser" />'s of this traversal that hold the results of the traversal.
/// </summary>
IEnumerable<Traverser> Traversers { get; set; }
/// <summary>
/// Iterates all <see cref="Traverser" /> instances in the traversal.
/// </summary>
/// <returns>The fully drained traversal.</returns>
ITraversal Iterate();
}
/// <summary>
/// A traversal represents a directed walk over a graph.
/// </summary>
public interface ITraversal<S, E> : ITraversal, IEnumerator<E>
{
/// <summary>
/// Gets the next result from the traversal.
/// </summary>
/// <returns>The result.</returns>
E Next();
/// <summary>
/// Gets the next n-number of results from the traversal.
/// </summary>
/// <param name="amount">The number of results to get.</param>
/// <returns>The n-results.</returns>
IEnumerable<E> Next(int amount);
/// <summary>
/// Iterates all <see cref="Traverser" /> instances in the traversal.
/// </summary>
/// <returns>The fully drained traversal.</returns>
new ITraversal<S, E> Iterate();
/// <summary>
/// Gets the next <see cref="Traverser" />.
/// </summary>
/// <returns>The next <see cref="Traverser" />.</returns>
Traverser NextTraverser();
/// <summary>
/// Puts all the results into a <see cref="IList{T}" />.
/// </summary>
/// <returns>The results in a list.</returns>
IList<E> ToList();
/// <summary>
/// Puts all the results into a <see cref="ISet{T}" />.
/// </summary>
/// <returns>The results in a set.</returns>
ISet<E> ToSet();
/// <summary>
/// Starts a promise to execute a function on the current traversal that will be completed in the future.
/// </summary>
/// <typeparam name="TReturn">The return type of the <paramref name="callback" />.</typeparam>
/// <param name="callback">The function to execute on the current traversal.</param>
/// <returns>The result of the executed <paramref name="callback" />.</returns>
Task<TReturn> Promise<TReturn>(Func<ITraversal<S, E>, TReturn> callback);
}
} | 36.321101 | 117 | 0.60394 | [
"Apache-2.0"
] | GCHQResearcher1337/tinkerpop | gremlin-dotnet/src/Gremlin.Net/Process/Traversal/ITraversal.cs | 3,959 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using HoppoAlpha.DataLibrary.RawApi.ApiPort;
using HoppoAlpha.DataLibrary.DataObject;
using Codeplex.Data;
namespace VisualFormTest
{
public static class UnitQueryExt
{
//デフォルトではAND検索でチェック
public static bool CheckAll(this UnitQuery query, ApiShip oship)
{
if (!query.IsOr)
{
//AND検索
foreach (UnitQueryItem x in query.Query)
{
if (!x.Check(oship)) return false;
}
return true;
}
else
{
//OR検索
foreach (UnitQueryItem x in query.Query)
{
if (x.Check(oship)) return true;
}
return false;
}
}
//JSONに変換
public static string ToJson(this UnitQuery query)
{
return DynamicJson.Serialize(query);
}
}
public static class UnitQueryItemExt
{
//これをJSONに
public static string ToJson(this UnitQueryItem item)
{
string str = DynamicJson.Serialize(item);
return str;
}
//SeachをJSONに
public static string ToSearchesJson(this UnitQueryItem item)
{
string str = DynamicJson.Serialize(item.Searches);
return str;
}
//JSONをSearchesに
public static List<UnitQueryItemSearchBase> FromJsonToSearches(string json)
{
var ojson = DynamicJson.Parse(json);
return ojson.Deserialize<List<UnitQueryItemSearchBase>>();
}
//Targetのインスタンスを取得
public static object GetInstance(this UnitQueryItem item, ApiShip oship)
{
object instance = null;
//値の取得
switch (item.TargetEnum)
{
case UnitQueryMode.ID:
instance = oship.api_id;
break;
case UnitQueryMode.Name:
instance = oship.ShipName;
break;
case UnitQueryMode.Lv:
instance = oship.api_lv;
break;
case UnitQueryMode.ShipType:
instance = oship.DShip.api_stype;
break;
case UnitQueryMode.ShipTypeName://5
instance = oship.ShipTypeName;
break;
case UnitQueryMode.Cond:
instance = oship.api_cond;
break;
case UnitQueryMode.NdockTime:
instance = oship.api_ndock_time;
break;
case UnitQueryMode.HP:
instance = oship.api_nowhp;
break;
case UnitQueryMode.MaxHP:
instance = oship.api_maxhp;
break;
case UnitQueryMode.HPRatio://10
instance = (double)oship.api_nowhp / (double)oship.api_maxhp;
break;
case UnitQueryMode.IsLatestRemodeling:
instance = Convert.ToInt32(oship.DShip.api_aftershipid == "0");
break;
case UnitQueryMode.EXP:
instance = oship.api_exp[0];
break;
case UnitQueryMode.Fire:
instance = oship.api_karyoku[0];
break;
case UnitQueryMode.Torpedo:
instance = oship.api_raisou[0];
break;
case UnitQueryMode.NightFire://15
instance = oship.api_karyoku[0] + oship.api_raisou[0];
break;
case UnitQueryMode.AirSup:
instance = oship.GetAirSupValue(APIGetMember.SlotItemsDictionary, APIPort.IsWithdrawn, APIPort.DeckPorts).AirSupValueMax;
break;
case UnitQueryMode.CarrierFire:
instance = KancolleInfoFleet.CalcCarrierFire(oship);
break;
case UnitQueryMode.AntiSubmarine:
instance = oship.api_taisen[0];
break;
case UnitQueryMode.AntiAir:
instance = oship.api_taiku[0];
break;
case UnitQueryMode.Defense://20
instance = oship.api_soukou[0];
break;
case UnitQueryMode.Evasion:
instance = oship.api_kaihi[0];
break;
case UnitQueryMode.AircraftNum:
instance = oship.api_onslot.Sum();
break;
case UnitQueryMode.Range:
instance = oship.api_leng;
break;
case UnitQueryMode.Search:
instance = oship.api_sakuteki[0];
break;
case UnitQueryMode.Luck://25
instance = oship.api_lucky[0];
break;
case UnitQueryMode.IsLocked:
instance = oship.api_locked;
break;
case UnitQueryMode.FuelNow:
instance = oship.api_fuel;
break;
case UnitQueryMode.FuelMax:
instance = oship.DShip.api_fuel_max;
break;
case UnitQueryMode.FuelRatio:
instance = (double)oship.api_fuel / (double)oship.DShip.api_fuel_max;
break;
case UnitQueryMode.BullNow://30
instance = oship.api_bull;
break;
case UnitQueryMode.BullMax:
instance = oship.DShip.api_bull_max;
break;
case UnitQueryMode.BullRatio:
instance = (double)oship.api_bull / (double)oship.DShip.api_bull_max;
break;
case UnitQueryMode.IsFleetAssign:
var fleets = APIPort.DeckPorts.SelectMany(x => x.api_ship).Where(x => x != -1);
instance = fleets.Contains(oship.api_id) ? 1 : 0;
break;
case UnitQueryMode.IsBath:
var ndock = APIPort.Ndocks.Select(x => x.api_ship_id).Where(x => x != 0);
instance = ndock.Contains(oship.api_id) ? 1 : 0;
break;
case UnitQueryMode.SallyArea:
instance = oship.api_sally_area;
break;
}
return instance;
}
//SearchBase単体でのチェック
public static bool Check(this UnitQueryItem item, ApiShip oship)
{
object instance = item.GetInstance(oship);
//デフォルトでは全OR検索
if (!item.IsAnd)
{
foreach (UnitQueryItemSearchBase x in item.Searches)
{
if (x.Checker(oship, instance)) return (true ^ item.IsNot);
}
return (false ^ item.IsNot);
}
//AND検索
else
{
foreach (UnitQueryItemSearchBase x in item.Searches)
{
if (!x.Checker(oship, instance)) return (false ^ item.IsNot);
}
return (true ^ item.IsNot);
}
}
}
public static class UnitQueryItemSearchBaseExt
{
//JSONから変換
public static List<UnitQueryItemSearchBase> FromJson(string json)
{
var ojson = DynamicJson.Parse(json);
return ojson.Deserialize<List<UnitQueryItemSearchBase>>();
}
}
public static class UnitQueryModeExt
{
//ToolTipのメッセージ
public static string GetToolTipMessage(this UnitQueryMode u)
{
StringBuilder sb;
switch (u)
{
case UnitQueryMode.ID: return "艦娘ごとに割り当てられている固有のIDで判定します。\nIDは艦娘リストに表示されているIDと一致します。";
case UnitQueryMode.Name: return "艦娘の名前で判定します。\n例:吹雪、伊58、長門改…。";
case UnitQueryMode.Lv: return "艦娘のレベルで判定します。";
case UnitQueryMode.ShipType:
sb = new StringBuilder();
sb.AppendLine("艦種をマスターデータで管理されているIDで判定します。");
sb.AppendLine("この値は、艦種ごとに異なる整数を取ります。");
sb.AppendLine("--値一覧 : --");
foreach (var x in APIMaster.MstStypesDictionary)
{
sb.AppendFormat("{0}={1} ", x.Key, x.Value.api_name);
if (x.Key % 5 == 4) sb.AppendLine();
}
return sb.ToString();
case UnitQueryMode.ShipTypeName:
return "艦種を文字列で判定します。\n文字列の検索モードが完全一致の場合、\nマスターデータで定義されている艦種名と同じでなければいけません。\n例:完全一致+雷巡→×, 完全一致+重雷装巡洋艦→○, 前方一致+重雷装→○";//5
case UnitQueryMode.Cond: return "Cond値で判定します";
case UnitQueryMode.NdockTime: return "入渠時間をミリ秒単位で判定します。\n最大値は 2147483647 です。";
case UnitQueryMode.HP: return "現在の耐久(HP)で判定します。";
case UnitQueryMode.MaxHP: return "耐久(HP)最大値で判定します。";
case UnitQueryMode.HPRatio:
return "現在の耐久(HP)÷耐久(HP)最大値 で判定します。\n小破、中破などの損傷条件で判定したい場合は範囲で指定してください\n・大破:x ≦0.25\n・中破 : 0.25 < x ≦ 0.5\n・小破 : 0.5 < x ≦ 0.75\n・無傷 : x > 0.75\n[Tips]「aより大きくbより小さい」といった判定を用いたい場合は、\nこのクエリアイテムのANDモードをONにしてください。";//10
case UnitQueryMode.IsLatestRemodeling: return "最終改造であるかどうかを判定します。\nこれ以上改造不可能ならば1を、改造可能ならば0を返します";
case UnitQueryMode.EXP: return "Lv1からの累積経験値で判定します。\nLv99でカンストしている場合はこの値は1000000(100万)です";
case UnitQueryMode.Fire: return "現在の火力で判定します。\nこれは編成で表示される値で、キャップ補正・消費弾薬補正等は含まれません。";
case UnitQueryMode.Torpedo: return "現在の雷装で判定します。\nこれは編成で表示される値で、キャップ補正・消費弾薬補正等は含まれません。";
case UnitQueryMode.NightFire: return "夜戦火力(火力+雷装)で判定します。\nキャップ補正・消費弾薬補正等は含まれません。";//15
case UnitQueryMode.AirSup: return "現在の制空値で判定します。";
case UnitQueryMode.CarrierFire: return "空母の昼戦の砲雷撃戦時の実質的な火力で判定します。この値は、(火力+雷装)×1.5+爆装×2+55 で計算されます。\nキャップ補正・消費弾薬補正等は含まれません。";
case UnitQueryMode.AntiSubmarine: return "現在の対潜で判定します。\nこれは編成で表示される値で、キャップ補正・消費弾薬補正等は含まれません。";
case UnitQueryMode.AntiAir: return "現在の対空で判定します。\nこれは編成で表示される値です。";
case UnitQueryMode.Defense: return "現在の装甲で判定します。";//20
case UnitQueryMode.Evasion: return "現在の回避で判定します。\nこれは編成で表示される値で、疲労補正・消費燃料補正等は含まれません。";
case UnitQueryMode.AircraftNum: return "現在の搭載数で判定します。\n艦載機を装備していないスロットの搭載数も合計して計算されます。";
case UnitQueryMode.Range: return "艦娘の射程を数値で判定します。\n例 : 0 = なし, 1 = 短, 2 = 中, …, 5 = 超超長";
case UnitQueryMode.Search: return "現在の索敵で判定します。\nこれは編成で表示される値で、2-5式等のルート制御の計算結果とは異なります。";
case UnitQueryMode.Luck: return "現在の運で判定します。";//25
case UnitQueryMode.IsLocked: return "艦娘がロックされているかを判定します。\nロックされている場合は1を、ロックされていなければ0を返します";
case UnitQueryMode.FuelNow: return "現在の燃料残量で判定します。\nこの値は残目盛り数とは異なり、\nケッコンしていない場合、燃料最大値からこの値を引くと補給に必要な燃料と一致します。\nケッコン済の場合は、引き算の結果に燃費向上補正をかけたものと一致します。";
case UnitQueryMode.FuelMax: return "燃料搭載の最大値で判定します。\nこの値は残目盛り数とは異なります。";
case UnitQueryMode.FuelRatio: return "燃料の残量÷燃料最大値で判定します。\nこの値はおよそ残目盛り数と一致します。";
case UnitQueryMode.BullNow:
return "現在の弾薬残量で判定します。\nこの値は残目盛り数とは異なり、\nケッコンしていない場合、弾薬最大値からこの値を引くと補給に必要な弾薬と一致します。\nケッコン済の場合は、引き算の結果に燃費向上補正をかけたものと一致します。";//30
case UnitQueryMode.BullMax: return "弾薬搭載の最大値で判定します。\nこの値は残目盛り数とは異なります。";
case UnitQueryMode.BullRatio: return "弾薬の残量÷弾薬最大値で判定します。\nこの値はおよそ残目盛り数と一致します。";
case UnitQueryMode.IsFleetAssign: return "いずれかの艦隊に配属されているかで判定します。\n配属されてなければ0、配属されていれば1を返します。";
case UnitQueryMode.IsBath: return "入渠しているを判定します。\n入渠していなければ0、入渠していれば1を返します。";
case UnitQueryMode.SallyArea: return "出撃マップの制限を判定します。\nイベント期間中以外は常に0となります。";
default: throw new ArgumentOutOfRangeException();
}
}
}
}
| 44.375 | 234 | 0.540523 | [
"MIT"
] | yamadansan/HoppoAlpha | VisualFormTest/DataLibraryHelper/UnitQueryExt.cs | 15,499 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.XR.ARFoundation;
using UniRx;
using UnityEngine.XR.ARSubsystems;
using ViewModel;
using System.Linq;
using TMPro;
using System;
namespace Components
{
public class TrackedManagerImageDisplay : MonoBehaviour
{
[Header("AR Reference")]
public ARTrackedImageManager ARTrackedImageManager;
public TrackManagerViewModel trackData;
private GameObject _arPrefabInstantied;
private GameObject _cubeScreen;
void OnEnable() => ARTrackedImageManager.trackedImagesChanged += OnTrackedImagesChanged;
void OnDisable() => ARTrackedImageManager.trackedImagesChanged -= OnTrackedImagesChanged;
private void OnTrackedImagesChanged(ARTrackedImagesChangedEventArgs eventArgs)
{
if(trackData.ARTrackedEnable.Value == false)
return;
try
{
foreach(ARTrackedImage trackedImage in eventArgs.added)
{
InstanceARPrefab(trackedImage);
}
foreach(ARTrackedImage trackedImage in eventArgs.updated)
{
if (trackedImage.trackingState == TrackingState.Tracking)
{
if(_arPrefabInstantied != null)
UpdateARPrefab(_arPrefabInstantied, trackedImage);
}
else
{
if(_arPrefabInstantied != null)
_arPrefabInstantied.SetActive(false);
}
}
foreach(ARTrackedImage trackedImage in eventArgs.removed)
{
if(_arPrefabInstantied != null)
_arPrefabInstantied.SetActive(false);
}
}
catch(Exception e)
{
Debug.LogError("Horrible things happened! ("+e.ToString()+")");
}
}
private void InstanceARPrefab(ARTrackedImage trackedImage)
{
int idObject = trackData.currentRecognition.Value.prediction;
Debug.Log($"Instance AR Prefab with name {trackData.deepLearningConfig.recognitionResponse[idObject]}");
GameObject arObject = trackData.ARObjectPrefab
.Where(arobject => arobject.GetComponent<ARObject>().arObjectData.objectId == idObject)
.FirstOrDefault();
_arPrefabInstantied = Instantiate(arObject);
ShowTrackInfo(trackedImage.referenceImage.name);
UpdateARPrefab(_arPrefabInstantied, trackedImage);
}
private void UpdateARPrefab(GameObject prefab, ARTrackedImage trackedImage)
{
prefab.transform.position = trackedImage.transform.position;
//prefab.transform.rotation = Quaternion.identity;
//prefab.transform.localScale = trackData;
prefab.SetActive(true);
}
private void ShowTrackInfo(string name)
{
var runtimeReferenceImageLibrary = ARTrackedImageManager.referenceLibrary as MutableRuntimeReferenceImageLibrary;
Debug.Log($"Go in arObjects.Values: {_arPrefabInstantied.name}");
}
}
}
| 36.630435 | 135 | 0.596439 | [
"Apache-2.0"
] | matiasvallejosdev/ar-dl-color-mapping | unity-ar/Assets/Scripts/Components/tracked/TrackedManagerImageDisplay.cs | 3,370 | 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("P02_ExtractSentencesByKeyword")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("P02_ExtractSentencesByKeyword")]
[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("7f449400-cb46-481f-9640-c40442c8ce1f")]
// 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.675676 | 84 | 0.751223 | [
"MIT"
] | ivakis1/Programming-Fundamentals-C-Sharp | 11.1 Regular Expressions (REGEX) - Exercises/P02_ExtractSentencesByKeyword/Properties/AssemblyInfo.cs | 1,434 | C# |
using System.ComponentModel.DataAnnotations;
using Abp.Authorization.Users;
using Abp.AutoMapper;
using Abp.MultiTenancy;
namespace MyCouldBook.MultiTenancy.Dto
{
[AutoMapTo(typeof(Tenant))]
public class CreateTenantDto
{
[Required]
[StringLength(AbpTenantBase.MaxTenancyNameLength)]
[RegularExpression(AbpTenantBase.TenancyNameRegex)]
public string TenancyName { get; set; }
[Required]
[StringLength(AbpTenantBase.MaxNameLength)]
public string Name { get; set; }
[Required]
[StringLength(AbpUserBase.MaxEmailAddressLength)]
public string AdminEmailAddress { get; set; }
[StringLength(AbpTenantBase.MaxConnectionStringLength)]
public string ConnectionString { get; set; }
public bool IsActive {get; set;}
public string AdminPassword { get; set; }
}
}
| 28.516129 | 63 | 0.687783 | [
"MIT"
] | cacayue/MyCouldBook | src/mycouldbook-aspnet-core/src/MyCouldBook.Application/MultiTenancy/Dto/CreateTenantDto.cs | 884 | C# |
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Octopus.Client.Editors.Async;
using Octopus.Client.Model;
using Octopus.Client.Model.Endpoints;
namespace Octopus.Client.Repositories.Async
{
public interface IWorkerRepository : IFindByName<WorkerResource>, IGet<WorkerResource>, ICreate<WorkerResource>, IModify<WorkerResource>, IDelete<WorkerResource>
{
Task<WorkerResource> Discover(string host, int port = 10933, DiscoverableEndpointType? discoverableEndpointType = null);
Task<MachineConnectionStatus> GetConnectionStatus(WorkerResource machine);
Task<List<WorkerResource>> FindByThumbprint(string thumbprint);
Task<WorkerEditor> CreateOrModify(
string name,
EndpointResource endpoint,
WorkerPoolResource[] pools);
Task<ResourceCollection<WorkerResource>> List(int skip = 0,
int? take = null,
string ids = null,
string name = null,
string partialName = null,
bool? isDisabled = false,
string healthStatuses = null,
string commStyles = null,
string workerpoolIds = null);
}
class WorkerRepository : BasicRepository<WorkerResource>, IWorkerRepository
{
public WorkerRepository(IOctopusAsyncRepository repository) : base(repository, "Workers")
{
}
public async Task<WorkerResource> Discover(string host, int port = 10933, DiscoverableEndpointType? type = null)
{
return await Client.Get<WorkerResource>(await Repository.Link("DiscoverWorker").ConfigureAwait(false), new { host, port, type }).ConfigureAwait(false);
}
public Task<MachineConnectionStatus> GetConnectionStatus(WorkerResource worker)
{
if (worker == null) throw new ArgumentNullException("worker");
return Client.Get<MachineConnectionStatus>(worker.Link("Connection"));
}
public async Task<List<WorkerResource>> FindByThumbprint(string thumbprint)
{
if (thumbprint == null) throw new ArgumentNullException("thumbprint");
return await Client.Get<List<WorkerResource>>(await Repository.Link("Workers").ConfigureAwait(false), new { id = IdValueConstant.IdAll, thumbprint }).ConfigureAwait(false);
}
public Task<WorkerEditor> CreateOrModify(
string name,
EndpointResource endpoint,
WorkerPoolResource[] workerpools)
{
return new WorkerEditor(this).CreateOrModify(name, endpoint, workerpools);
}
public async Task<ResourceCollection<WorkerResource>> List(int skip = 0,
int? take = null,
string ids = null,
string name = null,
string partialName = null,
bool? isDisabled = false,
string healthStatuses = null,
string commStyles = null,
string workerpoolIds = null)
{
return await Client.List<WorkerResource>(await Repository.Link("Workers").ConfigureAwait(false), new
{
skip,
take,
ids,
name,
partialName,
isDisabled,
healthStatuses,
commStyles,
workerpoolIds
}).ConfigureAwait(false);
}
}
}
| 38.840909 | 184 | 0.630778 | [
"Apache-2.0"
] | BlythMeister/OctopusClients | source/Octopus.Server.Client/Repositories/Async/WorkerRepository.cs | 3,418 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OrderedTestFileGenerator;
namespace OrderedTestFileGeneratorTests
{
[TestClass]
public class TestDefinitionCategorySequencerTests
{
private List<TestDefinition> testDefinitions = new List<TestDefinition>
{
new TestDefinition { Categories = new[] { "Smoke" } },
new TestDefinition { Categories = new[] { "Critical" } },
new TestDefinition { Categories = new[] { "Smoke", "Critical" } },
};
[TestMethod]
public void Sequenced_NoOrphans_OnlySmokeTestsReturned()
{
List<string> categorySequence = new List<string> { "Critical" };
var target = new TestDefinitionCategorySequencer(testDefinitions, categorySequence);
var actual = target.Sequenced.ToList();
Assert.AreEqual(2, actual.Count);
Assert.IsTrue(actual[0].Categories.Contains("Critical"));
}
[TestMethod]
public void Sequenced_WithOrphans_AllTestsReturned()
{
List<string> categorySequence = new List<string> { "Critical" };
var target = new TestDefinitionCategorySequencer(testDefinitions, categorySequence);
target.AppendOrphans = true;
var actual = target.Sequenced.ToList();
Assert.AreEqual(3, actual.Count);
Assert.IsTrue(actual.First().Categories.Contains("Critical"));
Assert.IsTrue(actual.Last().Categories.Contains("Smoke"));
}
}
}
| 33.604167 | 96 | 0.642901 | [
"Apache-2.0"
] | andywilsonuk/OrderedTestFileGenerator | OrderedTestFileGeneratorTests/TestDefinitionCategorySequencerTests.cs | 1,615 | C# |
using System;
namespace A5Soft.CARMA.Domain
{
/// <summary>
/// Contains event data for the RemovingItem
/// event.
/// </summary>
public class RemovingItemEventArgs : EventArgs
{
/// <summary>
/// Gets a reference to the item that was removed from the list.
/// </summary>
public object RemovingItem { get; }
/// <summary>
/// Create an instance of the object.
/// </summary>
/// <param name="removingItem">
/// A reference to the item that was removed from the list.
/// </param>
public RemovingItemEventArgs(object removingItem)
{
RemovingItem = removingItem;
}
}
}
| 24.724138 | 72 | 0.559275 | [
"MIT"
] | Apskaita5/CARMA | src/A5Soft.CARMA.Domain/RemovingItemEventArgs.cs | 719 | C# |
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using FluentAssertions;
using Xunit;
namespace RateLimiter.Tests
{
public class PersistentCountByIntervalAwaitableConstraintTest
{
[Fact]
public async Task WaitForReadiness_WithoutInitialState()
{
var log = new List<DateTime>();
var constraint = new PersistentCountByIntervalAwaitableConstraint(1, TimeSpan.FromMilliseconds(200),
timeStamp => log.Add(timeStamp), null);
for (int i = 0; i < 5; i++)
{
(await constraint.WaitForReadiness(CancellationToken.None)).Dispose();
}
log.Should().HaveCount(5);
}
[Fact]
public async Task WaitForReadiness_WithInitialState()
{
var firstTimeStamp = new DateTime(2000, 1, 1);
var secondTimeStamp = new DateTime(2001, 1, 1);
var log = new List<DateTime> {firstTimeStamp, secondTimeStamp};
var constraint = new PersistentCountByIntervalAwaitableConstraint(7, TimeSpan.FromSeconds(1),
timeStamp => log.Add(timeStamp), log);
for (int i = 0; i < 5; i++)
{
(await constraint.WaitForReadiness(CancellationToken.None)).Dispose();
}
log.Should().HaveCount(7);
log[0].Should().Be(firstTimeStamp);
log[1].Should().Be(secondTimeStamp);
}
}
}
| 30.795918 | 112 | 0.597747 | [
"MIT"
] | ArefGihuni/RateLimiter | RateLimiter.Tests/PersistentCountByIntervalAwaitableConstraintTest.cs | 1,511 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.