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
/* * 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 cognito-idp-2016-04-18.normal.json service model. */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Net; using System.Text; using System.Xml.Serialization; using Amazon.CognitoIdentityProvider.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; using ThirdParty.Json.LitJson; namespace Amazon.CognitoIdentityProvider.Model.Internal.MarshallTransformations { /// <summary> /// Response Unmarshaller for SetUserSettings operation /// </summary> public class SetUserSettingsResponseUnmarshaller : JsonResponseUnmarshaller { /// <summary> /// Unmarshaller the response from the service to the response class. /// </summary> /// <param name="context"></param> /// <returns></returns> public override AmazonWebServiceResponse Unmarshall(JsonUnmarshallerContext context) { SetUserSettingsResponse response = new SetUserSettingsResponse(); return response; } /// <summary> /// Unmarshaller error response to exception. /// </summary> /// <param name="context"></param> /// <param name="innerException"></param> /// <param name="statusCode"></param> /// <returns></returns> public override AmazonServiceException UnmarshallException(JsonUnmarshallerContext context, Exception innerException, HttpStatusCode statusCode) { ErrorResponse errorResponse = JsonErrorResponseUnmarshaller.GetInstance().Unmarshall(context); if (errorResponse.Code != null && errorResponse.Code.Equals("InternalErrorException")) { return new InternalErrorException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode); } if (errorResponse.Code != null && errorResponse.Code.Equals("InvalidParameterException")) { return new InvalidParameterException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode); } if (errorResponse.Code != null && errorResponse.Code.Equals("NotAuthorizedException")) { return new NotAuthorizedException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode); } if (errorResponse.Code != null && errorResponse.Code.Equals("PasswordResetRequiredException")) { return new PasswordResetRequiredException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode); } if (errorResponse.Code != null && errorResponse.Code.Equals("ResourceNotFoundException")) { return new ResourceNotFoundException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode); } if (errorResponse.Code != null && errorResponse.Code.Equals("UserNotConfirmedException")) { return new UserNotConfirmedException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode); } if (errorResponse.Code != null && errorResponse.Code.Equals("UserNotFoundException")) { return new UserNotFoundException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode); } return new AmazonCognitoIdentityProviderException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode); } private static SetUserSettingsResponseUnmarshaller _instance = new SetUserSettingsResponseUnmarshaller(); internal static SetUserSettingsResponseUnmarshaller GetInstance() { return _instance; } /// <summary> /// Gets the singleton. /// </summary> public static SetUserSettingsResponseUnmarshaller Instance { get { return _instance; } } } }
44.622807
178
0.68331
[ "Apache-2.0" ]
Bio2hazard/aws-sdk-net
sdk/src/Services/CognitoIdentityProvider/Generated/Model/Internal/MarshallTransformations/SetUserSettingsResponseUnmarshaller.cs
5,087
C#
using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq.Expressions; using System.Linq; using System.Reflection; using System.Data.Linq; using System.Data.Linq.Mapping; using System.Data.Linq.Provider; using System.Diagnostics.CodeAnalysis; namespace System.Data.Linq.SqlClient { /// <summary> /// Method used for dealing with dynamic types. The ClrType of SqlNode is the /// statically known type originating in the source expression tree. For methods /// like GetType(), we need to know the dynamic type that will be constructed. /// </summary> internal static class TypeSource { private class Visitor : SqlVisitor { class UnwrapStack { public UnwrapStack(UnwrapStack last, bool unwrap) { Last = last; Unwrap = unwrap; } public UnwrapStack Last { get; private set; } public bool Unwrap { get; private set; } } UnwrapStack UnwrapSequences; internal SqlExpression sourceExpression; internal Type sourceType; [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification="These issues are related to our use of if-then and case statements for node types, which adds to the complexity count however when reviewed they are easy to navigate and understand.")] internal override SqlNode Visit(SqlNode node) { if (node == null) return null; sourceExpression = node as SqlExpression; if (sourceExpression != null) { Type type = sourceExpression.ClrType; UnwrapStack unwrap = this.UnwrapSequences; while (unwrap != null) { if (unwrap.Unwrap) { type = TypeSystem.GetElementType(type); } unwrap = unwrap.Last; } sourceType = type; } if (sourceType != null && TypeSystem.GetNonNullableType(sourceType).IsValueType) { return node; // Value types can't also have a dynamic type. } if (sourceType != null && TypeSystem.HasIEnumerable(sourceType)) { return node; // Sequences can't be polymorphic. } switch (node.NodeType) { case SqlNodeType.ScalarSubSelect: case SqlNodeType.Multiset: case SqlNodeType.Element: case SqlNodeType.SearchedCase: case SqlNodeType.ClientCase: case SqlNodeType.SimpleCase: case SqlNodeType.Member: case SqlNodeType.DiscriminatedType: case SqlNodeType.New: case SqlNodeType.FunctionCall: case SqlNodeType.MethodCall: case SqlNodeType.Convert: // Object identity does not survive convert. It does survive Cast. // Dig no further. return node; case SqlNodeType.TypeCase: sourceType = ((SqlTypeCase)node).RowType.Type; return node; case SqlNodeType.Link: sourceType = ((SqlLink)node).RowType.Type; return node; case SqlNodeType.Table: sourceType = ((SqlTable)node).RowType.Type; return node; case SqlNodeType.Value: SqlValue val = (SqlValue)node; if (val.Value != null) { // In some cases the ClrType of a Value node may // differ from the actual runtime type of the value. // Therefore, we ensure here that the correct type is set. sourceType = val.Value.GetType(); } return node; } return base.Visit(node); } internal override SqlSelect VisitSelect(SqlSelect select) { /* * We're travelling through <expression> of something like: * * SELECT <expression> * FROM <alias> * * Inside the expression there may be a reference to <alias> that * represents the dynamic type that we're trying to discover. * * In this case, the type relationship between AliasRef and Alias is * T to IEnumerable<T>. * * We need to remember to 'unpivot' the type of IEnumerable<T> to * get the correct dynamic type. * * Since SELECTs may be nested, we use a stack of pivots. * */ this.UnwrapSequences = new UnwrapStack(this.UnwrapSequences, true); VisitExpression(select.Selection); this.UnwrapSequences = this.UnwrapSequences.Last; return select; } internal override SqlExpression VisitAliasRef(SqlAliasRef aref) { if (this.UnwrapSequences != null && this.UnwrapSequences.Unwrap) { this.UnwrapSequences = new UnwrapStack(this.UnwrapSequences, false); this.VisitAlias(aref.Alias); this.UnwrapSequences = this.UnwrapSequences.Last; } else { this.VisitAlias(aref.Alias); } return aref; } internal override SqlExpression VisitColumnRef(SqlColumnRef cref) { this.VisitColumn(cref.Column); // Travel through column references return cref; } } /// <summary> /// Get a MetaType that represents the dynamic type of the given node. /// </summary> internal static MetaType GetSourceMetaType(SqlNode node, MetaModel model) { Visitor v = new Visitor(); v.Visit(node); Type type = v.sourceType; type = TypeSystem.GetNonNullableType(type); // Emulate CLR's behavior: strip nullability from type. return model.GetMetaType(type); } /// <summary> /// Retrieve the expression that will represent the _dynamic_ type of the /// given expression. This is either a SqlDiscriminatedType or a SqlValue /// of type Type. /// </summary> internal static SqlExpression GetTypeSource(SqlExpression expr) { Visitor v = new Visitor(); v.Visit(expr); return v.sourceExpression; } } }
45.314103
292
0.531051
[ "Apache-2.0" ]
295007712/295007712.github.io
sourceCode/dotNet4.6/ndp/fx/src/DLinq/Dlinq/SqlClient/Query/TypeSource.cs
7,069
C#
using Microsoft.EntityFrameworkCore.Migrations; namespace ItLinksBot.Migrations { public partial class StatusCodeWeekly_data : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.InsertData( table: "Providers", columns: new[] { "ProviderID", "ProviderName", "DigestURL" }, values: new object[,] { { 12, "StatusCode Weekly", "https://weekly.statuscode.com/issues" } } ); migrationBuilder.InsertData( table: "TelegramChannels", columns: new[] { "ChannelID", "ChannelName", "ProviderID" }, values: new object[,] { { 12, "-1001462629105", 12 } } ); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DeleteData( table: "Providers", keyColumn: "ProviderID", keyValue: 12 ); migrationBuilder.DeleteData( table: "TelegramChannels", keyColumn: "ChannelID", keyValue: 12 ); } } }
28.946429
71
0.394201
[ "Apache-2.0" ]
papersaltserver/ITLinksBot
src/ItLinksBot/Migrations/20210111082032_StatusCodeWeekly_data.cs
1,623
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 sagemaker-2017-07-24.normal.json service model. */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Net; using System.Text; using System.Xml.Serialization; using Amazon.SageMaker.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; using ThirdParty.Json.LitJson; namespace Amazon.SageMaker.Model.Internal.MarshallTransformations { /// <summary> /// Response Unmarshaller for DeviceStats Object /// </summary> public class DeviceStatsUnmarshaller : IUnmarshaller<DeviceStats, XmlUnmarshallerContext>, IUnmarshaller<DeviceStats, JsonUnmarshallerContext> { /// <summary> /// Unmarshaller the response from the service to the response class. /// </summary> /// <param name="context"></param> /// <returns></returns> DeviceStats IUnmarshaller<DeviceStats, XmlUnmarshallerContext>.Unmarshall(XmlUnmarshallerContext context) { throw new NotImplementedException(); } /// <summary> /// Unmarshaller the response from the service to the response class. /// </summary> /// <param name="context"></param> /// <returns></returns> public DeviceStats Unmarshall(JsonUnmarshallerContext context) { context.Read(); if (context.CurrentTokenType == JsonToken.Null) return null; DeviceStats unmarshalledObject = new DeviceStats(); int targetDepth = context.CurrentDepth; while (context.ReadAtDepth(targetDepth)) { if (context.TestExpression("ConnectedDeviceCount", targetDepth)) { var unmarshaller = LongUnmarshaller.Instance; unmarshalledObject.ConnectedDeviceCount = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("RegisteredDeviceCount", targetDepth)) { var unmarshaller = LongUnmarshaller.Instance; unmarshalledObject.RegisteredDeviceCount = unmarshaller.Unmarshall(context); continue; } } return unmarshalledObject; } private static DeviceStatsUnmarshaller _instance = new DeviceStatsUnmarshaller(); /// <summary> /// Gets the singleton. /// </summary> public static DeviceStatsUnmarshaller Instance { get { return _instance; } } } }
34.408163
146
0.629893
[ "Apache-2.0" ]
ChristopherButtars/aws-sdk-net
sdk/src/Services/SageMaker/Generated/Model/Internal/MarshallTransformations/DeviceStatsUnmarshaller.cs
3,372
C#
using Fusion.ApiClients.Org; using Newtonsoft.Json; using System; using System.Net; using System.Net.Http; using System.Text; using System.Threading.Tasks; using Fusion.Resources.Domain.Commands; using System.Linq; using System.Collections.Generic; namespace Fusion.Resources { public static class IOrgApiClientExtensions { public static IDisposable SetResourcesChangeSource(this IOrgApiClient client, Database.Entities.DbResourceAllocationRequest request) { return client.UseRequestHeaders() .WithChangeSource("Resources Allocation", $"{request.RequestNumber}"); } public static async Task<RequestResponse<TResponse>> GetAsync<TResponse>(this IOrgApiClient client, string url) { var request = new HttpRequestMessage(HttpMethod.Get, url); var response = await client.SendAsync(request); return await RequestResponse<TResponse>.FromResponseAsync(response); } public static async Task<RequestResponse<TResponse>> PutAsync<TResponse>(this IOrgApiClient client, string url) { var request = new HttpRequestMessage(HttpMethod.Put, url); var response = await client.SendAsync(request); return await RequestResponse<TResponse>.FromResponseAsync(response); } public static async Task<RequestResponse<ApiPositionV2>> PatchPositionInstanceAsync(this IOrgApiClient client, ApiPositionV2 position, Guid positionInstanceId, PatchPositionInstanceV2 instance) { if (position.Id == Guid.Empty) throw new ArgumentException("Position id cannot be empty when updating."); if (position.ProjectId == Guid.Empty && (position.Project?.ProjectId == null || position.Project.ProjectId == Guid.Empty)) throw new ArgumentException("Could not locate the project id on the position. Cannot generate url from position"); var url = $"projects/{position.ProjectId}/positions/{position.Id}/instances/{positionInstanceId}"; var request = new HttpRequestMessage(HttpMethod.Patch, url); request.Content = new StringContent(JsonConvert.SerializeObject(instance, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore }), Encoding.UTF8, "application/json"); var response = await client.SendAsync(request); return await RequestResponse<ApiPositionV2>.FromResponseAsync(response); } /// <summary> /// Resolve the task owner for a specific instance on the position. /// This operation will return the task owner at the start of the instance (applies from date) if no other date is specified. /// /// The dates are validated on the instance and returns error if it is out of bounds. /// </summary> /// <param name="projectId">The project the position exists in</param> /// <param name="positionId">The position id</param> /// <param name="date">Optionally provide a date to use for calculating the report path. If left out today is used.</param> /// <returns>The return object is a bit different </returns> public static async Task<RequestResponse<ApiTaskOwnerV2?>> GetInstanceTaskOwnerAsync(this IOrgApiClient client, Guid projectId, Guid positionId, Guid instanceId) { if (positionId == Guid.Empty) throw new ArgumentException("Position id cannot be empty when updating."); var url = $"projects/{projectId}/positions/{positionId}/instances/{instanceId}/task-owner?api-version=2.0"; return await GetAsync<ApiTaskOwnerV2?>(client, url); } public static async Task<List<ApiPositionV2>> GetReportingPath(this IOrgApiClient client, Guid projectId, Guid positionId, Guid instanceId) { var url = $"/projects/{projectId}/positions/{positionId}/instances/{instanceId}/reports-to"; var reportsTo = await GetAsync<ApiReportsTo>(client, url); return reportsTo.Value.ReportPositions != null && reportsTo.Value.Path != null ? reportsTo.Value.ReportPositions .OrderBy(pos => Array.IndexOf((Array) reportsTo.Value.Path, pos.Id)) .ToList() : new List<ApiPositionV2>(); } /// <summary> /// Updates a position. The position must have it's id, project and optionally the contract entity populated. /// The url is generated by using the project and contract reference, along with the position id. /// /// Preferably the position should be first fetched before updated. /// </summary> /// <param name="client"></param> /// <param name="position"></param> /// <returns></returns> public static async Task<RequestResponse<ApiPositionV2>> PutPositionAsync(this IOrgApiClient client, ApiPositionV2 position) { if (position.Id == Guid.Empty) throw new ArgumentException("Position id cannot be empty when updating."); if (position.ProjectId == Guid.Empty && (position.Project?.ProjectId == null || position.Project.ProjectId == Guid.Empty)) throw new ArgumentException("Could not locate the project id on the position. Cannot generate url from position"); var url = position.Contract switch { null => $"/projects/{position.Project.ProjectId}/positions/{position.Id}", _ => $"/projects/{position.Project.ProjectId}/contracts/{position.Contract.Id}/positions/{position.Id}" }; var request = new HttpRequestMessage(HttpMethod.Put, url); request.Content = new StringContent(JsonConvert.SerializeObject(position), Encoding.UTF8, "application/json"); var response = await client.SendAsync(request); return await RequestResponse<ApiPositionV2>.FromResponseAsync(response); } public static async Task<RequestResponse<ApiPositionV2>> CreatePositionAsync(this IOrgApiClient client, Guid projectId, Guid contractId, ApiPositionV2 position) { var url = $"/projects/{projectId}/contracts/{contractId}/positions"; var request = new HttpRequestMessage(HttpMethod.Post, url); request.Content = new StringContent(JsonConvert.SerializeObject(position), Encoding.UTF8, "application/json"); var response = await client.SendAsync(request); return await RequestResponse<ApiPositionV2>.FromResponseAsync(response); } public static Task<RequestResponse<ApiPositionV2>> GetPositionV2Async(this IOrgApiClient client, Guid projectId, Guid contractId, Guid positionId) => client.GetAsync<ApiPositionV2>($"/projects/{projectId}/contracts/{contractId}/positions/{positionId}?api-version=2.0"); public static Task<RequestResponse<ApiPositionV2>> GetPositionV2Async(this IOrgApiClient client, Guid projectId, Guid positionId) => client.GetAsync<ApiPositionV2>($"/projects/{projectId}/positions/{positionId}?api-version=2.0"); public static async Task<ApiDraftV2> CreateProjectDraftAsync(this IOrgApiClient client, Guid projectId, string name, string? description = null) { var resp = await client.PostAsync<ApiDraftV2>($"/projects/{projectId}/drafts?api-version=2.0", new ApiDraftV2() { Name = name, Description = description }); if (!resp.IsSuccessStatusCode) throw new OrgApiError(resp.Response, resp.Content); return resp.Value; } public static async Task<ApiDraftV2> PublishAndWaitAsync(this IOrgApiClient client, ApiDraftV2 draft) { var publishResp = await client.PostAsync<ApiDraftV2>($"/projects/{draft.ProjectId}/drafts/{draft.Id}/publish", null!); var publishedDraft = publishResp.Value; if (!publishResp.IsSuccessStatusCode) throw new OrgApiError(publishResp.Response, publishResp.Content); var response = publishResp.Response; if (response.StatusCode == HttpStatusCode.Accepted) { do { await Task.Delay(TimeSpan.FromSeconds(1)); var locationUrl = response.Headers.Location?.ToString() ?? $"/drafts/{draft.Id}/publish"; // Get poll location URL var checkResp = await client.GetAsync<ApiDraftV2>(locationUrl); if (!checkResp.IsSuccessStatusCode) throw new OrgApiError(checkResp.Response, checkResp.Content); response = checkResp.Response; publishedDraft = checkResp.Value; } while (response.StatusCode == HttpStatusCode.Accepted); } if (publishedDraft.Status == "PublishFailed") throw new DraftPublishingError(publishedDraft); return publishedDraft; } } public class RequestResponse<TResponse> { private RequestResponse(HttpResponseMessage response, string content, TResponse value) { Value = value; Content = content; Response = response; } private RequestResponse(HttpResponseMessage response, string content) { Content = content; Response = response; Value = default(TResponse)!; } public HttpStatusCode StatusCode => Response.StatusCode; public bool IsSuccessStatusCode => Response.IsSuccessStatusCode; public string Content { get; } public TResponse Value { get; } public HttpResponseMessage Response { get; } public static async Task<RequestResponse<TResponse>> FromResponseAsync(HttpResponseMessage response) { var content = await response.Content.ReadAsStringAsync(); if (response.IsSuccessStatusCode) { var value = JsonConvert.DeserializeObject<TResponse>(content); return new RequestResponse<TResponse>(response, content, value); } return new RequestResponse<TResponse>(response, content); } } public class ApiTaskOwnerV2 { /// <summary> /// The date used to resolve the task owner. /// </summary> public DateTime Date { get; set; } /// <summary> /// The position id of the task owner /// </summary> public Guid? PositionId { get; set; } /// <summary> /// Instances that are active at the date. This is usually related to rotations. /// Could also be delegated responsibility. /// </summary> public Guid[]? InstanceIds { get; set; } /// <summary> /// The persons assigned to the resolved instances. /// </summary> public ApiPersonV2[]? Persons { get; set; } } public class ApiReportsTo { public Guid[]? Path { get; set; } public ApiPositionV2[]? ReportPositions { get; set; } } public class DraftPublishingError : Exception { public ApiDraftV2 OrgChartDraft { get; set; } public DraftPublishingError(ApiDraftV2 draft) : base($"Publishing of draft resulted in error: {draft.Error?.Message}") { OrgChartDraft = draft; } } }
43.919847
201
0.644912
[ "MIT" ]
equinor/fusion-app-resources
src/backend/api/Fusion.Resources.Domain/Extensions/IOrgApiClientExtensions.cs
11,509
C#
/* Government Usage Rights Notice: The U.S. Government retains unlimited, royalty-free usage rights to this software, but not ownership, as provided by Federal law. 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 Government Usage Rights Notice, this list of conditions and the following disclaimer. • Redistributions in binary form must reproduce the above Government Usage Rights Notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. • Neither the names of the National Library of Medicine, the National Institutes of Health, nor the names of any of the software developers may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE U.S. GOVERNMENT AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITEDTO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE U.S. GOVERNMENT OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System.Drawing; namespace Imppoa.ManualLabeling { public static class Utils { public static Rectangle CreateRectangle(Point point1, Point point2) { var rect1 = CreateRectangle(point1); var rect2 = CreateRectangle(point2); var rect = Rectangle.Union(rect1, rect2); return rect; } public static Rectangle CreateRectangle(Point point) { var rect = new Rectangle(point, new Size(1, 1)); return rect; } public static Point Convert(System.Windows.Point point) { return new Point((int)point.X, (int)point.Y); } public static Size Convert(System.Windows.Size size) { return new Size((int)size.Width, (int)size.Height); } } }
53.510638
475
0.732406
[ "BSD-3-Clause" ]
raear/html-zoning
ManualLabeling/Utils.cs
2,523
C#
// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information. // Ported from um/winioctl.h in the Windows SDK for Windows 10.0.19041.0 // Original source is Copyright © Microsoft. All rights reserved. namespace TerraFX.Interop { public partial struct STORAGE_IDLE_POWER { [NativeTypeName("DWORD")] public uint Version; [NativeTypeName("DWORD")] public uint Size; public uint _bitfield; [NativeTypeName("DWORD : 1")] public uint WakeCapableHint { get { return _bitfield & 0x1u; } set { _bitfield = (_bitfield & ~0x1u) | (value & 0x1u); } } [NativeTypeName("DWORD : 1")] public uint D3ColdSupported { get { return (_bitfield >> 1) & 0x1u; } set { _bitfield = (_bitfield & ~(0x1u << 1)) | ((value & 0x1u) << 1); } } [NativeTypeName("DWORD : 30")] public uint Reserved { get { return (_bitfield >> 2) & 0x3FFFFFFFu; } set { _bitfield = (_bitfield & ~(0x3FFFFFFFu << 2)) | ((value & 0x3FFFFFFFu) << 2); } } [NativeTypeName("DWORD")] public uint D3IdleTimeout; } }
23.90625
145
0.480392
[ "MIT" ]
john-h-k/terrafx.interop.windows
sources/Interop/Windows/um/winioctl/STORAGE_IDLE_POWER.cs
1,532
C#
/* * Copyright (c) 2015, iLearnRW. Licensed under Modified BSD Licence. See licence.txt for details. */using UnityEngine; using System.Collections.Generic; public class AcDropChopScenarioV2 : ILearnRWActivityScenario, CustomActionListener { public Transform textPlanePrefab; public Transform splitDetectorPrefab; public Transform[] itemToSplitPrefabArr; public Transform[] crackPrefabArr; public Transform framePrefab; public Transform sfxPrefab; public Transform sparksPrefab; public Transform scalableGlowPrefab; public Transform planePrefab; public Transform skeletonSwipeHandPrefab; public Transform nettingPrefab; public Transform blockToObjectEffect; public Transform[] oneSyllPrefabs; public Transform[] twoSyllPrefabs; public Transform[] threeSyllPrefabs; public Transform[] fourSyllPrefabs; public Transform[] fiveSyllPrefabs; public bool showSparksEffect; SJLevelConfig currLvlConfig; SJWordItem currWordItem; Dictionary<int,SJWordItem> wordItemCache; int gridWidthInCells = 11;//17; int gridHeightInCells = 6; int numPrequelRows = 1; float borderThicknessPerc = 0f;//0.1f; GridProperties dropGrid_GuiGProp; GridProperties dropGrid_WorldGProp; string conveyorWordObjID; HashSet<string> conveyorWordGObjLookup; int nxtWordID = 1; int[,] gridState; string[,] debugGridState; string currConvWordBeingDropped; HashSet<string> droppingWords; HashSet<string> stationaryWords; Dictionary<string,TetrisInfo> tetrisInfMap; Dictionary<int,string> numIDToStrIDMap; Dictionary<string,string> blockToWDataMap; float wordDropStepTimerStart_Sec; float wordDropStepTime_Sec = 0.1f; bool conveyorOpen; bool updateStationaryBlocks; bool playItemCollideSound; bool performLineCheck = false; List<GameObject> cracksGObjs; float growScale; List<string> orderedFullySplitConvObjNames; int nxtIndexForOp; bool isPerformingPositioningSequence = false; bool isInAutoSplitMode; string itemForAutoSplit; List<int> syllsForAutoSplit; List<int> splitsDoneByGame; Color unmovableBlockColor = new Color(0.2f,0.16f,0.16f,1f); bool isWaitingForConveyorRowClearence; bool playerHasLost = false; bool chuteBusy = false; float wordChopTimerDuration_Sec = 30; List<GameObject> objsToUnPause; bool pause = false; bool[] upAxisArr = new bool[3] {false,true,false}; //int maxAttemptsPerConveyorWord = 3; bool[] conWordAttemptsStates; int currNumOfWordsDone = 0; int reqNumOfWordsDone; // Initialised when generator is initalised below. int numHooveredLines = 0; int numCorrectWordSplits = 0; int numIncorrectWordSplits = 0; List<int> playerSplitPattern; bool wordUnattempted = true; bool whistleVisible = false; bool firstTimeFlag = true; void Start() { acID = ApplicationID.DROP_CHOPS; loadActivitySessionMetaData(); this.loadTextures(); prepUIBounds(); initWorld(); this.initLevelConfigGenerator(); reqNumOfWordsDone = lvlConfigGen.getConfigCount(); genNextLevel(); showInfoSlideshow(); initPersonHelperPortraitPic(); recordActivityStart(); } void Update() { if(isInitialised) { if( ! pause) { // Move existing blocks down: //int nwLineToClear = -1; //bool moveMade = false; //bool cameToRestOccurred = false; HashSet<string> nwStationaryBlocks = new HashSet<string>(); HashSet<string> nwDestroyedBlocks = new HashSet<string>(); HashSet<string> nwDroppingBlocks = new HashSet<string>(); if((Time.time - wordDropStepTimerStart_Sec) > wordDropStepTime_Sec) { List<string> blocksToCheck = new List<string>(); blocksToCheck.AddRange(droppingWords); if(updateStationaryBlocks) { blocksToCheck.AddRange(stationaryWords); } bool changeOccurred = false; Vector3 movDownVect = new Vector3(0,-(dropGrid_WorldGProp.cellHeight + dropGrid_WorldGProp.borderThickness),0); for(int i=0; i<blocksToCheck.Count; i++) { //Debug.Log("ToCheck: "+blocksToCheck[i]); if(tetrisInfMap.ContainsKey(blocksToCheck[i])) { TetrisInfo tInfo = tetrisInfMap[blocksToCheck[i]]; int nwRow = tInfo.coords[1]+1; if(nwRow < (gridState.GetLength(1)+1)) { bool canMoveDown = true; if(nwRow >= gridState.GetLength(1)) { canMoveDown = false; } else { for(int x=tInfo.coords[0]; x<(tInfo.coords[0]+tInfo.wordSize); x++) { if(gridState[x,nwRow] != 0) { canMoveDown = false; break; } } } if(canMoveDown) { GameObject reqGObj = GameObject.Find(blocksToCheck[i]); reqGObj.transform.Translate(movDownVect); for(int x=tInfo.coords[0]; x<(tInfo.coords[0]+tInfo.wordSize); x++) { gridState[x,tInfo.coords[1]] = 0; gridState[x,nwRow] = tInfo.id; debugGridState[x,tInfo.coords[1]] = "0"; debugGridState[x,nwRow] = ""+tInfo.id; } tInfo.coords[1] = nwRow; tetrisInfMap[blocksToCheck[i]] = tInfo; if(stationaryWords.Contains(blocksToCheck[i])) { nwDroppingBlocks.Add(blocksToCheck[i]); } changeOccurred = true; //moveMade = true; } else { //cameToRestOccurred = true; if( ! stationaryWords.Contains(blocksToCheck[i])) { nwStationaryBlocks.Add(blocksToCheck[i]); performLineCheck = true; playItemCollideSound = true; } } } } } if( ! changeOccurred) { if(!isWaitingForConveyorRowClearence) { updateStationaryBlocks = false; if(!playerHasLost) { checkNHandleLosingCondition(); } } } if( ! changeOccurred) { if(isPerformingPositioningSequence) { if(nxtIndexForOp < orderedFullySplitConvObjNames.Count) { if(isRowFree(0)) { isWaitingForConveyorRowClearence = false; moveNextBlockToGrid(); } } } } wordDropStepTimerStart_Sec = Time.time; } foreach(string deletedItem in nwDestroyedBlocks) { droppingWords.Remove(deletedItem); } foreach(string dItem in nwDroppingBlocks) { if(!droppingWords.Contains(dItem)) { droppingWords.Add(dItem); } stationaryWords.Remove(dItem); } foreach(string statItem in nwStationaryBlocks) { if(!stationaryWords.Contains(statItem)) { stationaryWords.Add(statItem); } droppingWords.Remove(statItem); } if(performLineCheck) { int lineToClear = searchForLinesToClear(); if(lineToClear != -1) { performClearLineEffect(lineToClear); updateStationaryBlocks = true; numHooveredLines++; } performLineCheck = false; } // Check if Conveyor is free. if(! chuteBusy) { if(conveyorWordGObjLookup.Count == 0) { if((isRowFree(0)))//&&(isRowFree(1))) { conveyorOpen = true; } } } // Conveyor Script. When the current block is at rest, send the next block down. if(conveyorOpen) { if( ! droppingWords.Contains(currConvWordBeingDropped)) { if(conveyorOpen) { currNumOfWordsDone++; genNextLevel(); } } } if(playItemCollideSound) { triggerSoundAtCamera("Blop"); playItemCollideSound = false; } }// end of pause bracket. }// end of isInitialised bracket. } void OnGUI() { if( ! pause) { if(whistleVisible) { GUI.color = Color.clear; if(GUI.Button(uiBounds["WhistleIcon"],"")) { triggerSoundAtCamera("whistle1"); getDeliveryChuteScript().hurryUp(); setWhistleVisibility(false); } } GUI.color = Color.clear; if(uiBounds.ContainsKey("PauseBtn")) { if(GUI.Button(uiBounds["PersonPortrait"],"")) { showPersonHelperWindow(); } if(GUI.Button(uiBounds["PauseBtn"],"")) { showActivityPauseWindow(); } } } /*// Debugging: Display Grid State: for(int r=0; r<debugGridState.GetLength(1); r++) { for(int c=0; c<debugGridState.GetLength(0); c++) { if(debugGridState[c,r] != "0") { GUI.color = Color.black; } else { GUI.color = Color.white; } GUI.Label(new Rect((c * 20f),(r * 20),200,20),debugGridState[c,r]); GUI.color = Color.white; } }*/ } protected override void initWorld() { // Auto Adjust. GameObject tmpPersonPortrait = GameObject.Find("PersonPortrait"); GameObject tmpPauseButton = GameObject.Find("PauseButton"); GameObject tmpBackdrop = GameObject.Find("Background").gameObject; SpawnNormaliser.adjustGameObjectsToNwBounds(SpawnNormaliser.get2DBounds(tmpBackdrop.renderer.bounds), WorldSpawnHelper.getCameraViewWorldBounds(tmpBackdrop.transform.position.z,true), new List<GameObject>() { tmpPersonPortrait, tmpPauseButton }); //tmpExitBtnObj.transform.parent = Camera.main.transform; tmpPersonPortrait.transform.parent = GameObject.Find("Main Camera").transform; tmpPauseButton.transform.parent = GameObject.Find("Main Camera").transform; uiBounds.Add("PersonPortrait",WorldSpawnHelper.getWorldToGUIBounds(tmpPersonPortrait.renderer.bounds,upAxisArr)); uiBounds.Add("PauseBtn",WorldSpawnHelper.getWorldToGUIBounds(tmpPauseButton.renderer.bounds,upAxisArr)); // Mechanics Vars Init: // (1) Junk Grid: int totalRows = (gridHeightInCells+numPrequelRows); gridState = new int[gridWidthInCells,totalRows]; debugGridState = new string[gridWidthInCells,totalRows]; for(int r=0; r<totalRows; r++) { for(int c=0; c<gridWidthInCells; c++) { gridState[c,r] = 0; debugGridState[c,r] = "0"; } } currConvWordBeingDropped = ""; droppingWords = new HashSet<string>(); stationaryWords = new HashSet<string>(); tetrisInfMap = new Dictionary<string, TetrisInfo>(); numIDToStrIDMap = new Dictionary<int, string>(); blockToWDataMap = new Dictionary<string, string>(); wordItemCache = new Dictionary<int, SJWordItem>(); wordDropStepTimerStart_Sec = Time.time; conveyorOpen = true; updateStationaryBlocks = false; GameObject mainPitGObj = GameObject.Find("MainPit"); //Vector3 mainPitTopLeft = new Vector3(mainPitGObj.transform.position.x - (mainPitGObj.renderer.bounds.size.x/2f), // mainPitGObj.transform.position.y + (mainPitGObj.renderer.bounds.size.y/2f), // mainPitGObj.transform.position.z); //dropGrid_WorldGProp = new GridProperties(dropMainGridBox_world,gridWidthInCells,gridHeightInCells,borderThicknessPerc,mainPitGObj.transform.position.z); //dropGrid_WorldGProp = new GridProperties(new float[] {mainPitTopLeft.x,mainPitTopLeft.y,mainPitTopLeft.z},borderThicknessPerc,0.72f,0.72f,gridWidthInCells,gridHeightInCells); // Height is fixed. float reqHeightForCell = mainPitGObj.renderer.bounds.size.y/(gridHeightInCells * 1.0f); float reqWidthForCell = reqHeightForCell; float reqTotalWidthForGrid = reqWidthForCell * (gridWidthInCells * 1.0f); float reqTotalHeightForGrid = reqHeightForCell * (gridHeightInCells * 1.0f); Vector3 tmpLocalScale = mainPitGObj.transform.localScale; tmpLocalScale.x *= reqTotalWidthForGrid/mainPitGObj.renderer.bounds.size.x; tmpLocalScale.y *= reqTotalHeightForGrid/mainPitGObj.renderer.bounds.size.y; //tmpLocalScale.z = tmpLocalScale.z; mainPitGObj.transform.localScale = tmpLocalScale; Rect dropMainGridBox_world = CommonUnityUtils.get2DBounds(mainPitGObj.renderer.bounds); dropGrid_WorldGProp = new GridProperties(dropMainGridBox_world,gridWidthInCells,gridHeightInCells,borderThicknessPerc,mainPitGObj.transform.position.z); GridRenderer.createGridRender(dropGrid_WorldGProp,planePrefab,upAxisArr); createRandomStartGrid(); // (2) Other vars: conveyorWordObjID = null; conveyorWordGObjLookup = new HashSet<string>(); cracksGObjs = new List<GameObject>(); playItemCollideSound = false; conWordAttemptsStates = new bool[3] {false,false,false}; isInAutoSplitMode = false; itemForAutoSplit = null; syllsForAutoSplit = null; splitsDoneByGame = new List<int>(); playerSplitPattern = new List<int>(); isWaitingForConveyorRowClearence = false; wordDropStepTimerStart_Sec = Time.time; getChopTimerScript().setVisibilityState(false); PlayerBlockMovementScript pbms = transform.gameObject.GetComponent<PlayerBlockMovementScript>(); pbms.init(); LineDragActiveNDraw ldand = (GameObject.Find("LineMang").GetComponent<LineDragActiveNDraw>()); ldand.init(WorldSpawnHelper.getWorldToGUIBounds(GameObject.Find("Background").renderer.bounds,upAxisArr), 0.1f,dropGrid_WorldGProp.z,dropGrid_WorldGProp.z,"SplitDetect",0); ldand.registerListener("AcScen",this); ldand.setPause(true); ScoreBoardScript sbs = getScoreBoardScript(); sbs.reset(); updateLineCounterDisplay(); setWhistleVisibility(false); SoundOptionsDisplay sod = GameObject.Find("GlobObj").GetComponent<SoundOptionsDisplay>(); sod.registerListener("AcScen",this); } protected override void genNextLevel() { // Perhaps we will need to add a error message if the config list was empty. bool winFlag = checkNHandleWinningCondition(); if( ! winFlag) { if( ! firstTimeFlag) { conveyorOpen = false; chuteBusy = true; currLvlConfig = (SJLevelConfig) lvlConfigGen.getNextLevelConfig(null); wordItemCache.Add(currLvlConfig.getWordItem().getID(),currLvlConfig.getWordItem()); wordChopTimerDuration_Sec = 10f*(3-currLvlConfig.getSpeed()); if(serverCommunication != null) { serverCommunication.wordDisplayed(currLvlConfig.getWordItem().getWordAsString(),currLvlConfig.getWordItem().languageArea,currLvlConfig.getWordItem().difficulty); } playerSplitPattern = new List<int>(); openGate(); resetAttempts(); triggerChuteToFetchAndReturnWord(); } } } protected new bool initLevelConfigGenerator() { if( ! base.initLevelConfigGenerator()) { // Fallback. lvlConfigGen = new SJLevelConfigGeneratorServer(null); //new SJLevelConfigGeneratorHardCoded(); Debug.LogWarning("Warning: Using Level Gen Fallback"); } return true; } protected override bool checkNHandleWinningCondition() { updateActivityProgressMetaData(currNumOfWordsDone/(reqNumOfWordsDone*1.0f)); if(currNumOfWordsDone >= reqNumOfWordsDone) { pauseScene(true); performDefaultWinProcedure(); return true; } return false; } protected override bool checkNHandleLosingCondition() { playerHasLost = !(isRowFree(numPrequelRows-1,true)); if(playerHasLost) { pauseScene(true); performDefaultLoseProcedure(); return true; } return false; } protected override void buildNRecordConfigOutcome(System.Object[] para_extraParams) { // Build outcome object. bool positiveFlag = (bool) para_extraParams[0]; // Trigger record outcome. SJLevelOutcome reqOutcomeObj = null; if(positiveFlag) { reqOutcomeObj = new SJLevelOutcome(true); } else { reqOutcomeObj = new SJLevelOutcome(false,playerSplitPattern); } recordOutcomeForConfig(reqOutcomeObj); } protected override GameyResultData buildGameyData() { SJGameyResultData reqData = new SJGameyResultData(numHooveredLines,numCorrectWordSplits,numIncorrectWordSplits); return reqData; } protected override string generateGoalTextAppend() { return (" "+reqNumOfWordsDone); } protected override void pauseScene(bool para_state) { if(para_state) { pause = true; //LineDragActiveNDraw swipeMang = GameObject.Find("LineMang").GetComponent<LineDragActiveNDraw>(); //swipeMang.setPause(true); PlayerBlockMovementScript pbms = GameObject.Find("GlobObj").GetComponent<PlayerBlockMovementScript>(); if(pbms != null) { pbms.enabled = false; } /*if(objsToUnPause == null) { objsToUnPause = new List<GameObject>(); } else { objsToUnPause.Clear(); } foreach(string convItem in conveyorWordGObjLookup) { GameObject tmpObj = GameObject.Find(convItem); if(tmpObj != null) { objsToUnPause.Add(tmpObj); tmpObj.SetActive(false); } }*/ getDeliveryChuteScript().setPauseState(pause); CircleTimerScript chopTimerScript = getChopTimerScript(); if(chopTimerScript != null) { chopTimerScript.setPause(pause); } } else { pause = false; if(firstTimeFlag) { firstTimeFlag = false; genNextLevel(); } //LineDragActiveNDraw swipeMang = GameObject.Find("LineMang").GetComponent<LineDragActiveNDraw>(); //swipeMang.setPause(false); PlayerBlockMovementScript pbms = GameObject.Find("GlobObj").GetComponent<PlayerBlockMovementScript>(); if(pbms != null) { pbms.enabled = true; } /*for(int i=0; i<objsToUnPause.Count;i++) { objsToUnPause[i].SetActive(true); } objsToUnPause.Clear();*/ //conveyorCurrentTime = Time.time; getDeliveryChuteScript().setPauseState(pause); CircleTimerScript chopTimerScript = getChopTimerScript(); if(chopTimerScript != null) { chopTimerScript.setPause(pause); } } } public new void respondToEvent(string para_sourceID, string para_eventID, System.Object para_eventData) { base.respondToEvent(para_sourceID,para_eventID,para_eventData); if(para_sourceID == "BigPipe") { if(para_eventID == "EnterStart") { setWhistleVisibility(true); } else if(para_eventID == "DeliveryChuteEnter") { DeliveryChuteScript dcs = getDeliveryChuteScript(); GameObject nwWordBlock = dcs.getAttachedWordGObj(); nwWordBlock.transform.parent = null; growScale = dcs.getGrowScale(); registerNewWordBlock(nwWordBlock,currWordItem.getWordLength(),new int[] {0,-1},currWordItem.getID()); registerNewConveyorWord(nwWordBlock); recordPresentedConfig(currLvlConfig); LineDragActiveNDraw swipeMang = GameObject.Find("LineMang").GetComponent<LineDragActiveNDraw>(); swipeMang.setPause(false); SplittableBlockUtil.setStateOfSplitDetectsForWord(nwWordBlock,true); // Switch timer back on. //conveyorCurrentTime = Time.time; //conveyorTimerOn = true; ScoreBoardScript sbs = getScoreBoardScript(); sbs.resetCrosses(); getChopTimerScript().reset(); closeGate(); } } else if(para_eventID == "SwipeHit") { string[] swipeLocInfo = (string[]) para_eventData; handleSplitterHit(swipeLocInfo[0],swipeLocInfo[1]); } else if(para_eventID == "SwipeComplete") { if(GameObject.Find(para_sourceID).transform.parent != null) { if(GameObject.Find(para_sourceID).transform.parent.name == "SkeletonSwipeHand")// { if((isInAutoSplitMode)&&(GameObject.Find("SkeletonSwipeHand") != null)) { Destroy(GameObject.Find("SkeletonSwipeHand")); if(syllsForAutoSplit.Count > 0) { performNextAutoSwipe(); } else { isInAutoSplitMode = false; LineDragActiveNDraw swipeMang = GameObject.Find("LineMang").GetComponent<LineDragActiveNDraw>(); swipeMang.setPause(true); } } } } } else if(para_eventID == "HighlightSequence") { if(nxtIndexForOp < orderedFullySplitConvObjNames.Count) { performNextHighlightSequence(); } else { // if((!wordUnattempted)&&( ! hasGotWrongAttemptOnCurrentWord())) { ScoreBoardScript sbs = getScoreBoardScript(); sbs.registerListener("AcScen",this); getScoreBoardScript().addStar(); } else { respondToEvent("Scoreboard","ScoreboardUpdate",null); } } } else if(para_eventID == "ScoreboardUpdate") { // All clear to open the gate and start placing // the cut blocks automatically in the grid. openGate(); isPerformingPositioningSequence = true; nxtIndexForOp = 0; isWaitingForConveyorRowClearence = false; moveNextBlockToGrid(); } else if(para_eventID == "MoveToGridAndTransformSequence") { // Delete Crack. if(cracksGObjs.Count > 0) { Destroy(cracksGObjs[0]); cracksGObjs.RemoveAt(0); } performIndivisibleSpawn(GameObject.Find(para_sourceID)); droppingWords.Add(para_sourceID); isWaitingForConveyorRowClearence = false; if(nxtIndexForOp == orderedFullySplitConvObjNames.Count) { // End of placement sequence. isPerformingPositioningSequence = false; chuteBusy = false; nxtIndexForOp = 0; } } else if(para_sourceID == "SkeletonSwipeHand") { if(para_eventID == "MoveToLocation") { LineFollowActiveNDraw lfand = GameObject.Find(para_sourceID).transform.FindChild("FingerTip").GetComponent<LineFollowActiveNDraw>(); lfand.triggerSwipeComplete(); Destroy(GameObject.Find(para_sourceID)); } } else if(para_eventID == "GateOpenAni") { } else if(para_eventID == "GateCloseAni") { // If tts is needed then say the word. if(currLvlConfig.getUseTtsFlag()) { try { if(gameObject.GetComponent<AudioSource>() == null) { gameObject.AddComponent<AudioSource>(); } audio.PlayOneShot(WorldViewServerCommunication.tts.say(currLvlConfig.getWordItem().getWordAsString())); } catch(System.Exception ex) { Debug.LogError("Failed to use TTS. "+ex.Message); } } // Restart Timer. getChopTimerScript().init(wordChopTimerDuration_Sec); getChopTimerScript().setVisibilityState(true); } else if(para_eventID == "CircleTimerFinished") { buildNRecordConfigOutcome(new object[] { false }); triggerAutoSwipeSequence(conveyorWordObjID); } } // LOGIC FUNCTIONS. private void openGate() { getChopTimerScript().setVisibilityState(false); ScoreBoardScript sbs = getScoreBoardScript(); sbs.resetCrosses(); GateScript gs = transform.gameObject.GetComponent<GateScript>(); if(gs == null) { gs = transform.gameObject.AddComponent<GateScript>(); } else { gs.enabled = true; } gs.registerListener("AcScen",this); gs.openGate(); } private void closeGate() { setWhistleVisibility(false); GateScript gs = transform.gameObject.GetComponent<GateScript>(); if(gs == null) { gs = transform.gameObject.AddComponent<GateScript>(); } else { gs.enabled = true; } gs.registerListener("AcScen",this); gs.closeGate(); } private void triggerChuteToFetchAndReturnWord() { DeliveryChuteScript dcs = getDeliveryChuteScript(); currWordItem = currLvlConfig.getWordItem(); dcs.performFetchWordSequence(currWordItem.getWordAsString(), dropGrid_WorldGProp, textPlanePrefab, splitDetectorPrefab, itemToSplitPrefabArr, framePrefab, scalableGlowPrefab, nettingPrefab); } private void registerNewWordBlock(GameObject para_wordBlockGObj, int para_wordLength, int[] para_gridCoords, int para_lvlID) { string suffix = (para_wordBlockGObj.name.Split(':'))[1]; string wordBlockName = "Block-"+nxtWordID+":"+suffix; para_wordBlockGObj.name = wordBlockName; int assignedID = nxtWordID; nxtWordID++; tetrisInfMap.Add(wordBlockName,new TetrisInfo(assignedID,para_gridCoords,para_wordLength,false)); numIDToStrIDMap.Add(assignedID,wordBlockName); blockToWDataMap.Add("Block-"+(assignedID), ""+para_lvlID); } // WARNING: Call registerNewWordBlock before this. private void registerNewConveyorWord(GameObject para_nwConveyorBlock) { // Clear items. conveyorWordObjID = null; conveyorWordGObjLookup.Clear(); currConvWordBeingDropped = null; // Update items. conveyorWordObjID = para_nwConveyorBlock.name.Split(':')[0]; conveyorWordGObjLookup.Add(para_nwConveyorBlock.name); currConvWordBeingDropped = para_nwConveyorBlock.name; splitsDoneByGame = new List<int>(); //resetConveyorTimerAndAttempts(); conveyorOpen = false; } private bool hasGotWrongAttemptOnCurrentWord() { bool flag = false; if(conWordAttemptsStates != null) { for(int i=0; i<conWordAttemptsStates.Length; i++) { if(conWordAttemptsStates[i]) { flag = true; break; } } } return flag; } private void triggerWrongSplitConsequences(string para_parentObjName, ref GameObject para_hitSplitDetector) { triggerSoundAtCamera("Buzzer_wrong_split"); ScoreBoardScript sbs = getScoreBoardScript(); if(sbs != null) { sbs.addWrongCross(); } string prefix1 = para_parentObjName.Split(':')[0]; string prefix2 = currConvWordBeingDropped.Split(':')[0]; if(prefix1 == prefix2) { if(conWordAttemptsStates[conWordAttemptsStates.Length-2] == true) { // Has reached max amount of tries. conWordAttemptsStates[conWordAttemptsStates.Length-1] = true; // Record outcome for this config. numIncorrectWordSplits++; buildNRecordConfigOutcome(new object[] { false }); // Trigger Auto Swipe. // Prevent User Swipes. LineDragActiveNDraw swipeMang = GameObject.Find("LineMang").GetComponent<LineDragActiveNDraw>(); swipeMang.setPause(true); // Trigger Auto Swipes. triggerAutoSwipeSequence(prefix1); } else { for(int i=0; i<conWordAttemptsStates.Length; i++) { if(conWordAttemptsStates[i] == false) { conWordAttemptsStates[i] = true; break; } } } } } private List<GameObject> triggerCorrectSplitConsequences(string para_wordObjName, int para_splitID) { GameObject wordObj = GameObject.Find(para_wordObjName); Transform wOverlay = wordObj.transform.FindChild("WordOverlay"); GameObject reqSplitDetector = (wOverlay.FindChild("SplitDet-"+para_splitID)).gameObject; return triggerCorrectSplitConsequences(para_wordObjName,ref reqSplitDetector); } private List<GameObject> triggerCorrectSplitConsequences(string para_parentObjName, ref GameObject para_hitSplitDetector) { int splitID = int.Parse((para_hitSplitDetector.name.Split('-'))[1]); // Trigger Sparks: if(showSparksEffect) { Vector3 sparksLoc = new Vector3(para_hitSplitDetector.transform.position.x,para_hitSplitDetector.transform.position.y,Camera.main.transform.position.z + 1); Instantiate(sparksPrefab,sparksLoc,Quaternion.identity); } // Trigger Sound: triggerSoundAtCamera("sfx_Swipe"); // Display Crack: Transform reqCrack = crackPrefabArr[Random.Range(0,crackPrefabArr.Length)]; float cWidth = dropGrid_WorldGProp.cellWidth * growScale; //Vector3 crackLoc = new Vector3(para_hitSplitDetector.transform.position.x,para_hitSplitDetector.transform.position.y,transform.position.z - 1); GameObject nwCrack = WorldSpawnHelper.initObjWithinWorldBounds(reqCrack,1f,1f, "Crack"+splitID, new Rect(para_hitSplitDetector.transform.position.x - (cWidth/2f), para_hitSplitDetector.transform.position.y + ((dropGrid_WorldGProp.cellHeight * growScale)/2f), cWidth, (dropGrid_WorldGProp.cellHeight * growScale)), null, para_hitSplitDetector.transform.position.z, upAxisArr); //Transform nwCrack = (Transform) Instantiate(reqCrack,crackLoc,Quaternion.identity); cracksGObjs.Add(nwCrack); // Split Word: // Switch layer type to default in order to prevent further input from this split detector. para_hitSplitDetector.layer = 0; // Color Green. MeshRenderer tmpRend = (MeshRenderer) para_hitSplitDetector.GetComponent(typeof(MeshRenderer)); Material nwMat = new Material(Shader.Find("Diffuse")); nwMat.color = Color.green; tmpRend.material = nwMat; tmpRend.enabled = true; // Split and register child blocks. List<GameObject> splitObjs = WordFactoryYUp.performSplitOnWordBoard(ref para_hitSplitDetector,framePrefab,scalableGlowPrefab); for(int i=0; i<splitObjs.Count; i++) { string splitObjName = splitObjs[i].name; string prefix = splitObjName.Split(':')[0]; string suffix = splitObjName.Split(':')[1]; TetrisInfo parentTetInf = tetrisInfMap[para_parentObjName]; int parentX = parentTetInf.coords[0]; int parentY = parentTetInf.coords[1]; int parentSuffixStart = int.Parse((para_parentObjName.Split(':')[1]).Split('-')[0]); string tmpWDataMapFullKey = blockToWDataMap[prefix]; SJWordItem parentWData = findWordInCache(int.Parse(tmpWDataMapFullKey)); //int sourceBlockID = int.Parse(prefix.Split('-')[1]); int childX1_FromParent = int.Parse(suffix.Split('-')[0]); int childX2_FromParent = int.Parse(suffix.Split('-')[1]); int[] childCoords = { (parentX + (childX1_FromParent - parentSuffixStart)), parentY }; // Check if child is indivisible. bool isIndivisible = parentWData.checkIfWordSegmentIsIndivisible(childX1_FromParent,childX2_FromParent); // Decide whether to drop or not. if(prefix == conveyorWordObjID) { conveyorWordGObjLookup.Add(splitObjName); conveyorWordGObjLookup.Remove(para_parentObjName); } else { droppingWords.Add(splitObjName); } tetrisInfMap.Add(splitObjName,new TetrisInfo(nxtWordID, childCoords, (childX2_FromParent - childX1_FromParent + 1),isIndivisible)); int assignedID = nxtWordID; nxtWordID++; numIDToStrIDMap.Add(assignedID,splitObjName); } // Delete parent block references. droppingWords.Remove(para_parentObjName); stationaryWords.Remove(para_parentObjName); tetrisInfMap.Remove(para_parentObjName); // Trigger block updates as some may have become free. updateStationaryBlocks = true; return splitObjs; } private void moveNextBlockToGrid() { if(nxtIndexForOp < orderedFullySplitConvObjNames.Count) { string blockName = orderedFullySplitConvObjNames[nxtIndexForOp]; TetrisInfo tInf = tetrisInfMap[blockName]; GameObject reqGObj = GameObject.Find(blockName); int gridColForBlock = ((int) (gridWidthInCells/2f)) - ((int) (tInf.wordSize/2f)); if((gridColForBlock < 0)||(gridColForBlock >= gridWidthInCells)) { gridColForBlock = 0; } int[] nwGridCoords = new int[2] {gridColForBlock,0}; tInf.coords = nwGridCoords; tetrisInfMap[blockName] = tInf; if(conveyorWordGObjLookup.Contains(blockName)) { conveyorWordGObjLookup.Remove(blockName); if(conveyorWordGObjLookup.Count == 0) { conveyorWordObjID = null; currConvWordBeingDropped = null; } } for(int c=tInf.coords[0]; c<(tInf.coords[0] + tInf.wordSize); c++) { if(c < (gridWidthInCells-1)) { gridState[c,tInf.coords[1]] = tInf.id; debugGridState[c,tInf.coords[1]] = ""+tInf.id; } } Rect gridBoundsForBlock = new Rect(dropGrid_WorldGProp.x + (tInf.coords[0] * (dropGrid_WorldGProp.cellWidth + dropGrid_WorldGProp.borderThickness)) + dropGrid_WorldGProp.borderThickness, dropGrid_WorldGProp.y + ((dropGrid_WorldGProp.cellHeight + dropGrid_WorldGProp.borderThickness)) + dropGrid_WorldGProp.borderThickness, (tInf.wordSize * dropGrid_WorldGProp.cellWidth) + ((tInf.wordSize-1) * dropGrid_WorldGProp.borderThickness), dropGrid_WorldGProp.cellHeight); Vector3 movDest = new Vector3(gridBoundsForBlock.x + (gridBoundsForBlock.width/2f), gridBoundsForBlock.y - (gridBoundsForBlock.height/2f), dropGrid_WorldGProp.z); float initWidthOfBlock = (dropGrid_WorldGProp.cellWidth * tInf.wordSize * growScale); float initHeightOfBlock = (dropGrid_WorldGProp.cellHeight * growScale); CustomAnimationManager caMang = reqGObj.AddComponent<CustomAnimationManager>(); List<List<AniCommandPrep>> cmdBatchList = new List<List<AniCommandPrep>>(); List<AniCommandPrep> cmdBatch1 = new List<AniCommandPrep>(); cmdBatch1.Add(new AniCommandPrep("TeleportToLocation",1,new List<System.Object>() { new float[3] {movDest.x,movDest.y,movDest.z} })); cmdBatch1.Add(new AniCommandPrep("ResizeToWorldSize",1,new List<System.Object>() { new float[3] {gridBoundsForBlock.width,gridBoundsForBlock.height,1}, new float[3] {initWidthOfBlock,initHeightOfBlock,1}})); List<AniCommandPrep> cmdBatch2 = new List<AniCommandPrep>(); cmdBatch2.Add(new AniCommandPrep("ColorTransition",1,new List<System.Object>() { new float[4] {0,1,0,1}, 2f })); cmdBatchList.Add(cmdBatch1); cmdBatchList.Add(cmdBatch2); caMang.init("MoveToGridAndTransformSequence",cmdBatchList); caMang.registerListener("AcScen",this); nxtIndexForOp++; isWaitingForConveyorRowClearence = true; } } private List<string> performClearLineEffect(int para_hooveLine) { HashSet<string> nwDestroyedBlocks = new HashSet<string>(); float tmpY = dropGrid_WorldGProp.y - dropGrid_WorldGProp.borderThickness - (dropGrid_WorldGProp.cellHeight/2f); Vector3 hooveLineCentrePos = new Vector3(dropGrid_WorldGProp.x + (dropGrid_WorldGProp.totalWidth/2f), tmpY - ((dropGrid_WorldGProp.cellHeight + dropGrid_WorldGProp.borderThickness) * (para_hooveLine-numPrequelRows)), dropGrid_WorldGProp.z); Rect highlighterWorldBounds = new Rect(dropGrid_WorldGProp.x,hooveLineCentrePos.y + (dropGrid_WorldGProp.cellHeight/2f),dropGrid_WorldGProp.totalWidth,dropGrid_WorldGProp.cellHeight); GameObject rowHighlighter = WorldSpawnHelper.initObjWithinWorldBounds(planePrefab,1,1,"HooveRowHighlighter",highlighterWorldBounds,null,dropGrid_WorldGProp.z + 0.1f,upAxisArr); rowHighlighter.renderer.material.color = new Color(0,0.4f,0); //new Color(0.9f,0.7f,0.05f); GameObject hooveLineCollection = new GameObject("HooveLineCollection"); hooveLineCollection.transform.position = hooveLineCentrePos; for(int i=0; i<gridWidthInCells; i++) { string blockName = numIDToStrIDMap[gridState[i,para_hooveLine]]; int wordLength = tetrisInfMap[blockName].wordSize; GameObject tmpBlockToRemove = GameObject.Find(blockName); tmpBlockToRemove.transform.parent = hooveLineCollection.transform; nwDestroyedBlocks.Add(blockName); tetrisInfMap.Remove(blockName); numIDToStrIDMap.Remove(gridState[i,para_hooveLine]); stationaryWords.Remove(blockName); droppingWords.Remove(blockName); for(int k=0; k<wordLength; k++) { gridState[i + k,para_hooveLine] = 0; debugGridState[i + k,para_hooveLine] = "0"; } i += (wordLength-1); // -1 because the for loop will increment i once anyway. } pause = true; // Trigger hoove. GameObject solomonWholeGObj = GameObject.Find("SolomonWhole"); GameObject hooveCntr = (solomonWholeGObj.transform.FindChild("HooveCentre")).gameObject; Vector3 hooveSpot = new Vector3(solomonWholeGObj.transform.position.x, hooveLineCentrePos.y + (solomonWholeGObj.transform.position.y - hooveCntr.transform.position.y), solomonWholeGObj.transform.position.z); float hooveMoveSpeed = 3f; float hooveSuctionSpeed = 15f; Vector3 hooveMovVectWithSpeed = (new Vector3(0,1,0)) * (dropGrid_WorldGProp.cellHeight * hooveMoveSpeed); Vector3 hooveSuctionVectWithSpeed = (new Vector3(-1,0,0)) * (dropGrid_WorldGProp.cellWidth * hooveSuctionSpeed); HooveScript hScript = solomonWholeGObj.AddComponent<HooveScript>(); hScript.triggerHoove(hooveSpot,hooveMovVectWithSpeed,hooveSuctionVectWithSpeed,dropGrid_WorldGProp.x - (dropGrid_WorldGProp.totalWidth/2f),hooveLineCollection,sfxPrefab); LineDragActiveNDraw swipeMang = GameObject.Find("LineMang").GetComponent<LineDragActiveNDraw>(); swipeMang.setPause(true); return (new List<string>(nwDestroyedBlocks)); } private int searchForLinesToClear() { int rowID = -1; for(int r=(gridState.GetLength(1)-1); r>0; r--) { bool fullLineFormed = true; for(int c=0; c<gridWidthInCells; c++) { if(gridState[c,r] == 0) { c = gridWidthInCells; // tmp hack. fullLineFormed = false; break; } else { string blockName = numIDToStrIDMap[gridState[c,r]]; TetrisInfo tmpTInf = tetrisInfMap[blockName]; if((! tmpTInf.isIndivisible)) { c = gridWidthInCells; // tmp hack. fullLineFormed = false; break; } } } if(fullLineFormed) { rowID = r; break; } } return rowID; } private bool isRowFree(int para_rowID) { bool retVal = true; for(int i=0; i<gridState.GetLength(0); i++) { if(gridState[i,para_rowID] != 0) { retVal = false; break; } } return retVal; } private bool isRowFree(int para_rowID, bool para_ignoreConveyorObjs) { bool retVal = true; for(int i=0; i<gridState.GetLength(0); i++) { if(gridState[i,para_rowID] != 0) { if(para_ignoreConveyorObjs) { if(conveyorWordGObjLookup.Contains(numIDToStrIDMap[gridState[i,para_rowID]])) { } else { retVal = false; break; } } else { retVal = false; break; } } } return retVal; } private void handleSplitterHit(GameObject para_splitDetectObj) { GameObject tmpOverlayObj = (para_splitDetectObj.transform.parent).gameObject; GameObject tmpMasterObj = (tmpOverlayObj.transform.parent).gameObject; handleSplitterHit(tmpMasterObj.name,para_splitDetectObj.name); } private void handleSplitterHit(string para_masterObjName, string para_splitDetectObjName) { // *** Check Where Split Event Occurred *** if( ! isInAutoSplitMode) { wordUnattempted = false; } GameObject tmpMasterObj = GameObject.Find(para_masterObjName); GameObject tmpOverlayObj = (tmpMasterObj.transform.FindChild("WordOverlay")).gameObject; GameObject hitSplitDetector = (tmpOverlayObj.transform.FindChild(para_splitDetectObjName)).gameObject; int splitIndex = int.Parse(hitSplitDetector.name.Split('-')[1]); string tmpWDatabaseWholeKey = blockToWDataMap[((tmpMasterObj.name).Split(':')[0])]; SJWordItem reqWord = findWordInCache(int.Parse(tmpWDatabaseWholeKey)); if( ! isInAutoSplitMode) { playerSplitPattern.Add(splitIndex); } if(! reqWord.isValidSplitIndex(splitIndex)) { // Invalid split. triggerWrongSplitConsequences(tmpMasterObj.name,ref hitSplitDetector); if(serverCommunication != null) { serverCommunication.wordSolvedCorrectly(reqWord.getWordAsString(),false,"Invalid splits",reqWord.languageArea,reqWord.difficulty); } } else { // Valid split. // Perform split. triggerCorrectSplitConsequences(tmpMasterObj.name,ref hitSplitDetector); if(serverCommunication != null) { serverCommunication.wordSolvedCorrectly(reqWord.getWordAsString(),true,"",reqWord.languageArea,reqWord.difficulty); } // If this is the final split in the word then trigger the transformation sequence. List<List<string>> wordSegmentExistenceLists = getExistenceOfWordSegments(para_masterObjName); List<string> existingSegments = wordSegmentExistenceLists[0]; List<string> nonExistingSegments = wordSegmentExistenceLists[1]; bool completeStatus = (nonExistingSegments.Count == 0); if(completeStatus) { LineDragActiveNDraw swipeMang = GameObject.Find("LineMang").GetComponent<LineDragActiveNDraw>(); swipeMang.setPause(true); orderedFullySplitConvObjNames = existingSegments; nxtIndexForOp = 0; // Tmp Switch Off Conveyor Timer. //conveyorTimerOn = false; getChopTimerScript().setPause(true); if( !isInAutoSplitMode) { // Record outcome for this config. numCorrectWordSplits++; buildNRecordConfigOutcome(new object[] { true }); } performNextHighlightSequence(); } } } private List<List<string>> getExistenceOfWordSegments(string para_masterObjName) { string wordID = para_masterObjName.Split(':')[0]; string wDataFullKey = blockToWDataMap[wordID]; SJWordItem reqWord = findWordInCache(int.Parse(wDataFullKey)); string wordStr = reqWord.getWordAsString(); int[] databaseSyllPositions = reqWord.getSyllSplitPositions(); List<int> syllSplitPositions = new List<int>(); for(int i=0; i<databaseSyllPositions.Length; i++) { syllSplitPositions.Add(databaseSyllPositions[i]); } syllSplitPositions.Add(wordStr.Length-1); List<string> existingSegments = new List<string>(); List<string> nonExistingSegments = new List<string>(); int startLetterIndex = 0; for(int i=0; i<syllSplitPositions.Count; i++) { int endLetterIndex = syllSplitPositions[i]; string segmentUniqueID = wordID + ":" + "" + startLetterIndex + "-" + endLetterIndex; if(tetrisInfMap.ContainsKey(segmentUniqueID)) { if(! existingSegments.Contains(segmentUniqueID)) { existingSegments.Add(segmentUniqueID); } } else { if(! nonExistingSegments.Contains(segmentUniqueID)) { nonExistingSegments.Add(segmentUniqueID); } } startLetterIndex = endLetterIndex + 1; } List<List<string>> retData = new List<List<string>>(); retData.Add(existingSegments); retData.Add(nonExistingSegments); return retData; } private void performNextHighlightSequence() { string para_segmentID = orderedFullySplitConvObjNames[nxtIndexForOp]; GameObject reqSeg = GameObject.Find(para_segmentID); CustomAnimationManager caMang = reqSeg.AddComponent<CustomAnimationManager>(); List<List<AniCommandPrep>> cmdBatchList = new List<List<AniCommandPrep>>(); List<AniCommandPrep> cmdBatch1 = new List<AniCommandPrep>(); cmdBatch1.Add(new AniCommandPrep("ColorTransition",1, new List<System.Object>() { new float[4] {0,1,0,1}, 0.25f })); List<AniCommandPrep> cmdBatch2 = new List<AniCommandPrep>(); cmdBatch2.Add(new AniCommandPrep("ColorTransition",1, new List<System.Object>() { new float[4] {1,1,1,1}, 0.25f })); cmdBatchList.Add(cmdBatch1); cmdBatchList.Add(cmdBatch2); caMang.init("HighlightSequence",cmdBatchList); caMang.registerListener("AcScen",this); nxtIndexForOp++; } private void createRandomStartGrid() { int rowsFromBottomToFill = 3; int maxSyllLength = 5; float[] whiteSpaceProbPerRow = new float[3] { 0.1f, 0.1f, 0.1f }; for(int tmpRCounter=0; tmpRCounter<rowsFromBottomToFill; tmpRCounter++) { bool rowHasWhite = false; List<string> rowBlocks = new List<string>(); for(int c=0; c<gridWidthInCells; c++) { int maxBound = maxSyllLength; if((c+maxBound) > gridWidthInCells) { maxBound = gridWidthInCells - c; } int nxtBlockSize = Random.Range(1,maxBound); if(nxtBlockSize > 0) { bool isWhiteSpace = (Random.Range(0,1.0f) <= whiteSpaceProbPerRow[tmpRCounter]); if(!isWhiteSpace) { //Debug.Log("Creating Brick at: {"+c+","+((gridHeightInCells+numPrequelRows)-1-tmpRCounter)+"}"); string nwRBlock = createIndivisibleAtGridLocation(new int[2] {c,(gridHeightInCells+numPrequelRows)-1 - tmpRCounter},nxtBlockSize); rowBlocks.Add(nwRBlock); } else { rowHasWhite = true; } c += nxtBlockSize; } } if( ! rowHasWhite) { int randIndex = Random.Range(0,rowBlocks.Count); destroyAndDeregisterBlock(rowBlocks[randIndex]); } } } private void destroyAndDeregisterBlock(string para_existingBlockName) { GameObject reqObj = GameObject.Find(para_existingBlockName); if(reqObj != null) { // Destroy from world. Destroy(reqObj); // Update Datastructures. TetrisInfo tmpTInf = tetrisInfMap[para_existingBlockName]; numIDToStrIDMap.Remove(tmpTInf.id); int[] gCoords = tmpTInf.coords; for(int c=gCoords[0]; c<(gCoords[0] + tmpTInf.wordSize); c++) { if((c >= 0)&&(c < gridWidthInCells)) { gridState[c,gCoords[1]] = 0; debugGridState[c,gCoords[1]] = "0"; } } tetrisInfMap.Remove(para_existingBlockName); if(droppingWords.Contains(para_existingBlockName)) { droppingWords.Remove(para_existingBlockName); } } } private string createIndivisibleAtGridLocation(int[] para_startLetterCoords, int para_length) { // Create new name and key. int assignedID = nxtWordID; string blkName = "Block-"+assignedID+":"+"0-"+(para_length-1); nxtWordID++; // Spawn the object. float boundsWidth = (para_length * dropGrid_WorldGProp.cellWidth); float boundsHeight = dropGrid_WorldGProp.cellHeight; Rect spawnWorldBounds = new Rect(dropGrid_WorldGProp.x + ((dropGrid_WorldGProp.borderThickness + dropGrid_WorldGProp.cellWidth) * para_startLetterCoords[0]), dropGrid_WorldGProp.y - ((dropGrid_WorldGProp.borderThickness + dropGrid_WorldGProp.cellHeight) * para_startLetterCoords[1]) + ((dropGrid_WorldGProp.borderThickness + dropGrid_WorldGProp.cellHeight) * 1), boundsWidth, boundsHeight); Transform reqSyllPrefab = selectRandomPrefabForSyll(para_length); GameObject nwIndiObj = WorldSpawnHelper.initObjWithinWorldBounds(reqSyllPrefab, reqSyllPrefab.renderer.bounds.size.x, reqSyllPrefab.renderer.bounds.size.y, blkName, spawnWorldBounds, null, dropGrid_WorldGProp.z, upAxisArr); //WorldSpawnHelper.initObjWithinWorldBounds(planePrefab,"DebugPlane",spawnWorldBounds,dropGrid_WorldGProp.z,upAxisArr); nwIndiObj.tag = "Indivisible"; SpriteRenderer tmpSR = nwIndiObj.GetComponent<SpriteRenderer>(); tmpSR.sortingOrder = 6; tmpSR.sprite.texture.wrapMode = TextureWrapMode.Clamp; applyMovableIndivisibleEffect(nwIndiObj); // Update Datastructures. tetrisInfMap.Add(blkName,new TetrisInfo(assignedID,new int[2] {para_startLetterCoords[0],para_startLetterCoords[1]},para_length,true)); numIDToStrIDMap.Add(assignedID,blkName); for(int c=para_startLetterCoords[0]; c<(para_startLetterCoords[0] + para_length); c++) { gridState[c,para_startLetterCoords[1]] = assignedID; debugGridState[c,para_startLetterCoords[1]] = ""+assignedID; } droppingWords.Add(blkName); return nwIndiObj.name; } private void performIndivisibleSpawn(GameObject para_objToChange) { TetrisInfo tInf = tetrisInfMap[para_objToChange.name]; int syllLength = tInf.wordSize; if(syllLength >= gridWidthInCells) { //int overflowLength = gridWidthInCells - syllLength; //tInf.coords[0] = 3; syllLength = 6; } Vector3 objCentrePos = new Vector3(para_objToChange.transform.position.x, para_objToChange.transform.position.y, para_objToChange.transform.position.z); // Determine if this is a moveable or fixed block. string prefix = para_objToChange.name.Split(':')[0]; string wDataFullKey = blockToWDataMap[prefix]; SJWordItem reqFullWord = findWordInCache(int.Parse(wDataFullKey)); string[] blockLetterRangeStrArr = (para_objToChange.name.Split(':')[1]).Split('-'); int[] blockLetterRange = new int[2] { int.Parse(blockLetterRangeStrArr[0]), int.Parse(blockLetterRangeStrArr[1]) }; int lastLetterIDForWord = blockLetterRange[1]; int boundarySplitToCheck = lastLetterIDForWord; if(lastLetterIDForWord == (reqFullWord.getWordLength()-1)) { boundarySplitToCheck = blockLetterRange[0] - 1; } bool isFixedBlock = (splitsDoneByGame.Contains(boundarySplitToCheck)); destroyAndDeregisterBlock(para_objToChange.name); //Destroy(para_objToChange); // Create indivisibles to replace the object. int maxIndivisibleLength = 4; List<int[]> itemStartCoords = new List<int[]>(); List<int> itemLengths = new List<int>(); //List<string> itemNames = new List<string>(); if(syllLength <= maxIndivisibleLength) { itemStartCoords.Add(tInf.coords); itemLengths.Add(tInf.wordSize); } else { int[] tmpCoords = new int[2]; tmpCoords[0] = tInf.coords[0]; tmpCoords[1] = 0; int remLength = syllLength; while(remLength > 0) { int maxL = 2;// maxIndivisibleLength; if(remLength < maxL) { maxL = remLength; } int chosenLength = Random.Range(1,(maxL+1)); itemStartCoords.Add(new int[2] {tmpCoords[0],tmpCoords[1]}); itemLengths.Add(chosenLength); tmpCoords[0] += chosenLength; remLength -= chosenLength; } } for(int i=0; i<itemStartCoords.Count; i++) { string nwItemName = createIndivisibleAtGridLocation(itemStartCoords[i],itemLengths[i]); GameObject nwIndiObj = GameObject.Find(nwItemName); if(isFixedBlock) { applyFixedIndivisibleEffect(nwIndiObj); } else { applyMovableIndivisibleEffect(nwIndiObj); } } // Apply sound effect and cloud prefab. triggerSoundAtCamera("sfx_BlockToObject"); if(blockToObjectEffect != null) { Vector3 effectSpawnPt = new Vector3(objCentrePos.x,objCentrePos.y,objCentrePos.z - 0.5f); Transform nwEffect = (Transform) Instantiate(blockToObjectEffect,effectSpawnPt,Quaternion.identity); nwEffect.localEulerAngles = new Vector3(blockToObjectEffect.localEulerAngles.x, blockToObjectEffect.localEulerAngles.y, blockToObjectEffect.localEulerAngles.z); } } private void applyMovableIndivisibleEffect(GameObject para_indiObj) { if(para_indiObj.GetComponent<BoxCollider>() == null) { para_indiObj.AddComponent<BoxCollider>(); } } private void applyFixedIndivisibleEffect(GameObject para_indiObj) { // Mark this object as wrong, i.e. immovable. SplittableBlockUtil.applyColorToBlock(para_indiObj,unmovableBlockColor); // Remove collider to make this object immovable by the player. if(para_indiObj.GetComponent<BoxCollider>() != null) { Destroy(para_indiObj.GetComponent<BoxCollider>()); } if(para_indiObj.GetComponent<MeshCollider>() != null) { Destroy(para_indiObj.GetComponent<MeshCollider>()); } } private Transform selectRandomPrefabForSyll(int para_syllLength) { bool isUsingDefault = false; Transform[] tmpArr = null; switch(para_syllLength) { case 1: tmpArr = oneSyllPrefabs; break; case 2: tmpArr = twoSyllPrefabs; break; case 3: tmpArr = threeSyllPrefabs; break; case 4: tmpArr = fourSyllPrefabs; break; case 5: tmpArr = fiveSyllPrefabs; break; default: isUsingDefault = true; break; } if(isUsingDefault) { return planePrefab; } else { int chosenTexIndex = Random.Range(0,tmpArr.Length); return tmpArr[chosenTexIndex]; } } // Handlers for player block movement. public void intakeObjectDragStart() { LineDragActiveNDraw ldand = GameObject.Find("LineMang").GetComponent<LineDragActiveNDraw>(); ldand.setPause(true); } public void intakeObjectDragCommand(ref GameObject para_indivisibleGObj, int para_dragCommand) { if(pause) { return; } if( ! conveyorWordGObjLookup.Contains(para_indivisibleGObj.name)) { TetrisInfo tInfo = tetrisInfMap[para_indivisibleGObj.name]; bool canPerformOp = true; DPadDir cmd = (DPadDir) para_dragCommand; switch(cmd) { case DPadDir.NORTH: // North. if(tInfo.coords[1] > 0) { int tmpX = tInfo.coords[0]; int tmpY = tInfo.coords[1]-1; for(int i=tmpX; i<(tmpX + tInfo.wordSize); i++) { if((gridState[i,tmpY] != 0)||(tmpY < numPrequelRows)) { canPerformOp = false; break; } } if(canPerformOp) { Vector3 movUpV = new Vector3(0,(dropGrid_WorldGProp.cellHeight + dropGrid_WorldGProp.borderThickness),0); para_indivisibleGObj.transform.position += movUpV; for(int x=tmpX; x<(tmpX + tInfo.wordSize); x++) { gridState[x,tInfo.coords[1]] = 0; gridState[x,tmpY] = tInfo.id; debugGridState[x,tInfo.coords[1]] = "0"; debugGridState[x,tmpY] = ""+tInfo.id; } tInfo.coords[1] = tmpY; tetrisInfMap[para_indivisibleGObj.name] = tInfo; //updateStationaryBlocks = true; } else { break; } } break; case DPadDir.SOUTH: if(tInfo.coords[1] < (gridState.GetLength(1)-1)) { int tmpX = tInfo.coords[0]; int tmpY = tInfo.coords[1]+1; for(int i=tmpX; i<(tmpX + tInfo.wordSize); i++) { if((gridState[i,tmpY] != 0)||(tmpY < numPrequelRows)) { canPerformOp = false; break; } } if(canPerformOp) { Vector3 movDownV = new Vector3(0,-(dropGrid_WorldGProp.cellHeight + dropGrid_WorldGProp.borderThickness),0); para_indivisibleGObj.transform.position += movDownV; for(int x=tmpX; x<(tmpX + tInfo.wordSize); x++) { gridState[x,tInfo.coords[1]] = 0; gridState[x,tmpY] = tInfo.id; debugGridState[x,tInfo.coords[1]] = "0"; debugGridState[x,tmpY] = ""+tInfo.id; } tInfo.coords[1] = tmpY; tetrisInfMap[para_indivisibleGObj.name] = tInfo; //updateStationaryBlocks = true; } else { break; } } break; case DPadDir.WEST: if(tInfo.coords[0] > 0) { int tmpX = tInfo.coords[0]; int tmpY = tInfo.coords[1]; if((gridState[tmpX-1,tmpY] != 0)||(tmpY < numPrequelRows)) { canPerformOp = false; } if(canPerformOp) { Vector3 movWestV = new Vector3(-(dropGrid_WorldGProp.cellHeight + dropGrid_WorldGProp.borderThickness),0,0); para_indivisibleGObj.transform.position += movWestV; gridState[tmpX + tInfo.wordSize -1,tmpY] = 0; gridState[tmpX-1,tmpY] = tInfo.id; debugGridState[tmpX + tInfo.wordSize -1,tmpY] = "0"; debugGridState[tmpX-1,tmpY] = ""+tInfo.id; tInfo.coords[0]--; tetrisInfMap[para_indivisibleGObj.name] = tInfo; //updateStationaryBlocks = true; } else { break; } } break; case DPadDir.EAST: int nwX = tInfo.coords[0]+tInfo.wordSize; if(nwX <= (gridState.GetLength(0)-1)) { int tmpX = tInfo.coords[0]; int tmpY = tInfo.coords[1]; if((gridState[nwX,tmpY] != 0)||(tmpY < numPrequelRows)) { canPerformOp = false; } if(canPerformOp) { Vector3 movEastV = new Vector3((dropGrid_WorldGProp.cellHeight + dropGrid_WorldGProp.borderThickness),0,0); para_indivisibleGObj.transform.position += movEastV; gridState[tmpX,tmpY] = 0; gridState[nwX,tmpY] = tInfo.id; debugGridState[tmpX,tmpY] = "0"; debugGridState[nwX,tmpY] = ""+tInfo.id; tInfo.coords[0]++; tetrisInfMap[para_indivisibleGObj.name] = tInfo; //updateStationaryBlocks = true; } else { break; } } break; } } } public void intakeObjectDragStop(string para_blockReleased) { if(pause) { return; } stationaryWords.Remove(para_blockReleased); droppingWords.Add(para_blockReleased); LineDragActiveNDraw ldand = GameObject.Find("LineMang").GetComponent<LineDragActiveNDraw>(); ldand.setPause(false); updateStationaryBlocks = true; } public void noticeHooveTermination() { Destroy(GameObject.Find("SolomonWhole").GetComponent(typeof(HooveScript))); Destroy(GameObject.Find("HooveRowHighlighter")); updateStationaryBlocks = true; pause = false; updateLineCounterDisplay(); LineDragActiveNDraw swipeMang = GameObject.Find("LineMang").GetComponent<LineDragActiveNDraw>(); swipeMang.setPause(false); } private void updateLineCounterDisplay() { TextMesh tMesh = getLineCounterTMesh(); tMesh.text = ""+numHooveredLines; tMesh.renderer.sortingOrder = 100; tMesh.renderer.material.color = Color.black; } private void setWhistleVisibility(bool para_state) { whistleVisible = para_state; if(uiBounds == null) { uiBounds = new Dictionary<string, Rect>(); } GameObject whistleIcon = GameObject.Find("PitRight").transform.FindChild("WhistleIcon").gameObject; whistleIcon.renderer.enabled = para_state; whistleIcon.SetActive(para_state); Rect whistleIconGUIBounds = WorldSpawnHelper.getWorldToGUIBounds(whistleIcon.renderer.bounds,upAxisArr); if(uiBounds.ContainsKey("WhistleIcon")) { uiBounds["WhistleIcon"] = whistleIconGUIBounds; } else { uiBounds.Add("WhistleIcon",whistleIconGUIBounds); } } private void spawnSkeletonSwipeHand(Vector3 para_swipeStartPt, Vector3 para_swipeDestPt) { float skeleSwipeHand_Width = dropGrid_WorldGProp.cellWidth * 3; float skeleSwipeHand_Height = skeleSwipeHand_Width; float skeleSwipeHand_X = para_swipeStartPt.x; float skeleSwipeHand_Y = para_swipeStartPt.y; GameObject skeleSwipeHandObj = WorldSpawnHelper.initObjWithinWorldBounds(skeletonSwipeHandPrefab, skeletonSwipeHandPrefab.renderer.bounds.size.x, skeletonSwipeHandPrefab.renderer.bounds.size.y, "SkeletonSwipeHand", new Rect (skeleSwipeHand_X,skeleSwipeHand_Y,skeleSwipeHand_Width,skeleSwipeHand_Height), null, para_swipeStartPt.z, upAxisArr); GameObject skeleFingerTipObj = (skeleSwipeHandObj.transform.FindChild("FingerTip")).gameObject; LineFollowActiveNDraw lfand = skeleFingerTipObj.GetComponent<LineFollowActiveNDraw>(); lfand.init(WorldSpawnHelper.getWorldToGUIBounds(GameObject.Find("Background").renderer.bounds,upAxisArr),0.1f,dropGrid_WorldGProp.z - (dropGrid_WorldGProp.cellWidth * 1.75f),dropGrid_WorldGProp.z,"SplitDetect",0); lfand.registerListener("AcScen",this); MoveToLocation skeleMovScript = skeleSwipeHandObj.AddComponent<MoveToLocation>(); skeleMovScript.initScript(new Vector3(para_swipeDestPt.x + (skeleSwipeHandObj.renderer.bounds.size.x/2f), para_swipeDestPt.y - (skeleSwipeHandObj.renderer.bounds.size.y/2f), para_swipeDestPt.z), 2f); skeleMovScript.registerListener("AcScen",this); } private void triggerAutoSwipeSequence(string para_blockNamePrefix) { splitsDoneByGame = new List<int>(); isInAutoSplitMode = true; itemForAutoSplit = para_blockNamePrefix; string wDatabaseFullKey = blockToWDataMap[itemForAutoSplit]; SJWordItem reqWord = findWordInCache(int.Parse(wDatabaseFullKey)); int[] tmpSyllSplitArr = reqWord.getSyllSplitPositions(); if(syllsForAutoSplit == null) { syllsForAutoSplit = new List<int>(); } else { syllsForAutoSplit.Clear(); } for(int k=0; k<tmpSyllSplitArr.Length; k++) { syllsForAutoSplit.Add(tmpSyllSplitArr[k]); } if(syllsForAutoSplit.Count > 0) { performNextAutoSwipe(); } } private void performNextAutoSwipe() { bool foundBlockToSplit = false; while((foundBlockToSplit == false)&&(syllsForAutoSplit.Count > 0)) { int nxtTargetSplitDetID = syllsForAutoSplit[0]; foreach(string tmpConvWordID in conveyorWordGObjLookup) { string[] suffix = (tmpConvWordID.Split(':')[1]).Split('-'); int[] suffixNums = new int[2] { int.Parse(suffix[0]), int.Parse(suffix[1]) }; if((nxtTargetSplitDetID >= suffixNums[0])&&(nxtTargetSplitDetID < suffixNums[1])) { Bounds splitDetBounds = SplittableBlockUtil.getSplitDetectWorldBounds(tmpConvWordID,nxtTargetSplitDetID); float zVal = Camera.main.transform.position.z + 2f; Rect topOfPitWorld = CommonUnityUtils.get2DBounds(GameObject.Find("TopOfPit").renderer.bounds); Vector3 swipeStartPos = new Vector3(splitDetBounds.min.x + (splitDetBounds.size.x * 0.25f),topOfPitWorld.y - topOfPitWorld.height,zVal); Vector3 swipeEndPos = new Vector3(splitDetBounds.min.x + (splitDetBounds.size.x * 0.75f),topOfPitWorld.y,zVal); spawnSkeletonSwipeHand(swipeStartPos,swipeEndPos); foundBlockToSplit = true; splitsDoneByGame.Add(nxtTargetSplitDetID); break; } } syllsForAutoSplit.RemoveAt(0); } } private void resetAttempts() { wordUnattempted = true; for(int i=0; i<conWordAttemptsStates.Length; i++) { conWordAttemptsStates[i] = false; } } private ScoreBoardScript getScoreBoardScript() { ScoreBoardScript sbs = transform.GetComponent<ScoreBoardScript>(); if(sbs == null) { sbs = transform.gameObject.AddComponent<ScoreBoardScript>(); } else { sbs.enabled = true; } return sbs; } private DeliveryChuteScript getDeliveryChuteScript() { DeliveryChuteScript dcs = transform.GetComponent<DeliveryChuteScript>(); if(dcs == null) { dcs = transform.gameObject.AddComponent<DeliveryChuteScript>(); } else { dcs.enabled = true; } dcs.registerListener("AcScen",this); return dcs; } private CircleTimerScript getChopTimerScript() { CircleTimerScript reqScript = null; Transform wordChopTimer = GameObject.Find("WordChopTimer").transform; if(wordChopTimer != null) { reqScript = wordChopTimer.FindChild("Timer").GetComponent<CircleTimerScript>(); if(reqScript != null) { reqScript.enabled = true; reqScript.registerListener("AcScen",this); } } return reqScript; } private TextMesh getLineCounterTMesh() { TextMesh retScript = null; GameObject solomonGObj = GameObject.Find("SolomonWhole"); if(solomonGObj != null) { retScript = solomonGObj.transform.FindChild("LineCounter").GetComponent<TextMesh>(); } return retScript; } private void triggerSoundAtCamera(string para_soundFileName) { GameObject camGObj = Camera.main.gameObject; GameObject nwSFX = ((Transform) Instantiate(sfxPrefab,camGObj.transform.position,Quaternion.identity)).gameObject; DontDestroyOnLoad(nwSFX); AudioSource audS = (AudioSource) nwSFX.GetComponent(typeof(AudioSource)); audS.clip = (AudioClip) Resources.Load("Sounds/"+para_soundFileName,typeof(AudioClip)); audS.volume = 0.5f; audS.Play(); } protected new void loadTextures() { availableTextures = new Dictionary<string, Texture2D>(); Texture2D progressBarTex = new Texture2D(1,1); progressBarTex.SetPixel(1,1,Color.green); progressBarTex.Apply(); Texture2D progressBarTexDark = new Texture2D(1,1); progressBarTexDark.SetPixel(1,1,new Color(0,0.2f,0)); progressBarTexDark.Apply(); availableTextures.Add("PortraitProgFore",progressBarTex); availableTextures.Add("PortraitProgForeDark",progressBarTexDark); } private SJWordItem findWordInCache(int para_id) { SJWordItem retData = null; if(wordItemCache.ContainsKey(para_id)) { retData = wordItemCache[para_id]; } return retData; } class TetrisInfo { public int id; public int[] coords; public int wordSize; public bool isIndivisible; public TetrisInfo(int para_id, int[] para_startingCoords, int para_wordSize, bool para_isIndivisible) { id = para_id; coords = para_startingCoords; wordSize = para_wordSize; isIndivisible = para_isIndivisible; } } class WordSegmentComparer : System.Collections.Generic.IComparer<string> { public int Compare(string x, string y) { string[] x_suffixParts = ((x.Split(':')[1]).Split('-')); string[] y_suffixParts = ((y.Split(':')[1]).Split('-')); int[] x_parsedLetterRange = new int[2] { int.Parse(x_suffixParts[0]), int.Parse(x_suffixParts[1]) }; int[] y_parsedLetterRange = new int[2] { int.Parse(y_suffixParts[0]), int.Parse(y_suffixParts[1]) }; if(x_parsedLetterRange[1] < y_parsedLetterRange[0]) { return -1; } else if(x_parsedLetterRange[0] > y_parsedLetterRange[1]) { return 1; } else { return 0; } } } }
28.946578
215
0.674745
[ "BSD-3-Clause" ]
TAPeri/WordsMatter
Assets/Ac_DropChop2/Code/Scripts/AcDropChopScenarioV2.cs
65,564
C#
using System; namespace mtti.Inject { [AttributeUsage(AttributeTargets.Field, AllowMultiple = false)] public class GetComponentAttribute : Attribute { public GetComponentAttribute() { } } [AttributeUsage(AttributeTargets.Field, AllowMultiple = false)] public class GetComponentInChildrenAttribute : Attribute { public GetComponentInChildrenAttribute() { } } /// <summary> /// Get a component if it exists in the game object and add it if it doesn't. /// </summary> [AttributeUsage(AttributeTargets.Field, AllowMultiple = false)] public class EnsureComponentAttribute : Attribute { public EnsureComponentAttribute() { } } }
27.307692
81
0.688732
[ "Apache-2.0" ]
mtti/inject
Runtime/Unity/attributes.cs
710
C#
// Copyright (c) 2020 Flucto Team and others. Licensed under the MIT Licence. // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.Runtime.InteropServices; using osuTK; using osuTK.Graphics; using osuTK.Graphics.ES30; namespace flucto.Graphics.OpenGL.Vertices { [StructLayout(LayoutKind.Sequential)] public struct Vertex2D : IEquatable<Vertex2D>, IVertex { [VertexMember(2, VertexAttribPointerType.Float)] public Vector2 Position; [VertexMember(4, VertexAttribPointerType.Float)] public Color4 Colour; public bool Equals(Vertex2D other) => Position.Equals(other.Position) && Colour.Equals(other.Colour); } }
31.68
109
0.729798
[ "MIT" ]
flucto/flucto
flucto/Graphics/OpenGL/Vertices/Vertex2D.cs
794
C#
using System; using System.Collections.Generic; using System.Threading; using Moq; using NBitcoin; using Xels.Bitcoin.Base; using Xels.Bitcoin.Utilities; using Xunit; namespace Xels.Bitcoin.Tests.Base { /// <summary> /// Tests of <see cref="ChainState"/> class. /// </summary> public class ChainStateTest { /// <summary>Source of randomness.</summary> private static Random rng = new Random(); /// <summary> /// Tests <see cref="ChainState.MarkBlockInvalid(uint256, DateTime?)"/> and <see cref="ChainState.IsMarkedInvalid(uint256)"/> /// for both permantently and temporary bans of blocks. /// </summary> /// <remarks>Note that this test is almost identical to <see cref="InvalidBlockHashStoreTest.MarkInvalid_PermanentAndTemporaryBans"/> /// as the <see cref="ChainState"/> is just a middleman between the users of the block hash store and the store itself.</remarks> [Fact] public void MarkBlockInvalid_PermanentAndTemporaryBans() { var fullNode = new Mock<IFullNode>(); fullNode.Setup(f => f.NodeService<IDateTimeProvider>(true)) .Returns(DateTimeProvider.Default); var store = new InvalidBlockHashStore(DateTimeProvider.Default); // Create some hashes that will be banned forever. var hashesBannedPermanently = new uint256[] { uint256.Parse("0000000000000000000000000000000000000000000000000000000000000001"), uint256.Parse("0000000000000000000000000000000000000000000000000000000000000002"), uint256.Parse("0000000000000000000000000000000000000000000000000000000000000003"), uint256.Parse("0000000000000000000000000000000000000000000000000000000000000004"), }; foreach (uint256 hash in hashesBannedPermanently) store.MarkInvalid(hash); // Create some hashes that will be banned now, but not in 5 seconds. var hashesBannedTemporarily1 = new uint256[] { uint256.Parse("0000000000000000000000000000000000000000000000000000000000000011"), uint256.Parse("0000000000000000000000000000000000000000000000000000000000000012"), uint256.Parse("0000000000000000000000000000000000000000000000000000000000000013"), uint256.Parse("0000000000000000000000000000000000000000000000000000000000000014"), }; foreach (uint256 hash in hashesBannedTemporarily1) store.MarkInvalid(hash, DateTime.UtcNow.AddMilliseconds(rng.Next(2000, 5000))); // Create some hashes that will be banned now and also after 5 seconds. var hashesBannedTemporarily2 = new uint256[] { uint256.Parse("0000000000000000000000000000000000000000000000000000000000000021"), uint256.Parse("0000000000000000000000000000000000000000000000000000000000000022"), uint256.Parse("0000000000000000000000000000000000000000000000000000000000000023"), uint256.Parse("0000000000000000000000000000000000000000000000000000000000000024"), }; foreach (uint256 hash in hashesBannedTemporarily2) store.MarkInvalid(hash, DateTime.UtcNow.AddMilliseconds(rng.Next(20000, 50000))); // Check that all hashes we have generated are banned now. var allHashes = new List<uint256>(hashesBannedPermanently); allHashes.AddRange(hashesBannedTemporarily1); allHashes.AddRange(hashesBannedTemporarily2); foreach (uint256 hash in allHashes) Assert.True(store.IsInvalid(hash)); // Wait 5 seconds and then check if hashes from first temporary group are no longer banned and all others still are. Thread.Sleep(5000); foreach (uint256 hash in allHashes) { uint num = hash.GetLow32(); bool isSecondGroup = (0x10 <= num) && (num < 0x20); Assert.Equal(!isSecondGroup, store.IsInvalid(hash)); } } } }
46.142857
141
0.661824
[ "MIT" ]
xels-io/SideChain-SmartContract
src/Xels.Bitcoin.Tests/Base/ChainStateTest.cs
4,201
C#
using Devon4Net.Infrastructure.Logger.Logging; using Devon4Net.Infrastructure.MediatR.Handler; using Devon4Net.Application.WebAPI.Implementation.Business.MediatRManagement.Commands; using Devon4Net.Application.WebAPI.Implementation.Business.MediatRManagement.Dto; using Devon4Net.Application.WebAPI.Implementation.Business.MediatRManagement.Queries; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Cors; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; namespace Devon4Net.Application.WebAPI.Implementation.Business.MediatRManagement.Controllers { /// <summary> /// Controller sample to implement the mediator pattern /// </summary> [ApiController] [Route("[controller]")] [EnableCors("CorsPolicy")] public class MediatRController : ControllerBase { private IMediatRHandler MediatRHandler { get; } /// <summary> /// Mediator sample controller /// </summary> /// <param name="mediatRHandler"></param> public MediatRController(IMediatRHandler mediatRHandler) { MediatRHandler = mediatRHandler; } /// <summary> /// Gets a TO-DO item given the Id via CQRS pattern via a MediatR query /// </summary> /// <param name="todoId"></param> /// <returns></returns> [HttpGet] [HttpOptions] [AllowAnonymous] [ProducesResponseType(typeof(TodoResultDto), StatusCodes.Status200OK)] [ProducesResponseType(StatusCodes.Status400BadRequest)] [ProducesResponseType(StatusCodes.Status404NotFound)] [ProducesResponseType(StatusCodes.Status500InternalServerError)] [Route("/v1/MediatR/gettodobyid")] public async Task<IActionResult> GetTodoById(long todoId) { Devon4NetLogger.Debug("Executing GetTodoById from controller MediatRController"); var query = new GetTodoQuery(todoId); return Ok(await MediatRHandler.QueryAsync(query).ConfigureAwait(false)); } /// <summary> /// Creates a TO-DO item sending a MediatR via a message command /// </summary> /// <param name="todoDescription">The description of the TO-DO command. It cannot be empty</param> /// <returns></returns> [HttpPost] [HttpOptions] [AllowAnonymous] [ProducesResponseType(typeof(bool), StatusCodes.Status200OK)] [ProducesResponseType(StatusCodes.Status400BadRequest)] [ProducesResponseType(StatusCodes.Status404NotFound)] [ProducesResponseType(StatusCodes.Status500InternalServerError)] [Route("/v1/MediatR/createtodo")] public async Task<IActionResult> CreateTodo(string todoDescription) { if (string.IsNullOrEmpty(todoDescription)) { return StatusCode(StatusCodes.Status400BadRequest, "Please provide a valid description for the TO-DO"); } Devon4NetLogger.Debug("Executing CreateTodo from controller MediatRController"); var command = new CreateTodoCommand(todoDescription); return Ok(await MediatRHandler.QueryAsync(command).ConfigureAwait(false)); } } }
41.435897
119
0.684406
[ "Apache-2.0" ]
BenjaminE98/devon4net
source/Templates/WebAPI/Devon4Net.Application.WebAPI.Implementation/Business/MediatRManagement/Controllers/MediatRController.cs
3,234
C#
/* * Copyright (C) Sportradar AG. See LICENSE for full license governing this code */ using System; using System.Collections.Generic; using Dawn; using System.Linq; using Sportradar.OddsFeed.SDK.Messages.REST; namespace Sportradar.OddsFeed.SDK.Entities.REST.Internal.DTO.Lottery { /// <summary> /// Defines a data-transfer-object for lottery /// </summary> internal class LotteryDTO : SportEventSummaryDTO { /// <summary> /// Gets the sport /// </summary> /// <value>The sport</value> public SportDTO Sport { get; } /// <summary> /// Gets the category /// </summary> /// <value>The category</value> public CategorySummaryDTO Category { get; } /// <summary> /// Gets the bonus information /// </summary> /// <value>The bonus information</value> public BonusInfoDTO BonusInfo { get; } /// <summary> /// Gets the draw information /// </summary> /// <value>The draw information</value> public DrawInfoDTO DrawInfo { get; } /// <summary> /// Gets the draw events /// </summary> /// <value>The draw events</value> public IEnumerable<DrawDTO> DrawEvents { get; } /// <summary> /// Gets the <see cref="DateTime"/> specifying when the associated message was generated (on the server side) /// </summary> public DateTime? GeneratedAt { get; } internal LotteryDTO(lottery item) : base(new sportEvent { id = item == null ? "wns:lottery:1" : item.id, name = item?.name, scheduledSpecified = false, scheduled = DateTime.MinValue, tournament = item?.sport == null ? null : new tournament { sport = item.sport } }) { if (item == null) { return; } if (item.sport!=null) { Sport = new SportDTO(item.sport.id, item.sport.name, (IEnumerable<tournamentExtended>) null); } if (item.category != null) { Category = new CategorySummaryDTO(item.category); } if (item.bonus_info != null) { BonusInfo = new BonusInfoDTO(item.bonus_info); } if (item.draw_info != null) { DrawInfo = new DrawInfoDTO(item.draw_info); } } internal LotteryDTO(lottery_schedule item) : this(item.lottery) { Guard.Argument(item, nameof(item)).NotNull(); if (item.draw_events != null && item.draw_events.Any()) { DrawEvents = item.draw_events.Select(draw => new DrawDTO(draw)).ToList(); } GeneratedAt = item.generated_atSpecified ? item.generated_at : (DateTime?) null; } } }
29.875
117
0.508529
[ "Apache-2.0" ]
Honore-Gaming/UnifiedOddsSdkNetCore
src/Sportradar.OddsFeed.SDK/Entities/REST/Internal/DTO/Lottery/LotteryDTO.cs
3,109
C#
using EngineeringUnits.Units; using Newtonsoft.Json; using System; using System.Diagnostics; namespace EngineeringUnits { public partial class Temperature : BaseUnit { [JsonProperty] private TemperatureUnit PublicUnit { get; init; } [JsonProperty] private decimal PublicValue { get; init; } [JsonProperty] private bool NoRunback { get; init; } public Temperature() {} public Temperature(int value, TemperatureUnit selectedUnit) : this() { Unit = selectedUnit.Unit; NEWValue = value; //Public view of tempature if (selectedUnit.Unit.IsSIUnit() is false) { PublicUnit = selectedUnit; PublicValue = value; } //Forcing all temperatures to stay in kelvin for calculations NEWValue = GetValueAs(TemperatureUnit.Kelvin.Unit); Unit = TemperatureUnit.Kelvin.Unit; } public Temperature(double value, TemperatureUnit selectedUnit) :this() { //Public view of tempature if (selectedUnit.Unit.IsSIUnit() is false) { PublicUnit = selectedUnit; } if (double.IsInfinity(value) || value > (double)decimal.MaxValue || value < (double)decimal.MinValue || double.IsNaN(value)) { Inf = true; } else { Inf = false; //SymbolValue = (decimal)value; NEWValue = (decimal)value; PublicValue = (decimal)value; } //Forcing all temperatures to stay in kelvin Unit = selectedUnit.Unit; NEWValue = GetValueAs(TemperatureUnit.Kelvin.Unit); Unit = TemperatureUnit.Kelvin.Unit; } public Temperature(decimal value, TemperatureUnit selectedUnit) : this() { Unit = selectedUnit.Unit; NEWValue = value; //Public view of tempature if (selectedUnit.Unit.IsSIUnit() is false) { PublicUnit = selectedUnit; PublicValue = value; } //Forcing all temperatures to stay in kelvin for calculations NEWValue = GetValueAs(TemperatureUnit.Kelvin.Unit); Unit = TemperatureUnit.Kelvin.Unit; } private Temperature(decimal value, TemperatureUnit selectedUnit, bool noRunback = true) : this() { NoRunback = noRunback; NEWValue = value; Unit = selectedUnit.Unit; } public Temperature(UnknownUnit value) : base(value) { } public static Temperature From(double value, TemperatureUnit unit) => new(value, unit); public double As(TemperatureUnit ReturnInThisUnit) => GetValueAsDouble(ReturnInThisUnit.Unit); public Temperature ToUnit(TemperatureUnit selectedUnit) { return new Temperature(GetValueAs(selectedUnit.Unit), selectedUnit, false); } public static Temperature Zero => new(0, TemperatureUnit.SI); public static implicit operator Temperature(UnknownUnit Unit) => new(Unit); public static implicit operator Temperature(int zero) { if (zero != 0) throw new WrongUnitException($"You need to give it a unit unless you set it to 0 (zero)!"); return Zero; } public override string ToString() { if (!NoRunback && PublicUnit is not null) { return new Temperature(PublicValue, PublicUnit, true).ToString(); } return base.ToString(); } public override string ToString(string format, IFormatProvider provider) { if (!NoRunback && PublicUnit is not null) { return new Temperature(PublicValue, PublicUnit, true).ToString(format, provider); } return base.ToString(format, provider); } } }
27.644737
136
0.555926
[ "MIT" ]
AtefeBahrani/EngineeringUnits
EngineeringUnits/BaseUnits/Temperature/Temperature.cs
4,204
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using Microsoft.Toolkit.Parsers.Markdown; using Microsoft.Toolkit.Parsers.Markdown.Blocks; using Microsoft.Toolkit.Parsers.Markdown.Inlines; namespace UnitTests.Markdown.Parse { /// <summary> /// Extension methods. /// </summary> public static class ParseTestExtensionMethods { /// <summary> /// Adds one or more child elements to the given parent object. /// </summary> /// <typeparam name="T">the type</typeparam> /// <param name="parent">the parent</param> /// <param name="elements">the elements to add</param> /// <returns>parent</returns> public static T AddChildren<T>(this T parent, params object[] elements) { foreach (var child in elements) AddChild(parent, child); return parent; } private static void AddChild<T>(T parent, object child) { if (parent is MarkdownDocument) AddChild(() => ((MarkdownDocument)(object)parent).Blocks, (value) => ((MarkdownDocument)(object)parent).Blocks = value, (MarkdownBlock)child); else if (parent is HeaderBlock) AddChild(() => ((HeaderBlock)(object)parent).Inlines, (value) => ((HeaderBlock)(object)parent).Inlines = value, (MarkdownInline)child); else if (parent is ListBlock) AddChild(() => ((ListBlock)(object)parent).Items, (value) => ((ListBlock)(object)parent).Items = value, (ListItemBlock)child); else if (parent is ListItemBlock) AddChild(() => ((ListItemBlock)(object)parent).Blocks, (value) => ((ListItemBlock)(object)parent).Blocks = value, (MarkdownBlock)child); else if (parent is ParagraphBlock) AddChild(() => ((ParagraphBlock)(object)parent).Inlines, (value) => ((ParagraphBlock)(object)parent).Inlines = value, (MarkdownInline)child); else if (parent is QuoteBlock) AddChild(() => ((QuoteBlock)(object)parent).Blocks, (value) => ((QuoteBlock)(object)parent).Blocks = value, (MarkdownBlock)child); else if (parent is TableBlock) AddChild(() => ((TableBlock)(object)parent).Rows, (value) => ((TableBlock)(object)parent).Rows = value, (TableBlock.TableRow)child); else if (parent is TableBlock.TableRow) AddChild(() => ((TableBlock.TableRow)(object)parent).Cells, (value) => ((TableBlock.TableRow)(object)parent).Cells = value, (TableBlock.TableCell)child); else if (parent is TableBlock.TableCell) AddChild(() => ((TableBlock.TableCell)(object)parent).Inlines, (value) => ((TableBlock.TableCell)(object)parent).Inlines = value, (MarkdownInline)child); else if (parent is BoldTextInline) AddChild(() => ((BoldTextInline)(object)parent).Inlines, (value) => ((BoldTextInline)(object)parent).Inlines = value, (MarkdownInline)child); else if (parent is ItalicTextInline) AddChild(() => ((ItalicTextInline)(object)parent).Inlines, (value) => ((ItalicTextInline)(object)parent).Inlines = value, (MarkdownInline)child); else if (parent is MarkdownLinkInline) AddChild(() => ((MarkdownLinkInline)(object)parent).Inlines, (value) => ((MarkdownLinkInline)(object)parent).Inlines = value, (MarkdownInline)child); else if (parent is StrikethroughTextInline) AddChild(() => ((StrikethroughTextInline)(object)parent).Inlines, (value) => ((StrikethroughTextInline)(object)parent).Inlines = value, (MarkdownInline)child); else if (parent is SuperscriptTextInline) AddChild(() => ((SuperscriptTextInline)(object)parent).Inlines, (value) => ((SuperscriptTextInline)(object)parent).Inlines = value, (MarkdownInline)child); else throw new NotSupportedException(string.Format("Unsupported type {0}", typeof(T).Name)); } private static void AddChild<T>(Func<IList<T>> getter, Action<IList<T>> setter, T child) { var list = getter(); if (list == null) { list = new List<T>(); setter(list); } list.Add(child); } } }
58.584416
175
0.623587
[ "MIT" ]
GraniteStateHacker/UWPCommunityToolkit
UnitTests/Markdown/Parse/ParseTestExtensionMethods.cs
4,511
C#
// <auto-generated> // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // </auto-generated> namespace Microsoft.Azure.Management.Compute.Fluent { using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; using System.Collections; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; /// <summary> /// VirtualMachinesOperations operations. /// </summary> public partial interface IVirtualMachinesOperations { /// <summary> /// Gets all the virtual machines under the specified subscription for /// the specified location. /// </summary> /// <param name='location'> /// The location for which virtual machines under the subscription are /// queried. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IPage<VirtualMachineInner>>> ListByLocationWithHttpMessagesAsync(string location, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Captures the VM by copying virtual hard disks of the VM and outputs /// a template that can be used to create similar VMs. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='vmName'> /// The name of the virtual machine. /// </param> /// <param name='parameters'> /// Parameters supplied to the Capture Virtual Machine operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<VirtualMachineCaptureResultInner>> CaptureWithHttpMessagesAsync(string resourceGroupName, string vmName, VirtualMachineCaptureParameters parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// The operation to create or update a virtual machine. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='vmName'> /// The name of the virtual machine. /// </param> /// <param name='parameters'> /// Parameters supplied to the Create Virtual Machine operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<VirtualMachineInner>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string vmName, VirtualMachineInner parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// The operation to update a virtual machine. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='vmName'> /// The name of the virtual machine. /// </param> /// <param name='parameters'> /// Parameters supplied to the Update Virtual Machine operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<VirtualMachineInner>> UpdateWithHttpMessagesAsync(string resourceGroupName, string vmName, VirtualMachineUpdate parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// The operation to delete a virtual machine. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='vmName'> /// The name of the virtual machine. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string vmName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Retrieves information about the model view or the instance view of /// a virtual machine. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='vmName'> /// The name of the virtual machine. /// </param> /// <param name='expand'> /// The expand expression to apply on the operation. Possible values /// include: 'instanceView' /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<VirtualMachineInner>> GetWithHttpMessagesAsync(string resourceGroupName, string vmName, InstanceViewTypes? expand = default(InstanceViewTypes?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Retrieves information about the run-time state of a virtual /// machine. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='vmName'> /// The name of the virtual machine. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<VirtualMachineInstanceView>> InstanceViewWithHttpMessagesAsync(string resourceGroupName, string vmName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Converts virtual machine disks from blob-based to managed disks. /// Virtual machine must be stop-deallocated before invoking this /// operation. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='vmName'> /// The name of the virtual machine. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse> ConvertToManagedDisksWithHttpMessagesAsync(string resourceGroupName, string vmName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Shuts down the virtual machine and releases the compute resources. /// You are not billed for the compute resources that this virtual /// machine uses. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='vmName'> /// The name of the virtual machine. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse> DeallocateWithHttpMessagesAsync(string resourceGroupName, string vmName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Sets the state of the virtual machine to generalized. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='vmName'> /// The name of the virtual machine. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse> GeneralizeWithHttpMessagesAsync(string resourceGroupName, string vmName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Lists all of the virtual machines in the specified resource group. /// Use the nextLink property in the response to get the next page of /// virtual machines. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IPage<VirtualMachineInner>>> ListWithHttpMessagesAsync(string resourceGroupName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Lists all of the virtual machines in the specified subscription. /// Use the nextLink property in the response to get the next page of /// virtual machines. /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IPage<VirtualMachineInner>>> ListAllWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Lists all available virtual machine sizes to which the specified /// virtual machine can be resized. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='vmName'> /// The name of the virtual machine. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IEnumerable<VirtualMachineSizeInner>>> ListAvailableSizesWithHttpMessagesAsync(string resourceGroupName, string vmName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// The operation to power off (stop) a virtual machine. The virtual /// machine can be restarted with the same provisioned resources. You /// are still charged for this virtual machine. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='vmName'> /// The name of the virtual machine. /// </param> /// <param name='skipShutdown'> /// The parameter to request non-graceful VM shutdown. True value for /// this flag indicates non-graceful shutdown whereas false indicates /// otherwise. Default value for this flag is false if not specified /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse> PowerOffWithHttpMessagesAsync(string resourceGroupName, string vmName, bool? skipShutdown = false, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// The operation to restart a virtual machine. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='vmName'> /// The name of the virtual machine. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse> RestartWithHttpMessagesAsync(string resourceGroupName, string vmName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// The operation to start a virtual machine. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='vmName'> /// The name of the virtual machine. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse> StartWithHttpMessagesAsync(string resourceGroupName, string vmName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// The operation to redeploy a virtual machine. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='vmName'> /// The name of the virtual machine. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse> RedeployWithHttpMessagesAsync(string resourceGroupName, string vmName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Reimages the virtual machine which has an ephemeral OS disk back to /// its initial state. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='vmName'> /// The name of the virtual machine. /// </param> /// <param name='tempDisk'> /// Specifies whether to reimage temp disk. Default value: false. Note: /// This temp disk reimage parameter is only supported for VM/VMSS with /// Ephemeral OS disk. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse> ReimageWithHttpMessagesAsync(string resourceGroupName, string vmName, bool? tempDisk = default(bool?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// The operation to perform maintenance on a virtual machine. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='vmName'> /// The name of the virtual machine. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse> PerformMaintenanceWithHttpMessagesAsync(string resourceGroupName, string vmName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Run command on the VM. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='vmName'> /// The name of the virtual machine. /// </param> /// <param name='parameters'> /// Parameters supplied to the Run command operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<RunCommandResultInner>> RunCommandWithHttpMessagesAsync(string resourceGroupName, string vmName, RunCommandInput parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Captures the VM by copying virtual hard disks of the VM and outputs /// a template that can be used to create similar VMs. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='vmName'> /// The name of the virtual machine. /// </param> /// <param name='parameters'> /// Parameters supplied to the Capture Virtual Machine operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<VirtualMachineCaptureResultInner>> BeginCaptureWithHttpMessagesAsync(string resourceGroupName, string vmName, VirtualMachineCaptureParameters parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// The operation to create or update a virtual machine. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='vmName'> /// The name of the virtual machine. /// </param> /// <param name='parameters'> /// Parameters supplied to the Create Virtual Machine operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<VirtualMachineInner>> BeginCreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string vmName, VirtualMachineInner parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// The operation to update a virtual machine. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='vmName'> /// The name of the virtual machine. /// </param> /// <param name='parameters'> /// Parameters supplied to the Update Virtual Machine operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<VirtualMachineInner>> BeginUpdateWithHttpMessagesAsync(string resourceGroupName, string vmName, VirtualMachineUpdate parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// The operation to delete a virtual machine. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='vmName'> /// The name of the virtual machine. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse> BeginDeleteWithHttpMessagesAsync(string resourceGroupName, string vmName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Converts virtual machine disks from blob-based to managed disks. /// Virtual machine must be stop-deallocated before invoking this /// operation. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='vmName'> /// The name of the virtual machine. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse> BeginConvertToManagedDisksWithHttpMessagesAsync(string resourceGroupName, string vmName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Shuts down the virtual machine and releases the compute resources. /// You are not billed for the compute resources that this virtual /// machine uses. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='vmName'> /// The name of the virtual machine. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse> BeginDeallocateWithHttpMessagesAsync(string resourceGroupName, string vmName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// The operation to power off (stop) a virtual machine. The virtual /// machine can be restarted with the same provisioned resources. You /// are still charged for this virtual machine. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='vmName'> /// The name of the virtual machine. /// </param> /// <param name='skipShutdown'> /// The parameter to request non-graceful VM shutdown. True value for /// this flag indicates non-graceful shutdown whereas false indicates /// otherwise. Default value for this flag is false if not specified /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse> BeginPowerOffWithHttpMessagesAsync(string resourceGroupName, string vmName, bool? skipShutdown = false, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// The operation to restart a virtual machine. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='vmName'> /// The name of the virtual machine. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse> BeginRestartWithHttpMessagesAsync(string resourceGroupName, string vmName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// The operation to start a virtual machine. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='vmName'> /// The name of the virtual machine. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse> BeginStartWithHttpMessagesAsync(string resourceGroupName, string vmName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// The operation to redeploy a virtual machine. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='vmName'> /// The name of the virtual machine. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse> BeginRedeployWithHttpMessagesAsync(string resourceGroupName, string vmName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Reimages the virtual machine which has an ephemeral OS disk back to /// its initial state. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='vmName'> /// The name of the virtual machine. /// </param> /// <param name='tempDisk'> /// Specifies whether to reimage temp disk. Default value: false. Note: /// This temp disk reimage parameter is only supported for VM/VMSS with /// Ephemeral OS disk. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse> BeginReimageWithHttpMessagesAsync(string resourceGroupName, string vmName, bool? tempDisk = default(bool?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// The operation to perform maintenance on a virtual machine. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='vmName'> /// The name of the virtual machine. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse> BeginPerformMaintenanceWithHttpMessagesAsync(string resourceGroupName, string vmName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Run command on the VM. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='vmName'> /// The name of the virtual machine. /// </param> /// <param name='parameters'> /// Parameters supplied to the Run command operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<RunCommandResultInner>> BeginRunCommandWithHttpMessagesAsync(string resourceGroupName, string vmName, RunCommandInput parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets all the virtual machines under the specified subscription for /// the specified location. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IPage<VirtualMachineInner>>> ListByLocationNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Lists all of the virtual machines in the specified resource group. /// Use the nextLink property in the response to get the next page of /// virtual machines. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IPage<VirtualMachineInner>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Lists all of the virtual machines in the specified subscription. /// Use the nextLink property in the response to get the next page of /// virtual machines. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IPage<VirtualMachineInner>>> ListAllNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); } }
49.840173
311
0.61941
[ "MIT" ]
acelina/azure-libraries-for-net
src/ResourceManagement/Compute/Generated/IVirtualMachinesOperations.cs
46,152
C#
namespace Panuon.UI.Silver.Internal.Resources { static class StyleKeys { public const string DataGridComboBoxStyle = nameof(DataGridComboBoxStyle); public const string IconButtonStyle = nameof(IconButtonStyle); public const string IconRepeatButtonStyle = nameof(IconRepeatButtonStyle); public const string SpinnerStyle = nameof(SpinnerStyle); public const string WindowXButtonStyle = nameof(WindowXButtonStyle); public const string WindowXStyle = nameof(WindowXStyle); public const string SliderRepeatButtonStyle = nameof(SliderRepeatButtonStyle); } }
44.357143
86
0.748792
[ "MIT" ]
Panuon/Panuon.UI.Silver
DotNet/WPF/Src/SharedResources/Panuon.UI.Silver.Internal/Resources/StyleKeys.cs
623
C#
using AliGulmen.UnluCoProject.UrunKatalog.WebAPI.Controllers.Resources.CategoryResources; using AliGulmen.UnluCoProject.UrunKatalog.Core.Domain.Entities; using AutoMapper; using AliGulmen.UnluCoProject.UrunKatalog.Shared; namespace AliGulmen.UnluCoProject.UrunKatalog.Infrastructure.Mapping { public class CategoryProfile : Profile { public CategoryProfile() { CreateMap<Category, CategoryResource>(); CreateMap<SaveCategoryResource, Category>(); CreateMap<PaginatedResult<Category>, PaginatedResult<CategoryResource>>(); } } }
28.809524
90
0.73719
[ "MIT" ]
Patika-dev-Unlu-Co-Net-Bootcamp/AliGulmen.UnluCoProject.UrunKatalog
AliGulmen.UnluCoProject.UrunKatalog/Infrastructure/Mapping/CategoryProfile.cs
607
C#
// Copyright (c) Philipp Wagner. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using ElasticsearchFulltextExample.Web.Logging; using ElasticsearchFulltextExample.Web.Options; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using System; using System.Diagnostics; using System.IO; using System.Threading.Tasks; namespace ElasticsearchFulltextExample.Web.Services { public class TesseractService { private readonly ILogger<TesseractService> logger; private readonly TesseractOptions tesseractOptions; public TesseractService(ILogger<TesseractService> logger, IOptions<TesseractOptions> tesseractOptions) { this.logger = logger; this.tesseractOptions = tesseractOptions.Value; } public async Task<string> ProcessDocument(byte[] document, string language) { var temporarySourceFilename = Path.Combine(tesseractOptions.TempDirectory, Path.GetRandomFileName()); var temporaryTargetFilename = Path.Combine(tesseractOptions.TempDirectory, Path.GetRandomFileName()); if (logger.IsInformationEnabled()) { logger.LogInformation($"Generating Temporary Filenames (Source = \"{temporarySourceFilename}\", Target = \"{temporaryTargetFilename}\")"); } // The Tesseract CLI in 5.0.0-alpha always adds a .txt to the output file: var temporaryTesseractOutputFile = $"{temporaryTargetFilename}.txt"; try { await File.WriteAllBytesAsync(temporarySourceFilename, document); var tesseractArguments = $"{temporarySourceFilename} {temporaryTargetFilename} -l {language}"; if(logger.IsInformationEnabled()) { logger.LogInformation($"Running OCR Command: \"{tesseractOptions.Executable} {tesseractArguments}\""); } var result = await RunProcessAsync(tesseractOptions.Executable, tesseractArguments); if (result != 0) { if (logger.IsErrorEnabled()) { logger.LogError($"Tesseract Exited with Error Code = \"{result}\""); } throw new Exception($"Tesseract exited with Error Code \"{result}\""); } if (!File.Exists(temporaryTesseractOutputFile)) { if(logger.IsWarningEnabled()) { logger.LogWarning("Tesseract failed to extract data from the document. No output document exists."); } return string.Empty; } var ocrDocumentText = File.ReadAllText(temporaryTesseractOutputFile); if (logger.IsDebugEnabled()) { logger.LogDebug($"Tesseract extracted the following text from the document: {ocrDocumentText}"); } return ocrDocumentText; } finally { if (logger.IsDebugEnabled()) { logger.LogDebug($"Deleting temporary files (Source = \"{temporarySourceFilename}\", Target = \"{temporaryTargetFilename}\")"); } if (File.Exists(temporarySourceFilename)) { File.Delete(temporarySourceFilename); } if (File.Exists(temporaryTesseractOutputFile)) { File.Delete(temporaryTesseractOutputFile); } } } // This is just a very simple way to kick off Tesseract by Command Line. Does // it scale? Oh it doesn't for sure, but we can switch the implementation at a // later point anyway ... private Task<int> RunProcessAsync(string filename, string arguments) { if(logger.IsDebugEnabled()) { logger.LogDebug($"Running Process Asynchronously: Filename = {filename}, Arguments = {arguments}"); } var tcs = new TaskCompletionSource<int>(); var process = new Process { StartInfo = { FileName = filename, Arguments = arguments }, EnableRaisingEvents = true }; process.Exited += (sender, args) => { tcs.SetResult(process.ExitCode); process.Dispose(); }; process.Start(); return tcs.Task; } } }
36
154
0.566709
[ "MIT" ]
bytefish/ElasticsearchFulltextExample
Backend/ElasticsearchFulltextExample.Web/Services/TesseractService.cs
4,754
C#
using System; using Dapper; namespace Demo.Data { public interface IData { Guid Id { get; set; } } public class Data : IData { [Key] public Guid Id { get; set; } } }
13.5
36
0.518519
[ "Apache-2.0" ]
PeterKneale/IdentityAnd2FA
Demo.Data/Data.cs
218
C#
/******************************************************************************* * Copyright 2009-2017 Amazon Services. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"); * * You may not use this file except in compliance with the License. * You may obtain a copy of the License at: http://aws.amazon.com/apache2.0 * 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. ******************************************************************************* * List Orders By Next Token Result * API Version: 2013-09-01 * Library Version: 2017-02-22 * Generated: Thu Mar 02 12:41:05 UTC 2017 */ using System; using System.Xml; using System.Collections.Generic; using AmazonAPI.MWSClientRuntime; namespace AmazonAPI.Orders.MarketplaceWebServiceOrders.Model { public class ListOrdersByNextTokenResult : AbstractMwsObject { private string _nextToken; private DateTime? _createdBefore; private DateTime? _lastUpdatedBefore; private List<Order> _orders; /// <summary> /// Gets and sets the NextToken property. /// </summary> public string NextToken { get { return this._nextToken; } set { this._nextToken = value; } } /// <summary> /// Sets the NextToken property. /// </summary> /// <param name="nextToken">NextToken property.</param> /// <returns>this instance.</returns> public ListOrdersByNextTokenResult WithNextToken(string nextToken) { this._nextToken = nextToken; return this; } /// <summary> /// Checks if NextToken property is set. /// </summary> /// <returns>true if NextToken property is set.</returns> public bool IsSetNextToken() { return this._nextToken != null; } /// <summary> /// Gets and sets the CreatedBefore property. /// </summary> public DateTime CreatedBefore { get { return this._createdBefore.GetValueOrDefault(); } set { this._createdBefore = value; } } /// <summary> /// Sets the CreatedBefore property. /// </summary> /// <param name="createdBefore">CreatedBefore property.</param> /// <returns>this instance.</returns> public ListOrdersByNextTokenResult WithCreatedBefore(DateTime createdBefore) { this._createdBefore = createdBefore; return this; } /// <summary> /// Checks if CreatedBefore property is set. /// </summary> /// <returns>true if CreatedBefore property is set.</returns> public bool IsSetCreatedBefore() { return this._createdBefore != null; } /// <summary> /// Gets and sets the LastUpdatedBefore property. /// </summary> public DateTime LastUpdatedBefore { get { return this._lastUpdatedBefore.GetValueOrDefault(); } set { this._lastUpdatedBefore = value; } } /// <summary> /// Sets the LastUpdatedBefore property. /// </summary> /// <param name="lastUpdatedBefore">LastUpdatedBefore property.</param> /// <returns>this instance.</returns> public ListOrdersByNextTokenResult WithLastUpdatedBefore(DateTime lastUpdatedBefore) { this._lastUpdatedBefore = lastUpdatedBefore; return this; } /// <summary> /// Checks if LastUpdatedBefore property is set. /// </summary> /// <returns>true if LastUpdatedBefore property is set.</returns> public bool IsSetLastUpdatedBefore() { return this._lastUpdatedBefore != null; } /// <summary> /// Gets and sets the Orders property. /// </summary> public List<Order> Orders { get { if(this._orders == null) { this._orders = new List<Order>(); } return this._orders; } set { this._orders = value; } } /// <summary> /// Sets the Orders property. /// </summary> /// <param name="orders">Orders property.</param> /// <returns>this instance.</returns> public ListOrdersByNextTokenResult WithOrders(Order[] orders) { this._orders.AddRange(orders); return this; } /// <summary> /// Checks if Orders property is set. /// </summary> /// <returns>true if Orders property is set.</returns> public bool IsSetOrders() { return this.Orders.Count > 0; } public override void ReadFragmentFrom(IMwsReader reader) { _nextToken = reader.Read<string>("NextToken"); _createdBefore = reader.Read<DateTime?>("CreatedBefore"); _lastUpdatedBefore = reader.Read<DateTime?>("LastUpdatedBefore"); _orders = reader.ReadList<Order>("Orders", "Order"); } public override void WriteFragmentTo(IMwsWriter writer) { writer.Write("NextToken", _nextToken); writer.Write("CreatedBefore", _createdBefore); writer.Write("LastUpdatedBefore", _lastUpdatedBefore); writer.WriteList("Orders", "Order", _orders); } public override void WriteTo(IMwsWriter writer) { writer.Write("https://mws.amazonservices.com/Orders/2013-09-01", "ListOrdersByNextTokenResult", this); } public ListOrdersByNextTokenResult() : base() { } } }
32.38587
114
0.563182
[ "MIT" ]
ECourant/AmazonAPI
Orders/Model/ListOrdersByNextTokenResult.cs
5,959
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator 1.0.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.Network.Models { using Azure; using Management; using Network; /// <summary> /// Defines values for AssociationType. /// </summary> public static class AssociationType { public const string Associated = "Associated"; public const string Contains = "Contains"; } }
26.96
74
0.697329
[ "MIT" ]
DiogenesPolanco/azure-sdk-for-net
src/ResourceManagement/Network/Microsoft.Azure.Management.Network/Generated/Models/AssociationType.cs
674
C#
using System.Threading; using DreamBot.Utils; namespace DreamBot.Workers { internal class BackgroundWorker : IWorker { private readonly BlockingQueue<Action> _queue; private bool _isStoped = true; public BackgroundWorker() { _queue = new BlockingQueue<Action>(); } public void Start() { _isStoped = false; ThreadPool.QueueUserWorkItem(state => { while (!_isStoped) { var action = _queue.Dequeue(); if(!_isStoped) action(); } }); } public void Stop() { _isStoped = true; } public void Queue(Action action) { _queue.Enqueue(action); } } }
21.769231
54
0.469965
[ "MIT" ]
PleXone2019/DreamBot
Workers/BackgroundWorker.cs
849
C#
using System.Collections.Generic; namespace SharpMessaging.Persistence { public interface IPersistantQueueFileReader { /// <summary> /// current size of the file /// </summary> long FileSize { get; } /// <summary> /// Close files /// </summary> void Close(); /// <summary> /// Close and delete files /// </summary> void Delete(); /// <summary> /// Dequeue a set of records. /// </summary> /// <param name="messages">Will be cleared and then filled with all available buffers</param> /// <param name="maxNumberOfMessages">Number of wanted records (will return less if less are available)</param> /// <returns>Amount of items that was dequeued.</returns> int Dequeue(List<byte[]> messages, int maxNumberOfMessages); /// <summary> /// Open file and move to the correct position (with the help of the position file) /// </summary> void Open(); /// <summary> /// Read from the file, but do not update the positition (in the position file) /// </summary> /// <param name="messages">Will be cleared and then filled with all available buffers</param> /// <param name="maxNumberOfMessages">Number of wanted records (will return less if less are available)</param> /// <remarks> /// <para> /// Caches peeked records and returns the same if no Dequeus have been made between the Peeks /// </para> /// </remarks> void Peek(List<byte[]> messages, int maxNumberOfMessages); /// <summary> /// We've failed to read a valid record. Attempt to find the next one. /// </summary> void Recover(); /// <summary> /// Try dequeue a buffer /// </summary> /// <param name="buffer"></param> /// <returns></returns> bool TryDequeue(out byte[] buffer); /// <summary> /// Try to peek at a record /// </summary> /// <param name="buffer"></param> /// <returns><c>true</c> if a record is available; otherwise false.</returns> bool TryPeek(out byte[] buffer); } }
35.863636
120
0.534432
[ "Apache-2.0" ]
gauffininteractive/SharpMessaging
src/lib/SharpMessaging/Persistence/IPersistantQueueFileReader.cs
2,367
C#
using System; using Newtonsoft.Json; namespace AzureDocsUpdates.Shared.Model { public class ProcessDayInfoForTitlesJob { [JsonProperty(PropertyName = "dayInfoId")] [JsonConverter(typeof(IsoShortDateTimeConverter))] public DateTime DayInfoId { get; set; } public string id { get { return DayInfoId.ToString(new IsoShortDateTimeConverter().DateTimeFormat); } } } }
29.142857
111
0.713235
[ "MIT" ]
madrinathapa/KeepUpWithDocs
AzureDocsUpdates.Shared/Model/ProcessDayInfoForTitlesJob.cs
408
C#
// Copyright 2004-2021 Castle Project - http://www.castleproject.org/ // // 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 Castle.DynamicProxy { using System; /// <summary> /// Describes the <see cref="IInvocation.Proceed"/> operation for an <see cref="IInvocation"/> /// at a specific point during interception. /// </summary> public interface IInvocationProceedInfo { /// <summary> /// Executes the <see cref="IInvocation.Proceed"/> operation described by this instance. /// </summary> /// <exception cref="NotImplementedException">There is no interceptor, nor a proxy target object, to proceed to.</exception> void Invoke(); } }
36.65625
126
0.724638
[ "Apache-2.0" ]
Havunen/Core
src/Castle.Core/DynamicProxy/IInvocationProceedInfo.cs
1,173
C#
using System; using System.Collections.Generic; namespace ZLServerDashboard.DataBase { public partial class TbApplication { public TbApplication() { TbStreamProxy = new HashSet<TbStreamProxy>(); } public long Id { get; set; } public string App { get; set; } public string Remark { get; set; } public int Status { get; set; } public DateTime CreateTs { get; set; } public long CreateBy { get; set; } public DateTime UpdateTs { get; set; } public long UpdateBy { get; set; } public virtual TbUser CreateByNavigation { get; set; } public virtual TbUser UpdateByNavigation { get; set; } public virtual ICollection<TbStreamProxy> TbStreamProxy { get; set; } } }
29.518519
77
0.614806
[ "MIT" ]
MingZhuLiu/ZLMediaKitDashboard
ZLServerDashboard/DataBase/TbApplication.cs
799
C#
using System; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq; using System.Reactive.Linq; using System.Text; using System.Windows; using ESME.Scenarios; using HRC.Aspects; using HRC.Services; using HRC.ViewModels; using HRC.WPF; namespace ESME.Views.TransmissionLossViewer { public class TransmissionLossViewModel : ViewModelBase { public IHRCSaveFileService SaveFileService { get; set; } public TransmissionLossViewModel() { TitleString = "<no radial selected>"; Observable.FromEventPattern<PropertyChangedEventArgs>(this, "PropertyChanged") .Where(e => e.EventArgs.PropertyName == "SelectedRadialIndex") .Select(e => SelectedRadialIndex) .DistinctUntilChanged() .Where(selectedRadialIndex => selectedRadialIndex >= 0) .Throttle(TimeSpan.FromMilliseconds(200)) .ObserveOnDispatcher() .Subscribe(selectedRadialIndex => { Debug.WriteLine(string.Format("{0:HH:mm:ss.fff} TransmissionLossViewModel: SelectedRadialIndex is now {1}", DateTime.Now, selectedRadialIndex)); //CurrentRadialView = RadialViews[value]; // var foo = SelectedMode.TransmissionLossPluginType. some regex here. var tlstring = ""; if (SelectedMode.TransmissionLossPluginType.ToLowerInvariant().Contains("bellhop")) tlstring = "Bellhop"; if (SelectedMode.TransmissionLossPluginType.ToLowerInvariant().Contains("ramgeo")) tlstring = "RAMGeo"; var nameString = Radials == null ? "<no radial selected>" : string.Format("Radial bearing: {0:000.0} degrees. Calculator: {1}", Radials[selectedRadialIndex].Bearing, tlstring); TitleString = nameString; if (RadialViewModel != null) { RadialViewModel.FullRange.Update(MinTransmissionLoss, MaxTransmissionLoss); RadialViewModel.Radial = Radials == null ? null : Radials[selectedRadialIndex]; RadialViewModel.AxisSeriesViewModel.PlotTitle = nameString; } }); Observable.FromEventPattern<PropertyChangedEventArgs>(this, "PropertyChanged") .Where(e => e.EventArgs.PropertyName == "SelectedRadialIndex") .Select(e => SelectedRadialIndex) .DistinctUntilChanged() .Where(selectedRadialIndex => selectedRadialIndex >= 0) .ObserveOnDispatcher() .Subscribe(selectedRadialIndex => { if (Radials == null || Radials.Count < selectedRadialIndex) SelectedBearingGeometry = null; else { var geometryString = new StringBuilder(); SelectedRadialBearing = Radials[selectedRadialIndex].Bearing; const double radius = 8; double x, y; for (double angle = 0; angle <= 2 * Math.PI; angle += Math.PI / 32.0) { geometryString.Append(geometryString.Length == 0 ? "M" : "L"); x = (Math.Sin(angle) * radius) + radius; y = (Math.Cos(angle) * radius) + radius; geometryString.Append(string.Format(CultureInfo.InvariantCulture, " {0:0.###},{1:0.###} ", x, y)); } geometryString.Append(string.Format("M {0:0.###}, {0:0.###} ", radius)); x = (Math.Sin(SelectedRadialBearing * (Math.PI / 180)) * radius) + radius; y = (-Math.Cos(SelectedRadialBearing * (Math.PI / 180)) * radius) + radius; geometryString.Append(string.Format(CultureInfo.InvariantCulture, "L {0:0.###},{1:0.###} ", x, y)); SelectedBearingGeometry = geometryString.ToString(); } }); Observable.FromEventPattern<PropertyChangedEventArgs>(this, "PropertyChanged") .ObserveOnDispatcher() .Where(e => e.EventArgs.PropertyName == "Window") .Subscribe(e => { if (RadialViewModel == null) RadialViewModel = new RadialViewModel { RadialView = Window.FindChildren<RadialView>().First() }; }); Observable.FromEventPattern<PropertyChangedEventArgs>(this, "PropertyChanged") .ObserveOnDispatcher() .Where(e => e.EventArgs.PropertyName == "SelectedMode") .Subscribe(e => { if (RadialViewModel != null) RadialViewModel.SelectedMode = SelectedMode; }); Observable.FromEventPattern<PropertyChangedEventArgs>(this, "PropertyChanged") .ObserveOnDispatcher() .Where(e => e.EventArgs.PropertyName == "RadialViewModel") .Subscribe(e1 => { RadialViewModel.SelectedMode = SelectedMode; RadialViewModel.PropertyChanged += (s, e) => { if (e.PropertyName == "WriteableBitmap" && Window != null) Window.Dispatcher.InvokeIfRequired(() => Window.Activate()); }; }); Observable.FromEventPattern<PropertyChangedEventArgs>(this, "PropertyChanged") .Where(e => e.EventArgs.PropertyName == "TransmissionLoss") .Select(e => TransmissionLoss) .DistinctUntilChanged() .ObserveOnDispatcher() .Subscribe(transmissionLoss => { if (_transmissionLossObserver != null) _transmissionLossObserver.Dispose(); _transmissionLossObserver = null; Radials = TransmissionLoss == null ? null : TransmissionLoss.Radials.OrderBy(r => r.Bearing).ToList(); if (Radials == null) RadialCount = 0; if (transmissionLoss == null || Radials == null || Radials.Count == 0) return; Debug.WriteLine(string.Format("{0:HH:mm:ss.fff} TransmissionLossViewModel: TransmissionLoss changed to {1}", DateTime.Now, transmissionLoss.ToString())); RadialCount = Radials.Count - 1; SelectedRadialIndex = -1; try { MinTransmissionLoss = (from radial in Radials from minimumValue in radial.MinimumTransmissionLossValues where !double.IsNaN(minimumValue) && !double.IsInfinity(minimumValue) select minimumValue).Min(); MaxTransmissionLoss = (from radial in Radials from maximumValue in radial.MaximumTransmissionLossValues where !double.IsNaN(maximumValue) && !double.IsInfinity(maximumValue) select maximumValue).Max(); } catch (FileNotFoundException ex) { Debug.WriteLine(string.Format("File not found exception loading radial: {0}", ex.FileName)); } catch (IOException ex) { Debug.WriteLine(string.Format("I/O exception loading radial: {0}", ex.Message)); } catch (InvalidOperationException ex) { Debug.WriteLine(string.Format("Invalid operation exception loading radial: {0}", ex.Message)); } SelectedMode = transmissionLoss.Modes.OrderBy(m => m.MaxPropagationRadius).Last(); MinRadialBearing = Radials.Min(r => r.Bearing); MaxRadialBearing = Radials.Max(r => r.Bearing); RadialBearingChange = (MaxRadialBearing - MinRadialBearing) / RadialCount; SelectedRadialBearing = MinRadialBearing; Debug.WriteLine("{0:HH:mm:ss.fff} TransmissionLossViewModel: SelectedRadialIndex set to -1", DateTime.Now); _transmissionLossObserver = Observable.FromEventPattern<PropertyChangedEventArgs>(transmissionLoss, "PropertyChanged") .ObserveOnDispatcher() .Select(e => TransmissionLoss) .DistinctUntilChanged() .Subscribe(tl => { if (tl.IsDeleted && Window != null) CloseDialog(null); }); SelectedRadialIndex = 0; }); } IDisposable _transmissionLossObserver; [Initialize("<No radial selected>")] public string TitleString { get; set; } [Initialize(-1)] public int SelectedRadialIndex { get; set; } public Window Window { get; set; } public List<Radial> Radials { get; set; } public int RadialCount { get; private set; } public double MinRadialBearing { get; private set; } public double MaxRadialBearing { get; private set; } public double RadialBearingChange { get; private set; } public double SelectedRadialBearing { get; set; } public Mode SelectedMode { get; set; } public string SelectedBearingGeometry { get; set; } public RadialViewModel RadialViewModel { get; set; } public float MaxTransmissionLoss { get; set; } public float MinTransmissionLoss { get; set; } public ESME.Scenarios.TransmissionLoss TransmissionLoss { get; set; } #region Commands bool AreSaveCommandsEnabled { get { return RadialViewModel != null && RadialViewModel.Radial != null; } } #region SaveAsImageCommand public SimpleCommand<object, object> SaveAsImageCommand { get { return _saveAsImage ?? (_saveAsImage = new SimpleCommand<object, object>(delegate { return AreSaveCommandsEnabled; }, delegate { SaveAsImageHandler(); })); } } SimpleCommand<object, object> _saveAsImage; void SaveAsImageHandler() { SaveFileService.Filter = "Portable Network Graphics (*.png)|*.png|JPEG (*.jpg)|*.jpg|TIFF (*.tiff)|*.tiff|Bitmap (*.bmp)|*.bmp|GIF (*.gif)|*.gif"; SaveFileService.OverwritePrompt = true; SaveFileService.FileName = RadialViewModel.OutputFileName; var result = SaveFileService.ShowDialog(); if (result.HasValue && result.Value) { Properties.Settings.Default.LastImageExportFileDirectory = Path.GetDirectoryName(SaveFileService.FileName); RadialViewModel.SaveAsImage(SaveFileService.FileName); } } #endregion #region SaveAsCSVCommand public SimpleCommand<object, object> SaveAsCSVCommand { get { return _saveAsCSV ?? (_saveAsCSV = new SimpleCommand<object, object>(delegate { return AreSaveCommandsEnabled; }, delegate { SaveAsCSVHandler(); })); } } SimpleCommand<object, object> _saveAsCSV; void SaveAsCSVHandler() { SaveFileService.Filter = "Comma-Separated Value (*.csv)|*.csv"; SaveFileService.OverwritePrompt = true; SaveFileService.FileName = RadialViewModel.OutputFileName; var result = SaveFileService.ShowDialog(); if (result.HasValue && result.Value) { Properties.Settings.Default.LastCSVExportFileDirectory = Path.GetDirectoryName(SaveFileService.FileName); RadialViewModel.SaveAsCSV(SaveFileService.FileName); } } #endregion #region CopyImageToClipboardCommand public SimpleCommand<object, object> CopyImageToClipboardCommand { get { return _copyImageToClipboard ?? (_copyImageToClipboard = new SimpleCommand<object, object>(delegate { return AreSaveCommandsEnabled; }, delegate { CopyImageToClipboardHandler(); })); } } SimpleCommand<object, object> _copyImageToClipboard; void CopyImageToClipboardHandler() { Clipboard.SetImage(RadialViewModel.ToBitmapSource()); } #endregion #region CopyCSVToClipboardCommand public SimpleCommand<object, object> CopyCSVToClipboardCommand { get { return _copyCSVToClipboard ?? (_copyCSVToClipboard = new SimpleCommand<object, object>(delegate { return AreSaveCommandsEnabled; }, delegate { CopyCSVToClipboardHandler(); })); } } SimpleCommand<object, object> _copyCSVToClipboard; void CopyCSVToClipboardHandler() { Clipboard.SetText(RadialViewModel.ToCSV()); } #endregion #region InternalViewClosingCommand public SimpleCommand<object, object> InternalViewClosingCommand { get { return _internalViewClosing ?? (_internalViewClosing = new SimpleCommand<object, object>(InternalViewClosingHandler)); } } SimpleCommand<object, object> _internalViewClosing; static void InternalViewClosingHandler(object o) { Properties.Settings.Default.Save(); } #endregion #region CloseCommand public SimpleCommand<object, EventToCommandArgs> CloseCommand { get { return _close ?? (_close = new SimpleCommand<object, EventToCommandArgs>(o => CloseDialog(null))); } } SimpleCommand<object, EventToCommandArgs> _close; #endregion #endregion #region Design-time data public static TransmissionLossViewModel DesignTimeData { get; private set; } static TransmissionLossViewModel() { DesignTimeData = new TransmissionLossViewModel { RadialViewModel = RadialViewModel.DesignTimeData }; } #endregion } }
52.538732
203
0.557536
[ "MPL-2.0" ]
AuditoryBiophysicsLab/ESME-Workbench
Libraries/ESME.Views/TransmissionLossViewer/TransmissionLossViewModel.cs
14,923
C#
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using Microsoft.CodeAnalysis.Editor.CSharp.DocumentationComments; using Microsoft.CodeAnalysis.Editor.Host; using Microsoft.CodeAnalysis.Editor.UnitTests.DocumentationComments; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.VisualStudio.Commanding; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Text.Operations; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.DocumentationComments { public class DocumentationCommentTests : AbstractDocumentationCommentTests { [WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)] public void TypingCharacter_Class() { var code = @"//$$ class C { }"; var expected = @"/// <summary> /// $$ /// </summary> class C { }"; VerifyTypingCharacter(code, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)] public void TypingCharacter_Class_NewLine() { var code = "//$$\r\nclass C\r\n{\r\n}"; var expected = "/// <summary>\n/// $$\n/// </summary>\r\nclass C\r\n{\r\n}"; VerifyTypingCharacter(code, expected, newLine: "\n"); code = "//$$\r\nclass C\r\n{\r\n}"; expected = "/// <summary>\r\n/// $$\r\n/// </summary>\r\nclass C\r\n{\r\n}"; VerifyTypingCharacter(code, expected, newLine: "\r\n"); } [WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)] public void TypingCharacter_Class_AutoGenerateXmlDocCommentsOff() { var code = @"//$$ class C { }"; var expected = @"///$$ class C { }"; VerifyTypingCharacter(code, expected, autoGenerateXmlDocComments: false); } [WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)] public void TypingCharacter_Method() { var code = @"class C { //$$ int M<T>(int goo) { return 0; } }"; var expected = @"class C { /// <summary> /// $$ /// </summary> /// <typeparam name=""T""></typeparam> /// <param name=""goo""></param> /// <returns></returns> int M<T>(int goo) { return 0; } }"; VerifyTypingCharacter(code, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)] public void TypingCharacter_Method_WithVerbatimParams() { var code = @"class C { //$$ int M<@int>(int @goo) { return 0; } }"; var expected = @"class C { /// <summary> /// $$ /// </summary> /// <typeparam name=""int""></typeparam> /// <param name=""goo""></param> /// <returns></returns> int M<@int>(int @goo) { return 0; } }"; VerifyTypingCharacter(code, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)] public void TypingCharacter_AutoProperty() { var code = @"class C { //$$ int P { get; set; } }"; var expected = @"class C { /// <summary> /// $$ /// </summary> int P { get; set; } }"; VerifyTypingCharacter(code, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)] public void TypingCharacter_Property() { var code = @"class C { //$$ int P { get { return 0; } set { } } }"; var expected = @"class C { /// <summary> /// $$ /// </summary> int P { get { return 0; } set { } } }"; VerifyTypingCharacter(code, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)] public void TypingCharacter_Indexer() { var code = @"class C { //$$ int this[int index] { get { return 0; } set { } } }"; var expected = @"class C { /// <summary> /// $$ /// </summary> /// <param name=""index""></param> /// <returns></returns> int this[int index] { get { return 0; } set { } } }"; VerifyTypingCharacter(code, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)] public void TypingCharacter_VoidMethod1() { var code = @"class C { //$$ void M<T>(int goo) { } }"; var expected = @"class C { /// <summary> /// $$ /// </summary> /// <typeparam name=""T""></typeparam> /// <param name=""goo""></param> void M<T>(int goo) { } }"; VerifyTypingCharacter(code, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)] public void TypingCharacter_VoidMethod_WithVerbatimParams() { var code = @"class C { //$$ void M<@T>(int @int) { } }"; var expected = @"class C { /// <summary> /// $$ /// </summary> /// <typeparam name=""T""></typeparam> /// <param name=""int""></param> void M<@T>(int @int) { } }"; VerifyTypingCharacter(code, expected); } [WorkItem(538699, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538699")] [WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)] public void TypingCharacter_VoidMethod2() { var code = @"class C { //$$ void Method() { } }"; var expected = @"class C { /// <summary> /// $$ /// </summary> void Method() { } }"; VerifyTypingCharacter(code, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)] public void TypingCharacter_NotWhenDocCommentExists1() { var code = @" /// //$$ class C { }"; var expected = @" /// ///$$ class C { }"; VerifyTypingCharacter(code, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)] public void TypingCharacter_NotWhenDocCommentExists2() { var code = @" /// //$$ class C { }"; var expected = @" /// ///$$ class C { }"; VerifyTypingCharacter(code, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)] public void TypingCharacter_NotWhenDocCommentExists3() { var code = @" class B { } /// //$$ class C { }"; var expected = @" class B { } /// ///$$ class C { }"; VerifyTypingCharacter(code, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)] public void TypingCharacter_NotWhenDocCommentExists4() { var code = @"//$$ /// <summary></summary> class C { }"; var expected = @"///$$ /// <summary></summary> class C { }"; VerifyTypingCharacter(code, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)] public void TypingCharacter_NotWhenDocCommentExists5() { var code = @"class C { //$$ /// <summary></summary> int M<T>(int goo) { return 0; } }"; var expected = @"class C { ///$$ /// <summary></summary> int M<T>(int goo) { return 0; } }"; VerifyTypingCharacter(code, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)] public void TypingCharacter_NotInsideMethodBody1() { var code = @"class C { void M(int goo) { //$$ } }"; var expected = @"class C { void M(int goo) { ///$$ } }"; VerifyTypingCharacter(code, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)] public void TypingCharacter_NotInsideMethodBody2() { var code = @"class C { /// <summary></summary> void M(int goo) { //$$ } }"; var expected = @"class C { /// <summary></summary> void M(int goo) { ///$$ } }"; VerifyTypingCharacter(code, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)] public void TypingCharacter_NotAfterClassName() { var code = @"class C//$$ { }"; var expected = @"class C///$$ { }"; VerifyTypingCharacter(code, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)] public void TypingCharacter_NotAfterOpenBrace() { var code = @"class C {//$$ }"; var expected = @"class C {///$$ }"; VerifyTypingCharacter(code, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)] public void TypingCharacter_NotAfterCtorName() { var code = @"class C { C() //$$ }"; var expected = @"class C { C() ///$$ }"; VerifyTypingCharacter(code, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)] public void TypingCharacter_NotInsideCtor() { var code = @"class C { C() { //$$ } }"; var expected = @"class C { C() { ///$$ } }"; VerifyTypingCharacter(code, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)] public void PressingEnter_InsertComment_Class1() { var code = @"///$$ class C { }"; var expected = @"/// <summary> /// $$ /// </summary> class C { }"; VerifyPressingEnter(code, expected); } [WorkItem(4817, "https://github.com/dotnet/roslyn/issues/4817")] [WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)] public void PressingEnter_InsertComment_Class1_AutoGenerateXmlDocCommentsOff() { var code = @"///$$ class C { }"; var expected = @"/// $$ class C { }"; VerifyPressingEnter(code, expected, autoGenerateXmlDocComments: false); } [WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)] public void PressingEnter_InsertComment_Class2() { var code = @"///$$class C { }"; var expected = @"/// <summary> /// $$ /// </summary> class C { }"; VerifyPressingEnter(code, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)] public void PressingEnter_InsertComment_Class3() { var code = @"///$$[Goo] class C { }"; var expected = @"/// <summary> /// $$ /// </summary> [Goo] class C { }"; VerifyPressingEnter(code, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)] public void PressingEnter_InsertComment_NotAfterWhitespace() { var code = @"/// $$class C { }"; var expected = @"/// /// $$class C { }"; VerifyPressingEnter(code, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)] public void PressingEnter_InsertComment_Method1() { var code = @"class C { ///$$ int M<T>(int goo) { return 0; } }"; var expected = @"class C { /// <summary> /// $$ /// </summary> /// <typeparam name=""T""></typeparam> /// <param name=""goo""></param> /// <returns></returns> int M<T>(int goo) { return 0; } }"; VerifyPressingEnter(code, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)] public void PressingEnter_InsertComment_Method2() { var code = @"class C { ///$$int M<T>(int goo) { return 0; } }"; var expected = @"class C { /// <summary> /// $$ /// </summary> /// <typeparam name=""T""></typeparam> /// <param name=""goo""></param> /// <returns></returns> int M<T>(int goo) { return 0; } }"; VerifyPressingEnter(code, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)] public void PressingEnter_NotInMethodBody1() { var code = @"class C { void Goo() { ///$$ } }"; var expected = @"class C { void Goo() { /// $$ } }"; VerifyPressingEnter(code, expected); } [WorkItem(537513, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537513")] [WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)] public void PressingEnter_NotInterleavedInClassName1() { var code = @"class///$$ C { }"; var expected = @"class/// $$ C { }"; VerifyPressingEnter(code, expected); } [WorkItem(537513, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537513")] [WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)] public void PressingEnter_NotInterleavedInClassName2() { var code = @"class ///$$C { }"; var expected = @"class /// $$C { }"; VerifyPressingEnter(code, expected); } [WorkItem(537513, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537513")] [WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)] public void PressingEnter_NotInterleavedInClassName3() { var code = @"class /// $$C { }"; var expected = @"class /// $$C { }"; VerifyPressingEnter(code, expected); } [WorkItem(537514, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537514")] [WorkItem(537532, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537532")] [WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)] public void PressingEnter_NotAfterClassName1() { var code = @"class C ///$$ { }"; var expected = @"class C /// $$ { }"; VerifyPressingEnter(code, expected); } [WorkItem(537552, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537552")] [WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)] public void PressingEnter_NotAfterClassName2() { var code = @"class C /** $$ { }"; var expected = @"class C /** $$ { }"; VerifyPressingEnter(code, expected); } [WorkItem(537535, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537535")] [WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)] public void PressingEnter_NotAfterCtorName() { var code = @"class C { C() ///$$ }"; var expected = @"class C { C() /// $$ }"; VerifyPressingEnter(code, expected); } [WorkItem(537511, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537511")] [WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)] public void PressingEnter_NotInsideCtor() { var code = @"class C { C() { ///$$ } }"; var expected = @"class C { C() { /// $$ } }"; VerifyPressingEnter(code, expected); } [WorkItem(537550, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537550")] [WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)] public void PressingEnter_NotBeforeDocComment() { var code = @" class c1 { $$/// <summary> /// /// </summary> /// <returns></returns> public async Task goo() { var x = 1; } }"; var expected = @" class c1 { $$/// <summary> /// /// </summary> /// <returns></returns> public async Task goo() { var x = 1; } }"; VerifyPressingEnter(code, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)] public void PressingEnter_InsertSlashes1() { var code = @"///$$ /// <summary></summary> class C { }"; var expected = @"/// /// $$ /// <summary></summary> class C { }"; VerifyPressingEnter(code, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)] public void PressingEnter_InsertSlashes2() { var code = @"/// <summary> /// $$ /// </summary> class C { }"; var expected = @"/// <summary> /// /// $$ /// </summary> class C { }"; VerifyPressingEnter(code, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)] public void PressingEnter_InsertSlashes3() { var code = @" /// <summary> /// $$ /// </summary> class C { }"; var expected = @" /// <summary> /// /// $$ /// </summary> class C { }"; VerifyPressingEnter(code, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)] public void PressingEnter_InsertSlashes4() { var code = @"/// <summary>$$</summary> class C { }"; var expected = @"/// <summary> /// $$</summary> class C { }"; VerifyPressingEnter(code, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)] public void PressingEnter_InsertSlashes5() { var code = @" /// <summary> /// $$ /// </summary> class C { }"; var expected = @" /// <summary> /// /// $$ /// </summary> class C { }"; VerifyPressingEnter(code, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)] public void PressingEnter_InsertSlashes6() { var code = @"/// <summary></summary>$$ class C { }"; var expected = @"/// <summary></summary> /// $$ class C { }"; VerifyPressingEnter(code, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)] public void PressingEnter_InsertSlashes7() { var code = @" /// <summary>$$</summary> class C { }"; var expected = @" /// <summary> /// $$</summary> class C { }"; VerifyPressingEnter(code, expected); } [WorkItem(538702, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538702")] [WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)] public void PressingEnter_InsertSlashes8() { var code = @"/// <summary> /// /// </summary> ///$$class C {}"; var expected = @"/// <summary> /// /// </summary> /// /// $$class C {}"; VerifyPressingEnter(code, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)] public void PressingEnter_InsertSlashes9() { var code = @"class C { ///$$ /// <summary></summary> int M<T>(int goo) { return 0; } }"; var expected = @"class C { /// /// $$ /// <summary></summary> int M<T>(int goo) { return 0; } }"; VerifyPressingEnter(code, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)] public void PressingEnter_InsertSlashes10() { var code = @"/// <summary> /// /// </summary> ///$$Go ahead and add some slashes"; var expected = @"/// <summary> /// /// </summary> /// /// $$Go ahead and add some slashes"; VerifyPressingEnter(code, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)] public void PressingEnter_InsertSlashes11() { var code = @"class C { /// <summary> /// /// </summary> /// <param name=""i"">$$</param> void Goo(int i) { } }"; var expected = @"class C { /// <summary> /// /// </summary> /// <param name=""i""> /// $$</param> void Goo(int i) { } }"; VerifyPressingEnter(code, expected); } [WorkItem(4817, "https://github.com/dotnet/roslyn/issues/4817")] [WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)] public void PressingEnter_InsertSlashes12_AutoGenerateXmlDocCommentsOff() { var code = @"///$$ /// <summary></summary> class C { }"; var expected = @"/// /// $$ /// <summary></summary> class C { }"; VerifyPressingEnter(code, expected, autoGenerateXmlDocComments: false); } [WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)] public void PressingEnter_DontInsertSlashes1() { var code = @"/// <summary></summary> /// $$ class C { }"; var expected = @"/// <summary></summary> /// $$ class C { }"; VerifyPressingEnter(code, expected); } [WorkItem(538701, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538701")] [WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)] public void PressingEnter_DontInsertSlashes2() { var code = @"///<summary></summary> ///$$ class C{}"; var expected = @"///<summary></summary> /// $$ class C{}"; VerifyPressingEnter(code, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)] [WorkItem(25746, "https://github.com/dotnet/roslyn/issues/25746")] public void PressingEnter_ExtraSlashesAfterExteriorTrivia() { var code = @"class C { C() { //////$$ } }"; var expected = @"class C { C() { ////// ///$$ } }"; VerifyPressingEnter(code, expected); } [WorkItem(542426, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542426")] [WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)] public void PressingEnter_PreserveParams() { var code = @"/// <summary> /// /// </summary> /// <param name=""args"">$$</param> static void Main(string[] args) { }"; var expected = @"/// <summary> /// /// </summary> /// <param name=""args""> /// $$</param> static void Main(string[] args) { }"; VerifyPressingEnter(code, expected); } [WorkItem(2091, "https://github.com/dotnet/roslyn/issues/2091")] [WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)] public void PressingEnter_InTextBeforeSpace() { const string code = @"class C { /// <summary> /// hello$$ world /// </summary> void M() { } }"; const string expected = @"class C { /// <summary> /// hello /// $$world /// </summary> void M() { } }"; VerifyPressingEnter(code, expected); } [WorkItem(2108, "https://github.com/dotnet/roslyn/issues/2108")] [WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)] public void PressingEnter_Indentation1() { const string code = @"class C { /// <summary> /// hello world$$ /// </summary> void M() { } }"; const string expected = @"class C { /// <summary> /// hello world /// $$ /// </summary> void M() { } }"; VerifyPressingEnter(code, expected); } [WorkItem(2108, "https://github.com/dotnet/roslyn/issues/2108")] [WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)] public void PressingEnter_Indentation2() { const string code = @"class C { /// <summary> /// hello $$world /// </summary> void M() { } }"; const string expected = @"class C { /// <summary> /// hello /// $$world /// </summary> void M() { } }"; VerifyPressingEnter(code, expected); } [WorkItem(2108, "https://github.com/dotnet/roslyn/issues/2108")] [WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)] public void PressingEnter_Indentation3() { const string code = @"class C { /// <summary> /// hello$$ world /// </summary> void M() { } }"; const string expected = @"class C { /// <summary> /// hello /// $$world /// </summary> void M() { } }"; VerifyPressingEnter(code, expected); } [WorkItem(2108, "https://github.com/dotnet/roslyn/issues/2108")] [WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)] public void PressingEnter_Indentation4() { const string code = @"class C { /// <summary> /// $$hello world /// </summary> void M() { } }"; const string expected = @"class C { /// <summary> /// /// $$hello world /// </summary> void M() { } }"; VerifyPressingEnter(code, expected); } [WorkItem(2108, "https://github.com/dotnet/roslyn/issues/2108")] [WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)] public void PressingEnter_Indentation5_UseTabs() { const string code = @"class C { /// <summary> /// hello world$$ /// </summary> void M() { } }"; const string expected = @"class C { /// <summary> /// hello world /// $$ /// </summary> void M() { } }"; VerifyPressingEnter(code, expected, useTabs: true); } [WorkItem(5486, "https://github.com/dotnet/roslyn/issues/5486")] [WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)] public void PressingEnter_Selection1() { var code = @"/// <summary> /// Hello [|World|]$$! /// </summary> class C { }"; var expected = @"/// <summary> /// Hello /// $$! /// </summary> class C { }"; VerifyPressingEnter(code, expected); } [WorkItem(5486, "https://github.com/dotnet/roslyn/issues/5486")] [WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)] public void PressingEnter_Selection2() { var code = @"/// <summary> /// Hello $$[|World|]! /// </summary> class C { }"; var expected = @"/// <summary> /// Hello /// $$! /// </summary> class C { }"; VerifyPressingEnter(code, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)] [WorkItem(27223, "https://github.com/dotnet/roslyn/issues/27223")] public void PressingEnter_XmldocInStringLiteral() { var code = @"class C { C() { string s = @"" /// <summary>$$</summary> void M() {}"" } }"; var expected = @"class C { C() { string s = @"" /// <summary> /// $$</summary> void M() {}"" } }"; VerifyPressingEnter(code, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)] public void Command_Class() { var code = @"class C {$$ }"; var expected = @"/// <summary> /// $$ /// </summary> class C { }"; VerifyInsertCommentCommand(code, expected); } [WorkItem(4817, "https://github.com/dotnet/roslyn/issues/4817")] [WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)] public void Command_Class_AutoGenerateXmlDocCommentsOff() { var code = @"class C {$$ }"; var expected = @"/// <summary> /// $$ /// </summary> class C { }"; VerifyInsertCommentCommand(code, expected, autoGenerateXmlDocComments: false); } [WorkItem(538714, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538714")] [WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)] public void Command_BeforeClass1() { var code = @"$$ class C { }"; var expected = @" /// <summary> /// $$ /// </summary> class C { }"; VerifyInsertCommentCommand(code, expected); } [WorkItem(538714, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538714")] [WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)] public void Command_BeforeClass2() { var code = @"class B { } $$ class C { }"; var expected = @"class B { } /// <summary> /// $$ /// </summary> class C { }"; VerifyInsertCommentCommand(code, expected); } [WorkItem(538714, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538714")] [WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)] public void Command_BeforeClass3() { var code = @"class B { $$ class C { } }"; var expected = @"class B { /// <summary> /// $$ /// </summary> class C { } }"; VerifyInsertCommentCommand(code, expected); } [WorkItem(527604, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527604")] [WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)] public void Command_Class_NotIfMultilineDocCommentExists() { var code = @"/** */ class C { $$ }"; var expected = @"/** */ class C { $$ }"; VerifyInsertCommentCommand(code, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)] public void Command_Method() { var code = @"class C { int M<T>(int goo) { $$return 0; } }"; var expected = @"class C { /// <summary> /// $$ /// </summary> /// <typeparam name=""T""></typeparam> /// <param name=""goo""></param> /// <returns></returns> int M<T>(int goo) { return 0; } }"; VerifyInsertCommentCommand(code, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)] public void Command_Class_NotIfCommentExists() { var code = @"/// <summary></summary> class C {$$ }"; var expected = @"/// <summary></summary> class C {$$ }"; VerifyInsertCommentCommand(code, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)] public void Command_Method_NotIfCommentExists() { var code = @"class C { /// <summary></summary> int M<T>(int goo) { $$return 0; } }"; var expected = @"class C { /// <summary></summary> int M<T>(int goo) { $$return 0; } }"; VerifyInsertCommentCommand(code, expected); } [WorkItem(538482, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538482")] [WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)] public void Command_FirstClassOnLine() { var code = @"$$class C { } class D { }"; var expected = @"/// <summary> /// $$ /// </summary> class C { } class D { }"; VerifyInsertCommentCommand(code, expected); } [WorkItem(538482, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538482")] [WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)] public void Command_NotOnSecondClassOnLine() { var code = @"class C { } $$class D { }"; var expected = @"class C { } $$class D { }"; VerifyInsertCommentCommand(code, expected); } [WorkItem(538482, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538482")] [WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)] public void Command_FirstMethodOnLine() { var code = @"class C { protected abstract void $$Goo(); protected abstract void Bar(); }"; var expected = @"class C { /// <summary> /// $$ /// </summary> protected abstract void Goo(); protected abstract void Bar(); }"; VerifyInsertCommentCommand(code, expected); } [WorkItem(538482, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538482")] [WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)] public void Command_NotOnSecondMethodOnLine() { var code = @"class C { protected abstract void Goo(); protected abstract void $$Bar(); }"; var expected = @"class C { protected abstract void Goo(); protected abstract void $$Bar(); }"; VerifyInsertCommentCommand(code, expected); } [WorkItem(917904, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/917904")] [WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)] public void TestUseTab() { var code = @"using System; public class Class1 { //$$ public Class1() { } }"; var expected = @"using System; public class Class1 { /// <summary> /// $$ /// </summary> public Class1() { } }"; VerifyTypingCharacter(code, expected, useTabs: true); } [WorkItem(2090, "https://github.com/dotnet/roslyn/issues/2090")] [WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)] public void TestOpenLineAbove1() { const string code = @"class C { /// <summary> /// stuff$$ /// </summary> void M() { } }"; var expected = @"class C { /// <summary> /// $$ /// stuff /// </summary> void M() { } }"; VerifyOpenLineAbove(code, expected); } [WorkItem(2090, "https://github.com/dotnet/roslyn/issues/2090")] [WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)] public void TestOpenLineAbove2() { const string code = @"class C { /// <summary> /// $$stuff /// </summary> void M() { } }"; const string expected = @"class C { /// <summary> /// $$ /// stuff /// </summary> void M() { } }"; VerifyOpenLineAbove(code, expected); } [WorkItem(2090, "https://github.com/dotnet/roslyn/issues/2090")] [WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)] public void TestOpenLineAbove3() { const string code = @"class C { /// $$<summary> /// stuff /// </summary> void M() { } }"; // Note that the caret position specified below does not look correct because // it is in virtual space in this case. const string expected = @"class C { $$ /// <summary> /// stuff /// </summary> void M() { } }"; VerifyOpenLineAbove(code, expected); } [WorkItem(2090, "https://github.com/dotnet/roslyn/issues/2090")] [WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)] public void TestOpenLineAbove4_Tabs() { const string code = @"class C { /// <summary> /// $$stuff /// </summary> void M() { } }"; const string expected = @"class C { /// <summary> /// $$ /// stuff /// </summary> void M() { } }"; VerifyOpenLineAbove(code, expected, useTabs: true); } [WorkItem(2090, "https://github.com/dotnet/roslyn/issues/2090")] [WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)] public void TestOpenLineBelow1() { const string code = @"class C { /// <summary> /// stuff$$ /// </summary> void M() { } }"; const string expected = @"class C { /// <summary> /// stuff /// $$ /// </summary> void M() { } }"; VerifyOpenLineBelow(code, expected); } [WorkItem(2090, "https://github.com/dotnet/roslyn/issues/2090")] [WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)] public void TestOpenLineBelow2() { const string code = @"class C { /// <summary> /// $$stuff /// </summary> void M() { } }"; const string expected = @"class C { /// <summary> /// stuff /// $$ /// </summary> void M() { } }"; VerifyOpenLineBelow(code, expected); } [WorkItem(2090, "https://github.com/dotnet/roslyn/issues/2090")] [WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)] public void TestOpenLineBelow3() { const string code = @"/// <summary> /// stuff /// $$</summary> "; const string expected = @"/// <summary> /// stuff /// </summary> /// $$ "; VerifyOpenLineBelow(code, expected); } [WorkItem(2090, "https://github.com/dotnet/roslyn/issues/2090")] [WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)] public void TestOpenLineBelow4_Tabs() { const string code = @"class C { /// <summary> /// $$stuff /// </summary> void M() { } }"; const string expected = @"class C { /// <summary> /// stuff /// $$ /// </summary> void M() { } }"; VerifyOpenLineBelow(code, expected, useTabs: true); } [WorkItem(468638, @"https://devdiv.visualstudio.com/DevDiv/NET%20Developer%20Experience%20IDE/_workitems/edit/468638")] [WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)] public void VerifyEnterWithTrimNewLineEditorConfigOption() { const string code = @"/// <summary> /// $$ /// </summary> class C { }"; const string expected = @"/// <summary> /// /// $$ /// </summary> class C { }"; try { VerifyPressingEnter(code, expected, useTabs: true, setOptionsOpt: workspace => { workspace.GetService<IEditorOptionsFactoryService>().GlobalOptions .SetOptionValue(DefaultOptions.TrimTrailingWhiteSpaceOptionName, true); }); } finally { TestWorkspace.CreateCSharp("").GetService<IEditorOptionsFactoryService>().GlobalOptions .SetOptionValue(DefaultOptions.TrimTrailingWhiteSpaceOptionName, false); } } protected override char DocumentationCommentCharacter { get { return '/'; } } internal override ICommandHandler CreateCommandHandler( IWaitIndicator waitIndicator, ITextUndoHistoryRegistry undoHistoryRegistry, IEditorOperationsFactoryService editorOperationsFactoryService) { return new DocumentationCommentCommandHandler(waitIndicator, undoHistoryRegistry, editorOperationsFactoryService); } protected override TestWorkspace CreateTestWorkspace(string code) => TestWorkspace.CreateCSharp(code); } }
20.118146
161
0.542062
[ "Apache-2.0" ]
20chan/roslyn
src/EditorFeatures/CSharpTest/DocumentationComments/DocumentationCommentTests.cs
40,359
C#
using System.Collections.Generic; using System.Linq; using Microsoft.Extensions.Logging; using Microsoft.TeamFoundation.WorkItemTracking.Client; using MigrationTools.Enrichers; namespace MigrationTools.ProcessorEnrichers { public class TfsValidateRequiredField : WorkItemProcessorEnricher { private TfsValidateRequiredFieldOptions _Options; public TfsValidateRequiredField(IMigrationEngine engine, ILogger<WorkItemProcessorEnricher> logger) : base(engine, logger) { } public override void Configure(IProcessorEnricherOptions options) { _Options = (TfsValidateRequiredFieldOptions)options; } public bool ValidatingRequiredField(string fieldToFind, List<_EngineV1.DataContracts.WorkItemData> sourceWorkItems) { var sourceWorkItemTypes = sourceWorkItems.Select(wid => wid.ToWorkItem().Type).Distinct(); var targetTypes = Engine.Target.WorkItems.Project.ToProject().WorkItemTypes; var result = true; foreach (WorkItemType sourceWorkItemType in sourceWorkItemTypes) { var workItemTypeName = sourceWorkItemType.Name; if (Engine.TypeDefinitionMaps.Items.ContainsKey(workItemTypeName)) { workItemTypeName = Engine.TypeDefinitionMaps.Items[workItemTypeName].Map(); } var targetType = targetTypes[workItemTypeName]; if (targetType.FieldDefinitions.Contains(fieldToFind)) { Log.LogDebug("ValidatingRequiredField: {WorkItemTypeName} contains {fieldToFind}", targetType.Name, fieldToFind); } else { Log.LogWarning("ValidatingRequiredField: {WorkItemTypeName} does not contain {fieldToFind}", targetType.Name, fieldToFind); result = false; } } return result; } //private void ConfigValidation() //{ // //Make sure that the ReflectedWorkItemId field name specified in the config exists in the target process, preferably on each work item type // var fields = _witClient.GetFieldsAsync(Engine.Target.Config.AsTeamProjectConfig().Project).Result; // bool rwiidFieldExists = fields.Any(x => x.ReferenceName == Engine.Target.Config.AsTeamProjectConfig().ReflectedWorkItemIDFieldName || x.Name == Engine.Target.Config.AsTeamProjectConfig().ReflectedWorkItemIDFieldName); // contextLog.Information("Found {FieldsFoundCount} work item fields.", fields.Count.ToString("n0")); // if (rwiidFieldExists) // contextLog.Information("Found '{ReflectedWorkItemIDFieldName}' in this project, proceeding.", Engine.Target.Config.AsTeamProjectConfig().ReflectedWorkItemIDFieldName); // else // { // contextLog.Information("Config file specifies '{ReflectedWorkItemIDFieldName}', which wasn't found.", Engine.Target.Config.AsTeamProjectConfig().ReflectedWorkItemIDFieldName); // contextLog.Information("Instead, found:"); // foreach (var field in fields.OrderBy(x => x.Name)) // contextLog.Information("{FieldType} - {FieldName} - {FieldRefName}", field.Type.ToString().PadLeft(15), field.Name.PadRight(20), field.ReferenceName ?? ""); // throw new Exception("Running a replay migration requires a ReflectedWorkItemId field to be defined in the target project's process."); // } //} } }
53.850746
231
0.659368
[ "MIT" ]
tomfrenzel/azure-devops-migration-tools
src/MigrationTools.Clients.AzureDevops.ObjectModel/ProcessorEnrichers/TfsValidateRequiredField.cs
3,610
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 workspaces-2015-04-08.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.WorkSpaces.Model { /// <summary> /// Describes a tag. /// </summary> public partial class Tag { private string _key; private string _value; /// <summary> /// Gets and sets the property Key. /// <para> /// The key of the tag. /// </para> /// </summary> public string Key { get { return this._key; } set { this._key = value; } } // Check to see if Key property is set internal bool IsSetKey() { return this._key != null; } /// <summary> /// Gets and sets the property Value. /// <para> /// The value of the tag. /// </para> /// </summary> public string Value { get { return this._value; } set { this._value = value; } } // Check to see if Value property is set internal bool IsSetValue() { return this._value != null; } } }
25.88
108
0.58372
[ "Apache-2.0" ]
Bio2hazard/aws-sdk-net
sdk/src/Services/WorkSpaces/Generated/Model/Tag.cs
1,941
C#
namespace MassTransit.AzureServiceBusTransport.Configuration { using System; public abstract class ServiceBusEntityConfigurator : IServiceBusEntityConfigurator { protected ServiceBusEntityConfigurator() { DefaultMessageTimeToLive = Defaults.DefaultMessageTimeToLive; } public TimeSpan? AutoDeleteOnIdle { get; set; } public TimeSpan? DefaultMessageTimeToLive { get; set; } public bool? EnableBatchedOperations { get; set; } public string UserMetadata { get; set; } } }
24.652174
73
0.680776
[ "ECL-2.0", "Apache-2.0" ]
AlexanderMeier/MassTransit
src/Transports/MassTransit.Azure.ServiceBus.Core/AzureServiceBusTransport/Configuration/ServiceBusEntityConfigurator.cs
567
C#
using AutoMapper; using Eventures.Data; using Eventures.Models; using Eventures.Services; using Eventures.Services.Contracts; using Eventures.Web.Middlewares; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; namespace Eventures.Web { public class Startup { public Startup(IConfiguration configuration) { this.Configuration = configuration; } public IConfiguration Configuration { get; } public void ConfigureServices(IServiceCollection services) { services.AddDbContext<EventuresDbContext>(options => options.UseSqlServer( this.Configuration.GetConnectionString("DefaultConnection"))); services.AddIdentity<User, IdentityRole>(options => { options.Password.RequireDigit = false; options.Password.RequiredLength = 5; options.Password.RequiredUniqueChars = 0; options.Password.RequireLowercase = false; options.Password.RequireNonAlphanumeric = false; options.Password.RequireUppercase = false; }) .AddDefaultTokenProviders() .AddEntityFrameworkStores<EventuresDbContext>(); services.AddAuthentication() .AddFacebook(facebookOptions => { facebookOptions.AppId = this.Configuration["Authentication:Facebook:AppId"]; facebookOptions.AppSecret = this.Configuration["Authentication:Facebook:AppSecret"]; }); services.AddMvc(options => options.Filters.Add(new AutoValidateAntiforgeryTokenAttribute())) .SetCompatibilityVersion(CompatibilityVersion.Version_2_1); services.AddAutoMapper(); services.AddScoped<IAccountService, AccountService>(); services.AddScoped<IEventsService, EventsService>(); services.AddScoped<IOrdersService, OrdersService>(); } public void Configure(IApplicationBuilder app) { app.UseDeveloperExceptionPage(); app.UseDatabaseErrorPage(); app.UseSeedDataMiddleware(); app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseAuthentication(); app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); } } }
33.604938
104
0.622704
[ "MIT" ]
KolyaPetrova/SoftUni--CSharp-Web
C# MVC Frameworks - ASP.NET Core/07. Architecture/Eventures/Eventures.Web/Startup.cs
2,724
C#
//------------------------------------------------------------------------------ // <auto-generated /> // // This file was automatically generated by SWIG (http://www.swig.org). // Version 3.0.10 // // Do not make changes to this file unless you know what you are doing--modify // the SWIG interface file instead. //------------------------------------------------------------------------------ namespace RakNet { public class NatPunchthroughDebugInterface_PacketLogger : NatPunchthroughDebugInterface { private global::System.Runtime.InteropServices.HandleRef swigCPtr; internal NatPunchthroughDebugInterface_PacketLogger(global::System.IntPtr cPtr, bool cMemoryOwn) : base(RakNetPINVOKE.NatPunchthroughDebugInterface_PacketLogger_SWIGUpcast(cPtr), cMemoryOwn) { swigCPtr = new global::System.Runtime.InteropServices.HandleRef(this, cPtr); } internal static global::System.Runtime.InteropServices.HandleRef getCPtr(NatPunchthroughDebugInterface_PacketLogger obj) { return (obj == null) ? new global::System.Runtime.InteropServices.HandleRef(null, global::System.IntPtr.Zero) : obj.swigCPtr; } ~NatPunchthroughDebugInterface_PacketLogger() { Dispose(); } public override void Dispose() { lock(this) { if (swigCPtr.Handle != global::System.IntPtr.Zero) { if (swigCMemOwn) { swigCMemOwn = false; RakNetPINVOKE.delete_NatPunchthroughDebugInterface_PacketLogger(swigCPtr); } swigCPtr = new global::System.Runtime.InteropServices.HandleRef(null, global::System.IntPtr.Zero); } global::System.GC.SuppressFinalize(this); base.Dispose(); } } public PacketLogger pl { set { RakNetPINVOKE.NatPunchthroughDebugInterface_PacketLogger_pl_set(swigCPtr, PacketLogger.getCPtr(value)); } get { global::System.IntPtr cPtr = RakNetPINVOKE.NatPunchthroughDebugInterface_PacketLogger_pl_get(swigCPtr); PacketLogger ret = (cPtr == global::System.IntPtr.Zero) ? null : new PacketLogger(cPtr, false); return ret; } } public NatPunchthroughDebugInterface_PacketLogger() : this(RakNetPINVOKE.new_NatPunchthroughDebugInterface_PacketLogger(), true) { } public override void OnClientMessage(string msg) { RakNetPINVOKE.NatPunchthroughDebugInterface_PacketLogger_OnClientMessage(swigCPtr, msg); } } }
37.253968
194
0.694078
[ "BSD-2-Clause" ]
Alexthegr92/RakNet
DependentExtensions/Swig/SwigOutput/SwigCSharpOutput/NatPunchthroughDebugInterface_PacketLogger.cs
2,347
C#
using Prism.Regions; namespace ManageUsecase { public interface INavigationService { void RequestNavigate<T>(NavigationParameters navigationParameters = null) where T : class; } }
22.333333
98
0.731343
[ "MIT" ]
nuitsjp/PrismWpfStudy
ManageUsecase/ManageUsecase/INavigationService.cs
203
C#
/* Copyright 2012 Zoran Maksimovic (zoran.maksimovich@gmail.com http://www.agile-code.com) Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using System; using System.Runtime.Serialization; using NUnit.Framework; using Newtonsoft.Json; using System.Diagnostics; using System.Linq; namespace Google.DataTable.Net.Wrapper.Tests { [TestFixture] public class DataTableTest { [Test(Description="Creates a new DataTable instance by using the default constructor")] public void CanCreateDataTableWithEmptyConstructor() { //Arrange ------------ DataTable dt = null; //Act ----------------- dt = new DataTable(); //Assert -------------- Assert.IsTrue(dt!=null); } [Test] public void CanAddNewRowToTheDataTable() { //Arrange ------------ DataTable dt = GetNewDataTableInstance(); Row row = dt.NewRow(); //Act ----------------- dt.AddRow(row); //Assert -------------- Assert.IsTrue(dt.Rows.Count() == 1); } [Test] public void CanAddColumnToTheDataTable() { //Arrange ------------ DataTable dt = GetNewDataTableInstance(); Column col = new Column(ColumnType.String); //Act ----------------- dt.AddColumn(col); //Assert -------------- Assert.IsTrue(dt.Columns.Count() == 1); } [Test] public void CanListColumns() { //Arrange ------------ DataTable dt = GetNewDataTableInstance(); Column col = new Column(ColumnType.String, "column1"); Column col2 = new Column(ColumnType.Number, "column2"); dt.AddColumn(col); dt.AddColumn(col2); //Act ----------------- var columns = dt.Columns; //Assert -------------- Assert.IsTrue(columns.Count() == 2); } [Test] public void CreateDateTimeObjects() { //Arrange ------------ DataTable dt = GetNewDataTableInstance(); Column dateTimeColumn = new Column(ColumnType.Datetime, "DateTimeColumn"); Column dateColumn = new Column(ColumnType.Date, "DateColumn"); dt.AddColumn(dateTimeColumn); dt.AddColumn(dateColumn); Row r = dt.NewRow(); r.AddCell(new Cell(DateTime.Now)); // DateTime column value r.AddCell(new Cell(DateTime.Now)); // Date columnvalue dt.AddRow(r); //Act ----------------- var json = dt.GetJson(); //Assert -------------- Assert.IsTrue(json != null); } [Test] public void ColumnsWithTheSameIdAreNotAccepted() { const string COLUMN_NAME = "whatever_column_name"; //Arrange ------------ DataTable dt = GetNewDataTableInstance(); Column col = new Column(ColumnType.String, COLUMN_NAME, ""); Column col2 = new Column(ColumnType.String, COLUMN_NAME, ""); //Act ----------------- dt.AddColumn(col); Assert.Throws<Exception>(() => dt.AddColumn(col2)); } [Test(Description = "Unfortunately, is a known issue that the deserialization for a custom generated class doesn't work")] public void CanDeserializeDataTableJsonWithJSonNet() { //Arrange ------------ DataTable dt = GetExampleDataTable(); //Act ---------------- var json = dt.GetJson(); //Assert ------------- Assert.Throws<SerializationException>(() => DeserializeFromJson(json)); } private DataTable DeserializeFromJson(string json) { var dataTable = JsonConvert.DeserializeObject<DataTable>(json); return dataTable; } [Test(Description="Test that the serialization/deserialization by using Json.NET is working")] public void CanSerializeAndDeserializeWithJsonNet() { //Arrange ------------ var dt = GetExampleDataTable(); //Act ---------------- var dtSerialized = JsonConvert.SerializeObject(dt); var dtDeserialized = JsonConvert.DeserializeObject<DataTable>(dtSerialized); //Assert-------------- Assert.IsTrue(dtSerialized != null); Assert.IsTrue(dtDeserialized != null); } /// <summary> /// Get some data to work on... /// </summary> /// <returns></returns> private DataTable GetExampleDataTable() { DataTable dt = GetNewDataTableInstance(); var columnYear = new Column(ColumnType.Number, "Year"); var columnCount = new Column(ColumnType.String, "Count"); //Act ----------------- dt.AddColumn(columnYear); dt.AddColumn(columnCount); var row1 = dt.NewRow(); var row2 = dt.NewRow(); var row3 = dt.NewRow(); row1.AddCellRange(new Cell[] { new Cell() {Value = 2012, Formatted = "2012"}, new Cell() {Value = 1, Formatted = "1"} }); row2.AddCellRange(new Cell[] { new Cell() {Value = 2013, Formatted = "2013"}, new Cell() {Value = 100, Formatted = "100"} }); row3.AddCellRange(new Cell[] { new Cell() {Value = 2014, Formatted = "2014"}, new Cell() {Value = 50, Formatted = "50"} }); dt.AddRow(row1); dt.AddRow(row2); dt.AddRow(row3); return dt; } /// <summary> /// Returns a new instance of the DataTable. /// </summary> /// <returns></returns> public DataTable GetNewDataTableInstance() { return new DataTable(); } [Test(Description = "Check that the column Id is automatically assigned")] public void DataTable_Column_id_Assgined_if_Not_specified() { //Arrange ------------------- DataTable dt = GetNewDataTableInstance(); var column = new Column(); dt.AddColumn(column); //Assert ------------------- var columnId = dt.Columns.ElementAt(0).Id; Assert.That( columnId == "Column 0"); } [Test] [Explicit] public void RunPerformanceTest() { const int TOTAL_NUM_OF_ROWS = 500; DataTable dt = GetNewDataTableInstance(); var columnYear = new Column(ColumnType.Number, "Year"); var columnCount = new Column(ColumnType.String, "Count"); //Act ----------------- dt.AddColumn(columnYear); dt.AddColumn(columnCount); var sw = new Stopwatch(); sw.Start(); for (int i = 0; i < TOTAL_NUM_OF_ROWS; i++) { var row = dt.NewRow(); row.AddCellRange(new Cell[] { new Cell() {Value = 2012, Formatted = "2012"}, new Cell() {Value = 1, Formatted = "1"} }); dt.AddRow(row); } sw.Stop(); Debug.WriteLine("Adding rows: " + sw.ElapsedMilliseconds + " ms"); sw.Reset(); sw.Start(); var json = dt.GetJson(); sw.Stop(); Debug.WriteLine("Serialization takes: " + sw.ElapsedMilliseconds + " ms"); Assert.That(json != null); Assert.That(json.Length > 0); Assert.True(true); } } }
32.18797
130
0.500234
[ "Apache-2.0" ]
DaleCam/GoogleDataTableLib
src/Google.DataTable.Net.Wrapper.Tests/DataTableTest.cs
8,564
C#
using Microsoft.AspNetCore.Hosting; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text.RegularExpressions; namespace VRT.Resume.Mvc { public static class WebHostEnvironmentExtensions { public static IEnumerable<(string relativePath, string caption)> GetImages(this IWebHostEnvironment hosting, string relativeDirPath) { var path = hosting.GetFullPath(relativeDirPath); var names = Directory.GetFiles(path) .Where(s => s.EndsWith(".svg") || s.EndsWith(".png")) .Select(s => { var fileName = Path.GetFileName(s); var relativePath = Path.Combine(relativeDirPath, fileName); return (relativePath.AsHtmPath(), Path.GetFileNameWithoutExtension(fileName)); }); return names; } public static string GetImageInfo(this IWebHostEnvironment hosting, string relativePath) => hosting.GetFullPath(relativePath); private static string GetFullPath(this IWebHostEnvironment hosting, string relativePath) => Path.Combine(hosting.WebRootPath, relativePath); private static string AsHtmPath(this string path) { if (string.IsNullOrWhiteSpace(path)) return path; return Regex.Replace($"/{path}", @"[\\/]{1,}", "/"); } } }
37.243902
98
0.591356
[ "MIT" ]
rutkowskit/VRT.Resume
VRT.Resume.Mvc/Extensions/WebHostEnvironmentExtensions.cs
1,529
C#
// Copyright (c) Christophe Gondouin (CGO Conseils). All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Model { /// <summary> /// AddEventRequestMessage /// </summary> public enum PMRegardingObjects { BusinessUnit, SystemUser, Contact, Appointment, SaleCycle, PhoneCall, HERMES_INTERET, HERMES_PROSPECT, SaleOffer, RENDEZVOUS, HERMES_AGENCE, HERMES_VENDEUR } }
22.6
95
0.646018
[ "MIT" ]
papayet974/XrmFramework
src/Utils/XrmFramework.Common/Utils/PMRegardingObjects.cs
680
C#
using System; using System.Linq; using Microsoft.Extensions.DependencyInjection; namespace Oakton.AspNetCore.Descriptions { public class DefaultDescribedSystemPartFactory : IDescribedSystemPartFactory { private readonly IServiceProvider _services; public DefaultDescribedSystemPartFactory(IServiceProvider services) { _services = services; } public IDescribedSystemPart[] FindParts() { return _services.GetServices<IDescribedSystemPart>().ToArray(); } } }
26.190476
80
0.7
[ "Apache-2.0" ]
ndcomplete/oakton
src/Oakton.AspNetCore/Descriptions/DefaultDescribedSystemPartFactory.cs
550
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("TOCManager.DataLayer")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("TOCManager.DataLayer")] [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("9cafa2ef-1e8b-4d5a-a806-07d8158eed60")] // 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.189189
84
0.746638
[ "MIT" ]
radgie/TOC-Manager
TOCManager.DataLayer/Properties/AssemblyInfo.cs
1,416
C#
// --------------------------------------------------------------- // Copyright (c) Coalition of the Good-Hearted Engineers // --------------------------------------------------------------- namespace Ezregx { public interface IExpression { } }
23.545455
67
0.328185
[ "MIT" ]
hassanhabib/Ezregx
Ezregx/IExpression.cs
261
C#
using Content.Server.GameObjects.Components.Mobs; using Content.Shared.GameObjects.Components.Mobs; using JetBrains.Annotations; using Robust.Shared.GameObjects.Systems; using Robust.Shared.Interfaces.Timing; using Robust.Shared.IoC; namespace Content.Server.GameObjects.EntitySystems { [UsedImplicitly] internal sealed class TimedOverlayRemovalSystem : EntitySystem { [Dependency] private readonly IGameTiming _gameTiming = default!; public override void Update(float frameTime) { base.Update(frameTime); foreach (var component in ComponentManager.EntityQuery<ServerOverlayEffectsComponent>()) { foreach (var overlay in component.ActiveOverlays.ToArray()) { if (overlay.TryGetOverlayParameter<TimedOverlayParameter>(out var parameter)) { if (parameter.StartedAt + parameter.Length <= _gameTiming.CurTime.TotalMilliseconds) { component.RemoveOverlay(overlay); } } } } } } }
33.305556
108
0.598832
[ "MIT" ]
ALMv1/space-station-14
Content.Server/GameObjects/EntitySystems/TimedOverlayRemovalSystem.cs
1,201
C#
#if ASYNC using System.Linq; using System.Data; using System.Diagnostics; using System; using System.Threading.Tasks; using System.Threading; using System.Data.SqlClient; using Xunit; namespace Dapper.Tests { public partial class TestSuite { [Fact] public async Task TestBasicStringUsageAsync() { var query = await connection.QueryAsync<string>("select 'abc' as [Value] union all select @txt", new { txt = "def" }); var arr = query.ToArray(); arr.IsSequenceEqualTo(new[] { "abc", "def" }); } [Fact] public async Task TestBasicStringUsageAsyncNonBuffered() { var query = await connection.QueryAsync<string>(new CommandDefinition("select 'abc' as [Value] union all select @txt", new { txt = "def" }, flags: CommandFlags.None)); var arr = query.ToArray(); arr.IsSequenceEqualTo(new[] { "abc", "def" }); } [Fact] public void TestLongOperationWithCancellation() { CancellationTokenSource cancel = new CancellationTokenSource(TimeSpan.FromSeconds(5)); var task = connection.QueryAsync<int>(new CommandDefinition("waitfor delay '00:00:10';select 1", cancellationToken: cancel.Token)); try { if (!task.Wait(TimeSpan.FromSeconds(7))) { throw new TimeoutException(); // should have cancelled } } catch (AggregateException agg) { (agg.InnerException is SqlException).IsTrue(); } } [Fact] public async Task TestBasicStringUsageClosedAsync() { var query = await connection.QueryAsync<string>("select 'abc' as [Value] union all select @txt", new { txt = "def" }); var arr = query.ToArray(); arr.IsSequenceEqualTo(new[] { "abc", "def" }); } [Fact] public async Task TestQueryDynamicAsync() { var row = (await connection.QueryAsync("select 'abc' as [Value]")).Single(); string value = row.Value; value.IsEqualTo("abc"); } [Fact] public async Task TestClassWithStringUsageAsync() { var query = await connection.QueryAsync<BasicType>("select 'abc' as [Value] union all select @txt", new { txt = "def" }); var arr = query.ToArray(); arr.Select(x => x.Value).IsSequenceEqualTo(new[] { "abc", "def" }); } [Fact] public async Task TestExecuteAsync() { var val = await connection.ExecuteAsync("declare @foo table(id int not null); insert @foo values(@id);", new { id = 1 }); val.Equals(1); } [Fact] public void TestExecuteClosedConnAsync() { var query = connection.ExecuteAsync("declare @foo table(id int not null); insert @foo values(@id);", new { id = 1 }); var val = query.Result; val.Equals(1); } [Fact] public async Task TestMultiMapWithSplitAsync() { const string sql = @"select 1 as id, 'abc' as name, 2 as id, 'def' as name"; var productQuery = await connection.QueryAsync<Product, Category, Product>(sql, (prod, cat) => { prod.Category = cat; return prod; }); var product = productQuery.First(); // assertions product.Id.IsEqualTo(1); product.Name.IsEqualTo("abc"); product.Category.Id.IsEqualTo(2); product.Category.Name.IsEqualTo("def"); } [Fact] public async Task TestMultiMapArbitraryWithSplitAsync() { const string sql = @"select 1 as id, 'abc' as name, 2 as id, 'def' as name"; var productQuery = await connection.QueryAsync<Product>(sql, new[] { typeof(Product), typeof(Category) }, (objects) => { var prod = (Product)objects[0]; prod.Category = (Category)objects[1]; return prod; }); var product = productQuery.First(); // assertions product.Id.IsEqualTo(1); product.Name.IsEqualTo("abc"); product.Category.Id.IsEqualTo(2); product.Category.Name.IsEqualTo("def"); } [Fact] public async Task TestMultiMapWithSplitClosedConnAsync() { var sql = @"select 1 as id, 'abc' as name, 2 as id, 'def' as name"; using (var conn = GetClosedConnection()) { var productQuery = await conn.QueryAsync<Product, Category, Product>(sql, (prod, cat) => { prod.Category = cat; return prod; }); var product = productQuery.First(); // assertions product.Id.IsEqualTo(1); product.Name.IsEqualTo("abc"); product.Category.Id.IsEqualTo(2); product.Category.Name.IsEqualTo("def"); } } [Fact] public async Task TestMultiAsync() { using (SqlMapper.GridReader multi = await connection.QueryMultipleAsync("select 1; select 2")) { multi.ReadAsync<int>().Result.Single().IsEqualTo(1); multi.ReadAsync<int>().Result.Single().IsEqualTo(2); } } [Fact] public async Task TestMultiAsyncViaFirstOrDefault() { using (SqlMapper.GridReader multi = await connection.QueryMultipleAsync("select 1; select 2; select 3; select 4; select 5")) { multi.ReadFirstOrDefaultAsync<int>().Result.IsEqualTo(1); multi.ReadAsync<int>().Result.Single().IsEqualTo(2); multi.ReadFirstOrDefaultAsync<int>().Result.IsEqualTo(3); multi.ReadAsync<int>().Result.Single().IsEqualTo(4); multi.ReadFirstOrDefaultAsync<int>().Result.IsEqualTo(5); } } [Fact] public async Task TestMultiClosedConnAsync() { using (SqlMapper.GridReader multi = await connection.QueryMultipleAsync("select 1; select 2")) { multi.ReadAsync<int>().Result.Single().IsEqualTo(1); multi.ReadAsync<int>().Result.Single().IsEqualTo(2); } } [Fact] public async Task TestMultiClosedConnAsyncViaFirstOrDefault() { using (SqlMapper.GridReader multi = await connection.QueryMultipleAsync("select 1; select 2; select 3; select 4; select 5;")) { multi.ReadFirstOrDefaultAsync<int>().Result.IsEqualTo(1); multi.ReadAsync<int>().Result.Single().IsEqualTo(2); multi.ReadFirstOrDefaultAsync<int>().Result.IsEqualTo(3); multi.ReadAsync<int>().Result.Single().IsEqualTo(4); multi.ReadFirstOrDefaultAsync<int>().Result.IsEqualTo(5); } } #if !COREFX [Fact] public async Task ExecuteReaderOpenAsync() { var dt = new DataTable(); dt.Load(await connection.ExecuteReaderAsync("select 3 as [three], 4 as [four]")); dt.Columns.Count.IsEqualTo(2); dt.Columns[0].ColumnName.IsEqualTo("three"); dt.Columns[1].ColumnName.IsEqualTo("four"); dt.Rows.Count.IsEqualTo(1); ((int)dt.Rows[0][0]).IsEqualTo(3); ((int)dt.Rows[0][1]).IsEqualTo(4); } [Fact] public async Task ExecuteReaderClosedAsync() { using (var conn = GetClosedConnection()) { var dt = new DataTable(); dt.Load(await conn.ExecuteReaderAsync("select 3 as [three], 4 as [four]")); dt.Columns.Count.IsEqualTo(2); dt.Columns[0].ColumnName.IsEqualTo("three"); dt.Columns[1].ColumnName.IsEqualTo("four"); dt.Rows.Count.IsEqualTo(1); ((int)dt.Rows[0][0]).IsEqualTo(3); ((int)dt.Rows[0][1]).IsEqualTo(4); } } #endif [Fact] public async Task LiteralReplacementOpen() { await LiteralReplacement(connection); } [Fact] public async Task LiteralReplacementClosed() { using (var conn = GetClosedConnection()) await LiteralReplacement(conn); } private async Task LiteralReplacement(IDbConnection conn) { try { await conn.ExecuteAsync("drop table literal1"); } catch { } await conn.ExecuteAsync("create table literal1 (id int not null, foo int not null)"); await conn.ExecuteAsync("insert literal1 (id,foo) values ({=id}, @foo)", new { id = 123, foo = 456 }); var rows = new[] { new { id = 1, foo = 2 }, new { id = 3, foo = 4 } }; await conn.ExecuteAsync("insert literal1 (id,foo) values ({=id}, @foo)", rows); var count = (await conn.QueryAsync<int>("select count(1) from literal1 where id={=foo}", new { foo = 123 })).Single(); count.IsEqualTo(1); int sum = (await conn.QueryAsync<int>("select sum(id) + sum(foo) from literal1")).Single(); sum.IsEqualTo(123 + 456 + 1 + 2 + 3 + 4); } [Fact] public async Task LiteralReplacementDynamicOpen() { await LiteralReplacementDynamic(connection); } [Fact] public async Task LiteralReplacementDynamicClosed() { using (var conn = GetClosedConnection()) await LiteralReplacementDynamic(conn); } private async Task LiteralReplacementDynamic(IDbConnection conn) { var args = new DynamicParameters(); args.Add("id", 123); try { await conn.ExecuteAsync("drop table literal2"); } catch { } await conn.ExecuteAsync("create table literal2 (id int not null)"); await conn.ExecuteAsync("insert literal2 (id) values ({=id})", args); args = new DynamicParameters(); args.Add("foo", 123); var count = (await conn.QueryAsync<int>("select count(1) from literal2 where id={=foo}", args)).Single(); count.IsEqualTo(1); } [Fact] public async Task LiteralInAsync() { await connection.ExecuteAsync("create table #literalin(id int not null);"); await connection.ExecuteAsync("insert #literalin (id) values (@id)", new[] { new { id = 1 }, new { id = 2 }, new { id = 3 }, }); var count = (await connection.QueryAsync<int>("select count(1) from #literalin where id in {=ids}", new { ids = new[] { 1, 3, 4 } })).Single(); count.IsEqualTo(2); } [Fact] public async Task RunSequentialVersusParallelAsync() { var ids = Enumerable.Range(1, 20000).Select(id => new { id }).ToArray(); await marsConnection.ExecuteAsync(new CommandDefinition("select @id", ids.Take(5), flags: CommandFlags.None)); var watch = Stopwatch.StartNew(); await marsConnection.ExecuteAsync(new CommandDefinition("select @id", ids, flags: CommandFlags.None)); watch.Stop(); Console.WriteLine("No pipeline: {0}ms", watch.ElapsedMilliseconds); watch = Stopwatch.StartNew(); await marsConnection.ExecuteAsync(new CommandDefinition("select @id", ids, flags: CommandFlags.Pipelined)); watch.Stop(); Console.WriteLine("Pipeline: {0}ms", watch.ElapsedMilliseconds); } [Fact] public void RunSequentialVersusParallelSync() { var ids = Enumerable.Range(1, 20000).Select(id => new { id }).ToArray(); marsConnection.Execute(new CommandDefinition("select @id", ids.Take(5), flags: CommandFlags.None)); var watch = Stopwatch.StartNew(); marsConnection.Execute(new CommandDefinition("select @id", ids, flags: CommandFlags.None)); watch.Stop(); Console.WriteLine("No pipeline: {0}ms", watch.ElapsedMilliseconds); watch = Stopwatch.StartNew(); marsConnection.Execute(new CommandDefinition("select @id", ids, flags: CommandFlags.Pipelined)); watch.Stop(); Console.WriteLine("Pipeline: {0}ms", watch.ElapsedMilliseconds); } [Fact] public void AssertNoCacheWorksForQueryMultiple() { int a = 123, b = 456; var cmdDef = new CommandDefinition(@"select @a; select @b;", new { a, b }, commandType: CommandType.Text, flags: CommandFlags.NoCache); int c, d; SqlMapper.PurgeQueryCache(); int before = SqlMapper.GetCachedSQLCount(); using (var multi = marsConnection.QueryMultiple(cmdDef)) { c = multi.Read<int>().Single(); d = multi.Read<int>().Single(); } int after = SqlMapper.GetCachedSQLCount(); before.IsEqualTo(0); after.IsEqualTo(0); c.IsEqualTo(123); d.IsEqualTo(456); } class BasicType { public string Value { get; set; } } [Fact] public async Task TypeBasedViaTypeAsync() { Type type = GetSomeType(); dynamic actual = (await marsConnection.QueryAsync(type, "select @A as [A], @B as [B]", new { A = 123, B = "abc" })).FirstOrDefault(); ((object)actual).GetType().IsEqualTo(type); int a = actual.A; string b = actual.B; a.IsEqualTo(123); b.IsEqualTo("abc"); } [Fact] public async Task TypeBasedViaTypeAsyncFirstOrDefault() { Type type = GetSomeType(); dynamic actual = (await marsConnection.QueryFirstOrDefaultAsync(type, "select @A as [A], @B as [B]", new { A = 123, B = "abc" })); ((object)actual).GetType().IsEqualTo(type); int a = actual.A; string b = actual.B; a.IsEqualTo(123); b.IsEqualTo("abc"); } [Fact] public async Task Issue22_ExecuteScalarAsync() { int i = await connection.ExecuteScalarAsync<int>("select 123"); i.IsEqualTo(123); i = await connection.ExecuteScalarAsync<int>("select cast(123 as bigint)"); i.IsEqualTo(123); long j = await connection.ExecuteScalarAsync<long>("select 123"); j.IsEqualTo(123L); j = await connection.ExecuteScalarAsync<long>("select cast(123 as bigint)"); j.IsEqualTo(123L); int? k = await connection.ExecuteScalarAsync<int?>("select @i", new { i = default(int?) }); k.IsNull(); } [Fact] public async Task Issue346_QueryAsyncConvert() { int i = (await connection.QueryAsync<int>("Select Cast(123 as bigint)")).First(); i.IsEqualTo(123); } [Fact] public async Task TestSupportForDynamicParametersOutputExpressionsAsync() { { var bob = new Person { Name = "bob", PersonId = 1, Address = new Address { PersonId = 2 } }; var p = new DynamicParameters(bob); p.Output(bob, b => b.PersonId); p.Output(bob, b => b.Occupation); p.Output(bob, b => b.NumberOfLegs); p.Output(bob, b => b.Address.Name); p.Output(bob, b => b.Address.PersonId); await connection.ExecuteAsync(@" SET @Occupation = 'grillmaster' SET @PersonId = @PersonId + 1 SET @NumberOfLegs = @NumberOfLegs - 1 SET @AddressName = 'bobs burgers' SET @AddressPersonId = @PersonId", p); bob.Occupation.IsEqualTo("grillmaster"); bob.PersonId.IsEqualTo(2); bob.NumberOfLegs.IsEqualTo(1); bob.Address.Name.IsEqualTo("bobs burgers"); bob.Address.PersonId.IsEqualTo(2); } } [Fact] public async Task TestSupportForDynamicParametersOutputExpressions_ScalarAsync() { var bob = new Person { Name = "bob", PersonId = 1, Address = new Address { PersonId = 2 } }; var p = new DynamicParameters(bob); p.Output(bob, b => b.PersonId); p.Output(bob, b => b.Occupation); p.Output(bob, b => b.NumberOfLegs); p.Output(bob, b => b.Address.Name); p.Output(bob, b => b.Address.PersonId); var result = (int)(await connection.ExecuteScalarAsync(@" SET @Occupation = 'grillmaster' SET @PersonId = @PersonId + 1 SET @NumberOfLegs = @NumberOfLegs - 1 SET @AddressName = 'bobs burgers' SET @AddressPersonId = @PersonId select 42", p)); bob.Occupation.IsEqualTo("grillmaster"); bob.PersonId.IsEqualTo(2); bob.NumberOfLegs.IsEqualTo(1); bob.Address.Name.IsEqualTo("bobs burgers"); bob.Address.PersonId.IsEqualTo(2); result.IsEqualTo(42); } [Fact] public async Task TestSupportForDynamicParametersOutputExpressions_Query_Default() { var bob = new Person { Name = "bob", PersonId = 1, Address = new Address { PersonId = 2 } }; var p = new DynamicParameters(bob); p.Output(bob, b => b.PersonId); p.Output(bob, b => b.Occupation); p.Output(bob, b => b.NumberOfLegs); p.Output(bob, b => b.Address.Name); p.Output(bob, b => b.Address.PersonId); var result = (await connection.QueryAsync<int>(@" SET @Occupation = 'grillmaster' SET @PersonId = @PersonId + 1 SET @NumberOfLegs = @NumberOfLegs - 1 SET @AddressName = 'bobs burgers' SET @AddressPersonId = @PersonId select 42", p)).Single(); bob.Occupation.IsEqualTo("grillmaster"); bob.PersonId.IsEqualTo(2); bob.NumberOfLegs.IsEqualTo(1); bob.Address.Name.IsEqualTo("bobs burgers"); bob.Address.PersonId.IsEqualTo(2); result.IsEqualTo(42); } [Fact] public async Task TestSupportForDynamicParametersOutputExpressions_Query_BufferedAsync() { var bob = new Person { Name = "bob", PersonId = 1, Address = new Address { PersonId = 2 } }; var p = new DynamicParameters(bob); p.Output(bob, b => b.PersonId); p.Output(bob, b => b.Occupation); p.Output(bob, b => b.NumberOfLegs); p.Output(bob, b => b.Address.Name); p.Output(bob, b => b.Address.PersonId); var result = (await connection.QueryAsync<int>(new CommandDefinition(@" SET @Occupation = 'grillmaster' SET @PersonId = @PersonId + 1 SET @NumberOfLegs = @NumberOfLegs - 1 SET @AddressName = 'bobs burgers' SET @AddressPersonId = @PersonId select 42", p, flags: CommandFlags.Buffered))).Single(); bob.Occupation.IsEqualTo("grillmaster"); bob.PersonId.IsEqualTo(2); bob.NumberOfLegs.IsEqualTo(1); bob.Address.Name.IsEqualTo("bobs burgers"); bob.Address.PersonId.IsEqualTo(2); result.IsEqualTo(42); } [Fact] public async Task TestSupportForDynamicParametersOutputExpressions_Query_NonBufferedAsync() { var bob = new Person { Name = "bob", PersonId = 1, Address = new Address { PersonId = 2 } }; var p = new DynamicParameters(bob); p.Output(bob, b => b.PersonId); p.Output(bob, b => b.Occupation); p.Output(bob, b => b.NumberOfLegs); p.Output(bob, b => b.Address.Name); p.Output(bob, b => b.Address.PersonId); var result = (await connection.QueryAsync<int>(new CommandDefinition(@" SET @Occupation = 'grillmaster' SET @PersonId = @PersonId + 1 SET @NumberOfLegs = @NumberOfLegs - 1 SET @AddressName = 'bobs burgers' SET @AddressPersonId = @PersonId select 42", p, flags: CommandFlags.None))).Single(); bob.Occupation.IsEqualTo("grillmaster"); bob.PersonId.IsEqualTo(2); bob.NumberOfLegs.IsEqualTo(1); bob.Address.Name.IsEqualTo("bobs burgers"); bob.Address.PersonId.IsEqualTo(2); result.IsEqualTo(42); } [Fact] public async Task TestSupportForDynamicParametersOutputExpressions_QueryMultipleAsync() { var bob = new Person { Name = "bob", PersonId = 1, Address = new Address { PersonId = 2 } }; var p = new DynamicParameters(bob); p.Output(bob, b => b.PersonId); p.Output(bob, b => b.Occupation); p.Output(bob, b => b.NumberOfLegs); p.Output(bob, b => b.Address.Name); p.Output(bob, b => b.Address.PersonId); int x, y; using (var multi = await connection.QueryMultipleAsync(@" SET @Occupation = 'grillmaster' SET @PersonId = @PersonId + 1 SET @NumberOfLegs = @NumberOfLegs - 1 SET @AddressName = 'bobs burgers' select 42 select 17 SET @AddressPersonId = @PersonId", p)) { x = multi.ReadAsync<int>().Result.Single(); y = multi.ReadAsync<int>().Result.Single(); } bob.Occupation.IsEqualTo("grillmaster"); bob.PersonId.IsEqualTo(2); bob.NumberOfLegs.IsEqualTo(1); bob.Address.Name.IsEqualTo("bobs burgers"); bob.Address.PersonId.IsEqualTo(2); x.IsEqualTo(42); y.IsEqualTo(17); } [Fact] public async Task TestSubsequentQueriesSuccessAsync() { var data0 = (await connection.QueryAsync<AsyncFoo0>("select 1 as [Id] where 1 = 0")).ToList(); data0.Count.IsEqualTo(0); var data1 = (await connection.QueryAsync<AsyncFoo1>(new CommandDefinition("select 1 as [Id] where 1 = 0", flags: CommandFlags.Buffered))).ToList(); data1.Count.IsEqualTo(0); var data2 = (await connection.QueryAsync<AsyncFoo2>(new CommandDefinition("select 1 as [Id] where 1 = 0", flags: CommandFlags.None))).ToList(); data2.Count.IsEqualTo(0); data0 = (await connection.QueryAsync<AsyncFoo0>("select 1 as [Id] where 1 = 0")).ToList(); data0.Count.IsEqualTo(0); data1 = (await connection.QueryAsync<AsyncFoo1>(new CommandDefinition("select 1 as [Id] where 1 = 0", flags: CommandFlags.Buffered))).ToList(); data1.Count.IsEqualTo(0); data2 = (await connection.QueryAsync<AsyncFoo2>(new CommandDefinition("select 1 as [Id] where 1 = 0", flags: CommandFlags.None))).ToList(); data2.Count.IsEqualTo(0); } class AsyncFoo0 { public int Id { get; set; } } class AsyncFoo1 { public int Id { get; set; } } class AsyncFoo2 { public int Id { get; set; } } [Fact] public async Task TestSchemaChangedViaFirstOrDefaultAsync() { await connection.ExecuteAsync("create table #dog(Age int, Name nvarchar(max)) insert #dog values(1, 'Alf')"); try { var d = await connection.QueryFirstOrDefaultAsync<Dog>("select * from #dog"); d.Name.IsEqualTo("Alf"); d.Age.IsEqualTo(1); connection.Execute("alter table #dog drop column Name"); d = await connection.QueryFirstOrDefaultAsync<Dog>("select * from #dog"); d.Name.IsNull(); d.Age.IsEqualTo(1); } finally { await connection.ExecuteAsync("drop table #dog"); } } [Fact] public async Task TestMultiMapArbitraryMapsAsync() { // please excuse the trite example, but it is easier to follow than a more real-world one const string createSql = @" create table #ReviewBoards (Id int, Name varchar(20), User1Id int, User2Id int, User3Id int, User4Id int, User5Id int, User6Id int, User7Id int, User8Id int, User9Id int) create table #Users (Id int, Name varchar(20)) insert #Users values(1, 'User 1') insert #Users values(2, 'User 2') insert #Users values(3, 'User 3') insert #Users values(4, 'User 4') insert #Users values(5, 'User 5') insert #Users values(6, 'User 6') insert #Users values(7, 'User 7') insert #Users values(8, 'User 8') insert #Users values(9, 'User 9') insert #ReviewBoards values(1, 'Review Board 1', 1, 2, 3, 4, 5, 6, 7, 8, 9) "; await connection.ExecuteAsync(createSql); try { const string sql = @" select rb.Id, rb.Name, u1.*, u2.*, u3.*, u4.*, u5.*, u6.*, u7.*, u8.*, u9.* from #ReviewBoards rb inner join #Users u1 on u1.Id = rb.User1Id inner join #Users u2 on u2.Id = rb.User2Id inner join #Users u3 on u3.Id = rb.User3Id inner join #Users u4 on u4.Id = rb.User4Id inner join #Users u5 on u5.Id = rb.User5Id inner join #Users u6 on u6.Id = rb.User6Id inner join #Users u7 on u7.Id = rb.User7Id inner join #Users u8 on u8.Id = rb.User8Id inner join #Users u9 on u9.Id = rb.User9Id "; var types = new[] { typeof(ReviewBoard), typeof(User), typeof(User), typeof(User), typeof(User), typeof(User), typeof(User), typeof(User), typeof(User), typeof(User) }; Func<object[], ReviewBoard> mapper = (objects) => { var board = (ReviewBoard)objects[0]; board.User1 = (User)objects[1]; board.User2 = (User)objects[2]; board.User3 = (User)objects[3]; board.User4 = (User)objects[4]; board.User5 = (User)objects[5]; board.User6 = (User)objects[6]; board.User7 = (User)objects[7]; board.User8 = (User)objects[8]; board.User9 = (User)objects[9]; return board; }; var data = (await connection.QueryAsync<ReviewBoard>(sql, types, mapper)).ToList(); var p = data.First(); p.Id.IsEqualTo(1); p.Name.IsEqualTo("Review Board 1"); p.User1.Id.IsEqualTo(1); p.User2.Id.IsEqualTo(2); p.User3.Id.IsEqualTo(3); p.User4.Id.IsEqualTo(4); p.User5.Id.IsEqualTo(5); p.User6.Id.IsEqualTo(6); p.User7.Id.IsEqualTo(7); p.User8.Id.IsEqualTo(8); p.User9.Id.IsEqualTo(9); p.User1.Name.IsEqualTo("User 1"); p.User2.Name.IsEqualTo("User 2"); p.User3.Name.IsEqualTo("User 3"); p.User4.Name.IsEqualTo("User 4"); p.User5.Name.IsEqualTo("User 5"); p.User6.Name.IsEqualTo("User 6"); p.User7.Name.IsEqualTo("User 7"); p.User8.Name.IsEqualTo("User 8"); p.User9.Name.IsEqualTo("User 9"); } finally { connection.Execute("drop table #Users drop table #ReviewBoards"); } } [Fact] public async Task Issue157_ClosedReaderAsync() { var args = new { x = 42 }; const string sql = @"select 123 as [A], 'abc' as [B] where @x=42"; var row = (await connection.QueryAsync<SomeType>(new CommandDefinition( sql, args, flags:CommandFlags.None))).Single(); row.IsNotNull(); row.A.IsEqualTo(123); row.B.IsEqualTo("abc"); args = new { x = 5 }; (await connection.QueryAsync<SomeType>(new CommandDefinition( sql, args, flags: CommandFlags.None))).Any().IsFalse(); } [Fact] public async Task TestAtEscaping() { var id = (await connection.QueryAsync<int>(@" declare @@Name int select @@Name = @Id+1 select @@Name ", new Product { Id = 1 })).Single(); id.IsEqualTo(2); } [Fact] public async Task Issue1281_DataReaderOutOfOrderAsync() { using (var reader = await connection.ExecuteReaderAsync("Select 0, 1, 2")) { reader.Read().IsTrue(); reader.GetInt32(2).IsEqualTo(2); reader.GetInt32(0).IsEqualTo(0); reader.GetInt32(1).IsEqualTo(1); reader.Read().IsFalse(); } } } } #endif
40.48262
187
0.530233
[ "Apache-2.0" ]
abcba/dapper-dot-net
Dapper.Tests/Tests.Async.cs
30,283
C#
using DeveloperFramework.LibraryModel.CQP; using DeveloperFramework.Log.CQP; using DeveloperFramework.Simulator.CQP.Domain.Context; using DeveloperFramework.Simulator.CQP.Domain.Expositor; using DeveloperFramework.SimulatorModel.CQP; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DeveloperFramework.Simulator.CQP.Domain.Expression { /// <summary> /// 发送群消息的任务表达式 /// </summary> public class GroupMessageExpression : TaskExpression { /// <summary> /// 初始化 <see cref="GroupMessageExpression"/> 类的新实例 /// </summary> /// <param name="simulator">任务表达式关联的模拟器</param> public GroupMessageExpression (CQPSimulator simulator) : base (simulator) { } public override bool Interpret (TaskContext context) { if (context is GroupMessageTaskContext groupContext) { GroupMessageType subType = groupContext.SubType; Message msg = groupContext.Message; Group fromGroup = groupContext.FromGroup; QQ fromQQ = groupContext.FromQQ; GroupAnonymous fromAnonymous = groupContext.FromAnonymous; IntPtr font = groupContext.Font; // 存入消息列表 this.Simulator.DataPool.MessageCollection.Add (msg); // 调用app this.Simulator.PushGroupMessage (subType, msg.Id, fromGroup, fromQQ, fromAnonymous == null ? string.Empty : fromAnonymous.ToBase64String (), msg, font); } return false; } } }
28.3
156
0.74841
[ "Apache-2.0" ]
Jie2GG/DeveloperFramework
src/DeveloperFramework.Simulator.CQP/Domain/Expression/GroupMessageExpression.cs
1,493
C#
using System.Collections.Generic; namespace HelpFileMarkdownBuilder.CSharp.Members { /// <summary> /// Collection of properties /// </summary> public class CSPropertyCollection : CSMemberCollection<CSProperty> { /// <summary> /// Multiple member type name /// </summary> public override string MultipleMemberTypeName => "Properties"; /// <summary> /// Empty constructor /// </summary> public CSPropertyCollection() : base() { } /// <summary> /// Constructor with list initializer /// </summary> /// <param name="members">Members</param> public CSPropertyCollection(IEnumerable<CSProperty> members) : base(members) { } } }
27.925926
88
0.602122
[ "MIT" ]
BastienPerdriau/HelpFileMarkdownBuilder
Sources/HelpFileMarkdownBuilder.CSharp.Members/Collections/CSPropertyCollection.cs
756
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Windows.Forms; using GLib.AXLib.Utility; using GLib.GeneralModel; using SLW.ClientBase.Codec; using SLW.ClientBase.Media; using SLW.Media; namespace SLW.ClientBase.Media { public class MediaPlayer : IDisposable { private WaveAudioPlayer _ap; private VideoPlayer _vp; private bool _isworking = false; private Thread _playThread = null; private bool _IsAudioPlay = true; private bool _IsVideoPlay = true; private long _lastReceiveFrameTick = 0; private long _startPlayTick = 0;//开始播放的系统时间 private long _lastPausedTick = 0; private bool _isPaused = false; private bool _IgnoreVideoPlay = false; private AQueue<MediaFrame> _queue = new AQueue<MediaFrame>(); private List<MediaFrame> _cache = new List<MediaFrame>(); //是否为实时播放 public bool IsReadPlay { get; set; } //是否播放音频 public bool IsAudioPlay { get { return _IsAudioPlay; } set { _IsAudioPlay = value; } } //是否播放视频 public bool IsVideoPlay { get { return _IsVideoPlay; } set { _IsVideoPlay = value; } } //是否正在播放中 public bool IsPlaying { get { return _vp != null && _vp.IsPlaying; } } //缓冲播放时长,该值暂时只在第一次播放进行缓冲 public int BuffTime { get; set; } //当前播放缓冲区是否为空 public Boolean BufferEmpty { get { return _ap.BufferEmpty && _vp.BufferEmpty; } } //当前播放位置,对应当前音频或视频的最后一个播放帧的时间戳 public long Position { get { if (_ap.Position > _vp.Position) return _ap.Position; else return _vp.Position; } set { lock (_queue) { if (IsReadPlay) { var curPos = Position; _ap.ResetPosition(); _vp.ResetPosition(); _queue.Clear(); _firstVideoFrameTime = 0; _firstAudioFrameTime = 0; _firstFrameTime = 0; _startPlayTick = 0; } else { var curPos = Position; if (curPos > value) { _ap.ResetPosition(); _vp.ResetPosition(); _queue.Clear(); _firstVideoFrameTime = 0; _firstAudioFrameTime = 0; _firstFrameTime = 0; _startPlayTick = 0; bool _videoIFrameAdded = false; foreach (var item in _cache) { if (item.nTimetick >= value) { if (_videoIFrameAdded || (item.nIsKeyFrame == 1 && item.nIsAudio == 0)) { _queue.Enqueue(item); _videoIFrameAdded = true; } } } } else { _ap.ResetPosition(); _vp.ResetPosition(); _queue.Clear(); _firstVideoFrameTime = 0; _firstAudioFrameTime = 0; _firstFrameTime = 0; _startPlayTick = 0; bool _videoIFrameAdded = false; foreach (var item in _cache) { if (item.nTimetick >= value) { if (_videoIFrameAdded || (item.nIsKeyFrame == 1 && item.nIsAudio == 0)) { _queue.Enqueue(item); _videoIFrameAdded = true; } } } } } } var tick = Environment.TickCount; while (Environment.TickCount - tick < 1000 && _vp.Position == 0) ThreadEx.Sleep(10); } } public long VideoPosition { get { return _vp.Position; } } private float _speed = 1f; //播放速度,1为正常播放,该值处理不正确,暂不要使用 public float Speed { get { return _speed; } set { _speed = value; _ap.Speed = value; _vp.Speed = value; ; } } //最大播放时长 public long Length { get { return _lastReceiveFrameTick; } } //向前播放 public bool ForwardPlay { get { return _vp.ForwardPlay; } set { _vp.ForwardPlay = value; } } public int Volume { get { return _ap.Volume; } set { _ap.Volume = value; } } //异常事件 public event EventHandler<EventArgsEx<Exception>> Error; public MediaPlayer(IYUVDraw yuvDraw, bool isRealPlay = true,bool isCachePlay=false) { //if (System.Configuration.ConfigurationSettings.AppSettings["AudioPlayMode"] == "SDL") // _ap = new SDLAudioPlayer(); //else _ap = new WaveAudioPlayer(); _vp = new VideoPlayer(yuvDraw); IsReadPlay = isRealPlay; BuffTime = 0; if (isCachePlay) _IgnoreVideoPlay = true; } bool hasKey = false; public void Play(MediaFrame frame) { if (!_isworking) return; lock (_queue) { if (_lastReceiveFrameTick < frame.nTimetick) _lastReceiveFrameTick = frame.nTimetick; if (frame.nIsAudio == 1 && IsAudioPlay) _queue.Enqueue(frame); if (frame.nIsAudio == 0 && IsVideoPlay) { if (hasKey||frame.nIsKeyFrame==1) { _queue.Enqueue(frame); hasKey = true; } } if (!IsReadPlay) _cache.Add(frame); } } public void Start() { if (_isworking) return; _isworking = true; _firstVideoFrameTime = 0; _firstAudioFrameTime = 0; _firstFrameTime = 0; _startPlayTick = 0; _queue.Clear(); _cache.Clear(); _vp.Start(); _ap.Start(); _playThread = ThreadEx.ThreadCall(PlayThread); } public void Stop() { if (!_isworking) return; _isworking = false; _vp.Stop(); _ap.Stop(); ThreadEx.ThreadStop(_playThread); _queue = new AQueue<MediaFrame>(); _cache = new List<MediaFrame>(); } public void Pause() { if (_isPaused) return; _isPaused = true; _lastPausedTick = Environment.TickCount; _vp.Pause(); _ap.Pause(); } public void Continue() { if (!_isPaused) return; _isPaused = false; _startPlayTick += (Environment.TickCount - _lastPausedTick); _vp.Continue(); _ap.Continue(); } private long _firstVideoFrameTime = 0; private long _firstAudioFrameTime = 0; private long _firstFrameTime = 0; private void PlayThread() { bool _needBuffer = BuffTime > 0; bool _needSleep = false; while (_isworking) { lock (_queue) { if (_queue.Count > 0 && !_needBuffer && !_isPaused) { var frame = _queue.Dequeue(); if (_firstFrameTime == 0) _firstFrameTime = frame.nTimetick; if (_startPlayTick == 0) _startPlayTick = Environment.TickCount; if (frame.nIsAudio == 0) { if (_firstVideoFrameTime == 0) _firstVideoFrameTime = frame.nTimetick; } else if (frame.nIsAudio == 1 && (_vp.IsPlaying || _IgnoreVideoPlay) && ForwardPlay) { if (_firstAudioFrameTime == 0) _firstAudioFrameTime = frame.nTimetick; } if (_firstVideoFrameTime != 0) _vp.SyncPlayTime(_firstVideoFrameTime + (int)((Environment.TickCount - _startPlayTick) * 1)); if (_firstAudioFrameTime != 0) _ap.SyncPlayTime(_firstAudioFrameTime + (int)((Environment.TickCount - _startPlayTick) * 1)); if (frame.nIsAudio == 0) { _vp.Play(frame); } else if (frame.nIsAudio == 1 && (_vp.IsPlaying || _IgnoreVideoPlay) && ForwardPlay) { _ap.Play(frame); } _needSleep = false; } else { if (!_isPaused) { if (_firstVideoFrameTime != 0) _vp.SyncPlayTime(_firstVideoFrameTime + (int)((Environment.TickCount - _startPlayTick) * 1)); if (_firstAudioFrameTime != 0) _ap.SyncPlayTime(_firstAudioFrameTime + (int)((Environment.TickCount - _startPlayTick) * 1)); if (_queue.Count > 0 && _needBuffer) { var mf = _queue.Peek(); if (_lastReceiveFrameTick - mf.nTimetick > BuffTime * 1000) { _needBuffer = false; } } } _needSleep = true; } } if (_needSleep) Thread.Sleep(10); } } protected void OnError(Exception e) { if (Error != null) Error(this, new EventArgsEx<Exception>(e)); } public void Dispose() { Stop(); if (_ap != null) _ap.Dispose(); if (_vp != null) _vp.Dispose(); } } }
37.255245
125
0.445706
[ "BSD-2-Clause" ]
7956968/gb28181-sip
GB28181.Client/Player/Media/MediaPlayer.cs
10,923
C#
using Jcl.FileBrowser.Services.MimeTypes; using Jcl.FileBrowser.Services.RelativePath; using Microsoft.Extensions.Options; namespace Jcl.FileBrowser.Services.FileIcons; public class FileIconManager : IFileIconManager { private readonly IMimeTypeMapper _mimeTypeMapper; private readonly IImageAllowedMimeTypes _imageAllowedMimeTypes; private readonly IRelativePathManager _relativePathManager; private readonly IOptions<GlobalOptions> _options; public FileIconManager(IMimeTypeMapper mimeTypeMapper, IImageAllowedMimeTypes imageAllowedMimeTypes, IRelativePathManager relativePathManager, IOptions<GlobalOptions> options) { _mimeTypeMapper = mimeTypeMapper; _imageAllowedMimeTypes = imageAllowedMimeTypes; _relativePathManager = relativePathManager; _options = options; } private string BuildIconPath(string? icon) { var relativeFolder = "img/icons/vivid/"; if (icon is null) return "/" + relativeFolder + "blank.svg"; var folder = _relativePathManager.GetWebrootPath(relativeFolder); return "/" + relativeFolder + (File.Exists(Path.Combine(folder, icon.ToLower() + ".svg")) ? icon.ToLower() : "blank") + ".svg"; } private string GetIconUrlForExtension(string? extension) { if (extension is not null && extension.StartsWith(".")) extension = extension[1..]; return BuildIconPath(extension); } public string GetFileIconUrl(string filePath) { var fi = new FileInfo(filePath); var mimeType = _mimeTypeMapper.Map(fi.Name); string iconUrl; if (_imageAllowedMimeTypes.IsMimeTypeAllowed(mimeType)) { iconUrl = _options.Value.BuildPathWithBaseBrowsingPath(_relativePathManager.GetRelativePath(fi.FullName) + "?thumbnail&w=32&h=32"); } else { iconUrl = GetIconUrlForExtension(fi.Extension); } return iconUrl; } }
36.571429
118
0.675293
[ "MIT" ]
javiercampos/files.javiercampos.info
src/Jcl.FileBrowser/Services/FileIcons/FileIconManager.cs
2,050
C#
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections; using System.Collections.Generic; using System.Runtime.CompilerServices; using Microsoft.Extensions.Primitives; namespace Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http { internal partial class HttpResponseTrailers : HttpHeaders { public Enumerator GetEnumerator() { return new Enumerator(this); } protected override IEnumerator<KeyValuePair<string, StringValues>> GetEnumeratorFast() { return GetEnumerator(); } [MethodImpl(MethodImplOptions.NoInlining)] private void SetValueUnknown(string key, StringValues value) { ValidateHeaderNameCharacters(key); Unknown[key] = value; } [MethodImpl(MethodImplOptions.NoInlining)] private bool AddValueUnknown(string key, StringValues value) { ValidateHeaderNameCharacters(key); Unknown.Add(key, value); // Return true, above will throw and exit for false return true; } public partial struct Enumerator : IEnumerator<KeyValuePair<string, StringValues>> { private readonly HttpResponseTrailers _collection; private readonly long _bits; private int _next; private KeyValuePair<string, StringValues> _current; private KnownHeaderType _currentKnownType; private readonly bool _hasUnknown; private Dictionary<string, StringValues>.Enumerator _unknownEnumerator; internal Enumerator(HttpResponseTrailers collection) { _collection = collection; _bits = collection._bits; _next = 0; _current = default; _currentKnownType = default; _hasUnknown = collection.MaybeUnknown != null; _unknownEnumerator = _hasUnknown ? collection.MaybeUnknown!.GetEnumerator() : default; } public KeyValuePair<string, StringValues> Current => _current; internal KnownHeaderType CurrentKnownType => _currentKnownType; object IEnumerator.Current => _current; public void Dispose() { } public void Reset() { _next = 0; } } } }
32.525
111
0.609147
[ "Apache-2.0" ]
1kevgriff/aspnetcore
src/Servers/Kestrel/Core/src/Internal/Http/HttpResponseTrailers.cs
2,602
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using NUnit.Framework; using CprBroker.Data.DataProviders; using CprBroker.Engine; namespace CprBroker.Tests.Engine { namespace DataProviderFactoryTests { [TestFixture] public class CreateDataProvider : Base { [Test] [ExpectedException] public void CreateDataProvider_Null_ThrowsException() { new DataProviderFactory().CreateDataProvider(null); } [Test] public void CreateDataProvider_FakeType_ReturnsNull() { var result = new DataProviderFactory().CreateDataProvider(new DataProvider() { TypeName = "kaaklsdflksah" }); Assert.Null(result); } [Test] public void CreateDataProvider_RealInvalidType_ReturnsNull( [Values(typeof(object), typeof(LocalDataProviderStub))]Type type) { var result = new DataProviderFactory().CreateDataProvider(new DataProvider() { TypeName = type.AssemblyQualifiedName }); Assert.Null(result); } [Test] public void CreateDataProvider_RealCorrectType_ReturnsNotNull( [Values(typeof(CustomExternalDataProviderStub))]Type type) { var result = new DataProviderFactory().CreateDataProvider(new DataProvider() { TypeName = type.AssemblyQualifiedName }); Assert.NotNull(result); } [Test] public void CreateDataProvider_NewProperty_NoException() { var dbProvider = new CprBroker.Data.DataProviders.DataProvider() { TypeName = typeof(DataProviderWithNewConfigProperty).AssemblyQualifiedName }; var createdProvider = new DataProviderFactory().CreateDataProvider(dbProvider) as DataProviderWithNewConfigProperty; createdProvider.PropertyType = DataProviderConfigPropertyInfoTypes.Boolean; var result = createdProvider.BooleanPropertyValue; } } public class DataProviderWithNewConfigProperty : IExternalDataProvider { public Dictionary<string, string> ConfigurationProperties { get; set; } public DataProviderConfigPropertyInfo[] ConfigurationKeys { get { return new DataProviderConfigPropertyInfo[] { new DataProviderConfigPropertyInfo() { Confidential = false, Name = PropertyName, Required = false, Type = PropertyType } }; } } public bool IsAlive() { return true; } public Version Version { get { return new Version(); } } public DataProviderConfigPropertyInfoTypes PropertyType; public string PropertyName = Guid.NewGuid().ToString(); private Dictionary<string, string> _ConfigurationProperties = null; public bool BooleanPropertyValue { get { return Convert.ToBoolean(ConfigurationProperties[PropertyName]); } } } } }
34.824742
190
0.58733
[ "MPL-2.0", "MPL-2.0-no-copyleft-exception" ]
OS2CPRbroker/CPRbroker
PART/Source/Core/Engine.Tests/DataProviderFactoryTests.CreateDataProvider.Tests.cs
3,380
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 Gif2Spritesheet.Properties { using System; /// <summary> /// A strongly-typed resource class, for looking up localized strings, etc. /// </summary> // This class was auto-generated by the StronglyTypedResourceBuilder // class via a tool like ResGen or Visual Studio. // To add or remove a member, edit your .ResX file then rerun ResGen // with the /str option, or rebuild your VS project. [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] internal class Resources { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal Resources() { } /// <summary> /// Returns the cached ResourceManager instance used by this class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Resources.ResourceManager ResourceManager { get { if (object.ReferenceEquals(resourceMan, null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Gif2Spritesheet.Properties.Resources", typeof(Resources).Assembly); resourceMan = temp; } return resourceMan; } } /// <summary> /// Overrides the current thread's CurrentUICulture property for all /// resource lookups using this strongly typed resource class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } } }
43.640625
181
0.614393
[ "MIT" ]
PokemonUnity/GifToSpritesheet
Gif2Spritesheet/Gif2Spritesheet/Properties/Resources.Designer.cs
2,795
C#
using LinqKit; using System; using System.Linq.Expressions; namespace NooBIT.Model.Helpers { public static class PredicateHelper { public static ExpressionStarter<TEntity> ConditionalAnd<TEntity>(this ExpressionStarter<TEntity> starter, Expression<Func<TEntity, bool>> expression, Func<bool> condition) => condition() ? (ExpressionStarter<TEntity>)starter.And(expression) : starter; public static ExpressionStarter<TEntity> ConditionalOr<TEntity>(this ExpressionStarter<TEntity> starter, Expression<Func<TEntity, bool>> expression, Func<bool> condition) => condition() ? (ExpressionStarter<TEntity>)starter.Or(expression) : starter; } }
46.2
180
0.741703
[ "MIT" ]
cmxl/NooBIT.Model
src/NooBIT.Model.EntityFrameworkCore/Helpers/PredicateHelper.cs
695
C#
#region license // Copyright (c) HatTrick Labs, LLC. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // The latest version of this file can be found at https://github.com/HatTrickLabs/db-ex #endregion using HatTrick.DbEx.Sql.Converter; using System; namespace HatTrick.DbEx.Sql.Executor { public class OutputParameter : ISqlOutputParameter { #region internals protected Func<ISqlOutputParameter, Type, IValueConverter> FindValueConverter { get; private set; } #endregion #region interface public int Index { get; private set; } public string Name { get; private set; } public Type DataType { get; private set; } public object RawValue { get; private set; } #endregion #region constructors public OutputParameter(int index, string name, Type dataType, object value, Func<ISqlOutputParameter, Type, IValueConverter> findValueConverter) { Index = index; Name = name; DataType = dataType; RawValue = value; FindValueConverter = findValueConverter ?? throw new ArgumentNullException(nameof(findValueConverter)); } #endregion #region methods public T GetValue<T>() => FindValueConverter(this, typeof(T)).ConvertFromDatabase<T>(RawValue is DBNull ? null : RawValue); public object GetValue() => FindValueConverter(this, typeof(object)).ConvertFromDatabase(RawValue is DBNull ? null : RawValue); #endregion } }
36.508772
152
0.680442
[ "Apache-2.0" ]
HatTrickLabs/dbExpression
src/HatTrick.DbEx.Sql/Executor/OutputParameter.cs
2,083
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Xrm.Tools.WebAPI.Results { public class CRMBatchResultItem { public Guid EntityID{ get; set; } } }
17.642857
41
0.720648
[ "MIT" ]
EkoZuluDev/Xrm.Tools.CRMWebAPI
dotnet/Xrm.Tools.WebAPI/Results/CRMMultipleOperationResultItem.cs
249
C#
using System.Runtime.CompilerServices; [assembly: InternalsVisibleTo("HotChocolate.Abstractions")] [assembly: InternalsVisibleTo("HotChocolate.Language")] [assembly: InternalsVisibleTo("HotChocolate.Core")] [assembly: InternalsVisibleTo("HotChocolate.Types")] [assembly: InternalsVisibleTo("HotChocolate.Stitching")] [assembly: InternalsVisibleTo("HotChocolate.Utilities.Tests")]
42.444444
62
0.82199
[ "MIT" ]
Coldplayer1995/GraphQLTest
src/Core/Utilities/InternalsVisibleTo.cs
384
C#
using System; using System.Collections; namespace DXFLibrary { /// <summary> /// The representation of a DXF SECTION /// </summary> public class Section : Element { public Section(string s) : base() { startTag = new Data(0,"SECTION"); endTag = new Data(0,"ENDSEC"); data = new ArrayList(); elements = new ArrayList(); data.Add(new Data(2,s)); } public Section(string s, bool userDxfCode):base(s) { } } }
16.923077
52
0.636364
[ "MIT" ]
Titifonky/DXFLibrary
Section.cs
440
C#
namespace BuildingDrainageConsultant.Data.Models.Enums.Attica { using System.ComponentModel.DataAnnotations; public enum AtticaWalkableEnum { Walkable = 1, [Display(Name = "Not Walkable")] NotWalkable = 2 } }
20.916667
62
0.665339
[ "MIT" ]
AlShandor/ASP.NET-Core-Project-Building-Drainage-Consultant
BuildingDrainageConsultant/Data/Models/Enums/Attica/AtticaWalkableEnum.cs
253
C#
namespace Starnight.Internal.Entities.Channels; /// <summary> /// Represents flag added to a <see cref="DiscordChannel"/>. /// </summary> public enum DiscordChannelFlags { /// <summary> /// Indicates that this thread channel is pinned to the top of its parent forum channel. /// </summary> Pinned = 1 << 1 }
24.076923
89
0.699681
[ "MIT" ]
StarnightLibrary/starnight
Starnight/Internal/Entities/Channels/DiscordChannelFlags.cs
313
C#
// <auto-generated /> using System; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Migrations; using Microsoft.EntityFrameworkCore.Storage.ValueConversion; using Stenn.EntityFrameworkCore.Data.Main; namespace Stenn.EntityFrameworkCore.DbContext.Initial.Migrations { [DbContext(typeof(MainDbContext_Step2))] [Migration("20220329215435_AddCurrencyType")] partial class AddCurrencyType { protected override void BuildTargetModel(ModelBuilder modelBuilder) { #pragma warning disable 612, 618 modelBuilder .HasAnnotation("Relational:MaxIdentifierLength", 128) .HasAnnotation("ProductVersion", "5.0.15") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); modelBuilder.Entity("Stenn.EntityFrameworkCore.Data.Main.Contact", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("EMail") .HasColumnType("nvarchar(max)"); b.Property<string>("Name") .IsRequired() .HasColumnType("nvarchar(max)"); b.Property<byte>("Type") .HasColumnType("tinyint"); b.Property<string>("TypeName") .IsRequired() .HasMaxLength(100) .HasColumnType("nvarchar(100)"); b.Property<string>("TypeName2") .IsRequired() .HasMaxLength(100) .HasColumnType("nvarchar(100)"); b.HasKey("Id"); b.ToTable("Contact"); }); modelBuilder.Entity("Stenn.EntityFrameworkCore.Data.Main.Currency", b => { b.Property<string>("Iso3LetterCode") .HasMaxLength(3) .IsUnicode(false) .HasColumnType("char(3)") .IsFixedLength(true); b.Property<byte>("DecimalDigits") .HasColumnType("tinyint"); b.Property<string>("Description") .HasMaxLength(150) .IsUnicode(true) .HasColumnType("nvarchar(150)"); b.Property<int>("IsoNumericCode") .HasColumnType("int"); b.Property<int>("Type") .HasColumnType("int"); b.HasKey("Iso3LetterCode"); b.ToTable("Currency"); }); modelBuilder.Entity("Stenn.EntityFrameworkCore.Data.Main.Role", b => { b.Property<Guid>("Id") .HasColumnType("uniqueidentifier"); b.Property<DateTime>("Created") .ValueGeneratedOnAdd() .HasColumnType("datetime2") .HasDefaultValueSql("getdate()") .HasComment("Row creation datetime. Configured by convention 'ICreateAuditedEntity'"); b.Property<DateTime?>("Deleted") .HasColumnType("datetime2") .HasComment("Row deleted datetime. Used for soft delete row. Updated by 'instead of' trigger. Configured by convention 'ISoftDeleteEntity'"); b.Property<string>("Description") .HasColumnType("nvarchar(max)"); b.Property<bool>("IsDeleted") .ValueGeneratedOnAdd() .HasColumnType("bit") .HasDefaultValue(false) .HasComment("Row deleted flag. Used for soft delete row. Updated by 'instead of' trigger. Configured by convention 'ISoftDeleteEntity'"); b.Property<DateTime>("ModifiedAt") .ValueGeneratedOnAddOrUpdate() .HasColumnType("datetime2") .HasDefaultValueSql("getdate()") .HasComment("Row last modified datetime. Updated by trigger. Configured by convention 'IUpdateAuditedEntity'") .HasAnnotation("ColumnTriggerUpdate", "getdate()"); b.Property<string>("Name") .IsRequired() .HasColumnType("nvarchar(max)"); b.Property<string>("SourceSystemId") .IsRequired() .HasMaxLength(100) .IsUnicode(false) .HasColumnType("varchar(100)") .HasComment("Source system id. Row id for cross services' communication. Uses trigger on row insertion. Configured by convention 'IEntityWithSourceSystemId'"); b.HasKey("Id"); b.HasIndex("IsDeleted"); b.ToTable("Role"); b .HasAnnotation("ColumnTriggerSoftDelete", true); }); #pragma warning restore 612, 618 } } }
40.608696
183
0.509458
[ "MIT" ]
StennGroup/stenn-entityframework-core
src/Stenn.EntityFrameworkCore.Data.Main.MigrationsV2/Migrations/20220329215435_AddCurrencyType.Designer.cs
5,606
C#
using System; namespace RafaelEstevam.Simple.Spider.Interfaces { /// <summary> /// Represents a module to fetch resources from the disk/memory /// </summary> public interface ICacher : IFetcher { /// <summary> /// Occurs before fetch to check if the cache can be used /// </summary> event ShouldUseCache ShouldUseCache; /// <summary> /// Returns if this module has a cache for this resource /// </summary> /// <param name="link">Resource the be checked for</param> /// <returns>True if has a cache for the resource</returns> bool HasCache(Link link); /// <summary> /// Create cache for this fetched resource /// </summary> /// <param name="FetchComplete">The fetched resource to create a cache for</param> void GenerateCacheFor(FetchCompleteEventArgs FetchComplete); } }
32.785714
90
0.614379
[ "MIT" ]
RafaelEstevamReis/SimpleSpider
Simple.Lib/Interfaces/ICacher.cs
920
C#
using ngBook.Server.Models; using System.Data.Entity; namespace ngBook.Server.Data { public class BookContext : System.Data.Entity.DbContext { public BookContext() : base(nameOrConnectionString: "ngBook") { Configuration.ProxyCreationEnabled = false; Configuration.LazyLoadingEnabled = false; Configuration.AutoDetectChangesEnabled = true; } public DbSet<User> Users { get; set; } public DbSet<Role> Roles { get; set; } public DbSet<Book> Books { get; set; } public DbSet<Account> Accounts { get; set; } public DbSet<Profile> Profiles { get; set; } public DbSet<Collection> Collections { get; set; } public DbSet<FavoriteList> FavoriteLists { get; set; } } }
32.08
62
0.625935
[ "MIT" ]
QuinntyneBrown/ngBook
ngBook/Server/Data/BookContext.cs
804
C#
//This is modified from KerasSharp repo for use of Unity., by Xiaoxiao Ma, Aalto University, // // Keras-Sharp: C# port of the Keras library // https://github.com/cesarsouza/keras-sharp // // Based under the Keras library for Python. See LICENSE text for more details. // // The MIT License(MIT) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // namespace KerasSharp.Losses { using KerasSharp.Engine.Topology; using System.Runtime.Serialization; [DataContract] public class SparseCategoricalCrossEntropy : ILoss { public SparseCategoricalCrossEntropy() { } public Tensor Call(Tensor expected, Tensor actual, Tensor sample_weight = null, Tensor mask = null) { throw new System.NotImplementedException(); } } }
40.978261
107
0.708223
[ "MIT" ]
tcmxx/keras-sharp
Sources/Losses/SparseCategoricalCrossEntropy.cs
1,887
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // Allgemeine Informationen über eine Assembly werden über die folgenden // Attribute gesteuert. Ändern Sie diese Attributwerte, um die Informationen zu ändern, // die einer Assembly zugeordnet sind. [assembly: AssemblyTitle("SharpLibSteamDeck")] [assembly: AssemblyDescription("A simple .NET wrapper for Stream Deck")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("SharpLibSteamDeck")] [assembly: AssemblyCopyright("Copyright © 2018")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Durch Festlegen von ComVisible auf FALSE werden die Typen in dieser Assembly // für COM-Komponenten unsichtbar. Wenn Sie auf einen Typ in dieser Assembly von // COM aus zugreifen müssen, sollten Sie das ComVisible-Attribut für diesen Typ auf "True" festlegen. [assembly: ComVisible(false)] // Die folgende GUID bestimmt die ID der Typbibliothek, wenn dieses Projekt für COM verfügbar gemacht wird [assembly: Guid("d06ab787-766e-4b28-89c4-8d948070eb1c")] // Versionsinformationen für eine Assembly bestehen aus den folgenden vier Werten: // // Hauptversion // Nebenversion // Buildnummer // Revision // // Sie können alle Werte angeben oder Standardwerte für die Build- und Revisionsnummern verwenden, // indem Sie "*" wie unten gezeigt eingeben: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("0.0.4")]
40.894737
106
0.767053
[ "MIT" ]
Slion/SharpLibStreamDeck
Project/Library/Properties/AssemblyInfo.cs
1,569
C#
#region Copyright //////////////////////////////////////////////////////////////////////////////// // The following FIT Protocol software provided may be used with FIT protocol // devices only and remains the copyrighted property of Garmin Canada Inc. // The software is being provided on an "as-is" basis and as an accommodation, // and therefore all warranties, representations, or guarantees of any kind // (whether express, implied or statutory) including, without limitation, // warranties of merchantability, non-infringement, or fitness for a particular // purpose, are specifically disclaimed. // // Copyright 2020 Garmin Canada Inc. //////////////////////////////////////////////////////////////////////////////// // ****WARNING**** This file is auto-generated! Do NOT edit this file. // Profile Version = 21.30Release // Tag = production/akw/21.30.00-0-g324900c //////////////////////////////////////////////////////////////////////////////// #endregion using System; using System.Collections.Generic; using System.Diagnostics; using System.Text; using System.IO; using System.Linq; namespace Dynastream.Fit { /// <summary> /// Implements the VideoTitle profile message. /// </summary> public class VideoTitleMesg : Mesg { #region Fields #endregion /// <summary> /// Field Numbers for <see cref="VideoTitleMesg"/> /// </summary> public sealed class FieldDefNum { public const byte MessageIndex = 254; public const byte MessageCount = 0; public const byte Text = 1; public const byte Invalid = Fit.FieldNumInvalid; } #region Constructors public VideoTitleMesg() : base(Profile.GetMesg(MesgNum.VideoTitle)) { } public VideoTitleMesg(Mesg mesg) : base(mesg) { } #endregion // Constructors #region Methods ///<summary> /// Retrieves the MessageIndex field /// Comment: Long titles will be split into multiple parts</summary> /// <returns>Returns nullable ushort representing the MessageIndex field</returns> public ushort? GetMessageIndex() { Object val = GetFieldValue(254, 0, Fit.SubfieldIndexMainField); if(val == null) { return null; } return (Convert.ToUInt16(val)); } /// <summary> /// Set MessageIndex field /// Comment: Long titles will be split into multiple parts</summary> /// <param name="messageIndex_">Nullable field value to be set</param> public void SetMessageIndex(ushort? messageIndex_) { SetFieldValue(254, 0, messageIndex_, Fit.SubfieldIndexMainField); } ///<summary> /// Retrieves the MessageCount field /// Comment: Total number of title parts</summary> /// <returns>Returns nullable ushort representing the MessageCount field</returns> public ushort? GetMessageCount() { Object val = GetFieldValue(0, 0, Fit.SubfieldIndexMainField); if(val == null) { return null; } return (Convert.ToUInt16(val)); } /// <summary> /// Set MessageCount field /// Comment: Total number of title parts</summary> /// <param name="messageCount_">Nullable field value to be set</param> public void SetMessageCount(ushort? messageCount_) { SetFieldValue(0, 0, messageCount_, Fit.SubfieldIndexMainField); } ///<summary> /// Retrieves the Text field</summary> /// <returns>Returns byte[] representing the Text field</returns> public byte[] GetText() { byte[] data = (byte[])GetFieldValue(1, 0, Fit.SubfieldIndexMainField); return data.Take(data.Length - 1).ToArray(); } ///<summary> /// Retrieves the Text field</summary> /// <returns>Returns String representing the Text field</returns> public String GetTextAsString() { byte[] data = (byte[])GetFieldValue(1, 0, Fit.SubfieldIndexMainField); return data != null ? Encoding.UTF8.GetString(data, 0, data.Length - 1) : null; } ///<summary> /// Set Text field</summary> /// <param name="text_"> field value to be set</param> public void SetText(String text_) { byte[] data = Encoding.UTF8.GetBytes(text_); byte[] zdata = new byte[data.Length + 1]; data.CopyTo(zdata, 0); SetFieldValue(1, 0, zdata, Fit.SubfieldIndexMainField); } /// <summary> /// Set Text field</summary> /// <param name="text_">field value to be set</param> public void SetText(byte[] text_) { SetFieldValue(1, 0, text_, Fit.SubfieldIndexMainField); } #endregion // Methods } // Class } // namespace
35.08
92
0.54675
[ "MIT" ]
epvanhouten/PowerToSpeed
PowerToSpeed/Dynastream/Fit/Profile/Mesgs/VideoTitleMesg.cs
5,262
C#
using System; namespace Frapid.WebsiteBuilder.Syndication.Rss { public class RssItem { public string Title { get; set; } public string Link { get; set; } public string Description { get; set; } /// <summary> /// The publication date for the content in the channel. /// </summary> public DateTimeOffset PublishDate { get; set; } /// <summary> /// The last time the content of the channel changed. /// </summary> public DateTimeOffset LastBuildDate { get; set; } /// <summary> /// Specify one or more categories that the channel belongs to. /// </summary> public string Category { get; set; } public int Ttl { get; set; } } }
30.6
71
0.575163
[ "MIT" ]
denza/frapid
src/Frapid.Web/Areas/Frapid.WebsiteBuilder/Syndication/Rss/RssItem.cs
765
C#
using System; using System.Linq; namespace Myvas.AspNetCore.TencentCos { internal static class UriExtensions { public static Uri Append(this Uri uri, params string[] paths) { return new Uri(paths.Aggregate(uri.AbsoluteUri, (current, path) => string.Format("{0}/{1}", current.TrimEnd('/'), path.TrimStart('/')))); } } }
26.357143
149
0.628726
[ "MIT" ]
myvas/AspNetCore.TencentCos
src/TencentCos/Extensions/UriExtensions.cs
371
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // 有关程序集的常规信息通过以下 // 特性集控制。更改这些特性值可修改 // 与程序集关联的信息。 [assembly: AssemblyTitle("Senparc.Weixin.Open")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Senparc.Weixin.Open")] [assembly: AssemblyCopyright("Copyright © 2018")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // 将 ComVisible 设置为 false 使此程序集中的类型 // 对 COM 组件不可见。 如果需要从 COM 访问此程序集中的类型, // 则将该类型上的 ComVisible 特性设置为 true。 [assembly: ComVisible(false)] // 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID [assembly: Guid("7377ea9b-71b0-43a5-a030-c4a6bcb8f088")] // 程序集的版本信息由下面四个值组成: // // 主版本 // 次版本 // 生成号 // 修订号 // // 可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值, // 方法是按如下所示使用“*”: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("4.1.11.*")] //[assembly: AssemblyFileVersion("1.0.0.0")]
26.135135
56
0.712513
[ "Apache-2.0" ]
ImQdf/WeiXinMPSDK
src/Senparc.Weixin.Open/Senparc.Weixin.Open/Properties/AssemblyInfo.cs
1,326
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.Batch.V20181201.Inputs { /// <summary> /// Identifies the Azure key vault associated with a Batch account. /// </summary> public sealed class KeyVaultReferenceArgs : Pulumi.ResourceArgs { /// <summary> /// The resource ID of the Azure key vault associated with the Batch account. /// </summary> [Input("id", required: true)] public Input<string> Id { get; set; } = null!; /// <summary> /// The URL of the Azure key vault associated with the Batch account. /// </summary> [Input("url", required: true)] public Input<string> Url { get; set; } = null!; public KeyVaultReferenceArgs() { } } }
29.942857
85
0.629771
[ "Apache-2.0" ]
polivbr/pulumi-azure-native
sdk/dotnet/Batch/V20181201/Inputs/KeyVaultReferenceArgs.cs
1,048
C#
using SelfLoad.Business; namespace SelfLoad.Business.ERLevel { public partial class C09Level11111Child { #region Pseudo Event Handlers //partial void OnCreate(DataPortalHookArgs args) //{ // throw new System.Exception("The method or operation is not implemented."); //} //partial void OnDeletePre(DataPortalHookArgs args) //{ // throw new System.Exception("The method or operation is not implemented."); //} //partial void OnDeletePost(DataPortalHookArgs args) //{ // throw new System.Exception("The method or operation is not implemented."); //} //partial void OnFetchPre(DataPortalHookArgs args) //{ // throw new System.Exception("The method or operation is not implemented."); //} //partial void OnFetchPost(DataPortalHookArgs args) //{ // throw new System.Exception("The method or operation is not implemented."); //} //partial void OnFetchRead(DataPortalHookArgs args) //{ // throw new System.Exception("The method or operation is not implemented."); //} //partial void OnUpdatePre(DataPortalHookArgs args) //{ // throw new System.Exception("The method or operation is not implemented."); //} //partial void OnUpdatePost(DataPortalHookArgs args) //{ // throw new System.Exception("The method or operation is not implemented."); //} //partial void OnInsertPre(DataPortalHookArgs args) //{ // throw new System.Exception("The method or operation is not implemented."); //} //partial void OnInsertPost(DataPortalHookArgs args) //{ // throw new System.Exception("The method or operation is not implemented."); //} #endregion } }
31
89
0.580645
[ "MIT" ]
CslaGenFork/CslaGenFork
tags/DeepLoad sample v.1.0.0/SelfLoad.Business/ERLevel/C09Level11111Child.cs
1,984
C#
namespace Essensoft.AspNetCore.Payment.Alipay.Parser { public class SignItem { public string SignSourceData { get; set; } public string Sign { get; set; } } }
18.9
53
0.634921
[ "MIT" ]
LuohuaRain/payment
src/Essensoft.AspNetCore.Payment.Alipay/Parser/SignItem.cs
191
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 mediastore-2017-09-01.normal.json service model. */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Text; using System.Xml.Serialization; using Amazon.MediaStore.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; using ThirdParty.Json.LitJson; namespace Amazon.MediaStore.Model.Internal.MarshallTransformations { /// <summary> /// PutContainerPolicy Request Marshaller /// </summary> public class PutContainerPolicyRequestMarshaller : IMarshaller<IRequest, PutContainerPolicyRequest> , IMarshaller<IRequest,AmazonWebServiceRequest> { /// <summary> /// Marshaller the request object to the HTTP request. /// </summary> /// <param name="input"></param> /// <returns></returns> public IRequest Marshall(AmazonWebServiceRequest input) { return this.Marshall((PutContainerPolicyRequest)input); } /// <summary> /// Marshaller the request object to the HTTP request. /// </summary> /// <param name="publicRequest"></param> /// <returns></returns> public IRequest Marshall(PutContainerPolicyRequest publicRequest) { IRequest request = new DefaultRequest(publicRequest, "Amazon.MediaStore"); string target = "MediaStore_20170901.PutContainerPolicy"; request.Headers["X-Amz-Target"] = target; request.Headers["Content-Type"] = "application/x-amz-json-1.1"; request.Headers[Amazon.Util.HeaderKeys.XAmzApiVersion] = "2017-09-01"; request.HttpMethod = "POST"; request.ResourcePath = "/"; using (StringWriter stringWriter = new StringWriter(CultureInfo.InvariantCulture)) { JsonWriter writer = new JsonWriter(stringWriter); writer.WriteObjectStart(); var context = new JsonMarshallerContext(request, writer); if(publicRequest.IsSetContainerName()) { context.Writer.WritePropertyName("ContainerName"); context.Writer.Write(publicRequest.ContainerName); } if(publicRequest.IsSetPolicy()) { context.Writer.WritePropertyName("Policy"); context.Writer.Write(publicRequest.Policy); } writer.WriteObjectEnd(); string snippet = stringWriter.ToString(); request.Content = System.Text.Encoding.UTF8.GetBytes(snippet); } return request; } private static PutContainerPolicyRequestMarshaller _instance = new PutContainerPolicyRequestMarshaller(); internal static PutContainerPolicyRequestMarshaller GetInstance() { return _instance; } /// <summary> /// Gets the singleton. /// </summary> public static PutContainerPolicyRequestMarshaller Instance { get { return _instance; } } } }
35.5
151
0.625864
[ "Apache-2.0" ]
ChristopherButtars/aws-sdk-net
sdk/src/Services/MediaStore/Generated/Model/Internal/MarshallTransformations/PutContainerPolicyRequestMarshaller.cs
3,905
C#
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Security.Cryptography; using System.Security.Cryptography.X509Certificates; using Microsoft.AspNetCore.Certificates.Generation; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Server.Kestrel.Core; using Microsoft.AspNetCore.Server.Kestrel.Core.Internal; using Microsoft.AspNetCore.Server.Kestrel.Https; using Microsoft.AspNetCore.Server.Kestrel.Https.Internal; using Microsoft.AspNetCore.Server.Kestrel.Internal; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; namespace Microsoft.AspNetCore.Server.Kestrel { public class KestrelConfigurationLoader { private bool _loaded = false; internal KestrelConfigurationLoader(KestrelServerOptions options, IConfiguration configuration) { Options = options ?? throw new ArgumentNullException(nameof(options)); Configuration = configuration ?? throw new ArgumentNullException(nameof(configuration)); ConfigurationReader = new ConfigurationReader(Configuration); } public KestrelServerOptions Options { get; } public IConfiguration Configuration { get; } internal ConfigurationReader ConfigurationReader { get; } private IDictionary<string, Action<EndpointConfiguration>> EndpointConfigurations { get; } = new Dictionary<string, Action<EndpointConfiguration>>(0, StringComparer.OrdinalIgnoreCase); // Actions that will be delayed until Load so that they aren't applied if the configuration loader is replaced. private IList<Action> EndpointsToAdd { get; } = new List<Action>(); /// <summary> /// Specifies a configuration Action to run when an endpoint with the given name is loaded from configuration. /// </summary> public KestrelConfigurationLoader Endpoint(string name, Action<EndpointConfiguration> configureOptions) { if (string.IsNullOrEmpty(name)) { throw new ArgumentNullException(nameof(name)); } EndpointConfigurations[name] = configureOptions ?? throw new ArgumentNullException(nameof(configureOptions)); return this; } /// <summary> /// Bind to given IP address and port. /// </summary> public KestrelConfigurationLoader Endpoint(IPAddress address, int port) => Endpoint(address, port, _ => { }); /// <summary> /// Bind to given IP address and port. /// </summary> public KestrelConfigurationLoader Endpoint(IPAddress address, int port, Action<ListenOptions> configure) { if (address == null) { throw new ArgumentNullException(nameof(address)); } return Endpoint(new IPEndPoint(address, port), configure); } /// <summary> /// Bind to given IP endpoint. /// </summary> public KestrelConfigurationLoader Endpoint(IPEndPoint endPoint) => Endpoint(endPoint, _ => { }); /// <summary> /// Bind to given IP address and port. /// </summary> public KestrelConfigurationLoader Endpoint(IPEndPoint endPoint, Action<ListenOptions> configure) { if (endPoint == null) { throw new ArgumentNullException(nameof(endPoint)); } if (configure == null) { throw new ArgumentNullException(nameof(configure)); } EndpointsToAdd.Add(() => { Options.Listen(endPoint, configure); }); return this; } /// <summary> /// Listens on ::1 and 127.0.0.1 with the given port. Requesting a dynamic port by specifying 0 is not supported /// for this type of endpoint. /// </summary> public KestrelConfigurationLoader LocalhostEndpoint(int port) => LocalhostEndpoint(port, options => { }); /// <summary> /// Listens on ::1 and 127.0.0.1 with the given port. Requesting a dynamic port by specifying 0 is not supported /// for this type of endpoint. /// </summary> public KestrelConfigurationLoader LocalhostEndpoint(int port, Action<ListenOptions> configure) { if (configure == null) { throw new ArgumentNullException(nameof(configure)); } EndpointsToAdd.Add(() => { Options.ListenLocalhost(port, configure); }); return this; } /// <summary> /// Listens on all IPs using IPv6 [::], or IPv4 0.0.0.0 if IPv6 is not supported. /// </summary> public KestrelConfigurationLoader AnyIPEndpoint(int port) => AnyIPEndpoint(port, options => { }); /// <summary> /// Listens on all IPs using IPv6 [::], or IPv4 0.0.0.0 if IPv6 is not supported. /// </summary> public KestrelConfigurationLoader AnyIPEndpoint(int port, Action<ListenOptions> configure) { if (configure == null) { throw new ArgumentNullException(nameof(configure)); } EndpointsToAdd.Add(() => { Options.ListenAnyIP(port, configure); }); return this; } /// <summary> /// Bind to given Unix domain socket path. /// </summary> public KestrelConfigurationLoader UnixSocketEndpoint(string socketPath) => UnixSocketEndpoint(socketPath, _ => { }); /// <summary> /// Bind to given Unix domain socket path. /// </summary> public KestrelConfigurationLoader UnixSocketEndpoint(string socketPath, Action<ListenOptions> configure) { if (socketPath == null) { throw new ArgumentNullException(nameof(socketPath)); } if (socketPath.Length == 0 || socketPath[0] != '/') { throw new ArgumentException(CoreStrings.UnixSocketPathMustBeAbsolute, nameof(socketPath)); } if (configure == null) { throw new ArgumentNullException(nameof(configure)); } EndpointsToAdd.Add(() => { Options.ListenUnixSocket(socketPath, configure); }); return this; } /// <summary> /// Open a socket file descriptor. /// </summary> public KestrelConfigurationLoader HandleEndpoint(ulong handle) => HandleEndpoint(handle, _ => { }); /// <summary> /// Open a socket file descriptor. /// </summary> public KestrelConfigurationLoader HandleEndpoint(ulong handle, Action<ListenOptions> configure) { if (configure == null) { throw new ArgumentNullException(nameof(configure)); } EndpointsToAdd.Add(() => { Options.ListenHandle(handle, configure); }); return this; } // Called from ApplyEndpointDefaults so it applies to even explicit Listen endpoints. // Does not require a call to Load. internal void ApplyConfigurationDefaults(ListenOptions listenOptions) { var defaults = ConfigurationReader.EndpointDefaults; if (defaults.Protocols.HasValue) { listenOptions.Protocols = defaults.Protocols.Value; } } public void Load() { if (_loaded) { // The loader has already been run. return; } _loaded = true; LoadDefaultCert(ConfigurationReader); foreach (var endpoint in ConfigurationReader.Endpoints) { var listenOptions = AddressBinder.ParseAddress(endpoint.Url, out var https); Options.ApplyEndpointDefaults(listenOptions); if (endpoint.Protocols.HasValue) { listenOptions.Protocols = endpoint.Protocols.Value; } // Compare to UseHttps(httpsOptions => { }) var httpsOptions = new HttpsConnectionAdapterOptions(); if (https) { // Defaults Options.ApplyHttpsDefaults(httpsOptions); // Specified httpsOptions.ServerCertificate = LoadCertificate(endpoint.Certificate, endpoint.Name) ?? httpsOptions.ServerCertificate; // Fallback Options.ApplyDefaultCert(httpsOptions); } if (EndpointConfigurations.TryGetValue(endpoint.Name, out var configureEndpoint)) { var endpointConfig = new EndpointConfiguration(https, listenOptions, httpsOptions, endpoint.ConfigSection); configureEndpoint(endpointConfig); } // EndpointDefaults or configureEndpoint may have added an https adapter. if (https && !listenOptions.ConnectionAdapters.Any(f => f.IsHttps)) { if (httpsOptions.ServerCertificate == null && httpsOptions.ServerCertificateSelector == null) { throw new InvalidOperationException(CoreStrings.NoCertSpecifiedNoDevelopmentCertificateFound); } listenOptions.UseHttps(httpsOptions); } Options.ListenOptions.Add(listenOptions); } foreach (var action in EndpointsToAdd) { action(); } } private void LoadDefaultCert(ConfigurationReader configReader) { if (configReader.Certificates.TryGetValue("Default", out var defaultCertConfig)) { var defaultCert = LoadCertificate(defaultCertConfig, "Default"); if (defaultCert != null) { Options.DefaultCertificate = defaultCert; } } else { var logger = Options.ApplicationServices.GetRequiredService<ILogger<KestrelServer>>(); var certificate = FindDeveloperCertificateFile(configReader, logger); if (certificate != null) { logger.LocatedDevelopmentCertificate(certificate); Options.DefaultCertificate = certificate; } } } private X509Certificate2 FindDeveloperCertificateFile(ConfigurationReader configReader, ILogger<KestrelServer> logger) { string certificatePath = null; try { if (configReader.Certificates.TryGetValue("Development", out var certificateConfig) && certificateConfig.Path == null && certificateConfig.Password != null && TryGetCertificatePath(out certificatePath) && File.Exists(certificatePath)) { var certificate = new X509Certificate2(certificatePath, certificateConfig.Password); return IsDevelopmentCertificate(certificate) ? certificate : null; } else if (!File.Exists(certificatePath)) { logger.FailedToLocateDevelopmentCertificateFile(certificatePath); } } catch (CryptographicException) { logger.FailedToLoadDevelopmentCertificate(certificatePath); } return null; } private bool IsDevelopmentCertificate(X509Certificate2 certificate) { if (!string.Equals(certificate.Subject, "CN=localhost", StringComparison.Ordinal)) { return false; } foreach (var ext in certificate.Extensions) { if (string.Equals(ext.Oid.Value, CertificateManager.AspNetHttpsOid, StringComparison.Ordinal)) { return true; } } return false; } private bool TryGetCertificatePath(out string path) { var hostingEnvironment = Options.ApplicationServices.GetRequiredService<IHostEnvironment>(); var appName = hostingEnvironment.ApplicationName; // This will go away when we implement // https://github.com/aspnet/Hosting/issues/1294 var appData = Environment.GetEnvironmentVariable("APPDATA"); var home = Environment.GetEnvironmentVariable("HOME"); var basePath = appData != null ? Path.Combine(appData, "ASP.NET", "https") : null; basePath = basePath ?? (home != null ? Path.Combine(home, ".aspnet", "https") : null); path = basePath != null ? Path.Combine(basePath, $"{appName}.pfx") : null; return path != null; } private X509Certificate2 LoadCertificate(CertificateConfig certInfo, string endpointName) { if (certInfo.IsFileCert && certInfo.IsStoreCert) { throw new InvalidOperationException(CoreStrings.FormatMultipleCertificateSources(endpointName)); } else if (certInfo.IsFileCert) { var env = Options.ApplicationServices.GetRequiredService<IHostEnvironment>(); return new X509Certificate2(Path.Combine(env.ContentRootPath, certInfo.Path), certInfo.Password); } else if (certInfo.IsStoreCert) { return LoadFromStoreCert(certInfo); } return null; } private static X509Certificate2 LoadFromStoreCert(CertificateConfig certInfo) { var subject = certInfo.Subject; var storeName = certInfo.Store; var location = certInfo.Location; var storeLocation = StoreLocation.CurrentUser; if (!string.IsNullOrEmpty(location)) { storeLocation = (StoreLocation)Enum.Parse(typeof(StoreLocation), location, ignoreCase: true); } var allowInvalid = certInfo.AllowInvalid ?? false; return CertificateLoader.LoadFromStoreCert(subject, storeName, storeLocation, allowInvalid); } } }
37.934177
127
0.582288
[ "Apache-2.0" ]
Chief2/AspNetCore
src/Servers/Kestrel/Core/src/KestrelConfigurationLoader.cs
14,984
C#
using System; using System.Collections.Generic; using System.Data.Entity; using System.Linq; using System.Text; using System.Threading.Tasks; namespace WebApiUniqueConstraintHandling.Models { public class SampleInitializer : CreateDatabaseIfNotExists<SampleContext> { protected override void Seed(SampleContext context) { var TheWaspFactory = new Book { Title = "The Wasp Factory", Author = "Ian Banks" }; var TheDifferenceEngine = new Book { Title = "Idoru", Author = "William Gibson" }; var TheDrownedWorld = new Book { Title = "The Drowned World", Author = "J G Ballard" }; context.Books.AddRange(new List<Book> { TheWaspFactory, TheDifferenceEngine, TheDrownedWorld }); } } }
23.604651
77
0.518227
[ "MIT" ]
Useful-Software-Solutions-Ltd/AngularJS-with-Web-API-unique-property-validation
WebApiUniqueConstraintHandling/Models/SampleInitializer.cs
1,017
C#
using UnityEngine; using UnityEditor; using System.Collections.Generic; namespace UniBt.Editor { public sealed class BehaviorTreeEditor : BaseEditor { public enum SelectionMode { None, Pick, Rect, } public static BehaviorTreeEditor instance; public static BehaviorTree active { // This code is borrowed from ICode(https://www.assetstore.unity3d.com/en/#!/content/13761) get { if (BehaviorTreeEditor.instance == null) return null; return BehaviorTreeEditor.instance._active; } } public static GameObject activeGameObject { // This code is borrowed from ICode(https://www.assetstore.unity3d.com/en/#!/content/13761) get { if (BehaviorTreeEditor.instance == null) return null; return BehaviorTreeEditor.instance._activeGameObject; } } public static BehaviorTree root { // This code is borrowed from ICode(https://www.assetstore.unity3d.com/en/#!/content/13761) get { if (BehaviorTreeEditor.active == null) return null; return BehaviorTreeEditor.active.root; } } public static int SelectionCount { get { if (BehaviorTreeEditor.instance != null) { return BehaviorTreeEditor.instance._selection.Count; } return 0; } } private bool _isViewCenter; private BehaviorTree _active; private GameObject _activeGameObject; private Brain _brain; private Vector2 _selectionStartPosition; private Node _fromNode; private bool _isTopSelect; private SelectionMode _selectionMode; private Rect _shortcutRect; private MainToolBar _mainToolBar; private List<Node> _selection = new List<Node>(); private List<Decorator> _decoratorSelection = new List<Decorator>(); private List<Service> _serviceSelection = new List<Service>(); private Node[] nodes { get { if (BehaviorTreeEditor.active == null) return new Node[0]; return BehaviorTreeEditor.active.nodes; } } public static BehaviorTreeEditor ShowEditorWindow() { BehaviorTreeEditor window = EditorWindow.GetWindow<BehaviorTreeEditor>("BT Editor"); return window; } protected override void OnEnable() { base.OnEnable(); BehaviorTreeEditor.instance = this; if (_mainToolBar == null) _mainToolBar = new MainToolBar(); _isViewCenter = true; EditorApplication.playmodeStateChanged += OnPlayModeStateChanged; } private void OnPlayModeStateChanged() { if (EditorApplication.isPlayingOrWillChangePlaymode) { if (_activeGameObject != null) { _brain = activeGameObject.GetComponent<Brain>(); if (_brain != null && _brain.behaviorTree != null) SelectBehaviorTrees(_brain.behaviorTree); } _selection.Clear(); _decoratorSelection.Clear(); _serviceSelection.Clear(); UpdateUnitySelection(); } BehaviorTreeEditor.RepaintAll(); } private void Update() { if (BehaviorTreeEditor.active != null && BehaviorTreeEditor.activeGameObject != null) { if (EditorApplication.isPlaying) { _debugProgress += Time.unscaledDeltaTime * 2.5f; if (_debugProgress >= 1) _debugProgress = 0; BehaviorTreeEditor.RepaintAll(); } } } protected override Rect GetCanvasSize() { return new Rect(0, 17f, position.width, position.height - 17f); } protected override void OnGUI() { _mainToolBar.OnGUI(); base.Begin(); DoNodes(); base.End(); if (_isViewCenter) { CenterView(); _isViewCenter = false; } } private void DoNodes() { DoTransitions(); for (int i = 0; i < nodes.Length; i++) { Node node = nodes[i]; DoNode(node); } if (!EditorApplication.isPlayingOrWillChangePlaymode) { DoNodeEvents(); DecoratorContextMenu(); ServiceContextMenu(); NodeContextMenu(); } } private void NodeContextMenu() { if (_currentEvent.type != EventType.MouseDown || _currentEvent.button != 1 || _currentEvent.clickCount != 1) return; Node node = MouseOverNode(); if (node == null) return; GenericMenu nodeMenu = new GenericMenu(); if (!(node is Root)) { nodeMenu.AddItem(new GUIContent("Add Decorator/Decorator"), false, delegate () { BehaviorTreeEditorUtility.AddDecorator<Decorator>(node, BehaviorTreeEditor.active); }); if (node is Composite) { nodeMenu.AddItem(new GUIContent("Add Service"), false, delegate () { BehaviorTreeEditorUtility.AddService<Service>((Composite)node, BehaviorTreeEditor.active); }); } else { nodeMenu.AddDisabledItem(new GUIContent("Add Service")); } nodeMenu.AddSeparator("/"); nodeMenu.AddItem(new GUIContent("Delete Node"), false, delegate () { if (_selection.Contains(node)) { foreach (Node mNode in _selection) { if (!(mNode is Root)) BehaviorTreeEditorUtility.DeleteNode(mNode, BehaviorTreeEditor.active); } _selection.Clear(); } else { BehaviorTreeEditorUtility.DeleteNode(node, BehaviorTreeEditor.active); } UpdateUnitySelection(); EditorUtility.SetDirty(BehaviorTreeEditor.active); }); } else { nodeMenu.AddDisabledItem(new GUIContent("Add Decorator")); nodeMenu.AddDisabledItem(new GUIContent("Delete Node")); } nodeMenu.ShowAsContext(); Event.current.Use(); } private void DecoratorContextMenu() { if (_currentEvent.type != EventType.MouseDown || _currentEvent.button != 1 || _currentEvent.clickCount != 1) return; Decorator decorator = MouseOverDecorator(); if (decorator == null) return; int currentIndex = 0; for (int i = 0; i < decorator.parent.decorators.Length; i++) { if (decorator.parent.decorators[i] == decorator) break; currentIndex++; } GenericMenu menu = new GenericMenu(); if (currentIndex > 0) { menu.AddItem(new GUIContent("Move Up"), false, delegate () { decorator.parent.decorators = ArrayUtility.MoveItem<Decorator>(decorator.parent.decorators, currentIndex, currentIndex - 1); }); } else { menu.AddDisabledItem(new GUIContent("Move Up")); } if (currentIndex < decorator.parent.decorators.Length - 1) { menu.AddItem(new GUIContent("Move Down"), false, delegate () { decorator.parent.decorators = ArrayUtility.MoveItem<Decorator>(decorator.parent.decorators, currentIndex, currentIndex + 1); }); } else { menu.AddDisabledItem(new GUIContent("Move Down")); } menu.AddItem(new GUIContent("Delete Decorator"), false, delegate () { if (_decoratorSelection.Contains(decorator)) _decoratorSelection.Clear(); BehaviorTreeEditorUtility.DeleteDecorator(decorator); UpdateUnitySelection(); EditorUtility.SetDirty(BehaviorTreeEditor.active); }); menu.ShowAsContext(); Event.current.Use(); } private void ServiceContextMenu() { if (_currentEvent.type != EventType.MouseDown || _currentEvent.button != 1 || _currentEvent.clickCount != 1) return; Service service = MouseOverService(); if (service == null) return; int currentIndex = 0; for (int i = 0; i < service.parent.services.Length; i++) { if (service.parent.services[i] == service) break; currentIndex++; } GenericMenu menu = new GenericMenu(); if (currentIndex > 0) { menu.AddItem(new GUIContent("Move Up"), false, delegate () { service.parent.services = ArrayUtility.MoveItem<Service>(service.parent.services, currentIndex, currentIndex - 1); }); } else { menu.AddDisabledItem(new GUIContent("Move Up")); } if (currentIndex < service.parent.services.Length - 1) { menu.AddItem(new GUIContent("Move Down"), false, delegate () { service.parent.services = ArrayUtility.MoveItem<Service>(service.parent.services, currentIndex, currentIndex + 1); }); } else { menu.AddDisabledItem(new GUIContent("Move Down")); } menu.AddItem(new GUIContent("Delete Service"), false, delegate () { if (_serviceSelection.Contains(service)) _serviceSelection.Clear(); BehaviorTreeEditorUtility.DeleteService(service); UpdateUnitySelection(); EditorUtility.SetDirty(BehaviorTreeEditor.active); }); menu.ShowAsContext(); Event.current.Use(); } private void DoNode(Node node) { GUIStyle style = BehaviorTreeEditorStyles.GetNodeStyle((int)NodeColor.Grey, _selection.Contains(node)); if (EditorApplication.isPlaying && CompareLockedNodes(node)) { style = BehaviorTreeEditorStyles.GetNodeStyle((int)NodeColor.Yellow, _selection.Contains(node)); } node.position.width = NodeDrawer.GetMaxWidthContents(node); node.position.height = NodeDrawer.GetMaxHeightContents(node); GUI.Box(node.position, "", style); NodeDrawer.DrawNode(node, _selection.Contains(node)); if (node.hasTopSelector) { Rect rect = node.position; rect.x += 20; rect.width = rect.width - 40; rect.height = 10; GUIStyle topSelectorStyle = BehaviorTreeEditorStyles.GetSelectorStyle(false); if (GUI.Button(rect, "", topSelectorStyle) && !EditorApplication.isPlayingOrWillChangePlaymode) { if (_fromNode == null) { _fromNode = node; _isTopSelect = true; if (node.parentNode != null) { node.parentNode.childNodes = ArrayUtility.Remove<Node>(node.parentNode.childNodes, node); node.parentNode = null; } } else { if (!_isTopSelect && !ArrayUtility.Contains(_fromNode.childNodes, node)) AddTransition(_fromNode, node); _fromNode = null; } GUIUtility.hotControl = 0; GUIUtility.keyboardControl = 0; _selection.Clear(); _selection.Add(node); UpdateUnitySelection(); } } if (node.hasBotSelector) { Rect rect = node.position; rect.x += 20; rect.y += rect.height - 14; rect.width = rect.width - 40; rect.height = 10; GUIStyle botSelectorStyle = BehaviorTreeEditorStyles.GetSelectorStyle(false); if (GUI.Button(rect, "", botSelectorStyle) && !EditorApplication.isPlayingOrWillChangePlaymode) { if (_fromNode == null) { _fromNode = node; _isTopSelect = false; } else { if (_isTopSelect && !ArrayUtility.Contains(node.childNodes, _fromNode)) AddTransition(node, _fromNode); _fromNode = null; } GUIUtility.hotControl = 0; GUIUtility.keyboardControl = 0; _selection.Clear(); _selection.Add(node); UpdateUnitySelection(); } } } private void DoTransitions() { // This code is borrowed from ICode(https://www.assetstore.unity3d.com/en/#!/content/13761) if (_fromNode != null) { DrawConnection(_fromNode.position.center, _mousePosition, Color.green, 1, !_isTopSelect, true); Repaint(); } for (int i = 0; i < nodes.Length; i++) { Node node = nodes[i]; DoTransition(node); } } private void DoTransition(Node node) { // This code is borrowed from ICode(https://www.assetstore.unity3d.com/en/#!/content/13761) Node[] childNodes = node.childNodes; if (node.childNodes != null) { for (int i = 0; i < childNodes.Length; i++) { Node child = childNodes[i]; if (EditorApplication.isPlaying) { if (CompareLockedNodes(child)) DrawConnection(node.position.center, child.position.center, Color.cyan, 1, false, true); else DrawConnection(node.position.center, child.position.center, Color.gray, 1, false, false); } else { DrawConnection(node.position.center, child.position.center, Color.white, 1, false, false); } } } } private void AddTransition(Node fromNode, Node toNode) { if (fromNode is Root && !(toNode is Composite)) { return; } if (fromNode is Root) { for (int i = 0; i < fromNode.childNodes.Length; i++) { fromNode.childNodes[i].parentNode = null; } fromNode.childNodes = null; } toNode.parentNode = fromNode; fromNode.childNodes = ArrayUtility.Add<Node>(fromNode.childNodes, toNode); AssetDatabase.SaveAssets(); } private void OnSelectionChange() { // This code is borrowed from ICode(https://www.assetstore.unity3d.com/en/#!/content/13761) BehaviorTreeEditor.SelectGameObject(Selection.activeGameObject); } private void DoNodeEvents() { // This code is borrowed from ICode(https://www.assetstore.unity3d.com/en/#!/content/13761) if (_currentEvent.button != 0) return; SelectNodes(); DragNodes(); } private void SelectNodes() { int controlID = GUIUtility.GetControlID(FocusType.Passive); switch (_currentEvent.rawType) { case EventType.MouseDown: GUIUtility.hotControl = controlID; _selectionStartPosition = _mousePosition; Decorator decorator = MouseOverDecorator(); Service service = MouseOverService(); Node node = MouseOverNode(); if (decorator != null) { _selection.Clear(); _serviceSelection.Clear(); if (!_decoratorSelection.Contains(decorator)) { _decoratorSelection.Clear(); _decoratorSelection.Add(decorator); } GUIUtility.hotControl = 0; GUIUtility.keyboardControl = 0; UpdateUnitySelection(); return; } else if (service != null) { _selection.Clear(); _decoratorSelection.Clear(); if (!_serviceSelection.Contains(service)) { _serviceSelection.Clear(); _serviceSelection.Add(service); } GUIUtility.hotControl = 0; GUIUtility.keyboardControl = 0; UpdateUnitySelection(); return; } else if (node != null) { _decoratorSelection.Clear(); _serviceSelection.Clear(); if (_fromNode != null) { if (_fromNode != node) { if (_isTopSelect) { if (!ArrayUtility.Contains(node.childNodes, _fromNode) && _fromNode.parentNode != node) AddTransition(node, _fromNode); } else { if (!ArrayUtility.Contains(_fromNode.childNodes, node)) AddTransition(_fromNode, node); } } _fromNode = null; _selection.Clear(); _selection.Add(node); GUIUtility.hotControl = 0; GUIUtility.keyboardControl = 0; return; } if (EditorGUI.actionKey || _currentEvent.shift) { if (!_selection.Contains(node)) _selection.Add(node); else _selection.Remove(node); } else if (!_selection.Contains(node)) { _selection.Clear(); _selection.Add(node); } GUIUtility.hotControl = 0; GUIUtility.keyboardControl = 0; UpdateUnitySelection(); return; } _fromNode = null; _selectionMode = SelectionMode.Pick; if (!EditorGUI.actionKey && !_currentEvent.shift) { _selection.Clear(); _decoratorSelection.Clear(); _serviceSelection.Clear(); UpdateUnitySelection(); } _currentEvent.Use(); break; case EventType.MouseUp: if (GUIUtility.hotControl == controlID) { _selectionMode = SelectionMode.None; GUIUtility.hotControl = 0; _currentEvent.Use(); } break; case EventType.MouseDrag: if (GUIUtility.hotControl == controlID && !EditorGUI.actionKey && !_currentEvent.shift && (_selectionMode == SelectionMode.Pick || _selectionMode == SelectionMode.Rect)) { _selectionMode = SelectionMode.Rect; SelectNodesInRect(FromToRect(_selectionStartPosition, _mousePosition)); _currentEvent.Use(); } break; case EventType.Repaint: if (GUIUtility.hotControl == controlID && _selectionMode == SelectionMode.Rect) { GUIStyle selectionStyle = "SelectionRect"; selectionStyle.Draw(FromToRect(_selectionStartPosition, _mousePosition), false, false, false, false); } break; } } private Rect FromToRect(Vector2 start, Vector2 end) { // This code is borrowed from ICode(https://www.assetstore.unity3d.com/en/#!/content/13761) Rect rect = new Rect(start.x, start.y, end.x - start.x, end.y - start.y); if (rect.width < 0f) { rect.x = rect.x + rect.width; rect.width = -rect.width; } if (rect.height < 0f) { rect.y = rect.y + rect.height; rect.height = -rect.height; } return rect; } private void DragNodes() { // This code is borrowed from ICode(https://www.assetstore.unity3d.com/en/#!/content/13761) int controlID = GUIUtility.GetControlID(FocusType.Passive); switch (_currentEvent.rawType) { case EventType.MouseDown: GUIUtility.hotControl = controlID; _currentEvent.Use(); break; case EventType.MouseUp: if (GUIUtility.hotControl == controlID) { GUIUtility.hotControl = 0; _currentEvent.Use(); } break; case EventType.MouseDrag: if (GUIUtility.hotControl == controlID) { for (int i = 0; i < _selection.Count; i++) { Node node = _selection[i]; node.position.position += _currentEvent.delta; } _currentEvent.Use(); } break; case EventType.Repaint: if (GUIUtility.hotControl == controlID) { AutoPanNodes(1.5f); } break; } } private void AutoPanNodes(float speed) { // This code is borrowed from ICode(https://www.assetstore.unity3d.com/en/#!/content/13761) Vector2 delta = Vector2.zero; if (_mousePosition.x > _canvasSize.width + _scrollPosition.x - 50f) { delta.x += speed; } if ((_mousePosition.x < _scrollPosition.x + 50f) && _scrollPosition.x > 0f) { delta.x -= speed; } if (_mousePosition.y > _canvasSize.height + _scrollPosition.y - 50f) { delta.y += speed; } if ((_mousePosition.y < _scrollPosition.y + 50f) && _scrollPosition.y > 0f) { delta.y -= speed; } if (delta != Vector2.zero) { for (int i = 0; i < _selection.Count; i++) { Node node = _selection[i]; node.position.position += delta; } UpdateScrollPosition(_scrollPosition + delta); Repaint(); } } private Node MouseOverNode() { for (int i = 0; i < nodes.Length; i++) { Node node = nodes[i]; if (node.position.Contains(_mousePosition)) return node; } return null; } private Decorator MouseOverDecorator() { for (int i = 0; i < nodes.Length; i++) { Node node = nodes[i]; float sharedHeight = node.position.yMin + 7; float sharedWidth = node.position.width - 14; for (int j = 0; j < node.decorators.Length; j++) { Decorator decorator = node.decorators[j]; Rect decoratorRect = node.position; decoratorRect.width = sharedWidth; decoratorRect.yMin = sharedHeight; decoratorRect.yMax = sharedHeight + 32 + NodeDrawer.GetCommentHeight(decorator.comment); if (decoratorRect.Contains(_mousePosition)) { return decorator; } sharedHeight += decoratorRect.yMax - decoratorRect.yMin + 5; } } return null; } private Service MouseOverService() { for (int i = 0; i < nodes.Length; i++) { Node node = nodes[i]; if (node is Composite) { Composite composite = node as Composite; float sharedHeight = node.position.yMax - 14; for (int j = composite.services.Length - 1; j >= 0; j--) { Service service = composite.services[j]; Rect serviceRect = node.position; serviceRect.xMin += 7 + 13; serviceRect.xMax -= 7; serviceRect.yMin = sharedHeight - (32 + NodeDrawer.GetCommentHeight(service.comment)); serviceRect.yMax = sharedHeight; if (serviceRect.Contains(_mousePosition)) return service; sharedHeight -= serviceRect.yMax - serviceRect.yMin + 5; } } } return null; } private void SelectNodesInRect(Rect r) { // This code is borrowed from ICode(https://www.assetstore.unity3d.com/en/#!/content/13761) for (int i = 0; i < nodes.Length; i++) { Node node = nodes[i]; Rect rect = node.position; if (rect.xMax < r.x || rect.x > r.xMax || rect.yMax < r.y || rect.y > r.yMax) { _selection.Remove(node); continue; } if (!_selection.Contains(node)) _selection.Add(node); } UpdateUnitySelection(); } private void UpdateUnitySelection() { if (_decoratorSelection.Count > 0) Selection.objects = _decoratorSelection.ToArray(); else if (_serviceSelection.Count > 0) Selection.objects = _serviceSelection.ToArray(); else Selection.objects = _selection.ToArray(); } public void CenterView() { // This code is borrowed from ICode(https://www.assetstore.unity3d.com/en/#!/content/13761) Vector2 center = Vector2.zero; if (nodes.Length > 0) { for (int i = 0; i < nodes.Length; i++) { Node node = nodes[i]; center += new Vector2(node.position.center.x - _canvasSize.width * 0.5f, node.position.center.y - _canvasSize.height * 0.5f); } center /= nodes.Length; } else { center = BaseEditor.center; } UpdateScrollPosition(center); Repaint(); } protected override void CanvasContextMenu() { if (_currentEvent.type != EventType.MouseDown || _currentEvent.button != 1 || _currentEvent.clickCount != 1 || BehaviorTreeEditor.active == null) return; GenericMenu canvasMenu = new GenericMenu(); // Composite canvasMenu.AddItem(new GUIContent("Create Composite/Selector"), false, delegate () { BehaviorTreeEditorUtility.AddNode<Selector>(_mousePosition, BehaviorTreeEditor.active); }); canvasMenu.AddItem(new GUIContent("Create Composite/Sequence"), false, delegate () { BehaviorTreeEditorUtility.AddNode<Sequence>(_mousePosition, BehaviorTreeEditor.active); }); // Task canvasMenu.AddItem(new GUIContent("Create Task/Wait"), false, delegate () { BehaviorTreeEditorUtility.AddNode<Wait>(_mousePosition, BehaviorTreeEditor.active); }); canvasMenu.AddSeparator("Create Task/"); canvasMenu.AddItem(new GUIContent("Create Task/Task"), false, delegate () { BehaviorTreeEditorUtility.AddNode<Task>(_mousePosition, BehaviorTreeEditor.active); }); canvasMenu.ShowAsContext(); } private bool CompareLockedNodes(Node node) { if (_brain != null && _brain.behaviorTree != null) { Node cNode = _brain.aliveBehavior; while (cNode != null) { if (cNode == node) return true; cNode = cNode.parentNode; } } return false; } public static void SelectBehaviorTrees(BehaviorTree bt) { if (BehaviorTreeEditor.instance == null || BehaviorTreeEditor.active == bt) { BehaviorTreeEditor.instance.CenterView(); return; } BehaviorTreeEditor.instance._active = bt; BehaviorTreeEditor.instance._selection.Clear(); BehaviorTreeEditor.instance.UpdateUnitySelection(); BehaviorTreeEditor.instance.CenterView(); } public static void RepaintAll() { if (BehaviorTreeEditor.instance != null) BehaviorTreeEditor.instance.Repaint(); } public static bool CompareSelectedDecorators(Decorator decorator) { for (int i = 0; i < BehaviorTreeEditor.instance._decoratorSelection.Count; i++) { if (BehaviorTreeEditor.instance._decoratorSelection[i] == decorator) return true; } return false; } public static bool CompareSelectedServices(Service service) { for (int i = 0; i < BehaviorTreeEditor.instance._serviceSelection.Count; i++) { if (BehaviorTreeEditor.instance._serviceSelection[i] == service) return true; } return false; } public static void SelectGameObject(GameObject gameObject) { if (BehaviorTreeEditor.instance == null) return; if (gameObject != null) { Brain brain = gameObject.GetComponent<Brain>(); BehaviorTreeEditor.instance._brain = brain; if (brain != null && brain.behaviorTree != null) { BehaviorTreeEditor.instance._activeGameObject = gameObject; BehaviorTreeEditor.SelectBehaviorTrees(brain.behaviorTree); } } } public static bool CheckThisDecoratorClosed(Decorator decorator) { if (BehaviorTreeEditor.instance == null) return false; if (BehaviorTreeEditor.instance._brain != null) { Brain brain = BehaviorTreeEditor.instance._brain; for (int i = 0; i < brain.runtimeDecorators.Count; i++) { if (brain.runtimeDecorators[i].decorator == decorator) { #if UNITY_EDITOR if (brain.runtimeDecorators[i].closed) return true; else break; #else break; #endif } } } return false; } } }
35.877973
189
0.464951
[ "MIT" ]
gitter-badger/UniBt
Assets/UniBt/Scripts/Editor/BehaviorTreeEditor.cs
34,696
C#
using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Options; using System.Threading; using System.Threading.Tasks; using Volo.Abp.Localization; namespace LINGYUN.Abp.Localization.Dynamic { public class DynamicLocalizationInitializeService : BackgroundService { protected ILocalizationStore Store { get; } protected AbpLocalizationOptions LocalizationOptions { get; } protected AbpLocalizationDynamicOptions DynamicOptions { get; } public DynamicLocalizationInitializeService( ILocalizationStore store, IOptions<AbpLocalizationOptions> localizationOptions, IOptions<AbpLocalizationDynamicOptions> dynamicOptions) { Store = store; DynamicOptions = dynamicOptions.Value; LocalizationOptions = localizationOptions.Value; } protected override async Task ExecuteAsync(CancellationToken stoppingToken) { foreach (var resource in LocalizationOptions.Resources) { foreach (var contributor in resource.Value.Contributors) { if (contributor.GetType().IsAssignableFrom(typeof(DynamicLocalizationResourceContributor))) { var resourceLocalizationDic = await Store .GetLocalizationDictionaryAsync( resource.Value.ResourceName, stoppingToken); DynamicOptions.AddOrUpdate(resource.Value.ResourceName, resourceLocalizationDic); } } } } } }
39.090909
112
0.609302
[ "MIT" ]
colinin/abp-vue-admin-element-typescript
aspnet-core/modules/common/LINGYUN.Abp.Localization.Dynamic/LINGYUN/Abp/Localization/Dynamic/DynamicLocalizationInitializeService.cs
1,722
C#
/**************************************************************************** Copyright (c) 2013-2015 scutgame.com http://www.scutgame.com Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ using System; using System.Collections.Generic; namespace ZyGames.Framework.Game.Lang { /// <summary> /// Lang enum. /// </summary> [Obsolete] public enum LangEnum { /// <summary> /// 值=0 中文 /// </summary> ZH_CN, /// <summary> /// 值=1 英文 /// </summary> EN_US, /// <summary> /// 值=2 繁体 /// </summary> BIG5_TW, /// <summary> /// 值=3 韩文 /// </summary> KOREAN } /// <summary> /// 多语言 /// </summary> [Obsolete("Use Language.Instance call.")] public class LanguageHelper { private static object thisLock = new object(); private static Dictionary<LangEnum, ILanguage> _langTable = new Dictionary<LangEnum, ILanguage>(); private static LangEnum _langEnum; static LanguageHelper() { _langEnum = LangEnum.ZH_CN; } /// <summary> /// Sets the lang. /// </summary> /// <param name="lang">Lang.</param> public static void SetLang(LangEnum lang) { lock (thisLock) { _langEnum = lang; } } /// <summary> /// Gets the lang. /// </summary> /// <returns>The lang.</returns> public static ILanguage GetLang() { return GetLang(_langEnum); } /// <summary> /// Gets the lang. /// </summary> /// <returns>The lang.</returns> /// <param name="langEnum">Lang enum.</param> public static ILanguage GetLang(LangEnum langEnum) { ILanguage lang = null; if (!_langTable.ContainsKey(langEnum)) { lock (thisLock) { if (!_langTable.ContainsKey(langEnum)) { switch (langEnum) { case LangEnum.ZH_CN: _langTable.Add(langEnum, new BaseZHLanguage()); break; case LangEnum.BIG5_TW: _langTable.Add(langEnum, new BaseBIG5Language()); break; case LangEnum.EN_US: _langTable.Add(langEnum, new BaseENLanguage()); break; case LangEnum.KOREAN: _langTable.Add(langEnum, new BaseKoreanLanguage()); break; default: _langTable.Add(langEnum, new BaseZHLanguage()); break; } } } } lang = _langTable[langEnum]; return lang; } } }
34.048
107
0.495536
[ "Unlicense" ]
HongXiao/Scut
Source/Middleware/ZyGames.Framework.Game/Lang/LanguageHelper.cs
4,288
C#
using System.Web; using System.Web.Optimization; namespace WebAdressBook { public class BundleConfig { // For more information on bundling, visit http://go.microsoft.com/fwlink/?LinkId=301862 public static void RegisterBundles(BundleCollection bundles) { bundles.Add(new StyleBundle("~/Content/css").Include( "~/Content/bootstrap.css", "~/Content/site.css")); } } }
27.529412
96
0.602564
[ "Unlicense" ]
mrQLeech/WebAdressBook
WebAdressBook/WebAdressBook/App_Start/BundleConfig.cs
470
C#
using System.Collections; using NBitcoin.BouncyCastle.Asn1; using NBitcoin.BouncyCastle.Asn1.CryptoPro; using NBitcoin.BouncyCastle.Asn1.Iana; using NBitcoin.BouncyCastle.Asn1.Kisa; using NBitcoin.BouncyCastle.Asn1.Nist; using NBitcoin.BouncyCastle.Asn1.Ntt; using NBitcoin.BouncyCastle.Asn1.Oiw; using NBitcoin.BouncyCastle.Asn1.Pkcs; using NBitcoin.BouncyCastle.Asn1.X9; using NBitcoin.BouncyCastle.Crypto; using NBitcoin.BouncyCastle.Crypto.Generators; using NBitcoin.BouncyCastle.Utilities; using NBitcoin.BouncyCastle.Utilities.Collections; namespace NBitcoin.BouncyCastle.Security { public sealed class GeneratorUtilities { private GeneratorUtilities() { } private static readonly IDictionary kgAlgorithms = Platform.CreateHashtable(); private static readonly IDictionary kpgAlgorithms = Platform.CreateHashtable(); private static readonly IDictionary defaultKeySizes = Platform.CreateHashtable(); static GeneratorUtilities() { // // key generators. // AddKgAlgorithm("AES", "AESWRAP"); AddKgAlgorithm("AES128", "2.16.840.1.101.3.4.2", NistObjectIdentifiers.IdAes128Cbc, NistObjectIdentifiers.IdAes128Cfb, NistObjectIdentifiers.IdAes128Ecb, NistObjectIdentifiers.IdAes128Ofb, NistObjectIdentifiers.IdAes128Wrap); AddKgAlgorithm("AES192", "2.16.840.1.101.3.4.22", NistObjectIdentifiers.IdAes192Cbc, NistObjectIdentifiers.IdAes192Cfb, NistObjectIdentifiers.IdAes192Ecb, NistObjectIdentifiers.IdAes192Ofb, NistObjectIdentifiers.IdAes192Wrap); AddKgAlgorithm("AES256", "2.16.840.1.101.3.4.42", NistObjectIdentifiers.IdAes256Cbc, NistObjectIdentifiers.IdAes256Cfb, NistObjectIdentifiers.IdAes256Ecb, NistObjectIdentifiers.IdAes256Ofb, NistObjectIdentifiers.IdAes256Wrap); AddKgAlgorithm("BLOWFISH", "1.3.6.1.4.1.3029.1.2"); AddKgAlgorithm("CAMELLIA", "CAMELLIAWRAP"); AddKgAlgorithm("CAMELLIA128", NttObjectIdentifiers.IdCamellia128Cbc, NttObjectIdentifiers.IdCamellia128Wrap); AddKgAlgorithm("CAMELLIA192", NttObjectIdentifiers.IdCamellia192Cbc, NttObjectIdentifiers.IdCamellia192Wrap); AddKgAlgorithm("CAMELLIA256", NttObjectIdentifiers.IdCamellia256Cbc, NttObjectIdentifiers.IdCamellia256Wrap); AddKgAlgorithm("CAST5", "1.2.840.113533.7.66.10"); AddKgAlgorithm("CAST6"); AddKgAlgorithm("DES", OiwObjectIdentifiers.DesCbc, OiwObjectIdentifiers.DesCfb, OiwObjectIdentifiers.DesEcb, OiwObjectIdentifiers.DesOfb); AddKgAlgorithm("DESEDE", "DESEDEWRAP", "TDEA", OiwObjectIdentifiers.DesEde); AddKgAlgorithm("DESEDE3", PkcsObjectIdentifiers.DesEde3Cbc, PkcsObjectIdentifiers.IdAlgCms3DesWrap); AddKgAlgorithm("GOST28147", "GOST", "GOST-28147", CryptoProObjectIdentifiers.GostR28147Cbc); AddKgAlgorithm("HC128"); AddKgAlgorithm("HC256"); AddKgAlgorithm("IDEA", "1.3.6.1.4.1.188.7.1.1.2"); AddKgAlgorithm("NOEKEON"); AddKgAlgorithm("RC2", PkcsObjectIdentifiers.RC2Cbc, PkcsObjectIdentifiers.IdAlgCmsRC2Wrap); AddKgAlgorithm("RC4", "ARC4", "1.2.840.113549.3.4"); AddKgAlgorithm("RC5", "RC5-32"); AddKgAlgorithm("RC5-64"); AddKgAlgorithm("RC6"); AddKgAlgorithm("RIJNDAEL"); AddKgAlgorithm("SALSA20"); AddKgAlgorithm("SEED", KisaObjectIdentifiers.IdNpkiAppCmsSeedWrap, KisaObjectIdentifiers.IdSeedCbc); AddKgAlgorithm("SERPENT"); AddKgAlgorithm("SKIPJACK"); AddKgAlgorithm("TEA"); AddKgAlgorithm("TWOFISH"); AddKgAlgorithm("VMPC"); AddKgAlgorithm("VMPC-KSA3"); AddKgAlgorithm("XTEA"); // // HMac key generators // AddHMacKeyGenerator("MD2"); AddHMacKeyGenerator("MD4"); AddHMacKeyGenerator("MD5", IanaObjectIdentifiers.HmacMD5); AddHMacKeyGenerator("SHA1", PkcsObjectIdentifiers.IdHmacWithSha1, IanaObjectIdentifiers.HmacSha1); AddHMacKeyGenerator("SHA224", PkcsObjectIdentifiers.IdHmacWithSha224); AddHMacKeyGenerator("SHA256", PkcsObjectIdentifiers.IdHmacWithSha256); AddHMacKeyGenerator("SHA384", PkcsObjectIdentifiers.IdHmacWithSha384); AddHMacKeyGenerator("SHA512", PkcsObjectIdentifiers.IdHmacWithSha512); AddHMacKeyGenerator("SHA512/224"); AddHMacKeyGenerator("SHA512/256"); AddHMacKeyGenerator("SHA3-224"); AddHMacKeyGenerator("SHA3-256"); AddHMacKeyGenerator("SHA3-384"); AddHMacKeyGenerator("SHA3-512"); AddHMacKeyGenerator("RIPEMD128"); AddHMacKeyGenerator("RIPEMD160", IanaObjectIdentifiers.HmacRipeMD160); AddHMacKeyGenerator("TIGER", IanaObjectIdentifiers.HmacTiger); // // key pair generators. // AddKpgAlgorithm("DH", "DIFFIEHELLMAN"); AddKpgAlgorithm("DSA"); AddKpgAlgorithm("EC", // TODO Should this be an alias for ECDH? X9ObjectIdentifiers.DHSinglePassStdDHSha1KdfScheme); AddKpgAlgorithm("ECDH", "ECIES"); AddKpgAlgorithm("ECDHC"); AddKpgAlgorithm("ECMQV", X9ObjectIdentifiers.MqvSinglePassSha1KdfScheme); AddKpgAlgorithm("ECDSA"); AddKpgAlgorithm("ECGOST3410", "ECGOST-3410", "GOST-3410-2001"); AddKpgAlgorithm("ELGAMAL"); AddKpgAlgorithm("GOST3410", "GOST-3410", "GOST-3410-94"); AddKpgAlgorithm("RSA", "1.2.840.113549.1.1.1"); AddDefaultKeySizeEntries(64, "DES"); AddDefaultKeySizeEntries(80, "SKIPJACK"); AddDefaultKeySizeEntries(128, "AES128", "BLOWFISH", "CAMELLIA128", "CAST5", "DESEDE", "HC128", "HMACMD2", "HMACMD4", "HMACMD5", "HMACRIPEMD128", "IDEA", "NOEKEON", "RC2", "RC4", "RC5", "SALSA20", "SEED", "TEA", "XTEA", "VMPC", "VMPC-KSA3"); AddDefaultKeySizeEntries(160, "HMACRIPEMD160", "HMACSHA1"); AddDefaultKeySizeEntries(192, "AES", "AES192", "CAMELLIA192", "DESEDE3", "HMACTIGER", "RIJNDAEL", "SERPENT"); AddDefaultKeySizeEntries(224, "HMACSHA224"); AddDefaultKeySizeEntries(256, "AES256", "CAMELLIA", "CAMELLIA256", "CAST6", "GOST28147", "HC256", "HMACSHA256", "RC5-64", "RC6", "TWOFISH"); AddDefaultKeySizeEntries(384, "HMACSHA384"); AddDefaultKeySizeEntries(512, "HMACSHA512"); AddDefaultKeySizeEntries(224, "HMACSHA512/224"); AddDefaultKeySizeEntries(256, "HMACSHA512/256"); } private static void AddDefaultKeySizeEntries(int size, params string[] algorithms) { foreach (string algorithm in algorithms) { defaultKeySizes.Add(algorithm, size); } } private static void AddKgAlgorithm( string canonicalName, params object[] aliases) { kgAlgorithms[canonicalName] = canonicalName; foreach (object alias in aliases) { kgAlgorithms[alias.ToString()] = canonicalName; } } private static void AddKpgAlgorithm( string canonicalName, params object[] aliases) { kpgAlgorithms[canonicalName] = canonicalName; foreach (object alias in aliases) { kpgAlgorithms[alias.ToString()] = canonicalName; } } private static void AddHMacKeyGenerator( string algorithm, params object[] aliases) { string mainName = "HMAC" + algorithm; kgAlgorithms[mainName] = mainName; kgAlgorithms["HMAC-" + algorithm] = mainName; kgAlgorithms["HMAC/" + algorithm] = mainName; foreach (object alias in aliases) { kgAlgorithms[alias.ToString()] = mainName; } } // TODO Consider making this public internal static string GetCanonicalKeyGeneratorAlgorithm( string algorithm) { return (string) kgAlgorithms[Platform.ToUpperInvariant(algorithm)]; } // TODO Consider making this public internal static string GetCanonicalKeyPairGeneratorAlgorithm( string algorithm) { return (string)kpgAlgorithms[Platform.ToUpperInvariant(algorithm)]; } public static CipherKeyGenerator GetKeyGenerator( DerObjectIdentifier oid) { return GetKeyGenerator(oid.Id); } public static CipherKeyGenerator GetKeyGenerator( string algorithm) { string canonicalName = GetCanonicalKeyGeneratorAlgorithm(algorithm); if (canonicalName == null) throw new SecurityUtilityException("KeyGenerator " + algorithm + " not recognised."); int defaultKeySize = FindDefaultKeySize(canonicalName); if (defaultKeySize == -1) throw new SecurityUtilityException("KeyGenerator " + algorithm + " (" + canonicalName + ") not supported."); if (canonicalName == "DES") return new DesKeyGenerator(defaultKeySize); if (canonicalName == "DESEDE" || canonicalName == "DESEDE3") return new DesEdeKeyGenerator(defaultKeySize); return new CipherKeyGenerator(defaultKeySize); } public static IAsymmetricCipherKeyPairGenerator GetKeyPairGenerator( DerObjectIdentifier oid) { return GetKeyPairGenerator(oid.Id); } public static IAsymmetricCipherKeyPairGenerator GetKeyPairGenerator( string algorithm) { string canonicalName = GetCanonicalKeyPairGeneratorAlgorithm(algorithm); if (canonicalName == null) throw new SecurityUtilityException("KeyPairGenerator " + algorithm + " not recognised."); if (canonicalName == "DH") return new DHKeyPairGenerator(); if (canonicalName == "DSA") return new DsaKeyPairGenerator(); // "EC", "ECDH", "ECDHC", "ECDSA", "ECGOST3410", "ECMQV" if (canonicalName.StartsWith("EC")) return new ECKeyPairGenerator(canonicalName); if (canonicalName == "ELGAMAL") return new ElGamalKeyPairGenerator(); if (canonicalName == "GOST3410") return new Gost3410KeyPairGenerator(); if (canonicalName == "RSA") return new RsaKeyPairGenerator(); throw new SecurityUtilityException("KeyPairGenerator " + algorithm + " (" + canonicalName + ") not supported."); } internal static int GetDefaultKeySize( DerObjectIdentifier oid) { return GetDefaultKeySize(oid.Id); } internal static int GetDefaultKeySize( string algorithm) { string canonicalName = GetCanonicalKeyGeneratorAlgorithm(algorithm); if (canonicalName == null) throw new SecurityUtilityException("KeyGenerator " + algorithm + " not recognised."); int defaultKeySize = FindDefaultKeySize(canonicalName); if (defaultKeySize == -1) throw new SecurityUtilityException("KeyGenerator " + algorithm + " (" + canonicalName + ") not supported."); return defaultKeySize; } private static int FindDefaultKeySize( string canonicalName) { if (!defaultKeySizes.Contains(canonicalName)) return -1; return (int)defaultKeySizes[canonicalName]; } } }
38.422857
106
0.560306
[ "MIT" ]
dthorpe/NBitcoin
NBitcoin.BouncyCastle/security/GeneratorUtilities.cs
13,448
C#
using Handelabra.Sentinels.Engine.Controller; using Handelabra.Sentinels.Engine.Model; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; namespace Jp.ParahumansOfTheWormverse.Armsmaster { public abstract class ModuleCardController : CardController { public static string PrimarySecondaryKey = "IsPrimary"; public ModuleCardController(Card card, TurnTakerController controller) : base(card, controller) { SpecialStringMaker.ShowIfElseSpecialString(() => IsPrimaryModule(base.GameController, base.Card), () => base.Card.Title + " is attached as Primary.", () => base.Card.Title + " is attached as Secondary.").Condition = () => base.Card.IsInPlayAndHasGameText; } public override IEnumerator DeterminePlayLocation(List<MoveCardDestination> storedResults, bool isPutIntoPlay, List<IDecision> decisionSources, Location overridePlayArea = null, LinqTurnTakerCriteria additionalTurnTakerCriteria = null) { var e = SelectCardThisCardWillMoveNextTo( new LinqCardCriteria( c => c.DoKeywordsContain("halberd") && ( c == CharacterCard || c.GetAllNextToCards(false).All(c2 => ! IsPrimaryModule(GameController, c2)) || c.GetAllNextToCards(false).All(c2 => ! IsSecondaryModule(GameController, c2)) ), "halberd", useCardsSuffix: true ), storedResults, isPutIntoPlay, decisionSources ); if (UseUnityCoroutines) { yield return GameController.StartCoroutine(e); } else { GameController.ExhaustCoroutine(e); } } public override IEnumerator Play() { var ownerCard = Card.Location.OwnerCard; if (ownerCard == null) { yield break; } bool primaryAllowed = true; bool secondaryAllowed = true; if (ownerCard != CharacterCard) { foreach (var c in ownerCard.GetAllNextToCards(false)) { if (c == Card) { continue; } if (IsPrimaryModule(GameController, c)) { primaryAllowed = false; } if (IsSecondaryModule(GameController, c)) { secondaryAllowed = false; } } } if (primaryAllowed && secondaryAllowed) { var primarySecondary = new List<SelectWordDecision>(); var e = GameController.SelectWord( HeroTurnTakerController, new string[] { "Primary", "Secondary" }, SelectionType.Custom, primarySecondary, optional: false, new Card[] { Card }, GetCardSource() ); if (UseUnityCoroutines) { yield return GameController.StartCoroutine(e); } else { GameController.ExhaustCoroutine(e); } if (primarySecondary.FirstOrDefault().Index == 0) { SetCardProperty(PrimarySecondaryKey, true); } else { SetCardProperty(PrimarySecondaryKey, false); } } else { SetCardProperty(PrimarySecondaryKey, primaryAllowed); } } public override CustomDecisionText GetCustomDecisionText(IDecision decision) { return new CustomDecisionText( "Attach module as Primary or Secondary?", HeroTurnTaker.NameRespectingVariant + " is selecting module type", "Vote for attaching the module as Primary or Secondary", "Attach module as Primary or Secondary?" ); } public abstract IEnumerator DoPrimary(); public abstract IEnumerator DoSecondary(); public override IEnumerator ActivateAbility(string abilityKey) { IEnumerator e = null; if (abilityKey == "primary") { e = DoPrimary(); } if (abilityKey == "secondary") { e = DoSecondary(); } if (e == null) { yield break; } if (UseUnityCoroutines) { yield return GameController.StartCoroutine(e); } else { GameController.ExhaustCoroutine(e); } } public bool? IsPrimary() { return GetCardPropertyJournalEntryBoolean(PrimarySecondaryKey); } public static bool IsPrimaryModule(GameController gc, Card card) { var controller = gc.FindCardController(card) as ModuleCardController; if (controller == null) { return false; } return controller.IsPrimary() == true; } public static bool IsSecondaryModule(GameController gc, Card card) { var controller = gc.FindCardController(card) as ModuleCardController; if (controller == null) { return false; } return controller.IsPrimary() == false; } } }
33.436782
267
0.508938
[ "BSD-2-Clause" ]
jamespicone/potw
Mod/Heroes/Armsmaster/Extra/ModuleCardController.cs
5,820
C#
using System.Net.NetworkInformation; namespace RightpointLabs.Pourcast.Application.Orchestrators.Concrete { using System; using System.Collections.Generic; using System.Linq; using RightpointLabs.Pourcast.Application.Orchestrators.Abstract; using RightpointLabs.Pourcast.Application.Payloads; using RightpointLabs.Pourcast.Application.Transactions; using RightpointLabs.Pourcast.Domain.Models; using RightpointLabs.Pourcast.Domain.Repositories; public class BeerOrchestrator : BaseOrchestrator, IBeerOrchestrator { private readonly IBeerRepository _beerRepository; private readonly IBreweryRepository _breweryRepository; private readonly ITapRepository _tapRepository; private readonly IKegRepository _kegRepository; private readonly IStyleRepository _styleRepository; public BeerOrchestrator(IBeerRepository beerRepository, IBreweryRepository breweryRepository, ITapRepository tapRepository, IKegRepository kegRepository, IStyleRepository styleRepository) { if (beerRepository == null) throw new ArgumentNullException("beerRepository"); if(breweryRepository == null) throw new ArgumentNullException("breweryRepository"); if (tapRepository == null) throw new ArgumentNullException("tapRepository"); if (kegRepository == null) throw new ArgumentNullException("kegRepository"); if(null == styleRepository) throw new ArgumentException("styleRepository"); _beerRepository = beerRepository; _breweryRepository = breweryRepository; _tapRepository = tapRepository; _kegRepository = kegRepository; _styleRepository = styleRepository; } public IEnumerable<Beer> GetBeers() { return _beerRepository.GetAll(); } public IEnumerable<BeerOnTap> GetBeersOnTap() { var taps = _tapRepository.GetAll(); return taps.Select(tap => CreateBeerOnTap(tap)); } public BeerOnTap GetBeerOnTap(string tapId) { var tap = _tapRepository.GetById(tapId); return CreateBeerOnTap(tap); } private BeerOnTap CreateBeerOnTap(Tap tap) { if (tap.HasKeg) { var keg = _kegRepository.GetById(tap.KegId); var beer = _beerRepository.GetById(keg.BeerId); var brewery = _breweryRepository.GetById(beer.BreweryId); var style = (string.IsNullOrEmpty(beer.StyleId)) ? null : _styleRepository.GetById(beer.StyleId); //TODO Maybe add a default color beer.Color = (null == style) ? string.Empty : style.Color; beer.Style = (null == style) ? string.Empty : style.Name; return new BeerOnTap() { Tap = tap, Keg = keg, Beer = beer, Brewery = brewery, Style = style }; } else { return new BeerOnTap() { Tap = tap }; } } public IEnumerable<Beer> GetByName(string name) { return _beerRepository.GetAllByName(name); } public IEnumerable<Beer> GetByBrewery(string breweryId) { return _beerRepository.GetByBreweryId(breweryId); } public Beer GetById(string id) { return _beerRepository.GetById(id); } [Transactional] public string CreateBeer(string name, double abv, double baScore, string styleId, string breweryId) { var id = string.Empty; id = _beerRepository.NextIdentity(); var beer = new Beer(id, name) { ABV = abv, BAScore = baScore, BreweryId = breweryId, RPScore = 0, StyleId = styleId }; _beerRepository.Add(beer); return id; } public IEnumerable<Beer> GetBeersByName(string name) { return _beerRepository.GetAllByName(name); } [Transactional] public void Save(Beer beer) { _beerRepository.Update(beer); } } }
34.658537
195
0.614356
[ "MIT" ]
Rightpoint/Pourcast
RightpointLabs.Pourcast.Application/Orchestrators/Concrete/BeerOrchestrator.cs
4,265
C#
// Generated class v2.50.0.0, don't modify using System; using System.Collections.Generic; using System.Collections.Specialized; using System.Linq; using System.Text; namespace NHtmlUnit.Javascript.Host.Css { public partial class CSSRule : NHtmlUnit.Javascript.SimpleScriptable { static CSSRule() { ObjectWrapper.RegisterWrapperCreator((com.gargoylesoftware.htmlunit.javascript.host.css.CSSRule o) => new CSSRule(o)); } public CSSRule(com.gargoylesoftware.htmlunit.javascript.host.css.CSSRule wrappedObject) : base(wrappedObject) {} public new com.gargoylesoftware.htmlunit.javascript.host.css.CSSRule WObj { get { return (com.gargoylesoftware.htmlunit.javascript.host.css.CSSRule)WrappedObject; } } public CSSRule() : this(new com.gargoylesoftware.htmlunit.javascript.host.css.CSSRule()) {} public System.Int16 Type { get { return WObj.getType(); } } public System.String CssText { get { return WObj.getCssText(); } set { WObj.setCssText(value); } } public NHtmlUnit.Javascript.Host.Css.CSSStyleSheet ParentStyleSheet { get { return ObjectWrapper.CreateWrapper<NHtmlUnit.Javascript.Host.Css.CSSStyleSheet>( WObj.getParentStyleSheet()); } } public NHtmlUnit.Javascript.Host.Css.CSSRule ParentRule { get { return ObjectWrapper.CreateWrapper<NHtmlUnit.Javascript.Host.Css.CSSRule>( WObj.getParentRule()); } } } }
23.662162
119
0.596231
[ "Apache-2.0" ]
HtmlUnit/NHtmlUnit
app/NHtmlUnit/Generated/Javascript/Host/Css/CSSRule.cs
1,751
C#
#region Information // Solution: Spark // Spark.Engine // File: ResourceJsonFormatter.cs // // Created: 07/12/2017 : 10:34 AM // // Modified By: Howard Edidin // Modified: 08/20/2017 : 2:04 PM #endregion namespace FhirOnAzure.Formatters { using System; using System.IO; using System.Net.Http; using System.Net.Http.Formatting; using System.Net.Http.Headers; using System.Threading.Tasks; using Hl7.Fhir.Model; using Task = System.Threading.Tasks.Task; public class ResourceJsonFormatter : MediaTypeFormatter { public ResourceJsonFormatter() { SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/json+fhir")); } public override bool CanReadType(Type type) { return type == typeof(Resource); } public override bool CanWriteType(Type type) { return false; } public override Task<object> ReadFromStreamAsync(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger) { return Task.Factory.StartNew(() => (object) null); } } }
24.375
107
0.635043
[ "MIT" ]
HowardEdidin/HL7-FHIR-ON-AZURE
Samples and SDK/Server/FhirOnAzureServer/Spark.Engine/Formatters/ResourceJsonFormatter.cs
1,172
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; namespace WebAPI.SLA { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddMvc(); } // 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(); } } }
27.658537
106
0.667549
[ "MIT" ]
tang-junjie/CorporateServiceRepository
CorporateServiceRepository/WebAPI.SLA/Startup.cs
1,136
C#
using System; using System.Collections.Specialized; using System.IO; using Microsoft.Extensions.DependencyInjection; using NetInteractor.Core; using NetInteractor.Core.Config; using NetInteractor.Core.WebAccessors; using Xunit; namespace NetInteractor.Test { public class MainTest { [Fact] public async void TestShop() { var config = ConfigFactory.DeserializeXml<InteractConfig>(File.ReadAllText(Path.Combine(AppContext.BaseDirectory, "Scripts", "Shop.config"))); var executor = new InterationExecutor(); var inputs = new NameValueCollection(); var result = await executor.ExecuteAsync(config, inputs); Assert.True(result.Ok, result.Message); } } }
26.413793
154
0.681462
[ "Apache-2.0" ]
kerryjiang/NetInteractor
test/NetInteractor.Test/MainTest.cs
766
C#
using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Diagnostics; using System.IO; using System.Linq; using System.Text; using System.Text.RegularExpressions; using SchemaZen.Library.Models.Comparers; namespace SchemaZen.Library.Models { public class Database { #region " Constructors " public Database(IList<string> filteredTypes = null) { Props.Add(new DbProp("COMPATIBILITY_LEVEL", "")); Props.Add(new DbProp("COLLATE", "")); Props.Add(new DbProp("AUTO_CLOSE", "")); Props.Add(new DbProp("AUTO_SHRINK", "")); Props.Add(new DbProp("ALLOW_SNAPSHOT_ISOLATION", "")); Props.Add(new DbProp("READ_COMMITTED_SNAPSHOT", "")); Props.Add(new DbProp("RECOVERY", "")); Props.Add(new DbProp("PAGE_VERIFY", "")); Props.Add(new DbProp("AUTO_CREATE_STATISTICS", "")); Props.Add(new DbProp("AUTO_UPDATE_STATISTICS", "")); Props.Add(new DbProp("AUTO_UPDATE_STATISTICS_ASYNC", "")); Props.Add(new DbProp("ANSI_NULL_DEFAULT", "")); Props.Add(new DbProp("ANSI_NULLS", "")); Props.Add(new DbProp("ANSI_PADDING", "")); Props.Add(new DbProp("ANSI_WARNINGS", "")); Props.Add(new DbProp("ARITHABORT", "")); Props.Add(new DbProp("CONCAT_NULL_YIELDS_NULL", "")); Props.Add(new DbProp("NUMERIC_ROUNDABORT", "")); Props.Add(new DbProp("QUOTED_IDENTIFIER", "")); Props.Add(new DbProp("RECURSIVE_TRIGGERS", "")); Props.Add(new DbProp("CURSOR_CLOSE_ON_COMMIT", "")); Props.Add(new DbProp("CURSOR_DEFAULT", "")); Props.Add(new DbProp("TRUSTWORTHY", "")); Props.Add(new DbProp("DB_CHAINING", "")); Props.Add(new DbProp("PARAMETERIZATION", "")); //Props.Add(new DbProp("DATE_CORRELATION_OPTIMIZATION", "")); // This has caused infinite loop for some reason filteredTypes = filteredTypes ?? new List<string>(); foreach (var filteredType in filteredTypes) { Dirs.Remove(filteredType); } } public Database(string name, IList<string> filteredTypes = null) : this(filteredTypes) { Name = name; } #endregion #region " Properties " public const string SqlWhitespaceOrCommentRegex = @"(?>(?:\s+|--.*?(?:\r|\n)|/\*.*?\*/))"; public const string SqlEnclosedIdentifierRegex = @"\[.+?\]"; public const string SqlQuotedIdentifierRegex = "\".+?\""; public const string SqlRegularIdentifierRegex = @"(?!\d)[\w@$#]+"; // see rules for regular identifiers here https://msdn.microsoft.com/en-us/library/ms175874.aspx public List<SqlAssembly> Assemblies { get; set; } = new List<SqlAssembly>(); public string Connection { get; set; } = ""; public string Server => new SqlConnectionStringBuilder(Connection).DataSource; public string DbName => new SqlConnectionStringBuilder(Connection).InitialCatalog; public List<Table> DataTables { get; set; } = new List<Table>(); public string ScriptPath { get; set; } = ""; public string DataDir { get; set; } = ""; public List<ForeignKey> ForeignKeys { get; set; } = new List<ForeignKey>(); public string Name { get; set; } public List<DbProp> Props { get; set; } = new List<DbProp>(); public List<Routine> Routines { get; set; } = new List<Routine>(); public List<Schema> Schemas { get; set; } = new List<Schema>(); public List<Synonym> Synonyms { get; set; } = new List<Synonym>(); public List<Table> TableTypes { get; set; } = new List<Table>(); public List<Table> Tables { get; set; } = new List<Table>(); public List<UserDefinedType> UserDefinedTypes { get; set; } = new List<UserDefinedType>(); public List<Role> Roles { get; set; } = new List<Role>(); public List<SqlUser> Users { get; set; } = new List<SqlUser>(); public List<Constraint> ViewIndexes { get; set; } = new List<Constraint>(); public List<Permission> Permissions { get; set; } = new List<Permission>(); public bool NoDependencies { get; set; } = true; public DbProp FindProp(string name) { return Props.FirstOrDefault(p => string.Equals(p.Name, name, StringComparison.CurrentCultureIgnoreCase)); } public Table FindTable(string name, string owner, bool isTableType = false) { return FindTableBase(isTableType ? TableTypes : Tables, name, owner); } private static Table FindTableBase(IEnumerable<Table> tables, string name, string owner) { return tables.FirstOrDefault(t => t.Name == name && t.Owner == owner); } public Constraint FindConstraint(string name) { return Tables.SelectMany(t => t.Constraints).FirstOrDefault(c => c.Name == name); } public ForeignKey FindForeignKey(string name, string owner) { return ForeignKeys.FirstOrDefault(fk => fk.Name == name && fk.Table.Owner == owner); } public Routine FindRoutine(string name, string schema) { return Routines.FirstOrDefault(r => r.Name == name && r.Owner == schema); } public SqlAssembly FindAssembly(string name) { return Assemblies.FirstOrDefault(a => a.Name == name); } public SqlUser FindUser(string name) { return Users.FirstOrDefault(u => string.Equals(u.Name, name, StringComparison.CurrentCultureIgnoreCase)); } public Constraint FindViewIndex(string name) { return ViewIndexes.FirstOrDefault(c => c.Name == name); } public Synonym FindSynonym(string name, string schema) { return Synonyms.FirstOrDefault(s => s.Name == name && s.Owner == schema); } public Permission FindPermission(string name) { return Permissions.FirstOrDefault(g => g.Name == name); } public List<Table> FindTablesRegEx(string pattern, string excludePattern = null) { return Tables.Where(t => FindTablesRegExPredicate(t, pattern, excludePattern)).ToList(); } private static bool FindTablesRegExPredicate(Table table, string pattern, string excludePattern) { var include = string.IsNullOrEmpty(pattern) || Regex.IsMatch(table.Name, pattern); var exclude = !string.IsNullOrEmpty(excludePattern) && Regex.IsMatch(table.Name, excludePattern); return include && !exclude; } public static HashSet<string> Dirs { get; } = new HashSet<string> { "user_defined_types", "tables", "foreign_keys", "assemblies", "functions", "procedures", "triggers", "views", "xmlschemacollections", "data", "roles", "users", "synonyms", "table_types", "schemas", "props", "permissions", "check_constraints", "defaults", "routines" }; public static string ValidTypes { get { return Dirs.Aggregate((x, y) => x + ", " + y); } } private void SetPropOnOff(string propName, object dbVal) { if (dbVal != DBNull.Value) { FindProp(propName).Value = (bool)dbVal ? "ON" : "OFF"; } } private void SetPropString(string propName, object dbVal) { if (dbVal != DBNull.Value) { FindProp(propName).Value = dbVal.ToString(); } } #endregion #region Load public void Load() { Tables.Clear(); TableTypes.Clear(); Routines.Clear(); ForeignKeys.Clear(); DataTables.Clear(); ViewIndexes.Clear(); Assemblies.Clear(); Users.Clear(); Synonyms.Clear(); Roles.Clear(); Permissions.Clear(); using (var cn = new SqlConnection(Connection)) { cn.Open(); using (var cm = cn.CreateCommand()) { LoadProps(cm); LoadSchemas(cm); LoadTables(cm); LoadUserDefinedTypes(cm); LoadColumns(cm); LoadColumnIdentities(cm); LoadColumnDefaults(cm); LoadColumnComputes(cm); LoadConstraintsAndIndexes(cm); LoadCheckConstraints(cm); LoadForeignKeys(cm); LoadRoutines(cm); LoadRoutinesDependencies(cm); LoadXmlSchemas(cm); LoadCLRAssemblies(cm); LoadUsersAndLogins(cm); LoadSynonyms(cm); LoadRoles(cm); LoadPermissions(cm); } } } private void LoadSynonyms(SqlCommand cm) { try { // get synonyms cm.CommandText = @" select object_schema_name(object_id) as schema_name, name as synonym_name, base_object_name from sys.synonyms"; using (var dr = cm.ExecuteReader()) { while (dr.Read()) { var synonym = new Synonym((string)dr["synonym_name"], (string)dr["schema_name"]); synonym.BaseObjectName = (string)dr["base_object_name"]; Synonyms.Add(synonym); } } } catch (SqlException) { // SQL server version doesn't support synonyms, nothing to do here } } private void LoadPermissions(SqlCommand cm) { try { // get permissions // based on http://sql-articles.com/scripts/script-to-retrieve-security-information-sql-server-2005-and-above/ cm.CommandText = @" select U.name as user_name, state_desc, permission_name as permission, isnull(object_name(major_id), '') as object_name from sys.database_permissions inner join sys.sysusers U on grantee_principal_id = uid where U.issqluser = 1 and permission_name not like 'CONNECT' "; using (var dr = cm.ExecuteReader()) { while (dr.Read()) { var permission = new Permission((string)dr["user_name"], (string)dr["object_name"], (string)dr["permission"], (string)dr["state_desc"]); Permissions.Add(permission); } } } catch (SqlException) { // SQL server version doesn't support synonyms, nothing to do here } } private void LoadRoles(SqlCommand cm) { //Roles are complicated. This was adapted from https://dbaeyes.wordpress.com/2013/04/19/fully-script-out-a-mssql-database-role/ cm.CommandText = @" create table #ScriptedRoles ( name nvarchar(255) not null , script nvarchar(max) ) insert into #ScriptedRoles select name , null as script from sys.database_principals where type = 'R' and name not in ( -- Ignore default roles, just look for custom ones 'db_accessadmin' , 'db_backupoperator' , 'db_datareader' , 'db_datawriter' , 'db_ddladmin' , 'db_denydatareader' , 'db_denydatawriter' , 'db_owner' , 'db_securityadmin' , 'public' ) while(exists(select 1 from #ScriptedRoles where script is null)) begin DECLARE @RoleName VARCHAR(255) SET @RoleName = (select top 1 name from #ScriptedRoles where script is null) -- Script out the Role DECLARE @roleDesc VARCHAR(MAX), @crlf VARCHAR(2) SET @crlf = CHAR(13) + CHAR(10) SET @roleDesc = 'CREATE ROLE [' + @roleName + ']' + @crlf + 'GO' + @crlf + @crlf SELECT @roleDesc = @roleDesc + CASE dp.state WHEN 'D' THEN 'DENY ' WHEN 'G' THEN 'GRANT ' WHEN 'R' THEN 'REVOKE ' WHEN 'W' THEN 'GRANT ' END + dp.permission_name + ' ' + CASE dp.class WHEN 0 THEN '' WHEN 1 THEN --table or column subset on the table CASE WHEN dp.major_id < 0 THEN + 'ON [sys].[' + OBJECT_NAME(dp.major_id) + '] ' ELSE + 'ON [' + (SELECT SCHEMA_NAME(schema_id) + '].[' + name FROM sys.objects WHERE object_id = dp.major_id) + -- optionally concatenate column names CASE WHEN MAX(dp.minor_id) > 0 THEN '] ([' + REPLACE( (SELECT name + '], [' FROM sys.columns WHERE object_id = dp.major_id AND column_id IN (SELECT minor_id FROM sys.database_permissions WHERE major_id = dp.major_id AND USER_NAME(grantee_principal_id) IN (@roleName) ) FOR XML PATH('') ) --replace final square bracket pair + '])', ', []', '') ELSE ']' END + ' ' END WHEN 3 THEN 'ON SCHEMA::[' + SCHEMA_NAME(dp.major_id) + '] ' WHEN 4 THEN 'ON ' + (SELECT RIGHT(type_desc, 4) + '::[' + name FROM sys.database_principals WHERE principal_id = dp.major_id) + '] ' WHEN 5 THEN 'ON ASSEMBLY::[' + (SELECT name FROM sys.assemblies WHERE assembly_id = dp.major_id) + '] ' WHEN 6 THEN 'ON TYPE::[' + (SELECT name FROM sys.types WHERE user_type_id = dp.major_id) + '] ' WHEN 10 THEN 'ON XML SCHEMA COLLECTION::[' + (SELECT SCHEMA_NAME(schema_id) + '.' + name FROM sys.xml_schema_collections WHERE xml_collection_id = dp.major_id) + '] ' WHEN 15 THEN 'ON MESSAGE TYPE::[' + (SELECT name FROM sys.service_message_types WHERE message_type_id = dp.major_id) + '] ' WHEN 16 THEN 'ON CONTRACT::[' + (SELECT name FROM sys.service_contracts WHERE service_contract_id = dp.major_id) + '] ' WHEN 17 THEN 'ON SERVICE::[' + (SELECT name FROM sys.services WHERE service_id = dp.major_id) + '] ' WHEN 18 THEN 'ON REMOTE SERVICE BINDING::[' + (SELECT name FROM sys.remote_service_bindings WHERE remote_service_binding_id = dp.major_id) + '] ' WHEN 19 THEN 'ON ROUTE::[' + (SELECT name FROM sys.routes WHERE route_id = dp.major_id) + '] ' WHEN 23 THEN 'ON FULLTEXT CATALOG::[' + (SELECT name FROM sys.fulltext_catalogs WHERE fulltext_catalog_id = dp.major_id) + '] ' WHEN 24 THEN 'ON SYMMETRIC KEY::[' + (SELECT name FROM sys.symmetric_keys WHERE symmetric_key_id = dp.major_id) + '] ' WHEN 25 THEN 'ON CERTIFICATE::[' + (SELECT name FROM sys.certificates WHERE certificate_id = dp.major_id) + '] ' WHEN 26 THEN 'ON ASYMMETRIC KEY::[' + (SELECT name FROM sys.asymmetric_keys WHERE asymmetric_key_id = dp.major_id) + '] ' END COLLATE SQL_Latin1_General_CP1_CI_AS + 'TO [' + @roleName + ']' + CASE dp.state WHEN 'W' THEN ' WITH GRANT OPTION' ELSE '' END + @crlf FROM sys.database_permissions dp WHERE USER_NAME(dp.grantee_principal_id) IN (@roleName) GROUP BY dp.state, dp.major_id, dp.permission_name, dp.class update #ScriptedRoles set script = @roleDesc where name = @RoleName end select name , script from #ScriptedRoles "; Role r = null; using (var dr = cm.ExecuteReader()) { while (dr.Read()) { r = new Role { Name = (string)dr["name"], Script = (string)dr["script"] }; Roles.Add(r); } } } private void LoadUsersAndLogins(SqlCommand cm) { // get users that have access to the database cm.CommandText = @" select dp.name as UserName, USER_NAME(drm.role_principal_id) as AssociatedDBRole, default_schema_name from sys.database_principals dp left outer join sys.database_role_members drm on dp.principal_id = drm.member_principal_id where (dp.type_desc = 'SQL_USER' or dp.type_desc = 'WINDOWS_USER') and dp.sid not in (0x00, 0x01) and dp.name not in ('dbo', 'guest') and dp.is_fixed_role = 0 order by dp.name"; SqlUser u = null; using (var dr = cm.ExecuteReader()) { while (dr.Read()) { if (u == null || u.Name != (string)dr["UserName"]) u = new SqlUser((string)dr["UserName"], (string)dr["default_schema_name"]); if (!(dr["AssociatedDBRole"] is DBNull)) u.DatabaseRoles.Add((string)dr["AssociatedDBRole"]); if (!Users.Contains(u)) Users.Add(u); } } try { // get sql logins cm.CommandText = @" select sp.name, sl.password_hash from sys.server_principals sp inner join sys.sql_logins sl on sp.principal_id = sl.principal_id and sp.type_desc = 'SQL_LOGIN' where sp.name not like '##%##' and sp.name != 'SA' order by sp.name"; using (var dr = cm.ExecuteReader()) { while (dr.Read()) { u = FindUser((string)dr["name"]); if (u != null && !(dr["password_hash"] is DBNull)) u.PasswordHash = (byte[])dr["password_hash"]; } } } catch (SqlException) { // SQL server version (i.e. Azure) doesn't support logins, nothing to do here } } private void LoadCLRAssemblies(SqlCommand cm) { try { // get CLR assemblies cm.CommandText = @"select a.name as AssemblyName, a.permission_set_desc, af.name as FileName, af.content from sys.assemblies a inner join sys.assembly_files af on a.assembly_id = af.assembly_id where a.is_user_defined = 1 order by a.name, af.file_id"; SqlAssembly a = null; using (var dr = cm.ExecuteReader()) { while (dr.Read()) { if (a == null || a.Name != (string)dr["AssemblyName"]) { a = new SqlAssembly((string)dr["permission_set_desc"], (string)dr["AssemblyName"]); } a.Files.Add(new KeyValuePair<string, byte[]>((string)dr["FileName"], (byte[])dr["content"])); if (!Assemblies.Contains(a)) Assemblies.Add(a); } } } catch (SqlException) { // SQL server version doesn't support CLR assemblies, nothing to do here } } private void LoadXmlSchemas(SqlCommand cm) { try { // get xml schemas cm.CommandText = @" select s.name as DBSchemaName, x.name as XMLSchemaCollectionName, xml_schema_namespace(s.name, x.name) as definition from sys.xml_schema_collections x inner join sys.schemas s on s.schema_id = x.schema_id where s.name != 'sys'"; using (var dr = cm.ExecuteReader()) { while (dr.Read()) { var r = new Routine((string)dr["DBSchemaName"], (string)dr["XMLSchemaCollectionName"], this) { Text = string.Format("CREATE XML SCHEMA COLLECTION {0}.{1} AS N'{2}'", dr["DBSchemaName"], dr["XMLSchemaCollectionName"], dr["definition"]), RoutineType = Routine.RoutineKind.XmlSchemaCollection }; Routines.Add(r); } } } catch (SqlException) { // SQL server version doesn't support XML schemas, nothing to do here } } private void LoadRoutines(SqlCommand cm) { //get routines cm.CommandText = @" select s.name as schemaName, o.name as routineName, o.type_desc, m.definition, m.uses_ansi_nulls, m.uses_quoted_identifier, isnull(s2.name, s3.name) as tableSchema, isnull(t.name, v.name) as tableName, tr.is_disabled as trigger_disabled from sys.sql_modules m inner join sys.objects o on m.object_id = o.object_id inner join sys.schemas s on s.schema_id = o.schema_id left join sys.triggers tr on m.object_id = tr.object_id left join sys.tables t on tr.parent_id = t.object_id left join sys.views v on tr.parent_id = v.object_id left join sys.schemas s2 on s2.schema_id = t.schema_id left join sys.schemas s3 on s3.schema_id = v.schema_id where objectproperty(o.object_id, 'IsMSShipped') = 0 order by o.name "; using (var dr = cm.ExecuteReader()) { while (dr.Read()) { var r = new Routine((string)dr["schemaName"], (string)dr["routineName"], this); r.Text = dr["definition"] is DBNull ? string.Empty : (string)dr["definition"]; r.AnsiNull = (bool)dr["uses_ansi_nulls"]; r.QuotedId = (bool)dr["uses_quoted_identifier"]; Routines.Add(r); switch ((string)dr["type_desc"]) { case "SQL_STORED_PROCEDURE": r.RoutineType = Routine.RoutineKind.Procedure; break; case "SQL_TRIGGER": r.RoutineType = Routine.RoutineKind.Trigger; r.RelatedTableName = (string)dr["tableName"]; r.RelatedTableSchema = (string)dr["tableSchema"]; r.Disabled = (bool)dr["trigger_disabled"]; break; case "SQL_SCALAR_FUNCTION": case "SQL_INLINE_TABLE_VALUED_FUNCTION": case "SQL_TABLE_VALUED_FUNCTION": r.RoutineType = Routine.RoutineKind.Function; break; case "VIEW": r.RoutineType = Routine.RoutineKind.View; break; } } } } private void LoadRoutinesDependencies(SqlCommand cm) { if (NoDependencies) return; foreach (var routine in Routines) { cm.CommandText = @$" EXEC sp_MSdependencies '[{routine.Owner}].[{routine.Name}]', null, 1053183 "; using (var dr = cm.ExecuteReader()) { do { while (dr.Read()) { try { var owner = dr["oOwner"].ToString(); var name = dr["oObjName"].ToString(); var dependencyRoutine = Routines.FirstOrDefault(r => r.Owner == owner && r.Name == name); if (dependencyRoutine == null) continue; routine.Dependencies.Add(dependencyRoutine); } catch { } } } while (dr.NextResult()); } } } private void LoadCheckConstraints(SqlCommand cm) { cm.CommandText = @" SELECT OBJECT_NAME(o.OBJECT_ID) AS CONSTRAINT_NAME, SCHEMA_NAME(t.schema_id) AS TABLE_SCHEMA, OBJECT_NAME(o.parent_object_id) AS TABLE_NAME, CAST(0 AS bit) AS IS_TYPE, objectproperty(o.object_id, 'CnstIsNotRepl') AS NotForReplication, 'CHECK' AS ConstraintType, cc.definition as CHECK_CLAUSE, cc.is_system_named FROM sys.objects o inner join sys.check_constraints cc on cc.object_id = o.object_id inner join sys.tables t on t.object_id = o.parent_object_id WHERE o.type_desc = 'CHECK_CONSTRAINT' UNION ALL SELECT OBJECT_NAME(o.OBJECT_ID) AS CONSTRAINT_NAME, SCHEMA_NAME(tt.schema_id) AS TABLE_SCHEMA, tt.name AS TABLE_NAME, CAST(1 AS bit) AS IS_TYPE, objectproperty(o.object_id, 'CnstIsNotRepl') AS NotForReplication, 'CHECK' AS ConstraintType, cc.definition as CHECK_CLAUSE, cc.is_system_named FROM sys.objects o inner join sys.check_constraints cc on cc.object_id = o.object_id inner join sys.table_types tt on tt.type_table_object_id = o.parent_object_id WHERE o.type_desc = 'CHECK_CONSTRAINT' ORDER BY TABLE_SCHEMA, TABLE_NAME, CONSTRAINT_NAME "; using (var dr = cm.ExecuteReader()) { while (dr.Read()) { var t = FindTable((string)dr["TABLE_NAME"], (string)dr["TABLE_SCHEMA"], (bool)dr["IS_TYPE"]); if (t != null) { var constraint = Constraint.CreateCheckedConstraint( (string)dr["CONSTRAINT_NAME"], Convert.ToBoolean(dr["NotForReplication"]), Convert.ToBoolean(dr["is_system_named"]), (string)dr["CHECK_CLAUSE"] ); t.AddConstraint(constraint); } } } } private void LoadForeignKeys(SqlCommand cm) { //get foreign keys cm.CommandText = @" select TABLE_SCHEMA, TABLE_NAME, CONSTRAINT_NAME from INFORMATION_SCHEMA.TABLE_CONSTRAINTS where CONSTRAINT_TYPE = 'FOREIGN KEY'"; using (var dr = cm.ExecuteReader()) { while (dr.Read()) { var t = FindTable((string)dr["TABLE_NAME"], (string)dr["TABLE_SCHEMA"]); var fk = new ForeignKey((string)dr["CONSTRAINT_NAME"]); fk.Table = t; ForeignKeys.Add(fk); } } //get foreign key props cm.CommandText = @" select CONSTRAINT_NAME, OBJECT_SCHEMA_NAME(fk.parent_object_id) as TABLE_SCHEMA, UPDATE_RULE, DELETE_RULE, fk.is_disabled, fk.is_system_named from INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS rc inner join sys.foreign_keys fk on rc.CONSTRAINT_NAME = fk.name and rc.CONSTRAINT_SCHEMA = OBJECT_SCHEMA_NAME(fk.parent_object_id)"; using (var dr = cm.ExecuteReader()) { while (dr.Read()) { var fk = FindForeignKey((string)dr["CONSTRAINT_NAME"], (string)dr["TABLE_SCHEMA"]); fk.OnUpdate = (string)dr["UPDATE_RULE"]; fk.OnDelete = (string)dr["DELETE_RULE"]; fk.Check = !(bool)dr["is_disabled"]; fk.IsSystemNamed = (bool)dr["is_system_named"]; } } //get foreign key columns and ref table cm.CommandText = @" select fk.name as CONSTRAINT_NAME, OBJECT_SCHEMA_NAME(fk.parent_object_id) as TABLE_SCHEMA, c1.name as COLUMN_NAME, OBJECT_SCHEMA_NAME(fk.referenced_object_id) as REF_TABLE_SCHEMA, OBJECT_NAME(fk.referenced_object_id) as REF_TABLE_NAME, c2.name as REF_COLUMN_NAME from sys.foreign_keys fk inner join sys.foreign_key_columns fkc on fkc.constraint_object_id = fk.object_id inner join sys.columns c1 on fkc.parent_column_id = c1.column_id and fkc.parent_object_id = c1.object_id inner join sys.columns c2 on fkc.referenced_column_id = c2.column_id and fkc.referenced_object_id = c2.object_id order by fk.name, fkc.constraint_column_id "; using (var dr = cm.ExecuteReader()) { while (dr.Read()) { var fk = FindForeignKey((string)dr["CONSTRAINT_NAME"], (string)dr["TABLE_SCHEMA"]); if (fk == null) { continue; } fk.Columns.Add((string)dr["COLUMN_NAME"]); fk.RefColumns.Add((string)dr["REF_COLUMN_NAME"]); if (fk.RefTable == null) { fk.RefTable = FindTable((string)dr["REF_TABLE_NAME"], (string)dr["REF_TABLE_SCHEMA"]); } } } } private void LoadConstraintsAndIndexes(SqlCommand cm) { //get constraints & indexes cm.CommandText = @" select s.name as schemaName, t.name as tableName, t.baseType, i.name as indexName, c.name as columnName, i.is_primary_key, i.is_unique_constraint, i.is_unique, i.type_desc, i.filter_definition, isnull(ic.is_included_column, 0) as is_included_column, ic.is_descending_key, i.type from ( select object_id, name, schema_id, 'T' as baseType from sys.tables union select object_id, name, schema_id, 'V' as baseType from sys.views union select type_table_object_id, name, schema_id, 'TVT' as baseType from sys.table_types ) t inner join sys.indexes i on i.object_id = t.object_id inner join sys.index_columns ic on ic.object_id = t.object_id and ic.index_id = i.index_id inner join sys.columns c on c.object_id = t.object_id and c.column_id = ic.column_id inner join sys.schemas s on s.schema_id = t.schema_id where i.type_desc != 'HEAP' order by s.name, t.name, i.name, ic.key_ordinal, ic.index_column_id"; using (var dr = cm.ExecuteReader()) { while (dr.Read()) { var schemaName = (string)dr["schemaName"]; var tableName = (string)dr["tableName"]; var indexName = (string)dr["indexName"]; var isView = (string)dr["baseType"] == "V"; var t = isView ? new Table(schemaName, tableName) : FindTable(tableName, schemaName, (string)dr["baseType"] == "TVT"); var c = t.FindConstraint(indexName); if (c == null) { c = new Constraint(indexName, "", ""); t.AddConstraint(c); } if (isView) { if (ViewIndexes.Any(v => v.Name == indexName)) { c = ViewIndexes.First(v => v.Name == indexName); } else { ViewIndexes.Add(c); } } c.IndexType = dr["type_desc"] as string; c.Unique = (bool)dr["is_unique"]; c.Filter = dr["filter_definition"] as string; if ((bool)dr["is_included_column"]) { c.IncludedColumns.Add((string)dr["columnName"]); } else { c.Columns.Add(new ConstraintColumn((string)dr["columnName"], (bool)dr["is_descending_key"])); } c.Type = "INDEX"; if ((bool)dr["is_primary_key"]) c.Type = "PRIMARY KEY"; if ((bool)dr["is_unique_constraint"]) c.Type = "UNIQUE"; } } } private void LoadColumnComputes(SqlCommand cm) { //get computed column definitions cm.CommandText = @" select object_schema_name(t.object_id) as TABLE_SCHEMA, object_name(t.object_id) as TABLE_NAME, cc.name as COLUMN_NAME, cc.definition as DEFINITION, cc.is_persisted as PERSISTED, cc.is_nullable as NULLABLE, cast(0 as bit) as IS_TYPE from sys.computed_columns cc inner join sys.tables t on cc.object_id = t.object_id UNION ALL select SCHEMA_NAME(tt.schema_id) as TABLE_SCHEMA, tt.name as TABLE_NAME, cc.name as COLUMN_NAME, cc.definition as DEFINITION, cc.is_persisted as PERSISTED, cc.is_nullable as NULLABLE, cast(1 as bit) AS IS_TYPE from sys.computed_columns cc inner join sys.table_types tt on cc.object_id = tt.type_table_object_id "; using (var dr = cm.ExecuteReader()) { while (dr.Read()) { var t = FindTable((string)dr["TABLE_NAME"], (string)dr["TABLE_SCHEMA"], (bool)dr["IS_TYPE"]); if (t != null) { var column = t.Columns.Find((string)dr["COLUMN_NAME"]); if (column != null) { column.ComputedDefinition = (string)dr["DEFINITION"]; column.Persisted = (bool)dr["PERSISTED"]; } } } } } private void LoadColumnDefaults(SqlCommand cm) { //get column defaults cm.CommandText = @" select s.name as TABLE_SCHEMA, t.name as TABLE_NAME, c.name as COLUMN_NAME, d.name as DEFAULT_NAME, d.definition as DEFAULT_VALUE, d.is_system_named as IS_SYSTEM_NAMED, cast(0 AS bit) AS IS_TYPE from sys.tables t inner join sys.columns c on c.object_id = t.object_id inner join sys.default_constraints d on c.column_id = d.parent_column_id and d.parent_object_id = c.object_id inner join sys.schemas s on s.schema_id = t.schema_id UNION ALL select s.name as TABLE_SCHEMA, tt.name as TABLE_NAME, c.name as COLUMN_NAME, d.name as DEFAULT_NAME, d.definition as DEFAULT_VALUE, d.is_system_named as IS_SYSTEM_NAMED, cast(1 AS bit) AS IS_TYPE from sys.table_types tt inner join sys.columns c on c.object_id = tt.type_table_object_id inner join sys.default_constraints d on c.column_id = d.parent_column_id and d.parent_object_id = c.object_id inner join sys.schemas s on s.schema_id = tt.schema_id "; using (var dr = cm.ExecuteReader()) { while (dr.Read()) { var t = FindTable((string)dr["TABLE_NAME"], (string)dr["TABLE_SCHEMA"], (bool)dr["IS_TYPE"]); if (t != null) { var c = t.Columns.Find((string)dr["COLUMN_NAME"]); if (c != null) { c.Default = new Default(t, c, (string)dr["DEFAULT_NAME"], (string)dr["DEFAULT_VALUE"], (bool)dr["IS_SYSTEM_NAMED"]); } } } } } private void LoadColumnIdentities(SqlCommand cm) { //get column identities cm.CommandText = @" select s.name as TABLE_SCHEMA, t.name as TABLE_NAME, c.name AS COLUMN_NAME, i.SEED_VALUE, i.INCREMENT_VALUE from sys.tables t inner join sys.columns c on c.object_id = t.object_id inner join sys.identity_columns i on i.object_id = c.object_id and i.column_id = c.column_id inner join sys.schemas s on s.schema_id = t.schema_id "; using (var dr = cm.ExecuteReader()) { while (dr.Read()) { try { var t = FindTable((string)dr["TABLE_NAME"], (string)dr["TABLE_SCHEMA"]); var c = t.Columns.Find((string)dr["COLUMN_NAME"]); var seed = dr["SEED_VALUE"].ToString(); var increment = dr["INCREMENT_VALUE"].ToString(); c.Identity = new Identity(seed, increment); } catch (Exception ex) { throw new ApplicationException( string.Format("{0}.{1} : {2}", dr["TABLE_SCHEMA"], dr["TABLE_NAME"], ex.Message), ex); } } } } private void LoadColumns(SqlCommand cm) { //get columns cm.CommandText = @" select t.TABLE_SCHEMA, c.TABLE_NAME, c.COLUMN_NAME, c.DATA_TYPE, c.ORDINAL_POSITION, c.IS_NULLABLE, c.CHARACTER_MAXIMUM_LENGTH, c.NUMERIC_PRECISION, c.NUMERIC_SCALE, CASE WHEN COLUMNPROPERTY(OBJECT_ID(c.TABLE_SCHEMA + '.' + c.TABLE_NAME), c.COLUMN_NAME, 'IsRowGuidCol') = 1 THEN 'YES' ELSE 'NO' END AS IS_ROW_GUID_COL from INFORMATION_SCHEMA.COLUMNS c inner join INFORMATION_SCHEMA.TABLES t on t.TABLE_NAME = c.TABLE_NAME and t.TABLE_SCHEMA = c.TABLE_SCHEMA and t.TABLE_CATALOG = c.TABLE_CATALOG where t.TABLE_TYPE = 'BASE TABLE' order by t.TABLE_SCHEMA, c.TABLE_NAME, c.ORDINAL_POSITION "; using (var dr = cm.ExecuteReader()) { LoadColumnsBase(dr, Tables); } try { cm.CommandText = @" select s.name as TABLE_SCHEMA, tt.name as TABLE_NAME, c.name as COLUMN_NAME, t.name as DATA_TYPE, c.column_id as ORDINAL_POSITION, CASE WHEN c.is_nullable = 1 THEN 'YES' ELSE 'NO' END as IS_NULLABLE, CASE WHEN t.name = 'nvarchar' and c.max_length > 0 THEN CAST(c.max_length as int)/2 ELSE CAST(c.max_length as int) END as CHARACTER_MAXIMUM_LENGTH, c.precision as NUMERIC_PRECISION, CAST(c.scale as int) as NUMERIC_SCALE, CASE WHEN c.is_rowguidcol = 1 THEN 'YES' ELSE 'NO' END as IS_ROW_GUID_COL from sys.columns c inner join sys.table_types tt on tt.type_table_object_id = c.object_id inner join sys.schemas s on tt.schema_id = s.schema_id inner join sys.types t on t.system_type_id = c.system_type_id and t.user_type_id = c.user_type_id where tt.is_user_defined = 1 order by s.name, tt.name, c.column_id "; using (var dr = cm.ExecuteReader()) { LoadColumnsBase(dr, TableTypes); } } catch (SqlException) { // SQL server version doesn't support table types, nothing to do } } private static void LoadColumnsBase(IDataReader dr, List<Table> tables) { Table table = null; while (dr.Read()) { var c = new Column { Name = (string)dr["COLUMN_NAME"], Type = (string)dr["DATA_TYPE"], IsNullable = (string)dr["IS_NULLABLE"] == "YES", Position = (int)dr["ORDINAL_POSITION"], IsRowGuidCol = (string)dr["IS_ROW_GUID_COL"] == "YES" }; switch (c.Type) { case "binary": case "char": case "nchar": case "nvarchar": case "varbinary": case "varchar": c.Length = (int)dr["CHARACTER_MAXIMUM_LENGTH"]; break; case "decimal": case "numeric": c.Precision = (byte)dr["NUMERIC_PRECISION"]; c.Scale = (int)dr["NUMERIC_SCALE"]; break; } if (table == null || table.Name != (string)dr["TABLE_NAME"] || table.Owner != (string)dr["TABLE_SCHEMA"]) // only do a lookup if the table we have isn't already the relevant one { table = FindTableBase(tables, (string)dr["TABLE_NAME"], (string)dr["TABLE_SCHEMA"]); } table.Columns.Add(c); } } private void LoadTables(SqlCommand cm) { //get tables cm.CommandText = @" select TABLE_SCHEMA, TABLE_NAME from INFORMATION_SCHEMA.TABLES where TABLE_TYPE = 'BASE TABLE'"; using (var dr = cm.ExecuteReader()) { LoadTablesBase(dr, false, Tables); } //get table types try { cm.CommandText = @" select s.name as TABLE_SCHEMA, tt.name as TABLE_NAME from sys.table_types tt inner join sys.schemas s on tt.schema_id = s.schema_id where tt.is_user_defined = 1 order by s.name, tt.name"; using (var dr = cm.ExecuteReader()) { LoadTablesBase(dr, true, TableTypes); } } catch (SqlException) { // SQL server version doesn't support table types, nothing to do here } } private void LoadUserDefinedTypes(SqlCommand cm) { //get types cm.CommandText = @" select s.name as 'Type_Schema', t.name as 'Type_Name', tt.name as 'Base_Type_Name', t.max_length as 'Max_Length', t.is_nullable as 'Nullable' from sys.types t inner join sys.schemas s on s.schema_id = t.schema_id inner join sys.types tt on t.system_type_id = tt.user_type_id where t.is_user_defined = 1 and t.is_table_type = 0"; using (var dr = cm.ExecuteReader()) { LoadUserDefinedTypesBase(dr, UserDefinedTypes); } } private void LoadUserDefinedTypesBase(SqlDataReader dr, List<UserDefinedType> userDefinedTypes) { while (dr.Read()) { userDefinedTypes.Add(new UserDefinedType((string)dr["Type_Schema"], (string)dr["Type_Name"], (string)dr["Base_Type_Name"], Convert.ToInt16(dr["Max_Length"]), (bool)dr["Nullable"])); } } private static void LoadTablesBase(SqlDataReader dr, bool areTableTypes, List<Table> tables) { while (dr.Read()) { tables.Add(new Table((string)dr["TABLE_SCHEMA"], (string)dr["TABLE_NAME"]) { IsType = areTableTypes }); } } private void LoadSchemas(SqlCommand cm) { //get schemas cm.CommandText = @" select s.name as schemaName, p.name as principalName from sys.schemas s inner join sys.database_principals p on s.principal_id = p.principal_id where s.schema_id < 16384 and s.name not in ('dbo','guest','sys','INFORMATION_SCHEMA') order by schema_id "; using (var dr = cm.ExecuteReader()) { while (dr.Read()) { Schemas.Add(new Schema((string)dr["schemaName"], (string)dr["principalName"])); } } } private void LoadProps(SqlCommand cm) { var cnStrBuilder = new SqlConnectionStringBuilder(Connection); // query schema for database properties cm.CommandText = @" select [compatibility_level], [collation_name], [is_auto_close_on], [is_auto_shrink_on], [snapshot_isolation_state], [is_read_committed_snapshot_on], [recovery_model_desc], [page_verify_option_desc], [is_auto_create_stats_on], [is_auto_update_stats_on], [is_auto_update_stats_async_on], [is_ansi_null_default_on], [is_ansi_nulls_on], [is_ansi_padding_on], [is_ansi_warnings_on], [is_arithabort_on], [is_concat_null_yields_null_on], [is_numeric_roundabort_on], [is_quoted_identifier_on], [is_recursive_triggers_on], [is_cursor_close_on_commit_on], [is_local_cursor_default], [is_trustworthy_on], [is_db_chaining_on], [is_parameterization_forced], [is_date_correlation_on] from sys.databases where name = @dbname "; cm.Parameters.AddWithValue("@dbname", cnStrBuilder.InitialCatalog); using (IDataReader dr = cm.ExecuteReader()) { if (dr.Read()) { SetPropString("COMPATIBILITY_LEVEL", dr["compatibility_level"]); SetPropString("COLLATE", dr["collation_name"]); SetPropOnOff("AUTO_CLOSE", dr["is_auto_close_on"]); SetPropOnOff("AUTO_SHRINK", dr["is_auto_shrink_on"]); if (dr["snapshot_isolation_state"] != DBNull.Value) { FindProp("ALLOW_SNAPSHOT_ISOLATION").Value = (byte)dr["snapshot_isolation_state"] == 0 || (byte)dr["snapshot_isolation_state"] == 2 ? "OFF" : "ON"; } SetPropOnOff("READ_COMMITTED_SNAPSHOT", dr["is_read_committed_snapshot_on"]); SetPropString("RECOVERY", dr["recovery_model_desc"]); SetPropString("PAGE_VERIFY", dr["page_verify_option_desc"]); SetPropOnOff("AUTO_CREATE_STATISTICS", dr["is_auto_create_stats_on"]); SetPropOnOff("AUTO_UPDATE_STATISTICS", dr["is_auto_update_stats_on"]); SetPropOnOff("AUTO_UPDATE_STATISTICS_ASYNC", dr["is_auto_update_stats_async_on"]); SetPropOnOff("ANSI_NULL_DEFAULT", dr["is_ansi_null_default_on"]); SetPropOnOff("ANSI_NULLS", dr["is_ansi_nulls_on"]); SetPropOnOff("ANSI_PADDING", dr["is_ansi_padding_on"]); SetPropOnOff("ANSI_WARNINGS", dr["is_ansi_warnings_on"]); SetPropOnOff("ARITHABORT", dr["is_arithabort_on"]); SetPropOnOff("CONCAT_NULL_YIELDS_NULL", dr["is_concat_null_yields_null_on"]); SetPropOnOff("NUMERIC_ROUNDABORT", dr["is_numeric_roundabort_on"]); SetPropOnOff("QUOTED_IDENTIFIER", dr["is_quoted_identifier_on"]); SetPropOnOff("RECURSIVE_TRIGGERS", dr["is_recursive_triggers_on"]); SetPropOnOff("CURSOR_CLOSE_ON_COMMIT", dr["is_cursor_close_on_commit_on"]); if (dr["is_local_cursor_default"] != DBNull.Value) { FindProp("CURSOR_DEFAULT").Value = (bool)dr["is_local_cursor_default"] ? "LOCAL" : "GLOBAL"; } SetPropOnOff("TRUSTWORTHY", dr["is_trustworthy_on"]); SetPropOnOff("DB_CHAINING", dr["is_db_chaining_on"]); if (dr["is_parameterization_forced"] != DBNull.Value) { FindProp("PARAMETERIZATION").Value = (bool)dr["is_parameterization_forced"] ? "FORCED" : "SIMPLE"; } //SetPropOnOff("DATE_CORRELATION_OPTIMIZATION", dr["is_date_correlation_on"]); } } } #endregion #region Compare public DatabaseDiff Compare(Database db) { var diff = new DatabaseDiff { Db = db }; if (Dirs.Contains("props")) { //compare database properties foreach (var p in from p in Props let p2 = db.FindProp(p.Name) where p.Script() != p2.Script() select p) { diff.PropsChanged.Add(p); } } if (Dirs.Contains("tables")) { //get tables added and changed foreach (var tables in new[] { Tables, TableTypes }) { foreach (var t in tables) { var t2 = db.FindTable(t.Name, t.Owner, t.IsType); if (t2 == null) { diff.TablesAdded.Add(t); } else { //compare mutual tables var tDiff = t.Compare(t2); if (!tDiff.IsDiff) continue; if (t.IsType) { // types cannot be altered... diff.TableTypesDiff.Add(t); } else { diff.TablesDiff.Add(tDiff); } } } } //get deleted tables foreach (var t in db.Tables.Concat(db.TableTypes) .Where(t => FindTable(t.Name, t.Owner, t.IsType) == null)) { diff.TablesDeleted.Add(t); } } if (Dirs.Contains("routines") || Dirs.Contains("procedures") && Dirs.Contains("functions") && Dirs.Contains("views")) { //get procs added and changed foreach (var r in Routines) { var r2 = db.FindRoutine(r.Name, r.Owner); if (r2 == null) { diff.RoutinesAdded.Add(r); } else { //compare mutual procs if (r.Text.Trim() != r2.Text.Trim()) { diff.RoutinesDiff.Add(r); } } } //get procs deleted foreach (var r in db.Routines.Where(r => FindRoutine(r.Name, r.Owner) == null)) { diff.RoutinesDeleted.Add(r); } } if (Dirs.Contains("foreign_keys")) { //get added and compare mutual foreign keys foreach (var fk in ForeignKeys) { var fk2 = db.FindForeignKey(fk.Name, fk.Table.Owner); if (fk2 == null) { diff.ForeignKeysAdded.Add(fk); } else { if (fk.ScriptCreate() != fk2.ScriptCreate()) { diff.ForeignKeysDiff.Add(fk); } } } //get deleted foreign keys foreach (var fk in db.ForeignKeys.Where(fk => FindForeignKey(fk.Name, fk.Table.Owner) == null)) { diff.ForeignKeysDeleted.Add(fk); } } if (Dirs.Contains("assemblies")) { //get added and compare mutual assemblies foreach (var a in Assemblies) { var a2 = db.FindAssembly(a.Name); if (a2 == null) { diff.AssembliesAdded.Add(a); } else { if (a.ScriptCreate() != a2.ScriptCreate()) { diff.AssembliesDiff.Add(a); } } } //get deleted assemblies foreach (var a in db.Assemblies.Where(a => FindAssembly(a.Name) == null)) { diff.AssembliesDeleted.Add(a); } } if (Dirs.Contains("users")) { //get added and compare mutual users foreach (var u in Users) { var u2 = db.FindUser(u.Name); if (u2 == null) { diff.UsersAdded.Add(u); } else { if (u.ScriptCreate() != u2.ScriptCreate()) { diff.UsersDiff.Add(u); } } } //get deleted users foreach (var u in db.Users.Where(u => FindUser(u.Name) == null)) { diff.UsersDeleted.Add(u); } //get added and compare view indexes foreach (var c in ViewIndexes) { var c2 = db.FindViewIndex(c.Name); if (c2 == null) { diff.ViewIndexesAdded.Add(c); } else { if (c.ScriptCreate() != c2.ScriptCreate()) { diff.ViewIndexesDiff.Add(c); } } } //get deleted view indexes foreach (var c in db.ViewIndexes.Where(c => FindViewIndex(c.Name) == null)) { diff.ViewIndexesDeleted.Add(c); } } if (Dirs.Contains("synonyms")) { //get added and compare synonyms foreach (var s in Synonyms) { var s2 = db.FindSynonym(s.Name, s.Owner); if (s2 == null) { diff.SynonymsAdded.Add(s); } else { if (s.BaseObjectName != s2.BaseObjectName) { diff.SynonymsDiff.Add(s); } } } //get deleted synonyms foreach (var s in db.Synonyms.Where(s => FindSynonym(s.Name, s.Owner) == null)) { diff.SynonymsDeleted.Add(s); } } if (Dirs.Contains("permissions")) { //get added and compare permissions foreach (var p in Permissions) { var p2 = db.FindPermission(p.Name); if (p2 == null) { diff.PermissionsAdded.Add(p); } else { if (p.ScriptCreate() != p2.ScriptCreate()) { diff.PermissionsDiff.Add(p); } } } //get deleted permissions foreach (var p in db.Permissions.Where(p => FindPermission(p.Name) == null)) { diff.PermissionsDeleted.Add(p); } } return diff; } #endregion #region Script public string ScriptCreate() { var text = new StringBuilder(); text.AppendFormat("CREATE DATABASE {0}", Name); text.AppendLine(); text.AppendLine("GO"); text.AppendFormat("USE {0}", Name); text.AppendLine(); text.AppendLine("GO"); text.AppendLine(); if (Props.Count > 0) { text.Append(ScriptPropList(Props)); text.AppendLine("GO"); text.AppendLine(); } foreach (var schema in Schemas) { text.AppendLine(schema.ScriptCreate()); text.AppendLine("GO"); text.AppendLine(); } foreach (var t in Tables.Concat(TableTypes)) { text.AppendLine(t.ScriptCreate()); foreach (var constraint in t.Constraints.Where(c => c.Type == "CHECK" && !c.ScriptInline)) { text.AppendLine(constraint.ScriptCreate()); } var defaults = ( from c in t.Columns.Items where c.Default != null select c.Default) .ToArray(); foreach (var def in defaults) { text.AppendLine(def.ScriptCreate()); } } text.AppendLine(); text.AppendLine("GO"); foreach (var fk in ForeignKeys.OrderBy(f => f, ForeignKeyComparer.Instance)) { text.AppendLine(fk.ScriptCreate()); } text.AppendLine(); text.AppendLine("GO"); foreach (var r in Routines) { text.AppendLine(r.ScriptCreate()); text.AppendLine(); text.AppendLine("GO"); } foreach (var a in Assemblies) { text.AppendLine(a.ScriptCreate()); text.AppendLine(); text.AppendLine("GO"); } foreach (var u in Users) { text.AppendLine(u.ScriptCreate()); text.AppendLine(); text.AppendLine("GO"); } foreach (var c in ViewIndexes) { text.AppendLine(c.ScriptCreate()); text.AppendLine(); text.AppendLine("GO"); } foreach (var s in Synonyms) { text.AppendLine(s.ScriptCreate()); text.AppendLine(); text.AppendLine("GO"); } return text.ToString(); } public void ScriptToDir(Action<TraceLevel, string> log = null, bool commentSections = true) { if (log == null) log = (tl, s) => { }; if (File.Exists(ScriptPath)) { // delete the existing script file log(TraceLevel.Verbose, "Deleting existing file..."); File.Delete(ScriptPath); log(TraceLevel.Verbose, "Existing file deleted."); } var text = new StringBuilder(); if (commentSections) text.AppendLine($"-- Always check the migration script before you apply it"); WritePropsScript(text, log, commentSections); if (commentSections) text.AppendLine($"-- users.sql"); WriteScriptDir(text, "users", Users.ToArray(), log); if (commentSections) text.AppendLine($"-- roles.sql"); WriteScriptDir(text, "roles", Roles.ToArray(), log); WriteSchemaScript(text, log, commentSections); if (commentSections) text.AppendLine($"-- tables.sql"); text.AppendLine("GO"); text.AppendLine("SET ANSI_NULLS ON"); text.AppendLine("GO"); WriteScriptDir(text, "tables", Tables.ToArray(), log); if (commentSections) text.AppendLine($"-- constraints_and_defaults.sql"); foreach (var table in Tables) { WriteScriptDir(text, "check_constraints", table.Constraints.Where(c => c.Type == "CHECK").ToArray(), log); var defaults = (from c in table.Columns.Items where c.Default != null select c.Default).ToArray(); if (defaults.Any()) { WriteScriptDir(text, "defaults", defaults, log); } } if (commentSections) text.AppendLine($"-- table_types.sql"); WriteScriptDir(text, "table_types", TableTypes.ToArray(), log); if (commentSections) text.AppendLine($"-- user_defined_types.sql"); WriteScriptDir(text, "user_defined_types", UserDefinedTypes.ToArray(), log); if (commentSections) text.AppendLine($"-- assemblies.sql"); WriteScriptDir(text, "assemblies", Assemblies.ToArray(), log); if (commentSections) text.AppendLine($"-- synonyms.sql"); WriteScriptDir(text, "synonyms", Synonyms.ToArray(), log); var doneRoutines = new List<Routine>(); if (commentSections) text.AppendLine($"-- functions and views.sql"); var functionsAndViews = Routines.Where(x => x.RoutineType == Routine.RoutineKind.Function || x.RoutineType == Routine.RoutineKind.View).ToList(); WriteRoutinesScript(text, functionsAndViews, routine => !Dirs.Contains("views") && routine.RoutineType == Routine.RoutineKind.View || !Dirs.Contains("functions") && routine.RoutineType == Routine.RoutineKind.Function, doneRoutines); if (Dirs.Contains("procedures")) { if (commentSections) text.AppendLine($"-- procedures.sql"); var procedures = Routines.Where(x => x.RoutineType == Routine.RoutineKind.Procedure).ToList(); WriteRoutinesScript(text, procedures, null, doneRoutines); } if (commentSections) text.AppendLine($"-- view indexes.sql"); WriteScriptDir(text, "view indexes", ViewIndexes.ToArray(), log); if (commentSections) text.AppendLine($"-- triggers.sql"); var triggers = Routines.Where(x => x.RoutineType == Routine.RoutineKind.Trigger); WriteScriptDir(text, "triggers", triggers.ToArray(), log); if (commentSections) text.AppendLine($"-- foreign_keys.sql"); WriteScriptDir(text, "foreign_keys", ForeignKeys.OrderBy(x => x, ForeignKeyComparer.Instance).ToArray(), log); if (commentSections) text.AppendLine($"-- permissions.sql"); WriteScriptDir(text, "permissions", Permissions.ToArray(), log); File.WriteAllText(ScriptPath, text.ToString(), Encoding.UTF8); } private void WritePropsScript(StringBuilder text, Action<TraceLevel, string> log, bool commentSections) { if (!Dirs.Contains("props")) return; log(TraceLevel.Verbose, "Scripting database properties..."); if (commentSections) text.AppendLine("-- props.sql"); text.Append(ScriptPropList(Props)); text.AppendLine(); } private void WriteSchemaScript(StringBuilder text, Action<TraceLevel, string> log, bool commentSections) { if (!Dirs.Contains("schemas")) return; log(TraceLevel.Verbose, "Scripting database schemas..."); if (commentSections) text.AppendLine("-- schemas.sql"); foreach (var schema in Schemas) { text.Append(schema.ScriptCreate()); } text.AppendLine(); } private void WriteRoutinesScript(StringBuilder text, List<Routine> routines, Func<Routine, bool> check, List<Routine> done) { for (var i = 0; i < routines.Count; i++) { var routine = routines[i]; if (check?.Invoke(routine) ?? false) continue; if (!routine.Dependencies.Any() || !routine.Dependencies.Except(done).Any()) { text.AppendLine(routine.ScriptCreate()); text.AppendLine(); text.AppendLine("GO"); text.AppendLine(); done.Add(routine); } else { routines.RemoveAt(i); routines.Add(routine); i--; } } } private void WriteScriptDir(StringBuilder text, string name, ICollection<IScriptable> objects, Action<TraceLevel, string> log) { if (!objects.Any()) return; if (!Dirs.Contains(name)) return; var index = 0; foreach (var o in objects) { log(TraceLevel.Verbose, $"Scripting {name} {++index} of {objects.Count}...{(index < objects.Count ? "\r" : string.Empty)}"); var script = o.ScriptCreate(); text.AppendLine(script); text.AppendLine("GO"); } } private static string MakeFileName(object o) { // combine foreign keys into one script per table var fk = o as ForeignKey; if (fk != null) return MakeFileName(fk.Table); // combine defaults into one script per table if (o is Default) { return MakeFileName((o as Default).Table); } // combine check constraints into one script per table if (o is Constraint && (o as Constraint).Type == "CHECK") { return MakeFileName((o as Constraint).Table); } var schema = o as IHasOwner == null ? "" : (o as IHasOwner).Owner; var name = o as INameable == null ? "" : (o as INameable).Name; var fileName = MakeFileName(schema, name); // prefix user defined types with TYPE_ var prefix = o as Table == null ? "" : (o as Table).IsType ? "TYPE_" : ""; return string.Concat(prefix, fileName); } private static string MakeFileName(string schema, string name) { // Dont' include schema name for objects in the dbo schema. // This maintains backward compatability for those who use // SchemaZen to keep their schemas under version control. var fileName = name; if (!string.IsNullOrEmpty(schema) && schema.ToLower() != "dbo") { fileName = $"{schema}.{name}"; } return Path.GetInvalidFileNameChars().Aggregate(fileName, (current, invalidChar) => current.Replace(invalidChar, '-')); } public void ExportData(string tableHint = null, Action<TraceLevel, string> log = null) { if (!DataTables.Any()) return; var dataDir = Path.Combine(DataDir, "data"); if (!Directory.Exists(dataDir)) { Directory.CreateDirectory(dataDir); } log?.Invoke(TraceLevel.Info, "Exporting data..."); var index = 0; foreach (var t in DataTables) { log?.Invoke(TraceLevel.Verbose, $"Exporting data from {t.Owner + "." + t.Name} (table {++index} of {DataTables.Count})..."); var filePathAndName = dataDir + "/" + MakeFileName(t) + ".tsv"; var sw = File.CreateText(filePathAndName); t.ExportData(Connection, sw, tableHint); sw.Flush(); if (sw.BaseStream.Length == 0) { log?.Invoke(TraceLevel.Verbose, $" No data to export for {t.Owner + "." + t.Name}, deleting file..."); sw.Close(); File.Delete(filePathAndName); } else { sw.Close(); } } } public static string ScriptPropList(IList<DbProp> props) { var text = new StringBuilder(); text.AppendLine("DECLARE @DB VARCHAR(255)"); text.AppendLine("SET @DB = DB_NAME()"); foreach (var p in props.Select(p => p.Script()).Where(p => !string.IsNullOrEmpty(p))) { text.AppendLine(p); } return text.ToString(); } #endregion #region Create public void ImportData(Action<TraceLevel, string> log = null, bool overwrite = false) { if (log == null) log = (tl, s) => { }; var dataDir = DataDir + "\\data"; if (!Directory.Exists(dataDir)) { log(TraceLevel.Verbose, "No data to import."); return; } log(TraceLevel.Verbose, "Loading database schema..."); Load(); // load the schema first so we can import data log(TraceLevel.Verbose, "Database schema loaded."); log(TraceLevel.Info, "Importing data..."); foreach (var f in Directory.GetFiles(dataDir)) { var fi = new FileInfo(f); var schema = "dbo"; var table = Path.GetFileNameWithoutExtension(fi.Name); if (table.Contains(".")) { schema = fi.Name.Split('.')[0]; table = fi.Name.Split('.')[1]; } var t = FindTable(table, schema); if (t == null) { log(TraceLevel.Warning, $"Warning: found data file '{fi.Name}', but no corresponding table in database..."); continue; } try { log(TraceLevel.Verbose, $"Importing data for table {schema}.{table}..."); t.ImportData(Connection, fi.FullName, overwrite); } catch (SqlBatchException ex) { throw new DataFileException(ex.Message, fi.FullName, ex.LineNumber); } catch (Exception ex) { throw new DataFileException(ex.Message, fi.FullName, -1); } } log(TraceLevel.Info, "Data imported successfully."); } public void CreateFromDir(bool overwrite, string databaseFilesPath = null, Action<TraceLevel, string> log = null) { if (log == null) log = (tl, s) => { }; if (DBHelper.DbExists(Connection)) { log(TraceLevel.Verbose, "Dropping existing database..."); DBHelper.DropDb(Connection); log(TraceLevel.Verbose, "Existing database dropped."); } log(TraceLevel.Info, "Creating database..."); //create database DBHelper.CreateDb(Connection, databaseFilesPath); var createScript = File.ReadAllText(ScriptPath, Encoding.UTF8); // props var propsPart = createScript[createScript.IndexOf("-- props.sql")..createScript.IndexOf("-- users.sql")]; if (!string.IsNullOrWhiteSpace(propsPart)) { log(TraceLevel.Verbose, "Setting database properties..."); try { DBHelper.ExecBatchSql(Connection, propsPart); } catch (SqlBatchException ex) { throw new SqlFileException(ScriptPath + "/props.sql", ex); } // COLLATE can cause connection to be reset // so clear the pool so we get a new connection DBHelper.ClearPool(Connection); } // users var usersPart = createScript[createScript.IndexOf("-- users.sql")..createScript.IndexOf("-- roles.sql")]; if (!string.IsNullOrWhiteSpace(usersPart)) { log(TraceLevel.Info, "Adding users..."); try { DBHelper.ExecBatchSql(Connection, usersPart); } catch (SqlBatchException ex) { throw new SqlFileException("users", ex); } } // schemas var schemasPart = createScript[createScript.IndexOf("-- schemas.sql")..createScript.IndexOf("-- tables.sql")]; if (!string.IsNullOrWhiteSpace(schemasPart)) { log(TraceLevel.Verbose, "Creating database schemas..."); try { DBHelper.ExecBatchSql(Connection, schemasPart); } catch (SqlBatchException ex) { throw new SqlFileException("schemas", ex); } } log(TraceLevel.Info, "Creating database objects..."); // create db objects var allObjectsPart = createScript[createScript.IndexOf("-- tables.sql")..]; var errors = new List<SqlFileException>(); try { DBHelper.ExecBatchSql(Connection, allObjectsPart); } catch (SqlBatchException ex) { errors.Add(new SqlFileException("all other objects", ex)); //Console.WriteLine("Error occurred in {0}: {1}", f, ex); } //// resolve dependencies by trying over and over //// if the number of failures stops decreasing then give up //var scripts = GetScripts(); //var errors = new List<SqlFileException>(); //var prevCount = -1; //while (scripts.Count > 0 && (prevCount == -1 || errors.Count < prevCount)) { // if (errors.Count > 0) { // prevCount = errors.Count; // log(TraceLevel.Info, $"{errors.Count} errors occurred, retrying..."); // } // errors.Clear(); // var index = 0; // var total = scripts.Count; // foreach (var f in scripts.ToArray()) { // log(TraceLevel.Verbose, // $"Executing script {++index} of {total}...{(index < total ? "\r" : string.Empty)}"); // try { // DBHelper.ExecBatchSql(Connection, File.ReadAllText(f)); // scripts.Remove(f); // } catch (SqlBatchException ex) { // errors.Add(new SqlFileException(f, ex)); // //Console.WriteLine("Error occurred in {0}: {1}", f, ex); // } // } //} //if (prevCount > 0) { // log(TraceLevel.Info, // errors.Any() ? $"{prevCount} errors unresolved. Details will follow later." : // "All errors resolved, were probably dependency issues..."); //} //log(TraceLevel.Info, string.Empty); //ImportData(log); // load data //if (Directory.Exists(ScriptPath + "/after_data")) { // log(TraceLevel.Verbose, "Executing after-data scripts..."); // foreach (var f in Directory.GetFiles(ScriptPath + "/after_data", "*.sql")) { // try { // DBHelper.ExecBatchSql(Connection, File.ReadAllText(f)); // } catch (SqlBatchException ex) { // errors.Add(new SqlFileException(f, ex)); // } // } //} //// foreign keys //if (Directory.Exists(ScriptPath + "/foreign_keys")) { // log(TraceLevel.Info, "Adding foreign key constraints..."); // foreach (var f in Directory.GetFiles(ScriptPath + "/foreign_keys", "*.sql")) { // try { // DBHelper.ExecBatchSql(Connection, File.ReadAllText(f)); // } catch (SqlBatchException ex) { // //throw new SqlFileException(f, ex); // errors.Add(new SqlFileException(f, ex)); // } // } //} if (errors.Count > 0) { var ex = new BatchSqlFileException { Exceptions = errors }; throw ex; } } private List<string> GetScripts() { var scripts = new List<string>(); foreach ( var dirPath in Dirs.Where(dir => dir != "foreign_keys" && dir != "users") .Select(dir => ScriptPath + "/" + dir).Where(Directory.Exists)) { scripts.AddRange(Directory.GetFiles(dirPath, "*.sql")); } return scripts; } public void ExecCreate(bool dropIfExists) { var conStr = new SqlConnectionStringBuilder(Connection); var dbName = conStr.InitialCatalog; conStr.InitialCatalog = "master"; if (DBHelper.DbExists(Connection)) { if (dropIfExists) { DBHelper.DropDb(Connection); } else { throw new ApplicationException( $"Database {conStr.DataSource} {dbName} already exists."); } } DBHelper.ExecBatchSql(conStr.ToString(), ScriptCreate()); } #endregion } public class DatabaseDiff { public List<SqlAssembly> AssembliesAdded = new List<SqlAssembly>(); public List<SqlAssembly> AssembliesDeleted = new List<SqlAssembly>(); public List<SqlAssembly> AssembliesDiff = new List<SqlAssembly>(); public Database Db; public List<ForeignKey> ForeignKeysAdded = new List<ForeignKey>(); public List<ForeignKey> ForeignKeysDeleted = new List<ForeignKey>(); public List<ForeignKey> ForeignKeysDiff = new List<ForeignKey>(); public List<DbProp> PropsChanged = new List<DbProp>(); public List<Routine> RoutinesAdded = new List<Routine>(); public List<Routine> RoutinesDeleted = new List<Routine>(); public List<Routine> RoutinesDiff = new List<Routine>(); public List<Synonym> SynonymsAdded = new List<Synonym>(); public List<Synonym> SynonymsDeleted = new List<Synonym>(); public List<Synonym> SynonymsDiff = new List<Synonym>(); public List<Table> TablesAdded = new List<Table>(); public List<Table> TablesDeleted = new List<Table>(); public List<TableDiff> TablesDiff = new List<TableDiff>(); public List<Table> TableTypesDiff = new List<Table>(); public List<SqlUser> UsersAdded = new List<SqlUser>(); public List<SqlUser> UsersDeleted = new List<SqlUser>(); public List<SqlUser> UsersDiff = new List<SqlUser>(); public List<Constraint> ViewIndexesAdded = new List<Constraint>(); public List<Constraint> ViewIndexesDeleted = new List<Constraint>(); public List<Constraint> ViewIndexesDiff = new List<Constraint>(); public List<Permission> PermissionsAdded = new List<Permission>(); public List<Permission> PermissionsDeleted = new List<Permission>(); public List<Permission> PermissionsDiff = new List<Permission>(); public bool IsDiff => PropsChanged.Count > 0 || TablesAdded.Count > 0 || TablesDiff.Count > 0 || TableTypesDiff.Count > 0 || TablesDeleted.Count > 0 || RoutinesAdded.Count > 0 || RoutinesDiff.Count > 0 || RoutinesDeleted.Count > 0 || ForeignKeysAdded.Count > 0 || ForeignKeysDiff.Count > 0 || ForeignKeysDeleted.Count > 0 || AssembliesAdded.Count > 0 || AssembliesDiff.Count > 0 || AssembliesDeleted.Count > 0 || UsersAdded.Count > 0 || UsersDiff.Count > 0 || UsersDeleted.Count > 0 || ViewIndexesAdded.Count > 0 || ViewIndexesDiff.Count > 0 || ViewIndexesDeleted.Count > 0 || SynonymsAdded.Count > 0 || SynonymsDiff.Count > 0 || SynonymsDeleted.Count > 0 || PermissionsAdded.Count > 0 || PermissionsDiff.Count > 0 || PermissionsDeleted.Count > 0; private static string Summarize(bool includeNames, List<string> changes, string caption) { if (changes.Count == 0) return string.Empty; return changes.Count + "x " + caption + (includeNames ? "\r\n\t" + string.Join("\r\n\t", changes.ToArray()) : string.Empty) + "\r\n"; } public string SummarizeChanges(bool includeNames) { var sb = new StringBuilder(); sb.Append(Summarize(includeNames, AssembliesAdded.Select(o => o.Name).ToList(), "assemblies in source but not in target")); sb.Append(Summarize(includeNames, AssembliesDeleted.Select(o => o.Name).ToList(), "assemblies not in source but in target")); sb.Append(Summarize(includeNames, AssembliesDiff.Select(o => o.Name).ToList(), "assemblies altered")); sb.Append(Summarize(includeNames, ForeignKeysAdded.Select(o => o.Name).ToList(), "foreign keys in source but not in target")); sb.Append(Summarize(includeNames, ForeignKeysDeleted.Select(o => o.Name).ToList(), "foreign keys not in source but in target")); sb.Append(Summarize(includeNames, ForeignKeysDiff.Select(o => o.Name).ToList(), "foreign keys altered")); sb.Append(Summarize(includeNames, PropsChanged.Select(o => o.Name).ToList(), "properties changed")); sb.Append(Summarize(includeNames, RoutinesAdded.Select(o => $"{o.RoutineType.ToString()} {o.Owner}.{o.Name}") .ToList(), "routines in source but not in target")); sb.Append(Summarize(includeNames, RoutinesDeleted.Select(o => $"{o.RoutineType.ToString()} {o.Owner}.{o.Name}") .ToList(), "routines not in source but in target")); sb.Append(Summarize(includeNames, RoutinesDiff.Select(o => $"{o.RoutineType.ToString()} {o.Owner}.{o.Name}").ToList(), "routines altered")); sb.Append(Summarize(includeNames, TablesAdded.Where(o => !o.IsType).Select(o => $"{o.Owner}.{o.Name}").ToList(), "tables in source but not in target")); sb.Append(Summarize(includeNames, TablesDeleted.Where(o => !o.IsType).Select(o => $"{o.Owner}.{o.Name}").ToList(), "tables not in source but in target")); sb.Append(Summarize(includeNames, TablesDiff.Select(o => $"{o.Owner}.{o.Name}").ToList(), "tables altered")); sb.Append(Summarize(includeNames, TablesAdded.Where(o => o.IsType).Select(o => $"{o.Owner}.{o.Name}").ToList(), "table types in source but not in target")); sb.Append(Summarize(includeNames, TablesDeleted.Where(o => o.IsType).Select(o => $"{o.Owner}.{o.Name}").ToList(), "table types not in source but in target")); sb.Append(Summarize(includeNames, TableTypesDiff.Select(o => $"{o.Owner}.{o.Name}").ToList(), "table types altered")); sb.Append(Summarize(includeNames, UsersAdded.Select(o => o.Name).ToList(), "users in source but not in target")); sb.Append(Summarize(includeNames, UsersDeleted.Select(o => o.Name).ToList(), "users not in source but in target")); sb.Append(Summarize(includeNames, UsersDiff.Select(o => o.Name).ToList(), "users altered")); sb.Append(Summarize(includeNames, ViewIndexesAdded.Select(o => o.Name).ToList(), "view indexes in source but not in target")); sb.Append(Summarize(includeNames, ViewIndexesDeleted.Select(o => o.Name).ToList(), "view indexes not in source but in target")); sb.Append(Summarize(includeNames, ViewIndexesDiff.Select(o => o.Name).ToList(), "view indexes altered")); sb.Append(Summarize(includeNames, SynonymsAdded.Select(o => $"{o.Owner}.{o.Name}").ToList(), "synonyms in source but not in target")); sb.Append(Summarize(includeNames, SynonymsDeleted.Select(o => $"{o.Owner}.{o.Name}").ToList(), "synonyms not in source but in target")); sb.Append(Summarize(includeNames, SynonymsDiff.Select(o => $"{o.Owner}.{o.Name}").ToList(), "synonyms altered")); sb.Append(Summarize(includeNames, PermissionsAdded.Select(o => $"{o.ObjectName}: {o.StateDescription} {o.PermissionType} TO {o.UserName}") .ToList(), "permissions in source but not in target")); sb.Append(Summarize(includeNames, PermissionsDeleted .Select(o => $"{o.ObjectName}: {o.StateDescription} {o.PermissionType} TO {o.UserName}").ToList(), "permissions not in source but in target")); sb.Append(Summarize(includeNames, PermissionsDiff.Select(o => $"{o.ObjectName}: {o.StateDescription} {o.PermissionType} TO {o.UserName}") .ToList(), "permissions altered")); return sb.ToString(); } public string Script() { var text = new StringBuilder(); //alter database props //TODO need to check dependencies for collation change //TODO how can collation be set to null at the server level? if (PropsChanged.Count > 0) { text.Append(Database.ScriptPropList(PropsChanged)); text.AppendLine("GO"); text.AppendLine(); } //delete foreign keys if (ForeignKeysDeleted.Count + ForeignKeysDiff.Count > 0) { foreach (var fk in ForeignKeysDeleted) { text.AppendLine(fk.ScriptDrop()); } //delete modified foreign keys foreach (var fk in ForeignKeysDiff) { text.AppendLine(fk.ScriptDrop()); } text.AppendLine("GO"); } //delete tables if (TablesDeleted.Count + TableTypesDiff.Count > 0) { foreach (var t in TablesDeleted.Concat(TableTypesDiff)) { text.AppendLine(t.ScriptDrop()); } text.AppendLine("GO"); } // TODO: table types drop will fail if anything references them... try to find a workaround? //modify tables if (TablesDiff.Count > 0) { foreach (var t in TablesDiff) { text.Append(t.Script()); } text.AppendLine("GO"); } //add tables if (TablesAdded.Count + TableTypesDiff.Count > 0) { foreach (var t in TablesAdded.Concat(TableTypesDiff)) { text.Append(t.ScriptCreate()); } text.AppendLine("GO"); } //add foreign keys if (ForeignKeysAdded.Count + ForeignKeysDiff.Count > 0) { foreach (var fk in ForeignKeysAdded) { text.AppendLine(fk.ScriptCreate()); } //add modified foreign keys foreach (var fk in ForeignKeysDiff) { text.AppendLine(fk.ScriptCreate()); } text.AppendLine("GO"); } //add & delete procs, functions, & triggers foreach (var r in RoutinesAdded) { text.AppendLine(r.ScriptCreate()); text.AppendLine("GO"); } foreach (var r in RoutinesDiff) { // script alter if possible, otherwise drop and (re)create try { text.AppendLine(r.ScriptAlter(Db)); text.AppendLine("GO"); } catch { text.AppendLine(r.ScriptDrop()); text.AppendLine("GO"); text.AppendLine(r.ScriptCreate()); text.AppendLine("GO"); } } foreach (var r in RoutinesDeleted) { text.AppendLine(r.ScriptDrop()); text.AppendLine("GO"); } //add & delete synonyms foreach (var s in SynonymsAdded) { text.AppendLine(s.ScriptCreate()); text.AppendLine("GO"); } foreach (var s in SynonymsDiff) { text.AppendLine(s.ScriptDrop()); text.AppendLine("GO"); text.AppendLine(s.ScriptCreate()); text.AppendLine("GO"); } foreach (var s in SynonymsDeleted) { text.AppendLine(s.ScriptDrop()); text.AppendLine("GO"); } //add & delete permissions foreach (var p in PermissionsAdded) { text.AppendLine(p.ScriptCreate()); text.AppendLine("GO"); } foreach (var p in PermissionsDiff) { text.AppendLine(p.ScriptDrop()); text.AppendLine("GO"); text.AppendLine(p.ScriptCreate()); text.AppendLine("GO"); } foreach (var p in PermissionsDeleted) { text.AppendLine(p.ScriptDrop()); text.AppendLine("GO"); } return text.ToString(); } } }
32.624198
191
0.648976
[ "MIT" ]
idan-h/schemazen
model/Models/Database.cs
71,186
C#
using System; namespace Mankind { public class Worker :Human { private decimal salary; private int workingHours; public Worker(string firstName, string lastName, decimal salary, int workingHours) : base(firstName, lastName) { Salary = salary; WorkingHours = workingHours; } public decimal Salary { get => salary; set { if (value <= 10) { throw new ArgumentException("Expected value mismatch! Argument: weekSalary"); } salary = value; } } public int WorkingHours { get => workingHours; set { if (value < 1 || value > 12) { throw new ArgumentException("Expected value mismatch! Argument: workHoursPerDay"); } workingHours = value; } } public override string ToString() { var salaryPerHour = this.Salary / (this.WorkingHours * 5); return base.ToString() + $"Week Salary: {this.Salary:F2}{Environment.NewLine}" + $"Hours per day: {this.WorkingHours:F2}{Environment.NewLine}" + $"Salary per hour: {salaryPerHour:F2}"; } } }
27.307692
118
0.476056
[ "MIT" ]
IvanKirov/SoftUni
03. C# Fundamentals/02.C#_OOP_Basic/04. Inheritance - Exercise/03. Mankind/Worker.cs
1,422
C#
using System.IO; using CP77.CR2W.Reflection; using FastMember; using static CP77.CR2W.Types.Enums; namespace CP77.CR2W.Types { [REDMeta] public class ClueScannedEvent : redEvent { [Ordinal(0)] [RED("clueIndex")] public CInt32 ClueIndex { get; set; } [Ordinal(1)] [RED("requesterID")] public entEntityID RequesterID { get; set; } public ClueScannedEvent(CR2WFile cr2w, CVariable parent, string name) : base(cr2w, parent, name) { } } }
27.294118
103
0.698276
[ "MIT" ]
Eingin/CP77Tools
CP77.CR2W/Types/cp77/ClueScannedEvent.cs
448
C#
// <auto-generated> // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. // </auto-generated> namespace Microsoft.PowerBI.Api.Models { using Microsoft.Rest; using Newtonsoft.Json; using System.Linq; /// <summary> /// A dataset object in [GenerateTokenRequestV2](#generatetokenrequestv2) /// </summary> public partial class GenerateTokenRequestV2Dataset { /// <summary> /// Initializes a new instance of the GenerateTokenRequestV2Dataset /// class. /// </summary> public GenerateTokenRequestV2Dataset() { CustomInit(); } /// <summary> /// Initializes a new instance of the GenerateTokenRequestV2Dataset /// class. /// </summary> /// <param name="id">The dataset ID</param> /// <param name="xmlaPermissions">XMLA Permissions. Possible values /// include: 'Off', 'ReadOnly'</param> public GenerateTokenRequestV2Dataset(string id, XmlaPermissions? xmlaPermissions = default(XmlaPermissions?)) { Id = id; XmlaPermissions = xmlaPermissions; CustomInit(); } /// <summary> /// An initialization method that performs custom operations like setting defaults /// </summary> partial void CustomInit(); /// <summary> /// Gets or sets the dataset ID /// </summary> [JsonProperty(PropertyName = "id")] public string Id { get; set; } /// <summary> /// Gets or sets XMLA Permissions. Possible values include: 'Off', /// 'ReadOnly' /// </summary> [JsonProperty(PropertyName = "xmlaPermissions")] public XmlaPermissions? XmlaPermissions { get; set; } /// <summary> /// Validate the object. /// </summary> /// <exception cref="ValidationException"> /// Thrown if validation fails /// </exception> public virtual void Validate() { if (Id == null) { throw new ValidationException(ValidationRules.CannotBeNull, "Id"); } } } }
30.662162
117
0.576465
[ "MIT" ]
meburgess/PowerBI-CSharp
sdk/PowerBI.Api/Source/Models/GenerateTokenRequestV2Dataset.cs
2,269
C#
#pragma warning disable 108 // new keyword hiding #pragma warning disable 114 // new keyword hiding namespace Windows.Devices.Enumeration { #if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ || __MACOS__ [global::Uno.NotImplemented] #endif public partial interface IDevicePairingSettings { } }
28
98
0.758929
[ "Apache-2.0" ]
AbdalaMask/uno
src/Uno.UWP/Generated/3.0.0.0/Windows.Devices.Enumeration/IDevicePairingSettings.cs
336
C#
 namespace Sparkle.App_Start { using BundleTransformer.Core.Bundles; using BundleTransformer.Core.Orderers; using Sparkle.WebBase; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Optimization; public static class BundleConfig { public const string DefaultLibScripts = "~/b/Scripts/defaultlibs.js"; public const string DefaultScripts = "~/b/Scripts/default.js"; public const string PublicLibScripts = "~/b/Styles/publiclibs.js"; public const string PublicScripts = "~/b/Styles/public.js"; public const string DefaultStyles = "~/b/Styles/default.css"; public const string DefaultLteIE7Styles = "~/b/Styles/default.lteIE7.css"; public static void ConfigureStaticBundles(BundleCollection collection) { var scriptTransforms = new IItemTransform[] { }; // defaultlibs.js // contains all the JS libraries used when the user is authenticated var defaultLibScripts = new ScriptBundle(DefaultLibScripts) .Include("~/Scripts/modernizr.custom.35245.js") .Include("~/Scripts/jquery-1.11.1.js") .Include("~/Scripts/jquery-ui-1.10.4.custom.js") .Include("~/Scripts/underscore-min.js") .Include("~/Scripts/jquery.elastic.js") .Include("~/Scripts/jquery.mentionsInput.js") .Include("~/Scripts/knob.js"); ////defaultScripts.Transforms.Add(JsObscureStringTransform); BundleTable.Bundles.Add(defaultLibScripts); // default.js // contains all the JS SCRIPTS used when the user is authenticated var defaultScripts = new CustomScriptBundle(DefaultScripts) .Include("~/Scripts/common.js", scriptTransforms) .Include("~/Scripts/global.js", scriptTransforms) .Include("~/Scripts/timeline.js", scriptTransforms); defaultScripts.Builder = new DefaultBundleBuilder(); defaultScripts.Orderer = new NullOrderer(); defaultScripts.ConcatenationToken = ";" + Environment.NewLine; defaultScripts.Transforms.Add(new JsMinify()); defaultScripts.Transforms.Add(new JsObscureStringTransform()); BundleTable.Bundles.Add(defaultScripts); // publiclibs.js // contains all the JS libraries used when the user is NOT authenticated var publicLibScripts = new ScriptBundle(PublicLibScripts) .Include("~/Scripts/modernizr.custom.35245.js") .Include("~/Scripts/jquery-1.11.1.js") .Include("~/Scripts/jquery-ui-1.10.4.custom.js") .Include("~/Scripts/jquery.elastic.js") ; BundleTable.Bundles.Add(publicLibScripts); // public.js // contains all the JS SCRIPTS used when the user is NOT authenticated var publicScripts = new CustomScriptBundle(PublicScripts) .Include("~/Scripts/common.js", scriptTransforms) .Include("~/Scripts/public.js", scriptTransforms) .Include("~/Scripts/timeline.js", scriptTransforms) ; publicScripts.Builder = new DefaultBundleBuilder(); publicScripts.Orderer = new NullOrderer(); publicScripts.ConcatenationToken = ";" + Environment.NewLine; publicScripts.Transforms.Add(new JsMinify()); publicScripts.Transforms.Add(new JsObscureStringTransform()); BundleTable.Bundles.Add(publicScripts); var sparkleShow = new CustomStyleBundle("~/b/Styles/SparkleShow.css") .Include("~/Content/SparkleShow.less"); sparkleShow.Orderer = new NullOrderer(); BundleTable.Bundles.Add(sparkleShow); var dashboardStyles = new CustomStyleBundle("~/b/Styles/Dashboard.css") .Include("~/Content/Dashboard.less"); dashboardStyles.Orderer = new NullOrderer(); BundleTable.Bundles.Add(dashboardStyles); // site.less extension for IE <= 7 var siteLteIE7Styles = new CustomStyleBundle(BundleConfig.DefaultLteIE7Styles) .Include("~/Content/Site.lteIE7.less"); siteLteIE7Styles.Orderer = new NullOrderer(); BundleTable.Bundles.Add(siteLteIE7Styles); } public static void ConfigureNetworkBundles(BundleCollection collection, HttpServerUtility server, string networkName) { var siteCssBundle = new CustomStyleBundle(BundleConfig.DefaultStyles); siteCssBundle.Orderer = new NullOrderer(); var networkSiteLess = "~/Content/Networks/" + networkName + "/Styles/Site.less"; if (System.IO.File.Exists(server.MapPath(networkSiteLess))) siteCssBundle.Include(networkSiteLess); else siteCssBundle.Include("~/Content/Site.less"); siteCssBundle.Include("~/Content/Timeline.less"); siteCssBundle.Include("~/Content/themes/sparkle/jquery-ui-1.10.4.less"); siteCssBundle.Include("~/Content/jquery.mentionsInput.css"); BundleTable.Bundles.Add(siteCssBundle); } } }
48.955357
126
0.613533
[ "MPL-2.0" ]
SparkleNetworks/SparkleNetworks
src/Sparkle.Web/App_Start/BundleConfig.cs
5,485
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; namespace AppAdvisory.MathGame { public class gotoMA10 : ButtonHelper { public GameObject level; override public void OnClicked() { menuManager.backtonormal(); Destroy(level); menuManager.GoToMA10(); RemoveListener(); } } }
17.578947
40
0.724551
[ "MIT" ]
MrD005/Math-Game
BODMAS/Assets/MathGame/Scripts/addition/LevelWiseScript/gotoMA10.cs
336
C#
using Microsoft.Maui; using Microsoft.Maui.Hosting; using Microsoft.Maui.Controls.Compatibility; using Microsoft.Maui.LifecycleEvents; namespace HelloMaui { public class Startup : IStartup { public void Configure(IAppHostBuilder appBuilder) { appBuilder .UseFormsCompatibility() .UseMauiApp<App>() .ConfigureFonts(fonts => { fonts.AddFont("ionicons.ttf", "IonIcons"); }) .ConfigureLifecycleEvents(lifecycle => { #if ANDROID lifecycle.AddAndroid(d => { d.OnBackPressed(activity => { System.Diagnostics.Debug.WriteLine("Back button pressed!"); }); }); #endif }); } } }
25.548387
66
0.54798
[ "MIT" ]
thomasirmer/HelloZeissMAUI
HelloMaui/Startup.cs
792
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 kinesisanalyticsv2-2018-05-23.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.KinesisAnalyticsV2.Model { /// <summary> /// Describes details about the application code and starting parameters for an Amazon /// Kinesis Data Analytics application. /// </summary> public partial class ApplicationConfigurationDescription { private ApplicationCodeConfigurationDescription _applicationCodeConfigurationDescription; private ApplicationSnapshotConfigurationDescription _applicationSnapshotConfigurationDescription; private EnvironmentPropertyDescriptions _environmentPropertyDescriptions; private FlinkApplicationConfigurationDescription _flinkApplicationConfigurationDescription; private RunConfigurationDescription _runConfigurationDescription; private SqlApplicationConfigurationDescription _sqlApplicationConfigurationDescription; private List<VpcConfigurationDescription> _vpcConfigurationDescriptions = new List<VpcConfigurationDescription>(); /// <summary> /// Gets and sets the property ApplicationCodeConfigurationDescription. /// <para> /// The details about the application code for a Java-based Kinesis Data Analytics application. /// </para> /// </summary> public ApplicationCodeConfigurationDescription ApplicationCodeConfigurationDescription { get { return this._applicationCodeConfigurationDescription; } set { this._applicationCodeConfigurationDescription = value; } } // Check to see if ApplicationCodeConfigurationDescription property is set internal bool IsSetApplicationCodeConfigurationDescription() { return this._applicationCodeConfigurationDescription != null; } /// <summary> /// Gets and sets the property ApplicationSnapshotConfigurationDescription. /// <para> /// Describes whether snapshots are enabled for a Java-based Kinesis Data Analytics application. /// </para> /// </summary> public ApplicationSnapshotConfigurationDescription ApplicationSnapshotConfigurationDescription { get { return this._applicationSnapshotConfigurationDescription; } set { this._applicationSnapshotConfigurationDescription = value; } } // Check to see if ApplicationSnapshotConfigurationDescription property is set internal bool IsSetApplicationSnapshotConfigurationDescription() { return this._applicationSnapshotConfigurationDescription != null; } /// <summary> /// Gets and sets the property EnvironmentPropertyDescriptions. /// <para> /// Describes execution properties for a Java-based Kinesis Data Analytics application. /// </para> /// </summary> public EnvironmentPropertyDescriptions EnvironmentPropertyDescriptions { get { return this._environmentPropertyDescriptions; } set { this._environmentPropertyDescriptions = value; } } // Check to see if EnvironmentPropertyDescriptions property is set internal bool IsSetEnvironmentPropertyDescriptions() { return this._environmentPropertyDescriptions != null; } /// <summary> /// Gets and sets the property FlinkApplicationConfigurationDescription. /// <para> /// The details about a Java-based Kinesis Data Analytics application. /// </para> /// </summary> public FlinkApplicationConfigurationDescription FlinkApplicationConfigurationDescription { get { return this._flinkApplicationConfigurationDescription; } set { this._flinkApplicationConfigurationDescription = value; } } // Check to see if FlinkApplicationConfigurationDescription property is set internal bool IsSetFlinkApplicationConfigurationDescription() { return this._flinkApplicationConfigurationDescription != null; } /// <summary> /// Gets and sets the property RunConfigurationDescription. /// <para> /// The details about the starting properties for a Kinesis Data Analytics application. /// </para> /// </summary> public RunConfigurationDescription RunConfigurationDescription { get { return this._runConfigurationDescription; } set { this._runConfigurationDescription = value; } } // Check to see if RunConfigurationDescription property is set internal bool IsSetRunConfigurationDescription() { return this._runConfigurationDescription != null; } /// <summary> /// Gets and sets the property SqlApplicationConfigurationDescription. /// <para> /// The details about inputs, outputs, and reference data sources for an SQL-based Kinesis /// Data Analytics application. /// </para> /// </summary> public SqlApplicationConfigurationDescription SqlApplicationConfigurationDescription { get { return this._sqlApplicationConfigurationDescription; } set { this._sqlApplicationConfigurationDescription = value; } } // Check to see if SqlApplicationConfigurationDescription property is set internal bool IsSetSqlApplicationConfigurationDescription() { return this._sqlApplicationConfigurationDescription != null; } /// <summary> /// Gets and sets the property VpcConfigurationDescriptions. /// <para> /// The array of descriptions of VPC configurations available to the application. /// </para> /// </summary> public List<VpcConfigurationDescription> VpcConfigurationDescriptions { get { return this._vpcConfigurationDescriptions; } set { this._vpcConfigurationDescriptions = value; } } // Check to see if VpcConfigurationDescriptions property is set internal bool IsSetVpcConfigurationDescriptions() { return this._vpcConfigurationDescriptions != null && this._vpcConfigurationDescriptions.Count > 0; } } }
41.317919
122
0.688724
[ "Apache-2.0" ]
atpyatt/aws-sdk-net
sdk/src/Services/KinesisAnalyticsV2/Generated/Model/ApplicationConfigurationDescription.cs
7,148
C#
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; namespace AutoFixture.AutoEF { /// <summary> /// Builds list of EF types by enumerating through DbSet properties on a DbContext subclass /// </summary> public class DbContextEntityTypesProvider : IEntityTypesProvider { private readonly Type _dbContext; public DbContextEntityTypesProvider(Type dbContext) { if (dbContext == null) throw new ArgumentNullException("dbContext"); _dbContext = dbContext; } public IEnumerable<Type> GetTypes() { return from prop in _dbContext.GetProperties(BindingFlags.Public | BindingFlags.Instance) let t = prop.PropertyType where t.IsGenericType && (t.Name.Remove(t.Name.IndexOf('`')) == "DbSet" || t.Name.Remove(t.Name.IndexOf('`')) == "IDbSet") select t.GenericTypeArguments[0]; } } }
32.125
123
0.609922
[ "MIT" ]
alexfoxgill/AutoFixture.AutoEntityFramework
src/AutoFixture.AutoEF/DbContextEntityTypesProvider.cs
1,030
C#
using System; using System.Collections.Generic; using Newtonsoft.Json; using Newtonsoft.Json.Converters; namespace Frau.Models { public class Invoice { [JsonProperty("id")] public uint Id { get; set; } [JsonProperty("currency")] public string Currency { get; set; } [JsonProperty("status")] public string Status { get; set; } [JsonProperty("user")] public uint User { get; set; } [JsonProperty("createdAt")] [JsonConverter(typeof(IsoDateTimeConverter))] public DateTime CreatedAt { get; set; } [JsonProperty("amount")] public int Amount { get; set; } [JsonProperty("items")] public List<InvoiceItem> Items { get; set; } } }
23.151515
53
0.599476
[ "MIT" ]
mika-sandbox/dotnet-mixier-api-wrapper
Sources/Frau/Models/Invoice.cs
766
C#
// ReSharper disable VirtualMemberCallInConstructor namespace ESchool.Data.Models { using System; using ESchool.Data.Common.Models; using Microsoft.AspNetCore.Identity; public class ApplicationRole : IdentityRole, IAuditInfo, IDeletableEntity { public ApplicationRole() : this(null) { } public ApplicationRole(string name) : base(name) { this.Id = Guid.NewGuid().ToString(); } public DateTime CreatedOn { get; set; } public DateTime? ModifiedOn { get; set; } public bool IsDeleted { get; set; } public DateTime? DeletedOn { get; set; } } }
21.53125
77
0.599419
[ "MIT" ]
llukanov/eSchool
Data/ESchool.Data.Models/ApplicationRole.cs
691
C#
using System; using System.ComponentModel.DataAnnotations.Schema; namespace Ictus.Data.Models { public class Tag { public Guid Id { get; set; } public string Name { get; set; } public int FileCount { get; set; } } }
21
51
0.630952
[ "MIT" ]
Zyrio/Ictus
src/Ictus/Data/Models/Tag.cs
252
C#
using UnityEngine; using UnityEngine.Events; using UnityEngine.Serialization; using Lean.Common; #if UNITY_EDITOR using UnityEditor; #endif namespace Lean.Touch { /// <summary>This component invokes events when a finger touches the screen that satisfies the specified conditions.</summary> [HelpURL(LeanTouch.HelpUrlPrefix + "LeanFingerDown")] [AddComponentMenu(LeanTouch.ComponentPathPrefix + "Finger Down")] public class LeanFingerDown : MonoBehaviour { [System.Serializable] public class LeanFingerEvent : UnityEvent<LeanFinger> {} [System.Serializable] public class Vector3Event : UnityEvent<Vector3> {} /// <summary>Ignore fingers with StartedOverGui?</summary> [Tooltip("Ignore fingers with StartedOverGui?")] public bool IgnoreStartedOverGui = true; /// <summary>Do nothing if this LeanSelectable isn't selected?</summary> [Tooltip("Do nothing if this LeanSelectable isn't selected?")] public LeanSelectable RequiredSelectable; /// <summary>Called on the first frame the conditions are met.</summary> public LeanFingerEvent OnFinger { get { if (onFinger == null) onFinger = new LeanFingerEvent(); return onFinger; } } [FormerlySerializedAs("onDown")] [FormerlySerializedAs("OnDown")] [SerializeField] private LeanFingerEvent onFinger; /// <summary>The method used to find world coordinates from a finger. See LeanScreenDepth documentation for more information.</summary> public LeanScreenDepth ScreenDepth = new LeanScreenDepth(LeanScreenDepth.ConversionType.DepthIntercept); /// <summary>Called on the first frame the conditions are met. /// Vector3 = Start point based on the ScreenDepth settings.</summary> public Vector3Event OnPosition { get { if (onPosition == null) onPosition = new Vector3Event(); return onPosition; } } [SerializeField] private Vector3Event onPosition; #if UNITY_EDITOR protected virtual void Reset() { RequiredSelectable = GetComponentInParent<LeanSelectable>(); } #endif protected virtual void Awake() { if (RequiredSelectable == null) { RequiredSelectable = GetComponentInParent<LeanSelectable>(); } } protected virtual void OnEnable() { LeanTouch.OnFingerDown += HandleOnFingerDown; } protected virtual void OnDisable() { LeanTouch.OnFingerDown -= HandleOnFingerDown; } private void HandleOnFingerDown(LeanFinger finger) { if (IgnoreStartedOverGui == true && finger.IsOverGui == true) { return; } if (RequiredSelectable != null && RequiredSelectable.IsSelected == false) { return; } if (onFinger != null) { onFinger.Invoke(finger); } if (onPosition != null) { var position = ScreenDepth.Convert(finger.StartScreenPosition, gameObject); onPosition.Invoke(position); } } } } #if UNITY_EDITOR namespace Lean.Touch { [CanEditMultipleObjects] [CustomEditor(typeof(LeanFingerDown))] public class LeanFingerDown_Inspector : LeanInspector<LeanFingerDown> { private bool showUnusedEvents; protected override void DrawInspector() { Draw("IgnoreStartedOverGui"); Draw("RequiredSelectable"); EditorGUILayout.Separator(); var usedA = Any(t => t.OnFinger.GetPersistentEventCount() > 0); var usedB = Any(t => t.OnPosition.GetPersistentEventCount() > 0); EditorGUI.BeginDisabledGroup(usedA && usedB); showUnusedEvents = EditorGUILayout.Foldout(showUnusedEvents, "Show Unused Events"); EditorGUI.EndDisabledGroup(); EditorGUILayout.Separator(); if (usedA == true || showUnusedEvents == true) { Draw("onFinger"); } if (usedB == true || showUnusedEvents == true) { Draw("ScreenDepth"); Draw("onPosition"); } } } } #endif
29.408
235
0.730413
[ "Apache-2.0" ]
ANKITVIRGO23/ARVRTest
Assets/Lean/Touch/Examples/Scripts/LeanFingerDown.cs
3,676
C#
using System; using System.Collections.Generic; using System.Runtime.CompilerServices; using System.Text; namespace uplink.NET.Models { public unsafe class EncryptionKey : IDisposable { internal SWIG.UplinkEncryptionKeyResult _encryptionKeyResulRef; /// <summary> /// The EncryptionKey to derive a salted encryption key for users when /// implementing multitenancy in a single app bucket. /// </summary> /// <param name="passphrase">The passphrase</param> /// <param name="salt">The salt - should be either 16 or 32 bytes</param> public EncryptionKey(string passphrase, byte[] salt) { fixed (byte* arrayPtr = salt) { _encryptionKeyResulRef = SWIG.storj_uplink.uplink_derive_encryption_key(passphrase, new SWIG.SWIGTYPE_p_void(new IntPtr(arrayPtr), true), (uint)salt.Length); } if (_encryptionKeyResulRef.error != null && !string.IsNullOrEmpty(_encryptionKeyResulRef.error.message)) throw new ArgumentException(_encryptionKeyResulRef.error.message); } public void Dispose() { if (_encryptionKeyResulRef != null) { SWIG.storj_uplink.uplink_free_encryption_key_result(_encryptionKeyResulRef); _encryptionKeyResulRef.Dispose(); _encryptionKeyResulRef = null; } } } }
36.2
173
0.638812
[ "MIT" ]
Neus252/uplink.net
uplink.NET/uplink.NET/Models/EncryptionKey.cs
1,450
C#
using System; using System.Collections.Generic; using System.IO; using System.Net; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Ocelot.Configuration.File; using Shouldly; using TestStack.BDDfy; using Xunit; namespace Ocelot.AcceptanceTests { public class RoutingTests : IDisposable { private IWebHost _builder; private readonly Steps _steps; private string _downstreamPath; public RoutingTests() { _steps = new Steps(); } [Fact] public void should_return_response_404_when_no_configuration_at_all() { this.Given(x => _steps.GivenThereIsAConfiguration(new FileConfiguration())) .And(x => _steps.GivenOcelotIsRunning()) .When(x => _steps.WhenIGetUrlOnTheApiGateway("/")) .Then(x => _steps.ThenTheStatusCodeShouldBe(HttpStatusCode.NotFound)) .BDDfy(); } [Fact] public void should_return_response_200_with_simple_url() { var configuration = new FileConfiguration { ReRoutes = new List<FileReRoute> { new FileReRoute { DownstreamPathTemplate = "/", DownstreamScheme = "http", DownstreamHost = "localhost", DownstreamPort = 51879, UpstreamPathTemplate = "/", UpstreamHttpMethod = new List<string> { "Get" }, } } }; this.Given(x => x.GivenThereIsAServiceRunningOn("http://localhost:51879", "", 200, "Hello from Laura")) .And(x => _steps.GivenThereIsAConfiguration(configuration)) .And(x => _steps.GivenOcelotIsRunning()) .When(x => _steps.WhenIGetUrlOnTheApiGateway("/")) .Then(x => _steps.ThenTheStatusCodeShouldBe(HttpStatusCode.OK)) .And(x => _steps.ThenTheResponseBodyShouldBe("Hello from Laura")) .BDDfy(); } [Fact] public void bug() { var configuration = new FileConfiguration { ReRoutes = new List<FileReRoute> { new FileReRoute { DownstreamPathTemplate = "/api/v1/vacancy", DownstreamScheme = "http", DownstreamHost = "localhost", DownstreamPort = 51879, UpstreamPathTemplate = "/vacancy/", UpstreamHttpMethod = new List<string> { "Options", "Put", "Get", "Post", "Delete" }, ServiceName = "botCore", LoadBalancer = "LeastConnection" }, new FileReRoute { DownstreamPathTemplate = "/api/v1/vacancy/{vacancyId}", DownstreamScheme = "http", DownstreamHost = "localhost", DownstreamPort = 51879, UpstreamPathTemplate = "/vacancy/{vacancyId}", UpstreamHttpMethod = new List<string> { "Options", "Put", "Get", "Post", "Delete" }, ServiceName = "botCore", LoadBalancer = "LeastConnection" } } }; this.Given(x => x.GivenThereIsAServiceRunningOn("http://localhost:51879", "/api/v1/vacancy/1", 200, "Hello from Laura")) .And(x => _steps.GivenThereIsAConfiguration(configuration)) .And(x => _steps.GivenOcelotIsRunning()) .When(x => _steps.WhenIGetUrlOnTheApiGateway("/vacancy/1")) .Then(x => _steps.ThenTheStatusCodeShouldBe(HttpStatusCode.OK)) .And(x => _steps.ThenTheResponseBodyShouldBe("Hello from Laura")) .BDDfy(); } [Fact] public void should_return_response_200_when_path_missing_forward_slash_as_first_char() { var configuration = new FileConfiguration { ReRoutes = new List<FileReRoute> { new FileReRoute { DownstreamPathTemplate = "/api/products", DownstreamScheme = "http", DownstreamHost = "localhost", DownstreamPort = 51879, UpstreamPathTemplate = "/", UpstreamHttpMethod = new List<string> { "Get" }, } } }; this.Given(x => x.GivenThereIsAServiceRunningOn("http://localhost:51879", "/api/products", 200, "Hello from Laura")) .And(x => _steps.GivenThereIsAConfiguration(configuration)) .And(x => _steps.GivenOcelotIsRunning()) .When(x => _steps.WhenIGetUrlOnTheApiGateway("/")) .Then(x => _steps.ThenTheStatusCodeShouldBe(HttpStatusCode.OK)) .And(x => _steps.ThenTheResponseBodyShouldBe("Hello from Laura")) .BDDfy(); } [Fact] public void should_return_response_200_when_host_has_trailing_slash() { var configuration = new FileConfiguration { ReRoutes = new List<FileReRoute> { new FileReRoute { DownstreamPathTemplate = "/api/products", DownstreamScheme = "http", DownstreamHost = "localhost/", DownstreamPort = 51879, UpstreamPathTemplate = "/", UpstreamHttpMethod = new List<string> { "Get" }, } } }; this.Given(x => x.GivenThereIsAServiceRunningOn("http://localhost:51879", "/api/products", 200, "Hello from Laura")) .And(x => _steps.GivenThereIsAConfiguration(configuration)) .And(x => _steps.GivenOcelotIsRunning()) .When(x => _steps.WhenIGetUrlOnTheApiGateway("/")) .Then(x => _steps.ThenTheStatusCodeShouldBe(HttpStatusCode.OK)) .And(x => _steps.ThenTheResponseBodyShouldBe("Hello from Laura")) .BDDfy(); } [Fact] public void should_not_care_about_no_trailing() { var configuration = new FileConfiguration { ReRoutes = new List<FileReRoute> { new FileReRoute { DownstreamPathTemplate = "/products", DownstreamScheme = "http", DownstreamHost = "localhost", DownstreamPort = 51879, UpstreamPathTemplate = "/products/", UpstreamHttpMethod = new List<string> { "Get" }, } } }; this.Given(x => x.GivenThereIsAServiceRunningOn("http://localhost:51879", "/products", 200, "Hello from Laura")) .And(x => _steps.GivenThereIsAConfiguration(configuration)) .And(x => _steps.GivenOcelotIsRunning()) .When(x => _steps.WhenIGetUrlOnTheApiGateway("/products")) .Then(x => _steps.ThenTheStatusCodeShouldBe(HttpStatusCode.OK)) .And(x => _steps.ThenTheResponseBodyShouldBe("Hello from Laura")) .BDDfy(); } [Fact] public void should_not_care_about_trailing() { var configuration = new FileConfiguration { ReRoutes = new List<FileReRoute> { new FileReRoute { DownstreamPathTemplate = "/products", DownstreamScheme = "http", DownstreamHost = "localhost", DownstreamPort = 51879, UpstreamPathTemplate = "/products", UpstreamHttpMethod = new List<string> { "Get" }, } } }; this.Given(x => x.GivenThereIsAServiceRunningOn("http://localhost:51879", "/products", 200, "Hello from Laura")) .And(x => _steps.GivenThereIsAConfiguration(configuration)) .And(x => _steps.GivenOcelotIsRunning()) .When(x => _steps.WhenIGetUrlOnTheApiGateway("/products/")) .Then(x => _steps.ThenTheStatusCodeShouldBe(HttpStatusCode.OK)) .And(x => _steps.ThenTheResponseBodyShouldBe("Hello from Laura")) .BDDfy(); } [Fact] public void should_return_not_found() { var configuration = new FileConfiguration { ReRoutes = new List<FileReRoute> { new FileReRoute { DownstreamPathTemplate = "/products", DownstreamScheme = "http", DownstreamHost = "localhost", DownstreamPort = 51879, UpstreamPathTemplate = "/products/{productId}", UpstreamHttpMethod = new List<string> { "Get" }, QoSOptions = new FileQoSOptions() { ExceptionsAllowedBeforeBreaking = 3, DurationOfBreak = 5, TimeoutValue = 5000 } } } }; this.Given(x => x.GivenThereIsAServiceRunningOn("http://localhost:51879", "/products", 200, "Hello from Laura")) .And(x => _steps.GivenThereIsAConfiguration(configuration)) .And(x => _steps.GivenOcelotIsRunning()) .When(x => _steps.WhenIGetUrlOnTheApiGateway("/products/")) .Then(x => _steps.ThenTheStatusCodeShouldBe(HttpStatusCode.NotFound)) .BDDfy(); } [Fact] public void should_return_response_200_with_complex_url() { var configuration = new FileConfiguration { ReRoutes = new List<FileReRoute> { new FileReRoute { DownstreamPathTemplate = "/api/products/{productId}", DownstreamScheme = "http", DownstreamHost = "localhost", DownstreamPort = 51879, UpstreamPathTemplate = "/products/{productId}", UpstreamHttpMethod = new List<string> { "Get" }, } } }; this.Given(x => x.GivenThereIsAServiceRunningOn("http://localhost:51879", "/api/products/1", 200, "Some Product")) .And(x => _steps.GivenThereIsAConfiguration(configuration)) .And(x => _steps.GivenOcelotIsRunning()) .When(x => _steps.WhenIGetUrlOnTheApiGateway("/products/1")) .Then(x => _steps.ThenTheStatusCodeShouldBe(HttpStatusCode.OK)) .And(x => _steps.ThenTheResponseBodyShouldBe("Some Product")) .BDDfy(); } [Fact] public void should_not_add_trailing_slash_to_downstream_url() { var configuration = new FileConfiguration { ReRoutes = new List<FileReRoute> { new FileReRoute { DownstreamPathTemplate = "/api/products/{productId}", DownstreamScheme = "http", DownstreamHost = "localhost", DownstreamPort = 51879, UpstreamPathTemplate = "/products/{productId}", UpstreamHttpMethod = new List<string> { "Get" }, } } }; this.Given(x => GivenThereIsAServiceRunningOn("http://localhost:51879", "/api/products/1", 200, "Some Product")) .And(x => _steps.GivenThereIsAConfiguration(configuration)) .And(x => _steps.GivenOcelotIsRunning()) .When(x => _steps.WhenIGetUrlOnTheApiGateway("/products/1")) .Then(x => ThenTheDownstreamUrlPathShouldBe("/api/products/1")) .BDDfy(); } [Fact] public void should_return_response_201_with_simple_url() { var configuration = new FileConfiguration { ReRoutes = new List<FileReRoute> { new FileReRoute { DownstreamPathTemplate = "/", DownstreamHost = "localhost", DownstreamPort = 51879, DownstreamScheme = "http", UpstreamPathTemplate = "/", UpstreamHttpMethod = new List<string> { "Post" }, } } }; this.Given(x => x.GivenThereIsAServiceRunningOn("http://localhost:51879", "", 201, string.Empty)) .And(x => _steps.GivenThereIsAConfiguration(configuration)) .And(x => _steps.GivenOcelotIsRunning()) .And(x => _steps.GivenThePostHasContent("postContent")) .When(x => _steps.WhenIPostUrlOnTheApiGateway("/")) .Then(x => _steps.ThenTheStatusCodeShouldBe(HttpStatusCode.Created)) .BDDfy(); } [Fact] public void should_return_response_201_with_complex_query_string() { var configuration = new FileConfiguration { ReRoutes = new List<FileReRoute> { new FileReRoute { DownstreamPathTemplate = "/newThing", UpstreamPathTemplate = "/newThing", DownstreamScheme = "http", DownstreamHost = "localhost", DownstreamPort = 51879, UpstreamHttpMethod = new List<string> { "Get" }, } } }; this.Given(x => x.GivenThereIsAServiceRunningOn("http://localhost:51879", "", 200, "Hello from Laura")) .And(x => _steps.GivenThereIsAConfiguration(configuration)) .And(x => _steps.GivenOcelotIsRunning()) .When(x => _steps.WhenIGetUrlOnTheApiGateway("/newThing?DeviceType=IphoneApp&Browser=moonpigIphone&BrowserString=-&CountryCode=123&DeviceName=iPhone 5 (GSM+CDMA)&OperatingSystem=iPhone OS 7.1.2&BrowserVersion=3708AdHoc&ipAddress=-")) .Then(x => _steps.ThenTheStatusCodeShouldBe(HttpStatusCode.OK)) .And(x => _steps.ThenTheResponseBodyShouldBe("Hello from Laura")) .BDDfy(); } [Fact] public void should_return_response_200_with_placeholder_for_final_url_path() { var configuration = new FileConfiguration { ReRoutes = new List<FileReRoute> { new FileReRoute { DownstreamPathTemplate = "/api/{urlPath}", DownstreamScheme = "http", DownstreamHost = "localhost", DownstreamPort = 51879, UpstreamPathTemplate = "/myApp1Name/api/{urlPath}", UpstreamHttpMethod = new List<string> { "Get" }, } } }; this.Given(x => x.GivenThereIsAServiceRunningOn("http://localhost:51879", "/myApp1Name/api/products/1", 200, "Some Product")) .And(x => _steps.GivenThereIsAConfiguration(configuration)) .And(x => _steps.GivenOcelotIsRunning()) .When(x => _steps.WhenIGetUrlOnTheApiGateway("/myApp1Name/api/products/1")) .Then(x => _steps.ThenTheStatusCodeShouldBe(HttpStatusCode.OK)) .And(x => _steps.ThenTheResponseBodyShouldBe("Some Product")) .BDDfy(); } [Fact] public void should_return_response_201_with_simple_url_and_multiple_upstream_http_method() { var configuration = new FileConfiguration { ReRoutes = new List<FileReRoute> { new FileReRoute { DownstreamPathTemplate = "/", DownstreamHost = "localhost", DownstreamPort = 51879, DownstreamScheme = "http", UpstreamPathTemplate = "/", UpstreamHttpMethod = new List<string> { "Get", "Post" }, } } }; this.Given(x => x.GivenThereIsAServiceRunningOn("http://localhost:51879", "", 201, string.Empty)) .And(x => _steps.GivenThereIsAConfiguration(configuration)) .And(x => _steps.GivenOcelotIsRunning()) .And(x => _steps.GivenThePostHasContent("postContent")) .When(x => _steps.WhenIPostUrlOnTheApiGateway("/")) .Then(x => _steps.ThenTheStatusCodeShouldBe(HttpStatusCode.Created)) .BDDfy(); } [Fact] public void should_return_response_200_with_simple_url_and_any_upstream_http_method() { var configuration = new FileConfiguration { ReRoutes = new List<FileReRoute> { new FileReRoute { DownstreamPathTemplate = "/", DownstreamHost = "localhost", DownstreamPort = 51879, DownstreamScheme = "http", UpstreamPathTemplate = "/", UpstreamHttpMethod = new List<string>(), } } }; this.Given(x => x.GivenThereIsAServiceRunningOn("http://localhost:51879", "", 200, "Hello from Laura")) .And(x => _steps.GivenThereIsAConfiguration(configuration)) .And(x => _steps.GivenOcelotIsRunning()) .When(x => _steps.WhenIGetUrlOnTheApiGateway("/")) .Then(x => _steps.ThenTheStatusCodeShouldBe(HttpStatusCode.OK)) .And(x => _steps.ThenTheResponseBodyShouldBe("Hello from Laura")) .BDDfy(); } [Fact] public void should_return_404_when_calling_upstream_route_with_no_matching_downstream_re_route_github_issue_134() { var configuration = new FileConfiguration { ReRoutes = new List<FileReRoute> { new FileReRoute { DownstreamPathTemplate = "/api/v1/vacancy", DownstreamScheme = "http", DownstreamHost = "localhost", DownstreamPort = 51879, UpstreamPathTemplate = "/vacancy/", UpstreamHttpMethod = new List<string> { "Options", "Put", "Get", "Post", "Delete" }, ServiceName = "botCore", LoadBalancer = "LeastConnection" }, new FileReRoute { DownstreamPathTemplate = "/api/v1/vacancy/{vacancyId}", DownstreamScheme = "http", DownstreamHost = "localhost", DownstreamPort = 51879, UpstreamPathTemplate = "/vacancy/{vacancyId}", UpstreamHttpMethod = new List<string> { "Options", "Put", "Get", "Post", "Delete" }, ServiceName = "botCore", LoadBalancer = "LeastConnection" } } }; this.Given(x => x.GivenThereIsAServiceRunningOn("http://localhost:51879", "/api/v1/vacancy/1", 200, "Hello from Laura")) .And(x => _steps.GivenThereIsAConfiguration(configuration)) .And(x => _steps.GivenOcelotIsRunning()) .When(x => _steps.WhenIGetUrlOnTheApiGateway("api/vacancy/1")) .Then(x => _steps.ThenTheStatusCodeShouldBe(HttpStatusCode.NotFound)) .BDDfy(); } private void GivenThereIsAServiceRunningOn(string baseUrl, string basePath, int statusCode, string responseBody) { _builder = new WebHostBuilder() .UseUrls(baseUrl) .UseKestrel() .UseContentRoot(Directory.GetCurrentDirectory()) .UseIISIntegration() .Configure(app => { app.UsePathBase(basePath); app.Run(async context => { _downstreamPath = context.Request.PathBase.Value; context.Response.StatusCode = statusCode; await context.Response.WriteAsync(responseBody); }); }) .Build(); _builder.Start(); } internal void ThenTheDownstreamUrlPathShouldBe(string expectedDownstreamPath) { _downstreamPath.ShouldBe(expectedDownstreamPath); } public void Dispose() { _builder?.Dispose(); _steps.Dispose(); } } }
43.721154
249
0.485067
[ "MIT" ]
albertosam/Ocelot
test/Ocelot.AcceptanceTests/RoutingTests.cs
22,735
C#
using AwsAspNetCoreLabs.Models; namespace AwsAspNetCoreLabs.SES { public interface INoteEmailService { void SendNote(string email, Note note); } }
18.666667
47
0.714286
[ "MIT" ]
a-patel/aspnetcore-aws-labs
src/AwsAspNetCoreLabs.SES/INoteEmailService.cs
170
C#