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 Microsoft.AspNetCore.Mvc; using TCOMSapps.Features.Account; namespace TCOMSapps.Extensions { public static class UrlHelperExtensions { public static string EmailConfirmationLink(this IUrlHelper urlHelper, string userId, string code, string scheme) { return urlHelper.Action( action: nameof(AccountController.ConfirmEmail), controller: "Account", values: new { userId, code }, protocol: scheme); } public static string ResetPasswordCallbackLink(this IUrlHelper urlHelper, string userId, string code, string scheme) { return urlHelper.Action( action: nameof(AccountController.ResetPassword), controller: "Account", values: new { userId, code }, protocol: scheme); } } }
32.888889
124
0.609234
[ "MIT" ]
emo333/TCOMSapps
TCOMSapps/Extensions/UrlHelperExtensions.cs
888
C#
//using Kore.DI; namespace Kore.Data.EntityFramework { public interface IEntityTypeConfiguration { bool IsEnabled { get; } } }
17.333333
46
0.628205
[ "MIT" ]
artinite21/KoreCMS
Kore.EntityFramework/Data/EntityFramework/IEntityTypeConfiguration.cs
158
C#
// Copyright (c) Valdis Iljuconoks. All rights reserved. // Licensed under Apache-2.0. See the LICENSE file in the project root for more information using System.Globalization; using Microsoft.Extensions.Localization; namespace DbLocalizationProvider.AspNetCore { /// <summary> /// Workaround interface for changing language on <see cref="IStringLocalizer"/> /// </summary> public interface ICultureAwareStringLocalizer { /// <summary> /// Change language of the provider and returns string localizer with specified language. /// </summary> /// <param name="language">Language to change to.</param> /// <returns>Localizer with specified language.</returns> IStringLocalizer ChangeLanguage(CultureInfo language); } }
35.909091
97
0.703797
[ "Apache-2.0" ]
LoloActemium/localization-provider-core
src/DbLocalizationProvider.AspNetCore/ICultureAwareStringLocalizer.cs
790
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.Globalization; using System.Linq; using QuantConnect.Configuration; using QuantConnect.Data.Market; using QuantConnect.Logging; namespace QuantConnect.ToolBox.DukascopyDownloader { class Program { /// <summary> /// Primary entry point to the program /// </summary> static void Main(string[] args) { if (args.Length != 4) { Console.WriteLine("Usage: DukascopyDownloader SYMBOLS RESOLUTION FROMDATE TODATE"); Console.WriteLine("SYMBOLS = eg EURUSD,USDJPY"); Console.WriteLine("RESOLUTION = Tick/Second/Minute/Hour/Daily/All"); Console.WriteLine("FROMDATE = yyyymmdd"); Console.WriteLine("TODATE = yyyymmdd"); Environment.Exit(1); } try { // Load settings from command line var symbols = args[0].Split(','); var allResolutions = args[1].ToLower() == "all"; var resolution = allResolutions ? Resolution.Tick : (Resolution)Enum.Parse(typeof(Resolution), args[1]); var startDate = DateTime.ParseExact(args[2], "yyyyMMdd", CultureInfo.InvariantCulture); var endDate = DateTime.ParseExact(args[3], "yyyyMMdd", CultureInfo.InvariantCulture); // Load settings from config.json var dataDirectory = Config.Get("data-directory", "../../../Data"); // Download the data const string market = Market.Dukascopy; var downloader = new DukascopyDataDownloader(); foreach (var symbol in symbols) { if (!downloader.HasSymbol(symbol)) throw new ArgumentException("The symbol " + symbol + " is not available."); } foreach (var symbol in symbols) { var securityType = downloader.GetSecurityType(symbol); var symbolObject = Symbol.Create(symbol, securityType, Market.Dukascopy); var data = downloader.Get(symbolObject, resolution, startDate, endDate); if (allResolutions) { var ticks = data.Cast<Tick>().ToList(); // Save the data (tick resolution) var writer = new LeanDataWriter(resolution, symbolObject, dataDirectory); writer.Write(ticks); // Save the data (other resolutions) foreach (var res in new[] { Resolution.Second, Resolution.Minute, Resolution.Hour, Resolution.Daily }) { var resData = DukascopyDataDownloader.AggregateTicks(symbolObject, ticks, res.ToTimeSpan()); writer = new LeanDataWriter(res, symbolObject, dataDirectory); writer.Write(resData); } } else { // Save the data (single resolution) var writer = new LeanDataWriter(resolution, symbolObject, dataDirectory); writer.Write(data); } } } catch (Exception err) { Log.Error(err); } } } }
41.235294
126
0.553971
[ "Apache-2.0" ]
Bimble/Lean
ToolBox/DukascopyDownloader/Program.cs
4,208
C#
using Anomalous.Interop; using Engine; using System; using System.Collections.Generic; using System.Linq; using System.Runtime.InteropServices; using System.Security.Cryptography.X509Certificates; using System.Text; using System.Threading.Tasks; namespace Anomalous.OSPlatform.iOS { static class iOSFunctions { #if STATIC_LINK internal const String LibraryName = "__Internal"; #else internal const String LibraryName = "OSHelper"; #endif public static String LocalUserDocumentsFolder { get { using (StringRetriever sr = new StringRetriever()) { iOSPlatformConfig_getLocalUserDocumentsFolder(sr.StringCallback, sr.Handle); return sr.retrieveString(); } } } public static String LocalDataFolder { get { using (StringRetriever sr = new StringRetriever()) { iOSPlatformConfig_getLocalDataFolder(sr.StringCallback, sr.Handle); return sr.retrieveString(); } } } public static String LocalPrivateDataFolder { get { using (StringRetriever sr = new StringRetriever()) { iOSPlatformConfig_getLocalPrivateDataFolder(sr.StringCallback, sr.Handle); return sr.retrieveString(); } } } #region PInvoke [DllImport(LibraryName, CallingConvention = CallingConvention.Cdecl)] private static unsafe extern void iOSPlatformConfig_getLocalUserDocumentsFolder(StringRetriever.Callback retrieve, IntPtr handle); [DllImport(LibraryName, CallingConvention = CallingConvention.Cdecl)] private static unsafe extern void iOSPlatformConfig_getLocalDataFolder(StringRetriever.Callback retrieve, IntPtr handle); [DllImport(LibraryName, CallingConvention = CallingConvention.Cdecl)] private static unsafe extern void iOSPlatformConfig_getLocalPrivateDataFolder(StringRetriever.Callback retrieve, IntPtr handle); #endregion } }
32.43662
139
0.610508
[ "MIT" ]
AnomalousMedical/Engine
OSPlatform.iOS/iOSFunctions.cs
2,305
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; /// <summary> /// The type WorkbookTableSortReapplyRequestBuilder. /// </summary> public partial class WorkbookTableSortReapplyRequestBuilder : BaseGetMethodRequestBuilder<IWorkbookTableSortReapplyRequest>, IWorkbookTableSortReapplyRequestBuilder { /// <summary> /// Constructs a new <see cref="WorkbookTableSortReapplyRequestBuilder"/>. /// </summary> /// <param name="requestUrl">The URL for the request.</param> /// <param name="client">The <see cref="IBaseClient"/> for handling requests.</param> public WorkbookTableSortReapplyRequestBuilder( string requestUrl, IBaseClient client) : base(requestUrl, client) { } /// <summary> /// A method used by the base class to construct a request class instance. /// </summary> /// <param name="functionUrl">The request URL to </param> /// <param name="options">The query and header options for the request.</param> /// <returns>An instance of a specific request class.</returns> protected override IWorkbookTableSortReapplyRequest CreateRequest(string functionUrl, IEnumerable<Option> options) { var request = new WorkbookTableSortReapplyRequest(functionUrl, this.Client, options); return request; } } }
41.8
168
0.609782
[ "MIT" ]
MIchaelMainer/GraphAPI
src/Microsoft.Graph/Requests/Generated/WorkbookTableSortReapplyRequestBuilder.cs
1,881
C#
using FluentAssertions; using global::Azure.Identity; using global::HealthChecks.AzureServiceBus; using global::System; using global::System.Linq; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Diagnostics.HealthChecks; using Microsoft.Extensions.Options; using Xunit; namespace UnitTests.HealthChecks.DependencyInjection.AzureServiceBus { public class azure_service_bus_topic_registration_with_token_should { [Fact] public void add_health_check_when_properly_configured() { var services = new ServiceCollection(); services.AddHealthChecks() .AddAzureServiceBusTopic("cnn", "topicName", new AzureCliCredential()); var serviceProvider = services.BuildServiceProvider(); var options = serviceProvider.GetService<IOptions<HealthCheckServiceOptions>>(); var registration = options.Value.Registrations.First(); var check = registration.Factory(serviceProvider); registration.Name.Should().Be("azuretopic"); check.GetType().Should().Be(typeof(AzureServiceBusTopicHealthCheck)); } [Fact] public void add_named_health_check_when_properly_configured() { var services = new ServiceCollection(); services.AddHealthChecks() .AddAzureServiceBusTopic("cnn", "topic", new AzureCliCredential(), "azuretopiccheck"); var serviceProvider = services.BuildServiceProvider(); var options = serviceProvider.GetService<IOptions<HealthCheckServiceOptions>>(); var registration = options.Value.Registrations.First(); var check = registration.Factory(serviceProvider); registration.Name.Should().Be("azuretopiccheck"); check.GetType().Should().Be(typeof(AzureServiceBusTopicHealthCheck)); } [Fact] public void fail_when_no_health_check_configuration_provided() { var services = new ServiceCollection(); services.AddHealthChecks() .AddAzureServiceBusTopic(string.Empty, string.Empty, new AzureCliCredential()); var serviceProvider = services.BuildServiceProvider(); var options = serviceProvider.GetService<IOptions<HealthCheckServiceOptions>>(); var registration = options.Value.Registrations.First(); Assert.Throws<ArgumentNullException>(() => registration.Factory(serviceProvider)); } } }
38.545455
95
0.678066
[ "Apache-2.0" ]
BartNetJS/AspNetCore.Diagnostics.HealthChecks
test/UnitTests/DependencyInjection/AzureServiceBus/AzureServiceBusTopicWithTokenUnitTests.cs
2,544
C#
using System.Threading.Tasks; using Microsoft.AspNetCore.Components; using Microsoft.JSInterop; namespace Spect.Net.Shell.Interop { public static class SpectNetShellInterop { /// <summary> /// Creates a new editor with the specified id /// </summary> /// <param name="jsRuntime">JS runtime object</param> public static async Task Hello(this IJSRuntime jsRuntime) { await jsRuntime.InvokeAsync<object>("SpectNetShell.hello"); } /// <summary> /// Gets the element offset dimensions /// </summary> /// <param name="jsRuntime">JS runtime object</param> /// <param name="element">HTML element reference</param> /// <returns>Element dimensions</returns> public static async Task<ElementBoundaries> GetElementOffset(this IJSRuntime jsRuntime, ElementReference element) { return await jsRuntime.InvokeAsync<ElementBoundaries>("SpectNetShell.getElementOffset", element); } /// <summary> /// Start focus change checking /// </summary> /// <param name="jsRuntime">JS runtime object</param> /// <returns>Element dimensions</returns> public static async Task StartFocusChangeCheck(this IJSRuntime jsRuntime) { await jsRuntime.InvokeAsync<object>("SpectNetShell.checkFocusChange"); } } }
35.45
121
0.636812
[ "MIT" ]
Dotneteer/electron-spectnetide
Spec.Net.Electron/Spect.Net.Shell/Interop/SpectNetShellInterop.cs
1,420
C#
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace chat.Models { public class Message { [Key] [Required] public int MessageId { get; set; } public DateTime Time { get; set; } public string Content { get; set; } public string UserName { get; set; } public int RoomId { get; set; } [ForeignKey("UserName")] public virtual User User { get; set; } [ForeignKey("RoomId")] public virtual Room Room { get; set; } } }
28.347826
51
0.630368
[ "MIT" ]
monsterddq/rscchat
Asp.Net/server/chat/chat/Models/Message.cs
654
C#
using System.ComponentModel.DataAnnotations.Schema; using System.Data.Entity.ModelConfiguration; using System.CodeDom.Compiler; namespace AppCampus.Infrastructure.Models.Mapping { [GeneratedCode("EntityFrameworkCodeGeneration", "6.1.1")] public class UserTableMap : EntityTypeConfiguration<UserTable> { public UserTableMap() { // Primary Key this.HasKey(t => t.Id); // Properties this.Property(t => t.PasswordHash) .IsRequired(); this.Property(t => t.UserName) .IsRequired() .HasMaxLength(256); this.Property(t => t.FirstName) .IsRequired() .HasMaxLength(50); this.Property(t => t.LastName) .IsRequired() .HasMaxLength(50); // Relationships this.HasRequired(t => t.Company) .WithMany(t => t.Users) .HasForeignKey(d => d.CompanyId); } } }
25.875
66
0.541063
[ "MIT" ]
hendrikdelarey/appcampus
AppCampus.Infrastructure/Models/Mapping/UserMap.cs
1,035
C#
/* * Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the glacier-2012-06-01.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.Glacier.Model { /// <summary> /// A list of in-progress multipart uploads for a vault. /// </summary> public partial class UploadListElement { private string _archiveDescription; private DateTime? _creationDate; private string _multipartUploadId; private long? _partSizeInBytes; private string _vaultARN; /// <summary> /// Empty constructor used to set properties independently even when a simple constructor is available /// </summary> public UploadListElement() { } /// <summary> /// Gets and sets the property ArchiveDescription. /// <para> /// The description of the archive that was specified in the Initiate Multipart Upload /// request. /// </para> /// </summary> public string ArchiveDescription { get { return this._archiveDescription; } set { this._archiveDescription = value; } } // Check to see if ArchiveDescription property is set internal bool IsSetArchiveDescription() { return this._archiveDescription != null; } /// <summary> /// Gets and sets the property CreationDate. /// <para> /// The UTC time at which the multipart upload was initiated. /// </para> /// </summary> public DateTime CreationDate { get { return this._creationDate.GetValueOrDefault(); } set { this._creationDate = value; } } // Check to see if CreationDate property is set internal bool IsSetCreationDate() { return this._creationDate.HasValue; } /// <summary> /// Gets and sets the property MultipartUploadId. /// <para> /// The ID of a multipart upload. /// </para> /// </summary> public string MultipartUploadId { get { return this._multipartUploadId; } set { this._multipartUploadId = value; } } // Check to see if MultipartUploadId property is set internal bool IsSetMultipartUploadId() { return this._multipartUploadId != null; } /// <summary> /// Gets and sets the property PartSizeInBytes. /// <para> /// The part size, in bytes, specified in the Initiate Multipart Upload request. This /// is the size of all the parts in the upload except the last part, which may be smaller /// than this size. /// </para> /// </summary> public long PartSizeInBytes { get { return this._partSizeInBytes.GetValueOrDefault(); } set { this._partSizeInBytes = value; } } // Check to see if PartSizeInBytes property is set internal bool IsSetPartSizeInBytes() { return this._partSizeInBytes.HasValue; } /// <summary> /// Gets and sets the property VaultARN. /// <para> /// The Amazon Resource Name (ARN) of the vault that contains the archive. /// </para> /// </summary> public string VaultARN { get { return this._vaultARN; } set { this._vaultARN = value; } } // Check to see if VaultARN property is set internal bool IsSetVaultARN() { return this._vaultARN != null; } } }
31.191489
111
0.596635
[ "Apache-2.0" ]
DetlefGolze/aws-sdk-net
sdk/src/Services/Glacier/Generated/Model/UploadListElement.cs
4,398
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.Generic; using System.Collections.Specialized; using System.IO; using System.Net; using System.Web; using DotNetOpenId; using DotNetOpenId.Provider; using OpenSim.Framework; using OpenSim.Framework.Servers; using OpenSim.Framework.Servers.HttpServer; namespace OpenSim.Grid.UserServer.Modules { /// <summary> /// Temporary, in-memory store for OpenID associations /// </summary> public class ProviderMemoryStore : IAssociationStore<AssociationRelyingPartyType> { private class AssociationItem { public AssociationRelyingPartyType DistinguishingFactor; public string Handle; public DateTime Expires; public byte[] PrivateData; } Dictionary<string, AssociationItem> m_store = new Dictionary<string, AssociationItem>(); SortedList<DateTime, AssociationItem> m_sortedStore = new SortedList<DateTime, AssociationItem>(); object m_syncRoot = new object(); #region IAssociationStore<AssociationRelyingPartyType> Members public void StoreAssociation(AssociationRelyingPartyType distinguishingFactor, Association assoc) { AssociationItem item = new AssociationItem(); item.DistinguishingFactor = distinguishingFactor; item.Handle = assoc.Handle; item.Expires = assoc.Expires.ToLocalTime(); item.PrivateData = assoc.SerializePrivateData(); lock (m_syncRoot) { m_store[item.Handle] = item; m_sortedStore[item.Expires] = item; } } public Association GetAssociation(AssociationRelyingPartyType distinguishingFactor) { lock (m_syncRoot) { if (m_sortedStore.Count > 0) { AssociationItem item = m_sortedStore.Values[m_sortedStore.Count - 1]; return Association.Deserialize(item.Handle, item.Expires.ToUniversalTime(), item.PrivateData); } else { return null; } } } public Association GetAssociation(AssociationRelyingPartyType distinguishingFactor, string handle) { AssociationItem item; bool success = false; lock (m_syncRoot) success = m_store.TryGetValue(handle, out item); if (success) return Association.Deserialize(item.Handle, item.Expires.ToUniversalTime(), item.PrivateData); else return null; } public bool RemoveAssociation(AssociationRelyingPartyType distinguishingFactor, string handle) { lock (m_syncRoot) { for (int i = 0; i < m_sortedStore.Values.Count; i++) { AssociationItem item = m_sortedStore.Values[i]; if (item.Handle == handle) { m_sortedStore.RemoveAt(i); break; } } return m_store.Remove(handle); } } public void ClearExpiredAssociations() { lock (m_syncRoot) { List<AssociationItem> itemsCopy = new List<AssociationItem>(m_sortedStore.Values); DateTime now = DateTime.Now; for (int i = 0; i < itemsCopy.Count; i++) { AssociationItem item = itemsCopy[i]; if (item.Expires <= now) { m_sortedStore.RemoveAt(i); m_store.Remove(item.Handle); } } } } #endregion } public class OpenIdStreamHandler : IStreamHandler { #region HTML /// <summary>Login form used to authenticate OpenID requests</summary> const string LOGIN_PAGE = @"<html> <head><title>OpenSim OpenID Login</title></head> <body> <h3>OpenSim Login</h3> <form method=""post""> <label for=""first"">First Name:</label> <input readonly type=""text"" name=""first"" id=""first"" value=""{0}""/> <label for=""last"">Last Name:</label> <input readonly type=""text"" name=""last"" id=""last"" value=""{1}""/> <label for=""pass"">Password:</label> <input type=""password"" name=""pass"" id=""pass""/> <input type=""submit"" value=""Login""> </form> </body> </html>"; /// <summary>Page shown for a valid OpenID identity</summary> const string OPENID_PAGE = @"<html> <head> <title>{2} {3}</title> <link rel=""openid2.provider openid.server"" href=""{0}://{1}/openid/server/""/> </head> <body>OpenID identifier for {2} {3}</body> </html> "; /// <summary>Page shown for an invalid OpenID identity</summary> const string INVALID_OPENID_PAGE = @"<html><head><title>Identity not found</title></head> <body>Invalid OpenID identity</body></html>"; /// <summary>Page shown if the OpenID endpoint is requested directly</summary> const string ENDPOINT_PAGE = @"<html><head><title>OpenID Endpoint</title></head><body> This is an OpenID server endpoint, not a human-readable resource. For more information, see <a href='http://openid.net/'>http://openid.net/</a>. </body></html>"; #endregion HTML public string ContentType { get { return m_contentType; } } public string HttpMethod { get { return m_httpMethod; } } public string Path { get { return m_path; } } string m_contentType; string m_httpMethod; string m_path; UserLoginService m_loginService; ProviderMemoryStore m_openidStore = new ProviderMemoryStore(); /// <summary> /// Constructor /// </summary> public OpenIdStreamHandler(string httpMethod, string path, UserLoginService loginService) { m_loginService = loginService; m_httpMethod = httpMethod; m_path = path; m_contentType = "text/html"; } /// <summary> /// Handles all GET and POST requests for OpenID identifier pages and endpoint /// server communication /// </summary> public void Handle(string path, Stream request, Stream response, OSHttpRequest httpRequest, OSHttpResponse httpResponse) { Uri providerEndpoint = new Uri(String.Format("{0}://{1}{2}", httpRequest.Url.Scheme, httpRequest.Url.Authority, httpRequest.Url.AbsolutePath)); // Defult to returning HTML content m_contentType = "text/html"; try { NameValueCollection postQuery = HttpUtility.ParseQueryString(new StreamReader(httpRequest.InputStream).ReadToEnd()); NameValueCollection getQuery = HttpUtility.ParseQueryString(httpRequest.Url.Query); NameValueCollection openIdQuery = (postQuery.GetValues("openid.mode") != null ? postQuery : getQuery); OpenIdProvider provider = new OpenIdProvider(m_openidStore, providerEndpoint, httpRequest.Url, openIdQuery); if (provider.Request != null) { if (!provider.Request.IsResponseReady && provider.Request is IAuthenticationRequest) { IAuthenticationRequest authRequest = (IAuthenticationRequest)provider.Request; string[] passwordValues = postQuery.GetValues("pass"); UserProfileData profile; if (TryGetProfile(new Uri(authRequest.ClaimedIdentifier.ToString()), out profile)) { // Check for form POST data if (passwordValues != null && passwordValues.Length == 1) { if (profile != null && m_loginService.AuthenticateUser(profile, passwordValues[0])) authRequest.IsAuthenticated = true; else authRequest.IsAuthenticated = false; } else { // Authentication was requested, send the client a login form using (StreamWriter writer = new StreamWriter(response)) writer.Write(String.Format(LOGIN_PAGE, profile.FirstName, profile.SurName)); return; } } else { // Cannot find an avatar matching the claimed identifier authRequest.IsAuthenticated = false; } } // Add OpenID headers to the response foreach (string key in provider.Request.Response.Headers.Keys) httpResponse.AddHeader(key, provider.Request.Response.Headers[key]); string[] contentTypeValues = provider.Request.Response.Headers.GetValues("Content-Type"); if (contentTypeValues != null && contentTypeValues.Length == 1) m_contentType = contentTypeValues[0]; // Set the response code and document body based on the OpenID result httpResponse.StatusCode = (int)provider.Request.Response.Code; response.Write(provider.Request.Response.Body, 0, provider.Request.Response.Body.Length); response.Close(); } else if (httpRequest.Url.AbsolutePath.Contains("/openid/server")) { // Standard HTTP GET was made on the OpenID endpoint, send the client the default error page using (StreamWriter writer = new StreamWriter(response)) writer.Write(ENDPOINT_PAGE); } else { // Try and lookup this avatar UserProfileData profile; if (TryGetProfile(httpRequest.Url, out profile)) { using (StreamWriter writer = new StreamWriter(response)) { // TODO: Print out a full profile page for this avatar writer.Write(String.Format(OPENID_PAGE, httpRequest.Url.Scheme, httpRequest.Url.Authority, profile.FirstName, profile.SurName)); } } else { // Couldn't parse an avatar name, or couldn't find the avatar in the user server using (StreamWriter writer = new StreamWriter(response)) writer.Write(INVALID_OPENID_PAGE); } } } catch (Exception ex) { httpResponse.StatusCode = (int)HttpStatusCode.InternalServerError; using (StreamWriter writer = new StreamWriter(response)) writer.Write(ex.Message); } } /// <summary> /// Parse a URL with a relative path of the form /users/First_Last and try to /// retrieve the profile matching that avatar name /// </summary> /// <param name="requestUrl">URL to parse for an avatar name</param> /// <param name="profile">Profile data for the avatar</param> /// <returns>True if the parse and lookup were successful, otherwise false</returns> bool TryGetProfile(Uri requestUrl, out UserProfileData profile) { if (requestUrl.Segments.Length == 3 && requestUrl.Segments[1] == "users/") { // Parse the avatar name from the path string username = requestUrl.Segments[requestUrl.Segments.Length - 1]; string[] name = username.Split('_'); if (name.Length == 2) { profile = m_loginService.GetTheUser(name[0], name[1]); return (profile != null); } } profile = null; return false; } } }
41.80826
155
0.570874
[ "BSD-3-Clause" ]
Ideia-Boa/diva-distribution
OpenSim/Grid/UserServer.Modules/OpenIdService.cs
14,173
C#
namespace Stripe { using System; using System.Collections.Generic; using Newtonsoft.Json; using Stripe.Infrastructure; public class SubscriptionSchedule : StripeEntity<SubscriptionSchedule>, IHasId, IHasMetadata, IHasObject { /// <summary> /// Unique identifier for the object. /// </summary> [JsonProperty("id")] public string Id { get; set; } /// <summary> /// String representing the object’s type. Objects of the same type share the same value. /// </summary> [JsonProperty("object")] public string Object { get; set; } /// <summary> /// Time at which the subscription schedule was canceled. Measured in seconds since the /// Unix epoch. /// </summary> [JsonProperty("canceled_at")] [JsonConverter(typeof(DateTimeConverter))] public DateTime? CanceledAt { get; set; } /// <summary> /// Time at which the subscription schedule was completed. Measured in seconds since the /// Unix epoch. /// </summary> [JsonProperty("completed_at")] [JsonConverter(typeof(DateTimeConverter))] public DateTime? CompletedAt { get; set; } /// <summary> /// Time at which the object was created. Measured in seconds since the Unix epoch. /// </summary> [JsonProperty("created")] [JsonConverter(typeof(DateTimeConverter))] public DateTime Created { get; set; } /// <summary> /// Object representing the start and end dates for the current phase of the subscription /// schedule, if it is <c>active</c>. /// </summary> [JsonProperty("current_phase")] public SubscriptionScheduleCurrentPhase CurrentPhase { get; set; } #region Expandable Customer /// <summary> /// ID of the <see cref="Customer"/> associated with the subscription schedule. /// <para>Expandable.</para> /// </summary> [JsonIgnore] public string CustomerId { get => this.InternalCustomer?.Id; set => this.InternalCustomer = SetExpandableFieldId(value, this.InternalCustomer); } /// <summary> /// (Expanded) The <see cref="Customer"/> associated with the subscription schedule. /// </summary> [JsonIgnore] public Customer Customer { get => this.InternalCustomer?.ExpandedObject; set => this.InternalCustomer = SetExpandableFieldObject(value, this.InternalCustomer); } [JsonProperty("customer")] [JsonConverter(typeof(ExpandableFieldConverter<Customer>))] internal ExpandableField<Customer> InternalCustomer { get; set; } #endregion /// <summary> /// Object representing the subscription schedule’s default settings. /// </summary> [JsonProperty("default_settings")] public SubscriptionScheduleDefaultSettings DefaultSettings { get; set; } /// <summary> /// Behavior of the subscription schedule and underlying subscription when it ends. Possible /// values are <c>cancel</c>, <c>none</c>, <c>release</c> and <c>renew</c>. /// </summary> [JsonProperty("end_behavior")] public string EndBehavior { get; set; } /// <summary> /// Has the value <c>true</c> if the object exists in live mode or the value /// <c>false</c> if the object exists in test mode. /// </summary> [JsonProperty("livemode")] public bool Livemode { get; set; } /// <summary> /// A set of key/value pairs that you can attach to a subscription schedule object. /// </summary> [JsonProperty("metadata")] public Dictionary<string, string> Metadata { get; set; } /// <summary> /// Configuration for the subscription schedule’s phases. /// </summary> [JsonProperty("phases")] public List<SubscriptionSchedulePhase> Phases { get; set; } /// <summary> /// Time at which the subscription schedule was released. Measured in seconds since the /// Unix epoch. /// </summary> [JsonProperty("released_at")] [JsonConverter(typeof(DateTimeConverter))] public DateTime? ReleasedAt { get; set; } /// <summary> /// ID of the subscription once managed by the subscription schedule (if it is released). /// </summary> [JsonProperty("released_subscription")] public string ReleasedSubscriptionId { get; set; } /// <summary> /// Interval and duration at which the subscription schedule renews for when it ends if /// <c>renewal_behavior</c> is <c>renew</c>. /// </summary> [JsonProperty("renewal_interval")] public SubscriptionScheduleRenewalInterval RenewalInterval { get; set; } /// <summary> /// Possible values are <c>active</c>, <c>canceled</c>, <c>completed</c>, /// <c>not_started</c> and <c>released</c>. /// </summary> [JsonProperty("status")] public string Status { get; set; } #region Expandable Subscription /// <summary> /// ID of the <see cref="Subscription"/> associated with the subscription schedule. /// <para>Expandable.</para> /// </summary> [JsonIgnore] public string SubscriptionId { get => this.InternalSubscription?.Id; set => this.InternalSubscription = SetExpandableFieldId(value, this.InternalSubscription); } /// <summary> /// (Expanded) The <see cref="Subscription"/> associated with the subscription schedule. /// </summary> [JsonIgnore] public Subscription Subscription { get => this.InternalSubscription?.ExpandedObject; set => this.InternalSubscription = SetExpandableFieldObject(value, this.InternalSubscription); } [JsonProperty("subscription")] [JsonConverter(typeof(ExpandableFieldConverter<Subscription>))] internal ExpandableField<Subscription> InternalSubscription { get; set; } #endregion } }
37.195266
108
0.600859
[ "Apache-2.0" ]
formstack/stripe-dotnet
src/Stripe.net/Entities/SubscriptionSchedules/SubscriptionSchedule.cs
6,292
C#
/******************************************************************************** * FragmentActionGenerator.cs * * * * Author: Denes Solti * ********************************************************************************/ using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; namespace Solti.Utils.SQL.Internals { using Interfaces; internal sealed class FragmentActionGenerator<TView>: ActionGenerator<TView> { private static readonly bool IsAggregate = Selections .Any(col => col.Reason is AggregateSelectionAttribute); protected override IEnumerable<MethodCallExpression> Generate(ParameterExpression bldr) { foreach(ColumnSelection sel in Selections) { IFragmentFactory fragment = sel.Reason; foreach (MethodCallExpression action in fragment.GetFragments(bldr, sel.ViewProperty, IsAggregate)) { yield return action; } } } } }
38.4375
115
0.45935
[ "MIT" ]
Sholtee/sql
SRC/SqlUtils/Private/SqlBuilder/Generators/FragmentActionGenerator.cs
1,230
C#
using System.Collections.Generic; namespace PackProject.Tool.Services.GraphAnalyzer { public class ProjectDefinition { public static IEqualityComparer<ProjectDefinition> PathComparer { get; } = new PathEqualityComparer(); public string Path { get; set; } public string Version { get; set; } public string PackageName { get; set; } private sealed class PathEqualityComparer : IEqualityComparer<ProjectDefinition> { public bool Equals(ProjectDefinition x, ProjectDefinition y) { if (ReferenceEquals(x, y)) return true; if (ReferenceEquals(x, null)) return false; if (ReferenceEquals(y, null)) return false; if (x.GetType() != y.GetType()) return false; return x.Path == y.Path; } public int GetHashCode(ProjectDefinition obj) { return (obj.Path != null ? obj.Path.GetHashCode() : 0); } } } }
32.25
110
0.583333
[ "MIT" ]
btshft/ProjectPack
src/Tool/Services/GraphAnalyzer/ProjectDefinition.cs
1,034
C#
using Luna.Gpio.Controllers; using Luna.Logging; using Luna.Logging.Interfaces; using System.Collections.Generic; using System.Threading.Tasks; namespace Luna.Gpio.Events { public class EventManager { private readonly ILogger Logger = new Logger(typeof(EventManager).Name); private readonly Dictionary<int, Generator> Events = new Dictionary<int, Generator>(); private readonly GpioCore Core; internal EventManager(GpioCore _core) => Core = _core; internal async Task<bool> RegisterEvent(EventConfig config) { if (!PinController.IsValidPin(config.GpioPin)) { Logger.Warning("The specified pin is invalid."); return false; } if (Events.ContainsKey(config.GpioPin)) { return false; } Generator gen = new Generator(Core, config, Logger); while (!gen.Config.IsEventRegistered) { await Task.Delay(1).ConfigureAwait(false); } Events.Add(config.GpioPin, gen); return gen.Config.IsEventRegistered; } internal void StopAllEventGenerators() { foreach(KeyValuePair<int, Generator> pair in Events) { StopEventGeneratorForPin(pair.Key); } } internal void StopEventGeneratorForPin(int pin) { if (!PinController.IsValidPin(pin)) { return; } if(!Events.TryGetValue(pin, out Generator? generator) || generator == null) { return; } generator.OverrideEventPolling(); Logger.Trace($"Stopped pin polling for '{pin}' pin"); } } }
25.818182
88
0.715493
[ "MIT" ]
ArunPrakashG/HomeAssistant
Assistant.Gpio/Events/EventManager.cs
1,420
C#
using System.Collections.Generic; using Macad.Core; using Macad.Occt; using Macad.Occt.Helper; using Macad.Resources; namespace Macad.Interaction.Visual { public class ClipPlane { static Graphic3d_TextureMap _HatchTexture = null; //-------------------------------------------------------------------------------------------------- readonly Graphic3d_ClipPlane _OcClipPlane; readonly List<V3d_View> _Views = new List<V3d_View>(); //-------------------------------------------------------------------------------------------------- public ClipPlane(Pln plane) { _OcClipPlane = new Graphic3d_ClipPlane(plane); _UpdateAspects(); _OcClipPlane.SetOn(true); } //-------------------------------------------------------------------------------------------------- ~ClipPlane() { _OcClipPlane.Dispose(); } //-------------------------------------------------------------------------------------------------- void _UpdateAspects() { if (_HatchTexture == null) { var bitmap = ResourceUtils.ReadBitmapFromResource(@"Visual\Hatch45.png"); if (bitmap == null) { Messages.Error($"Could not load hatch texture from resource."); return; } var pixmap = PixMapHelper.ConvertFromBitmap(bitmap); if (pixmap == null) { Messages.Error($"Could not load hatch texture into pixmap."); return; } _HatchTexture = new Graphic3d_Texture2Dmanual(pixmap); _HatchTexture.EnableModulate(); _HatchTexture.EnableRepeat(); _HatchTexture.GetParams().SetScale(new Graphic3d_Vec2(0.05f)); } _OcClipPlane.SetCapping(true); _OcClipPlane.SetUseObjectMaterial(true); _OcClipPlane.SetUseObjectTexture(false); _OcClipPlane.SetCappingTexture(_HatchTexture); } //-------------------------------------------------------------------------------------------------- public void Remove() { _Views.ForEach(view => view.RemoveClipPlane(_OcClipPlane)); _Views.Clear(); } //-------------------------------------------------------------------------------------------------- public void AddViewport(Viewport vcViewport) { var ocView = vcViewport.V3dView; if (_Views.Contains(ocView)) return; _Views.Add(ocView); ocView.AddClipPlane(_OcClipPlane); ocView.Update(); } //-------------------------------------------------------------------------------------------------- } }
33.362637
109
0.389657
[ "MIT" ]
aliveho/Macad3D
Source/Macad.Interaction/Visual/ClipPlane.cs
3,038
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 neptune-2014-10-31.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.Neptune.Model { /// <summary> /// Container for the parameters to the DescribeDBParameterGroups operation. /// Returns a list of <code>DBParameterGroup</code> descriptions. If a <code>DBParameterGroupName</code> /// is specified, the list will contain only the description of the specified DB parameter /// group. /// </summary> public partial class DescribeDBParameterGroupsRequest : AmazonNeptuneRequest { private string _dbParameterGroupName; private List<Filter> _filters = new List<Filter>(); private string _marker; private int? _maxRecords; /// <summary> /// Gets and sets the property DBParameterGroupName. /// <para> /// The name of a specific DB parameter group to return details for. /// </para> /// /// <para> /// Constraints: /// </para> /// <ul> <li> /// <para> /// If supplied, must match the name of an existing DBClusterParameterGroup. /// </para> /// </li> </ul> /// </summary> public string DBParameterGroupName { get { return this._dbParameterGroupName; } set { this._dbParameterGroupName = value; } } // Check to see if DBParameterGroupName property is set internal bool IsSetDBParameterGroupName() { return this._dbParameterGroupName != null; } /// <summary> /// Gets and sets the property Filters. /// <para> /// This parameter is not currently supported. /// </para> /// </summary> public List<Filter> Filters { get { return this._filters; } set { this._filters = value; } } // Check to see if Filters property is set internal bool IsSetFilters() { return this._filters != null && this._filters.Count > 0; } /// <summary> /// Gets and sets the property Marker. /// <para> /// An optional pagination token provided by a previous <code>DescribeDBParameterGroups</code> /// request. If this parameter is specified, the response includes only records beyond /// the marker, up to the value specified by <code>MaxRecords</code>. /// </para> /// </summary> public string Marker { get { return this._marker; } set { this._marker = value; } } // Check to see if Marker property is set internal bool IsSetMarker() { return this._marker != null; } /// <summary> /// Gets and sets the property MaxRecords. /// <para> /// The maximum number of records to include in the response. If more records exist than /// the specified <code>MaxRecords</code> value, a pagination token called a marker is /// included in the response so that the remaining results can be retrieved. /// </para> /// /// <para> /// Default: 100 /// </para> /// /// <para> /// Constraints: Minimum 20, maximum 100. /// </para> /// </summary> public int MaxRecords { get { return this._maxRecords.GetValueOrDefault(); } set { this._maxRecords = value; } } // Check to see if MaxRecords property is set internal bool IsSetMaxRecords() { return this._maxRecords.HasValue; } } }
32.413043
108
0.588867
[ "Apache-2.0" ]
ChristopherButtars/aws-sdk-net
sdk/src/Services/Neptune/Generated/Model/DescribeDBParameterGroupsRequest.cs
4,473
C#
/* Copyright (c) 2015 Ki 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.Xml.Linq; using ILSpy.BamlDecompiler.Baml; namespace ILSpy.BamlDecompiler.Handlers { internal class PropertyArrayHandler : IHandler { public BamlRecordType Type => BamlRecordType.PropertyArrayStart; public BamlElement Translate(XamlContext ctx, BamlNode node, BamlElement parent) { var record = (PropertyArrayStartRecord)((BamlBlockNode)node).Header; var doc = new BamlElement(node); var elemAttr = ctx.ResolveProperty(record.AttributeId); doc.Xaml = new XElement(elemAttr.ToXName(ctx, null)); doc.Xaml.Element.AddAnnotation(elemAttr); parent.Xaml.Element.Add(doc.Xaml.Element); HandlerMap.ProcessChildren(ctx, (BamlBlockNode)node, doc); elemAttr.DeclaringType.ResolveNamespace(doc.Xaml, ctx); doc.Xaml.Element.Name = elemAttr.ToXName(ctx, null); return doc; } } }
37.156863
82
0.775198
[ "MIT" ]
AraHaan/ILSpy
ILSpy.BamlDecompiler/Handlers/Blocks/PropertyArrayHandler.cs
1,897
C#
using GammaJul.ReSharper.EnhancedTooltip.DocumentMarkup; using JetBrains.ProjectModel; using JetBrains.ReSharper.Daemon.CSharp.Errors; using JetBrains.ReSharper.Psi.CodeAnnotations; namespace GammaJul.ReSharper.EnhancedTooltip.Presentation.Highlightings.CSharp { [SolutionComponent] internal sealed class CannotImplementDynamicInterfaceErrorEnhancer : CSharpHighlightingEnhancer<CannotImplementDynamicInterfaceError> { protected override void AppendTooltip(CannotImplementDynamicInterfaceError highlighting, CSharpColorizer colorizer) { colorizer.AppendPlainText("Cannot implement a "); colorizer.AppendKeyword("dynamic"); colorizer.AppendPlainText(" interface '"); colorizer.AppendExpressionType(highlighting.SuperType, false, PresenterOptions.FullWithoutParameterNames); colorizer.AppendPlainText("'"); } public CannotImplementDynamicInterfaceErrorEnhancer( TextStyleHighlighterManager textStyleHighlighterManager, CodeAnnotationsConfiguration codeAnnotationsConfiguration, HighlighterIdProviderFactory highlighterIdProviderFactory) : base(textStyleHighlighterManager, codeAnnotationsConfiguration, highlighterIdProviderFactory) { } } }
42.285714
136
0.847973
[ "Apache-2.0" ]
FallenDev/ReSharper.EnhancedTooltip
source/GammaJul.ReSharper.EnhancedTooltip/Presentation/Highlightings/CSharp/CannotImplementDynamicInterfaceErrorEnhancer.cs
1,184
C#
using System; using System.Collections.Generic; using System.Configuration; using System.Web.Mvc; using Moq; using Ninject; using PyrotechnicShop.Domain.Entities; using PyrotechnicShop.Domain.Abstract; using PyrotechnicShop.Domain.Concrete; using PyrotechnicShop.WebUI.Infrastructure.Abstract; using PyrotechnicShop.WebUI.Infrastructure.Concrete; namespace PyrotechnicShop.WebUI.Infrastructure { public class NinjectDependencyResolver : IDependencyResolver { private IKernel kernel; public NinjectDependencyResolver(IKernel kernelParam) { kernel = kernelParam; AddBindings(); } public object GetService(Type serviceType) { return kernel.TryGet(serviceType); } public IEnumerable<object> GetServices(Type serviceType) { return kernel.GetAll(serviceType); } private void AddBindings() { kernel.Bind<IPyrotechnicsRepository>().To<EFPyrotechnicsRepository>(); EmailSettings emailSettings = new EmailSettings { WriteAsFile = bool.Parse(ConfigurationManager .AppSettings["Email.WriteAsFile"] ?? "false") }; kernel.Bind<IOrderProcessor>().To<EmailOrderProcessor>() .WithConstructorArgument("settings", emailSettings); kernel.Bind<IAuthProvider>().To<FormAuthProvider>(); } } }
28.72549
82
0.656655
[ "MIT" ]
oldgunner/PyrotechnicShop
PyrotechnicShop.WebUI/Infrastructure/NinjectDependencyResolver.cs
1,467
C#
using System; using Otter.Graphics; using Otter.Graphics.Drawables; using Otter.Utility; namespace Otter.Colliders { /// <summary> /// Collider that can use an image as a mask. This is not recommended to use for most cases as it can /// be pretty expensive to process. /// </summary> public class PixelCollider : Collider { #region Public Fields /// <summary> /// The amount of Alpha a pixel needs to exceed to register as a collision. /// If 0, any pixel with an alpha above 0 will register as collidable. /// </summary> public float Threshold = 0; #endregion #region Public Properties /// <summary> /// The byte array of pixels. /// </summary> public byte[] Pixels { get { return collideImage.Pixels; } } #endregion #region Private Fields SFML.Graphics.Image collideImage; SFML.Graphics.Texture texture; Texture visibleTexture; Graphic visibleImage; bool rendered; #endregion #region Constructors /// <summary> /// Creates a pixel collider. /// </summary> /// <param name="source">The source image to create the collider from.</param> /// <param name="tags">The tags to register the collider with.</param> public PixelCollider(string source, params int[] tags) { texture = Textures.Load(source); collideImage = texture.CopyToImage(); Width = texture.Size.X; Height = texture.Size.Y; AddTag(tags); } public PixelCollider(Texture texture, params int[] tags) { this.texture = texture.SFMLTexture; collideImage = this.texture.CopyToImage(); Width = this.texture.Size.X; Height = this.texture.Size.Y; AddTag(tags); } public PixelCollider(string source, Enum tag, params Enum[] tags) : this(source) { AddTag(tag); AddTag(tags); } public PixelCollider(Texture texture, Enum tag, params Enum[] tags) : this(texture) { AddTag(tag); AddTag(tags); } #endregion #region Private Methods void InitializeTexture() { visibleTexture = new Texture((int)Width, (int)Height); for (var x = 0; x < Width; x++) { for (var y = 0; y < Height; y++) { if (PixelAt(x, y)) { visibleTexture.SetPixel(x, y, Color.Red); } else { visibleTexture.SetPixel(x, y, Color.None); } } } visibleImage = new Image(visibleTexture); } #endregion #region Public Methods /// <summary> /// Check if a pixel is collidable at x, y. /// </summary> /// <param name="x">The X position of the pixel to check.</param> /// <param name="y">The Y position of the pixel to check.</param> /// <returns>True if the pixel collides.</returns> public bool PixelAt(int x, int y) { if (x < 0 || y < 0 || x > Width || y > Height) return false; if (collideImage.GetPixel((uint)x, (uint)y).A > Threshold) return true; return false; } /// <summary> /// Check if a pixel is collidable at X, Y. /// </summary> /// <param name="x">The X position of the pixel to check.</param> /// <param name="y">The Y position of the pixel to check.</param> /// <param name="threshold">The alpha threshold that should register a collision.</param> /// <returns>True if the pixel collides.</returns> public bool PixelAt(int x, int y, float threshold) { if (x < 0 || y < 0 || x > Width || y > Height) return false; if (collideImage.GetPixel((uint)x, (uint)y).A > threshold) return true; return false; } /// <summary> /// Check if a pixel is collideable at X - Left, Y - Top. /// </summary> /// <param name="x">The X position of the pixel to check.</param> /// <param name="y">The Y position of the pixel to check.</param> /// <returns>True if the pixel collides.</returns> public bool PixelAtRelative(int x, int y) { x -= (int)Left; y -= (int)Top; return PixelAt(x, y); } /// <summary> /// Check if a pixel is collideable at X - Left, Y - Top. /// </summary> /// <param name="x">The X position of the pixel to check.</param> /// <param name="y">The Y position of the pixel to check.</param> /// <param name="threshold">The alpha threshold that should register a collision.</param> /// <returns>True if the pixel collides.</returns> public bool PixelAtRelative(int x, int y, float threshold) { x -= (int)Left; y -= (int)Top; return PixelAt(x, y, threshold); } /// <summary> /// Check if any pixels in the area defined by X, Y, X2, Y2 are collideable. /// </summary> /// <param name="x">The left of the area to check.</param> /// <param name="y">The top of the area to check.</param> /// <param name="x2">The right of the area to check.</param> /// <param name="y2">The bottom of the area to check.</param> /// <returns>True if the pixel collides.</returns> public bool PixelArea(int x, int y, int x2, int y2) { for (var i = x; i < x2; i++) { for (var j = y; j < y2; j++) { if (PixelAt(i, j)) return true; } } return false; } /// <summary> /// Check if any pixels in the area defined by X, Y, X2, Y2 are collideable. /// </summary> /// <param name="x">The left of the area to check.</param> /// <param name="y">The top of the area to check.</param> /// <param name="x2">The right of the area to check.</param> /// <param name="y2">The bottom of the area to check.</param> /// <param name="threshold">The alpha threshold that should register a collision.</param> /// <returns>True if the pixel collides.</returns> public bool PixelArea(int x, int y, int x2, int y2, float threshold) { for (var i = x; i < x2; i++) { for (var j = y; j < y2; j++) { if (PixelAt(i, j, threshold)) return true; } } return false; } /// <summary> /// Draw the collider for debug purposes. /// </summary> public override void Render(Color color = null) { base.Render(color); if (color == null) color = Color.Red; if (Entity == null) return; if (!rendered) { rendered = true; InitializeTexture(); } visibleImage.Color = color; Draw.Graphic(visibleImage, Left, Top); } #endregion } }
31.195021
106
0.506651
[ "MIT" ]
WillSams/Otter
Otter/Colliders/PixelCollider.cs
7,518
C#
// Copyright (c) Microsoft. All rights reserved. namespace Microsoft.Azure.Devices.Routing.Core { public class NullRoutingUserMetricLogger : IRoutingUserMetricLogger { public static NullRoutingUserMetricLogger Instance { get; } = new NullRoutingUserMetricLogger(); NullRoutingUserMetricLogger() { } public void LogEgressMetric(long metricValue, string iotHubName, MessageRoutingStatus messageStatus, string messageSource) { } public void LogEgressFallbackMetric(long metricValue, string iotHubName) { } public void LogEventHubEndpointEgressSuccessMetric(long metricValue, string iotHubName) { } public void LogEventHubEndpointLatencyMetric(long metricValue, string iotHubName) { } public void LogQueueEndpointEgressSuccessMetric(long metricValue, string iotHubName) { } public void LogQueueEndpointLatencyMetric(long metricValue, string iotHubName) { } public void LogTopicEndpointEgressSuccessMetric(long metricValue, string iotHubName) { } public void LogTopicEndpointLatencyMetric(long metricValue, string iotHubName) { } public void LogBuiltInEndpointEgressSuccessMetric(long metricValue, string iotHubName) { } public void LogBuiltInEndpointLatencyMetric(long metricValue, string iotHubName) { } } }
28.846154
130
0.674667
[ "MIT" ]
DaveEM/iotedge
edge-hub/src/Microsoft.Azure.Devices.Routing.Core/NullRoutingUserMetricLogger.cs
1,502
C#
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Threading.Tasks; namespace HTLLBB.Models.ForumViewModels { public class IndexViewModel { [Required] public bool IsAdmin { get; set; } [Required] public Forum Forum { get; set; } [Required] public String UserId { get; set; } } }
21.842105
44
0.660241
[ "MIT" ]
filedesless/HTLLBB
src/Models/ForumViewModels/IndexViewModel.cs
417
C#
using System; using System.Collections.Generic; using Xamarin.Forms; namespace OfPost.View { public partial class HomePage : ContentPage { public HomePage() { InitializeComponent(); } } }
14.9375
47
0.610879
[ "MIT" ]
ooleglysiak/of_post_frontend_app
OfPost/View/HomePage.xaml.cs
241
C#
// Copyright 2007-2019 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.Registration { using System; using System.Collections.Concurrent; using Scoping; public static class ConsumerConfiguratorCache { static CachedConfigurator GetOrAdd(Type type) { return Cached.Instance.GetOrAdd(type, _ => (CachedConfigurator)Activator.CreateInstance(typeof(CachedConfigurator<>).MakeGenericType(type))); } public static void Configure(Type consumerType, IReceiveEndpointConfigurator configurator, IConsumerScopeProvider scopeProvider) { GetOrAdd(consumerType).Configure(configurator, scopeProvider); } interface CachedConfigurator { void Configure(IReceiveEndpointConfigurator configurator, IConsumerScopeProvider scopeProvider); } class CachedConfigurator<T> : CachedConfigurator where T : class, IConsumer { public void Configure(IReceiveEndpointConfigurator configurator, IConsumerScopeProvider scopeProvider) { var consumerFactory = new ScopeConsumerFactory<T>(scopeProvider); configurator.Consumer(consumerFactory); } } static class Cached { internal static readonly ConcurrentDictionary<Type, CachedConfigurator> Instance = new ConcurrentDictionary<Type, CachedConfigurator>(); } } }
36.362069
154
0.674727
[ "ECL-2.0", "Apache-2.0" ]
AOrlov/MassTransit
src/MassTransit/Configuration/Registration/ConsumerConfiguratorCache.cs
2,111
C#
//----------------------------------------------------------------------- // <copyright file="ExcludeDataFromInspectorAttribute.cs" company="Sirenix IVS"> // Copyright (c) 2018 Sirenix IVS // // 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. // </copyright> //----------------------------------------------------------------------- namespace instance.id.OdinSerializer { using System; /// <summary> /// <para> /// Causes Odin's inspector to completely ignore a given member, preventing it from even being included in an Odin PropertyTree, /// and such will not cause any performance hits in the inspector. /// </para> /// <para>Note that Odin can still serialize an excluded member - it is merely ignored in the inspector itself.</para> /// </summary> [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = false, Inherited = true)] [Obsolete("Use [HideInInspector] instead - it now also excludes the member completely from becoming a property in the property tree.", false)] public sealed class ExcludeDataFromInspectorAttribute : Attribute { } }
48.058824
146
0.664015
[ "MIT" ]
instance-id/SO-Persistent-Reference
Assets/instance.id/SOReference/Utils/OdinSerializer/Core/Misc/ExcludeDataFromInspectorAttribute.cs
1,634
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace Microsoft.Extensions.Hosting { using System; using System.Reflection; /// <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("Microsoft.Extensions.Hosting.Resources", typeof(Resources).GetTypeInfo().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; } } /// <summary> /// Looks up a localized string similar to HostBuilder allows creation only of a single instance of Host. /// </summary> internal static string HostBuilder_SingleInstance { get { return ResourceManager.GetString("HostBuilder_SingleInstance", resourceCulture); } } } }
43.364865
197
0.613275
[ "MIT" ]
Magicianred/Messaging
src/Microsoft.Extensions.Hosting/Resources.Designer.cs
3,211
C#
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="OpenSkyService.cs" company="OpenSky"> // OpenSky project 2021-2022 // </copyright> // -------------------------------------------------------------------------------------------------------------------- // ReSharper disable once CheckNamespace namespace OpenSkyApi { using System.Net.Http; using OpenSky.Client.Properties; /// ------------------------------------------------------------------------------------------------- /// <summary> /// OpenSky API service client. /// </summary> /// <remarks> /// sushi.at, 01/06/2021. /// </remarks> /// <seealso cref="T:OpenSkyApi.OpenSkyServiceBase"/> /// ------------------------------------------------------------------------------------------------- public partial class OpenSkyService { /// ------------------------------------------------------------------------------------------------- /// <summary> /// Initializes static members of the <see cref="OpenSkyService"/> class. /// </summary> /// <remarks> /// sushi.at, 01/06/2021. /// </remarks> /// ------------------------------------------------------------------------------------------------- static OpenSkyService() { Instance = new OpenSkyService(new HttpClient()); } /// ------------------------------------------------------------------------------------------------- /// <summary> /// Initializes a new instance of the <see cref="OpenSkyService"/> class. /// </summary> /// <remarks> /// sushi.at, 01/06/2021. /// </remarks> /// <param name="httpClient"> /// The HTTP client. /// </param> /// ------------------------------------------------------------------------------------------------- private OpenSkyService(HttpClient httpClient) : base(httpClient) { this.BaseUrl = Settings.Default.OpenSkyAPIUrl; this._httpClient = httpClient; this._settings = new System.Lazy<Newtonsoft.Json.JsonSerializerSettings>(this.CreateSerializerSettings); } /// ------------------------------------------------------------------------------------------------- /// <summary> /// Gets the single static instance. /// </summary> /// ------------------------------------------------------------------------------------------------- public static OpenSkyService Instance { get; } } }
41.734375
120
0.33246
[ "MIT" ]
opensky-to/client
OpenSky.Client/OpenAPIs/OpenSkyService.cs
2,673
C#
using Ding.MockData.Abstractions.Options; namespace Ding.MockData.Core.Options { /// <summary> /// Guid配置 /// </summary> public class GuidFieldOptions : FieldOptionsBase, IGuidFieldOptions { /// <summary> /// 是否大写字符 /// </summary> public bool Uppercase { get; set; } = true; } }
21.0625
71
0.58457
[ "MIT" ]
EnhWeb/DC.Framework
src/Ding.MockData/Core/Options/GuidFieldOptions.cs
355
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace FlowerViewer { public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); Model m = new Model(this); FlowerApp.Launch(this, m); // FlowerCore.RefreshUI(this, flowers[0]); } } }
23.586207
54
0.694444
[ "BSD-3-Clause" ]
ant04x/FlowerViewer
MainWindow.xaml.cs
686
C#
using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ASS { public class tactLogType { public int id { get; set; } public int TactNumber { get; set; } public int Time { get; set; } public string PlateID { get; set; } public DateTime RunDate { get; set; } public int roundNumber { get; set; } public int ParcelsOnbuffer { get; set; } public int ParcelsOnLine { get; set; } public int StartSensorReads { get; set; } public int StoptSensorReads { get; set; } public int TactSensorReads { get; set; } public int LenghtSensorReads { get; set; } public int SignalingReads { get; set; } public int Scanner1SensorReads { get; set; } public int PlateSensorReads { get; set; } public int Stand1_Reads { get; set; } public int Stand2_Reads { get; set; } public int Stand3_Reads { get; set; } public int Stand4_Reads { get; set; } public int Stand5_Reads { get; set; } public int Stand6_Reads { get; set; } public int Stand7_Reads { get; set; } public int Stand8_Reads { get; set; } public int Stand9_Reads { get; set; } public int Stand10_Reads { get; set; } public int Stand11_Reads { get; set; } public int Stand12_Reads { get; set; } public int Stand13_Reads { get; set; } public int SignalingWrites { get; set; } public DataTable dt { get; set; } public int TCPRead { get; set; } public int TCPWrite { get; set; } public int MysqlCommand { get; set; } public int TimeStamp { get; set; } public tactLogType(int TactNumber, string time, string plateID,int roundnumber,int parcelsbuffer,int parcelsline, int StartSensorReads , int StoptSensorReads , int TactSensorReads , int LenghtSensorReads , int SignalingReads , int Scanner1SensorReads , int PlateSensorReads , int Stand1_Reads , int Stand2_Reads , int Stand3_Reads , int Stand4_Reads , int Stand5_Reads , int Stand6_Reads , int Stand7_Reads , int Stand8_Reads , int Stand9_Reads , int Stand10_Reads , int Stand11_Reads , int Stand12_Reads , int Stand13_Reads , int signalingwrites, int tcpread,int tcpwrite,int mysqlcommand, DataTable tb, int timestamp ) { int test = 0; this.TactNumber = TactNumber ; //this.Time = int.Parse(time.Split(',')[0]); int.TryParse(time.Split(',')[0], out test); this.Time = test; this.TimeStamp = timestamp; this.PlateID = plateID; this.RunDate = DateTime.Now; this.roundNumber = roundnumber; this.ParcelsOnbuffer = parcelsbuffer; this.ParcelsOnLine = parcelsline; this.StartSensorReads = StartSensorReads; this.StoptSensorReads = StoptSensorReads; this.TactSensorReads = TactSensorReads; this.LenghtSensorReads = LenghtSensorReads; this.SignalingReads = SignalingReads; this.Scanner1SensorReads = Scanner1SensorReads; this.PlateSensorReads = PlateSensorReads; this.Stand1_Reads = Stand1_Reads; this.Stand2_Reads = Stand2_Reads; this.Stand3_Reads = Stand3_Reads; this.Stand4_Reads = Stand4_Reads; this.Stand5_Reads = Stand5_Reads; this.Stand6_Reads = Stand6_Reads; this.Stand7_Reads = Stand7_Reads; this.Stand8_Reads = Stand8_Reads; this.Stand9_Reads = Stand9_Reads; this.Stand10_Reads = Stand10_Reads; this.Stand11_Reads = Stand11_Reads; this.Stand12_Reads = Stand12_Reads; this.Stand13_Reads = Stand13_Reads; this.SignalingWrites = signalingwrites; this.TCPRead = tcpread; this.TCPWrite = tcpwrite; this.MysqlCommand = mysqlcommand; this.dt = tb; } public static string ToJson(List<tactLogType> l) { string js = JsonConvert.SerializeObject(l); return js; } public static void SaveAsync(List<tactLogType> l) { Task.Run(() => Save(l)); } private static void Save(List<tactLogType> l) { if (l != null) { if (l.Count > 0) { mySQLcore m = mySQLcore.DB_Main(); string delid = m.GetString("SELECT id FROM tactlogs order by id desc limit 49,50;"); m.ExecuteNonQuery("delete from tactlogs where id < " + delid + ";"); TactLogDBType o = new TactLogDBType(); o.js = ToJson(l); o.roundnumber = l[0].roundNumber; m.Insert("tactlogs", "id", o); } } } } public class TactLogDBType { public int id { get; set; } public string js { get; set; } public int roundnumber { get; set; } public static List<tactLogType> GetData(int id) { mySQLcore m = mySQLcore.DB_Main(); string js = m.GetString("select js from tactlogs where id = '" + id + "';"); List<tactLogType> l = JsonConvert.DeserializeObject<List<tactLogType>>(js); return l; } } }
33.988166
121
0.564589
[ "CC0-1.0" ]
pawelklis/ASS
ASS/tactLogType.cs
5,746
C#
using System.Runtime.Serialization; namespace BabylonExport.Entities { [DataContract] public class BabylonCubeTexture : BabylonTexture { [DataMember] public string customType { get; private set; } [DataMember] public bool filtered { get; private set; } [DataMember] public float[] boundingBoxSize { get; set; } [DataMember] public float[] boundingBoxPosition { get; set; } [DataMember] public bool prefiltered = false; public BabylonCubeTexture() { SetCustomType("BABYLON.CubeTexture"); isCube = true; filtered = true; prefiltered = false; boundingBoxSize = null; boundingBoxPosition = null; } public void SetCustomType(string type) { customType = type; } } }
23.552632
56
0.567598
[ "MIT" ]
davidzwa/BabylonUnityLearnings
RollABall/Assets/Babylon/Entities/BabylonCubeTexture.cs
897
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("SpaceSpiders.Services")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("SpaceSpiders.Services")] [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("9885c90f-4d3f-4eae-9478-5cabb8139d80")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
38.055556
84
0.753285
[ "MIT" ]
pollirrata/service-fabric-talkdemos
spacespiders/TraditionalBackend/SpaceSpiders.Services/SpaceSpiders.Services/Properties/AssemblyInfo.cs
1,373
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. */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; using System.Text; using System.Xml; using Amazon.Runtime; using Amazon.SecurityToken.Model; namespace Amazon.SecurityToken.SAML { #if !NETSTANDARD13 /// <summary> /// Contains the parsed SAML response data following successful user /// authentication against a federated endpoint. We only parse out the /// data we need to support generation of temporary AWS credentials. /// </summary> public class SAMLAssertion { const string AssertionNamespace = "urn:oasis:names:tc:SAML:2.0:assertion"; const string RoleXPath = "//response:Attribute[@Name='https://aws.amazon.com/SAML/Attributes/Role']"; /// <summary> /// The full SAML assertion parsed from the identity provider's /// response. /// </summary> public string AssertionDocument { get; private set; } /// <summary> /// The collection of roles available to the authenticated user. /// he parsed friendly role name is used to key the entries. /// </summary> public IDictionary<string, string> RoleSet { get; private set; } /// <summary> /// Retrieves a set of temporary credentials for the specified role, valid for the specified timespan. /// If the SAML authentication data yield more than one role, a valid role name must be specified. /// </summary> /// <param name="stsClient">The STS client to use when making the AssumeRoleWithSAML request.</param> /// <param name="principalAndRoleArns"> /// The arns of the principal and role as returned in the SAML assertion. /// </param> /// <param name="duration">The valid timespan for the credentials.</param> /// <returns>Temporary session credentials for the specified or default role for the user.</returns> public SAMLImmutableCredentials GetRoleCredentials( IAmazonSecurityTokenService stsClient, string principalAndRoleArns, TimeSpan duration) { string roleArn = null; string principalArn = null; var swappedPrincipalAndRoleArns = string.Empty; if (!string.IsNullOrEmpty(principalAndRoleArns)) { var roleComponents = principalAndRoleArns.Split(','); if(roleComponents.Count() != 2) { throw new ArgumentException("Unknown or invalid principal and role arns format."); } swappedPrincipalAndRoleArns = roleComponents.Last() + "," + roleComponents.First(); } foreach (var s in RoleSet.Values) { if (s.Equals(principalAndRoleArns, StringComparison.OrdinalIgnoreCase) || s.Equals(swappedPrincipalAndRoleArns, StringComparison.OrdinalIgnoreCase)) { var roleComponents = s.Split(','); if (IsSamlProvider(roleComponents.First())) { //Backwards compatible format -- arn:...:saml-provider/SAML,arn:...:role/RoleName principalArn = roleComponents.First(); roleArn = roleComponents.Last(); } else { //Documented format -- arn:...:role/RoleName,arn:...:saml-provider/SAML roleArn = roleComponents.First(); principalArn = roleComponents.Last(); } break; } } if (string.IsNullOrEmpty(roleArn) || string.IsNullOrEmpty(principalArn)) throw new ArgumentException("Unknown or invalid role specified."); var assumeSamlRequest = new AssumeRoleWithSAMLRequest { SAMLAssertion = AssertionDocument, RoleArn = roleArn, PrincipalArn = principalArn, DurationSeconds = (int)duration.TotalSeconds }; #if NETSTANDARD //In the NetStandard SDK flavor the sync operations are internal only. var response = ((AmazonSecurityTokenServiceClient)stsClient).AssumeRoleWithSAML(assumeSamlRequest); #else var response = stsClient.AssumeRoleWithSAML(assumeSamlRequest); #endif return new SAMLImmutableCredentials(response.Credentials.GetCredentials(), response.Credentials.Expiration.ToUniversalTime(), response.Subject); } /// <summary> /// Constructs a new SAML assertion wrapper based on a successful authentication /// response and extracts the role data contained in the assertion. /// </summary> /// <param name="assertion"></param> internal SAMLAssertion(string assertion) { AssertionDocument = assertion; RoleSet = ExtractRoleData(); } /// <summary> /// Parses the role data out of the assertion using xpath queries. We additionally /// parse the role ARNs to extract friendly role names that can be used in UI /// prompts in tooling. /// </summary> /// <returns>Dictionary of friendly role names to role arn mappings.</returns> private IDictionary<string, string> ExtractRoleData() { var doc = new XmlDocument(); //var sw = new StringWriter(CultureInfo.InvariantCulture); var decoded = Convert.FromBase64String(AssertionDocument); var deflated = Encoding.UTF8.GetString(decoded); doc.LoadXml(deflated); //using (var tw = new XmlTextWriter(sw) { Formatting = Formatting.Indented }) //{ // doc.WriteTo(tw); //} var nsmgr = new XmlNamespaceManager(doc.NameTable); nsmgr.AddNamespace("response", AssertionNamespace); var roleAttributeNodes = doc.DocumentElement.SelectNodes(RoleXPath, nsmgr); var discoveredRoles = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase); if (roleAttributeNodes != null && roleAttributeNodes.Count > 0) { var roleNodes = roleAttributeNodes[0].ChildNodes; // we use this in case we encounter a provider that does allow duplicate // role definitions (unlikely) var seenRoles = new HashSet<string>(StringComparer.Ordinal); foreach (XmlNode roleNode in roleNodes) { if (!string.IsNullOrEmpty(roleNode.InnerText)) { var chunks = roleNode.InnerText.Split(new[] { ',' }, 3); var samlRole = chunks[0] + ',' + chunks[1]; if (!seenRoles.Contains(samlRole)) { var roleName = string.Empty; if (IsSamlProvider(chunks[1])) { //Documented format -- arn:...:role/RoleName,arn:...:saml-provider/SAML roleName = ExtractRoleName(chunks[0]); } else { //Backwards compatible format -- arn:...:saml-provider/SAML,arn:...:role/RoleName roleName = ExtractRoleName(chunks[1]); } discoveredRoles.Add(roleName, samlRole); seenRoles.Add(samlRole); } } } } return discoveredRoles; } private static bool IsSamlProvider(string chunk) { return chunk.IndexOf(":saml-provider", StringComparison.OrdinalIgnoreCase) != -1; } private static string ExtractRoleName(string chunk) { // It is possible to configure the same role name across different accounts // so we must take account number into consideration to get the friendly name // to avoid duplicate keys //Example chunk format: arn:aws:iam::account-number:role/role-name1 var roleNameStart = chunk.LastIndexOf("::", StringComparison.Ordinal); string roleName; if (roleNameStart >= 0) roleName = chunk.Substring(roleNameStart + 2); else roleName = chunk; return roleName; } } #endif }
42.022422
164
0.571657
[ "Apache-2.0" ]
PureKrome/aws-sdk-net
sdk/src/Services/SecurityToken/Custom/SAML/SAMLAssertion.cs
9,373
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; namespace BizHawk.Client.Common { public interface IMovieImport { ImportResult Import(string path); } internal abstract class MovieImporter : IMovieImport { protected const string EmulationOrigin = "emuOrigin"; protected const string MD5 = "MD5"; protected const string MovieOrigin = "MovieOrigin"; public ImportResult Import(string path) { SourceFile = new FileInfo(path); if (!SourceFile.Exists) { Result.Errors.Add($"Could not find the file {path}"); return Result; } var newFileName = $"{SourceFile.FullName}.{Bk2Movie.Extension}"; Result.Movie = new Bk2Movie(newFileName); RunImport(); if (!Result.Errors.Any()) { Result.Movie.Save(); } return Result; } protected ImportResult Result { get; } = new ImportResult(); protected FileInfo SourceFile { get; private set; } protected abstract void RunImport(); // Get the content for a particular header. protected static string ParseHeader(string line, string headerName) { // Case-insensitive search. int x = line.ToLower().LastIndexOf( headerName.ToLower()) + headerName.Length; string str = line.Substring(x + 1, line.Length - x - 1); return str.Trim(); } // Reduce all whitespace to single spaces. protected static string SingleSpaces(string line) { line = line.Replace("\t", " "); line = line.Replace("\n", " "); line = line.Replace("\r", " "); line = line.Replace("\r\n", " "); string prev; do { prev = line; line = line.Replace(" ", " "); } while (prev != line); return line; } // Ends the string where a NULL character is found. protected static string NullTerminated(string str) { int pos = str.IndexOf('\0'); if (pos != -1) { str = str.Substring(0, pos); } return str; } } public class ImportResult { public IList<string> Warnings { get; } = new List<string>(); public IList<string> Errors { get; } = new List<string>(); public IMovie Movie { get; set; } public static ImportResult Error(string errorMsg) { var result = new ImportResult(); result.Errors.Add(errorMsg); return result; } } [AttributeUsage(AttributeTargets.Class)] public sealed class ImporterForAttribute : Attribute { public ImporterForAttribute(string emulator, string extension) { Emulator = emulator; Extension = extension; } public string Emulator { get; } public string Extension { get; } } }
22.896552
70
0.634036
[ "MIT" ]
Gorialis/BizHawk
BizHawk.Client.Common/movie/import/IMovieImport.cs
2,658
C#
using Com.Danliris.Service.Packing.Inventory.Data.Models.Garmentshipping.GarmentPackingList; using Com.Danliris.Service.Packing.Inventory.Data.Models.Garmentshipping.GarmentShippingInvoice; using Com.Danliris.Service.Packing.Inventory.Infrastructure; using Com.Danliris.Service.Packing.Inventory.Infrastructure.Repositories.GarmentShipping.GarmentPackingList; using Com.Danliris.Service.Packing.Inventory.Infrastructure.Repositories.GarmentShipping.GarmentShippingInvoice; using Com.Danliris.Service.Packing.Inventory.Test.DataUtils.GarmentShipping.GarmentPackingList; using Com.Danliris.Service.Packing.Inventory.Test.DataUtils.GarmentShipping.GarmentShippingInvoice; using System; using System.Linq; using System.Threading.Tasks; using Xunit; namespace Com.Danliris.Service.Packing.Inventory.Test.Repositories.GarmentShipping.GarmentShippingInvoice { public class GarmentShippingInvoiceRepositoryTest : BaseRepositoryTest<PackingInventoryDbContext, GarmentShippingInvoiceRepository, GarmentShippingInvoiceModel, GarmentShippingInvoiceDataUtil> { private const string ENTITY = "GarmentShippingInvoice"; public GarmentShippingInvoiceRepositoryTest() : base(ENTITY) { } [Fact] public async override Task Should_Success_Insert() { string testName = GetCurrentMethod(); var dbContext = DbContext(testName); var serviceProvider = GetServiceProviderMock(dbContext).Object; GarmentPackingListRepository repoPL = new GarmentPackingListRepository(dbContext, serviceProvider); GarmentPackingListDataUtil utilPL = new GarmentPackingListDataUtil(repoPL); GarmentPackingListModel dataPL = utilPL.GetModel(); var dataPackingList = await repoPL.InsertAsync(dataPL); GarmentShippingInvoiceRepository repo = new GarmentShippingInvoiceRepository(dbContext, serviceProvider); GarmentShippingInvoiceDataUtil invoiceDataUtil = new GarmentShippingInvoiceDataUtil(repo, utilPL); GarmentShippingInvoiceModel data = invoiceDataUtil.GetModel(); data.PackingListId = dataPL.Id; var result = await repo.InsertAsync(data); Assert.NotEqual(0, result); } [Fact] public async override Task Should_Success_Delete() { string testName = GetCurrentMethod(); var dbContext = DbContext(testName); var serviceProvider = GetServiceProviderMock(dbContext).Object; GarmentPackingListRepository repoPL = new GarmentPackingListRepository(dbContext, serviceProvider); GarmentPackingListDataUtil utilPL = new GarmentPackingListDataUtil(repoPL); GarmentPackingListModel dataPL = utilPL.GetModel(); var dataPackingList = await repoPL.InsertAsync(dataPL); GarmentShippingInvoiceRepository repo = new GarmentShippingInvoiceRepository(dbContext, serviceProvider); GarmentShippingInvoiceDataUtil invoiceDataUtil = new GarmentShippingInvoiceDataUtil(repo, utilPL); GarmentShippingInvoiceModel data = invoiceDataUtil.GetModel(); data.PackingListId = dataPL.Id; var result = await repo.InsertAsync(data); var resultdelete = await repo.DeleteAsync(data.Id); Assert.NotEqual(0, result); } [Fact] public async override Task Should_Success_ReadById() { string testName = GetCurrentMethod(); var dbContext = DbContext(testName); var serviceProvider = GetServiceProviderMock(dbContext).Object; GarmentPackingListRepository repoPL = new GarmentPackingListRepository(dbContext, serviceProvider); GarmentPackingListDataUtil utilPL = new GarmentPackingListDataUtil(repoPL); GarmentPackingListModel dataPL = utilPL.GetModel(); var dataPackingList = await repoPL.InsertAsync(dataPL); GarmentShippingInvoiceRepository repo = new GarmentShippingInvoiceRepository(dbContext, serviceProvider); GarmentShippingInvoiceDataUtil invoiceDataUtil = new GarmentShippingInvoiceDataUtil(repo, utilPL); GarmentShippingInvoiceModel data = invoiceDataUtil.GetModel(); data.PackingListId = dataPL.Id; var results = await repo.InsertAsync(data); var result = repo.ReadByIdAsync(data.Id); Assert.NotNull(result); } [Fact] public async override Task Should_Success_ReadAll() { string testName = GetCurrentMethod(); var dbContext = DbContext(testName); var serviceProvider = GetServiceProviderMock(dbContext).Object; GarmentPackingListRepository repoPL = new GarmentPackingListRepository(dbContext, serviceProvider); GarmentPackingListDataUtil utilPL = new GarmentPackingListDataUtil(repoPL); GarmentPackingListModel dataPL = utilPL.GetModel(); var dataPackingList = await repoPL.InsertAsync(dataPL); GarmentShippingInvoiceRepository repo = new GarmentShippingInvoiceRepository(dbContext, serviceProvider); GarmentShippingInvoiceDataUtil invoiceDataUtil = new GarmentShippingInvoiceDataUtil(repo, utilPL); GarmentShippingInvoiceModel data = invoiceDataUtil.GetModel(); data.PackingListId = dataPL.Id; var results = await repo.InsertAsync(data); var result = repo.ReadAll(); Assert.NotEmpty(result); } [Fact] public async override Task Should_Success_Update() { string testName = GetCurrentMethod(); var dbContext = DbContext(testName); var serviceProvider = GetServiceProviderMock(dbContext).Object; GarmentPackingListRepository repoPL = new GarmentPackingListRepository(dbContext, serviceProvider); GarmentPackingListDataUtil utilPL = new GarmentPackingListDataUtil(repoPL); GarmentPackingListModel dataPL = utilPL.GetModel(); var dataPackingList = await repoPL.InsertAsync(dataPL); GarmentShippingInvoiceRepository repo = new GarmentShippingInvoiceRepository(dbContext, serviceProvider); GarmentShippingInvoiceRepository repo2 = new GarmentShippingInvoiceRepository(dbContext, serviceProvider); GarmentShippingInvoiceDataUtil invoiceDataUtil = new GarmentShippingInvoiceDataUtil(repo, utilPL); GarmentShippingInvoiceModel oldModel = invoiceDataUtil.GetModels(); oldModel.PackingListId = dataPL.Id; await repo.InsertAsync(oldModel); var model = repo.ReadAll().FirstOrDefault(); var data = await repo.ReadByIdAsync(model.Id); data.SetFrom("aaaa", data.LastModifiedBy, data.LastModifiedAgent); data.SetTo("bbb", data.LastModifiedBy, data.LastModifiedAgent); data.SetConsignee ( "dsdsds", data.LastModifiedBy, data.LastModifiedAgent); data.SetShippingPer( "model.ShippingPer", data.LastModifiedBy, data.LastModifiedAgent); data.SetSailingDate( DateTimeOffset.Now.AddDays(3), data.LastModifiedBy, data.LastModifiedAgent); data.SetConfirmationOfOrderNo( "dada", data.LastModifiedBy, data.LastModifiedAgent); data.SetShippingStaffId( 4, data.LastModifiedBy, data.LastModifiedAgent); data.SetShippingStaff( " model.ShippingStaff", data.LastModifiedBy, data.LastModifiedAgent); data.SetFabricTypeId( 2, data.LastModifiedBy, data.LastModifiedAgent); data.SetFabricType( "model.FabricType", data.LastModifiedBy, data.LastModifiedAgent); data.SetBankAccountId( 3, data.LastModifiedBy, data.LastModifiedAgent); data.SetBankAccount( "model.BankAccount", data.LastModifiedBy, data.LastModifiedAgent); data.SetPaymentDue( 33, data.LastModifiedBy, data.LastModifiedAgent); data.SetPEBNo( "model.PEBNo", data.LastModifiedBy, data.LastModifiedAgent); data.SetPEBDate( DateTimeOffset.Now.AddDays(3), data.LastModifiedBy, data.LastModifiedAgent); data.SetNPENo( "model.NPENo", data.LastModifiedBy, data.LastModifiedAgent); data.SetNPEDate( DateTimeOffset.Now.AddDays(3), data.LastModifiedBy, data.LastModifiedAgent); data.SetBL( "model.BL", data.LastModifiedBy, data.LastModifiedAgent); data.SetBLDate( DateTimeOffset.Now.AddDays(3), data.LastModifiedBy, data.LastModifiedAgent); data.SetCO( "model.CO", data.LastModifiedBy, data.LastModifiedAgent); data.SetCODate( DateTimeOffset.Now.AddDays(3), data.LastModifiedBy, data.LastModifiedAgent); data.SetCOTP("model.COTP", data.LastModifiedBy, data.LastModifiedAgent); data.SetCOTPDate( DateTimeOffset.Now.AddDays(3), data.LastModifiedBy, data.LastModifiedAgent); data.SetDescription("model.Description", data.LastModifiedBy, data.LastModifiedAgent); data.SetCPrice( "cprice", data.LastModifiedBy, data.LastModifiedAgent); data.SetMemo("model.Memo", data.LastModifiedBy, data.LastModifiedAgent); data.SetAmountToBePaid( 500, data.LastModifiedBy, data.LastModifiedAgent); data.SetTotalAmount(2, data.LastModifiedBy, data.LastModifiedAgent); data.SetConsigneeAddress("updated", data.LastModifiedBy, data.LastModifiedAgent); data.SetDeliverTo("updated", data.LastModifiedBy, data.LastModifiedAgent); data.Items.Add(new GarmentShippingInvoiceItemModel("ro", "scno", 1, "buyerbrandname", 1, 1, "comocode", "comoname", "comodesc", "comodesc", "comodesc", "comodesc", 1, "pcs", 10, 10, 100, "usd", 1, "unitcode", 3)); foreach (var item in data.Items) { item.SetPrice(1039, item.LastModifiedBy, item.LastModifiedAgent); item.SetComodityDesc("hahhahah", item.LastModifiedBy, item.LastModifiedAgent); item.SetDesc2("hahhahah", item.LastModifiedBy, item.LastModifiedAgent); item.SetDesc3("hahhahah", item.LastModifiedBy, item.LastModifiedAgent); item.SetDesc4("hahhahah", item.LastModifiedBy, item.LastModifiedAgent); item.SetCMTPrice(56000, item.LastModifiedBy, item.LastModifiedAgent); item.SetUomId(2, item.LastModifiedBy, item.LastModifiedAgent); item.SetUomUnit("sss", item.LastModifiedBy, item.LastModifiedAgent); } var ajdData = data.GarmentShippingInvoiceAdjustment.FirstOrDefault(); data.GarmentShippingInvoiceAdjustment.Add(new GarmentShippingInvoiceAdjustmentModel(data.Id,"ddd",1000, 1)); ajdData.SetAdjustmentDescription("dsds", ajdData.LastModifiedBy, ajdData.LastModifiedAgent); ajdData.SetAdjustmentValue( 10000 + ajdData.AdjustmentValue, ajdData.LastModifiedBy, ajdData.LastModifiedAgent); ajdData.SetAdditionalChargesId(1 + ajdData.AdditionalChargesId, ajdData.LastModifiedBy, ajdData.LastModifiedAgent); var unitData = data.GarmentShippingInvoiceUnit.FirstOrDefault(); data.GarmentShippingInvoiceUnit.Add(new GarmentShippingInvoiceUnitModel(1, "ddd",100, 1000)); unitData.SetUnitCode("dsdsasda", unitData.LastModifiedBy, ajdData.LastModifiedAgent); unitData.SetUnitId(unitData.UnitId+1, unitData.LastModifiedBy, ajdData.LastModifiedAgent); unitData.SetQuantityPercentage(unitData.QuantityPercentage+1, unitData.LastModifiedBy, ajdData.LastModifiedAgent); unitData.SetAmountPercentage(unitData.AmountPercentage + 1, unitData.LastModifiedBy, ajdData.LastModifiedAgent); var result = await repo2.UpdateAsync(data.Id, data); Assert.NotEqual(0, result); } [Fact] public async Task Should_Success_Update_2() { string testName = GetCurrentMethod(); var dbContext = DbContext(testName); var serviceProvider = GetServiceProviderMock(dbContext).Object; GarmentPackingListRepository repoPL = new GarmentPackingListRepository(dbContext, serviceProvider); GarmentPackingListDataUtil utilPL = new GarmentPackingListDataUtil(repoPL); GarmentPackingListModel dataPL = utilPL.GetModel(); var dataPackingList = await repoPL.InsertAsync(dataPL); GarmentShippingInvoiceRepository repo = new GarmentShippingInvoiceRepository(dbContext, serviceProvider); GarmentShippingInvoiceRepository repo2 = new GarmentShippingInvoiceRepository(dbContext, serviceProvider); GarmentShippingInvoiceDataUtil invoiceDataUtil = new GarmentShippingInvoiceDataUtil(repo, utilPL); GarmentShippingInvoiceModel oldModel = invoiceDataUtil.GetModels(); oldModel.PackingListId = dataPL.Id; await repo.InsertAsync(oldModel); var model = repo.ReadAll().FirstOrDefault(); var data = await repo.ReadByIdAsync(model.Id); var Newdata = invoiceDataUtil.CopyModel(oldModel); var unitData = Newdata.GarmentShippingInvoiceUnit.FirstOrDefault(); Newdata.GarmentShippingInvoiceUnit.Remove(unitData); var result = await repo2.UpdateAsync(data.Id, Newdata); Assert.NotEqual(0, result); } } }
54.371681
225
0.776693
[ "MIT" ]
kuswandanu-moonlay/com-danliris-service-packing-inventory
src/Com.Danliris.Service.Packing.Inventory.Test/Repositories/GarmentShipping/GarmentShippingInvoice/GarmentShippingInvoiceRepositoryTest.cs
12,290
C#
using System; using System.Globalization; using Microsoft.AspNetCore.Authentication.OAuth; using Microsoft.AspNetCore.Authentication.Twitter; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Identity.EntityFrameworkCore; using Microsoft.AspNetCore.Localization; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Caching.Memory; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using MusicStore.Components; using MusicStore.Mocks.Common; using MusicStore.Mocks.Facebook; using MusicStore.Mocks.Google; using MusicStore.Mocks.MicrosoftAccount; using MusicStore.Mocks.Twitter; using MusicStore.Models; namespace MusicStore { public class StartupSocialTesting { public StartupSocialTesting(IHostingEnvironment hostingEnvironment) { //Below code demonstrates usage of multiple configuration sources. For instance a setting say 'setting1' is found in both the registered sources, //then the later source will win. By this way a Local config can be overridden by a different setting while deployed remotely. var builder = new ConfigurationBuilder() .SetBasePath(hostingEnvironment.ContentRootPath) .AddJsonFile("config.json") .AddEnvironmentVariables() //All environment variables in the process's context flow in as configuration values. .AddJsonFile("configoverride.json", optional: true); // Used to override some configuration parameters that cannot be overridden by environment. Configuration = builder.Build(); } public IConfiguration Configuration { get; private set; } public void ConfigureServices(IServiceCollection services) { services.Configure<AppSettings>(Configuration.GetSection("AppSettings")); // Add EF services to the services container services.AddMusicStoreDbContext(Configuration); // Add Identity services to the services container services.AddIdentity<ApplicationUser, IdentityRole>() .AddEntityFrameworkStores<MusicStoreContext>() .AddDefaultTokenProviders(); services.ConfigureApplicationCookie(options => options.AccessDeniedPath = "/Home/AccessDenied"); services.AddCors(options => { options.AddPolicy("CorsPolicy", builder => { builder.WithOrigins("http://example.com"); }); }); // Add MVC services to the services container services.AddMvc(); //Add InMemoryCache services.AddSingleton<IMemoryCache, MemoryCache>(); // Add session related services. services.AddMemoryCache(); services.AddDistributedMemoryCache(); services.AddSession(); // Add the system clock service services.AddSingleton<ISystemClock, SystemClock>(); // Configure Auth services.AddAuthorization(options => { options.AddPolicy("ManageStore", new AuthorizationPolicyBuilder().RequireClaim("ManageStore", "Allowed").Build()); }); services.AddAuthentication() .AddFacebook(options => { options.AppId = "[AppId]"; options.AppSecret = "[AppSecret]"; options.Events = new OAuthEvents() { OnCreatingTicket = TestFacebookEvents.OnCreatingTicket, OnTicketReceived = TestFacebookEvents.OnTicketReceived, OnRedirectToAuthorizationEndpoint = TestFacebookEvents.RedirectToAuthorizationEndpoint }; options.BackchannelHttpHandler = new FacebookMockBackChannelHttpHandler(); options.StateDataFormat = new CustomStateDataFormat(); options.Scope.Add("email"); options.Scope.Add("read_friendlists"); options.Scope.Add("user_checkins"); }).AddGoogle(options => { options.ClientId = "[ClientId]"; options.ClientSecret = "[ClientSecret]"; options.AccessType = "offline"; options.Events = new OAuthEvents() { OnCreatingTicket = TestGoogleEvents.OnCreatingTicket, OnTicketReceived = TestGoogleEvents.OnTicketReceived, OnRedirectToAuthorizationEndpoint = TestGoogleEvents.RedirectToAuthorizationEndpoint }; options.StateDataFormat = new CustomStateDataFormat(); options.BackchannelHttpHandler = new GoogleMockBackChannelHttpHandler(); }).AddTwitter(options => { options.ConsumerKey = "[ConsumerKey]"; options.ConsumerSecret = "[ConsumerSecret]"; options.Events = new TwitterEvents() { OnCreatingTicket = TestTwitterEvents.OnCreatingTicket, OnTicketReceived = TestTwitterEvents.OnTicketReceived, OnRedirectToAuthorizationEndpoint = TestTwitterEvents.RedirectToAuthorizationEndpoint }; options.StateDataFormat = new CustomTwitterStateDataFormat(); options.BackchannelHttpHandler = new TwitterMockBackChannelHttpHandler(); }).AddMicrosoftAccount(options => { options.ClientId = "[ClientId]"; options.ClientSecret = "[ClientSecret]"; options.Events = new OAuthEvents() { OnCreatingTicket = TestMicrosoftAccountEvents.OnCreatingTicket, OnTicketReceived = TestMicrosoftAccountEvents.OnTicketReceived, OnRedirectToAuthorizationEndpoint = TestMicrosoftAccountEvents.RedirectToAuthorizationEndpoint }; options.BackchannelHttpHandler = new MicrosoftAccountMockBackChannelHandler(); options.StateDataFormat = new CustomStateDataFormat(); options.Scope.Add("wl.basic"); options.Scope.Add("wl.signin"); }); } public void Configure(IApplicationBuilder app) { // force the en-US culture, so that the app behaves the same even on machines with different default culture var supportedCultures = new[] { new CultureInfo("en-US") }; app.UseRequestLocalization(new RequestLocalizationOptions { DefaultRequestCulture = new RequestCulture("en-US"), SupportedCultures = supportedCultures, SupportedUICultures = supportedCultures }); app.UseStatusCodePagesWithRedirects("~/Home/StatusCodePage"); // Error page middleware displays a nice formatted HTML page for any unhandled exceptions in the request pipeline. // Note: Not recommended for production. app.UseDeveloperExceptionPage(); app.UseDatabaseErrorPage(); // Configure Session. app.UseSession(); // Add static files to the request pipeline app.UseStaticFiles(); // Add cookie-based authentication to the request pipeline app.UseAuthentication(); // Add MVC to the request pipeline app.UseMvc(routes => { routes.MapRoute( name: "areaRoute", template: "{area:exists}/{controller}/{action}", defaults: new { action = "Index" }); routes.MapRoute( name: "default", template: "{controller}/{action}/{id?}", defaults: new { controller = "Home", action = "Index" }); routes.MapRoute( name: "api", template: "{controller}/{id?}"); }); //Populates the MusicStore sample data SampleData.InitializeMusicStoreDatabaseAsync(app.ApplicationServices).Wait(); } } }
43.035354
160
0.617533
[ "Apache-2.0" ]
lvarin/s2i-aspnet-musicstore-ex
samples/MusicStore/ForTesting/Mocks/StartupSocialTesting.cs
8,521
C#
using System; using System.Collections; namespace MelonLoader { public class MelonCoroutines { /// <summary> /// Start a new coroutine.<br /> /// Coroutines are called at the end of the game Update loops. /// </summary> /// <param name="routine">The target routine</param> /// <returns>An object that can be passed to Stop to stop this coroutine</returns> public static object Start(IEnumerator routine) { if (SupportModule.supportModule == null) throw new NotSupportedException("Support module must be initialized before starting coroutines"); return SupportModule.supportModule.StartCoroutine(routine); } /// <summary> /// Stop a currently running coroutine /// </summary> /// <param name="coroutineToken">The coroutine to stop</param> public static void Stop(object coroutineToken) { if (SupportModule.supportModule == null) throw new NotSupportedException("Support module must be initialized before starting coroutines"); SupportModule.supportModule.StopCoroutine(coroutineToken); } [Obsolete("Use version with IEnumerator parameter", true)] public static void Start<T>(T routine) => Start((IEnumerator) routine); } }
38.027778
113
0.631848
[ "Apache-2.0", "MIT" ]
Aides359/MelonLoader
MelonLoader.ModHandler/MelonCoroutines.cs
1,369
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("MiniLanguage")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("MiniLanguage")] [assembly: AssemblyCopyright("Copyright © 2021")] [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("6d264531-f0b6-4258-86b8-0d46c7446579")] // 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.621622
84
0.747845
[ "MIT" ]
Maxization/MiniLanguage
MiniLanguage/MiniLanguage/Properties/AssemblyInfo.cs
1,395
C#
#region Header // Vorspire _,-'/-'/ Handler.cs // . __,-; ,'( '/ // \. `-.__`-._`:_,-._ _ , . `` // `:-._,------' ` _,`--` -: `_ , ` ,' : // `---..__,,--' (C) 2018 ` -'. -' // # Vita-Nex [http://core.vita-nex.com] # // {o)xxx|===============- # -===============|xxx(o} // # The MIT License (MIT) # #endregion #region References using System; #endregion namespace VitaNex.Web { public class WebAPIHandler { public string Uri { get; private set; } public Action<WebAPIContext> Handler { get; set; } public WebAPIHandler(string uri, Action<WebAPIContext> handler) { Uri = uri; Handler = handler; } public override int GetHashCode() { return Uri.GetHashCode(); } } }
22.971429
66
0.46393
[ "MIT" ]
Vita-Nex/Core
Services/WebAPI/Objects/Handler.cs
804
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 identitystore-2020-06-15.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.IdentityStore.Model { /// <summary> /// This is the response object from the DescribeGroup operation. /// </summary> public partial class DescribeGroupResponse : AmazonWebServiceResponse { private string _displayName; private string _groupId; /// <summary> /// Gets and sets the property DisplayName. /// <para> /// Contains the group’s display name value. The length limit is 1024 characters. This /// value can consist of letters, accented characters, symbols, numbers, punctuation, /// tab, new line, carriage return, space and non breaking space in this attribute. The /// characters “&lt;&gt;;:%” are excluded. This value is specified at the time the group /// is created and stored as an attribute of the group object in the identity store. /// </para> /// </summary> [AWSProperty(Required=true, Min=1, Max=1024)] public string DisplayName { get { return this._displayName; } set { this._displayName = value; } } // Check to see if DisplayName property is set internal bool IsSetDisplayName() { return this._displayName != null; } /// <summary> /// Gets and sets the property GroupId. /// <para> /// The identifier for a group in the identity store. /// </para> /// </summary> [AWSProperty(Required=true, Min=1, Max=47)] public string GroupId { get { return this._groupId; } set { this._groupId = value; } } // Check to see if GroupId property is set internal bool IsSetGroupId() { return this._groupId != null; } } }
33.939024
112
0.614086
[ "Apache-2.0" ]
philasmar/aws-sdk-net
sdk/src/Services/IdentityStore/Generated/Model/DescribeGroupResponse.cs
2,789
C#
using System; using System.IO; using System.Linq; using System.Security.Cryptography; namespace SRTPluginProviderDMC4SE { /// <summary> /// SHA256 hashes for the DMC4SE game executables. /// </summary> public static class GameHashes { private static readonly byte[] DevilMayCry4SpecialEditionWW_20190328_1 = new byte[32] { 0x64, 0x2D, 0x11, 0xB9, 0x4F, 0xC8, 0x22, 0x6D, 0x0A, 0x90, 0x63, 0x01, 0xC0, 0xD4, 0x28, 0x36, 0x26, 0x3F, 0xC8, 0x60, 0xC7, 0x51, 0x50, 0x22, 0x72, 0xBF, 0xAC, 0xC7, 0xFE, 0xE5, 0x1E, 0xFC }; private static readonly byte[] DevilMayCry4SpecialEditionWW_20210727_1 = new byte[32] { 0xED, 0x63, 0xFB, 0xF6, 0x01, 0x84, 0x21, 0x9C, 0x45, 0x5C, 0x38, 0x7B, 0xEB, 0x54, 0x92, 0x69, 0x4D, 0x60, 0xC2, 0x0E, 0xEE, 0x9C, 0xF6, 0x4C, 0xF9, 0xEA, 0xAD, 0x9D, 0x64, 0x79, 0x9A, 0x46 }; public static GameVersion DetectVersion(string filePath) { byte[] checksum; using (SHA256 hashFunc = SHA256.Create()) using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete)) checksum = hashFunc.ComputeHash(fs); if (checksum.SequenceEqual(DevilMayCry4SpecialEditionWW_20190328_1)) { Console.WriteLine("Old Patch"); return GameVersion.DevilMayCry4SpecialEditionWW_20190328_1; } else if (checksum.SequenceEqual(DevilMayCry4SpecialEditionWW_20210727_1)) { Console.WriteLine("Latest Release"); return GameVersion.DevilMayCry4SpecialEditionWW_20210727_1; } Console.WriteLine("Unknown Version"); return GameVersion.Unknown; } } }
45.333333
289
0.650452
[ "MIT" ]
Mysterion06/SRTPluginProviderDMC4SE
SRTPluginProviderDMC4SE/GameHashes.cs
1,770
C#
using System; namespace R5T.Visigothia.Base.Construction { class Program { static void Main(string[] args) { Console.WriteLine("Hello World!"); } } }
16.307692
47
0.523585
[ "MIT" ]
MinexAutomation/R5T.Visigothia.Base
source/R5T.Visigothia.Base.Construction/Code/Program.cs
214
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("Azure.NLog.Query")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Azure.NLog.Query")] [assembly: AssemblyCopyright("Copyright © 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("89fc7955-3ce5-4ad4-b638-a721938cbad6")] // 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.972973
84
0.743772
[ "Apache-2.0" ]
caseyjmorris/NLogAzureTableStorageViewer
Azure.NLog.Query/Properties/AssemblyInfo.cs
1,408
C#
using CodeGenHero.Core; using CodeGenHero.Template.Models.Interfaces; using System; using System.Collections.Generic; namespace CodeGenHero.Template.Models { public class TemplateAssembly : BaseMarshalByRefObject, ITemplateAssembly { public TemplateAssembly(TemplateAssemblyAttribute templateAssemblyAttribute, string importBundleIdentifier = null) { Templates = new List<ITemplate>(); TemplateAssemblyAttribute = templateAssemblyAttribute; ImportBundleIdentifier = importBundleIdentifier; } public string Author { get { return TemplateAssemblyAttribute?.Author; } } public string Description { get { return TemplateAssemblyAttribute?.Description; } } public Guid Id { get { return TemplateAssemblyAttribute == null ? Guid.Empty : TemplateAssemblyAttribute.Id; } } public string ImportBundleIdentifier { get; set; } public string Name { get { return TemplateAssemblyAttribute?.Name; } } public string RequiredMetadataSource { get { return TemplateAssemblyAttribute?.RequiredMetadataSource; } } public TemplateAssemblyAttribute TemplateAssemblyAttribute { get; private set; } public IList<ITemplate> Templates { get; private set; } public string Version { get { return TemplateAssemblyAttribute?.Version; } } public void Dispose() { } } }
22.951807
122
0.528609
[ "MIT" ]
MSCTek/CodeGenHero
src/CodeGenHero.Template/Models/TemplateAssembly.cs
1,907
C#
using System.Management.Automation; using PnP.PowerShell.CmdletHelpAttributes; using System; using PnP.PowerShell.Commands.Properties; namespace PnP.PowerShell.Commands.Base { [Cmdlet(VerbsCommon.Get, "PnPContext")] [CmdletHelp("Returns the current context", "Returns a Client Side Object Model context", Category = CmdletHelpCategory.Base, OutputType = typeof(Microsoft.SharePoint.Client.ClientContext), OutputTypeLink = "https://msdn.microsoft.com/en-us/library/microsoft.sharepoint.client.clientcontext.aspx")] [CmdletExample( Code = @"PS:> $ctx = Get-PnPContext", Remarks = @"This will put the current context in the $ctx variable.", SortOrder = 1)] [CmdletExample( Code = @"PS:> Connect-PnPOnline -Url $siteAurl -Credentials $credentials PS:> $ctx = Get-PnPContext PS:> Get-PnPList # returns the lists from site specified with $siteAurl PS:> Connect-PnPOnline -Url $siteBurl -Credentials $credentials PS:> Get-PnPList # returns the lists from the site specified with $siteBurl PS:> Set-PnPContext -Context $ctx # switch back to site A PS:> Get-PnPList # returns the lists from site A", SortOrder = 2)] public class GetSPOContext : PSCmdlet { protected override void BeginProcessing() { base.BeginProcessing(); if (PnPConnection.CurrentConnection == null) { throw new InvalidOperationException(Resources.NoSharePointConnection); } if (PnPConnection.CurrentConnection.Context == null) { throw new InvalidOperationException(Resources.NoSharePointConnection); } } protected override void ProcessRecord() { WriteObject(PnPConnection.CurrentConnection.Context); } } }
37.714286
116
0.667749
[ "MIT" ]
FPotrafky/PnP-PowerShell
Commands/Base/GetContext.cs
1,850
C#
namespace HotelSystem.Web.Areas.Administration.Controllers { using System; using System.Linq; using System.Web.Mvc; using HotelSystem.Common; using HotelSystem.Services.Data.Contracts; using HotelSystem.Web.Areas.Administration.ViewModels.Bookings; using HotelSystem.Web.Infrastructure.Mapping; public class BookingsController : AdminController { private IBookingsService bookings; private IHotelRoomsService hotelRooms; public BookingsController(IBookingsService bookingsService, IHotelRoomsService hotelRoomsService) { this.bookings = bookingsService; this.hotelRooms = hotelRoomsService; } public ActionResult Index() { var allBookings = this.bookings .GetAllWithDeleted() .OrderBy(h => h.Id) .To<BookingViewModel>(); return this.View(allBookings); } [HttpGet] public ActionResult Create() { return this.View(); } [HttpPost] [ValidateAntiForgeryToken] public ActionResult Create(BookingInputModel model) { if (!this.ModelState.IsValid) { return this.View(model); } var booking = this.Mapper.Map<HotelSystem.Data.Models.Booking>(model); var freeRoom = this.hotelRooms.FreeHotelRoom(model.HotelName, model.RoomType); if (freeRoom == null) { this.TempData["Error"] = "There's no available rooms!"; return this.View(model); } booking.HotelRoomsId = freeRoom.Id; this.bookings.CreateBooking(booking); freeRoom.Booked = true; this.hotelRooms.Update(); this.TempData["Success"] = "Booking was successful!"; return this.RedirectToAction("Index"); } [HttpGet] public ActionResult Edit(int id = 1) { var booking = this.bookings.GetById(id); var bookingModel = this.Mapper.Map<BookingEditModel>(booking); return this.View("Edit", bookingModel); } [HttpPost] [ValidateAntiForgeryToken] public ActionResult Edit(BookingEditModel model) { if (!this.ModelState.IsValid) { this.ViewBag.Error = ModelValidationErrors.InvalidModel; return this.View(model); } var booking = this.bookings.GetById(model.Id); if (booking == null) { this.TempData["Error"] = ModelValidationErrors.EditDeletedEntity; return this.RedirectToAction("Index"); } booking.BookedFrom = model.BookedFrom; booking.BookedTo = model.BookedTo; this.bookings.Update(); this.TempData["Success"] = "Booking was successful edited!"; return this.RedirectToAction("Index"); } public ActionResult Delete(int id) { try { this.bookings.Delete(id); } catch (Exception e) { this.TempData["Error"] = e.Message; return this.RedirectToAction("Index"); } this.TempData["Success"] = "Deleted"; return this.RedirectToAction("Index"); } } }
30.474576
106
0.538932
[ "MIT" ]
iwelina-popova/HotelSystem
Source/Web/HotelSystem.Web/Areas/Administration/Controllers/BookingsController.cs
3,598
C#
using Common.ApplicationCommands; using MovieHub.MediaPlayerElement.Interfaces; using MovieHub.MediaPlayerElement.Service; using System; using System.Windows; using System.Windows.Controls; using System.Windows.Input; using MovieHub.MediaPlayerElement.ViewModel; using System.Windows.Threading; using Movies.Models.Interfaces; using Movies.Models.Model; using System.Windows.Data; using MovieHub.MediaPlayerElement.Models; using Movies.Enums; using System.Collections.Generic; using MovieHub.MediaPlayerElement.Util; using System.Windows.Media; using System.Dynamic; using Common.Util; namespace MovieHub.MediaPlayerElement { public enum WindowFullScreenState { FullScreen, Normal }; public enum MediaPlayerViewType { FullMediaPanel, MiniMediaPanel }; [TemplatePart(Name = "MediaControlRegion", Type = typeof(ContentControl))] public sealed class MediaPlayerElement : Control, IMediaPlayerElement { private ContentControl _mediaControlRegion; private ContentControl _mediaelementregion; private ContentControl _playlistregion; private dynamic _savedSettings; private IMediaPlayabeLastSeen _playlastableLastSeen; private IPlayable _currentstreamingitem; private bool _hasInitialised; private bool _isDragging; internal bool _isrewindorfastforward; private bool _awaitHostToRender; private bool _canAnimateControl = true; private bool _isPlaylistVisible = false; private bool _allowmediaAutodispose = true; private MovieControl _savedSecondaryControl = null; internal bool _allowMediaSizeEventExecute = true; private DispatcherTimer _controlAnimationTimer; private static bool IscheckingForRepeating = false; private static MediaPlayerElement _current; internal IPlayable CurrentStreamingitem { get { return _currentstreamingitem; } set { if (_currentstreamingitem != null) _currentstreamingitem.IsActive = false; _currentstreamingitem = value; if(CurrentlyStreamingChangedEvent != null) CurrentlyStreamingChangedEvent.Invoke(value); } } internal IMediaPlayabeLastSeen PlayableLastSeen { get { return _playlastableLastSeen; } set { PlayableLastSeenSaveAction(); _playlastableLastSeen = value; } } internal delegate void CurrentlyStreamingHandler(IPlayable playable); internal CurrentlyStreamingHandler CurrentlyStreamingChangedEvent { get; set; } internal MediaMenu _mediaMenu; internal ContentControl _contentdockregion; /// <summary> /// Set to true if you want MediaPlayer to dispose on Unloaded event /// Set to false to manually dispose MediaPlayer resources. /// </summary> public bool AllowMediaPlayerAutoDispose { get { return _allowmediaAutodispose; } set { _allowmediaAutodispose = value; } } private bool canescapekeyclosemedia; public bool CanEscapeKeyCloseMedia { get { return canescapekeyclosemedia; } set { canescapekeyclosemedia = value; } } static MediaPlayerElement() { DefaultStyleKeyProperty.OverrideMetadata(typeof(MediaPlayerElement), new FrameworkPropertyMetadata(typeof(MediaPlayerElement))); RegisterMediaPlayerServiceEvent(); RegisterControlCommands(); } #region Dependency Properties public MediaPlayerViewType MediaPlayerViewType { get { return (MediaPlayerViewType)GetValue(MediaPlayerViewTypeProperty); } set { SetValue(MediaPlayerViewTypeProperty, value); } } // Using a DependencyProperty as the backing store for MediaPlayerViewType. This enables animation, styling, binding, etc... public static readonly DependencyProperty MediaPlayerViewTypeProperty = DependencyProperty.Register("MediaPlayerViewType", typeof(MediaPlayerViewType), typeof(MediaPlayerElement), new PropertyMetadata(MediaPlayerViewType.FullMediaPanel)); public Stretch MediaStretch { get { return (Stretch)GetValue(MediaStretchProperty); } set { SetValue(MediaStretchProperty, value); } } // Using a DependencyProperty as the backing store for MediaStretch. This enables animation, styling, binding, etc... public static readonly DependencyProperty MediaStretchProperty = DependencyProperty.Register("MediaStretch", typeof(Stretch), typeof(MediaPlayerElement), new PropertyMetadata(Stretch.Uniform,OnStretchPropertyChanged)); private static void OnStretchPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { MediaPlayerElement mediaplayerelement = d as MediaPlayerElement; if (mediaplayerelement != null) { mediaplayerelement.SetStretchProperty((Stretch)e.NewValue); } } public bool IsMediaContextMenuEnabled { get { return (bool)GetValue(IsMediaContextEnabledProperty); } set { SetValue(IsMediaContextEnabledProperty, value); } } // Using a DependencyProperty as the backing store for IsMediaContextEnabled. This enables animation, styling, binding, etc... public static readonly DependencyProperty IsMediaContextEnabledProperty = DependencyProperty.Register("IsMediaContextMenuEnabled", typeof(bool), typeof(MediaPlayerElement), new PropertyMetadata(true)); public bool AllowMovieControlAnimation { get { return (bool)GetValue(AllowMovieControlAnimationProperty); } set { SetValue(AllowMovieControlAnimationProperty, value); } } // Using a DependencyProperty as the backing store for AllowMovieControlAnimation. This enables animation, styling, binding, etc... public static readonly DependencyProperty AllowMovieControlAnimationProperty = DependencyProperty.Register("AllowMovieControlAnimation", typeof(bool), typeof(MediaPlayerElement), new PropertyMetadata(false, OnAllowMovieControlAnimationChanged)); private static void OnAllowMovieControlAnimationChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { MediaPlayerElement mediaplayerelement = d as MediaPlayerElement; if (mediaplayerelement != null) { mediaplayerelement.InitializeAnimationTimer((bool)e.NewValue); } } public bool CanMediaFastForwardOrRewind { get { return (bool)GetValue(CanMediaFastForwardOrRewindProperty); } set { SetValue(CanMediaFastForwardOrRewindProperty, value); } } // Using a DependencyProperty as the backing store for CanMediaFastForwardOrRewind. This enables animation, styling, binding, etc... public static readonly DependencyProperty CanMediaFastForwardOrRewindProperty = DependencyProperty.Register("CanMediaFastForwardOrRewind", typeof(bool), typeof(MediaPlayerElement), new PropertyMetadata(true)); public string MediaTitle { get { return (string)GetValue(MediaTitleProperty); } private set { SetValue(MediaTitleProperty, value); } } // Using a DependencyProperty as the backing store for MediaTitle. This enables animation, styling, binding, etc... public static readonly DependencyProperty MediaTitleProperty = DependencyProperty.Register("MediaTitle", typeof(string), typeof(MediaPlayerElement), new PropertyMetadata("-No title-")); public bool IsPlaying { get { return (bool)GetValue(IsPlayingProperty); } private set { SetValue(IsPlayingProperty, value); } } // Using a DependencyProperty as the backing store for IsPlaying. This enables animation, styling, binding, etc... public static readonly DependencyProperty IsPlayingProperty = DependencyProperty.Register("IsPlaying", typeof(bool), typeof(MediaPlayerElement), new PropertyMetadata(false)); public WindowFullScreenState WindowFullScreenState { get { return (WindowFullScreenState)GetValue(WindowFullScreenStateProperty); } private set { SetValue(WindowFullScreenStateProperty, value); } } // Using a DependencyProperty as the backing store for WindowFullScreenState. This enables animation, styling, binding, etc... public static readonly DependencyProperty WindowFullScreenStateProperty = DependencyProperty.Register("WindowFullScreenState", typeof(WindowFullScreenState), typeof(MediaPlayerElement), new FrameworkPropertyMetadata() { DefaultValue = WindowFullScreenState.Normal}); public bool CanRenderControl { get { return (bool)GetValue(CanRenderControlProperty); } set { SetValue(CanRenderControlProperty, value); } } // Using a DependencyProperty as the backing store for CanRenderControl. This enables animation, styling, binding, etc... public static readonly DependencyProperty CanRenderControlProperty = DependencyProperty.Register("CanRenderControl", typeof(bool), typeof(MediaPlayerElement), new PropertyMetadata(true,OnCanrenderControlChanged)); private static void OnCanrenderControlChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { MediaPlayerElement mediaplayerelement = d as MediaPlayerElement; if (mediaplayerelement != null) { var newValue = (Boolean)e.NewValue; mediaplayerelement.AllowMovieControlAnimation = newValue; if (mediaplayerelement._mediaControlRegion == null) return; if (newValue) { mediaplayerelement._mediaControlRegion.Content = mediaplayerelement.MovieControl; return; } mediaplayerelement._mediaControlRegion.Content = null; } } public bool IsCloseButtonVisible { get { return (bool)GetValue(IsCloseButtonVisibleProperty); } set { SetValue(IsCloseButtonVisibleProperty, value); } } // Using a DependencyProperty as the backing store for IsFullScreenCloseButtonVisible. This enables animation, styling, binding, etc... public static readonly DependencyProperty IsCloseButtonVisibleProperty = DependencyProperty.Register("IsCloseButtonVisible", typeof(bool), typeof(MediaPlayerElement), new PropertyMetadata(false, OnIsCloseButtonVisibleChanged)); private static void OnIsCloseButtonVisibleChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { MediaPlayerElement mediaplayerelement = d as MediaPlayerElement; if (mediaplayerelement != null) { mediaplayerelement.MovieControl.MovieControlSettings.IsControlMediaCloseButtonEnabled = (bool)e.NewValue; } } public MoviesPlaylistManager PlaylistManager { get { return (MoviesPlaylistManager)GetValue(PlaylistManagerProperty); } private set { SetValue(PlaylistManagerProperty, value); } } // Using a DependencyProperty as the backing store for PlaylistManager. This enables animation, styling, binding, etc... public static readonly DependencyProperty PlaylistManagerProperty = DependencyProperty.Register("PlaylistManager", typeof(MoviesPlaylistManager), typeof(MediaPlayerElement), new PropertyMetadata(null, OnPlaylistManagerPropertyChanged)); private static void OnPlaylistManagerPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { MediaPlayerElement mediaplayerelement = d as MediaPlayerElement; if (mediaplayerelement != null) { if (mediaplayerelement.PlaylistManager != null) { mediaplayerelement.LoadPlaylistComponents(); } else { mediaplayerelement.UnLoadPlaylistComponents(); } } } public IMediaPlayerService MediaPlayerServices { get { return (IMediaPlayerService)GetValue(MediaPlayerServiceProperty); } private set { SetValue(MediaPlayerServiceProperty, value); } } // Using a DependencyProperty as the backing store for MyProperty. This enables animation, styling, binding, etc... public static readonly DependencyProperty MediaPlayerServiceProperty = DependencyProperty.Register("MediaPlayerService", typeof(IMediaPlayerService), typeof(MediaPlayerElement), new PropertyMetadata(null)); public MovieControl UseSecondaryControl { get { return (MovieControl)GetValue(UseSecondaryControlProperty); } set { SetValue(UseSecondaryControlProperty, value); } } // Using a DependencyProperty as the backing store for UseSecondaryControl. This enables animation, styling, binding, etc... public static readonly DependencyProperty UseSecondaryControlProperty = DependencyProperty.Register("UseSecondaryControl", typeof(MovieControl), typeof(MediaPlayerElement), new PropertyMetadata(null,OnSecondaryControlChanged)); private static void OnSecondaryControlChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { MediaPlayerElement mediaplayerelement = d as MediaPlayerElement; if (mediaplayerelement != null) { MovieControl movieControl = e.NewValue as MovieControl; if (e.NewValue != null) { mediaplayerelement.CanRenderControl = false; movieControl.InitializeMediaPlayerControl(mediaplayerelement); mediaplayerelement._savedSecondaryControl = movieControl; } bool shouldRender = false; if (movieControl == null) { movieControl = new MovieControl(mediaplayerelement); shouldRender = true; var oldcontrol = e.OldValue as MovieControl; if (oldcontrol != null) { oldcontrol.InitializeMediaPlayerControl(null,true); } movieControl.SetControlSettings(oldcontrol.MovieControlSettings); movieControl.MediaDetailProps = oldcontrol.MediaDetailProps; } movieControl.ApplyTemplate(); mediaplayerelement.MovieControl = movieControl; if (shouldRender) { mediaplayerelement.CanRenderControl = shouldRender; } } } public MovieControl MovieControl { get { return (MovieControl)GetValue(MovieControlProperty); } private set { SetValue(MovieControlProperty, value); } } public VolumeState VolumeState { get { return MovieControl.VolumeControl.VolumeState; } private set { MovieControl.VolumeControl.VolumeState = value; } } // Using a DependencyProperty as the backing store for MovieControl. This enables animation, styling, binding, etc... public static readonly DependencyProperty MovieControlProperty = DependencyProperty.Register("MovieControl", typeof(MovieControl), typeof(MediaPlayerElement), new PropertyMetadata(null)); #endregion #region Events /// <summary> /// OnMediaSizeChanged is a routed event. /// </summary> public static readonly RoutedEvent OnMediaSizeChangedEvent = EventManager.RegisterRoutedEvent( "OnMediaSizeChanged", RoutingStrategy.Bubble, typeof(EventHandler<MediaSizeChangedRoutedArgs>), typeof(MediaPlayerElement)); /// <summary> /// Raised On Media Size Changed. /// </summary> public event EventHandler<MediaSizeChangedRoutedArgs> OnMediaSizeChanged { add { AddHandler(OnMediaSizeChangedEvent, value); } remove { RemoveHandler(OnMediaSizeChangedEvent, value); } } /// <summary> /// OnFullScreenButtonToggle is a routed event. /// </summary> public static readonly RoutedEvent OnFullScreenButtonToggleEvent = EventManager.RegisterRoutedEvent( "OnFullScreenButtonToggle", RoutingStrategy.Bubble, typeof(EventHandler<WindowFullScreenRoutedEventArgs>), typeof(MediaPlayerElement)); /// <summary> /// Raised On FullScreen Button Toggled. /// </summary> public event EventHandler<WindowFullScreenRoutedEventArgs> OnFullScreenButtonToggle { add { AddHandler(OnFullScreenButtonToggleEvent, value); } remove { RemoveHandler(OnFullScreenButtonToggleEvent, value); } } /// <summary> /// OnMinimizedControlExecuted is a routed event. /// </summary> public static readonly RoutedEvent OnMinimizedControlExecutedEvent = EventManager.RegisterRoutedEvent( "OnMinimizedControlExecuted", RoutingStrategy.Bubble, typeof(EventHandler<MediaPlayerViewTypeRoutedEventArgs>), typeof(MediaPlayerElement)); /// <summary> /// Raised when Minimized Control button is executed /// </summary> public event EventHandler<MediaPlayerViewTypeRoutedEventArgs> OnMinimizedControlExecuted { add { AddHandler(OnMinimizedControlExecutedEvent, value); } remove { RemoveHandler(OnMinimizedControlExecutedEvent, value); } } /// <summary> /// SetWindowTopMostProperty is a routed event. /// </summary> public static readonly RoutedEvent SetWindowTopMostPropertyEvent = EventManager.RegisterRoutedEvent( "SetWindowTopMostProperty", RoutingStrategy.Bubble, typeof(RoutedEventHandler), typeof(MediaPlayerElement)); /// <summary> /// Raised when the topMost button is toggled /// </summary> public event RoutedEventHandler SetWindowTopMostProperty { add { AddHandler(SetWindowTopMostPropertyEvent, value); } remove { RemoveHandler(SetWindowTopMostPropertyEvent, value); } } /// <summary> /// OnMediaTitleChanged is a routed event. /// </summary> public static readonly RoutedEvent OnMediaTitleChangedEvent = EventManager.RegisterRoutedEvent( "OnMediaTitleChanged", RoutingStrategy.Bubble, typeof(RoutedEventHandler), typeof(MediaPlayerElement)); /// <summary> /// Raised On Media Title Changed /// </summary> public event RoutedEventHandler OnMediaTitleChanged { add { AddHandler(OnMediaTitleChangedEvent, value); } remove { RemoveHandler(OnMediaTitleChangedEvent, value); } } /// <summary> /// OnCloseWindowToggled is a routed event. /// </summary> public static readonly RoutedEvent OnCloseWindowToggledEvent = EventManager.RegisterRoutedEvent( "OnCloseWindowToggled", RoutingStrategy.Bubble, typeof(RoutedEventHandler), typeof(MediaPlayerElement)); /// <summary> /// Raised On closewindow button pressed /// </summary> public event RoutedEventHandler OnCloseWindowToggled { add { AddHandler(OnCloseWindowToggledEvent, value); } remove { RemoveHandler(OnCloseWindowToggledEvent, value); } } /// <summary> /// OnMediaInfoChanged is a routed event. /// </summary> public static readonly RoutedEvent OnMediaInfoChangedEvent = EventManager.RegisterRoutedEvent( "OnMediaInfoChanged", RoutingStrategy.Bubble, typeof(EventHandler<MediaInfoChangedEventArgs>), typeof(MediaPlayerElement)); /// <summary> /// Raised On Media Information Changed. /// </summary> public event EventHandler<MediaInfoChangedEventArgs> OnMediaInfoChanged { add { AddHandler(OnMediaInfoChangedEvent, value); } remove { RemoveHandler(OnMediaInfoChangedEvent, value); } } #endregion public MediaPlayerElement() { InitializeComponents(); _savedSettings = new ExpandoObject(); this.Unloaded += (s, e) => UnloadComponents(); } private void InitializeComponents() { MediaPlayerServices = new MediaPlayerService(); MovieControl = new MovieControl(this); AllowMovieControlAnimation = true; _current = this; } private void InitializeAnimationTimer(bool canAnimate) { if (canAnimate) { _controlAnimationTimer = new DispatcherTimer(DispatcherPriority.Background) { Interval = TimeSpan.FromMilliseconds(1200) }; _controlAnimationTimer.Tick += _controlAnimationTimer_Tick; return; } if (_controlAnimationTimer != null) { _controlAnimationTimer.Tick -= _controlAnimationTimer_Tick; _controlAnimationTimer = new DispatcherTimer(DispatcherPriority.Background); } } public override void OnApplyTemplate() { base.OnApplyTemplate(); _mediaControlRegion = (ContentControl)this.GetTemplateChild("MediaControlRegion"); _mediaelementregion = (ContentControl)this.GetTemplateChild("MediaElementRegion"); _contentdockregion = (ContentControl)this.GetTemplateChild("ContentDockRegion"); _playlistregion = (ContentControl)this.GetTemplateChild("PlaylistRegion"); var videoplayer = (MediaPlayerServices as MediaPlayerService).VideoPlayer; videoplayer.ApplyTemplate(); this._mediaelementregion.Content = videoplayer; //if (MovieControl.IsPlaylistToggleEnabled) // this.PlaylistRegion.Content = IPlaylistManager.GetPlaylistView(); MovieControl.ApplyTemplate(); if (CanRenderControl) { _mediaControlRegion.Content = MovieControl; } _hasInitialised = true; _awaitHostToRender = true; if (MediaPlayerViewType == MediaPlayerViewType.FullMediaPanel) { _mediaelementregion.MouseDoubleClick += _mediaelementregion_MouseDoubleClick; } //MediaPlayerUtil.ExecuteTimerAction(()=> HookUpEvents(),50); } protected override void OnKeyDown(KeyEventArgs e) { base.OnKeyDown(e); } protected override void OnKeyUp(KeyEventArgs e) { base.OnKeyUp(e); } protected override void OnMouseDown(MouseButtonEventArgs e) { base.OnMouseDown(e); e.Handled = this.MovieControl.Focus(); } //protected override void OnRender(DrawingContext drawingContext) //{ // base.OnRender(drawingContext); // this.Focus(); //} protected override void OnPreviewMouseRightButtonDown(MouseButtonEventArgs e) { base.OnPreviewMouseRightButtonDown(e); e.Handled = true; } protected override void OnMouseDoubleClick(MouseButtonEventArgs e) { base.OnMouseDoubleClick(e); } protected override void OnMouseMove(MouseEventArgs e) { base.OnMouseMove(e); if (e.Source == this) StartControlAnimation(); } #region Command Management #region MediaPlayerServices private static void RegisterMediaPlayerServiceEvent() { EventManager.RegisterClassHandler(typeof(MediaPlayerService), MediaPlayerService.OnMediaOpeningEvent, new RoutedEventHandler(MediaPlayerService_OnMediaOpeningEvent)); EventManager.RegisterClassHandler(typeof(MediaPlayerService), MediaPlayerService.OnMediaOpenedEvent, new RoutedEventHandler(MediaPlayerService_OnMediaOpenedEvent)); EventManager.RegisterClassHandler(typeof(MediaPlayerService), MediaPlayerService.OnMediaStoppedEvent, new RoutedEventHandler(MediaPlayerService_OnMediaStoppedEvent)); EventManager.RegisterClassHandler(typeof(MediaPlayerService), MediaPlayerService.OnStateChangedEvent, new RoutedEventHandler(MediaPlayerService_OnStateChangedEvent)); EventManager.RegisterClassHandler(typeof(MediaPlayerService), MediaPlayerService.OnTimeChangedEvent, new RoutedEventHandler(MediaPlayerService_OnTimeChangedEvent)); EventManager.RegisterClassHandler(typeof(MediaPlayerService), MediaPlayerService.EncounteredErrorEvent, new RoutedEventHandler(MediaPlayerService_EncounteredErrorEvent)); EventManager.RegisterClassHandler(typeof(MediaPlayerService), MediaPlayerService.EndReachedEvent, new RoutedEventHandler(MediaPlayerService_EndReachedEvent)); EventManager.RegisterClassHandler(typeof(MediaPlayerService), MediaPlayerService.BufferingEvent, new EventHandler<MediaBufferingEventArgs>(MediaPlayerService_BufferingEvent)); EventManager.RegisterClassHandler(typeof(MediaPlayerService), MediaPlayerService.OnMediaInfoChangedEvent, new EventHandler<MediaInfoChangedEventArgs>(MediaPlayerService_OnMediaInfoChangedEvent)); } private static void MediaPlayerService_OnMediaInfoChangedEvent(object sender, MediaInfoChangedEventArgs e) { if(_current !=null) _current.Dispatcher.BeginInvoke((Action)(() => _current.RaiseEvent(new MediaInfoChangedEventArgs(OnMediaInfoChangedEvent, e.Source, e.MediaInformation)))); } private static void MediaPlayerService_BufferingEvent(object sender, MediaBufferingEventArgs e) { if (_current != null && _current.IsLoaded) _current.MediaPlayerService_Buffering(e); } private static void MediaPlayerService_OnMediaStoppedEvent(object sender, RoutedEventArgs e) { if (_current != null && _current.IsLoaded) _current.MediaPlayerService_OnMediaStopped(); } private static void MediaPlayerService_OnStateChangedEvent(object sender, RoutedEventArgs e) { if(_current != null && _current.IsLoaded) _current.MediaPlayerService_OnStateChanged(); } private static void MediaPlayerService_OnTimeChangedEvent(object sender, RoutedEventArgs e) { if (_current != null && _current.IsLoaded) _current.MediaPlayerService_OnTimeChanged(); } private static void MediaPlayerService_EncounteredErrorEvent(object sender, RoutedEventArgs e) { if (_current != null && _current.IsLoaded) _current.MediaPlayerService_EncounteredError(); } private static void MediaPlayerService_EndReachedEvent(object sender, RoutedEventArgs e) { if (_current != null && _current.IsLoaded) _current.MediaPlayerService_EndReached(); } private static void MediaPlayerService_OnMediaOpenedEvent(object sender, RoutedEventArgs e) { if (_current != null && _current.IsLoaded) _current.MediaPlayerService_OnMediaOpened(); } private static void MediaPlayerService_OnMediaOpeningEvent(object sender, RoutedEventArgs e) { if (_current != null && _current.IsLoaded) _current.MediaPlayerService_OnMediaOpening(); } private void MediaPlayerService_Buffering(MediaBufferingEventArgs e) { SetMovieBoardText(string.Format("Buffering {0} %", e.NewCache)); if (e.NewCache == 100) SetMovieBoardText(string.Format("Playing - {0} ", CurrentStreamingitem.MediaTitle)); } private void MediaPlayerService_EndReached() { OnMediaFinishedAction(); } private void MediaPlayerService_EncounteredError() { OnStopAction(); } private void MediaPlayerService_OnTimeChanged() { TimeChangeAction(); } private void MediaPlayerService_OnStateChanged() { SetMovieBoardText(string.Format("{0} - {1}", MediaPlayerServices.State, CurrentStreamingitem.MediaTitle)); IsPlaying = MediaPlayerServices.State == MovieMediaState.Playing ? true : false; if (IsPlaying) StartControlAnimation(); else ResetControlAnimation(); } private void MediaPlayerService_OnMediaStopped() { OnStopAction(); } private void MediaPlayerService_OnMediaOpened() { SetMediaControlDetails(); if (_mediaMenu != null) _mediaMenu.Dispose(); CurrentStreamingitem.IsActive = true; IsPlaying = true; StartControlAnimation(); if (_allowMediaSizeEventExecute) MediaPlayerElementRaiseEvent(new MediaSizeChangedRoutedArgs(OnMediaSizeChangedEvent, this, MediaPlayerServices.PixelHeight, MediaPlayerServices.PixelWidth)); this.MovieControl.MediaPlayerElementNotifyLastSeen(PlayableLastSeen); } private void MediaPlayerService_OnMediaOpening() { SetMovieBoardText(string.Format("Opening - {0}", CurrentStreamingitem.MediaTitle)); } #endregion private static void RegisterCommandBings(Type type, ICommand command, CommandBinding commandBinding, params InputGesture[] inputBinding) { CommandManager.RegisterClassCommandBinding(type, commandBinding); if (inputBinding.Length > 0) { foreach (var ipbing in inputBinding) { CommandManager.RegisterClassInputBinding(type, new InputBinding(command, ipbing)); } } } private static void RegisterControlCommands() { //Each Control shud have the commands } #endregion internal void HookUpEvents() { _mediaMenu = new MediaMenu(this); HookUpControllerEvents(); // _hasRegisteredEvents = true; } private void HookUpControllerEvents() { MovieControl.MouseEnter -= MovieControl_MouseEnter; MovieControl.MouseLeave -= MovieControl_MouseLeave; MovieControl.MouseEnter += MovieControl_MouseEnter; MovieControl.MouseLeave += MovieControl_MouseLeave; if (MovieControl.MovieControlSettings.IsMediaSliderEnabled && MovieControl.MediaSlider != null) { MovieControl.MediaSlider.ThumbDragStarted -= MediaSlider_ThumbDragStarted; MovieControl.MediaSlider.ThumbDragCompleted -= MediaSlider_ThumbDragCompleted; MovieControl.MediaSlider.ThumbDragStarted += MediaSlider_ThumbDragStarted; MovieControl.MediaSlider.ThumbDragCompleted += MediaSlider_ThumbDragCompleted; } } private void MovieControl_MouseLeave(object sender, MouseEventArgs e) { _canAnimateControl = true; } private void MovieControl_MouseEnter(object sender, MouseEventArgs e) { _canAnimateControl = false; } private void _controlAnimationTimer_Tick(object sender, EventArgs e) { if (!IsPlaying) { _controlAnimationTimer.Stop(); return; } if ( _canAnimateControl && !_isPlaylistVisible) { _controlAnimationTimer.Stop(); HideControl(); } else if (!_canAnimateControl) { this._controlAnimationTimer.Stop(); } } private void MediaSlider_ThumbDragCompleted(object sender, System.Windows.Controls.Primitives.DragCompletedEventArgs e) { //start animation MediaPlayerServices.CurrentTimer = TimeSpan.FromSeconds(MovieControl.MediaSlider.Value); _isDragging = false; } private void MediaSlider_ThumbDragStarted(object sender, System.Windows.Controls.Primitives.DragStartedEventArgs e) { _isDragging = true; //stop animation } private void _mediaelementregion_MouseDoubleClick(object sender, MouseButtonEventArgs e) { if(this.MediaPlayerViewType == MediaPlayerViewType.FullMediaPanel) WindowsFullScreenAction(); } private void UnloadComponents() { if (!AllowMediaPlayerAutoDispose || MediaPlayerServices == null) return; if (!MediaPlayerServices.HasStopped) MediaPlayerServices.Stop(); MediaPlayerServices.Dispose(); BindingOperations.ClearAllBindings(this); _current = null; //CurrentStreamingitem.IsActive = false; //PlayableLastSeen = null; #region Useless //MovieControl.Dispose(); //_mediaMenu = null; //MediaPlayerService = null; //MovieControl = null; #endregion } internal void MediaPlayerElementRaiseEvent(RoutedEventArgs _event) { RaiseEvent(_event); } internal void MediaPlayerElementRaiseEvent(RoutedEvent _event) { RaiseEvent(new RoutedEventArgs(_event, this)); } private void SetMediaControlDetails() { this.MovieControl.MediaDetailProps.MediaDuration = MediaPlayerServices.Duration.TotalSeconds; this.MovieControl.SetMediaVolume(MovieControl.VolumeControl.VolumeLevel); } private void TimeChangeAction() { if (!_isDragging) { MovieControl.MediaDetailProps.CurrentMediaTime = MediaPlayerServices.CurrentTimer.TotalSeconds; PlayableLastSeen.Progress = Math.Round(((MovieControl.MediaDetailProps.CurrentMediaTime / MovieControl.MediaDetailProps.MediaDuration) * 100), 2); } } private void UnLoadPlaylistComponents() { MovieControl.UnloadedPlaylistControls(); _playlistregion.Content = null; } private void LoadPlaylistComponents() { MovieControl.LoadPlaylistControls(); _playlistregion.Content = PlaylistManager; } private void OnStopAction() { this.IsPlaying = false; //reset Animation ResetControlAnimation(); MovieControl.CloseLastSeenBoard(); PlayableLastSeenSaveAction(); CurrentStreamingitem.IsActive = false; MovieControl.MediaDetailProps.CurrentMediaTime = 0.0; } internal void ControlViewChangeCommandAction() { // MovieControl.ControlViewType = MovieControl.ControlViewType == MediaControlViewType.LargeView ? MediaControlViewType.MiniView : MediaControlViewType.LargeView; } private void PlayableLastSeenSaveAction() { if (_playlastableLastSeen != null && !string.IsNullOrEmpty(_playlastableLastSeen.LastPlayedPoisition.FileName)) { _playlastableLastSeen.SetProgress(); if (!_playlastableLastSeen.LastPlayedPoisition.Exist && _playlastableLastSeen.Progress > 0) { _playlastableLastSeen.LastPlayedPoisition.Add(); } _playlastableLastSeen.LastPlayedPoisition.Save(); } } private void OnMediaFinishedAction() { ResetControlAnimation(); PlayableLastSeen.PlayCompletely(); CheckForRepeat(); } private void CheckForRepeat() { if (!IscheckingForRepeating) { IscheckingForRepeating = true; if (PlaylistManager != null && MovieControl.MediaDetailProps.RepeatMode != RepeatMode.NoRepeat) MediaPlayerUtil.ExecuteTimerAction(() => StartRepeatAction(), 50); else IscheckingForRepeating = false; } } private void StartRepeatAction() { IscheckingForRepeating = false; if (MovieControl.MediaDetailProps.RepeatMode == RepeatMode.RepeatOnce) { Source(CurrentStreamingitem); return; } var vfc = PlaylistManager.GetNextItem(); if (vfc != null) this.Source(vfc); } internal void ReWindFastForward() { if (!_isrewindorfastforward) { _isrewindorfastforward = true; if (VolumeState == VolumeState.Active) { MediaPlayerServices.ToggleMute(); } ResetControlAnimation(); } } internal void RestoreRewindFastforwardSettings() { if (VolumeState == VolumeState.Active) { MediaPlayerServices.ToggleMute(); } _isrewindorfastforward = false; StartControlAnimation(); } internal void RepeatModeAction() { if (MovieControl.MediaDetailProps.RepeatMode == RepeatMode.NoRepeat) { MovieControl.MediaDetailProps.RepeatMode = RepeatMode.Repeat; } else if (MovieControl.MediaDetailProps.RepeatMode == RepeatMode.Repeat) { MovieControl.MediaDetailProps.RepeatMode = RepeatMode.RepeatOnce; } else if (MovieControl.MediaDetailProps.RepeatMode == RepeatMode.RepeatOnce) { MovieControl.MediaDetailProps.RepeatMode = RepeatMode.NoRepeat; } } internal void MuteAction() { if (!MediaPlayerServices.IsMute) { MediaPlayerServices.ToggleMute(); //MovieControl.VolumeControl.IsEnabled = false; VolumeState = VolumeState.Muted; } else { MediaPlayerServices.ToggleMute(); // MovieControl.VolumeControl.IsEnabled = true; VolumeState = VolumeState.Active; } } internal void PreviousAction() { if (!MediaPlayerServices.HasStopped) MediaPlayerServices.Stop(); Source(PlaylistManager.GetPreviousItem()); } internal void NextAction() { if (!MediaPlayerServices.HasStopped) MediaPlayerServices.Stop(); Source(PlaylistManager.GetNextItem()); } internal void WindowsFullScreenAction() { WindowFullScreenState = WindowFullScreenState == WindowFullScreenState.Normal ? WindowFullScreenState.FullScreen : WindowFullScreenState.Normal; var routedevent = new WindowFullScreenRoutedEventArgs(OnFullScreenButtonToggleEvent, this, WindowFullScreenState); this.MediaPlayerElementRaiseEvent(routedevent); } private void SetStretchProperty(Stretch newValue) { MediaPlayerServices.VideoStretch = newValue; } internal void MinimizeControlAction() { if (this.MediaPlayerViewType == MediaPlayerViewType.FullMediaPanel) { SaveMediaDefinitedSettings(); if (_isPlaylistVisible) TogglePlaylistView(); if(_savedSecondaryControl != null) { _savedSecondaryControl.SetControlSettings(this.MovieControl.MovieControlSettings); this.UseSecondaryControl = _savedSecondaryControl; } else this.MovieControl.ControlViewType = MediaControlViewType.MiniView; this.MediaPlayerViewType = MediaPlayerViewType.MiniMediaPanel; this.MediaStretch = Stretch.UniformToFill; _allowMediaSizeEventExecute = false; } else { RestoreMediaDefinitedSetting(); } var routedevent = new MediaPlayerViewTypeRoutedEventArgs(OnMinimizedControlExecutedEvent, this, this.MediaPlayerViewType); this.MediaPlayerElementRaiseEvent(routedevent); PreviewControl(); } private void RestoreMediaDefinitedSetting() { if(_savedSecondaryControl == null) this.MovieControl.ControlViewType = _savedSettings.MovieControlViewType; this.MediaPlayerViewType = _savedSettings.MediaPlayerMode; this.IsMediaContextMenuEnabled = _savedSettings.AllowContextMenu; this._allowMediaSizeEventExecute = _savedSettings.AllowMediaResize; this.MediaStretch = _savedSettings.stretchValue; this.IsMediaContextMenuEnabled = _savedSettings.IsContextMenuEnabled; //if(_savedSettings.PlaylistContent != null) //{ // PlaylistManager.ApplyTemplate(); // this._playlistregion.Content = PlaylistManager; //} } private void SaveMediaDefinitedSettings() { _savedSettings.MovieControlViewType = this.MovieControl.ControlViewType; _savedSettings.AllowContextMenu = this.IsMediaContextMenuEnabled; _savedSettings.MediaPlayerMode = MediaPlayerViewType; _savedSettings.AllowMediaResize = _allowMediaSizeEventExecute; _savedSettings.stretchValue = this.MediaStretch; _savedSettings.IsContextMenuEnabled = IsMediaContextMenuEnabled; } internal void WindowsClosedAction() { this.MediaPlayerElementRaiseEvent(OnCloseWindowToggledEvent); } private void ShowControl() { MovieControl.SetIsMouseOverMediaElement(MovieControl as UIElement, null); this.Cursor = Cursors.Arrow; } private void HideControl() { MovieControl.SetIsMouseOverMediaElement(MovieControl as UIElement, false); this.Cursor = Cursors.None; } internal void PreviewControl() { _controlAnimationTimer.Stop(); ShowControl(); _controlAnimationTimer.Start(); } private void ResetControlAnimation() { _controlAnimationTimer.Stop(); ShowControl(); } private void StartControlAnimation() { ShowControl(); _controlAnimationTimer.Start(); } private void InitializePlaylist() { if (PlaylistManager == null) PlaylistManager = new MoviesPlaylistManager(this); } private void ExecuteLater(Action action, long milliseconds) { MediaPlayerUtil.ExecuteTimerAction(action, milliseconds); } internal void PauseOrPlayAction(bool igonreMediaState = false) { if (igonreMediaState) { MediaPlayerServices.Play(); return; } if (MediaPlayerServices.State == MovieMediaState.Playing) { MediaPlayerServices.PauseOrResume(); IsPlaying = false; } else if (MediaPlayerServices.State == MovieMediaState.Ended || MediaPlayerServices.State == MovieMediaState.Paused || MediaPlayerServices.State == MovieMediaState.Stopped) { if (MediaPlayerServices.State == MovieMediaState.Ended) { this.Source(CurrentStreamingitem); return; } MediaPlayerServices.Play(); IsPlaying = true; } } internal void TogglePlaylistView() { if (PlaylistManager.TogglePlayVisibility()) { PlaylistManager.Focus(); ResetControlAnimation(); _isPlaylistVisible = true; return; } StartControlAnimation(); _isPlaylistVisible = false; } internal void SetMovieBoardText(string info) { MediaTitle = info; this.MovieControl.SetMovieTitleBoard(info); this.MediaPlayerElementRaiseEvent(new RoutedEventArgs(OnMediaTitleChangedEvent, this)); } internal void SourceFromPlaylist(IPlayable file_to_pay) { Source(file_to_pay); } public void Source(IPlayable file_to_pay) { if (!_hasInitialised && !_awaitHostToRender) { this.ApplyTemplate(); } if (!MediaPlayerServices.HasStopped) MediaPlayerServices.Stop(); this.CurrentStreamingitem = file_to_pay; if (file_to_pay.Url == null) throw new NotImplementedException("No media Url"); if (!_hasInitialised) throw new Exception("MediaPlayerElement not Initialized"); (MediaPlayerServices as MediaPlayerService).LoadMedia(file_to_pay.Url); PlayableLastSeen = file_to_pay is IMediaPlayabeLastSeen ? file_to_pay as IMediaPlayabeLastSeen : DummyIMediaPlayabeLastSeen.CreateDummtObject(); } public void Source(Uri file_to_pay) { Source(DummyPlayableFile.Parse(file_to_pay)); } public void Source(IPlaylistModel plm) { //if (!_hasInitialised && !_awaitHostToRender) //{ // ExecuteLater(() => this.Source(plm), 50); // _awaitHostToRender = true; // return; //} if (!_hasInitialised && !_awaitHostToRender) { this.ApplyTemplate(); } InitializePlaylist(); PlaylistManager.PlayFromAList(plm); } public void Source(IPlayable playFile, IEnumerable<IPlayable> TemperalList) { if (!_hasInitialised && !_awaitHostToRender) { this.ApplyTemplate(); } Source(playFile); InitializePlaylist(); PlaylistManager.PlayFromTemperalList(TemperalList); } public void AddToPlaylist(IPlayable vfc) { if (!_hasInitialised && !_awaitHostToRender) { this.ApplyTemplate(); } InitializePlaylist(); PlaylistManager.Add(vfc); } public void AddRangeToPlaylist(IEnumerable<IPlayable> EnumerableVfc) { if (!_hasInitialised && !_awaitHostToRender) { this.ApplyTemplate(); } InitializePlaylist(); PlaylistManager.AddRange(EnumerableVfc); } public void Dispose() { AllowMediaPlayerAutoDispose = true; this.UnloadComponents(); } } }
38.568858
207
0.620864
[ "MIT" ]
eadwinCode/MoviePlayer
src/MovieHub.MediaPlayerElement/MediaPlayerElement.cs
49,293
C#
using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Authorization; using Microsoft.AspNetCore.Mvc.Filters; using Microsoft.Extensions.Caching.Memory; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using Microsoft.IdentityModel.Tokens; using System; using System.IdentityModel.Tokens.Jwt; using System.Linq; using System.Net.Http; using System.Security.Claims; using System.Text.Json; using System.Threading.Tasks; namespace Qf.Core.Web.Authorization { /// <summary> /// 授权认证 /// </summary> public class BearerAuthorizeAttribute : AuthorizeAttribute, IAsyncAuthorizationFilter { /// <summary> /// 默认授权 /// </summary> public const string DefaultAuthenticationScheme = "BearerAuth"; private readonly ILogger<BearerAuthorizeAttribute> _logger; private readonly AppSettings _options; private readonly IHttpClientFactory _clientFactory; /// <summary> /// 认证服务器地址 /// </summary> private readonly string issUrl = string.Empty; /// <summary> /// 保护的API名称 /// </summary> private readonly string apiName = string.Empty; private readonly IMemoryCache _cache; /// <summary> /// Initializes a new instance of the <see cref="BearerAuthorizeAttribute"/> class. /// </summary> /// <param name="optionsAccessor"></param> /// <param name="clientFactory"></param> /// <param name="memoryCache"></param> public BearerAuthorizeAttribute(ILogger<BearerAuthorizeAttribute> logger, IOptions<AppSettings> optionsAccessor, IHttpClientFactory clientFactory, IMemoryCache memoryCache) { _logger = logger; AuthenticationSchemes = DefaultAuthenticationScheme; _options = optionsAccessor.Value ?? throw new ArgumentNullException(nameof(optionsAccessor)); _clientFactory = clientFactory ?? throw new ArgumentNullException(nameof(clientFactory)); _cache = memoryCache; issUrl = _options.Auth.ServerUrl; apiName = _options.Auth.ApiName; } /// <summary> /// 授权认证 /// </summary> /// <param name="context"></param> public async Task OnAuthorizationAsync(AuthorizationFilterContext context) { if (context.Filters.Any(item => item is IAllowAnonymousFilter)) return; var result = await context.HttpContext.AuthenticateAsync(DefaultAuthenticationScheme); if (result == null || !result.Succeeded) { string authHeader = context.HttpContext.Request.Headers["Authorization"]; if (authHeader != null && authHeader.StartsWith("Bearer ")) { try { var token = authHeader.Replace("Bearer ", string.Empty); if (!_cache.TryGetValue(token, out ClaimsPrincipal cacheEntry)) { using (var httpclient = _clientFactory.CreateClient()) { var jwtKey = await httpclient.GetStringAsync(issUrl + "/.well-known/openid-configuration/jwks"); var ids4keys = JsonSerializer.Deserialize<Ids4Keys>(jwtKey); var handler = new JwtSecurityTokenHandler(); cacheEntry = handler.ValidateToken(token, new TokenValidationParameters { ValidIssuer = issUrl, IssuerSigningKeys = ids4keys.Keys, ValidateLifetime = true, ValidAudience = apiName, }, out var _); _cache.Set(token, cacheEntry, new MemoryCacheEntryOptions() .SetSlidingExpiration(TimeSpan.FromSeconds(3600))); } } await context.HttpContext.SignInAsync(DefaultAuthenticationScheme, cacheEntry); context.HttpContext.User = cacheEntry; return; } catch (SecurityTokenExpiredException ex) { _logger.LogWarning($"验证授权失败:{apiName} {issUrl} {ex.Message}"); } catch (Exception ex) { _logger.LogError(ex, "验证授权失败:{apiName} {issUrl}", apiName, issUrl); } } context.Result = new UnauthorizedResult(); } else { if (result?.Principal != null) { context.HttpContext.User = result.Principal; } } return; } } }
40.354331
180
0.549463
[ "MIT" ]
576245308/Qf.Core
framework/src/Qf.Core.Web/Authorization/BearerAuthorizeAttribute.cs
5,203
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ using Bright.Serialization; using System.Collections.Generic; namespace Cfg.StartServer { public sealed class StartScene : Bright.Config.BeanBase { public StartScene(ByteBuf _buf) { Id = _buf.ReadInt(); Process = _buf.ReadInt(); Zone = _buf.ReadInt(); SceneType = (ET.SceneType)_buf.ReadInt(); Name = _buf.ReadString(); OuterPort = _buf.ReadInt(); } public static StartScene DeserializeStartScene(ByteBuf _buf) { return new StartServer.StartScene(_buf); } /// <summary> /// Id /// </summary> public int Id { get; private set; } /// <summary> /// 所属进程 /// </summary> public int Process { get; private set; } /// <summary> /// 所属区 /// </summary> public int Zone { get; private set; } /// <summary> /// 类型 /// </summary> public ET.SceneType SceneType { get; private set; } /// <summary> /// 名字 /// </summary> public string Name { get; private set; } /// <summary> /// 外网端口 /// </summary> public int OuterPort { get; private set; } public const int __ID__ = 1690877139; public override int GetTypeId() => __ID__; public void Resolve(Dictionary<string, object> _tables) { } public void TranslateText(System.Func<string, string, string> translator) { } public override string ToString() { return "{ " + "Id:" + Id + "," + "Process:" + Process + "," + "Zone:" + Zone + "," + "SceneType:" + SceneType + "," + "Name:" + Name + "," + "OuterPort:" + OuterPort + "," + "}"; } } }
24.130952
80
0.510607
[ "MIT" ]
kteong1012/Arthas
Server/Model/Generate/Config/StartServer/StartScene.cs
2,057
C#
namespace TurnerSoftware.BuildVersioning.Tool { internal class BuildVersioner { private IVersionDetailsProvider VersionDetailsProvider { get; } public BuildVersioner(IVersionDetailsProvider versionDetailsProvider) { VersionDetailsProvider = versionDetailsProvider; } public BuildVersion GetBuildVersion(BuildVersioningOptions options) { var versionDetails = VersionDetailsProvider.GetVersionDetails(); if (versionDetails is null) { return null; } if (!versionDetails.IsTaggedRelease && versionDetails.PreRelease is null && options.PreReleaseFormat?.Length > 0) { versionDetails = versionDetails with { PreRelease = options.PreReleaseFormat .Replace("{CommitHeight}", versionDetails.CommitHeight.ToString()) }; } if (options.BuildMetadataFormat?.Length > 0) { versionDetails = versionDetails with { BuildMetadata = options.BuildMetadataFormat .Replace("{CommitHash}", versionDetails.CommitHash) .Replace("{CommitHeight}", versionDetails.CommitHeight.ToString()) }; } var fullVersion = FormatFullVersion(options.FullVersionFormat, versionDetails); var fileVersion = FormatVersion(options.FileVersionFormat, versionDetails); var assemblyVersion = FormatVersion(options.AssemblyVersionFormat, versionDetails); return new BuildVersion { FullVersion = fullVersion, FileVersion = fileVersion, AssemblyVersion = assemblyVersion }; } private static string FormatFullVersion(string format, VersionDetails versionDetails) { if (string.IsNullOrEmpty(format)) { return format; } return FormatVersion(format, versionDetails) .Replace("{PreRelease}", versionDetails.PreRelease is null ? default : $"-{versionDetails.PreRelease}") .Replace("{BuildMetadata}", versionDetails.BuildMetadata is null ? default : $"+{versionDetails.BuildMetadata}"); } private static string FormatVersion(string format, VersionDetails versionDetails) { if (string.IsNullOrEmpty(format)) { return format; } var autoIncrement = versionDetails.IsTaggedRelease ? 0 : 1; return format .Replace("{Major}", versionDetails.MajorVersion.ToString()) .Replace("{Major++}", (versionDetails.MajorVersion + autoIncrement).ToString()) .Replace("{Minor}", versionDetails.MinorVersion.ToString()) .Replace("{Minor++}", (versionDetails.MinorVersion + autoIncrement).ToString()) .Replace("{Patch}", versionDetails.PatchVersion.ToString()) .Replace("{Patch++}", (versionDetails.PatchVersion + autoIncrement).ToString()) .Replace("{CommitHeight}", versionDetails.CommitHeight.ToString()) .Replace("{CommitHash}", versionDetails.CommitHash ?? "NOCANDO"); } } }
32.951807
117
0.730896
[ "MIT" ]
TurnerSoftware/BuildVersioning
src/TurnerSoftware.BuildVersioning.Tool/BuildVersioner.cs
2,737
C#
using MinecraftMappings.Internal.Textures.Block; namespace MinecraftMappings.Minecraft.Java.Textures.Block { public class OrangeConcretePowder : JavaBlockTexture { public OrangeConcretePowder() : base("Orange Concrete Powder") { AddVersion("orange_concrete_powder") .WithMinVersion("1.12"); //.MapsToBedrockBlock<MinecraftMappings.Minecraft.Bedrock.Textures.Block.ConcretePowderOrange>(); } } }
31.8
113
0.681342
[ "MIT" ]
null511/MinecraftMappings.NET
MinecraftMappings.NET/Minecraft/Java/Textures/Block/OrangeConcretePowder.cs
479
C#
using System.Collections.Generic; using System.Linq; using Improbable.Gdk.CodeGeneration.FileHandling; namespace Improbable.Gdk.CodeGenerator { /// <summary> /// A FileSystem implementation that ignores the existence of ".meta" files when listing directory contents. /// </summary> class MetaDataCompatibleFileSystem : IFileSystem { private readonly FileSystem fileSystem = new FileSystem(); public List<IFile> GetFilesInDirectory(string path, string searchPattern = "*.*", bool recursive = true) { var files = fileSystem.GetFilesInDirectory(path, searchPattern, recursive); return files.Where(f => !f.CompletePath.EndsWith(".meta")).ToList(); } public void WriteToFile(string path, string content) { fileSystem.WriteToFile(path, content); } public string ReadFromFile(string path) { return fileSystem.ReadFromFile(path); } public IFile GetFileInfo(string path) { return fileSystem.GetFileInfo(path); } public bool DirectoryExists(string path) { return fileSystem.DirectoryExists(path); } public void CreateDirectory(string path) { fileSystem.CreateDirectory(path); } public void DeleteDirectory(string path) { fileSystem.DeleteDirectory(path); } } }
28.607843
116
0.623715
[ "MIT" ]
gdk-for-unity-bot/gdk-for-unity
workers/unity/Packages/com.improbable.gdk.tools/.CodeGenerator/GdkCodeGenerator/src/MetaDataCompatibleFileSystem.cs
1,459
C#
using System.Collections.Generic; using GraphQL; using GraphQL.Types; namespace appservice_graphql_dotnet.Types { public class TriviaQuery : ObjectGraphType { public TriviaQuery(QuizData data) { Field<NonNullGraphType<ListGraphType<NonNullGraphType<QuizType>>>>("quizzes", resolve: context => { return data.Quizzes; }); Field<NonNullGraphType<QuizType>>("quiz", arguments: new QueryArguments() { new QueryArgument<NonNullGraphType<StringGraphType>> { Name = "id", Description = "id of the quiz" } }, resolve: (context) => data.FindById(context.GetArgument<string>("id"))); } } }
32.727273
116
0.618056
[ "MIT" ]
AzureAdvocateBit/appservice-graphql-dotnet-1
Types/TriviaQuery.cs
720
C#
using AutoMapper; using System.Net; using WeShare.Application.Common.Mappings; using WeShare.Domain.Entities; namespace WeShare.Application.DTOs; public class WebhookPostSendFailureDto : PostSendFailureDto, IMapFrom<PostSendFailure> { public HttpStatusCode? StatusCode { get; set; } public int ResponseLatency { get; set; } public WebhookPostSendFailureDto(HttpStatusCode? statusCode, int responseLatency, DateTimeOffset createdAt) : base(createdAt) { StatusCode = statusCode; ResponseLatency = responseLatency; } public WebhookPostSendFailureDto() { } void IMapFrom<PostSendFailure>.Mapping(Profile profile) //Necessary to override base class definition => profile.CreateMap<WebhookPostSendFailure, WebhookPostSendFailureDto>(); }
30.961538
111
0.751553
[ "MIT" ]
PoolPirate/WeShare
src/Application/DataTransferObjects/PostSendFailure/Types/WebhookPostSendFailureDto.cs
807
C#
using MCM.Abstractions.Settings.Base; using MCM.Abstractions.Settings.Formats; namespace MCM.Implementation.Settings.Formats.Json { /// <summary> /// So it can be overriden by an external library /// </summary> public interface IJsonSettingsFormat : ISettingsFormat { string SaveJson(BaseSettings settings); BaseSettings? LoadFromJson(BaseSettings settings, string content); } }
30
74
0.721429
[ "MIT" ]
Aragas/Bannerlord.MBOptionScreen
src/MCM/Implementation/Settings/Formats/Json/IJsonSettingsFormat.cs
422
C#
//----------------------------------------------------------------------- // <copyright file="AssemblyInfo.cs" company="Akka.NET Project"> // Copyright (C) 2009-2016 Typesafe Inc. <http://www.typesafe.com> // Copyright (C) 2013-2016 Akka.NET project <https://github.com/akkadotnet/akka.net> // </copyright> //----------------------------------------------------------------------- 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("Akka.Persistence.Sql.Common.TestKit")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Akka.Persistence.Sql.Common.TestKit")] [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("e7bc4f35-b9fb-49cb-b12c-cd00f6a08ea2")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
41.659091
88
0.67976
[ "Apache-2.0" ]
EnterpriseProductsLP/akka.net
src/contrib/persistence/Akka.Persistence.Sql.Common.TestKit/Properties/AssemblyInfo.cs
1,836
C#
#region License /* Copyright (c) 2009 - 2013 Fatjon Sakiqi Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #endregion namespace Cloo { using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using Cloo.Bindings; //////////////////////////////////////////////////////////////////////////////////////////////////// /// <summary> Represents a list of OpenCL generated or user created events. </summary> /// /// <seealso cref="T:System.Collections.Generic.IList{Cloo.ComputeEventBase}"/> /// <seealso cref="ComputeCommandQueue"/> //////////////////////////////////////////////////////////////////////////////////////////////////// public class ComputeEventList : IList<ComputeEventBase> { #region Fields /// <summary> The events. </summary> [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] private readonly List<ComputeEventBase> events; #endregion #region Constructors /// <summary> Creates an empty <see cref="ComputeEventList"/>. </summary> public ComputeEventList() { events = new List<ComputeEventBase>(); } //////////////////////////////////////////////////////////////////////////////////////////////////// /// <summary> /// Creates a new <see cref="ComputeEventList"/> from an existing list of /// <see cref="ComputeEventBase"/>s. /// </summary> /// /// <param name="events"> A list of <see cref="ComputeEventBase"/>s. </param> //////////////////////////////////////////////////////////////////////////////////////////////////// public ComputeEventList(IList<ComputeEventBase> events) { events = new Collection<ComputeEventBase>(events); } #endregion #region Properties //////////////////////////////////////////////////////////////////////////////////////////////////// /// <summary> Gets the last <see cref="ComputeEventBase"/> on the list. </summary> /// /// <value> The last <see cref="ComputeEventBase"/> on the list. </value> //////////////////////////////////////////////////////////////////////////////////////////////////// public ComputeEventBase Last => events[events.Count - 1]; #endregion #region Public methods //////////////////////////////////////////////////////////////////////////////////////////////////// /// <summary> Waits on the host thread for the specified events to complete. </summary> /// /// <param name="events"> The events to be waited for completition. </param> //////////////////////////////////////////////////////////////////////////////////////////////////// public static void Wait(ICollection<ComputeEventBase> events) { int eventWaitListSize; CLEventHandle[] eventHandles = ComputeTools.ExtractHandles(events, out eventWaitListSize); ComputeErrorCode error = CL12.WaitForEvents(eventWaitListSize, eventHandles); ComputeException.ThrowOnError(error); } //////////////////////////////////////////////////////////////////////////////////////////////////// /// <summary> /// Waits on the host thread for the <see cref="ComputeEventBase"/>s in the /// <see cref="ComputeEventList"/> to complete. /// </summary> //////////////////////////////////////////////////////////////////////////////////////////////////// public void Wait() { ComputeEventList.Wait(events); } #endregion #region IList<ComputeEventBase> Members //////////////////////////////////////////////////////////////////////////////////////////////////// /// <summary> Index of the given item. </summary> /// /// <param name="item"> . </param> /// /// <returns> An int. </returns> /// /// <seealso cref="M:System.Collections.Generic.IList{Cloo.ComputeEventBase}.IndexOf(ComputeEventBase)"/> //////////////////////////////////////////////////////////////////////////////////////////////////// public int IndexOf(ComputeEventBase item) { return events.IndexOf(item); } //////////////////////////////////////////////////////////////////////////////////////////////////// /// <summary> Inserts. </summary> /// /// <param name="index"> . </param> /// <param name="item"> . </param> /// /// <seealso cref="M:System.Collections.Generic.IList{Cloo.ComputeEventBase}.Insert(int,ComputeEventBase)"/> //////////////////////////////////////////////////////////////////////////////////////////////////// public void Insert(int index, ComputeEventBase item) { events.Insert(index, item); } //////////////////////////////////////////////////////////////////////////////////////////////////// /// <summary> Removes at described by index. </summary> /// /// <param name="index"> . </param> /// /// <seealso cref="M:System.Collections.Generic.IList{Cloo.ComputeEventBase}.RemoveAt(int)"/> //////////////////////////////////////////////////////////////////////////////////////////////////// public void RemoveAt(int index) { events.RemoveAt(index); } //////////////////////////////////////////////////////////////////////////////////////////////////// /// <summary> /// Indexer to get or set items within this collection using array index syntax. /// </summary> /// /// <param name="index"> . </param> /// /// <returns> The indexed item. </returns> /// /// <seealso cref="M:System.Collections.Generic.IList{Cloo.ComputeEventBase}.this(int)"/> //////////////////////////////////////////////////////////////////////////////////////////////////// public ComputeEventBase this[int index] { get => events[index]; set => events[index] = value; } #endregion #region ICollection<ComputeEventBase> Members //////////////////////////////////////////////////////////////////////////////////////////////////// /// <summary> Adds item. </summary> /// /// <param name="item"> . </param> //////////////////////////////////////////////////////////////////////////////////////////////////// public void Add(ComputeEventBase item) { events.Add(item); } /// <summary> Clears this object to its blank/initial state. </summary> public void Clear() { events.Clear(); } //////////////////////////////////////////////////////////////////////////////////////////////////// /// <summary> Query if this object contains the given item. </summary> /// /// <param name="item"> . </param> /// /// <returns> True if the object is in this collection, false if not. </returns> //////////////////////////////////////////////////////////////////////////////////////////////////// public bool Contains(ComputeEventBase item) { return events.Contains(item); } //////////////////////////////////////////////////////////////////////////////////////////////////// /// <summary> Copies to. </summary> /// /// <param name="array"> . </param> /// <param name="arrayIndex"> . </param> //////////////////////////////////////////////////////////////////////////////////////////////////// public void CopyTo(ComputeEventBase[] array, int arrayIndex) { events.CopyTo(array, arrayIndex); } //////////////////////////////////////////////////////////////////////////////////////////////////// /// <summary> Gets the number of. </summary> /// /// <value> The count. </value> //////////////////////////////////////////////////////////////////////////////////////////////////// public int Count => events.Count; //////////////////////////////////////////////////////////////////////////////////////////////////// /// <summary> Gets a value indicating whether this object is read only. </summary> /// /// <value> True if this object is read only, false if not. </value> //////////////////////////////////////////////////////////////////////////////////////////////////// public bool IsReadOnly => false; //////////////////////////////////////////////////////////////////////////////////////////////////// /// <summary> Removes the given item. </summary> /// /// <param name="item"> . </param> /// /// <returns> True if it succeeds, false if it fails. </returns> //////////////////////////////////////////////////////////////////////////////////////////////////// public bool Remove(ComputeEventBase item) { return events.Remove(item); } #endregion #region IEnumerable<ComputeEventBase> Members //////////////////////////////////////////////////////////////////////////////////////////////////// /// <summary> Gets the enumerator. </summary> /// /// <returns> The enumerator. </returns> //////////////////////////////////////////////////////////////////////////////////////////////////// public IEnumerator<ComputeEventBase> GetEnumerator() { return ((IEnumerable<ComputeEventBase>)events).GetEnumerator(); } #endregion #region IEnumerable Members //////////////////////////////////////////////////////////////////////////////////////////////////// /// <summary> Gets the enumerator. </summary> /// /// <returns> The enumerator. </returns> //////////////////////////////////////////////////////////////////////////////////////////////////// IEnumerator IEnumerable.GetEnumerator() { return ((IEnumerable)events).GetEnumerator(); } #endregion } }
39.462329
116
0.398681
[ "MIT" ]
mattcolefla/KelpNet-master
Cloo/ComputeEventList.cs
11,525
C#
// Copyright 2017-2020 Elringus (Artyom Sovetnikov). All Rights Reserved. using System.Collections.Generic; using System.Linq; using UniRx.Async; using UnityEngine; namespace Naninovel { /// <inheritdoc cref="ITextManager"/> [InitializeAtRuntime] public class TextManager : ITextManager { public ManagedTextConfiguration Configuration { get; } private readonly IResourceProviderManager providersManager; private readonly ILocalizationManager localizationManager; private readonly HashSet<ManagedTextRecord> records = new HashSet<ManagedTextRecord>(); private ResourceLoader<TextAsset> documentLoader; public TextManager (ManagedTextConfiguration config, IResourceProviderManager providersManager, ILocalizationManager localizationManager) { Configuration = config; this.providersManager = providersManager; this.localizationManager = localizationManager; } public UniTask InitializeServiceAsync () { localizationManager.AddChangeLocaleTask(ApplyManagedTextAsync); documentLoader = Configuration.Loader.CreateLocalizableFor<TextAsset>(providersManager, localizationManager); return UniTask.CompletedTask; } public void ResetService () { } public void DestroyService () { localizationManager?.RemoveChangeLocaleTask(ApplyManagedTextAsync); documentLoader?.UnloadAll(); } public string GetRecordValue (string key, string category = ManagedTextRecord.DefaultCategoryName) { foreach (var record in records) if (record.Category.EqualsFast(category) && record.Key.EqualsFast(key)) return record.Value; return null; } public IEnumerable<ManagedTextRecord> GetAllRecords (params string[] categoryFilter) { if (categoryFilter is null || categoryFilter.Length == 0) return records.ToList(); var result = new List<ManagedTextRecord>(); foreach (var record in records) if (categoryFilter.Contains(record.Category)) result.Add(record); return result; } public async UniTask ApplyManagedTextAsync () { records.Clear(); documentLoader.UnloadAll(); var documentResources = await documentLoader.LoadAllAsync(); foreach (var documentResource in documentResources) { if (!documentResource.IsValid) { Debug.LogWarning($"Failed to load `{documentResource.Path}` managed text document."); continue; } var managedTextSet = ManagedTextUtils.ParseDocument(documentResource.Object.text, documentLoader.BuildLocalPath(documentResource.Path)); foreach (var text in managedTextSet) records.Add(new ManagedTextRecord(text.Key, text.Value, text.Category)); ManagedTextUtils.ApplyRecords(managedTextSet); } } } }
38.517647
153
0.624007
[ "MIT" ]
286studio/Sim286
AVG/Assets/Naninovel/Runtime/ManagedText/TextManager.cs
3,276
C#
// Copyright 2013-2016 Serilog Contributors // // 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 Serilog.Debugging; using System; using System.Threading; using System.Threading.Tasks; namespace Serilog.Sinks.Seq { sealed class PortableTimer : IDisposable { readonly object _stateLock = new(); readonly Func<CancellationToken, Task> _onTick; readonly CancellationTokenSource _cancel = new(); #if THREADING_TIMER readonly Timer _timer; #endif bool _running; bool _disposed; public PortableTimer(Func<CancellationToken, Task> onTick) { _onTick = onTick ?? throw new ArgumentNullException(nameof(onTick)); #if THREADING_TIMER _timer = new Timer(_ => OnTick(), null, Timeout.Infinite, Timeout.Infinite); #endif } public void Start(TimeSpan interval) { if (interval < TimeSpan.Zero) throw new ArgumentOutOfRangeException(nameof(interval)); lock (_stateLock) { if (_disposed) throw new ObjectDisposedException(nameof(PortableTimer)); #if THREADING_TIMER _timer.Change(interval, Timeout.InfiniteTimeSpan); #else Task.Delay(interval, _cancel.Token) .ContinueWith( _ => OnTick(), CancellationToken.None, TaskContinuationOptions.DenyChildAttach, TaskScheduler.Default); #endif } } async void OnTick() { try { lock (_stateLock) { if (_disposed) { return; } // There's a little bit of raciness here, but it's needed to support the // current API, which allows the tick handler to reenter and set the next interval. if (_running) { Monitor.Wait(_stateLock); if (_disposed) { return; } } _running = true; } if (!_cancel.Token.IsCancellationRequested) { await _onTick(_cancel.Token); } } catch (OperationCanceledException tcx) { SelfLog.WriteLine("The timer was canceled during invocation: {0}", tcx); } finally { lock (_stateLock) { _running = false; Monitor.PulseAll(_stateLock); } } } public void Dispose() { _cancel.Cancel(); lock (_stateLock) { if (_disposed) { return; } while (_running) { Monitor.Wait(_stateLock); } #if THREADING_TIMER _timer.Dispose(); #endif _disposed = true; } } } }
27.507246
103
0.499473
[ "Apache-2.0" ]
datalust/serilog-sinks-seq
src/Serilog.Sinks.Seq/Sinks/Seq/PortableTimer.cs
3,798
C#
// ReSharper disable CommentTypo namespace IctBaden.Units { public static class GeoCoordinateFormatter { /// <summary> /// Format the given geo-coordinate /// Possible formats: /// d - Dezimalgrad, zum Beispiel 37.7°, -122.2° /// g - Grad, Minuten, Sekunden, zum Beispiel 37°25'19.07"N, 122°05'06.24"W /// m - Grad, Dezimalminuten, zum Beispiel 32° 18.385' N 122° 36.875' W /// Grad, Dezimalgrad ohne Grad-Zeichen /// </summary> /// <param name="coordinate"></param> /// <param name="format">Format to be used: d, g or m</param> /// <returns></returns> public static string ToString(this GeoCoordinate coordinate, string format = "") { var latitude = new SexagesimalCoordinate(coordinate.Latitude); var longitude = new SexagesimalCoordinate(coordinate.Longitude); return $"{latitude.ToLatString(format)}, {longitude.ToLongString(format)}"; } } }
42.083333
88
0.60297
[ "MIT" ]
FrankPfattheicher/IctBaden.Units
IctBaden.Units/GeoCoordinates/GeoCoordinateFormatter.cs
1,018
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.Web.V20201201 { public static class ListWebAppConnectionStrings { /// <summary> /// String dictionary resource. /// </summary> public static Task<ListWebAppConnectionStringsResult> InvokeAsync(ListWebAppConnectionStringsArgs args, InvokeOptions? options = null) => Pulumi.Deployment.Instance.InvokeAsync<ListWebAppConnectionStringsResult>("azure-native:web/v20201201:listWebAppConnectionStrings", args ?? new ListWebAppConnectionStringsArgs(), options.WithVersion()); } public sealed class ListWebAppConnectionStringsArgs : Pulumi.InvokeArgs { /// <summary> /// Name of the app. /// </summary> [Input("name", required: true)] public string Name { get; set; } = null!; /// <summary> /// Name of the resource group to which the resource belongs. /// </summary> [Input("resourceGroupName", required: true)] public string ResourceGroupName { get; set; } = null!; public ListWebAppConnectionStringsArgs() { } } [OutputType] public sealed class ListWebAppConnectionStringsResult { /// <summary> /// Resource Id. /// </summary> public readonly string Id; /// <summary> /// Kind of resource. /// </summary> public readonly string? Kind; /// <summary> /// Resource Name. /// </summary> public readonly string Name; /// <summary> /// Connection strings. /// </summary> public readonly ImmutableDictionary<string, Outputs.ConnStringValueTypePairResponse> Properties; /// <summary> /// Resource type. /// </summary> public readonly string Type; [OutputConstructor] private ListWebAppConnectionStringsResult( string id, string? kind, string name, ImmutableDictionary<string, Outputs.ConnStringValueTypePairResponse> properties, string type) { Id = id; Kind = kind; Name = name; Properties = properties; Type = type; } } }
29.627907
217
0.603611
[ "Apache-2.0" ]
polivbr/pulumi-azure-native
sdk/dotnet/Web/V20201201/ListWebAppConnectionStrings.cs
2,548
C#
using UnityEngine; using UnityAtoms.SceneMgmt; namespace UnityAtoms.SceneMgmt { /// <summary> /// Variable of type `SceneField`. Inherits from `EquatableAtomVariable&lt;SceneField, SceneFieldPair, SceneFieldEvent, SceneFieldPairEvent, SceneFieldSceneFieldFunction&gt;`. /// </summary> [EditorIcon("atom-icon-lush")] [CreateAssetMenu(menuName = "Unity Atoms/Variables/SceneField", fileName = "SceneFieldVariable")] public sealed class SceneFieldVariable : EquatableAtomVariable<SceneField, SceneFieldPair, SceneFieldEvent, SceneFieldPairEvent, SceneFieldSceneFieldFunction> { } }
46.461538
179
0.779801
[ "MIT" ]
puschie286/unity-atoms
Packages/SceneMgmt/Runtime/Variables/SceneFieldVariable.cs
604
C#
namespace Caliburn.Micro.HelloScreens.Framework { public interface IHaveShutdownTask { IResult GetShutdownTask(); } }
26.6
49
0.729323
[ "MIT" ]
victorarias/Caliburn.Micro
samples/Caliburn.Micro.HelloScreens/Caliburn.Micro.HelloScreens/Framework/IHaveShutdownTask.cs
133
C#
//----------------------------------------------------------------------- // <copyright company="CoApp Project"> // Copyright (c) 2010-2013 Garrett Serack and CoApp Contributors. // Contributors can be discovered using the 'git log' command. // All rights reserved. // </copyright> // <license> // The software is licensed under the Apache 2.0 License (the "License") // You may not use the software except in compliance with the License. // </license> //----------------------------------------------------------------------- namespace ClrPlus.Windows.PeBinary.Utility { using Core.Extensions; using Platform; public class BindingRedirect { public FourPartVersion Low; public FourPartVersion High; public FourPartVersion Target; public string VersionRange { get { return "{0}-{1}".format(Low.ToString(), High.ToString()); } } } }
34.928571
77
0.523517
[ "Apache-2.0" ]
Jaykul/clrplus
Windows.PeBinary/Utility/BindingRedirect.cs
978
C#
using System; using System.Linq; using System.Net.Http; using System.Threading.Tasks; using Xunit; using Xunit.Abstractions; using ZendeskApi.Client.Exceptions; using ZendeskApi.Client.IntegrationTests.Factories; using ZendeskApi.Client.Models; using ZendeskApi.Client.Requests; namespace ZendeskApi.Client.IntegrationTests.Resources { public class OrganizationResourceTests : IClassFixture<ZendeskClientFactory> { private readonly ITestOutputHelper _output; private readonly ZendeskClientFactory _clientFactory; public OrganizationResourceTests( ITestOutputHelper output, ZendeskClientFactory clientFactory) { _output = output; _clientFactory = clientFactory; } [Fact] public async Task GetAllAsync_WhenCalled_ReturnsOrganisations() { var client = _clientFactory.GetClient(); var id = Guid.NewGuid().ToString(); var created = await client.Organizations .CreateAsync(new Organization { ExternalId = id, Name = $"ZendeskApi.Client.IntegrationTests {id}" }); var organisations = await client .Organizations .GetAllAsync(); Assert.NotEmpty(organisations); await client.Organizations .DeleteAsync(created.Id); } [Fact] public async Task GetAllAsync_WhenCalledWithOrganisationIds_ReturnsOrganisations() { var client = _clientFactory.GetClient(); var id = Guid.NewGuid().ToString(); var created = await client.Organizations .CreateAsync(new Organization { ExternalId = id, Name = $"ZendeskApi.Client.IntegrationTests {id}" }); var organisations = await client .Organizations .GetAllAsync(new [] { created.Id }); Assert.NotEmpty(organisations); await client.Organizations .DeleteAsync(created.Id); } [Fact] public async Task GetAllAsync_WhenCalledWithExternalIds_ReturnsOrganisations() { var client = _clientFactory.GetClient(); var id = Guid.NewGuid().ToString(); var created = await client.Organizations .CreateAsync(new Organization { ExternalId = id, Name = $"ZendeskApi.Client.IntegrationTests {id}" }); var organisations = await client .Organizations .GetAllByExternalIdsAsync(new[] { created.ExternalId }); Assert.NotEmpty(organisations); await client.Organizations .DeleteAsync(created.Id); } [Fact] public async Task GetAllByUserId_WhenCalled_ReturnsOrganisations() { var client = _clientFactory.GetClient(); var id = Guid.NewGuid().ToString(); var createdOrganisation = await client.Organizations .CreateAsync(new Organization { ExternalId = id, Name = $"ZendeskApi.Client.IntegrationTests {id}" }); var userId = Guid.NewGuid().ToString(); var user = await client.Users .CreateAsync(new UserCreateRequest(userId)); var organisationResultsBeforeMembership = await client .Organizations .GetAllByUserIdAsync(user.Id); Assert.Empty(organisationResultsBeforeMembership); var organisationMembership = await client .OrganizationMemberships .CreateAsync(new OrganizationMembership { OrganizationId = createdOrganisation.Id, UserId = user.Id }); var organisationResultsAfterMembership = await client .Organizations .GetAllByUserIdAsync(user.Id); Assert.NotEmpty(organisationResultsAfterMembership); await client .OrganizationMemberships .DeleteAsync(organisationMembership.Id.Value); await client .Users .DeleteAsync(user.Id); await client .Organizations .DeleteAsync(createdOrganisation.Id); } [Fact] public async Task GetAsync_WhenCalled_ReturnsOrganisation() { var client = _clientFactory.GetClient(); var id = Guid.NewGuid().ToString(); var created = await client.Organizations .CreateAsync(new Organization { ExternalId = id, Name = $"ZendeskApi.Client.IntegrationTests {id}" }); var organisation = await client .Organizations .GetAsync(created.Id); Assert.NotNull(organisation); await client.Organizations .DeleteAsync(created.Id); } [Fact] public async Task GetAsync_WhenCalledWithInvalidId_ReturnsNull() { var client = _clientFactory.GetClient(); var organisation = await client .Organizations .GetAsync(long.MaxValue); Assert.Null(organisation); } [Fact] public async Task CreateAync_WhenCalled_CreatesOrganisation() { var client = _clientFactory.GetClient(); var id = Guid.NewGuid().ToString(); var created = await client.Organizations .CreateAsync(new Organization { ExternalId = id, Name = $"ZendeskApi.Client.IntegrationTests {id}" }); var found = await client .Organizations .GetAllByExternalIdsAsync(new[] { id }); Assert.Single(found); var org = found.First(); Assert.Equal(id, org.ExternalId); Assert.Equal($"ZendeskApi.Client.IntegrationTests {id}", org.Name); await client.Organizations .DeleteAsync(created.Id); } [Fact] public async Task UpdateAsync_WhenCalled_UpdatesOrganisation() { var client = _clientFactory.GetClient(); var id = Guid.NewGuid().ToString(); var updatedId = Guid.NewGuid().ToString(); var created = await client.Organizations .CreateAsync(new Organization { ExternalId = id, Name = $"ZendeskApi.Client.IntegrationTests {id}" }); var updated = await client.Organizations .UpdateAsync(new Organization { Id = created.Id, Name = $"ZendeskApi.Client.IntegrationTests {updatedId}", ExternalId = updatedId }); Assert.NotNull(updated); var found = await client .Organizations .GetAllByExternalIdsAsync(new[] { updatedId }); Assert.Single(found); var org = found.First(); Assert.Equal(updatedId, org.ExternalId); Assert.Equal($"ZendeskApi.Client.IntegrationTests {updatedId}", org.Name); await client.Organizations .DeleteAsync(created.Id); } [Fact] public async Task UpdateAsync_WhenCalledWithInvalidId_ReturnsNull() { var client = _clientFactory.GetClient(); var id = Guid.NewGuid().ToString(); var updated = await client.Organizations .UpdateAsync(new Organization { Id = long.MaxValue, Name = $"ZendeskApi.Client.IntegrationTests {id}", ExternalId = id }); Assert.Null(updated); } [Fact] public async Task DeleteAsync_WhenCalled_DeletesOrganisation() { var client = _clientFactory.GetClient(); var id = Guid.NewGuid().ToString(); var created = await client.Organizations .CreateAsync(new Organization { ExternalId = id, Name = $"ZendeskApi.Client.IntegrationTests {id}" }); var beforeDeleteSearch = await client .Organizations .GetAllByExternalIdsAsync(new[] { id }); Assert.Single(beforeDeleteSearch); await client.Organizations .DeleteAsync(created.Id); var afterDeleteSearch = await client .Organizations .GetAllByExternalIdsAsync(new[] { id }); Assert.Empty(afterDeleteSearch); } [Fact] public async Task DeleteAsync_WhenCalledWithInvalidId_Throws() { var client = _clientFactory.GetClient(); await Assert.ThrowsAsync<ZendeskRequestException>(() => client.Organizations .DeleteAsync(long.MaxValue)); } } }
29.506024
90
0.524296
[ "Apache-2.0" ]
Ud0o/ZendeskApiClient
test/ZendeskApi.Client.IntegrationTests/Resources/OrganizationResourceTests.cs
9,796
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. */ namespace Sys.Workflow.Engine.Impl { /// <summary> /// holds the parameters of a page (partial result) for a query. /// /// /// /// </summary> public class Page { protected internal int firstResult; protected internal int maxResults; public Page(int firstResult, int maxResults) { this.firstResult = firstResult; this.maxResults = maxResults; } public virtual int FirstResult { get { return firstResult; } } public virtual int MaxResults { get { return maxResults; } } } }
25.9
75
0.588417
[ "Apache-2.0" ]
18502079446/cusss
NActiviti/Sys.Bpm.Engine.API/Engine/impl/Page.cs
1,297
C#
using System; using System.Diagnostics; using System.Threading; using Pixytech.Core.Logging; namespace Demo.Helpers { public class PluginDebugger { private readonly int _parentProcessId; public delegate PluginDebugger Factory(int parentProcessId); ILog _logger = LogManager.GetLogger(typeof(PluginDebugger)); public PluginDebugger(int parentProcessId) { _parentProcessId = parentProcessId; } [Conditional("DEBUG")] [DebuggerStepThrough] public void TryAttachToDebugger() { try { if (!Debugger.IsAttached) { // VsDebugger.AttachCurrentWithDebugger(_parentProcessId); Thread.Sleep(500); _logger.Debug(@"Attached to visual studio debugger"); } } catch (Exception ex) { _logger.DebugFormat(@"Error while attaching to visual studio : {0} ", ex.Message); } } [Conditional("DEBUG")] [DebuggerStepThrough] public void Break() { if (Debugger.IsAttached) { Debugger.Break(); } } } }
25.56
98
0.533646
[ "Apache-2.0" ]
Pixytech/Frameworks
Demo/Helpers/PluginDebugger.cs
1,280
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.Security.Latest.Inputs { /// <summary> /// A custom alert rule that checks if a value (depends on the custom alert type) is allowed. /// </summary> public sealed class AllowlistCustomAlertRuleArgs : Pulumi.ResourceArgs { [Input("allowlistValues", required: true)] private InputList<string>? _allowlistValues; /// <summary> /// The values to allow. The format of the values depends on the rule type. /// </summary> public InputList<string> AllowlistValues { get => _allowlistValues ?? (_allowlistValues = new InputList<string>()); set => _allowlistValues = value; } /// <summary> /// Status of the custom alert. /// </summary> [Input("isEnabled", required: true)] public Input<bool> IsEnabled { get; set; } = null!; /// <summary> /// The type of the custom alert rule. /// Expected value is 'ListCustomAlertRule'. /// </summary> [Input("ruleType", required: true)] public Input<string> RuleType { get; set; } = null!; public AllowlistCustomAlertRuleArgs() { } } }
31.666667
97
0.615789
[ "Apache-2.0" ]
pulumi-bot/pulumi-azure-native
sdk/dotnet/Security/Latest/Inputs/AllowlistCustomAlertRuleArgs.cs
1,520
C#
using System; using System.ComponentModel.DataAnnotations.Schema; using Payments.Domain.Common; namespace Payments.Domain.Enums { public enum PaymentStatus { Pending, Confirmed, Cancelled } }
17.285714
52
0.652893
[ "MIT" ]
marinasundstrom/PointOfSale
Payments/Payments/Domain/Enums/PaymentStatus.cs
242
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("18.RemoveElementsFromArray")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("18.RemoveElementsFromArray")] [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("10cb3895-8f98-4d00-aa5c-8e3668ad574d")] // 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.513514
84
0.748772
[ "MIT" ]
glifada/High-Quality-Code-Homeworks
C#-Part2/01. Arrays/18.RemoveElementsFromArray/Properties/AssemblyInfo.cs
1,428
C#
using Unity.Barracuda; using System; using UnityEngine; using UnityEngine.Serialization; using Unity.MLAgents.Actuators; using Unity.MLAgents.Sensors.Reflection; namespace Unity.MLAgents.Policies { /// <summary> /// Defines what type of behavior the Agent will be using /// </summary> [Serializable] public enum BehaviorType { /// <summary> /// The Agent will use the remote process for decision making. /// if unavailable, will use inference and if no model is provided, will use /// the heuristic. /// </summary> Default, /// <summary> /// The Agent will always use its heuristic /// </summary> HeuristicOnly, /// <summary> /// The Agent will always use inference with the provided /// neural network model. /// </summary> InferenceOnly } /// <summary> /// Options for controlling how the Agent class is searched for <see cref="ObservableAttribute"/>s. /// </summary> public enum ObservableAttributeOptions { /// <summary> /// All ObservableAttributes on the Agent will be ignored. This is the /// default behavior. If there are no ObservableAttributes on the /// Agent, this will result in the fastest initialization time. /// </summary> Ignore, /// <summary> /// Only members on the declared class will be examined; members that are /// inherited are ignored. This is a reasonable tradeoff between /// performance and flexibility. /// </summary> /// <remarks>This corresponds to setting the /// [BindingFlags.DeclaredOnly](https://docs.microsoft.com/en-us/dotnet/api/system.reflection.bindingflags?view=netcore-3.1) /// when examining the fields and properties of the Agent class instance. /// </remarks> ExcludeInherited, /// <summary> /// All members on the class will be examined. This can lead to slower /// startup times. /// </summary> ExamineAll } /// <summary> /// A component for setting an <seealso cref="Agent"/> instance's behavior and /// brain properties. /// </summary> /// <remarks>At runtime, this component generates the agent's policy objects /// according to the settings you specified in the Editor.</remarks> [AddComponentMenu("ML Agents/Behavior Parameters", (int)MenuGroup.Default)] public class BehaviorParameters : MonoBehaviour { [HideInInspector, SerializeField] BrainParameters m_BrainParameters = new BrainParameters(); /// <summary> /// The associated <see cref="Policies.BrainParameters"/> for this behavior. /// </summary> public BrainParameters BrainParameters { get { return m_BrainParameters; } internal set { m_BrainParameters = value; } } [HideInInspector, SerializeField] NNModel m_Model; /// <summary> /// The neural network model used when in inference mode. /// This should not be set at runtime; use <see cref="Agent.SetModel(string,NNModel,Policies.InferenceDevice)"/> /// to set it instead. /// </summary> public NNModel Model { get { return m_Model; } set { m_Model = value; UpdateAgentPolicy(); } } [HideInInspector, SerializeField] InferenceDevice m_InferenceDevice; /// <summary> /// How inference is performed for this Agent's model. /// This should not be set at runtime; use <see cref="Agent.SetModel(string,NNModel,Policies.InferenceDevice)"/> /// to set it instead. /// </summary> public InferenceDevice InferenceDevice { get { return m_InferenceDevice; } set { m_InferenceDevice = value; UpdateAgentPolicy(); } } [HideInInspector, SerializeField] BehaviorType m_BehaviorType; /// <summary> /// The BehaviorType for the Agent. /// </summary> public BehaviorType BehaviorType { get { return m_BehaviorType; } set { m_BehaviorType = value; UpdateAgentPolicy(); } } [HideInInspector, SerializeField] string m_BehaviorName = "My Behavior"; /// <summary> /// The name of this behavior, which is used as a base name. See /// <see cref="FullyQualifiedBehaviorName"/> for the full name. /// This should not be set at runtime; use <see cref="Agent.SetModel(string,NNModel,Policies.InferenceDevice)"/> /// to set it instead. /// </summary> public string BehaviorName { get { return m_BehaviorName; } set { m_BehaviorName = value; UpdateAgentPolicy(); } } /// <summary> /// The team ID for this behavior. /// </summary> [HideInInspector, SerializeField, FormerlySerializedAs("m_TeamID")] public int TeamId; // TODO properties here instead of Agent [FormerlySerializedAs("m_useChildSensors")] [HideInInspector] [SerializeField] [Tooltip("Use all Sensor components attached to child GameObjects of this Agent.")] bool m_UseChildSensors = true; [HideInInspector] [SerializeField] [Tooltip("Use all Actuator components attached to child GameObjects of this Agent.")] bool m_UseChildActuators = true; /// <summary> /// Whether or not to use all the sensor components attached to child GameObjects of the agent. /// Note that changing this after the Agent has been initialized will not have any effect. /// </summary> public bool UseChildSensors { get { return m_UseChildSensors; } set { m_UseChildSensors = value; } } /// <summary> /// Whether or not to use all the actuator components attached to child GameObjects of the agent. /// Note that changing this after the Agent has been initialized will not have any effect. /// </summary> public bool UseChildActuators { get { return m_UseChildActuators; } set { m_UseChildActuators = value; } } [HideInInspector, SerializeField] ObservableAttributeOptions m_ObservableAttributeHandling = ObservableAttributeOptions.Ignore; /// <summary> /// Determines how the Agent class is searched for <see cref="ObservableAttribute"/>s. /// </summary> public ObservableAttributeOptions ObservableAttributeHandling { get { return m_ObservableAttributeHandling; } set { m_ObservableAttributeHandling = value; } } /// <summary> /// Returns the behavior name, concatenated with any other metadata (i.e. team id). /// </summary> public string FullyQualifiedBehaviorName { get { return m_BehaviorName + "?team=" + TeamId; } } internal IPolicy GeneratePolicy(ActionSpec actionSpec, ActuatorManager actuatorManager) { switch (m_BehaviorType) { case BehaviorType.HeuristicOnly: return new HeuristicPolicy(actuatorManager, actionSpec); case BehaviorType.InferenceOnly: { if (m_Model == null) { var behaviorType = BehaviorType.InferenceOnly.ToString(); throw new UnityAgentsException( $"Can't use Behavior Type {behaviorType} without a model. " + "Either assign a model, or change to a different Behavior Type." ); } return new BarracudaPolicy(actionSpec, m_Model, m_InferenceDevice, m_BehaviorName); } case BehaviorType.Default: if (Academy.Instance.IsCommunicatorOn) { return new RemotePolicy(actionSpec, FullyQualifiedBehaviorName); } if (m_Model != null) { return new BarracudaPolicy(actionSpec, m_Model, m_InferenceDevice, m_BehaviorName); } else { return new HeuristicPolicy(actuatorManager, actionSpec); } default: return new HeuristicPolicy(actuatorManager, actionSpec); } } internal void UpdateAgentPolicy() { var agent = GetComponent<Agent>(); if (agent == null) { return; } agent.ReloadPolicy(); } } }
36.626016
132
0.578357
[ "Apache-2.0" ]
418sec/ml-agents
com.unity.ml-agents/Runtime/Policies/BehaviorParameters.cs
9,010
C#
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; namespace System.Reflection { public static class MemberInfoExtensions { public static Type GetUnderlyingType(this MemberInfo member) { switch (member.MemberType) { case MemberTypes.Event: return ((EventInfo)member).EventHandlerType; case MemberTypes.Field: return ((FieldInfo)member).FieldType; case MemberTypes.Method: return ((MethodInfo)member).ReturnType; case MemberTypes.Property: return ((PropertyInfo)member).PropertyType; default: throw new ArgumentException ( "Input MemberInfo must be if type EventInfo, FieldInfo, MethodInfo, or PropertyInfo" ); } } } }
31
105
0.560117
[ "MIT" ]
maca88/PowerArhitecture
Source/SharperArchitecture.Common/Extensions/MemberInfoExtensions.cs
1,025
C#
using System; using System.Collections; using DragonBones; using UnityEngine; using Transform = UnityEngine.Transform; namespace WSGJ { public abstract class BaseEntity : MonoBehaviour { public static event Action<BaseEntity> Died; public float ScoreValue => scoreValue; [SerializeField, Header("Entity Settings")] float movementSpeed; [SerializeField] float attackDamage = 10f; [SerializeField] float delayBetweenAttacks = 2f; [SerializeField] float scoreValue; Transform currentTarget; TruckController truckController; protected UnityArmatureComponent ArmatureComponent; protected bool CanMove = true; protected bool IsDead = false; IEnumerator attackCoroutine; void Awake() { ArmatureComponent = GetComponentInChildren<UnityArmatureComponent>(true); SetTarget(FindObjectOfType<TruckController>()?.transform); } void Update() { if(CanMove == false || IsDead) return; if((UnityEngine.Object)currentTarget == null) return; var dir = currentTarget.position - transform.position; var distance = dir.sqrMagnitude; var newScale = transform.localScale; newScale.x = Math.Sign(dir.x) > 0 ? -1f : 1f; transform.localScale = newScale; bool isInAttackRange = distance < 25f; SetAttackState(isInAttackRange); if(!isInAttackRange) { transform.position += movementSpeed * Time.deltaTime * Math.Sign(dir.x) * transform.right; if(ArmatureComponent.animationName != "move") { ArmatureComponent.animation.Play("move", -1); } } } protected virtual void SetTarget(Transform target) { currentTarget = target; truckController = currentTarget.GetComponent<TruckController>(); } void SetAttackState(bool isAttacking) { if(isAttacking && attackCoroutine == null) { attackCoroutine = AttackWithDelay(); StartCoroutine(attackCoroutine); } if(!isAttacking && attackCoroutine != null) { StopCoroutine(attackCoroutine); attackCoroutine = null; if(ArmatureComponent.animationName != "move") { ArmatureComponent.animation.Play("move", -1); } } } IEnumerator AttackWithDelay() { while(true) { if(IsDead) yield break; yield return new WaitForSeconds(delayBetweenAttacks); if(IsDead) yield break; truckController.OnDamageTaken(attackDamage); ArmatureComponent.animation.Play("atack", 1); } } void OnTriggerEnter2D(Collider2D other) { if(other.CompareTag("Weapon") == false) return; OnEntityDied(); } public virtual void OnEntityDied() { CanMove = false; Died?.Invoke(this); } } }
21.593496
94
0.693901
[ "MIT" ]
mszkopinski/FilmowkaGameJam2019
Assets/Scripts/Entities/BaseEntity.cs
2,656
C#
using MyCalendar.Mobile.Views.Home.TabPages.AddAppointment; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace MyCalendar.Mobile.Common.Services.Appointment { public class AppointmentServiceMock : IAppointmentService { private List<AppointmentViewModel> appointments; public AppointmentServiceMock() { this.appointments = new List<AppointmentViewModel>(); } public Task<int> CreateAppointmentAsync(AppointmentViewModel appointment) { appointment.Id = this.appointments.Count + 1; this.appointments.Add(appointment); return Task.FromResult(appointment.Id); } public Task<IEnumerable<AppointmentViewModel>> GetAppointmentOverviewAsync() { return Task.FromResult(this.appointments.AsEnumerable()); } } }
28.1875
84
0.684035
[ "MIT" ]
sunshineV9/MyCalendar
MyCalendar/MyCalendar.Mobile/MyCalendar.Mobile/Common/Services/Appointment/AppointmentServiceMock.cs
904
C#
/* * Copyright (c) 2014-Present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ namespace React.Router { /// <summary> /// Context object used during render of React Router component /// </summary> public class RoutingContext { /// <summary> /// HTTP Status Code. /// If present signifies that the given status code should be returned by server. /// </summary> public int? status { get; set; } /// <summary> /// URL to redirect to. /// If included this signals that React Router determined a redirect should happen. /// </summary> public string url { get; set; } } }
27.633333
85
0.68275
[ "BSD-3-Clause" ]
gunnarsireus/React.NET
src/React.Router/RoutingContext.cs
831
C#
using Discord; using Discord.Commands; using Microsoft.Extensions.Configuration; using System.Linq; using System.Threading.Tasks; namespace AvaBot.Modules { // for commands to be available, and have the Context passed to them, we must inherit ModuleBase [Summary("📋 Help Commands")] //[Group("help")] //[Alias("h")] public class HelpCommands : ModuleBase { private readonly CommandService _commands; private readonly IConfiguration _config; public HelpCommands(CommandService commands, IConfiguration config) { _commands = commands; _config = config; } [Command("help")] [Alias("h")] [Summary("Show every commands available")] public async Task HelpCommand() { EmbedBuilder embedBuilder = new EmbedBuilder() .WithTitle("Commands help") .WithDescription("The actual prefix is `" + _config["Prefix"] + "`." + "\nFor more informations about a command, use `" + _config["Prefix"] + "help [command]`.") .WithFooter("github.com/AvaN0x", "https://avatars3.githubusercontent.com/u/27494805?s=460&v=4") .WithColor(255, 241, 185); //TODO : Don't add multiple times the same command foreach (var module in _commands.Modules.Where(m => !m.Name.ToLower().Contains("help"))) embedBuilder.AddField(module.Summary ?? module.Name, string.Join(", ", module.Commands.Select(c => "`" + c.Name + "`"))); await ReplyAsync("", false, embedBuilder.Build()); } [Command("help")] [Alias("h")] [Summary("Show informations about a command")] public async Task HelpCommand([Summary("The command to explain")] string commandName) { var commands = _commands.Commands.Where(c => c.Name == commandName.ToLower()); if (commands.Count() == 0) { EmbedBuilder embedMessage = new EmbedBuilder() .WithDescription("There are no commands with that name.") .WithColor(255, 0, 0); var errorMessage = await ReplyAsync("", false, embedMessage.Build()); await Task.Delay(5000); // 5 seconds await errorMessage.DeleteAsync(); return; } EmbedBuilder embedBuilder = new EmbedBuilder() .WithFooter("github.com/AvaN0x", "https://avatars3.githubusercontent.com/u/27494805?s=460&v=4") .WithColor(255, 241, 185); foreach (var cmd in commands) { embedBuilder.AddField("Command " + cmd.Name, "" + string.Join("\n", cmd.Aliases.Select(a => "`" + _config["Prefix"] + a + string.Join("", cmd.Parameters.Select(p => " [" + p.Name + "]")) + "`")) + "\n__Summary :__ \n" + "*" + (cmd.Summary ?? "No description available") + "*\n" + (cmd.Parameters.Count() > 0 ? "__Parameters :__ " + string.Concat(cmd.Parameters.Select(p => "\n[" + p.Name + "] : *" + (p.Summary ?? "No description available") + "*")) + "\n" : "") + ""); } await ReplyAsync("", false, embedBuilder.Build()); } } }
43.679487
172
0.540652
[ "MIT" ]
AvaN0x/AvaBot
Modules/HelpCommands.cs
3,412
C#
using Moneyventory.Application.Common.Validation; using NUnit.Framework; namespace Moneyventory.Application.Tests.Common.Validation { using static DomainAddressValidator; [TestFixture] [Parallelizable(ParallelScope.Children)] public class GivenDomainAddressValidator { [Test] public void WhenAllAreAlphaNumericThenItIsValid() => Assert.That(IsValid("localhost123"), Is.True); [Test] public void WhenNamesAreSeparatedByDotThenItIsValid() => Assert.That(IsValid("name.domain"), Is.True); [Test] public void WhenStartedByDotThenItIsNotValid() => Assert.That(IsValid(".domain"), Is.False); [Test] public void WhenEndedByDotThenItIsNotValid() => Assert.That(IsValid("name."), Is.False); [Test] public void WhenContainsDashOrUnderscoreThenItIsValid() => Assert.That(IsValid("another-domain_name"), Is.True); [Test] public void WhenStartedByDashCharacterThenItIsNotValid() => Assert.That(IsValid("-domain.name"), Is.False); [Test] public void WhenSomePartStartedByDashThenItIsNotValid() => Assert.That(IsValid("www.-domain.com"), Is.False); [Test] public void WhenSomePartEndedByDashThenItIsNotValid() => Assert.That(IsValid("www.domain-.com"), Is.False); [Test] public void WhenEndedByDashThenItIsNotValid() => Assert.That(IsValid("domain-"), Is.False); [Test] public void WhenContainsSpecialCharacterOtherThanDashOrUnderscoreThenItIsNotValid() => Assert.That(IsValid("in%valid.domain"), Is.False); } }
36.454545
120
0.693267
[ "MIT" ]
fakhrulhilal/moneyventory
tests/Core/Application.Tests/Common/Validation/GivenDomainAddressValidator.cs
1,604
C#
using Sanja.Model; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Shapes; namespace Sanja.Forme { /// <summary> /// Interaction logic for IzmeniVozaca.xaml /// </summary> public partial class IzmeniVozaca : Window { private MainWindow mw; private Vozac vozac; private ListaVozaca parent; public IzmeniVozaca(MainWindow w, ListaVozaca d, Vozac v) { parent = d; mw = w; vozac = v; InitializeComponent(); this.DataContext = this; tbIdVozaca.Text = vozac.Id.ToString(); tbImeVozaca.Text = vozac.Ime; tbPrezimeVozaca.Text = vozac.Prezime; tbAdresaVozaca.Text = vozac.Adresa; tbJMBGVozaca.Text = vozac.JMBG; tbKontaktVozaca.Text = vozac.Kontakt; } private void Button_Click(object sender, RoutedEventArgs e) { foreach (Vozac v in mw.Pod.Vozaci) { if(v.Id == vozac.Id) { if (provera()) { v.Ime = tbImeVozaca.Text; v.Prezime = tbPrezimeVozaca.Text; v.Adresa = tbAdresaVozaca.Text; v.Kontakt = tbKontaktVozaca.Text; parent.dataVozaci.Items.Refresh(); this.Close(); } } } } private bool provera() { string message = ""; int flag = -1; if (String.IsNullOrEmpty(tbIdVozaca.Text)) { message += "ID vozaca ne sme biti prazno!\n"; tbIdVozaca.Focus(); flag = 1; } if (!String.IsNullOrEmpty(tbIdVozaca.Text) && !Int32.TryParse(tbIdVozaca.Text, out int id)) { message += "ID vozaca mora biti broj!\n"; tbIdVozaca.Focus(); flag = 1; } if (!String.IsNullOrEmpty(tbIdVozaca.Text) && (tbIdVozaca.Text[0] == '-' || tbIdVozaca.Text[0] == '+')) { message += "ID vozaca mora biti pozitivan ceo broj!\n"; tbIdVozaca.Focus(); flag = 1; } if (tbIdVozaca.Text.Length > 1 && tbIdVozaca.Text[0] == '0') { message += "ID vozaca ne moze da pocnje sa 0!\n"; tbIdVozaca.Focus(); flag = 1; } if (String.IsNullOrEmpty(tbImeVozaca.Text)) { message += "Ime klijenta ne sme biti prazno!\n"; tbImeVozaca.Focus(); flag = 1; } if (String.IsNullOrEmpty(tbJMBGVozaca.Text)) { message += "JMBG ne sme biti prazan!"; tbJMBGVozaca.Focus(); flag = 1; } if (!Regex.Match(tbJMBGVozaca.Text, "^[0-9]*$").Success) { message += "Neispravan JMBG!\n"; tbJMBGVozaca.Focus(); flag = 1; } if (!String.IsNullOrEmpty(tbJMBGVozaca.Text) && tbJMBGVozaca.Text.Length != 13) { message += "Neispravan JMBG!\n"; tbJMBGVozaca.Focus(); flag = 1; } if (flag == 1) { MessageBox.Show(message); return false; } else { return true; } } private void Button_Click_2(object sender, RoutedEventArgs e) { this.Close(); } } }
29.171429
115
0.47478
[ "Apache-2.0" ]
drobicsanja/ntransport
Sanja/Forme/IzmeniVozaca.xaml.cs
4,086
C#
 namespace TrainingProviderTestData.Web { using System; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using StructureMap; using Application.Configuration; using Application.Interfaces; using Application.Importers; using Application.Repositories; public class Startup { public IConfiguration Configuration { get; } public Startup(IConfiguration configuration) { Configuration = configuration; } // This method gets called by the runtime. Use this method to add services to the container. // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940 public IServiceProvider ConfigureServices(IServiceCollection services) { services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2); return ConfigureIoC(services); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseMvc(routes => { routes.MapRoute("default", "{controller=Home}/{action=Index}/{id?}"); }); } private IServiceProvider ConfigureIoC(IServiceCollection services) { var container = new Container(); container.Configure(config => { config.Populate(services); config.For<IApplicationConfiguration>().Use(x => ConfigurationFactory.GetApplicationConfiguration(Configuration)); config.For<ITestDataRepository>().Use<TestDataRepository>(); config.For<IUkrlpDataImporter>().Use<UkrlpDataImporter>(); config.For<ICompaniesHouseDataImporter>().Use<CompaniesHouseDataImporter>(); config.For<ICharityDataImporter>().Use<CharityDataImporter>(); }); return container.GetInstance<IServiceProvider>(); } } }
37.885246
130
0.655993
[ "MIT" ]
David-B-Read/training-provider-test-data
src/TrainingProviderTestData.Web/Startup.cs
2,313
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 rds-2014-10-31.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.RDS.Model { /// <summary> /// The requested operation can't be performed while the cluster is in this state. /// </summary> #if !NETSTANDARD [Serializable] #endif public partial class InvalidDBClusterStateException : AmazonRDSException { /// <summary> /// Constructs a new InvalidDBClusterStateException with the specified error /// message. /// </summary> /// <param name="message"> /// Describes the error encountered. /// </param> public InvalidDBClusterStateException(string message) : base(message) {} /// <summary> /// Construct instance of InvalidDBClusterStateException /// </summary> /// <param name="message"></param> /// <param name="innerException"></param> public InvalidDBClusterStateException(string message, Exception innerException) : base(message, innerException) {} /// <summary> /// Construct instance of InvalidDBClusterStateException /// </summary> /// <param name="innerException"></param> public InvalidDBClusterStateException(Exception innerException) : base(innerException) {} /// <summary> /// Construct instance of InvalidDBClusterStateException /// </summary> /// <param name="message"></param> /// <param name="innerException"></param> /// <param name="errorType"></param> /// <param name="errorCode"></param> /// <param name="requestId"></param> /// <param name="statusCode"></param> public InvalidDBClusterStateException(string message, Exception innerException, ErrorType errorType, string errorCode, string requestId, HttpStatusCode statusCode) : base(message, innerException, errorType, errorCode, requestId, statusCode) {} /// <summary> /// Construct instance of InvalidDBClusterStateException /// </summary> /// <param name="message"></param> /// <param name="errorType"></param> /// <param name="errorCode"></param> /// <param name="requestId"></param> /// <param name="statusCode"></param> public InvalidDBClusterStateException(string message, ErrorType errorType, string errorCode, string requestId, HttpStatusCode statusCode) : base(message, errorType, errorCode, requestId, statusCode) {} #if !NETSTANDARD /// <summary> /// Constructs a new instance of the InvalidDBClusterStateException class with serialized data. /// </summary> /// <param name="info">The <see cref="T:System.Runtime.Serialization.SerializationInfo" /> that holds the serialized object data about the exception being thrown.</param> /// <param name="context">The <see cref="T:System.Runtime.Serialization.StreamingContext" /> that contains contextual information about the source or destination.</param> /// <exception cref="T:System.ArgumentNullException">The <paramref name="info" /> parameter is null. </exception> /// <exception cref="T:System.Runtime.Serialization.SerializationException">The class name is null or <see cref="P:System.Exception.HResult" /> is zero (0). </exception> protected InvalidDBClusterStateException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) : base(info, context) { } /// <summary> /// Sets the <see cref="T:System.Runtime.Serialization.SerializationInfo" /> with information about the exception. /// </summary> /// <param name="info">The <see cref="T:System.Runtime.Serialization.SerializationInfo" /> that holds the serialized object data about the exception being thrown.</param> /// <param name="context">The <see cref="T:System.Runtime.Serialization.StreamingContext" /> that contains contextual information about the source or destination.</param> /// <exception cref="T:System.ArgumentNullException">The <paramref name="info" /> parameter is a null reference (Nothing in Visual Basic). </exception> #if BCL35 [System.Security.Permissions.SecurityPermission( System.Security.Permissions.SecurityAction.LinkDemand, Flags = System.Security.Permissions.SecurityPermissionFlag.SerializationFormatter)] #endif [System.Security.SecurityCritical] // These FxCop rules are giving false-positives for this method [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2123:OverrideLinkDemandsShouldBeIdenticalToBase")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2134:MethodsMustOverrideWithConsistentTransparencyFxCopRule")] public override void GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { base.GetObjectData(info, context); } #endif } }
47.725806
178
0.683677
[ "Apache-2.0" ]
ChristopherButtars/aws-sdk-net
sdk/src/Services/RDS/Generated/Model/InvalidDBClusterStateException.cs
5,918
C#
using System; using System.Runtime.InteropServices; namespace LibHac.FsSystem.Save { internal ref struct SaveEntryKey { public ReadOnlySpan<byte> Name; public int Parent; public SaveEntryKey(ReadOnlySpan<byte> name, int parent) { Name = name; Parent = parent; } } [StructLayout(LayoutKind.Sequential, Pack = 1, Size = 0x14)] public struct SaveFileInfo { public int StartBlock; public long Length; public long Reserved; } /// <summary> /// Represents the current position when enumerating a directory's contents. /// </summary> [StructLayout(LayoutKind.Sequential, Pack = 1, Size = 0x14)] public struct SaveFindPosition { /// <summary>The ID of the next directory to be enumerated.</summary> public int NextDirectory; /// <summary>The ID of the next file to be enumerated.</summary> public int NextFile; } }
26.973684
81
0.6
[ "BSD-3-Clause" ]
CaitSith2/libhac
src/LibHac/FsSystem/Save/SaveFsEntry.cs
990
C#
/* * Copyright 2014, 2015 Dominick Baier, Brock Allen * * 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 IdentityServer3.Core.Configuration { internal static class CookieOptionsExtensions { public static string GetCookieName(this CookieOptions options, string name) { return options.Prefix + name; } const string SessionCookieName = "idsvr.session"; public static string GetSessionCookieName(this CookieOptions options) { return options.GetCookieName(SessionCookieName); } internal static bool? CalculateRememberMeFromUserInput(this CookieOptions options, bool? userInput) { // the browser will only send 'true' if the user has checked the checkbox // it will pass nothing if the user does not check the checkbox // this check here is to establish if the user deliberatly did not check the checkbox // or if the checkbox was not presented as an option (and thus AllowRememberMe is not allowed) // true means they did check it, false means they did not, null means they were not presented with the choice if (options.AllowRememberMe) { if (userInput != true) { userInput = false; } } else { userInput = null; } return userInput; } } }
36.636364
121
0.633251
[ "Apache-2.0" ]
AppliedSystems/IdentityServer3
source/Core/Extensions/CookieOptionsExtensions.cs
2,017
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Diagnostics; namespace System.Threading { internal partial class PortableThreadPool { private CountsOfThreadsProcessingUserCallbacks _countsOfThreadsProcessingUserCallbacks; public void ReportThreadStatus(bool isProcessingUserCallback) { CountsOfThreadsProcessingUserCallbacks counts = _countsOfThreadsProcessingUserCallbacks; while (true) { CountsOfThreadsProcessingUserCallbacks newCounts = counts; if (isProcessingUserCallback) { newCounts.IncrementCurrent(); } else { newCounts.DecrementCurrent(); } CountsOfThreadsProcessingUserCallbacks countsBeforeUpdate = _countsOfThreadsProcessingUserCallbacks.InterlockedCompareExchange(newCounts, counts); if (countsBeforeUpdate == counts) { break; } counts = countsBeforeUpdate; } } private short GetAndResetHighWatermarkCountOfThreadsProcessingUserCallbacks() { CountsOfThreadsProcessingUserCallbacks counts = _countsOfThreadsProcessingUserCallbacks; while (true) { CountsOfThreadsProcessingUserCallbacks newCounts = counts; newCounts.ResetHighWatermark(); CountsOfThreadsProcessingUserCallbacks countsBeforeUpdate = _countsOfThreadsProcessingUserCallbacks.InterlockedCompareExchange(newCounts, counts); if (countsBeforeUpdate == counts || countsBeforeUpdate.HighWatermark == countsBeforeUpdate.Current) { return countsBeforeUpdate.HighWatermark; } counts = countsBeforeUpdate; } } /// <summary> /// Tracks thread count information that is used when the <code>EnableWorkerTracking</code> config option is enabled. /// </summary> private struct CountsOfThreadsProcessingUserCallbacks { private const byte CurrentShift = 0; private const byte HighWatermarkShift = 16; private uint _data; private CountsOfThreadsProcessingUserCallbacks(uint data) => _data = data; private short GetInt16Value(byte shift) => (short)(_data >> shift); private void SetInt16Value(short value, byte shift) => _data = (_data & ~((uint)ushort.MaxValue << shift)) | ((uint)(ushort)value << shift); /// <summary> /// Number of threads currently processing user callbacks /// </summary> public short Current => GetInt16Value(CurrentShift); public void IncrementCurrent() { if (Current < HighWatermark) { _data += (uint)1 << CurrentShift; } else { Debug.Assert(Current == HighWatermark); Debug.Assert(Current != short.MaxValue); _data += ((uint)1 << CurrentShift) | ((uint)1 << HighWatermarkShift); } } public void DecrementCurrent() { Debug.Assert(Current > 0); _data -= (uint)1 << CurrentShift; } /// <summary> /// The high-warkmark of number of threads processing user callbacks since the high-watermark was last reset /// </summary> public short HighWatermark => GetInt16Value(HighWatermarkShift); public void ResetHighWatermark() => SetInt16Value(Current, HighWatermarkShift); public CountsOfThreadsProcessingUserCallbacks InterlockedCompareExchange( CountsOfThreadsProcessingUserCallbacks newCounts, CountsOfThreadsProcessingUserCallbacks oldCounts) { return new CountsOfThreadsProcessingUserCallbacks( Interlocked.CompareExchange(ref _data, newCounts._data, oldCounts._data)); } public static bool operator ==( CountsOfThreadsProcessingUserCallbacks lhs, CountsOfThreadsProcessingUserCallbacks rhs) => lhs._data == rhs._data; public static bool operator !=( CountsOfThreadsProcessingUserCallbacks lhs, CountsOfThreadsProcessingUserCallbacks rhs) => lhs._data != rhs._data; public override bool Equals(object? obj) => obj is CountsOfThreadsProcessingUserCallbacks other && _data == other._data; public override int GetHashCode() => (int)_data; } } }
39.448819
125
0.586826
[ "MIT" ]
ANISSARIZKY/runtime
src/libraries/System.Private.CoreLib/src/System/Threading/PortableThreadPool.WorkerTracking.cs
5,010
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. using System.Collections.Generic; namespace System.Reactive.Linq.ObservableImpl { internal sealed class Case<TValue, TResult> : Producer<TResult, Case<TValue, TResult>._>, IEvaluatableObservable<TResult> { private readonly Func<TValue> _selector; private readonly IDictionary<TValue, IObservable<TResult>> _sources; private readonly IObservable<TResult> _defaultSource; public Case(Func<TValue> selector, IDictionary<TValue, IObservable<TResult>> sources, IObservable<TResult> defaultSource) { _selector = selector; _sources = sources; _defaultSource = defaultSource; } public IObservable<TResult> Eval() { if (_sources.TryGetValue(_selector(), out var res)) { return res; } return _defaultSource; } protected override _ CreateSink(IObserver<TResult> observer) => new _(observer); protected override void Run(_ sink) => sink.Run(this); internal sealed class _ : IdentitySink<TResult> { public _(IObserver<TResult> observer) : base(observer) { } public void Run(Case<TValue, TResult> parent) { var result = default(IObservable<TResult>); try { result = parent.Eval(); } catch (Exception exception) { ForwardOnError(exception); return; } Run(result); } } } }
30.322581
129
0.56383
[ "Apache-2.0" ]
NickDarvey/reactive
Rx.NET/Source/src/System.Reactive/Linq/Observable/Case.cs
1,882
C#
// Copyright (c) Terence Parr, Sam Harwell. All Rights Reserved. // Licensed under the BSD License. See LICENSE.txt in the project root for license information. using System.Collections.Generic; using System.Collections.ObjectModel; using Antlr4.Runtime.Misc; using Antlr4.Runtime.Sharpen; namespace Antlr4.Runtime.Dfa { /// <author>Sam Harwell</author> public interface IEdgeMap<T> : IEnumerable<KeyValuePair<int, T>> { int Count { get; } bool IsEmpty { get; } bool ContainsKey(int key); T this[int key] { get; } [return: NotNull] IEdgeMap<T> Put(int key, [Nullable] T value); [return: NotNull] IEdgeMap<T> Remove(int key); [return: NotNull] IEdgeMap<T> PutAll(IEdgeMap<T> m); [return: NotNull] IEdgeMap<T> Clear(); [return: NotNull] ReadOnlyDictionary<int, T> ToMap(); } }
21.212766
95
0.57673
[ "BSD-3-Clause" ]
ProphetLamb-Organistion/antlr4cs
runtime/CSharp/Antlr4.Runtime/Dfa/IEdgeMap`1.cs
997
C#
namespace Schema.NET { using System; using System.Runtime.Serialization; using Newtonsoft.Json; /// <summary> /// A sub-grouping of food or drink items in a menu. E.g. courses (such as 'Dinner', 'Breakfast', etc.), specific type of dishes (such as 'Meat', 'Vegan', 'Drinks', etc.), or some other classification made by the menu provider. /// </summary> public partial interface IMenuSection : ICreativeWork { /// <summary> /// A food or drink item contained in a menu or menu section. /// </summary> OneOrMany<IMenuItem> HasMenuItem { get; set; } /// <summary> /// A subgrouping of the menu (by dishes, course, serving time period, etc.). /// </summary> OneOrMany<IMenuSection> HasMenuSection { get; set; } } /// <summary> /// A sub-grouping of food or drink items in a menu. E.g. courses (such as 'Dinner', 'Breakfast', etc.), specific type of dishes (such as 'Meat', 'Vegan', 'Drinks', etc.), or some other classification made by the menu provider. /// </summary> [DataContract] public partial class MenuSection : CreativeWork, IMenuSection { /// <summary> /// Gets the name of the type as specified by schema.org. /// </summary> [DataMember(Name = "@type", Order = 1)] public override string Type => "MenuSection"; /// <summary> /// A food or drink item contained in a menu or menu section. /// </summary> [DataMember(Name = "hasMenuItem", Order = 206)] [JsonConverter(typeof(ValuesJsonConverter))] public OneOrMany<IMenuItem> HasMenuItem { get; set; } /// <summary> /// A subgrouping of the menu (by dishes, course, serving time period, etc.). /// </summary> [DataMember(Name = "hasMenuSection", Order = 207)] [JsonConverter(typeof(ValuesJsonConverter))] public OneOrMany<IMenuSection> HasMenuSection { get; set; } } }
40.84
232
0.596964
[ "MIT" ]
candela-software/Schema.NET
Source/Schema.NET/core/MenuSection.cs
2,044
C#
using System; using System.Linq; using LanguageExt.UnitsOfMeasure; using static LanguageExt.Prelude; using System.Reflection; namespace LanguageExt { public static class Strategy { /// <summary> /// Compose a sequence of state computations /// </summary> public static State<StrategyContext, Unit> Compose(params State<StrategyContext, Unit>[] stages) => state => StateResult.Return(stages.Fold(state, (s, c) => c(s).State), unit); /// <summary> /// One-for-one strategy /// This strategy affects only the process that failed /// </summary> /// <param name="stages">Set of computations to compose that results in a behaviour /// for the strategy</param> /// <returns>Strategy computation as a State monad</returns> public static State<StrategyContext, Unit> OneForOne(params State<StrategyContext, Unit>[] stages) => state => Compose(stages)(state.With(Affects: new ProcessId[1] { state.Self })); /// <summary> /// All-for-one strategy /// This strategy affects the process that failed and its siblings /// </summary> /// <param name="stages">Set of computations to compose that results in a behaviour /// for the strategy</param> /// <returns>Strategy computation as a State monad</returns> public static State<StrategyContext, Unit> AllForOne(params State<StrategyContext, Unit>[] stages) => state => Compose(stages)(state.With(Affects: state.Siblings)); /// <summary> /// Get the context state State monad /// </summary> public static readonly State<StrategyContext, StrategyContext> Context = get<StrategyContext>(); /// <summary> /// Sets the decision directive. Once set, cant be un-set. /// If the directive is Stop then the Global state is reset for this /// strategy (global to the Process) /// </summary> /// <param name="directive">Directive to set</param> /// <returns>Strategy computation as a State monad</returns> public static State<StrategyContext, Unit> SetDirective(Option<Directive> directive) => from x in Context from y in put(x.With(Directive: directive)) select y; /// <summary> /// Sets the last-failure state. /// </summary> /// <param name="when">Time to set</param> /// <returns>Strategy computation as a State monad</returns> public static State<StrategyContext, Unit> SetLastFailure(DateTime when) => from x in Context from y in put(x.With(Global: x.Global.With(LastFailure: when))) select y; /// <summary> /// Sets the current back off amount /// </summary> /// <param name="step">Step size for the next Process pause before /// resuming</param> /// <returns>Strategy computation as a State monad</returns> public static State<StrategyContext, Unit> SetBackOffAmount(Time step) => from x in Context from y in put(x.With(Global: x.Global.With(BackoffAmount: step), Pause: step)) select y; /// <summary> /// Pauses the Process for a fixed amount of time /// </summary> /// <param name="duration">Duration of the pause before /// resuming</param> /// <returns>Strategy computation as a State monad</returns> public static State<StrategyContext, Unit> Pause(Time duration) => from x in Context from y in put(x.With(Pause: duration)) select y; /// <summary> /// Resets the global (to the Process) state. This wipes out things like /// the current retries counter, the time since the last failure, etc. /// </summary> public static State<StrategyContext, Unit> Reset => from x in Context from y in put(x.With(Global: StrategyState.Empty)) select y; /// <summary> /// Maps the global (to the Process) state. /// </summary> public static State<StrategyContext, Unit> MapGlobal(Func<StrategyState, StrategyState> map) => from x in Context from y in put(x.With(Global: map(x.Global))) select y; /// <summary> /// Identity function for the strategy state monad. Use when you /// want a no-op /// </summary> public static State<StrategyContext, Unit> Identity => state => StateResult.Return(state, unit); /// <summary> /// Gives the strategy a behaviour that will only fail N times before /// forcing the Process to stop /// </summary> /// <param name="Count">Number of times to retry</param> /// <returns>Strategy computation as a State monad</returns> public static State<StrategyContext, Unit> Retries(int Count) => from x in Context from y in x.Global.Failures >= Count ? SetDirective(Directive.Stop) : Identity select y; /// <summary> /// Gives the strategy a behaviour that will only fail N times before /// forcing the Process to stop. However if a time-peroid of Duration /// elapses, then the number of failures 'so far' is reset to zero. /// /// This behaviour allows something that's rapidly failing to shutdown, /// but will allow the occasional failure. /// </summary> /// <param name="Count">Number of times to retry</param> /// <param name="Duration">Time between failures</param> /// <returns>Strategy computation as a State monad</returns> public static State<StrategyContext, Unit> Retries(int Count, Time Duration) => from x in Context let now = DateTime.UtcNow let expired = (Time)(now - x.Global.LastFailure) > Duration let failures = x.Global.Failures from y in expired ? Reset : failures >= Count ? SetDirective(Directive.Stop) : Identity select y; /// <summary> /// Applies a strategy that causes the Process to 'back off'. That is it will /// be paused for an amount of time before it can continue doing other operations. /// </summary> /// <param name="Min">Minimum back-off time</param> /// <param name="Max">Maximum back-off time; once this point is reached the Process /// will stop for good</param> /// <param name="Step">The amount to add to the current back-off time for each failure. /// That allows for the steps to grow gradually larger as the Process keeps failing</param> /// <returns>Strategy computation as a State monad</returns> public static State<StrategyContext, Unit> Backoff(Time Min, Time Max, Time Step) => from x in Context let current = x.Global.Failures < 2 ? Min : (x.Global.BackoffAmount + Step).Max(Min) from y in current > Max ? SetDirective(Directive.Stop) : SetBackOffAmount(current) select y; /// <summary> /// Applies a strategy that causes the Process to 'back off' for a fixed amount of /// time. That is it will be paused for an amount of time before it can continue /// doing other operations. This strategy never causes a Process to be stopped. /// </summary> /// <param name="Duration">Back-off time period</param> /// <returns>Strategy computation as a State monad</returns> public static State<StrategyContext, Unit> Backoff(Time Duration) => Backoff(Duration, Double.MaxValue*seconds, 0*seconds); /// <summary> /// Increase the failure count state /// </summary> public static readonly State<StrategyContext, Unit> IncFailureCount = MapGlobal(g => g.With(Failures: g.Failures + 1)); /// <summary> /// Reset the failure count state to zero and set LastFailure to max-value /// </summary> public static readonly State<StrategyContext, Unit> ResetFailureCount = MapGlobal(g => g.With(Failures: 0, LastFailure: DateTime.MaxValue)); /// <summary> /// Set the failure count to 1 and set LastFailure to UtcNow /// </summary> public static readonly State<StrategyContext, Unit> FailedOnce = MapGlobal(g => g.With(Failures: 1, LastFailure: DateTime.UtcNow)); /// <summary> /// Always return this Directive in the final StrategyDecision /// </summary> /// <param name="directive">Directive to return</param> /// <returns>Strategy computation as a State monad</returns> public static State<StrategyContext, Unit> Always(Directive directive) => Match(Otherwise(directive)); /// <summary> /// Match a range of State computations that take the Exception that caused /// the failure and map it to an Optional Directive. The first computation to /// return a Some(Directive) will succeed /// </summary> /// <param name="directives">Directive maps</param> /// <returns>Strategy computation as a State monad</returns> public static State<StrategyContext, Unit> Match(params State<Exception, Option<Directive>>[] directives) => state => StateResult.Return( state.With( Directive: choose(directives.Concat(ProcessSetting.StandardDirectives) .ToArray())(state.Exception).Value), unit); /// <summary> /// Match a range of State computations that take the currently selected /// Directive and map it to an Optional MessageDirective. The first computation /// to return a Some(MessageDirective) will succeed. If a Directive hasn't been /// chosen by the time this is invoked then RestartNow is used by default. /// </summary> /// <param name="directives">Directive maps</param> /// <returns>Strategy computation as a State monad</returns> public static State<StrategyContext, Unit> Redirect(params State<Directive, Option<MessageDirective>>[] directives) => state => StateResult.Return( state.With(MessageDirective: choose(directives)(state.Directive.IfNone(Directive.Restart)).Value), unit ); /// <summary> /// Provides a message redirection strategy that always uses the same MessageDirective /// regardless of the Directive provided. /// </summary> /// <param name="defaultDirective">Default message directive</param> /// <returns>Strategy computation as a State monad</returns> public static State<StrategyContext, Unit> Redirect(MessageDirective defaultDirective) => Redirect(Otherwise(defaultDirective)); /// <summary> /// Used within the Strategy.Match function to match an Exception to a Directive. /// Use the function's generic type to specify the type of Exception to match. /// </summary> /// <typeparam name="TException">Type of Exception to match</typeparam> /// <param name="map">Map from the TException to a Directive</param> /// <returns>Strategy computation as a State monad</returns> public static State<Exception, Option<Directive>> With<TException>(Func<TException, Directive> map) where TException : Exception => from ex in get<Exception>() let typeMatch = typeof(TException).GetTypeInfo().IsAssignableFrom(ex.GetType().GetTypeInfo()) select typeMatch ? Some(map((TException)ex)) : None; /// <summary> /// Used within the Strategy.Match function to match an Exception to a Directive. /// Use the function's generic type to specify the type of Exception to match. /// </summary> /// <typeparam name="TException">Type of Exception to match</typeparam> /// <param name="map">Map from the TException to a Directive</param> /// <returns>Strategy computation as a State monad</returns> internal static State<Exception, Option<Directive>> With(Func<Exception, Directive> map, Type exceptionType) => from ex in get<Exception>() let typeMatch = exceptionType.GetTypeInfo().IsAssignableFrom(ex.GetType().GetTypeInfo()) select typeMatch ? Some(map(ex)) : None; /// <summary> /// Used within the Strategy.Match function to match an Exception to a Directive. /// Use the function's generic type to specify the type of Exception to match. /// </summary> /// <typeparam name="TException">Type of Exception to match</typeparam> /// <param name="directive">Directive to use if the Exception matches TException</param> /// <returns>Strategy computation as a State monad</returns> internal static State<Exception, Option<Directive>> With(Directive directive, Type exceptionType) => With(_ => directive, exceptionType); /// <summary> /// Used within the Strategy.Match function to match an Exception to a Directive. /// Use the function's generic type to specify the type of Exception to match. /// </summary> /// <typeparam name="TException">Type of Exception to match</typeparam> /// <param name="directive">Directive to use if the Exception matches TException</param> /// <returns>Strategy computation as a State monad</returns> public static State<Exception, Option<Directive>> With<TException>(Directive directive) where TException : Exception => With<TException>(_ => directive); /// <summary> /// Used within the Strategy.Match function to provide a default Directive if the /// Exception that caused the failure doesn't match any of the previous With clauses. /// </summary> /// <param name="map">Map from the Exception to a Directive</param> /// <returns>Strategy computation as a State monad</returns> public static State<Exception, Option<Directive>> Otherwise(Func<Exception, Directive> map) => from ex in get<Exception>() select (ex is ProcessKillException) || (ex is ProcessSetupException) ? None : Some(map(ex)); /// <summary> /// Used within the Strategy.Match function to provide a default Directive if the /// Exception that caused the failure doesn't match any of the previous With clauses. /// </summary> /// <param name="directive">Directive to use</param> /// <returns>Strategy computation as a State monad</returns> public static State<Exception, Option<Directive>> Otherwise(Directive directive) => Otherwise(_ => directive); public static State<Directive, Option<MessageDirective>> When<TDirective>(Func<TDirective, MessageDirective> map) where TDirective : Directive => from directive in get<Directive>() let typeMatch = typeof(TDirective).GetTypeInfo().IsAssignableFrom(directive.GetType().GetTypeInfo()) select typeMatch ? Some(map((TDirective)directive)) : None; internal static State<Directive, Option<MessageDirective>> When(Func<Directive, MessageDirective> map, Directive dir) => from directive in get<Directive>() let typeMatch = dir.GetType().GetTypeInfo().IsAssignableFrom(directive.GetType().GetTypeInfo()) select typeMatch ? Some(map(directive)) : None; public static State<Directive, Option<MessageDirective>> When<TDirective>(MessageDirective directive) where TDirective : Directive => When<TDirective>(_ => directive); internal static State<Directive, Option<MessageDirective>> When(MessageDirective directive, Directive dir) => When(_ => directive, dir); public static State<Directive, Option<MessageDirective>> Otherwise(Func<Directive, MessageDirective> map) => from directive in get<Directive>() select Some(map(directive)); public static State<Directive, Option<MessageDirective>> Otherwise(MessageDirective directive) => Otherwise(_ => directive); } }
49.94362
153
0.616006
[ "MIT" ]
jonny-novikov/language-ext
LanguageExt.Process/Strategy/Strategy.cs
16,833
C#
using System; using System.Linq; using System.Collections.Generic; using System.Runtime.InteropServices; using Torque3D.Engine; using Torque3D.Util; namespace Torque3D { public unsafe class ScriptObject : SimObject { public ScriptObject(bool pRegister = false) : base(pRegister) { } public ScriptObject(string pName, bool pRegister = false) : this(false) { Name = pName; if (pRegister) registerObject(); } public ScriptObject(string pName, string pParent, bool pRegister = false) : this(pName, pRegister) { CopyFrom(Sim.FindObject<SimObject>(pParent)); } public ScriptObject(string pName, SimObject pParent, bool pRegister = false) : this(pName, pRegister) { CopyFrom(pParent); } public ScriptObject(SimObject pObj) : base(pObj) { } public ScriptObject(IntPtr pObjPtr) : base(pObjPtr) { } protected override void CreateSimObjectPtr() { ObjectPtr = InternalUnsafeMethods.ScriptObject_create(); } #region UnsafeNativeMethods new internal struct InternalUnsafeMethods { [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate IntPtr _ScriptObject_create(); private static _ScriptObject_create _ScriptObject_createFunc; internal static IntPtr ScriptObject_create() { if (_ScriptObject_createFunc == null) { _ScriptObject_createFunc = (_ScriptObject_create)Marshal.GetDelegateForFunctionPointer(Torque3D.DllLoadUtils.GetProcAddress(Torque3D.Torque3DLibHandle, "fn_ScriptObject_create"), typeof(_ScriptObject_create)); } return _ScriptObject_createFunc(); } } #endregion #region Functions #endregion #region Properties #endregion } }
21.613636
136
0.656677
[ "MIT" ]
lukaspj/T3D-CSharp-Tools
BaseLibrary/Torque3D/Engine/ScriptObject.cs
1,902
C#
using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Blazored.LocalStorage; using Syncfusion.Blazor; using Microsoft.Extensions.Hosting; using Common.Web; using Common.Application; using System.Net.Http; using System; using Blazored.SessionStorage; using System.Collections.Generic; namespace Demo.Server { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } public void ConfigureServices(IServiceCollection services) { services.AddScoped(sp => new HttpClient { BaseAddress = new Uri("https://localhost:5000/") }); services.AddSignalR(e => { e.MaximumReceiveMessageSize = 102400000; }); services.AddRazorPages(); services.AddServerSideBlazor(); services.AddHttpClient(); services.AddCommonServices(); services.AddScoped<LoginService>(); services.AddScoped<DataService>(); } public static void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseRouting(); app.UseEndpoints(endpoints => { endpoints.MapBlazorHub(); endpoints.MapFallbackToPage("/Host"); }); } } }
27.344262
106
0.627098
[ "Unlicense" ]
kristof12345/Common
Demo.Server/Startup.cs
1,670
C#
using Microsoft.AspNetCore.Mvc; using Sepes.Infrastructure.Service.Interface; using Sepes.RestApi.ApiEndpoints.Base; using System.Net.Mime; using System.Threading; using System.Threading.Tasks; namespace Sepes.RestApi.ApiEndpoints.StudiesDatasets { [Route("api/studies")] public class GetDatasetResources : EndpointBase { readonly IStudySpecificDatasetService _studySpecificDatasetService; public GetDatasetResources(IStudySpecificDatasetService studySpecificDatasetService) { _studySpecificDatasetService = studySpecificDatasetService; } [HttpGet("{studyId}/datasets/{datasetId}/resources")] [Consumes(MediaTypeNames.Application.Json)] public async Task<IActionResult> Handle(int studyId, int datasetId, CancellationToken cancellation = default) { var datasetResource = await _studySpecificDatasetService.GetDatasetResourcesAsync(studyId, datasetId, cancellation); return new JsonResult(datasetResource); } } }
35.862069
128
0.743269
[ "MIT" ]
equinor/sepes
src/Sepes.RestApi/ApiEndpoints/StudiesDatasets/GetDatasetResources.cs
1,042
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Threading.Tasks; using Azure.Core.TestFramework; using Azure.ResourceManager.Storage.Models; using Azure.ResourceManager.Storage.Tests.Helpers; using NUnit.Framework; namespace Azure.ResourceManager.Storage.Tests.Tests { [RunFrequency(RunTestFrequency.Manually)] public class StorageAccountTests : StorageTestsManagementClientBase { public StorageAccountTests(bool isAsync) : base(isAsync) { } [SetUp] public void ClearChallengeCacheforRecord() { if (Mode == RecordedTestMode.Record || Mode == RecordedTestMode.Playback) { Initialize(); } } [TearDown] public async Task CleanupResourceGroup() { await CleanupResourceGroupsAsync(); } [Test] public async Task StorageAccountCreateTest() { string rgname = await CreateResourceGroupAsync(); string accountName = Recording.GenerateAssetName("sto"); string accountName1 = Recording.GenerateAssetName("sto"); StorageAccount account = await _CreateStorageAccountAsync(rgname, accountName); VerifyAccountProperties(account, true); //Make sure a second create returns immediately account = await _CreateStorageAccountAsync(rgname, accountName); VerifyAccountProperties(account, true); //Create storage account with only required params account = await _CreateStorageAccountAsync(rgname, accountName1); VerifyAccountProperties(account, false); } [Test] public async Task StorageAccountCreateWithEncryptionTest() { //Create resource group string rgname = await CreateResourceGroupAsync(); string accountName = Recording.GenerateAssetName("sto"); //Create storage account StorageAccountCreateParameters parameters = GetDefaultStorageAccountParameters(); parameters.Encryption = new Encryption(KeySource.MicrosoftStorage) { Services = new EncryptionServices { Blob = new EncryptionService { Enabled = true }, File = new EncryptionService { Enabled = true } } }; StorageAccount account = await _CreateStorageAccountAsync(rgname, accountName, parameters); VerifyAccountProperties(account, true); //Verify encryption settings Assert.NotNull(account.Encryption); Assert.NotNull(account.Encryption.Services.Blob); Assert.True(account.Encryption.Services.Blob.Enabled); Assert.NotNull(account.Encryption.Services.Blob.LastEnabledTime); Assert.NotNull(account.Encryption.Services.File); Assert.NotNull(account.Encryption.Services.File.Enabled); Assert.NotNull(account.Encryption.Services.File.LastEnabledTime); if (null != account.Encryption.Services.Table) { if (account.Encryption.Services.Table.Enabled.HasValue) { Assert.False(account.Encryption.Services.Table.LastEnabledTime.HasValue); } } if (null != account.Encryption.Services.Queue) { if (account.Encryption.Services.Queue.Enabled.HasValue) { Assert.False(account.Encryption.Services.Queue.LastEnabledTime.HasValue); } } } [Test] public async Task StorageAccountCreateWithAccessTierTest() { //Create resource group string rgname = await CreateResourceGroupAsync(); string accountName = Recording.GenerateAssetName("sto"); string accountName1 = Recording.GenerateAssetName("sto"); //Create storage account StorageAccountCreateParameters parameters = GetDefaultStorageAccountParameters(kind: Kind.BlobStorage); parameters.AccessTier = AccessTier.Hot; StorageAccount account = await _CreateStorageAccountAsync(rgname, accountName, parameters); VerifyAccountProperties(account, false); Assert.AreEqual(AccessTier.Hot, account.AccessTier); Assert.AreEqual(Kind.BlobStorage, account.Kind); //Create storage account with cool parameters = GetDefaultStorageAccountParameters(kind: Kind.BlobStorage); parameters.AccessTier = AccessTier.Cool; account = await _CreateStorageAccountAsync(rgname, accountName1, parameters); VerifyAccountProperties(account, false); Assert.AreEqual(AccessTier.Cool, account.AccessTier); Assert.AreEqual(Kind.BlobStorage, account.Kind); } [Test] public async Task StorageAccountBeginCreateTest() { //Create resource group string rgname = await CreateResourceGroupAsync(); string accountName = Recording.GenerateAssetName("sto"); //Create storage account await _CreateStorageAccountAsync(rgname, accountName); } [Test] public async Task StorageAccountDeleteTest() { //Create resource group string rgname = await CreateResourceGroupAsync(); //Delete an account which does not exist await DeleteStorageAccountAsync(rgname, "missingaccount"); //Create storage account string accountName = await CreateStorageAccount(AccountsClient, rgname, Recording); //Delete an account await DeleteStorageAccountAsync(rgname, accountName); //Delete an account which was just deleted await DeleteStorageAccountAsync(rgname, accountName); } [Test] public async Task StorageAccountGetStandardTest() { //Create resource group string rgname = await CreateResourceGroupAsync(); string accountName = Recording.GenerateAssetName("sto"); string accountName1 = Recording.GenerateAssetName("sto"); string accountName2 = Recording.GenerateAssetName("sto"); string accountName3 = Recording.GenerateAssetName("sto"); // Create and get a LRS storage account StorageAccountCreateParameters parameters = GetDefaultStorageAccountParameters(sku: new Sku(SkuName.StandardLRS)); await _CreateStorageAccountAsync(rgname, accountName, parameters); StorageAccount account = await WaitToGetAccountSuccessfullyAsync(rgname, accountName); VerifyAccountProperties(account, false); // Create and get a GRS storage account parameters = GetDefaultStorageAccountParameters(sku: new Sku(SkuName.StandardGRS)); await _CreateStorageAccountAsync(rgname, accountName1, parameters); account = await WaitToGetAccountSuccessfullyAsync(rgname, accountName1); VerifyAccountProperties(account, true); // Create and get a RAGRS storage account parameters = GetDefaultStorageAccountParameters(sku: new Sku(SkuName.StandardRagrs)); await _CreateStorageAccountAsync(rgname, accountName2, parameters); account = await WaitToGetAccountSuccessfullyAsync(rgname, accountName2); VerifyAccountProperties(account, false); // Create and get a ZRS storage account parameters = GetDefaultStorageAccountParameters(sku: new Sku(SkuName.StandardZRS)); await _CreateStorageAccountAsync(rgname, accountName3, parameters); account = await WaitToGetAccountSuccessfullyAsync(rgname, accountName3); VerifyAccountProperties(account, false); } [Test] public async Task StorageAccountGetBlobTest() { //Create resource group string rgname = await CreateResourceGroupAsync(); string accountName = Recording.GenerateAssetName("sto"); string accountName1 = Recording.GenerateAssetName("sto"); string accountName2 = Recording.GenerateAssetName("sto"); // Create and get a blob LRS storage account StorageAccountCreateParameters parameters = GetDefaultStorageAccountParameters(sku: new Sku(SkuName.StandardLRS), kind: Kind.BlobStorage); parameters.AccessTier = AccessTier.Hot; await _CreateStorageAccountAsync(rgname, accountName, parameters); StorageAccount account = await WaitToGetAccountSuccessfullyAsync(rgname, accountName); VerifyAccountProperties(account, false); // Create and get a blob GRS storage account parameters = GetDefaultStorageAccountParameters(sku: new Sku(SkuName.StandardGRS), kind: Kind.BlobStorage); parameters.AccessTier = AccessTier.Hot; await _CreateStorageAccountAsync(rgname, accountName1, parameters); account = await WaitToGetAccountSuccessfullyAsync(rgname, accountName1); VerifyAccountProperties(account, false); // Create and get a blob RAGRS storage account parameters = GetDefaultStorageAccountParameters(sku: new Sku(SkuName.StandardRagrs), kind: Kind.BlobStorage); parameters.AccessTier = AccessTier.Hot; await _CreateStorageAccountAsync(rgname, accountName2, parameters); account = await WaitToGetAccountSuccessfullyAsync(rgname, accountName2); VerifyAccountProperties(account, false); } [Test] public async Task StorageAccountGetPremiumTest() { //Create resource group string rgname = await CreateResourceGroupAsync(); string accountName = Recording.GenerateAssetName("sto"); // Create and get a Premium LRS storage account StorageAccountCreateParameters parameters = GetDefaultStorageAccountParameters(sku: new Sku(SkuName.StandardLRS), kind: Kind.BlobStorage); parameters.AccessTier = AccessTier.Hot; await _CreateStorageAccountAsync(rgname, accountName, parameters); StorageAccount account = await WaitToGetAccountSuccessfullyAsync(rgname, accountName); VerifyAccountProperties(account, false); } [Test] public async Task StorageAccountListByResourceGroupTest() { //Create resource group string rgname = await CreateResourceGroupAsync(); //List by resource group AsyncPageable<StorageAccount> accountlistAP = AccountsClient.ListByResourceGroupAsync(rgname); List<StorageAccount> accountlist = await accountlistAP.ToEnumerableAsync(); Assert.False(accountlist.Any()); // Create storage accounts string accountName1 = await CreateStorageAccount(AccountsClient, rgname, Recording); string accountName2 = await CreateStorageAccount(AccountsClient, rgname, Recording); accountlistAP = AccountsClient.ListByResourceGroupAsync(rgname); accountlist = await accountlistAP.ToEnumerableAsync(); Assert.AreEqual(2, accountlist.Count()); foreach (StorageAccount account in accountlist) { VerifyAccountProperties(account, true); } } [Test] public async Task StorageAccountListWithEncryptionTest() { //Create resource group string rgname = await CreateResourceGroupAsync(); string accountName = Recording.GenerateAssetName("sto"); // Create storage account StorageAccountCreateParameters parameters = GetDefaultStorageAccountParameters(); parameters.Encryption = new Encryption(KeySource.MicrosoftStorage) { Services = new EncryptionServices { Blob = new EncryptionService { Enabled = true }, File = new EncryptionService { Enabled = true } } }; await _CreateStorageAccountAsync(rgname, accountName, parameters); // List account and verify AsyncPageable<StorageAccount> accounts = AccountsClient.ListByResourceGroupAsync(rgname); List<StorageAccount> accountlist = await accounts.ToEnumerableAsync(); Assert.AreEqual(1, accountlist.Count()); StorageAccount account = accountlist.ToArray()[0]; VerifyAccountProperties(account, true); Assert.NotNull(account.Encryption); Assert.NotNull(account.Encryption.Services.Blob); Assert.True(account.Encryption.Services.Blob.Enabled); Assert.NotNull(account.Encryption.Services.Blob.LastEnabledTime); Assert.NotNull(account.Encryption.Services.File); Assert.True(account.Encryption.Services.File.Enabled); Assert.NotNull(account.Encryption.Services.File.LastEnabledTime); if (null != account.Encryption.Services.Table) { if (account.Encryption.Services.Table.Enabled.HasValue) { Assert.False(account.Encryption.Services.Table.LastEnabledTime.HasValue); } } if (null != account.Encryption.Services.Queue) { if (account.Encryption.Services.Queue.Enabled.HasValue) { Assert.False(account.Encryption.Services.Queue.LastEnabledTime.HasValue); } } } [Test] public async Task StorageAccountListBySubscriptionTest() { // Create resource group and storage account string rgname1 = await CreateResourceGroupAsync(); string accountName1 = await CreateStorageAccount(AccountsClient, rgname1, Recording); // Create different resource group and storage account string rgname2 = await CreateResourceGroupAsync(); string accountName2 = await CreateStorageAccount(AccountsClient, rgname2, Recording); AsyncPageable<StorageAccount> accountlist = AccountsClient.ListAsync(); List<StorageAccount> accountlists = accountlist.ToEnumerableAsync().Result; StorageAccount account1 = accountlists.First( t => StringComparer.OrdinalIgnoreCase.Equals(t.Name, accountName1)); VerifyAccountProperties(account1, true); StorageAccount account2 = accountlists.First( t => StringComparer.OrdinalIgnoreCase.Equals(t.Name, accountName2)); VerifyAccountProperties(account2, true); } [Test] public async Task StorageAccountListKeysTest() { //Create resource group string rgname = await CreateResourceGroupAsync(); // Create storage account string accountName = await CreateStorageAccount(AccountsClient, rgname, Recording); // List keys Response<StorageAccountListKeysResult> keys = await AccountsClient.ListKeysAsync(rgname, accountName); Assert.NotNull(keys); // Validate Key1 StorageAccountKey key1 = keys.Value.Keys.First( t => StringComparer.OrdinalIgnoreCase.Equals(t.KeyName, "key1")); Assert.NotNull(key1); Assert.AreEqual(KeyPermission.Full, key1.Permissions); Assert.NotNull(key1.Value); // Validate Key2 StorageAccountKey key2 = keys.Value.Keys.First( t => StringComparer.OrdinalIgnoreCase.Equals(t.KeyName, "key2")); Assert.NotNull(key2); Assert.AreEqual(KeyPermission.Full, key2.Permissions); Assert.NotNull(key2.Value); } [Test] public async Task StorageAccountRegenerateKeyTest() { //Create resource group string rgname = await CreateResourceGroupAsync(); // Create storage account string accountName = await CreateStorageAccount(AccountsClient, rgname, Recording); // List keys Response<StorageAccountListKeysResult> keys = await AccountsClient.ListKeysAsync(rgname, accountName); Assert.NotNull(keys); StorageAccountKey key2 = keys.Value.Keys.First( t => StringComparer.OrdinalIgnoreCase.Equals(t.KeyName, "key2")); Assert.NotNull(key2); // Regenerate keys and verify that keys change StorageAccountRegenerateKeyParameters keyParameters = new StorageAccountRegenerateKeyParameters("key2"); Response<StorageAccountListKeysResult> regenKeys = await AccountsClient.RegenerateKeyAsync(rgname, accountName, keyParameters); StorageAccountKey key2Regen = regenKeys.Value.Keys.First( t => StringComparer.OrdinalIgnoreCase.Equals(t.KeyName, "key2")); Assert.NotNull(key2Regen); // Validate key was regenerated Assert.AreNotEqual(key2.Value, key2Regen.Value); } [Test] public async Task StorageAccountRevokeUserDelegationKeysTest() { //Create resource group string rgname = await CreateResourceGroupAsync(); // Create storage account string accountName = await CreateStorageAccount(AccountsClient, rgname, Recording); // Revoke User DelegationKeys await AccountsClient.RevokeUserDelegationKeysAsync(rgname, accountName); } [Test] public async Task StorageAccountCheckNameTest() { //Create resource group string rgname = await CreateResourceGroupAsync(); string accountName = Recording.GenerateAssetName("sto"); // Check valid name StorageAccountCheckNameAvailabilityParameters storageAccountCheckNameAvailabilityParameters = new StorageAccountCheckNameAvailabilityParameters(accountName); Response<CheckNameAvailabilityResult> checkNameRequest = await AccountsClient.CheckNameAvailabilityAsync(storageAccountCheckNameAvailabilityParameters); Assert.True(checkNameRequest.Value.NameAvailable); Assert.Null(checkNameRequest.Value.Reason); Assert.Null(checkNameRequest.Value.Message); // Check invalid name storageAccountCheckNameAvailabilityParameters = new StorageAccountCheckNameAvailabilityParameters("CAPS"); checkNameRequest = await AccountsClient.CheckNameAvailabilityAsync(storageAccountCheckNameAvailabilityParameters); Assert.False(checkNameRequest.Value.NameAvailable); Assert.AreEqual(Reason.AccountNameInvalid, checkNameRequest.Value.Reason); Assert.AreEqual("CAPS is not a valid storage account name. Storage account name must be between 3 and 24 " + "characters in length and use numbers and lower-case letters only.", checkNameRequest.Value.Message); // Check name of account that already exists string accountName1 = await CreateStorageAccount(AccountsClient, rgname, Recording); storageAccountCheckNameAvailabilityParameters = new StorageAccountCheckNameAvailabilityParameters(accountName1); checkNameRequest = await AccountsClient.CheckNameAvailabilityAsync(storageAccountCheckNameAvailabilityParameters); Assert.False(checkNameRequest.Value.NameAvailable); Assert.AreEqual(Reason.AlreadyExists, checkNameRequest.Value.Reason); Assert.AreEqual("The storage account named " + accountName1 + " is already taken.", checkNameRequest.Value.Message); } [Test] public async Task StorageAccountUpdateWithCreateTest() { //Create resource group string rgname = await CreateResourceGroupAsync(); // Create storage account string accountName = await CreateStorageAccount(AccountsClient, rgname, Recording); // Update storage account type StorageAccountCreateParameters parameters = GetDefaultStorageAccountParameters(sku: new Sku(SkuName.StandardLRS)); StorageAccount account = await _CreateStorageAccountAsync(rgname, accountName, parameters); Assert.AreEqual(SkuName.StandardLRS, account.Sku.Name); // Validate Response<StorageAccount> accountProerties = await WaitToGetAccountSuccessfullyAsync(rgname, accountName); Assert.AreEqual(SkuName.StandardLRS, accountProerties.Value.Sku.Name); // Update storage tags parameters.Tags = new Dictionary<string, string> { { "key3", "value3" }, { "key4", "value4" }, { "key5", "value6" } }; account = await _CreateStorageAccountAsync(rgname, accountName, parameters); Assert.AreEqual(account.Tags.Count, parameters.Tags.Count); // Validate accountProerties = await WaitToGetAccountSuccessfullyAsync(rgname, accountName); Assert.AreEqual(accountProerties.Value.Tags.Count, parameters.Tags.Count); // Update storage encryption parameters.Encryption = new Encryption(KeySource.MicrosoftStorage) { Services = new EncryptionServices { Blob = new EncryptionService { Enabled = true }, File = new EncryptionService { Enabled = true } } }; account = await _CreateStorageAccountAsync(rgname, accountName, parameters); Assert.NotNull(account.Encryption); // Validate accountProerties = await WaitToGetAccountSuccessfullyAsync(rgname, accountName); Assert.NotNull(accountProerties.Value.Encryption); Assert.NotNull(accountProerties.Value.Encryption.Services.Blob); Assert.True(accountProerties.Value.Encryption.Services.Blob.Enabled); Assert.NotNull(accountProerties.Value.Encryption.Services.Blob.LastEnabledTime); Assert.NotNull(accountProerties.Value.Encryption.Services.File); Assert.True(accountProerties.Value.Encryption.Services.File.Enabled); Assert.NotNull(accountProerties.Value.Encryption.Services.File.LastEnabledTime); if (null != accountProerties.Value.Encryption.Services.Table) { if (accountProerties.Value.Encryption.Services.Table.Enabled.HasValue) { Assert.False(accountProerties.Value.Encryption.Services.Table.LastEnabledTime.HasValue); } } if (null != accountProerties.Value.Encryption.Services.Queue) { if (accountProerties.Value.Encryption.Services.Queue.Enabled.HasValue) { Assert.False(accountProerties.Value.Encryption.Services.Queue.LastEnabledTime.HasValue); } } // Update storage custom domains parameters = GetDefaultStorageAccountParameters(); parameters.CustomDomain = new CustomDomain("foo.example.com") { UseSubDomainName = true }; try { await AccountsClient.StartCreateAsync(rgname, accountName, parameters); Assert.True(false, "This request should fail with the below code."); } catch (RequestFailedException ex) { Assert.AreEqual((int)HttpStatusCode.Conflict, ex.Status); Assert.True(ex.Message != null && ex.Message.Contains("The custom domain name could not be verified. CNAME mapping from foo.example.com to")); } } [Test] public async Task StorageAccountUpdateTest() { //Create resource group string rgname = await CreateResourceGroupAsync(); // Create storage account string accountName = await CreateStorageAccount(AccountsClient, rgname, Recording); // Update storage account type StorageAccountUpdateParameters parameters = new StorageAccountUpdateParameters() { Sku = new Sku(SkuName.StandardLRS), }; StorageAccount account = await UpdateStorageAccountAsync(rgname, accountName, parameters); Assert.AreEqual(SkuName.StandardLRS, account.Sku.Name); // Validate Response<StorageAccount> accountProerties = await WaitToGetAccountSuccessfullyAsync(rgname, accountName); Assert.AreEqual(SkuName.StandardLRS, accountProerties.Value.Sku.Name); // Update storage tags parameters.Tags = new Dictionary<string, string> { { "key3", "value3" }, { "key4", "value4" }, { "key5", "value6" } }; account = await UpdateStorageAccountAsync(rgname, accountName, parameters); Assert.AreEqual(account.Tags.Count, parameters.Tags.Count); // Validate accountProerties = await WaitToGetAccountSuccessfullyAsync(rgname, accountName); Assert.AreEqual(accountProerties.Value.Tags.Count, parameters.Tags.Count); // Update storage encryption parameters.Encryption = new Encryption(KeySource.MicrosoftStorage) { Services = new EncryptionServices { Blob = new EncryptionService { Enabled = true }, File = new EncryptionService { Enabled = true } } }; account = await UpdateStorageAccountAsync(rgname, accountName, parameters); Assert.NotNull(account.Encryption); // Validate accountProerties = await WaitToGetAccountSuccessfullyAsync(rgname, accountName); Assert.NotNull(accountProerties.Value.Encryption); Assert.NotNull(accountProerties.Value.Encryption.Services.Blob); Assert.True(accountProerties.Value.Encryption.Services.Blob.Enabled); Assert.NotNull(accountProerties.Value.Encryption.Services.Blob.LastEnabledTime); Assert.NotNull(accountProerties.Value.Encryption.Services.File); Assert.True(accountProerties.Value.Encryption.Services.File.Enabled); Assert.NotNull(accountProerties.Value.Encryption.Services.File.LastEnabledTime); if (null != accountProerties.Value.Encryption.Services.Table) { if (accountProerties.Value.Encryption.Services.Table.Enabled.HasValue) { Assert.False(accountProerties.Value.Encryption.Services.Table.LastEnabledTime.HasValue); } } if (null != accountProerties.Value.Encryption.Services.Queue) { if (accountProerties.Value.Encryption.Services.Queue.Enabled.HasValue) { Assert.False(accountProerties.Value.Encryption.Services.Queue.LastEnabledTime.HasValue); } } // Update storage custom domains parameters = new StorageAccountUpdateParameters { CustomDomain = new CustomDomain("foo.example.com") { UseSubDomainName = true } }; try { await UpdateStorageAccountAsync(rgname, accountName, parameters); Assert.True(false, "This request should fail with the below code."); } catch (RequestFailedException ex) { Assert.AreEqual((int)HttpStatusCode.Conflict, ex.Status); Assert.True(ex.Message != null && ex.Message.Contains("The custom domain name could not be verified. CNAME mapping from foo.example.com to")); } } [Test] public async Task StorageAccountUpdateMultipleTest() { //Create resource group string rgname = await CreateResourceGroupAsync(); // Create storage account string accountName = await CreateStorageAccount(AccountsClient, rgname, Recording); // Update storage account type StorageAccountUpdateParameters parameters = new StorageAccountUpdateParameters() { Sku = new Sku(SkuName.StandardLRS), Tags = new Dictionary<string, string> { { "key3", "value3" }, { "key4", "value4" }, { "key5", "value6" } } }; StorageAccount account = await UpdateStorageAccountAsync(rgname, accountName, parameters); Assert.AreEqual(SkuName.StandardLRS, account.Sku.Name); Assert.AreEqual(account.Tags.Count, parameters.Tags.Count); // Validate Response<StorageAccount> accountProerties = await WaitToGetAccountSuccessfullyAsync(rgname, accountName); Assert.AreEqual(SkuName.StandardLRS, accountProerties.Value.Sku.Name); Assert.AreEqual(accountProerties.Value.Tags.Count, parameters.Tags.Count); } [Test] public async Task StorageAccountLocationUsageTest() { // Query usage string Location = DefaultLocation; AsyncPageable<Usage> usages = UsagesClient.ListByLocationAsync(Location); List<Usage> usagelist = await usages.ToEnumerableAsync(); Assert.AreEqual(1, usagelist.Count()); Assert.AreEqual(UsageUnit.Count, usagelist.First().Unit); Assert.NotNull(usagelist.First().CurrentValue); Assert.AreEqual(250, usagelist.First().Limit); Assert.NotNull(usagelist.First().Name); Assert.AreEqual("StorageAccounts", usagelist.First().Name.Value); Assert.AreEqual("Storage Accounts", usagelist.First().Name.LocalizedValue); } [Test] [Ignore("Track2: The function of 'ResourceProviderOperationDetails' is not found in trach2 Management.Resource")] public void StorageAccountGetOperationsTest() { //var handler = new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK }; //using (MockContext context = MockContext.Start(this.GetType())) //{ // var resourcesClient = GetResourceManagementClient(context, handler); // var ops = resourcesClient.ResourceProviderOperationDetails.List("Microsoft.Storage", "2015-06-15"); // Assert.True(ops.Count() > 1); //} } [Test] public async Task StorageAccountListAccountSASTest() { //Create resource group string rgname = await CreateResourceGroupAsync(); string accountName = Recording.GenerateAssetName("sto"); // Create storage account await _CreateStorageAccountAsync(rgname, accountName); AccountSasParameters accountSasParameters = new AccountSasParameters(services: "bftq", resourceTypes: "sco", permissions: "rdwlacup", sharedAccessExpiryTime: Recording.UtcNow.AddHours(1)) { Protocols = HttpProtocol.HttpsHttp, SharedAccessStartTime = Recording.UtcNow, KeyToSign = "key1" }; Response<ListAccountSasResponse> result = await AccountsClient.ListAccountSASAsync(rgname, accountName, accountSasParameters); AccountSasParameters resultCredentials = ParseAccountSASToken(result.Value.AccountSasToken); Assert.AreEqual(accountSasParameters.Services, resultCredentials.Services); Assert.AreEqual(accountSasParameters.ResourceTypes, resultCredentials.ResourceTypes); Assert.AreEqual(accountSasParameters.Permissions, resultCredentials.Permissions); Assert.AreEqual(accountSasParameters.Protocols, resultCredentials.Protocols); Assert.NotNull(accountSasParameters.SharedAccessStartTime); Assert.NotNull(accountSasParameters.SharedAccessExpiryTime); } [Test] public async Task StorageAccountListAccountSASWithDefaultProperties() { //Create resource group string rgname = await CreateResourceGroupAsync(); string accountName = Recording.GenerateAssetName("sto"); // Create storage account await _CreateStorageAccountAsync(rgname, accountName); // Test for default values of sas credentials. AccountSasParameters accountSasParameters = new AccountSasParameters(services: "b", resourceTypes: "sco", permissions: "rl", sharedAccessExpiryTime: Recording.UtcNow.AddHours(1)); Response<ListAccountSasResponse> result = await AccountsClient.ListAccountSASAsync(rgname, accountName, accountSasParameters); AccountSasParameters resultCredentials = ParseAccountSASToken(result.Value.AccountSasToken); Assert.AreEqual(accountSasParameters.Services, resultCredentials.Services); Assert.AreEqual(accountSasParameters.ResourceTypes, resultCredentials.ResourceTypes); Assert.AreEqual(accountSasParameters.Permissions, resultCredentials.Permissions); Assert.NotNull(accountSasParameters.SharedAccessExpiryTime); } [Test] public async Task StorageAccountListAccountSASWithMissingProperties() { //Create resource group string rgname = await CreateResourceGroupAsync(); string accountName = Recording.GenerateAssetName("sto"); // Create storage account await _CreateStorageAccountAsync(rgname, accountName); // Test for default values of sas credentials. AccountSasParameters accountSasParameters = new AccountSasParameters(services: "b", resourceTypes: "sco", permissions: "rl", sharedAccessExpiryTime: Recording.UtcNow.AddHours(-1)); try { Response<ListAccountSasResponse> result = await AccountsClient.ListAccountSASAsync(rgname, accountName, accountSasParameters); AccountSasParameters resultCredentials = ParseAccountSASToken(result.Value.AccountSasToken); } catch (Exception ex) { Assert.True(ex.Message != null && ex.Message.Contains("Values for request parameters are invalid: signedExpiry.")); return; } throw new Exception("AccountSasToken shouldn't be returned without SharedAccessExpiryTime"); } [Test] public async Task StorageAccountListServiceSASTest() { //Create resource group string rgname = await CreateResourceGroupAsync(); string accountName = Recording.GenerateAssetName("sto"); // Create storage account await _CreateStorageAccountAsync(rgname, accountName); string canonicalizedResourceParameter = "/blob/" + accountName + "/music"; ServiceSasParameters serviceSasParameters = new ServiceSasParameters(canonicalizedResource: canonicalizedResourceParameter) { Resource = "c", Permissions = "rdwlacup", Protocols = HttpProtocol.HttpsHttp, SharedAccessStartTime = Recording.UtcNow, SharedAccessExpiryTime = Recording.UtcNow.AddHours(1), KeyToSign = "key1" }; Task<Response<ListServiceSasResponse>> result = AccountsClient.ListServiceSASAsync(rgname, accountName, serviceSasParameters); ServiceSasParameters resultCredentials = ParseServiceSASToken(result.Result.Value.ServiceSasToken, canonicalizedResourceParameter); Assert.AreEqual(serviceSasParameters.Resource, resultCredentials.Resource); Assert.AreEqual(serviceSasParameters.Permissions, resultCredentials.Permissions); Assert.AreEqual(serviceSasParameters.Protocols, resultCredentials.Protocols); Assert.NotNull(serviceSasParameters.SharedAccessStartTime); Assert.NotNull(serviceSasParameters.SharedAccessExpiryTime); } [Test] public async Task StorageAccountListServiceSASWithDefaultProperties() { //Create resource group string rgname = await CreateResourceGroupAsync(); string accountName = Recording.GenerateAssetName("sto"); // Create storage account await _CreateStorageAccountAsync(rgname, accountName); // Test for default values of sas credentials. string canonicalizedResourceParameter = "/blob/" + accountName + "/music"; ServiceSasParameters serviceSasParameters = new ServiceSasParameters(canonicalizedResource: canonicalizedResourceParameter) { Resource = "c", Permissions = "rl", SharedAccessExpiryTime = Recording.UtcNow.AddHours(1), }; Response<ListServiceSasResponse> result = await AccountsClient.ListServiceSASAsync(rgname, accountName, serviceSasParameters); ServiceSasParameters resultCredentials = ParseServiceSASToken(result.Value.ServiceSasToken, canonicalizedResourceParameter); Assert.AreEqual(serviceSasParameters.Resource, resultCredentials.Resource); Assert.AreEqual(serviceSasParameters.Permissions, resultCredentials.Permissions); Assert.NotNull(serviceSasParameters.SharedAccessExpiryTime); } [Test] public async Task StorageAccountListServiceSASWithMissingProperties() { //Create resource group string rgname = await CreateResourceGroupAsync(); string accountName = Recording.GenerateAssetName("sto"); // Create storage account await _CreateStorageAccountAsync(rgname, accountName); // Test for default values of sas credentials. string canonicalizedResourceParameter = "/blob/" + accountName + "/music"; ServiceSasParameters serviceSasParameters = new ServiceSasParameters(canonicalizedResource: canonicalizedResourceParameter) { Resource = "b", Permissions = "rl" }; try { Response<ListServiceSasResponse> result = await AccountsClient.ListServiceSASAsync(rgname, accountName, serviceSasParameters); ServiceSasParameters resultCredentials = ParseServiceSASToken(result.Value.ServiceSasToken, canonicalizedResourceParameter); } catch (RequestFailedException ex) { Assert.True(ex.Message != null && ex.Message.Contains("Values for request parameters are invalid: signedExpiry.")); return; } throw new Exception("AccountSasToken shouldn't be returned without SharedAccessExpiryTime"); } [Test] public async Task StorageAccountUpdateEncryptionTest() { //Create resource group string rgname = await CreateResourceGroupAsync(); // Create storage account string accountName = await CreateStorageAccount(AccountsClient, rgname, Recording); // Update storage account type StorageAccountUpdateParameters parameters = new StorageAccountUpdateParameters { Sku = new Sku(SkuName.StandardLRS) }; StorageAccount account = await UpdateStorageAccountAsync(rgname, accountName, parameters); Assert.AreEqual(SkuName.StandardLRS, account.Sku.Name); // Validate account = await WaitToGetAccountSuccessfullyAsync(rgname, accountName); Assert.AreEqual(SkuName.StandardLRS, account.Sku.Name); // Update storage tags parameters = new StorageAccountUpdateParameters { Tags = new Dictionary<string, string> { {"key3","value3"}, {"key4","value4"}, {"key5","value6"} } }; account = await UpdateStorageAccountAsync(rgname, accountName, parameters); Assert.AreEqual(account.Tags.Count, parameters.Tags.Count); // Validate account = await WaitToGetAccountSuccessfullyAsync(rgname, accountName); Assert.AreEqual(account.Tags.Count, parameters.Tags.Count); // 1. Update storage encryption parameters = new StorageAccountUpdateParameters { Encryption = new Encryption(keySource: KeySource.MicrosoftStorage) { Services = new EncryptionServices { Blob = new EncryptionService { Enabled = true }, File = new EncryptionService { Enabled = true } } } }; account = await UpdateStorageAccountAsync(rgname, accountName, parameters); Assert.NotNull(account.Encryption); // Validate account = await WaitToGetAccountSuccessfullyAsync(rgname, accountName); Assert.NotNull(account.Encryption); Assert.NotNull(account.Encryption.Services.Blob); Assert.True(account.Encryption.Services.Blob.Enabled); Assert.NotNull(account.Encryption.Services.Blob.LastEnabledTime); Assert.NotNull(account.Encryption.Services.File); Assert.True(account.Encryption.Services.File.Enabled); Assert.NotNull(account.Encryption.Services.File.LastEnabledTime); // 2. Restore storage encryption parameters = new StorageAccountUpdateParameters { Encryption = new Encryption(keySource: KeySource.MicrosoftStorage) { Services = new EncryptionServices { Blob = new EncryptionService { Enabled = true }, File = new EncryptionService { Enabled = true } } } }; account = await UpdateStorageAccountAsync(rgname, accountName, parameters); Assert.NotNull(account.Encryption); // Validate account = await WaitToGetAccountSuccessfullyAsync(rgname, accountName); Assert.NotNull(account.Encryption); Assert.NotNull(account.Encryption.Services.Blob); Assert.True(account.Encryption.Services.Blob.Enabled); Assert.NotNull(account.Encryption.Services.Blob.LastEnabledTime); Assert.NotNull(account.Encryption.Services.File); Assert.True(account.Encryption.Services.File.Enabled); Assert.NotNull(account.Encryption.Services.File.LastEnabledTime); // 3. Remove file encryption service field. parameters = new StorageAccountUpdateParameters { Encryption = new Encryption(keySource: KeySource.MicrosoftStorage) { Services = new EncryptionServices { Blob = new EncryptionService { Enabled = true } } } }; account = await UpdateStorageAccountAsync(rgname, accountName, parameters); Assert.NotNull(account.Encryption); // Validate account = await WaitToGetAccountSuccessfullyAsync(rgname, accountName); Assert.NotNull(account.Encryption); Assert.NotNull(account.Encryption.Services.Blob); Assert.True(account.Encryption.Services.Blob.Enabled); Assert.NotNull(account.Encryption.Services.Blob.LastEnabledTime); Assert.NotNull(account.Encryption.Services.File); Assert.True(account.Encryption.Services.File.Enabled); Assert.NotNull(account.Encryption.Services.File.LastEnabledTime); } [Test] public async Task StorageAccountUpdateWithHttpsOnlyTest() { //Create resource group string rgname = await CreateResourceGroupAsync(); string accountName = Recording.GenerateAssetName("sto"); // Create storage account with hot StorageAccountCreateParameters parameters = GetDefaultStorageAccountParameters(); parameters.EnableHttpsTrafficOnly = false; StorageAccount account = await _CreateStorageAccountAsync(rgname, accountName, parameters); VerifyAccountProperties(account, false); Assert.False(account.EnableHttpsTrafficOnly); //Update storage account StorageAccountUpdateParameters parameter = new StorageAccountUpdateParameters { EnableHttpsTrafficOnly = true }; account = await UpdateStorageAccountAsync(rgname, accountName, parameter); VerifyAccountProperties(account, false); Assert.True(account.EnableHttpsTrafficOnly); //Update storage account parameter = new StorageAccountUpdateParameters { EnableHttpsTrafficOnly = false }; account = await UpdateStorageAccountAsync(rgname, accountName, parameter); VerifyAccountProperties(account, false); Assert.False(account.EnableHttpsTrafficOnly); } [Test] public async Task StorageAccountCreateWithHttpsOnlyTest() { //Create resource group string rgname = await CreateResourceGroupAsync(); string accountName = Recording.GenerateAssetName("sto"); string accountName1 = Recording.GenerateAssetName("sto"); // Create storage account with hot StorageAccountCreateParameters parameters = GetDefaultStorageAccountParameters(); parameters.EnableHttpsTrafficOnly = true; StorageAccount account = await _CreateStorageAccountAsync(rgname, accountName, parameters); VerifyAccountProperties(account, false); Assert.True(account.EnableHttpsTrafficOnly); // Create storage account with cool parameters.EnableHttpsTrafficOnly = false; account = await _CreateStorageAccountAsync(rgname, accountName1, parameters); VerifyAccountProperties(account, false); Assert.False(account.EnableHttpsTrafficOnly); } [Test] [Ignore("Track2: Need KeyVaultManagementClient")] public void StorageAccountCMKTest() { //var handler = new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK }; //using (MockContext context = MockContext.Start(this.GetType())) //{ // var resourcesClient = GetResourceManagementClient(context, handler); // var storageMgmtClient = GetStorageManagementClient(context, handler); // var keyVaultMgmtClient = GetKeyVaultManagementClient(context, handler); // var keyVaultClient = CreateKeyVaultClient(); // string accountName = TestUtilities.GenerateName("sto"); // var rgname = CreateResourceGroup(resourcesClient); // string vaultName = TestUtilities.GenerateName("keyvault"); // string keyName = TestUtilities.GenerateName("keyvaultkey"); // var parameters = GetDefaultStorageAccountParameters(); // parameters.Location = "centraluseuap"; // parameters.Identity = new Identity { }; // var account = storageMgmtClient.StorageAccounts.Create(rgname, accountName, parameters); // VerifyAccountProperties(account, false); // Assert.NotNull(account.Identity); // var accessPolicies = new List<Microsoft.Azure.Management.KeyVault.Models.AccessPolicyEntry>(); // accessPolicies.Add(new Microsoft.Azure.Management.KeyVault.Models.AccessPolicyEntry // { // TenantId = System.Guid.Parse(account.Identity.TenantId), // ObjectId = account.Identity.PrincipalId, // Permissions = new Microsoft.Azure.Management.KeyVault.Models.Permissions(new List<string> { "wrapkey", "unwrapkey" }) // }); // string servicePrincipalObjectId = GetServicePrincipalObjectId(); // accessPolicies.Add(new Microsoft.Azure.Management.KeyVault.Models.AccessPolicyEntry // { // TenantId = System.Guid.Parse(account.Identity.TenantId), // ObjectId = servicePrincipalObjectId, // Permissions = new Microsoft.Azure.Management.KeyVault.Models.Permissions(new List<string> { "all" }) // }); // var keyVault = keyVaultMgmtClient.Vaults.CreateOrUpdate(rgname, vaultName, new Microsoft.Azure.Management.KeyVault.Models.VaultCreateOrUpdateParameters // { // Location = account.Location, // Properties = new Microsoft.Azure.Management.KeyVault.Models.VaultProperties // { // TenantId = System.Guid.Parse(account.Identity.TenantId), // AccessPolicies = accessPolicies, // Sku = new Microsoft.Azure.Management.KeyVault.Models.Sku(Microsoft.Azure.Management.KeyVault.Models.SkuName.Standard), // EnabledForDiskEncryption = false, // EnabledForDeployment = false, // EnabledForTemplateDeployment = false // } // }); // var keyVaultKey = keyVaultClient.CreateKeyAsync(keyVault.Properties.VaultUri, keyName, JsonWebKeyType.Rsa, 2048, // JsonWebKeyOperation.AllOperations, new Microsoft.Azure.KeyVault.Models.KeyAttributes()).GetAwaiter().GetResult(); // // Enable encryption. // var updateParameters = new StorageAccountUpdateParameters // { // Encryption = new Encryption // { // Services = new EncryptionServices { Blob = new EncryptionService { Enabled = true }, File = new EncryptionService { Enabled = true } }, // KeySource = "Microsoft.Keyvault", // KeyVaultProperties = // new KeyVaultProperties // { // KeyName = keyVaultKey.KeyIdentifier.Name, // KeyVaultUri = keyVault.Properties.VaultUri, // KeyVersion = keyVaultKey.KeyIdentifier.Version // } // } // }; // account = storageMgmtClient.StorageAccounts.Update(rgname, accountName, updateParameters); // VerifyAccountProperties(account, false); // Assert.NotNull(account.Encryption); // Assert.True(account.Encryption.Services.Blob.Enabled); // Assert.True(account.Encryption.Services.File.Enabled); // Assert.Equal("Microsoft.Keyvault", account.Encryption.KeySource); // // Disable Encryption. // updateParameters = new StorageAccountUpdateParameters // { // Encryption = new Encryption // { // Services = new EncryptionServices { Blob = new EncryptionService { Enabled = true }, File = new EncryptionService { Enabled = true } }, // KeySource = "Microsoft.Storage" // } // }; // account = storageMgmtClient.StorageAccounts.Update(rgname, accountName, updateParameters); // VerifyAccountProperties(account, false); // Assert.NotNull(account.Encryption); // Assert.True(account.Encryption.Services.Blob.Enabled); // Assert.True(account.Encryption.Services.File.Enabled); // Assert.Equal("Microsoft.Storage", account.Encryption.KeySource); // updateParameters = new StorageAccountUpdateParameters // { // Encryption = new Encryption // { // Services = new EncryptionServices { Blob = new EncryptionService { Enabled = false }, File = new EncryptionService { Enabled = false } }, // KeySource = KeySource.MicrosoftStorage // } // }; // account = storageMgmtClient.StorageAccounts.Update(rgname, accountName, updateParameters); // VerifyAccountProperties(account, false); // Assert.Null(account.Encryption); //} } [Test] [Ignore("Track2: The constructor of OperationDisplay is internal")] public void StorageAccountOperationsTest() { //var handler = new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK }; //using (MockContext context = MockContext.Start(this.GetType())) //{ // var resourcesClient = GetResourceManagementClient(context, handler); // var storageMgmtClient = GetStorageManagementClient(context, handler); // var keyVaultMgmtClient = GetKeyVaultManagementClient(context, handler); // // Create storage account with hot // string accountName = TestUtilities.GenerateName("sto"); // var rgname = CreateResourceGroup(resourcesClient); // var ops = storageMgmtClient.Operations.List(); // var op1 = new Operation // { // Name = "Microsoft.Storage/storageAccounts/write", // Display = new OperationDisplay // { // Provider = "Microsoft Storage", // Resource = "Storage Accounts", // Operation = "Create/Update Storage Account" // } // }; // var op2 = new Operation // { // Name = "Microsoft.Storage/storageAccounts/delete", // Display = new OperationDisplay // { // Provider = "Microsoft Storage", // Resource = "Storage Accounts", // Operation = "Delete Storage Account" // } // }; // bool exists1 = false; // bool exists2 = false; // Assert.NotNull(ops); // Assert.NotNull(ops.GetEnumerator()); // var operation = ops.GetEnumerator(); // while (operation.MoveNext()) // { // if (operation.Current.ToString().Equals(op1.ToString())) // { // exists1 = true; // } // if (operation.Current.ToString().Equals(op2.ToString())) // { // exists2 = true; // } // } // Assert.True(exists1); // Assert.True(exists2); //} } [Test] public async Task StorageAccountVnetACLTest() { //Create resource group string rgname = await CreateResourceGroupAsync(); string accountName = Recording.GenerateAssetName("sto"); // Create storage account with Vnet StorageAccountCreateParameters parameters = GetDefaultStorageAccountParameters(); parameters.NetworkRuleSet = new NetworkRuleSet(defaultAction: DefaultAction.Deny) { Bypass = @"Logging,AzureServices", IpRules = new List<IPRule> { new IPRule(iPAddressOrRange: "23.45.67.90") } }; await _CreateStorageAccountAsync(rgname, accountName, parameters); StorageAccount account = await WaitToGetAccountSuccessfullyAsync(rgname, accountName); // Verify the vnet rule properties. Assert.NotNull(account.NetworkRuleSet); Assert.AreEqual(@"Logging, AzureServices", account.NetworkRuleSet.Bypass.ToString()); Assert.AreEqual(DefaultAction.Deny, account.NetworkRuleSet.DefaultAction); Assert.IsEmpty(account.NetworkRuleSet.VirtualNetworkRules); Assert.NotNull(account.NetworkRuleSet.IpRules); Assert.IsNotEmpty(account.NetworkRuleSet.IpRules); Assert.AreEqual("23.45.67.90", account.NetworkRuleSet.IpRules[0].IPAddressOrRange); Assert.AreEqual(DefaultAction.Allow.ToString(), account.NetworkRuleSet.IpRules[0].Action); // Update Vnet StorageAccountUpdateParameters updateParameters = new StorageAccountUpdateParameters { NetworkRuleSet = new NetworkRuleSet(defaultAction: DefaultAction.Deny) { Bypass = @"Logging, Metrics", IpRules = new List<IPRule> { new IPRule(iPAddressOrRange:"23.45.67.91") { Action = DefaultAction.Allow.ToString() }, new IPRule(iPAddressOrRange:"23.45.67.92") }, } }; await UpdateStorageAccountAsync(rgname, accountName, updateParameters); account = await WaitToGetAccountSuccessfullyAsync(rgname, accountName); Assert.NotNull(account.NetworkRuleSet); Assert.AreEqual(@"Logging, Metrics", account.NetworkRuleSet.Bypass.ToString()); Assert.AreEqual(DefaultAction.Deny, account.NetworkRuleSet.DefaultAction); Assert.IsEmpty(account.NetworkRuleSet.VirtualNetworkRules); Assert.NotNull(account.NetworkRuleSet.IpRules); Assert.IsNotEmpty(account.NetworkRuleSet.IpRules); Assert.AreEqual("23.45.67.91", account.NetworkRuleSet.IpRules[0].IPAddressOrRange); Assert.AreEqual(DefaultAction.Allow.ToString(), account.NetworkRuleSet.IpRules[0].Action); Assert.AreEqual("23.45.67.92", account.NetworkRuleSet.IpRules[1].IPAddressOrRange); Assert.AreEqual(DefaultAction.Allow.ToString(), account.NetworkRuleSet.IpRules[1].Action); // Delete vnet. updateParameters = new StorageAccountUpdateParameters { NetworkRuleSet = new NetworkRuleSet(DefaultAction.Allow) }; await UpdateStorageAccountAsync(rgname, accountName, updateParameters); account = await WaitToGetAccountSuccessfullyAsync(rgname, accountName); Assert.NotNull(account.NetworkRuleSet); Assert.AreEqual(@"Logging, Metrics", account.NetworkRuleSet.Bypass.ToString()); Assert.AreEqual(DefaultAction.Allow, account.NetworkRuleSet.DefaultAction); } [Test] public void StorageSKUListTest() { AsyncPageable<SkuInformation> skulist = SkusClient.ListAsync(); Assert.NotNull(skulist); Task<List<SkuInformation>> skuListTask = skulist.ToEnumerableAsync(); Assert.AreEqual(@"storageAccounts", skuListTask.Result.ElementAt(0).ResourceType); Assert.NotNull(skuListTask.Result.ElementAt(0).Name); Assert.True(skuListTask.Result.ElementAt(0).Name.GetType() == SkuName.PremiumLRS.GetType()); Assert.True(skuListTask.Result.ElementAt(0).Name.Equals(SkuName.PremiumLRS) || skuListTask.Result.ElementAt(0).Name.Equals(SkuName.StandardGRS) || skuListTask.Result.ElementAt(0).Name.Equals(SkuName.StandardLRS) || skuListTask.Result.ElementAt(0).Name.Equals(SkuName.StandardRagrs) || skuListTask.Result.ElementAt(0).Name.Equals(SkuName.StandardZRS)); Assert.NotNull(skuListTask.Result.ElementAt(0).Kind); Assert.True(skuListTask.Result.ElementAt(0).Kind.Equals(Kind.BlobStorage) || skuListTask.Result.ElementAt(0).Kind.Equals(Kind.Storage) || skuListTask.Result.ElementAt(0).Kind.Equals(Kind.StorageV2)); } [Test] public async Task StorageAccountCreateWithStorageV2() { //Create resource group string rgname = await CreateResourceGroupAsync(); string accountName = Recording.GenerateAssetName("sto"); // Create storage account with StorageV2 Sku sku = new Sku(SkuName.StandardGRS); StorageAccountCreateParameters parameters = new StorageAccountCreateParameters(sku: sku, kind: Kind.StorageV2, location: DefaultLocation); StorageAccount account = await _CreateStorageAccountAsync(rgname, accountName, parameters); VerifyAccountProperties(account, false); Assert.NotNull(account.PrimaryEndpoints.Web); Assert.AreEqual(Kind.StorageV2, account.Kind); } [Test] public async Task StorageAccountUpdateKindStorageV2() { //Create resource group string rgname = await CreateResourceGroupAsync(); // Create storage account string accountName = await CreateStorageAccount(AccountsClient, rgname, Recording); // Update storage account type StorageAccountUpdateParameters parameters = new StorageAccountUpdateParameters { Kind = Kind.StorageV2, EnableHttpsTrafficOnly = true }; StorageAccount account = await UpdateStorageAccountAsync(rgname, accountName, parameters); Assert.AreEqual(Kind.StorageV2, account.Kind); Assert.True(account.EnableHttpsTrafficOnly); Assert.NotNull(account.PrimaryEndpoints.Web); // Validate account = await WaitToGetAccountSuccessfullyAsync(rgname, accountName); Assert.AreEqual(Kind.StorageV2, account.Kind); Assert.True(account.EnableHttpsTrafficOnly); Assert.NotNull(account.PrimaryEndpoints.Web); } [Test] public async Task StorageAccountSetGetDeleteManagementPolicy() { //Create resource group string rgname = await CreateResourceGroupAsync(); string accountName = Recording.GenerateAssetName("sto"); // Create storage account Sku sku = new Sku(SkuName.StandardGRS); StorageAccountCreateParameters parameters = new StorageAccountCreateParameters(sku: sku, kind: Kind.StorageV2, location: "westus"); await _CreateStorageAccountAsync(rgname, accountName, parameters); List<ManagementPolicyRule> rules = new List<ManagementPolicyRule>(); ManagementPolicyAction Actions = new ManagementPolicyAction() { BaseBlob = new ManagementPolicyBaseBlob() { Delete = new DateAfterModification(300), TierToArchive = new DateAfterModification(90), TierToCool = new DateAfterModification(1000), }, Snapshot = new ManagementPolicySnapShot() { Delete = new DateAfterCreation(100) } }; ManagementPolicyDefinition Definition = new ManagementPolicyDefinition(Actions) { Filters = new ManagementPolicyFilter(new List<string>() { "blockBlob" }) { PrefixMatch = new List<string>() { "olcmtestcontainer", "testblob" } } }; ManagementPolicyRule rule1 = new ManagementPolicyRule("olcmtest", Definition) { Enabled = true }; rules.Add(rule1); ManagementPolicyAction Actions2 = new ManagementPolicyAction() { BaseBlob = new ManagementPolicyBaseBlob() { Delete = new DateAfterModification(1000), }, }; ManagementPolicyDefinition Definition2 = new ManagementPolicyDefinition(Actions2) { Filters = new ManagementPolicyFilter(new List<string>() { "blockBlob" }) }; ManagementPolicyRule rule2 = new ManagementPolicyRule("olcmtest2", Definition2) { Enabled = false }; rules.Add(rule2); ManagementPolicyAction Actions3 = new ManagementPolicyAction() { Snapshot = new ManagementPolicySnapShot() { Delete = new DateAfterCreation(200) } }; ManagementPolicyDefinition Definition3 = new ManagementPolicyDefinition(Actions3) { Filters = new ManagementPolicyFilter(new List<string>() { "blockBlob" }) }; ManagementPolicyRule rule3 = new ManagementPolicyRule("olcmtest3", Definition3); rules.Add(rule3); //Set Management Policies ManagementPolicySchema policyToSet = new ManagementPolicySchema(rules); ManagementPolicy managementPolicy = new ManagementPolicy() { Policy = policyToSet }; Response<ManagementPolicy> policy = await ManagementPoliciesClient.CreateOrUpdateAsync(rgname, accountName, managementPolicy); CompareStorageAccountManagementPolicyProperty(policyToSet, policy.Value.Policy); //Get Management Policies policy = await ManagementPoliciesClient.GetAsync(rgname, accountName); CompareStorageAccountManagementPolicyProperty(policyToSet, policy.Value.Policy); //Delete Management Policies, and check policy not exist await ManagementPoliciesClient.DeleteAsync(rgname, accountName); bool dataPolicyExist = true; try { policy = await ManagementPoliciesClient.GetAsync(rgname, accountName); } catch (RequestFailedException cloudException) { Assert.AreEqual((int)HttpStatusCode.NotFound, cloudException.Status); dataPolicyExist = false; } Assert.False(dataPolicyExist); //Delete not exist Management Policies will not fail await ManagementPoliciesClient.DeleteAsync(rgname, accountName); } private static void CompareStorageAccountManagementPolicyProperty(ManagementPolicySchema policy1, ManagementPolicySchema policy2) { Assert.AreEqual(policy1.Rules.Count, policy2.Rules.Count); foreach (ManagementPolicyRule rule1 in policy1.Rules) { bool ruleFound = false; foreach (ManagementPolicyRule rule2 in policy2.Rules) { if (rule1.Name == rule2.Name) { ruleFound = true; Assert.AreEqual(rule1.Enabled is null ? true : rule1.Enabled, rule2.Enabled); if (rule1.Definition.Filters != null || rule2.Definition.Filters != null) { Assert.AreEqual(rule1.Definition.Filters.BlobTypes, rule2.Definition.Filters.BlobTypes); Assert.AreEqual(rule1.Definition.Filters.PrefixMatch, rule2.Definition.Filters.PrefixMatch); } if (rule1.Definition.Actions.BaseBlob != null || rule2.Definition.Actions.BaseBlob != null) { CompareDateAfterModification(rule1.Definition.Actions.BaseBlob.TierToCool, rule2.Definition.Actions.BaseBlob.TierToCool); CompareDateAfterModification(rule1.Definition.Actions.BaseBlob.TierToArchive, rule2.Definition.Actions.BaseBlob.TierToArchive); CompareDateAfterModification(rule1.Definition.Actions.BaseBlob.Delete, rule2.Definition.Actions.BaseBlob.Delete); } if (rule1.Definition.Actions.Snapshot != null || rule2.Definition.Actions.Snapshot != null) { CompareDateAfterCreation(rule1.Definition.Actions.Snapshot.Delete, rule1.Definition.Actions.Snapshot.Delete); } break; } } Assert.True(ruleFound, string.Format("The set rule {0} should be found in the output.", rule1.Name)); } } private static void CompareDateAfterModification(DateAfterModification date1, DateAfterModification date2) { if ((date1 is null) && (date2 is null)) { return; } Assert.AreEqual(date1.DaysAfterModificationGreaterThan, date2.DaysAfterModificationGreaterThan); } private static void CompareDateAfterCreation(DateAfterCreation date1, DateAfterCreation date2) { if ((date1 is null) && (date2 is null)) { return; } Assert.AreEqual(date1.DaysAfterCreationGreaterThan, date2.DaysAfterCreationGreaterThan); } [Test] public async Task StorageAccountCreateGetdfs() { //Create resource group string rgname = await CreateResourceGroupAsync(); string accountName = Recording.GenerateAssetName("sto"); // Create storage account Sku sku = new Sku(SkuName.StandardGRS); StorageAccountCreateParameters parameters = new StorageAccountCreateParameters(sku: sku, kind: Kind.StorageV2, location: DefaultRGLocation) { IsHnsEnabled = true }; StorageAccount account = await _CreateStorageAccountAsync(rgname, accountName, parameters); Assert.True(account.IsHnsEnabled = true); Assert.NotNull(account.PrimaryEndpoints.Dfs); // Validate account = await WaitToGetAccountSuccessfullyAsync(rgname, accountName); Assert.True(account.IsHnsEnabled = true); Assert.NotNull(account.PrimaryEndpoints.Dfs); } [Test] public async Task StorageAccountCreateWithFileStorage() { //Create resource group string rgname = await CreateResourceGroupAsync(); string accountName = Recording.GenerateAssetName("sto"); // Create storage account with StorageV2 Sku sku = new Sku(SkuName.PremiumLRS); StorageAccountCreateParameters parameters = new StorageAccountCreateParameters(sku: sku, kind: Kind.FileStorage, location: "centraluseuap"); StorageAccount account = await _CreateStorageAccountAsync(rgname, accountName, parameters); VerifyAccountProperties(account, false); Assert.AreEqual(Kind.FileStorage, account.Kind); Assert.AreEqual(SkuName.PremiumLRS, account.Sku.Name); } [Test] public async Task StorageAccountCreateWithBlockBlobStorage() { //Create resource group string rgname = await CreateResourceGroupAsync(); string accountName = Recording.GenerateAssetName("sto"); // Create storage account with StorageV2 Sku sku = new Sku(SkuName.PremiumLRS); StorageAccountCreateParameters parameters = new StorageAccountCreateParameters(sku: sku, kind: Kind.BlockBlobStorage, location: "centraluseuap"); StorageAccount account = await _CreateStorageAccountAsync(rgname, accountName, parameters); VerifyAccountProperties(account, false); Assert.AreEqual(Kind.BlockBlobStorage, account.Kind); Assert.AreEqual(SkuName.PremiumLRS, account.Sku.Name); } [Test] [Ignore("Track2: Unable to locate active AAD DS for AAD tenant Id *************** associated with the storage account.")] public async Task StorageAccountCreateSetGetFileAadIntegration() { //Create resource group string rgname = await CreateResourceGroupAsync(); string accountName = Recording.GenerateAssetName("sto"); // Create storage account Sku sku = new Sku(SkuName.StandardGRS); StorageAccountCreateParameters parameters = new StorageAccountCreateParameters(sku: sku, kind: Kind.StorageV2, location: DefaultLocation) { AzureFilesIdentityBasedAuthentication = new AzureFilesIdentityBasedAuthentication(DirectoryServiceOptions.Aadds) }; StorageAccount account = await _CreateStorageAccountAsync(rgname, accountName, parameters); Assert.AreEqual(DirectoryServiceOptions.Aadds, account.AzureFilesIdentityBasedAuthentication.DirectoryServiceOptions); // Validate account = await WaitToGetAccountSuccessfullyAsync(rgname, accountName); Assert.AreEqual(DirectoryServiceOptions.Aadds, account.AzureFilesIdentityBasedAuthentication.DirectoryServiceOptions); // Update storage account StorageAccountUpdateParameters updateParameters = new StorageAccountUpdateParameters { AzureFilesIdentityBasedAuthentication = new AzureFilesIdentityBasedAuthentication(DirectoryServiceOptions.None), EnableHttpsTrafficOnly = true }; account = await UpdateStorageAccountAsync(rgname, accountName, updateParameters); Assert.AreEqual(DirectoryServiceOptions.None, account.AzureFilesIdentityBasedAuthentication.DirectoryServiceOptions); // Validate account = await WaitToGetAccountSuccessfullyAsync(rgname, accountName); Assert.AreEqual(DirectoryServiceOptions.None, account.AzureFilesIdentityBasedAuthentication.DirectoryServiceOptions); } [Test] [Ignore("Track2: Last sync time is unavailable for account sto218")] public async Task StorageAccountFailOver() { //Create resource group string rgname = await CreateResourceGroupAsync(); string accountName = Recording.GenerateAssetName("sto"); // Create storage account Sku sku = new Sku(SkuName.StandardRagrs); StorageAccountCreateParameters parameters = new StorageAccountCreateParameters(sku: sku, kind: Kind.StorageV2, location: DefaultLocation); _ = await _CreateStorageAccountAsync(rgname, accountName, parameters); // Wait for account ready to failover and Validate StorageAccount account; string location; int i = 100; do { account = await AccountsClient.GetPropertiesAsync(rgname, accountName, expand: StorageAccountExpand.GeoReplicationStats); Assert.AreEqual(SkuName.StandardRagrs, account.Sku.Name); Assert.Null(account.FailoverInProgress); location = account.SecondaryLocation; //Don't need sleep when playback, or Unit test will be very slow. Need sleep when record. if (Mode == RecordedTestMode.Record) { System.Threading.Thread.Sleep(10000); } } while ((account.GeoReplicationStats.CanFailover != true) && (i-- > 0)); // Failover storage account Operation<Response> failoverWait = await AccountsClient.StartFailoverAsync(rgname, accountName); await WaitForCompletionAsync(failoverWait); // Validate account = await WaitToGetAccountSuccessfullyAsync(rgname, accountName); Assert.AreEqual(SkuName.StandardLRS, account.Sku.Name); Assert.AreEqual(location, account.PrimaryLocation); } [Test] public async Task StorageAccountGetLastSyncTime() { //Create resource group string rgname = await CreateResourceGroupAsync(); string accountName = Recording.GenerateAssetName("sto"); // Create storage account Sku sku = new Sku(SkuName.StandardRagrs); StorageAccountCreateParameters parameters = new StorageAccountCreateParameters(sku: sku, kind: Kind.StorageV2, location: "eastus2(stage)"); StorageAccount account = await _CreateStorageAccountAsync(rgname, accountName, parameters); Assert.AreEqual(SkuName.StandardRagrs, account.Sku.Name); Assert.Null(account.GeoReplicationStats); account = await WaitToGetAccountSuccessfullyAsync(rgname, accountName); Assert.Null(account.GeoReplicationStats); account = await AccountsClient.GetPropertiesAsync(rgname, accountName, StorageAccountExpand.GeoReplicationStats); Assert.NotNull(account.GeoReplicationStats); Assert.NotNull(account.GeoReplicationStats.Status); Assert.NotNull(account.GeoReplicationStats.LastSyncTime); Assert.NotNull(account.GeoReplicationStats.CanFailover); } [Test] public async Task StorageAccountLargeFileSharesStateTest() { //Create resource group string rgname = await CreateResourceGroupAsync(); string accountName = Recording.GenerateAssetName("sto"); // Create storage account Sku sku = new Sku(SkuName.StandardLRS); StorageAccountCreateParameters parameters = new StorageAccountCreateParameters(sku: sku, kind: Kind.StorageV2, location: "westeurope") { LargeFileSharesState = LargeFileSharesState.Enabled }; StorageAccount account = await _CreateStorageAccountAsync(rgname, accountName, parameters); Assert.AreEqual(SkuName.StandardLRS, account.Sku.Name); Assert.AreEqual(LargeFileSharesState.Enabled, account.LargeFileSharesState); // Validate account = await WaitToGetAccountSuccessfullyAsync(rgname, accountName); Assert.AreEqual(SkuName.StandardLRS, account.Sku.Name); Assert.AreEqual(LargeFileSharesState.Enabled, account.LargeFileSharesState); } [Test] public async Task StorageAccountPrivateEndpointTest() { //Create resource group string rgname = await CreateResourceGroupAsync(); string accountName = Recording.GenerateAssetName("sto"); // Create storage account Sku sku = new Sku(SkuName.StandardLRS); StorageAccountCreateParameters parameters = new StorageAccountCreateParameters(sku: sku, kind: Kind.StorageV2, location: "westeurope") { LargeFileSharesState = LargeFileSharesState.Enabled }; StorageAccount account = await _CreateStorageAccountAsync(rgname, accountName, parameters); Assert.AreEqual(SkuName.StandardLRS, account.Sku.Name); account = await WaitToGetAccountSuccessfullyAsync(rgname, accountName); IList<PrivateEndpointConnection> pes = account.PrivateEndpointConnections; foreach (PrivateEndpointConnection pe in pes) { //Get from account await PrivateEndpointConnectionsClient.GetAsync(rgname, accountName, pe.Name); // Prepare data for set PrivateEndpoint endpoint = new PrivateEndpoint(); PrivateEndpointConnection connection = new PrivateEndpointConnection() { PrivateEndpoint = endpoint, PrivateLinkServiceConnectionState = new PrivateLinkServiceConnectionState() { ActionRequired = "None", Description = "123", Status = "Approved" } }; if (pe.PrivateLinkServiceConnectionState.Status != "Rejected") { //Set approve connection.PrivateLinkServiceConnectionState.Status = "Approved"; PrivateEndpointConnection pe3 = await PrivateEndpointConnectionsClient.PutAsync(rgname, accountName, pe.Name, pe); Assert.AreEqual("Approved", pe3.PrivateLinkServiceConnectionState.Status); //Validate approve by get pe3 = await PrivateEndpointConnectionsClient.GetAsync(rgname, accountName, pe.Name); Assert.AreEqual("Approved", pe3.PrivateLinkServiceConnectionState.Status); } if (pe.PrivateLinkServiceConnectionState.Status == "Rejected") { //Set reject connection.PrivateLinkServiceConnectionState.Status = "Rejected"; PrivateEndpointConnection pe4 = await PrivateEndpointConnectionsClient.PutAsync(rgname, accountName, pe.Name, pe); Assert.AreEqual("Rejected", pe4.PrivateLinkServiceConnectionState.Status); //Validate reject by get pe4 = await PrivateEndpointConnectionsClient.GetAsync(rgname, accountName, pe.Name); Assert.AreEqual("Rejected", pe4.PrivateLinkServiceConnectionState.Status); } } } [Test] public async Task StorageAccountPrivateLinkTest() { //Create resource group string rgname = await CreateResourceGroupAsync(); string accountName = Recording.GenerateAssetName("sto"); // Create storage account Sku sku = new Sku(SkuName.StandardLRS); StorageAccountCreateParameters parameters = new StorageAccountCreateParameters(sku: sku, kind: Kind.StorageV2, location: "westus") { LargeFileSharesState = LargeFileSharesState.Enabled }; await _CreateStorageAccountAsync(rgname, accountName, parameters); // Get private link resource Response<PrivateLinkResourceListResult> result = await PrivateLinkResourcesClient.ListByStorageAccountAsync(rgname, accountName); // Validate Assert.True(result.Value.Value.Count > 0); } [Test] public async Task StorageAccountCreateWithTableQueueEcryptionKeyTypeTest() { //Create resource group string rgname = await CreateResourceGroupAsync(); string accountName = Recording.GenerateAssetName("sto"); // Create storage account Sku sku = new Sku(SkuName.StandardLRS); StorageAccountCreateParameters parameters = new StorageAccountCreateParameters(sku: sku, kind: Kind.StorageV2, location: "East US 2 EUAP") { LargeFileSharesState = LargeFileSharesState.Enabled, Encryption = new Encryption(keySource: KeySource.MicrosoftStorage) { Services = new EncryptionServices { Queue = new EncryptionService { KeyType = KeyType.Account }, Table = new EncryptionService { KeyType = KeyType.Account }, } } }; StorageAccount account = await _CreateStorageAccountAsync(rgname, accountName, parameters); // Verify encryption settings Assert.NotNull(account.Encryption); Assert.NotNull(account.Encryption.Services.Blob); Assert.True(account.Encryption.Services.Blob.Enabled); Assert.AreEqual(KeyType.Account, account.Encryption.Services.Blob.KeyType); Assert.NotNull(account.Encryption.Services.Blob.LastEnabledTime); Assert.NotNull(account.Encryption.Services.File); Assert.True(account.Encryption.Services.File.Enabled); Assert.AreEqual(KeyType.Account, account.Encryption.Services.Blob.KeyType); Assert.NotNull(account.Encryption.Services.File.LastEnabledTime); Assert.NotNull(account.Encryption.Services.Queue); Assert.AreEqual(KeyType.Account, account.Encryption.Services.Queue.KeyType); Assert.True(account.Encryption.Services.Queue.Enabled); Assert.NotNull(account.Encryption.Services.Queue.LastEnabledTime); Assert.NotNull(account.Encryption.Services.Table); Assert.AreEqual(KeyType.Account, account.Encryption.Services.Table.KeyType); Assert.True(account.Encryption.Services.Table.Enabled); Assert.NotNull(account.Encryption.Services.Table.LastEnabledTime); } [Test] public async Task EcryptionScopeTest() { //Create resource group string rgname = await CreateResourceGroupAsync(); string accountName = Recording.GenerateAssetName("sto"); // Create storage account Sku sku = new Sku(SkuName.StandardLRS); StorageAccountCreateParameters parameters = new StorageAccountCreateParameters(sku: sku, kind: Kind.StorageV2, location: "East US 2 EUAP"); await _CreateStorageAccountAsync(rgname, accountName, parameters); //Create EcryptionScope EncryptionScope EncryptionScope = new EncryptionScope() { Source = EncryptionScopeSource.MicrosoftStorage, State = EncryptionScopeState.Disabled }; EncryptionScope es = await EncryptionScopesClient.PutAsync(rgname, accountName, "testscope", EncryptionScope); Assert.AreEqual("testscope", es.Name); Assert.AreEqual(EncryptionScopeState.Disabled, es.State); Assert.AreEqual(EncryptionScopeSource.MicrosoftStorage, es.Source); // Get EcryptionScope es = await EncryptionScopesClient.GetAsync(rgname, accountName, "testscope"); Assert.AreEqual("testscope", es.Name); Assert.AreEqual(EncryptionScopeState.Disabled, es.State); Assert.AreEqual(EncryptionScopeSource.MicrosoftStorage, es.Source); // Patch EcryptionScope es.State = EncryptionScopeState.Enabled; es = await EncryptionScopesClient.PatchAsync(rgname, accountName, "testscope", es); Assert.AreEqual("testscope", es.Name); Assert.AreEqual(EncryptionScopeState.Enabled, es.State); Assert.AreEqual(EncryptionScopeSource.MicrosoftStorage, es.Source); //List EcryptionScope AsyncPageable<EncryptionScope> ess = EncryptionScopesClient.ListAsync(rgname, accountName); Task<List<EncryptionScope>> essList = ess.ToEnumerableAsync(); es = essList.Result.First(); Assert.AreEqual("testscope", es.Name); Assert.AreEqual(EncryptionScopeState.Enabled, es.State); Assert.AreEqual(EncryptionScopeSource.MicrosoftStorage, es.Source); } private async Task<string> CreateResourceGroupAsync() { return await CreateResourceGroup(ResourceGroupsClient, Recording); } private async Task<StorageAccount> _CreateStorageAccountAsync(string resourceGroupName, string accountName, StorageAccountCreateParameters parameters = null) { StorageAccountCreateParameters saParameters = parameters ?? GetDefaultStorageAccountParameters(); Operation<StorageAccount> accountsResponse = await AccountsClient.StartCreateAsync(resourceGroupName, accountName, saParameters); StorageAccount account = (await WaitForCompletionAsync(accountsResponse)).Value; return account; } private async Task<Response<StorageAccount>> WaitToGetAccountSuccessfullyAsync(string resourceGroupName, string accountName) { return await AccountsClient.GetPropertiesAsync(resourceGroupName, accountName); } private async Task<Response<StorageAccount>> UpdateStorageAccountAsync(string resourceGroupName, string accountName, StorageAccountUpdateParameters parameters) { return await AccountsClient.UpdateAsync(resourceGroupName, accountName, parameters); } private async Task<Response> DeleteStorageAccountAsync(string resourceGroupName, string accountName) { return await AccountsClient.DeleteAsync(resourceGroupName, accountName); } } }
49.036935
211
0.634155
[ "MIT" ]
AzureDataBox/azure-sdk-for-net
sdk/storage/Azure.ResourceManager.Storage/tests/Tests/StorageAccountTests.cs
88,955
C#
namespace ClassLib018 { public class Class039 { public static string Property => "ClassLib018"; } }
15
55
0.633333
[ "MIT" ]
333fred/performance
src/scenarios/weblarge2.0/src/ClassLib018/Class039.cs
120
C#
using System; using System.Windows.Forms; namespace EfficientlyLazy.Crypto.Demo.UserControls { public class CryptoUserControl : UserControl { public virtual string DisplayName { get { throw new InvalidOperationException("Method needs to be overridden"); } } public virtual string Encrypt(string clearText) { return ValidateParameters() ? EngineEncrypt(clearText) : string.Empty; } public virtual string Decrypt(string encryptedText) { return ValidateParameters() ? EngineDecrypt(encryptedText) : string.Empty; } protected virtual bool ValidateParameters() { throw new InvalidOperationException("Method needs to be overridden"); } public virtual bool CanEncrypt { get { throw new InvalidOperationException("Method needs to be overridden"); } } protected virtual string EngineEncrypt(string clearText) { throw new InvalidOperationException("Method needs to be overridden"); } public virtual bool CanDecrypt { get { throw new InvalidOperationException("Method needs to be overridden"); } } protected virtual string EngineDecrypt(string encryptedText) { throw new InvalidOperationException("Method needs to be overridden"); } } }
27.967213
86
0.531067
[ "Apache-2.0" ]
jasonlaflair/EfficientlyLazy.Crypto
src/EfficientlyLazy.Crypto.Demo/UserControls/CryptoControl.cs
1,708
C#
using Bonos.Models; using Bonos.Helpers; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace Bonos.Controllers { public class UsuarioController : Controller { public ActionResult Login() { return View(); } [HttpPost] public ActionResult Login(Usuario usuario) { using (var db = new BonosModel()) { var aux = db.Usuario.FirstOrDefault(x => x.username == usuario.username && x.password == usuario.password); if (aux != null) { SessionHelper.userID = aux.Id; SessionHelper.nombre = aux.nombre; SessionHelper.apellido = aux.apellido; return RedirectToAction("Index", "Bono"); } ModelState.AddModelError("notFound", "Nombre de usuario y/o contraseña incorrectos"); } return View(usuario); } public ActionResult Register() { return View(); } [HttpPost] public ActionResult Register(Usuario usuario) { using (var db = new BonosModel()) { if (ModelState.IsValid) { var aux = db.Usuario.FirstOrDefault(x => x.username == usuario.username && x.password == usuario.password); if (aux == null) { db.Usuario.Add(usuario); db.SaveChanges(); return RedirectToAction("Login"); } } } return View(usuario); } } }
29.213115
127
0.482604
[ "MIT" ]
hyg1997/FinanzasBonos
Bonos/Bonos/Controllers/UsuarioController.cs
1,785
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // <auto-generated/> #nullable disable using System.Text.Json; using Azure.Core; namespace Azure.Analytics.Synapse.Artifacts.Models { public partial class TriggerSubscriptionOperationStatus { internal static TriggerSubscriptionOperationStatus DeserializeTriggerSubscriptionOperationStatus(JsonElement element) { string triggerName = default; EventSubscriptionStatus? status = default; foreach (var property in element.EnumerateObject()) { if (property.NameEquals("triggerName")) { if (property.Value.ValueKind == JsonValueKind.Null) { continue; } triggerName = property.Value.GetString(); continue; } if (property.NameEquals("status")) { if (property.Value.ValueKind == JsonValueKind.Null) { continue; } status = new EventSubscriptionStatus(property.Value.GetString()); continue; } } return new TriggerSubscriptionOperationStatus(triggerName, status); } } }
32.045455
125
0.540426
[ "MIT" ]
AzureDataBox/azure-sdk-for-net
sdk/synapse/Azure.Analytics.Synapse.Artifacts/src/Generated/Models/TriggerSubscriptionOperationStatus.Serialization.cs
1,410
C#
// *********************************************************************** // Copyright (c) 2007 Charlie Poole // // 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 NUnit.Framework.Api { /// <summary> /// Interface to be implemented by filters applied to tests. /// The filter applies when running the test, after it has been /// loaded, since this is the only time an ITest exists. /// </summary> public interface ITestFilter { /// <summary> /// Determine if a particular test passes the filter criteria. Pass /// may examine the parents and/or descendants of a test, depending /// on the semantics of the particular filter /// </summary> /// <param name="test">The test to which the filter is applied</param> /// <returns>True if the test passes the fFilter, otherwise false</returns> bool Pass( ITest test ); } }
43.711111
77
0.682766
[ "Apache-2.0" ]
OpenPSS/psm-mono
mcs/nunitlite/src/framework/Api/ITestFilter.cs
1,967
C#
using UnityEngine; using System; using System.Collections.Generic; using System.Linq; public class GlobalSystemsExecutor : MonoBehaviour { void OnEnable() { sendMessage("orderedOnEnable"); } //void OnDisable() //{ // reversesendMessage("orderedOnDisable"); //} void FixedUpdate() { sendMessage("orderedFixedUpdate"); } void Update() { sendMessage("orderedUpdate"); } void sendMessage(string message) { int count = transform.childCount; for (int i = 0; i < count; i++) { transform.GetChild(i).SendMessage(message, SendMessageOptions.DontRequireReceiver); } } // void reversesendMessage(string message) // { // int count = transform.childCount; // for (int i = count; i > 0; i--) // { // transform.GetChild(i).SendMessage(message, SendMessageOptions.DontRequireReceiver); // } // } }
20.270833
97
0.587873
[ "MIT" ]
pointcache/uECS
uECS/Assets/uECS/uECS/Core/Monos/GlobalSystemsExecutor.cs
975
C#
using UnityEngine; using BansheeGz.BGSpline.Curve; namespace BansheeGz.BGSpline.Editor { public class BGTransformMonitor { private Vector3 position; private Quaternion rotation; private Vector3 scale; private readonly BGCurve curve; public BGTransformMonitor(BGCurve curve) { this.curve = curve; Update(); } private void Update() { var transform = curve.transform; position = transform.position; rotation = transform.rotation; scale = transform.lossyScale; } public void Check() { if (Application.isPlaying) return; var transform = curve.transform; if (position != transform.position || rotation != transform.rotation || scale != transform.lossyScale) { Update(); curve.FireChange(null); } } } }
23.97561
114
0.549339
[ "MIT" ]
Margeli/IA_exercises
Exercises/Tanks3/Assets/BansheeGz/BGCurve/Scripts/Editor/Infra/BGTransformMonitor.cs
985
C#