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 |
|---|---|---|---|---|---|---|---|---|
// dnlib: See LICENSE.txt for more info
namespace dnlib.DotNet {
/// <summary>
/// Resolves tokens
/// </summary>
public interface ITokenResolver {
/// <summary>
/// Resolves a token
/// </summary>
/// <param name="token">The metadata token</param>
/// <param name="gpContext">Generic parameter context</param>
/// <returns>A <see cref="IMDTokenProvider"/> or <c>null</c> if <paramref name="token"/> is invalid</returns>
IMDTokenProvider ResolveToken(uint token, GenericParamContext gpContext);
}
public static partial class Extensions {
/// <summary>
/// Resolves a token
/// </summary>
/// <param name="self">This</param>
/// <param name="token">The metadata token</param>
/// <returns>A <see cref="IMDTokenProvider"/> or <c>null</c> if <paramref name="token"/> is invalid</returns>
public static IMDTokenProvider ResolveToken(this ITokenResolver self, uint token) => self.ResolveToken(token, new GenericParamContext());
}
}
| 35.703704 | 139 | 0.685685 | [
"MIT"
] | 0xd4d/dnlib | src/DotNet/ITokenResolver.cs | 964 | C# |
// MIT License
//
// Copyright (c) 2016 Wojciech Nagórski
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
using System;
namespace ExtendedXmlSerialization.Test.TestObject
{
public class TestClassPrimitiveTypesNullable
{
public void Init()
{
PropString = "Str";
PropInt = 1;
PropuInt = 2;
PropDecimal = 3.3m;
PropFloat = 7.4f;
PropDouble = 3.4;
PropEnum = TestEnum.EnumValue1;
PropLong = 234234142;
PropUlong = 2345352534;
PropShort = 23;
PropUshort = 2344;
PropDateTime = new DateTime(2014,01,23);
PropByte = 23;
PropSbyte = 33;
PropChar = 'g';
}
public void InitNull()
{
PropString = null;
PropInt = null;
PropuInt = null;
PropDecimal = null;
PropFloat = null;
PropDouble = null;
PropEnum = null;
PropLong = null;
PropUlong = null;
PropShort = null;
PropUshort = null;
PropDateTime = null;
PropByte = null;
PropSbyte = null;
PropChar = null;
}
public string PropString { get; set; }
public int? PropInt { get; set; }
public uint? PropuInt { get; set; }
public decimal? PropDecimal { get; set; }
public float? PropFloat { get; set; }
public double? PropDouble { get; set; }
public TestEnum? PropEnum { get; set; }
public long? PropLong { get; set; }
public ulong? PropUlong { get; set; }
public short? PropShort { get; set; }
public ushort? PropUshort { get; set; }
public DateTime? PropDateTime { get; set; }
public byte? PropByte { get; set; }
public sbyte? PropSbyte { get; set; }
public char? PropChar { get; set; }
}
}
| 36.560976 | 81 | 0.602402 | [
"MIT"
] | JnsV/ExtendedXmlSerializer | test/ExtendedXmlSerializerTest/TestObject/TestClassPrimitiveTypesNullable.cs | 3,001 | C# |
namespace SugCon.Website.Controllers
{
using Newtonsoft.Json;
using Sitecore;
using Sitecore.ContentSearch;
using Sitecore.ContentSearch.Maintenance;
using Sitecore.ContentSearch.Utilities;
using Sitecore.Security.Accounts;
using SugCon.Models.Notifications;
using SugCon.Website.Events;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Http;
using System.Web.Http.Results;
public class BotIndexController : ApiControllerBase
{
[HttpGet]
[Route("_bot/api/index/list")]
public IHttpActionResult List()
{
if (!IsAuthenticated)
{
return Unauthorized();
}
using (new UserSwitcher(Context.Site.Domain.GetFullName(this.ApiUser), false))
{
if (!Context.User.IsAdministrator)
{
return Unauthorized();
}
IList<IndexingUpdate> indexes = ContentSearchManager.Indexes.Where(index =>
{
return index.Group != IndexGroup.Experience && ContentSearchManager.Locator.GetInstance<ISearchIndexSwitchTracker>().IsIndexOn(index.Name);
})
.Select(index =>
{
StringBuilder sb = new StringBuilder();
sb.AppendLine(IndexingEventHandler.BuildTime(index));
sb.AppendLine(IndexingEventHandler.ThroughPut(index));
sb.AppendLine(string.Concat("Document count: ", index.Summary.NumberOfDocuments));
sb.AppendLine(string.Format("Last Updated: {0} (UTC)", string.Concat(index.Summary.LastUpdated.ToShortDateString(), " - ", index.Summary.LastUpdated.ToShortTimeString())));
var payload = new IndexingUpdate
{
IndexName = index.Name,
Message = sb.ToString(),
State = State.UnKnown,
NumberOfDocuments = index.Summary.NumberOfDocuments,
LastUpdated = index.Summary.LastUpdated,
IndexRebuildMilliseconds = IndexHealthHelper.GetIndexRebuildTime(index.Name),
IndexRebuildTime = IndexingEventHandler.BuildTime(index)
};
return payload;
}).ToList();
return new JsonResult<IList<IndexingUpdate>>(indexes, new JsonSerializerSettings(), Encoding.UTF8, this);
}
}
[HttpPost]
[Route("_bot/api/index/rebuild")]
public IHttpActionResult Rebuild([FromBody] string indexname)
{
if (!IsAuthenticated)
{
return Unauthorized();
}
using (new UserSwitcher(Context.Site.Domain.GetFullName(this.ApiUser), false))
{
if (!Context.User.IsAdministrator)
{
return Unauthorized();
}
var index = ContentSearchManager.Indexes.SingleOrDefault(idx => idx.Name == indexname);
var payload = new IndexingUpdate
{
IndexName = index.Name,
State = State.Started,
NumberOfDocuments = index.Summary.NumberOfDocuments,
LastUpdated = index.Summary.LastUpdated,
IndexRebuildMilliseconds = IndexHealthHelper.GetIndexRebuildTime(index.Name),
IndexRebuildTime = IndexingEventHandler.BuildTime(index)
};
if (index.Group == IndexGroup.Experience || !ContentSearchManager.Locator.GetInstance<ISearchIndexSwitchTracker>().IsIndexOn(index.Name))
{
payload.State = State.NotStarting;
return new JsonResult<IndexingUpdate>(payload, new JsonSerializerSettings(), Encoding.UTF8, this);
}
else
{
var job = IndexCustodian.FullRebuild(index, true);
payload.Job = job.DisplayName;
payload.State = State.Started;
return new JsonResult<IndexingUpdate>(payload, new JsonSerializerSettings(), Encoding.UTF8, this);
}
}
}
}
} | 40.0625 | 192 | 0.555605 | [
"MIT"
] | avwolferen/SitecoreBot | src/SugCon.Website/Controllers/BotIndexController.cs | 4,489 | C# |
[TestFixture]
public class ClassANotClassATests
{
} | 13.5 | 34 | 0.777778 | [
"BSD-3-Clause"
] | MarkSandy/Resharper.TestCop | Project/Src/test/data/highlighting/TestClassNameWarning/ClassBHasClassATests.cs | 54 | C# |
// Copyright 2022 Google LLC
//
// 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
//
// https://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.
// Generated code. DO NOT EDIT!
namespace Google.Cloud.ApiGateway.V1.Snippets
{
// [START apigateway_v1_generated_ApiGatewayService_ListApiConfigs_sync_flattened_resourceNames]
using Google.Api.Gax;
using Google.Cloud.ApiGateway.V1;
using System;
public sealed partial class GeneratedApiGatewayServiceClientSnippets
{
/// <summary>Snippet for ListApiConfigs</summary>
/// <remarks>
/// This snippet has been automatically generated for illustrative purposes only.
/// It may require modifications to work in your environment.
/// </remarks>
public void ListApiConfigsResourceNames()
{
// Create client
ApiGatewayServiceClient apiGatewayServiceClient = ApiGatewayServiceClient.Create();
// Initialize request argument(s)
ApiName parent = ApiName.FromProjectApi("[PROJECT]", "[API]");
// Make the request
PagedEnumerable<ListApiConfigsResponse, ApiConfig> response = apiGatewayServiceClient.ListApiConfigs(parent);
// Iterate over all response items, lazily performing RPCs as required
foreach (ApiConfig item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (ListApiConfigsResponse page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (ApiConfig item in page)
{
// Do something with each item
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<ApiConfig> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (ApiConfig item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
}
}
// [END apigateway_v1_generated_ApiGatewayService_ListApiConfigs_sync_flattened_resourceNames]
}
| 42.44 | 121 | 0.640905 | [
"Apache-2.0"
] | AlexandrTrf/google-cloud-dotnet | apis/Google.Cloud.ApiGateway.V1/Google.Cloud.ApiGateway.V1.GeneratedSnippets/ApiGatewayServiceClient.ListApiConfigsResourceNamesSnippet.g.cs | 3,183 | C# |
using System;
using UIKit;
using Foundation;
using ObjCRuntime;
using CoreGraphics;
using Firebase.Core;
namespace Firebase.CloudFunctions
{
// @interface FIRFunctions : NSObject
[DisableDefaultCtor]
[BaseType(typeof(NSObject), Name = "FIRFunctions")]
interface CloudFunctions
{
// + (FIRFunctions *)functions;
[Static]
[Export("functions")]
CloudFunctions DefaultInstance { get; }
// + (FIRFunctions *)functionsForApp:(FIRAPP *)app;
[Static]
[Export("functionsForApp:")]
CloudFunctions From(App app);
//+ (FIRFunctions *) functionsForRegion:(NSString*) region;
[Static]
[Export("functionsForRegion:")]
CloudFunctions From(string region);
//+ (FIRFunctions *)functionsForApp:(FIRApp *)app region:(NSString*) region
[Static]
[Export("functionsForApp:region:")]
CloudFunctions From(App app, string region);
//- (FIRHTTPSCallable *)HTTPSCallableWithName:(NSString *)name;
[Export("HTTPSCallableWithName:")]
HttpsCallable HttpsCallable(string name);
//- (void)useFunctionsEmulatorOrigin:(NSString *)origin
[Export("useFunctionsEmulatorOrigin:")]
void UseFunctionsEmulatorOrigin(string origin);
}
// void (^)(FIRHTTPSCallableResult *_Nullable result, NSError *_Nullable error);
delegate void HttpsCallableResultHandler([NullAllowed] HttpsCallableResult result, [NullAllowed] NSError error);
[DisableDefaultCtor]
[BaseType(typeof(NSObject), Name = "FIRHTTPSCallable")]
interface HttpsCallable
{
//- (void)callWithCompletion: (void (^)(FIRHTTPSCallableResult *_Nullable result, NSError *_Nullable error))completion;
[Export("callWithCompletion:")]
[Async]
void Call(HttpsCallableResultHandler completion);
//- (void)callWithObject:(nullable id)data completion:(void (^)(FIRHTTPSCallableResult* _Nullable result, NSError *_Nullable error))completion
[Export("callWithObject:completion:")]
[Async]
void Call([NullAllowed] NSObject data, HttpsCallableResultHandler completion);
//@property(nonatomic, assign) NSTimeInterval timeoutInterval;
[Export("timeoutInterval")]
double TimeoutInterval { get; set; }
}
[DisableDefaultCtor]
[BaseType(typeof(NSObject), Name = "FIRHTTPSCallableResult")]
interface HttpsCallableResult
{
//@property(nonatomic, strong, readonly) id data;
[Export("data")]
NSObject Data { get; }
}
}
| 30.012987 | 144 | 0.74643 | [
"MIT"
] | DigitallyImported/GoogleApisForiOSComponents | source/Firebase/CloudFunctions/ApiDefinition.cs | 2,313 | C# |
#pragma checksum "C:\Users\Burak\Documents\GitHub\natParkiAPIwithNetMVC\ParkiWEB\Views\Home\Login.cshtml" "{ff1816ec-aa5e-4d10-87f7-6f4963833460}" "e6a6fc8badbe981406bac568ecf7091f360b33ea"
// <auto-generated/>
#pragma warning disable 1591
[assembly: global::Microsoft.AspNetCore.Razor.Hosting.RazorCompiledItemAttribute(typeof(AspNetCore.Views_Home_Login), @"mvc.1.0.view", @"/Views/Home/Login.cshtml")]
namespace AspNetCore
{
#line hidden
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
#nullable restore
#line 1 "C:\Users\Burak\Documents\GitHub\natParkiAPIwithNetMVC\ParkiWEB\Views\_ViewImports.cshtml"
using ParkiWEB;
#line default
#line hidden
#nullable disable
#nullable restore
#line 2 "C:\Users\Burak\Documents\GitHub\natParkiAPIwithNetMVC\ParkiWEB\Views\_ViewImports.cshtml"
using ParkiWEB.Models;
#line default
#line hidden
#nullable disable
[global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"e6a6fc8badbe981406bac568ecf7091f360b33ea", @"/Views/Home/Login.cshtml")]
[global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"9984214517c9cc25d4da9a0f13ee7b8a4f8e87e2", @"/Views/_ViewImports.cshtml")]
public class Views_Home_Login : global::Microsoft.AspNetCore.Mvc.Razor.RazorPage<ParkiWEB.Models.User>
{
private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_0 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("href", new global::Microsoft.AspNetCore.Html.HtmlString("~/css/floatinglabel.css"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_1 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("rel", new global::Microsoft.AspNetCore.Html.HtmlString("stylesheet"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_2 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("type", "text", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_3 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("placeholder", new global::Microsoft.AspNetCore.Html.HtmlString("Username"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_4 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("value", "", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_5 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("type", "password", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_6 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("placeholder", new global::Microsoft.AspNetCore.Html.HtmlString("Password"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_7 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("method", "post", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_8 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("asp-controller", "Home", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_9 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("asp-action", "Register", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
#line hidden
#pragma warning disable 0649
private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperExecutionContext __tagHelperExecutionContext;
#pragma warning restore 0649
private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperRunner __tagHelperRunner = new global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperRunner();
#pragma warning disable 0169
private string __tagHelperStringValueBuffer;
#pragma warning restore 0169
private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperScopeManager __backed__tagHelperScopeManager = null;
private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperScopeManager __tagHelperScopeManager
{
get
{
if (__backed__tagHelperScopeManager == null)
{
__backed__tagHelperScopeManager = new global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperScopeManager(StartTagHelperWritingScope, EndTagHelperWritingScope);
}
return __backed__tagHelperScopeManager;
}
}
private global::Microsoft.AspNetCore.Mvc.Razor.TagHelpers.HeadTagHelper __Microsoft_AspNetCore_Mvc_Razor_TagHelpers_HeadTagHelper;
private global::Microsoft.AspNetCore.Mvc.Razor.TagHelpers.UrlResolutionTagHelper __Microsoft_AspNetCore_Mvc_Razor_TagHelpers_UrlResolutionTagHelper;
private global::Microsoft.AspNetCore.Mvc.Razor.TagHelpers.BodyTagHelper __Microsoft_AspNetCore_Mvc_Razor_TagHelpers_BodyTagHelper;
private global::Microsoft.AspNetCore.Mvc.TagHelpers.FormTagHelper __Microsoft_AspNetCore_Mvc_TagHelpers_FormTagHelper;
private global::Microsoft.AspNetCore.Mvc.TagHelpers.RenderAtEndOfFormTagHelper __Microsoft_AspNetCore_Mvc_TagHelpers_RenderAtEndOfFormTagHelper;
private global::Microsoft.AspNetCore.Mvc.TagHelpers.InputTagHelper __Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper;
private global::Microsoft.AspNetCore.Mvc.TagHelpers.AnchorTagHelper __Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper;
#pragma warning disable 1998
public async override global::System.Threading.Tasks.Task ExecuteAsync()
{
WriteLiteral("\n");
__tagHelperExecutionContext = __tagHelperScopeManager.Begin("head", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "e6a6fc8badbe981406bac568ecf7091f360b33ea7144", async() => {
WriteLiteral("\n ");
__tagHelperExecutionContext = __tagHelperScopeManager.Begin("link", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.SelfClosing, "e6a6fc8badbe981406bac568ecf7091f360b33ea7404", async() => {
}
);
__Microsoft_AspNetCore_Mvc_Razor_TagHelpers_UrlResolutionTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.Razor.TagHelpers.UrlResolutionTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_Razor_TagHelpers_UrlResolutionTagHelper);
__tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_0);
__tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_1);
await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);
if (!__tagHelperExecutionContext.Output.IsContentModified)
{
await __tagHelperExecutionContext.SetOutputContentAsync();
}
Write(__tagHelperExecutionContext.Output);
__tagHelperExecutionContext = __tagHelperScopeManager.End();
WriteLiteral("\n");
}
);
__Microsoft_AspNetCore_Mvc_Razor_TagHelpers_HeadTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.Razor.TagHelpers.HeadTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_Razor_TagHelpers_HeadTagHelper);
await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);
if (!__tagHelperExecutionContext.Output.IsContentModified)
{
await __tagHelperExecutionContext.SetOutputContentAsync();
}
Write(__tagHelperExecutionContext.Output);
__tagHelperExecutionContext = __tagHelperScopeManager.End();
WriteLiteral("\n");
__tagHelperExecutionContext = __tagHelperScopeManager.Begin("body", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "e6a6fc8badbe981406bac568ecf7091f360b33ea9282", async() => {
WriteLiteral("\n <div style=\"color: #f6f5f7; font-size:10.5px;\">Blank</div>\n <div class=\"container\" id=\"container\">\n\n <div class=\"container2 sign-in-container\">\n\n ");
__tagHelperExecutionContext = __tagHelperScopeManager.Begin("form", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "e6a6fc8badbe981406bac568ecf7091f360b33ea9722", async() => {
WriteLiteral("\n\n <h1 class=\"h1-white\">Login</h1>\n");
WriteLiteral("\n ");
__tagHelperExecutionContext = __tagHelperScopeManager.Begin("input", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.SelfClosing, "e6a6fc8badbe981406bac568ecf7091f360b33ea10096", async() => {
}
);
__Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.InputTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper);
#nullable restore
#line 21 "C:\Users\Burak\Documents\GitHub\natParkiAPIwithNetMVC\ParkiWEB\Views\Home\Login.cshtml"
__Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper.For = ModelExpressionProvider.CreateModelExpression(ViewData, __model => __model.UserName);
#line default
#line hidden
#nullable disable
__tagHelperExecutionContext.AddTagHelperAttribute("asp-for", __Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper.For, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
__Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper.InputTypeName = (string)__tagHelperAttribute_2.Value;
__tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_2);
__tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_3);
__Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper.Value = (string)__tagHelperAttribute_4.Value;
__tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_4);
await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);
if (!__tagHelperExecutionContext.Output.IsContentModified)
{
await __tagHelperExecutionContext.SetOutputContentAsync();
}
Write(__tagHelperExecutionContext.Output);
__tagHelperExecutionContext = __tagHelperScopeManager.End();
WriteLiteral("\n ");
__tagHelperExecutionContext = __tagHelperScopeManager.Begin("input", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.SelfClosing, "e6a6fc8badbe981406bac568ecf7091f360b33ea12192", async() => {
}
);
__Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.InputTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper);
#nullable restore
#line 22 "C:\Users\Burak\Documents\GitHub\natParkiAPIwithNetMVC\ParkiWEB\Views\Home\Login.cshtml"
__Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper.For = ModelExpressionProvider.CreateModelExpression(ViewData, __model => __model.Password);
#line default
#line hidden
#nullable disable
__tagHelperExecutionContext.AddTagHelperAttribute("asp-for", __Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper.For, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
__Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper.InputTypeName = (string)__tagHelperAttribute_5.Value;
__tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_5);
__tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_6);
__Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper.Value = (string)__tagHelperAttribute_4.Value;
__tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_4);
await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);
if (!__tagHelperExecutionContext.Output.IsContentModified)
{
await __tagHelperExecutionContext.SetOutputContentAsync();
}
Write(__tagHelperExecutionContext.Output);
__tagHelperExecutionContext = __tagHelperScopeManager.End();
WriteLiteral("\n <p><a class=\"link\" href=\"#\">Forgot your password?</a></p>\n <button id=\"btnLoginPost\" type=\"submit\" value=\"submit\">Login</button>\n ");
}
);
__Microsoft_AspNetCore_Mvc_TagHelpers_FormTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.FormTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_FormTagHelper);
__Microsoft_AspNetCore_Mvc_TagHelpers_RenderAtEndOfFormTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.RenderAtEndOfFormTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_RenderAtEndOfFormTagHelper);
__Microsoft_AspNetCore_Mvc_TagHelpers_FormTagHelper.Method = (string)__tagHelperAttribute_7.Value;
__tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_7);
await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);
if (!__tagHelperExecutionContext.Output.IsContentModified)
{
await __tagHelperExecutionContext.SetOutputContentAsync();
}
Write(__tagHelperExecutionContext.Output);
__tagHelperExecutionContext = __tagHelperScopeManager.End();
WriteLiteral(@"
</div>
<div class=""overlay-container"">
<div class=""overlay"">
<div class=""overlay-panel overlay-right"">
<br />
<h1>Hello, <br />Friend!</h1>
<br />
<p>Enter your personal details and start journey with us!</p>
<br />
");
__tagHelperExecutionContext = __tagHelperScopeManager.Begin("a", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "e6a6fc8badbe981406bac568ecf7091f360b33ea16096", async() => {
WriteLiteral("\n <button class=\"ghost\" id=\"signUp\">Sign Up</button>\n ");
}
);
__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.AnchorTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper);
__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper.Controller = (string)__tagHelperAttribute_8.Value;
__tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_8);
__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper.Action = (string)__tagHelperAttribute_9.Value;
__tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_9);
await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);
if (!__tagHelperExecutionContext.Output.IsContentModified)
{
await __tagHelperExecutionContext.SetOutputContentAsync();
}
Write(__tagHelperExecutionContext.Output);
__tagHelperExecutionContext = __tagHelperScopeManager.End();
WriteLiteral("\n\n </div>\n </div>\n </div>\n </div>\n");
}
);
__Microsoft_AspNetCore_Mvc_Razor_TagHelpers_BodyTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.Razor.TagHelpers.BodyTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_Razor_TagHelpers_BodyTagHelper);
await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);
if (!__tagHelperExecutionContext.Output.IsContentModified)
{
await __tagHelperExecutionContext.SetOutputContentAsync();
}
Write(__tagHelperExecutionContext.Output);
__tagHelperExecutionContext = __tagHelperScopeManager.End();
}
#pragma warning restore 1998
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.ViewFeatures.IModelExpressionProvider ModelExpressionProvider { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.IUrlHelper Url { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.IViewComponentHelper Component { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.Rendering.IJsonHelper Json { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.Rendering.IHtmlHelper<ParkiWEB.Models.User> Html { get; private set; }
}
}
#pragma warning restore 1591
| 82.718615 | 360 | 0.729223 | [
"MIT"
] | burakguler/natParkiAPIwithNetMVC | ParkiWEB/obj/Debug/netcoreapp3.1/Razor/Views/Home/Login.cshtml.g.cs | 19,108 | C# |
using System;
using System.Linq;
using System.Collections.Generic;
using UnityEngine;
namespace EcoBuilder.Archie
{
public class animal_object : MonoBehaviour
{
[SerializeField] SkinnedMeshRenderer smr;
[SerializeField] Animator anim;
public SkinnedMeshRenderer Renderer { get { return smr; } }
public Texture2D Eyes { get; set; }
public bool IsPlant { get; set; }
public void Die()
{
anim.SetTrigger("Die");
}
public void Live()
{
anim.SetTrigger("Live");
}
public void IdleAnimation()
{
anim.SetInteger("Which Cute", UnityEngine.Random.Range(0,2));
anim.SetTrigger("Be Cute");
}
void OnEnable()
{
enabledAnimals.Add(this);
}
void OnDisable()
{
enabledAnimals.Remove(this);
}
static HashSet<animal_object> enabledAnimals = new HashSet<animal_object>();
public static void RandomIdleAnimation()
{
int nSpecies = enabledAnimals.Count;
if (nSpecies == 0) {
return;
}
int choice = UnityEngine.Random.Range(0, nSpecies);
enabledAnimals.ElementAt(choice).IdleAnimation();
}
}
} | 27.102041 | 84 | 0.55497 | [
"MIT"
] | jxz12/EcoBuilder | Assets/Archie/Testing_Scenes/animal_object.cs | 1,330 | C# |
namespace Frank.Libraries.Ubl;
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.8.3928.0")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(Namespace = "urn:oasis:names:specification:ubl:schema:xsd:CommonSignatureComponents-2")]
[System.Xml.Serialization.XmlRootAttribute("UBLDocumentSignatures", Namespace = "urn:oasis:names:specification:ubl:schema:xsd:CommonSignatureComponents-2", IsNullable = false)]
public partial class UBLDocumentSignaturesType
{
private SignatureInformationType[] signatureInformationField;
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("SignatureInformation", Namespace = "urn:oasis:names:specification:ubl:schema:xsd:SignatureAggregateComponents-2")]
public SignatureInformationType[] SignatureInformation
{
get
{
return this.signatureInformationField;
}
set
{
this.signatureInformationField = value;
}
}
} | 39.642857 | 176 | 0.75045 | [
"MIT"
] | frankhaugen/Frank.Extensions | src/Frank.Libraries.Ubl/UBL/UBLDocumentSignaturesType.cs | 1,110 | C# |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
using System.Collections.Generic;
using Aliyun.Acs.Core;
using Aliyun.Acs.Core.Http;
using Aliyun.Acs.Core.Transform;
using Aliyun.Acs.Core.Utils;
using Aliyun.Acs.ivision.Transform;
using Aliyun.Acs.ivision.Transform.V20190308;
namespace Aliyun.Acs.ivision.Model.V20190308
{
public class CreateProjectRequest : RpcAcsRequest<CreateProjectResponse>
{
public CreateProjectRequest()
: base("ivision", "2019-03-08", "CreateProject", "ivision", "openAPI")
{
}
private string description;
private string action;
private string showLog;
private long? ownerId;
private string proType;
private string name;
public string Description
{
get
{
return description;
}
set
{
description = value;
DictionaryUtil.Add(QueryParameters, "Description", value);
}
}
public string Action
{
get
{
return action;
}
set
{
action = value;
DictionaryUtil.Add(QueryParameters, "Action", value);
}
}
public string ShowLog
{
get
{
return showLog;
}
set
{
showLog = value;
DictionaryUtil.Add(QueryParameters, "ShowLog", value);
}
}
public long? OwnerId
{
get
{
return ownerId;
}
set
{
ownerId = value;
DictionaryUtil.Add(QueryParameters, "OwnerId", value.ToString());
}
}
public string ProType
{
get
{
return proType;
}
set
{
proType = value;
DictionaryUtil.Add(QueryParameters, "ProType", value);
}
}
public string Name
{
get
{
return name;
}
set
{
name = value;
DictionaryUtil.Add(QueryParameters, "Name", value);
}
}
public override CreateProjectResponse GetResponse(UnmarshallerContext unmarshallerContext)
{
return CreateProjectResponseUnmarshaller.Unmarshall(unmarshallerContext);
}
}
}
| 21.015038 | 98 | 0.647943 | [
"Apache-2.0"
] | AxiosCros/aliyun-openapi-net-sdk | aliyun-net-sdk-ivision/Ivision/Model/V20190308/CreateProjectRequest.cs | 2,795 | 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 pinpoint-2016-12-01.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using System.Net;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.Pinpoint.Model
{
/// <summary>
/// This is the response object from the UpdateTemplateActiveVersion operation.
/// </summary>
public partial class UpdateTemplateActiveVersionResponse : AmazonWebServiceResponse
{
private MessageBody _messageBody;
/// <summary>
/// Gets and sets the property MessageBody.
/// </summary>
[AWSProperty(Required=true)]
public MessageBody MessageBody
{
get { return this._messageBody; }
set { this._messageBody = value; }
}
// Check to see if MessageBody property is set
internal bool IsSetMessageBody()
{
return this._messageBody != null;
}
}
} | 29.654545 | 106 | 0.679951 | [
"Apache-2.0"
] | ChristopherButtars/aws-sdk-net | sdk/src/Services/Pinpoint/Generated/Model/UpdateTemplateActiveVersionResponse.cs | 1,631 | C# |
using App.Shared.Commands;
using System;
namespace App.Domain.Commands.Request.Provider
{
public class DeleteProviderRequest : ICommand
{
public Guid Id { get; set; }
}
}
| 17.545455 | 49 | 0.683938 | [
"MIT"
] | carlosrogerioinfo/Core-API | App.Domain/Commands/Request/Provider/DeleteProviderRequest.cs | 195 | C# |
using System.Collections.Generic;
namespace Roki.Web.Models
{
public class ChannelViewModel
{
public Guild Guild { get; set; }
public List<Channel> Channels { get; set; }
}
} | 20.3 | 51 | 0.64532 | [
"MIT"
] | louzhang/roki | Roki.Web/Models/ViewModels.cs | 203 | C# |
namespace Basic.IO
{
using System;
/// <summary>
/// Declares input and output operations.
/// </summary>
public interface IInputOutput
{
/// <summary>
/// Occurs when the user breaks the program, f.e. when the user presses <c>Ctrl+C</c> or <c>Ctrl+Break</c>.
/// </summary>
event EventHandler OnBreak;
/// <summary>
/// Reads a single line from the input.
/// </summary>
/// <returns>The line read.</returns>
string ReadLine();
/// <summary>
/// Writes a string to the output.
/// </summary>
/// <param name="s">The string to write.</param>
void Write(string s);
/// <summary>
/// Formats string and writes it to the output.
/// </summary>
/// <param name="format">The format.</param>
/// <param name="args">The arguments.</param>
void Write(string format, params object[] args);
/// <summary>
/// Writes a string to the output and starts new line.
/// </summary>
/// <param name="s">The string to write.</param>
void WriteLine(string s);
/// <summary>
/// Formats string, writes it to the output, and starts new line.
/// </summary>
/// <param name="format">The format.</param>
/// <param name="args">The arguments.</param>
void WriteLine(string format, params object[] args);
/// <summary>
/// Starts new line.
/// </summary>
void WriteLine();
}
}
| 29.566038 | 115 | 0.529036 | [
"Unlicense"
] | markshevchenko/basic | Basic/IO/IInputOutput.cs | 1,569 | C# |
using System;
namespace LMS.Core.Models
{
/// <summary>
/// Serialization class in place of the NameValueCollection pairs
/// </summary>
/// <remarks>This exists because things like a querystring can havle multiple values, they are not a dictionary</remarks>
public struct NameValuePair
{
/// <summary>
/// The name for this variable
/// </summary>
public string Name { get; set; }
/// <summary>
/// The value for this variable
/// </summary>
public string Value { get; set; }
}
/// <summary>
/// Serialization class in place of the NameValueCollection pairs
/// </summary>
/// <remarks>This exists because things like a querystring can havle multiple values, they are not a dictionary</remarks>
public struct NameValueIntPair
{
/// <summary>
/// The name for this variable
/// </summary>
public string Name { get; set; }
/// <summary>
/// The value for this variable
/// </summary>
public int Value { get; set; }
}
public struct miniLog
{
public long Id { get; set; }
public string Type { get; set; }
public string Message { get; set; }
public DateTime Date { get; set; }
}
}
| 28.478261 | 125 | 0.576336 | [
"MIT"
] | RaynaldM/Shitsuke | LMS.Core/Models/BaseModels.cs | 1,312 | C# |
using System.Collections.Generic;
using APIS.WebScrapperLogic.Utils;
namespace APIS.WebScrapperLogic.Interfaces
{
public interface IWebScrapper
{
bool CanWebscrape(string companyGLN, string productURL);
WebScrappedData Webscrape(string hyperlink);
WebScrappedData FindAndWebscrape(string gtin, string internalCode, string description);
List<string> Find(string gtin, string internalCode, string description);
}
}
| 32.785714 | 95 | 0.755991 | [
"Unlicense"
] | alexmanie/docker-chrome-selenium | APIS.WebScrapperLogic/Interfaces/IWebScrapper.cs | 461 | C# |
using System;
using Reinforced.Tecture.Testing;
namespace Reinforced.Tecture.Features.Orm.Testing.Checks.Delete
{
public static class DeleteChecks
{
public static DeletePredicateCheck<T> Delete<T>(Func<T, bool> predicate, string explanation) => new DeletePredicateCheck<T>(predicate, explanation);
}
}
| 29.454545 | 156 | 0.753086 | [
"MIT"
] | ForNeVeR/Reinforced.Tecture | Features/Reinforced.Tecture.Features.Orm/Testing/Checks/Delete/DeleteChecks.cs | 326 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CinematicActionSetVariable : CinematicAction
{
private string mKey;
private string mValue;
public override string actionName
{
get
{
return "set";
}
}
public override void InterpretParameters(CinematicDataProvider dataProvider)
{
base.InterpretParameters(dataProvider);
mKey = mParameters["key"]; // Use the raw value to ensure it doesn't get converted...
mValue = dataProvider.GetStringData(mParameters, "value");
}
public override IEnumerator PlayInternal(CinematicDirector player)
{
player.dataProvider.SetData(mKey, mValue);
yield break;
}
}
| 23.181818 | 93 | 0.671895 | [
"Unlicense",
"MIT"
] | bdsowers/cutiequest | Assets/Scripts/Core/Cinematic/CinematicActions/CinematicActionSetVariable.cs | 767 | C# |
// This file is part of the re-linq project (relinq.codeplex.com)
// Copyright (C) 2005-2009 rubicon informationstechnologie gmbh, www.rubicon.eu
//
// re-linq is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License as published by the
// Free Software Foundation; either version 2.1 of the License,
// or (at your option) any later version.
//
// re-linq is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with re-linq; if not, see http://www.gnu.org/licenses.
//
using System;
using System.Linq.Expressions;
using System.Linq;
using Remotion.Linq.Clauses.Expressions;
using Remotion.Linq.Clauses.ExpressionTreeVisitors;
using Remotion.Linq.Clauses.StreamedData;
using Remotion.Linq.Utilities;
namespace Remotion.Linq.Clauses.ResultOperators
{
/// <summary>
/// Represents aggregating the items returned by a query into a single value. The first item is used as the seeding value for the aggregating
/// function.
/// This is a result operator, operating on the whole result set of a query.
/// </summary>
/// <example>
/// In C#, the "Aggregate" call in the following example corresponds to an <see cref="AggregateResultOperator"/>.
/// <code>
/// var result = (from s in Students
/// select s.Name).Aggregate((allNames, name) => allNames + " " + name);
/// </code>
/// </example>
public class AggregateResultOperator : ValueFromSequenceResultOperatorBase
{
private LambdaExpression _func;
/// <summary>
/// Initializes a new instance of the <see cref="AggregateResultOperator"/> class.
/// </summary>
/// <param name="func">The aggregating function. This is a <see cref="LambdaExpression"/> taking a parameter that represents the value accumulated so
/// far and returns a new accumulated value. This is a resolved expression, i.e. items streaming in from prior clauses and result operators
/// are represented as expressions containing <see cref="QuerySourceReferenceExpression"/> nodes.</param>
public AggregateResultOperator (LambdaExpression func)
{
ArgumentUtility.CheckNotNull ("func", func);
Func = func;
}
/// <summary>
/// Gets or sets the aggregating function. This is a <see cref="LambdaExpression"/> taking a parameter that represents the value accumulated so
/// far and returns a new accumulated value. This is a resolved expression, i.e. items streaming in from prior clauses and result operators
/// are represented as expressions containing <see cref="QuerySourceReferenceExpression"/> nodes.
/// </summary>
/// <value>The aggregating function.</value>
public LambdaExpression Func
{
get { return _func; }
set
{
ArgumentUtility.CheckNotNull ("value", value);
if (!DescribesValidFuncType (value))
{
var message = string.Format (
"The aggregating function must be a LambdaExpression that describes an instantiation of 'Func<T,T>', but it is '{0}'.",
value.Type);
throw new ArgumentTypeException (message, "value", typeof (Func<,>), value.Type);
}
_func = value;
}
}
/// <inheritdoc />
public override StreamedValue ExecuteInMemory<T> (StreamedSequence input)
{
ArgumentUtility.CheckNotNull ("input", input);
var sequence = input.GetTypedSequence<T>();
var funcLambda = ReverseResolvingExpressionTreeVisitor.ReverseResolveLambda (input.DataInfo.ItemExpression, Func, 1);
var func = (Func<T, T, T>) funcLambda.Compile ();
var result = sequence.Aggregate (func);
return new StreamedValue (result, (StreamedValueInfo) GetOutputDataInfo (input.DataInfo));
}
/// <inheritdoc />
public override ResultOperatorBase Clone (CloneContext cloneContext)
{
return new AggregateResultOperator (Func);
}
/// <inheritdoc />
public override IStreamedDataInfo GetOutputDataInfo (IStreamedDataInfo inputInfo)
{
var sequenceInfo = ArgumentUtility.CheckNotNullAndType<StreamedSequenceInfo> ("inputInfo", inputInfo);
var expectedItemType = GetExpectedItemType();
CheckSequenceItemType (sequenceInfo, expectedItemType);
return new StreamedScalarValueInfo (sequenceInfo.ItemExpression.Type);
}
public override void TransformExpressions (Func<Expression, Expression> transformation)
{
ArgumentUtility.CheckNotNull ("transformation", transformation);
Func = (LambdaExpression) transformation (Func);
}
/// <inheritdoc />
public override string ToString ()
{
return "Aggregate(" + FormattingExpressionTreeVisitor.Format (Func) + ")";
}
private bool DescribesValidFuncType (LambdaExpression value)
{
var funcType = value.Type;
if (!funcType.IsGenericType || funcType.GetGenericTypeDefinition () != typeof (Func<,>))
return false;
var genericArguments = funcType.GetGenericArguments ();
return genericArguments[0] == genericArguments[1];
}
private Type GetExpectedItemType ()
{
return Func.Type.GetGenericArguments ()[0];
}
}
} | 39.773723 | 154 | 0.697926 | [
"MIT"
] | rajcybage/BrightstarDB | src/portable/BrightstarDB.Portable/relinq/RelinqCore/Clauses/ResultOperators/AggregateResultOperator.cs | 5,449 | C# |
using Promitor.Core.Scraping.Configuration.Serialization;
using Promitor.Core.Scraping.Configuration.Serialization.v1.Model;
using Promitor.Core.Scraping.Configuration.Serialization.v1.Model.ResourceTypes;
using Promitor.Core.Scraping.Configuration.Serialization.v1.Providers;
using Xunit;
namespace Promitor.Scraper.Tests.Unit.Serialization.v1.Providers
{
public class StorageAccountDeserializerTests : ResourceDeserializerTest<StorageAccountDeserializer>
{
private readonly StorageAccountDeserializer _deserializer;
public StorageAccountDeserializerTests()
{
_deserializer = new StorageAccountDeserializer(Logger);
}
[Fact]
public void Deserialize_AccountNameSupplied_SetsAccountName()
{
const string storageAccountName = "promitor-account";
YamlAssert.PropertySet<StorageAccountResourceV1, AzureResourceDefinitionV1, string>(
_deserializer,
$"accountName: {storageAccountName}",
storageAccountName,
r => r.AccountName);
}
[Fact]
public void Deserialize_AccountNameNotSupplied_Null()
{
YamlAssert.PropertyNull<StorageAccountResourceV1, AzureResourceDefinitionV1>(
_deserializer,
"resourceGroupName: promitor-group",
r => r.AccountName);
}
protected override IDeserializer<AzureResourceDefinitionV1> CreateDeserializer()
{
return new StorageAccountDeserializer(Logger);
}
}
} | 36.883721 | 103 | 0.686003 | [
"MIT"
] | DaveOHenry/promitor | src/Promitor.Scraper.Tests.Unit/Serialization/v1/Providers/StorageAccountDeserializerTests.cs | 1,588 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BrokenMOFatImageDump
{
class DirEnt
{
internal const int DirEntSize = 32;
internal string FileName;
internal string FileExt;
internal byte Attributes;
internal int Time;
internal int Date;
internal int FatEntry;
internal int FileSize;
internal DateTime GetDateTime()
{
int year = ((Date >> 9) & 0x7f) + 1980;
int month = (Date >> 5) & 0xf;
int day = Date & 0x1f;
int hour = (Time >> 11) & 0x1f;
int minutes = (Time >> 5) & 0x3f;
int second = Time & 0x1f;
return new DateTime(year, month, day, hour, minutes, second);
}
internal string GetFileName()
{
if( string.IsNullOrWhiteSpace(FileExt))
{
return FileName;
}
return $"{FileName}.{FileExt}";
}
internal bool IsReadOnly => (Attributes & 0x01) != 0;
internal bool IsHidden => (Attributes & 0x02) != 0;
internal bool IsSystemFile => (Attributes & 0x04) != 0;
internal bool IsVolumeLabel => (Attributes & 0x08) != 0;
internal bool IsDirectory => (Attributes & 0x10) != 0;
internal bool IsArchive => (Attributes & 0x20) != 0;
internal void Dump()
{
Console.WriteLine($"{GetFileName():12} {FileSize:10} {FatEntry:X8} {Attributes:X2}");
}
}
class Directory
{
internal DirEnt[] Entries;
private static Directory loadCommon(FileStream stream, int size, byte[] all)
{
var dir = new Directory();
var list = new List<DirEnt>();
for (int i = 0; i < size; i += DirEnt.DirEntSize)
{
if (all[i] == 0) break;
if (all[i] == 0xe5) continue;
// may be broken
//if (all[i] == 0xcf && all[i + 1] == 0x23) return null;
// may be broken
//if (all[i+8] >= 0x80 && all[i + 9] >= 0x80 && all[i + 10] >= 0x80) return null;
var ent = new DirEnt();
ent.FileName = Util.SJ2String(all, i, 8).Trim();
ent.FileExt = Util.SJ2String(all, i + 8, 3).Trim();
ent.Attributes = all[i + 0xb];
ent.Time = all[i + 0x16] + (all[i + 0x17] << 8);
ent.Date = all[i + 0x18] + (all[i + 0x19] << 8);
ent.FatEntry = all[i + 0x1a] + (all[i + 0x1b] << 8);
ent.FileSize = all[i + 0x1c] + (all[i + 0x1d] << 8) + (all[i + 0x1e] << 16) + (all[i + 0x1f] << 24);
if (Util.IsVerbose) ent.Dump();
if (ent.Attributes != 0x0f) list.Add(ent);
}
dir.Entries = list.ToArray();
return dir;
}
internal static Directory LoadRoot(FileStream stream, IPL ipl, FAT fat)
{
var size = ipl.TotalRootDirectories * DirEnt.DirEntSize;
byte[] all = new byte[size];
stream.Read(all, 0, all.Length);
var r = loadCommon(stream, size, all);
ipl.DataAreaOffset = (int)stream.Position;
return r;
}
internal static Directory LoadSubDir(FileStream stream, byte[] allEntries, IPL ipl, FAT fat)
{
var r = loadCommon(stream, allEntries.Length, allEntries);
return r;
}
}
}
| 35.336634 | 116 | 0.508266 | [
"MIT"
] | autumn009/d88explorer | BrokenMOFatImageDump/BrokenMOFatImageDump/Directory.cs | 3,571 | C# |
/***************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
This code is licensed under the Visual Studio SDK license terms.
THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
***************************************************************************/
using System;
using System.Text;
using System.IO;
namespace Microsoft.VisualStudio.Shell
{
/// <summary>
/// Used to provide registration information to the XML Chooser
/// for a custom XML designer.
/// </summary>
[AttributeUsage(AttributeTargets.Class, AllowMultiple = true, Inherited = true)]
public sealed class ProvideXmlEditorChooserDesignerViewAttribute : RegistrationAttribute
{
const string XmlChooserFactory = "XmlChooserFactory";
const string XmlChooserEditorExtensionsKeyPath = @"Editors\{32CC8DFA-2D70-49b2-94CD-22D57349B778}\Extensions";
const string XmlEditorFactoryGuid = "{FA3CD31E-987B-443A-9B81-186104E8DAC1}";
private string name;
private string extension;
private Guid defaultLogicalView;
private int xmlChooserPriority;
/// <summary>
/// Constructor for ProvideXmlEditorChooserDesignerViewAttribute.
/// </summary>
/// <param name="name">The registry keyName for your XML editor. For example "RESX", "Silverlight", "Workflow", etc...</param>
/// <param name="extension">The file extension for your custom XML type (e.g. "xaml", "resx", "xsd").</param>
/// <param name="defaultLogicalViewEditorFactory">A Type, Guid, or String object representing the editor factory for the default logical view.</param>
/// <param name="xmlChooserPriority">The priority of the extension in the XML Chooser. This value must be greater than the extension's priority value for the XML designer's EditorFactory.</param>
public ProvideXmlEditorChooserDesignerViewAttribute(string name, string extension, object defaultLogicalViewEditorFactory, int xmlChooserPriority)
{
if (string.IsNullOrWhiteSpace(name))
{
throw new ArgumentException("Editor description cannot be null or empty.", "editorDescription");
}
if (string.IsNullOrWhiteSpace(extension))
{
throw new ArgumentException("Extension cannot be null or empty.", "extension");
}
if (defaultLogicalViewEditorFactory == null)
{
throw new ArgumentNullException("defaultLogicalViewEditorFactory");
}
this.name = name;
this.extension = extension;
this.defaultLogicalView = TryGetGuidFromObject(defaultLogicalViewEditorFactory);
this.xmlChooserPriority = xmlChooserPriority;
this.CodeLogicalViewEditor = XmlEditorFactoryGuid;
this.DebuggingLogicalViewEditor = XmlEditorFactoryGuid;
this.DesignerLogicalViewEditor = XmlEditorFactoryGuid;
this.TextLogicalViewEditor = XmlEditorFactoryGuid;
}
public override void Register(RegistrationContext context)
{
if (context == null)
{
throw new ArgumentNullException("context");
}
using (Key xmlChooserExtensions = context.CreateKey(XmlChooserEditorExtensionsKeyPath))
{
xmlChooserExtensions.SetValue(extension, xmlChooserPriority);
}
using (Key key = context.CreateKey(GetKeyName()))
{
key.SetValue("DefaultLogicalView", defaultLogicalView.ToString("B").ToUpperInvariant());
key.SetValue("Extension", extension);
if (!string.IsNullOrWhiteSpace(Namespace))
{
key.SetValue("Namespace", Namespace);
}
if (MatchExtensionAndNamespace)
{
key.SetValue("Match", "both");
}
if (IsDataSet.HasValue)
{
key.SetValue("IsDataSet", Convert.ToInt32(IsDataSet.Value));
}
SetLogicalViewMapping(key, VSConstants.LOGVIEWID_Debugging, DebuggingLogicalViewEditor);
SetLogicalViewMapping(key, VSConstants.LOGVIEWID_Code, CodeLogicalViewEditor);
SetLogicalViewMapping(key, VSConstants.LOGVIEWID_Designer, DesignerLogicalViewEditor);
SetLogicalViewMapping(key, VSConstants.LOGVIEWID_TextView, TextLogicalViewEditor);
}
}
private void SetLogicalViewMapping(Key key, Guid logicalView, object editorFactory)
{
if (editorFactory != null)
{
key.SetValue(logicalView.ToString("B").ToUpperInvariant(), TryGetGuidFromObject(editorFactory).ToString("B").ToUpperInvariant());
}
}
private Guid TryGetGuidFromObject(object guidObject)
{
// figure out what type of object they passed in and get the GUID from it
if (guidObject is string)
return new Guid((string)guidObject);
else if (guidObject is Type)
return ((Type)guidObject).GUID;
else if (guidObject is Guid)
return (Guid)guidObject;
else
throw new ArgumentException("Could not determine Guid from supplied object.", "guidObject");
}
public override void Unregister(RegistrationContext context)
{
if (context == null)
{
throw new ArgumentNullException("context");
}
context.RemoveKey(GetKeyName());
context.RemoveValue(XmlChooserEditorExtensionsKeyPath, extension);
context.RemoveKeyIfEmpty(XmlChooserEditorExtensionsKeyPath);
}
private string GetKeyName()
{
return Path.Combine(XmlChooserFactory, name);
}
/// <summary>
/// The XML Namespace used in documents that this editor supports.
/// </summary>
public string Namespace { get; set; }
/// <summary>
/// Boolean value indicating whether the XML chooser should match on both the file extension
/// and the Namespace. If false, the XML chooser will match on either the extension or the
/// Namespace.
/// </summary>
public bool MatchExtensionAndNamespace { get; set; }
/// <summary>
/// Special value used only by the DataSet designer.
/// </summary>
public bool? IsDataSet { get; set; }
/// <summary>
/// The editor factory to associate with the debugging logical view
/// </summary>
public object DebuggingLogicalViewEditor { get; set; }
/// <summary>
/// The editor factory to associate with the code logical view
/// </summary>
public object CodeLogicalViewEditor { get; set; }
/// <summary>
/// The editor factory to associate with the designer logical view
/// </summary>
public object DesignerLogicalViewEditor { get; set; }
/// <summary>
/// The editor factory to associate with the text logical view
/// </summary>
public object TextLogicalViewEditor { get; set; }
}
}
| 42.043478 | 204 | 0.597208 | [
"MIT"
] | Azure3bt/Xinq | Projects/Package/Sources/Xinq/Microsoft.VisualStudio.Shell/ProvideXmlEditorChooserDesignerViewAttribute.cs | 7,738 | C# |
using System.IO;
using System.Threading;
using System.Threading.Tasks;
namespace ThirdPartyLibraries.NuGet
{
public interface INuGetApi
{
Task<byte[]> ExtractSpecAsync(NuGetPackageId package, byte[] packageContent, CancellationToken token);
NuGetSpec ParseSpec(Stream content);
Task<string> ResolveLicenseCodeAsync(string licenseUrl, CancellationToken token);
Task<byte[]> DownloadPackageAsync(NuGetPackageId package, bool allowToUseLocalCache, CancellationToken token);
Task<byte[]> LoadFileContentAsync(byte[] packageContent, string fileName, CancellationToken token);
}
} | 33.263158 | 118 | 0.757911 | [
"MIT"
] | max-ieremenko/ThirdPartyLibraries | Sources/ThirdPartyLibraries.NuGet/INuGetApi.cs | 634 | C# |
using UnityEngine;
using System;
using System.Collections;
using System.Collections.Generic;
namespace puzzlegen.database {
public class DBItem
{
private string _className;
public string ClassName {
get { return _className; }
}
private Dictionary<string, object> _properties;
public bool Spawned {
get { return _numSpawned >= _capacity; }
}
private int _capacity;
private int _numSpawned;
// For giving items unique spawn indices
private int _nextSpawnIndex;
public int NextSpawnIndex {
get { return _nextSpawnIndex++; }
}
private bool _abstract;
public bool Abstract {
get { return _abstract; }
}
public DBItem(string className)
{
_className = className;
_numSpawned = 0;
_capacity = 1;
_abstract = false;
_properties = new Dictionary<string, object>();
_properties["classname"] = className;
_properties["carryable"] = false;
_properties["NPC"] = false;
_properties["mutables"] = new List<string>();
}
public void setProperty(string propertyName, object propertyVal)
{
if (propertyName == "abstract")
_abstract = (bool)propertyVal;
if (propertyName == "capacity" && (int)propertyVal > 0)
_capacity = (int)propertyVal;
_properties[propertyName] = propertyVal;
}
public object getProperty(string propertyName)
{
if (_properties.ContainsKey(propertyName))
return _properties[propertyName];
return null;
}
public List<string> getPropertyNames()
{
return new List<string>(_properties.Keys);
}
public bool propertyExists(string propertyName)
{
return _properties.ContainsKey(propertyName);
}
public DBItem copyToNewName(string newName)
{
DBItem newDBItem = new DBItem(newName);
foreach(KeyValuePair<string, object> keyVal in _properties) {
if (keyVal.Key != "classname")
newDBItem.setProperty(keyVal.Key, keyVal.Value);
}
return newDBItem;
}
public PuzzleItem spawnItem()
{
_numSpawned++;
PuzzleItem itemToReturn = new PuzzleItem(_className);
List<string> mutables;
if (_properties.ContainsKey("mutables"))
mutables = _properties["mutables"] as List<string>;
else
mutables = new List<string>();
// Copy properties from the dbitem to the output item
foreach (string propertyName in _properties.Keys) {
if (!mutables.Contains(propertyName))
itemToReturn.setProperty(propertyName, _properties[propertyName]);
}
return itemToReturn;
}
public void despawnItem()
{
_numSpawned--;
}
}
}
| 22.663793 | 72 | 0.670978 | [
"MIT"
] | alect/Puzzledice | Unity/Sandwitch/Assets/puzzlegen/database/DBItem.cs | 2,629 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
namespace System.Security.Policy
{
[Flags]
public enum PolicyStatementAttribute
{
All = 3,
Exclusive = 1,
LevelFinal = 2,
Nothing = 0,
}
}
| 21.666667 | 71 | 0.633846 | [
"MIT"
] | 2m0nd/runtime | src/libraries/System.Security.Permissions/src/System/Security/Policy/PolicyStatementAttribute.cs | 325 | C# |
//--------------------------------------------------------------------------------------------------
// <copyright file="ReleaseArtifactRepositoryTest.cs" company="Traeger Industry Components GmbH">
// This file is protected by Traeger Industry Components GmbH Copyright © 2019-2020.
// </copyright>
// <author>Fabian Traeger</author>
// <author>Timo Walter</author>
//--------------------------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.IO.Compression;
using System.Linq;
using FluentAssertions;
using Microsoft.Extensions.Logging;
using NSubstitute;
using ReleaseServer.WebApi.Models;
using Xunit;
namespace ReleaseServer.WebApi.Test
{
public class ReleaseArtifactRepositoryTest
{
private IReleaseArtifactRepository fsReleaseArtifactRepository;
private readonly string projectDirectory;
public ReleaseArtifactRepositoryTest()
{
//Could be done smarter
projectDirectory = TestUtils.GetProjectDirectory();
var artifactRootDirectory = new DirectoryInfo(Path.Combine(projectDirectory, "TestData"));
var backupRootDirectory = new DirectoryInfo(Path.Combine(projectDirectory, "TestBackupDir"));
fsReleaseArtifactRepository = new FsReleaseArtifactRepository(
Substitute.For<ILogger<FsReleaseArtifactRepository>>(),
artifactRootDirectory,
backupRootDirectory
);
}
[Fact]
public void TestStoringArtifact()
{
//Cleanup test dir from old tests (if they failed before)
TestUtils.CleanupDirIfExists(Path.Combine(projectDirectory, "TestData", "product"));
var testPath = Path.Combine(projectDirectory, "TestData", "product", "ubuntu", "amd64", "1.1");
//Create test artifact from a zip file
var testFile = File.ReadAllBytes(Path.Combine(projectDirectory, "TestData", "test_zip.zip"));
using var stream = new MemoryStream(testFile);
var testZip = new ZipArchive(stream);
var testArtifact = ReleaseArtifactMapper.ConvertToReleaseArtifact("product", "ubuntu",
"amd64", "1.1", testZip);
//Create the update test artifact from a zip file
var testUpdateFile = File.ReadAllBytes(Path.Combine(projectDirectory, "TestData", "update_test_zip.zip"));
using var updateStream = new MemoryStream(testUpdateFile);
var testUpdateZip = new ZipArchive(updateStream);
var testUpdateArtifact = ReleaseArtifactMapper.ConvertToReleaseArtifact("product", "ubuntu",
"amd64", "1.1", testUpdateZip);
//Act
//########################################
//1. Store the first artifact -> product folder will be created
//########################################
fsReleaseArtifactRepository.StoreArtifact(testArtifact);
//Assert if the directory and the unzipped files exist
Assert.True(Directory.Exists(testPath));
Assert.True(File.Exists(Path.Combine(testPath, "releaseNotes.json")));
Assert.True(File.Exists(Path.Combine(testPath, "testprogram.exe")));
Assert.True(File.Exists(Path.Combine(testPath, "deployment.json")));
//########################################
//2. Update the already existing product with the same artifact -> artifact folder & content will be updated
//########################################
fsReleaseArtifactRepository.StoreArtifact(testUpdateArtifact);
//Assert if the directory and the unzipped files exist
Assert.True(Directory.Exists(testPath));
Assert.True(File.Exists(Path.Combine(testPath, "releaseNotes_update.json")));
Assert.True(File.Exists(Path.Combine(testPath, "testprogram_update.exe")));
Assert.True(File.Exists(Path.Combine(testPath, "deployment_update.json")));
//Cleanup
//Directory.Delete(Path.Combine(ProjectDirectory, "TestData", "product"), true);
}
[Fact]
public void TestGetInfosByProductName()
{
//Setup
var testProductPath = Path.Combine(projectDirectory, "TestData", "testproduct", "debian", "amd64", "1.1");
//Cleanup test dir from old tests (if they failed before)
TestUtils.CleanupDirIfExists(Path.Combine(projectDirectory, "TestData", "testproduct"));
Directory.CreateDirectory(testProductPath);
var test = new DirectoryInfo(Path.Combine(projectDirectory, "TestData", "productx", "debian", "amd64", "1.1"));
foreach (var file in test.GetFiles())
{
file.CopyTo(Path.Combine(testProductPath, file.Name));
}
var expectedProductInfo = new ProductInformation
{
Identifier = "testproduct",
Os = "debian",
Architecture = "amd64",
Version = new ProductVersion("1.1"),
ReleaseNotes = new ReleaseNotes
{
Changes = new Dictionary<CultureInfo, List<ChangeSet>>
{
{
new CultureInfo("de"), new List<ChangeSet>
{
new ChangeSet
{
Platforms = new List<string>{"windows/any", "linux/rpi"},
Added = new List<string>{"added de 1"}
}
}
},
{
new CultureInfo("en"), new List<ChangeSet>
{
new ChangeSet
{
Platforms = new List<string>{"windows/any", "linux/rpi"},
Added = new List<string>{"added en 1"}
}
}
}
}
}
};
//Act
var testProductInfo = fsReleaseArtifactRepository.GetInfosByProductName("testproduct");
//Assert
testProductInfo.Should().BeEquivalentTo(expectedProductInfo);
//Cleanup
Directory.Delete(Path.Combine(projectDirectory, "TestData", "testproduct"), true);
}
[Fact]
public void TestGetPlatforms()
{
//Setup
List<string> expectedPlatforms1 = new List<string>()
{"ubuntu-amd64", "ubuntu-arm64"};
List<string> expectedPlatforms2 = new List<string>()
{"debian-amd64", "ubuntu-amd64"};
List<string> expectedPlatforms3 = new List<string>()
{"debian-amd64"};
//Act
var testPlatforms1 = fsReleaseArtifactRepository.GetPlatforms("productx", "1.0");
var testPlatforms2 = fsReleaseArtifactRepository.GetPlatforms("productx", "1.1");
var testPlatforms3 = fsReleaseArtifactRepository.GetPlatforms("productx", "1.2-beta");
//Assert
Assert.Equal(expectedPlatforms1, testPlatforms1);
Assert.Equal(expectedPlatforms2, testPlatforms2);
Assert.Equal(expectedPlatforms3, testPlatforms3);
}
[Fact]
public void TestGetVersions()
{
//Setup
var expectedVersions1 = new List<ProductVersion>
{new ProductVersion("1.2-beta"), new ProductVersion("1.1")};
var expectedVersions2 = new List<ProductVersion>
{ new ProductVersion("1.1"), new ProductVersion("1.0")};
var expectedVersions3 = new List<ProductVersion>
{new ProductVersion("1.0")};
//Act
var testVersions1 = fsReleaseArtifactRepository.GetVersions("productx", "debian", "amd64");
var testVersions2 = fsReleaseArtifactRepository.GetVersions("productx", "ubuntu", "amd64");
var testVersions3 = fsReleaseArtifactRepository.GetVersions("productx", "ubuntu", "arm64");
//Assert
Assert.Equal(expectedVersions1, testVersions1);
Assert.Equal(expectedVersions2, testVersions2);
Assert.Equal(expectedVersions3, testVersions3);
}
[Fact]
public void TestGetReleaseInfo()
{
//Setup
ReleaseInformation expectedReleaseInfo;
expectedReleaseInfo = new ReleaseInformation
{
ReleaseDate = new DateTime(2020, 02, 10),
ReleaseNotes = new ReleaseNotes
{
Changes = new Dictionary<CultureInfo, List<ChangeSet>>
{
{new CultureInfo("de"), new List<ChangeSet>
{
new ChangeSet
{
Platforms = new List<string>{"windows/any", "linux/rpi"},
Added = new List<string>{"added de 1", "added de 2"},
Fixed = new List<string>{"fix de 1", "fix de 2"},
Breaking = new List<string>{"breaking de 1", "breaking de 2"},
Deprecated = new List<string>{"deprecated de 1", "deprecated de 2"}
}
}
},
{new CultureInfo("en"), new List<ChangeSet>
{
new ChangeSet
{
Platforms = new List<string>{"windows/any", "linux/rpi"},
Added = new List<string>{"added en 1", "added en 2"},
Fixed = new List<string>{"fix en 1", "fix en 2"},
Breaking = new List<string>{"breaking en 1", "breaking en 2"},
Deprecated = new List<string>{"deprecated en 1", "deprecated en 2"}
},
new ChangeSet
{
Platforms = null,
Added = new List<string>{"added en 3"},
Fixed = new List<string>{"fix en 3"},
Breaking = new List<string>{"breaking en 3"},
Deprecated = new List<string>{"deprecated en 3"}
}
}
}
}
}
};
//Act
var testReleaseInfo = fsReleaseArtifactRepository.GetReleaseInfo("productx", "ubuntu",
"amd64", "1.1");
//Assert
testReleaseInfo.Should().BeEquivalentTo(expectedReleaseInfo);
}
[Fact]
public void TestGetReleaseInfo_Not_Found()
{
//Act
var testReleaseInfo = fsReleaseArtifactRepository.GetReleaseInfo("nonexistentProduct", "noOS", "noArch", "0");
//Assert
Assert.Null(testReleaseInfo);
}
[Fact]
public void TestGetSpecificArtifact()
{
//Setup
var expectedArtifact = new ArtifactDownload
{
FileName = Path.GetFileName(Path.Combine(projectDirectory, "TestData", "productx",
"ubuntu", "amd64", "1.1", "artifact.zip")),
Payload = File.ReadAllBytes(Path.Combine(projectDirectory, "TestData", "productx",
"ubuntu", "amd64", "1.1", "artifact.zip"))
};
//Act
var testArtifact = fsReleaseArtifactRepository.GetSpecificArtifact("productx",
"ubuntu", "amd64", "1.1");
//Assert
testArtifact.Should().BeEquivalentTo(expectedArtifact);
}
[Fact]
public void TestGetSpecificArtifact_Not_Found()
{
//Act
var testArtifact = fsReleaseArtifactRepository.GetSpecificArtifact("nonexistentProduct", "noOS", "noArch", "0");
//Assert
Assert.Null(testArtifact);
}
[Fact]
public void TestDeleteSpecificArtifact()
{
//Setup
//Cleanup test dir from old tests (if they failed before)
TestUtils.CleanupDirIfExists(Path.Combine(projectDirectory, "TestData", "producty"));
TestUtils.SetupTestDirectory(projectDirectory);
//Act
var productFound = fsReleaseArtifactRepository.DeleteSpecificArtifactIfExists("producty", "ubuntu", "amd64", "1.1");
//Assert
Assert.True(productFound);
Assert.False(Directory.Exists(Path.Combine(projectDirectory, "TestData", "producty", "ubuntu", "amd64", "1.1")));
//Cleanup
Directory.Delete(Path.Combine(projectDirectory, "TestData", "producty"), true);
}
[Fact]
public void TestDeleteSpecificArtifact_Not_Found()
{
//Act
var productFound = fsReleaseArtifactRepository.DeleteSpecificArtifactIfExists("nonexistentProduct", "noOS", "noArch", "0");
//Assert
Assert.False(productFound);
}
[Fact]
public void TestDeleteProduct()
{
//Setup
//Cleanup test dir from old tests (if they failed before)
TestUtils.CleanupDirIfExists(Path.Combine(projectDirectory, "TestData", "producty"));
TestUtils.SetupTestDirectory(projectDirectory);
//Act
var artifactFound = fsReleaseArtifactRepository.DeleteProductIfExists("producty");
//Assert
Assert.True(artifactFound);
Assert.False(Directory.Exists(Path.Combine(projectDirectory, "TestData", "producty")));
}
[Fact]
public void TestDeleteProductI_Not_Found()
{
//Act
var artifactFound = fsReleaseArtifactRepository.DeleteProductIfExists("nonexistentProduct");
//Assert
Assert.False(artifactFound); }
[Fact]
public void TestRunBackup()
{
//Setup
var testArtifactRoot = new DirectoryInfo(Path.Combine(projectDirectory, "TestArtifactRoot"));
var testBackupDir = new DirectoryInfo(Path.Combine(projectDirectory, "TestBackup"));
//Cleanup test dir from old tests (if they failed before)
TestUtils.CleanupDirIfExists(testArtifactRoot.FullName);
TestUtils.CleanupDirIfExists(testBackupDir.FullName);
if (!testArtifactRoot.Exists) {
testArtifactRoot.Create();
}
if (!testBackupDir.Exists) {
testBackupDir.Create();
}
var customRepository = new FsReleaseArtifactRepository(
Substitute.For<ILogger<FsReleaseArtifactRepository>>(),
testArtifactRoot,
testBackupDir
);
var expectedFile = File.ReadAllBytes(Path.Combine(projectDirectory, "TestData", "test_zip.zip"));
//Copy to the test file to the custom ArtifactRootDirectory
File.Copy(Path.Combine(projectDirectory, "TestData", "test_zip.zip"), Path.Combine(testArtifactRoot.FullName, "test_zip.zip"));
//Act
customRepository.RunBackup();
var backupFiles = Directory.GetFiles(testBackupDir.FullName);
//There is only one file -> .First() is used
ZipFile.ExtractToDirectory(backupFiles.First(), testBackupDir.FullName);
File.Delete(backupFiles.First());
//Get the actual file in the directory
backupFiles = Directory.GetFiles(testBackupDir.FullName);
var backupFile = File.ReadAllBytes(backupFiles.First());
//Assert
Assert.Equal(expectedFile, backupFile);
//Cleanup
testArtifactRoot.Delete(true);
testBackupDir.Delete(true);
}
[Fact]
public void TestRestore()
{
var testArtifactRoot = new DirectoryInfo(Path.Combine(projectDirectory, "TestArtifactRoot"));
var testBackupDir = new DirectoryInfo(Path.Combine(projectDirectory, "TestBackup"));
//Cleanup test dir from old tests (if they failed before)
TestUtils.CleanupDirIfExists(testArtifactRoot.FullName);
TestUtils.CleanupDirIfExists(testBackupDir.FullName);
if (!testArtifactRoot.Exists) {
testArtifactRoot.Create();
}
if (!testBackupDir.Exists) {
testBackupDir.Create();
}
var customRepository = new FsReleaseArtifactRepository(
Substitute.For<ILogger<FsReleaseArtifactRepository>>(),
testArtifactRoot,
testBackupDir
);
var testBackupZip = new ZipArchive(File.OpenRead(Path.Combine(projectDirectory, "TestData", "restoreTest", "testFile.zip")));
var expectedFile = File.ReadAllBytes(Path.Combine(projectDirectory, "TestData", "restoreTest", "testFile.txt"));
//Act
customRepository.RestoreBackup(testBackupZip);
//Get the (only) one file in the testArtifactRootDirectory
var artifactFiles = Directory.GetFiles(testArtifactRoot.FullName);
var testFile = File.ReadAllBytes(artifactFiles.First());
//Assert
Assert.Equal(expectedFile, testFile);
//Cleanup
testArtifactRoot.Delete(true);
testBackupDir.Delete(true);
}
}
} | 41.292576 | 139 | 0.521256 | [
"MIT"
] | tiwalter/release-server | sources/ReleaseServer/ReleaseServer.WebApi.Test/Repositories/ReleaseArtifactRepositoryTest.cs | 18,913 | C# |
using System;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Host;
namespace webjobs_core_example {
public class Jobs {
public static void ListenOnQueue([QueueTrigger("testqueue")] string message, TraceWriter log) {
log.Info($"Hello {message}");
}
}
} | 27.454545 | 103 | 0.68543 | [
"MIT"
] | christopheranderson/azure-webjobs-dotnet-core-sample | src/jobs/Jobs.cs | 302 | 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.MachineLearningServices.V20200301
{
/// <summary>
/// The Private Endpoint Connection resource.
/// </summary>
[AzureNativeResourceType("azure-native:machinelearningservices/v20200301:PrivateEndpointConnection")]
public partial class PrivateEndpointConnection : Pulumi.CustomResource
{
/// <summary>
/// The identity of the resource.
/// </summary>
[Output("identity")]
public Output<Outputs.IdentityResponse?> Identity { get; private set; } = null!;
/// <summary>
/// Specifies the location of the resource.
/// </summary>
[Output("location")]
public Output<string?> Location { get; private set; } = null!;
/// <summary>
/// Specifies the name of the resource.
/// </summary>
[Output("name")]
public Output<string> Name { get; private set; } = null!;
/// <summary>
/// The resource of private end point.
/// </summary>
[Output("privateEndpoint")]
public Output<Outputs.PrivateEndpointResponse?> PrivateEndpoint { get; private set; } = null!;
/// <summary>
/// A collection of information about the state of the connection between service consumer and provider.
/// </summary>
[Output("privateLinkServiceConnectionState")]
public Output<Outputs.PrivateLinkServiceConnectionStateResponse> PrivateLinkServiceConnectionState { get; private set; } = null!;
/// <summary>
/// The provisioning state of the private endpoint connection resource.
/// </summary>
[Output("provisioningState")]
public Output<string> ProvisioningState { get; private set; } = null!;
/// <summary>
/// The sku of the workspace.
/// </summary>
[Output("sku")]
public Output<Outputs.SkuResponse?> Sku { get; private set; } = null!;
/// <summary>
/// Contains resource tags defined as key/value pairs.
/// </summary>
[Output("tags")]
public Output<ImmutableDictionary<string, string>?> Tags { get; private set; } = null!;
/// <summary>
/// Specifies the type of the resource.
/// </summary>
[Output("type")]
public Output<string> Type { get; private set; } = null!;
/// <summary>
/// Create a PrivateEndpointConnection resource with the given unique name, arguments, and options.
/// </summary>
///
/// <param name="name">The unique name of the resource</param>
/// <param name="args">The arguments used to populate this resource's properties</param>
/// <param name="options">A bag of options that control this resource's behavior</param>
public PrivateEndpointConnection(string name, PrivateEndpointConnectionArgs args, CustomResourceOptions? options = null)
: base("azure-native:machinelearningservices/v20200301:PrivateEndpointConnection", name, args ?? new PrivateEndpointConnectionArgs(), MakeResourceOptions(options, ""))
{
}
private PrivateEndpointConnection(string name, Input<string> id, CustomResourceOptions? options = null)
: base("azure-native:machinelearningservices/v20200301:PrivateEndpointConnection", name, null, MakeResourceOptions(options, id))
{
}
private static CustomResourceOptions MakeResourceOptions(CustomResourceOptions? options, Input<string>? id)
{
var defaultOptions = new CustomResourceOptions
{
Version = Utilities.Version,
Aliases =
{
new Pulumi.Alias { Type = "azure-nextgen:machinelearningservices/v20200301:PrivateEndpointConnection"},
new Pulumi.Alias { Type = "azure-native:machinelearningservices:PrivateEndpointConnection"},
new Pulumi.Alias { Type = "azure-nextgen:machinelearningservices:PrivateEndpointConnection"},
new Pulumi.Alias { Type = "azure-native:machinelearningservices/v20200101:PrivateEndpointConnection"},
new Pulumi.Alias { Type = "azure-nextgen:machinelearningservices/v20200101:PrivateEndpointConnection"},
new Pulumi.Alias { Type = "azure-native:machinelearningservices/v20200218preview:PrivateEndpointConnection"},
new Pulumi.Alias { Type = "azure-nextgen:machinelearningservices/v20200218preview:PrivateEndpointConnection"},
new Pulumi.Alias { Type = "azure-native:machinelearningservices/v20200401:PrivateEndpointConnection"},
new Pulumi.Alias { Type = "azure-nextgen:machinelearningservices/v20200401:PrivateEndpointConnection"},
new Pulumi.Alias { Type = "azure-native:machinelearningservices/v20200501preview:PrivateEndpointConnection"},
new Pulumi.Alias { Type = "azure-nextgen:machinelearningservices/v20200501preview:PrivateEndpointConnection"},
new Pulumi.Alias { Type = "azure-native:machinelearningservices/v20200515preview:PrivateEndpointConnection"},
new Pulumi.Alias { Type = "azure-nextgen:machinelearningservices/v20200515preview:PrivateEndpointConnection"},
new Pulumi.Alias { Type = "azure-native:machinelearningservices/v20200601:PrivateEndpointConnection"},
new Pulumi.Alias { Type = "azure-nextgen:machinelearningservices/v20200601:PrivateEndpointConnection"},
new Pulumi.Alias { Type = "azure-native:machinelearningservices/v20200801:PrivateEndpointConnection"},
new Pulumi.Alias { Type = "azure-nextgen:machinelearningservices/v20200801:PrivateEndpointConnection"},
new Pulumi.Alias { Type = "azure-native:machinelearningservices/v20200901preview:PrivateEndpointConnection"},
new Pulumi.Alias { Type = "azure-nextgen:machinelearningservices/v20200901preview:PrivateEndpointConnection"},
new Pulumi.Alias { Type = "azure-native:machinelearningservices/v20210101:PrivateEndpointConnection"},
new Pulumi.Alias { Type = "azure-nextgen:machinelearningservices/v20210101:PrivateEndpointConnection"},
new Pulumi.Alias { Type = "azure-native:machinelearningservices/v20210301preview:PrivateEndpointConnection"},
new Pulumi.Alias { Type = "azure-nextgen:machinelearningservices/v20210301preview:PrivateEndpointConnection"},
new Pulumi.Alias { Type = "azure-native:machinelearningservices/v20210401:PrivateEndpointConnection"},
new Pulumi.Alias { Type = "azure-nextgen:machinelearningservices/v20210401:PrivateEndpointConnection"},
new Pulumi.Alias { Type = "azure-native:machinelearningservices/v20210701:PrivateEndpointConnection"},
new Pulumi.Alias { Type = "azure-nextgen:machinelearningservices/v20210701:PrivateEndpointConnection"},
},
};
var merged = CustomResourceOptions.Merge(defaultOptions, options);
// Override the ID if one was specified for consistency with other language SDKs.
merged.Id = id ?? merged.Id;
return merged;
}
/// <summary>
/// Get an existing PrivateEndpointConnection resource's state with the given name, ID, and optional extra
/// properties used to qualify the lookup.
/// </summary>
///
/// <param name="name">The unique name of the resulting resource.</param>
/// <param name="id">The unique provider ID of the resource to lookup.</param>
/// <param name="options">A bag of options that control this resource's behavior</param>
public static PrivateEndpointConnection Get(string name, Input<string> id, CustomResourceOptions? options = null)
{
return new PrivateEndpointConnection(name, id, options);
}
}
public sealed class PrivateEndpointConnectionArgs : Pulumi.ResourceArgs
{
/// <summary>
/// The identity of the resource.
/// </summary>
[Input("identity")]
public Input<Inputs.IdentityArgs>? Identity { get; set; }
/// <summary>
/// Specifies the location of the resource.
/// </summary>
[Input("location")]
public Input<string>? Location { get; set; }
/// <summary>
/// The name of the private endpoint connection associated with the workspace
/// </summary>
[Input("privateEndpointConnectionName")]
public Input<string>? PrivateEndpointConnectionName { get; set; }
/// <summary>
/// A collection of information about the state of the connection between service consumer and provider.
/// </summary>
[Input("privateLinkServiceConnectionState", required: true)]
public Input<Inputs.PrivateLinkServiceConnectionStateArgs> PrivateLinkServiceConnectionState { get; set; } = null!;
/// <summary>
/// Name of the resource group in which workspace is located.
/// </summary>
[Input("resourceGroupName", required: true)]
public Input<string> ResourceGroupName { get; set; } = null!;
/// <summary>
/// The sku of the workspace.
/// </summary>
[Input("sku")]
public Input<Inputs.SkuArgs>? Sku { get; set; }
[Input("tags")]
private InputMap<string>? _tags;
/// <summary>
/// Contains resource tags defined as key/value pairs.
/// </summary>
public InputMap<string> Tags
{
get => _tags ?? (_tags = new InputMap<string>());
set => _tags = value;
}
/// <summary>
/// Name of Azure Machine Learning workspace.
/// </summary>
[Input("workspaceName", required: true)]
public Input<string> WorkspaceName { get; set; } = null!;
public PrivateEndpointConnectionArgs()
{
}
}
}
| 50.606796 | 179 | 0.641727 | [
"Apache-2.0"
] | polivbr/pulumi-azure-native | sdk/dotnet/MachineLearningServices/V20200301/PrivateEndpointConnection.cs | 10,425 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[ExecuteInEditMode]
public class Teste : MonoBehaviour
{
public Rect lifeBarRect; public Rect lifeBarLabelRect; public Rect lifeBarBackgroundRect; public Texture2D lifeBarBackground; public Texture2D lifeBar;
public GameObject PlayerData;
private float LifeBarWidth = 300f;
public float life = 100;
void OnGUI()
{
lifeBarRect.width = LifeBarWidth * (life / 200);
lifeBarRect.height = 20;
lifeBarBackgroundRect.width = LifeBarWidth;
lifeBarBackgroundRect.height = 20;
GUI.DrawTexture(lifeBarBackgroundRect, lifeBarBackground);
GUI.DrawTexture(lifeBarRect, lifeBar);
GUI.Label(lifeBarLabelRect, "LIFE");
}
}
| 23 | 155 | 0.714834 | [
"MIT"
] | douglasciole/SimpleAI | Assets/SimpleAI/Scripts/Teste.cs | 784 | C# |
using System.Threading.Tasks;
namespace NpuRozklad.Telegram.LongLastingUserActions
{
public interface ILongLastingUserActionManager
{
Task UpsertUserAction(LongLastingUserActionArguments arguments);
Task ClearUserAction(TelegramRozkladUser rozkladUser);
Task<LongLastingUserActionArguments> GetUserLongLastingAction(TelegramRozkladUser telegramRozkladUser);
}
} | 36.181818 | 111 | 0.809045 | [
"MIT"
] | matryosha/Npu-Rozklad-App | Src/NpuRozklad.Telegram/LongLastingUserActions/ILongLastingUserActionManager.cs | 398 | C# |
using AnnoSavegameViewer.Serialization.Core;
using System.Collections.Generic;
namespace AnnoSavegameViewer.Structures.Savegame.Generated {
public class OriginalShareOwnerList {
[BinaryContent(Name = "value", NodeType = BinaryContentTypes.Node)]
public OriginalShareOwnerListValue Value { get; set; }
}
} | 26.666667 | 71 | 0.7875 | [
"MIT"
] | brumiros/AnnoSavegameViewer | AnnoSavegameViewer/Structures/Savegame/Generated/NoContent/OriginalShareOwnerList.cs | 320 | C# |
// ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------------------------------------------------------------
using System;
using System.IO;
using System.Linq;
using Microsoft.WindowsAzure.Commands.ScenarioTest;
using Xunit;
using Microsoft.WindowsAzure.Commands.CloudService.Development;
using Microsoft.WindowsAzure.Commands.CloudService.Development.Scaffolding;
using Microsoft.WindowsAzure.Commands.Common.Test.Mocks;
using Microsoft.WindowsAzure.Commands.Test.Utilities.CloudService;
using Microsoft.WindowsAzure.Commands.Test.Utilities.Common;
using Microsoft.WindowsAzure.Commands.Utilities.CloudService;
using Microsoft.WindowsAzure.Commands.Utilities.CloudService.AzureTools;
using Microsoft.WindowsAzure.Commands.Utilities.Common;
using Microsoft.WindowsAzure.Commands.Utilities.Properties;
using Microsoft.WindowsAzure.Commands.Common;
using Microsoft.Azure.Commands.Common.Authentication;
using Microsoft.Azure.Commands.Common.Authentication.Abstractions;
namespace Microsoft.WindowsAzure.Commands.Test.CloudService.Utilities
{
public class AzureServiceTests: SMTestBase
{
private const string serviceName = "AzureService";
private MockCommandRuntime mockCommandRuntime;
private AddAzureNodeWebRoleCommand addNodeWebCmdlet;
private AddAzureNodeWorkerRoleCommand addNodeWorkerCmdlet;
/// <summary>
/// This method handles most possible cases that user can do to create role
/// </summary>
/// <param name="webRole">Count of web roles to add</param>
/// <param name="workerRole">Count of worker role to add</param>
/// <param name="addWebBeforeWorker">Decides in what order to add roles. There are three options, note that value between brackets is the value to pass:
/// 1. Web then, interleaving (0): interleave adding and start by adding web role first.
/// 2. Worker then, interleaving (1): interleave adding and start by adding worker role first.
/// 3. Web then worker (2): add all web roles then worker roles.
/// 4. Worker then web (3): add all worker roles then web roles.
/// By default this parameter is set to 0
/// </param>
private void AddNodeRoleTest(int webRole, int workerRole, int order = 0)
{
using (FileSystemHelper files = new FileSystemHelper(this))
{
AzureServiceWrapper wrappedService = new AzureServiceWrapper(files.RootPath, serviceName, null);
CloudServiceProject service = new CloudServiceProject(Path.Combine(files.RootPath, serviceName), null);
WebRoleInfo[] webRoles = null;
if (webRole > 0)
{
webRoles = new WebRoleInfo[webRole];
for (int i = 0; i < webRoles.Length; i++)
{
webRoles[i] = new WebRoleInfo(string.Format("{0}{1}", Resources.WebRole, i + 1), 1);
}
}
WorkerRoleInfo[] workerRoles = null;
if (workerRole > 0)
{
workerRoles = new WorkerRoleInfo[workerRole];
for (int i = 0; i < workerRoles.Length; i++)
{
workerRoles[i] = new WorkerRoleInfo(string.Format("{0}{1}", Resources.WorkerRole, i + 1), 1);
}
}
RoleInfo[] roles = (webRole + workerRole > 0) ? new RoleInfo[webRole + workerRole] : null;
if (order == 0)
{
for (int i = 0, w = 0, wo = 0; i < webRole + workerRole; )
{
if (w++ < webRole) roles[i++] = wrappedService.AddWebRole(Test.Utilities.Common.Data.NodeWebRoleScaffoldingPath);
if (wo++ < workerRole) roles[i++] = wrappedService.AddWorkerRole(Test.Utilities.Common.Data.NodeWorkerRoleScaffoldingPath);
}
}
else if (order == 1)
{
for (int i = 0, w = 0, wo = 0; i < webRole + workerRole; )
{
if (wo++ < workerRole) roles[i++] = wrappedService.AddWorkerRole(Test.Utilities.Common.Data.NodeWorkerRoleScaffoldingPath);
if (w++ < webRole) roles[i++] = wrappedService.AddWebRole(Test.Utilities.Common.Data.NodeWebRoleScaffoldingPath);
}
}
else if (order == 2)
{
wrappedService.AddRole(Test.Utilities.Common.Data.NodeWebRoleScaffoldingPath, Test.Utilities.Common.Data.NodeWorkerRoleScaffoldingPath, webRole, workerRole);
webRoles.CopyTo(roles, 0);
Array.Copy(workerRoles, 0, roles, webRole, workerRoles.Length);
}
else if (order == 3)
{
wrappedService.AddRole(Test.Utilities.Common.Data.NodeWebRoleScaffoldingPath, Test.Utilities.Common.Data.NodeWorkerRoleScaffoldingPath, 0, workerRole);
workerRoles.CopyTo(roles, 0);
wrappedService.AddRole(Test.Utilities.Common.Data.NodeWebRoleScaffoldingPath, Test.Utilities.Common.Data.NodeWorkerRoleScaffoldingPath, webRole, 0);
Array.Copy(webRoles, 0, roles, workerRole, webRoles.Length);
}
else
{
throw new ArgumentException("value for order parameter is unknown");
}
AzureAssert.AzureServiceExists(Path.Combine(files.RootPath, serviceName), Resources.GeneralScaffolding, serviceName, webRoles: webRoles, workerRoles: workerRoles, webScaff: Test.Utilities.Common.Data.NodeWebRoleScaffoldingPath, workerScaff: Test.Utilities.Common.Data.NodeWorkerRoleScaffoldingPath, roles: roles);
}
}
private void AddPHPRoleTest(int webRole, int workerRole, int order = 0)
{
using (FileSystemHelper files = new FileSystemHelper(this))
{
AzureServiceWrapper wrappedService = new AzureServiceWrapper(files.RootPath, serviceName, null);
CloudServiceProject service = new CloudServiceProject(Path.Combine(files.RootPath, serviceName), null);
WebRoleInfo[] webRoles = null;
if (webRole > 0)
{
webRoles = new WebRoleInfo[webRole];
for (int i = 0; i < webRoles.Length; i++)
{
webRoles[i] = new WebRoleInfo(string.Format("{0}{1}", Resources.WebRole, i + 1), 1);
}
}
WorkerRoleInfo[] workerRoles = null;
if (workerRole > 0)
{
workerRoles = new WorkerRoleInfo[workerRole];
for (int i = 0; i < workerRoles.Length; i++)
{
workerRoles[i] = new WorkerRoleInfo(string.Format("{0}{1}", Resources.WorkerRole, i + 1), 1);
}
}
RoleInfo[] roles = (webRole + workerRole > 0) ? new RoleInfo[webRole + workerRole] : null;
if (order == 0)
{
for (int i = 0, w = 0, wo = 0; i < webRole + workerRole; )
{
if (w++ < webRole) roles[i++] = wrappedService.AddWebRole(Test.Utilities.Common.Data.PHPWebRoleScaffoldingPath);
if (wo++ < workerRole) roles[i++] = wrappedService.AddWorkerRole(Test.Utilities.Common.Data.PHPWorkerRoleScaffoldingPath);
}
}
else if (order == 1)
{
for (int i = 0, w = 0, wo = 0; i < webRole + workerRole; )
{
if (wo++ < workerRole) roles[i++] = wrappedService.AddWorkerRole(Test.Utilities.Common.Data.PHPWorkerRoleScaffoldingPath);
if (w++ < webRole) roles[i++] = wrappedService.AddWebRole(Test.Utilities.Common.Data.PHPWebRoleScaffoldingPath);
}
}
else if (order == 2)
{
wrappedService.AddRole(Test.Utilities.Common.Data.PHPWebRoleScaffoldingPath, Test.Utilities.Common.Data.PHPWorkerRoleScaffoldingPath, webRole, workerRole);
webRoles.CopyTo(roles, 0);
Array.Copy(workerRoles, 0, roles, webRole, workerRoles.Length);
}
else if (order == 3)
{
wrappedService.AddRole(Test.Utilities.Common.Data.PHPWebRoleScaffoldingPath, Test.Utilities.Common.Data.PHPWorkerRoleScaffoldingPath, 0, workerRole);
workerRoles.CopyTo(roles, 0);
wrappedService.AddRole(Test.Utilities.Common.Data.PHPWebRoleScaffoldingPath, Test.Utilities.Common.Data.PHPWorkerRoleScaffoldingPath, webRole, 0);
Array.Copy(webRoles, 0, roles, workerRole, webRoles.Length);
}
else
{
throw new ArgumentException("value for order parameter is unknown");
}
AzureAssert.AzureServiceExists(Path.Combine(files.RootPath, serviceName), Resources.GeneralScaffolding, serviceName, webRoles: webRoles, workerRoles: workerRoles, webScaff: Test.Utilities.Common.Data.PHPWebRoleScaffoldingPath, workerScaff: Test.Utilities.Common.Data.PHPWorkerRoleScaffoldingPath, roles: roles);
}
}
public AzureServiceTests()
{
AzureTool.IgnoreMissingSDKError = true;
AzurePowerShell.ProfileDirectory = Test.Utilities.Common.Data.AzureSdkAppDir;
mockCommandRuntime = new MockCommandRuntime();
}
[Fact]
[Trait(Category.AcceptanceType, Category.CheckIn)]
public void AzureServiceCreateNew()
{
using (FileSystemHelper files = new FileSystemHelper(this))
{
CloudServiceProject service = new CloudServiceProject(files.RootPath, serviceName, null);
AzureAssert.AzureServiceExists(Path.Combine(files.RootPath, serviceName), Resources.GeneralScaffolding, serviceName);
}
}
[Fact]
[Trait(Category.AcceptanceType, Category.CheckIn)]
public void AzureServiceCreateNewEmptyParentDirectoryFail()
{
Testing.AssertThrows<ArgumentException>(() => new CloudServiceProject(string.Empty, serviceName, null), string.Format(Resources.InvalidOrEmptyArgumentMessage, "service parent directory"));
}
[Fact]
[Trait(Category.AcceptanceType, Category.CheckIn)]
public void AzureServiceCreateNewNullParentDirectoryFail()
{
Testing.AssertThrows<ArgumentException>(() => new CloudServiceProject(null, serviceName, null), string.Format(Resources.InvalidOrEmptyArgumentMessage, "service parent directory"));
}
[Fact]
[Trait(Category.AcceptanceType, Category.CheckIn)]
public void AzureServiceCreateNewInvalidParentDirectoryFail()
{
foreach (string invalidName in Test.Utilities.Common.Data.InvalidFileName)
{
Testing.AssertThrows<ArgumentException>(() => new CloudServiceProject(string.Empty, serviceName, null), string.Format(Resources.InvalidOrEmptyArgumentMessage, "service parent directory"));
}
}
[Fact]
[Trait(Category.AcceptanceType, Category.CheckIn)]
public void AzureServiceCreateNewDoesNotExistParentDirectoryFail()
{
Testing.AssertThrows<FileNotFoundException>(() => new CloudServiceProject("DoesNotExist", serviceName, null), string.Format(Resources.PathDoesNotExistForElement, Resources.ServiceParentDirectory, "DoesNotExist"));
}
[Fact]
[Trait(Category.AcceptanceType, Category.CheckIn)]
public void AzureServiceCreateNewEmptyServiceNameFail()
{
using (FileSystemHelper files = new FileSystemHelper(this))
{
Testing.AssertThrows<ArgumentException>(() => new CloudServiceProject(files.RootPath, string.Empty, null), string.Format(Resources.InvalidOrEmptyArgumentMessage, "Name"));
}
}
[Fact]
[Trait(Category.AcceptanceType, Category.CheckIn)]
public void AzureServiceCreateNewNullServiceNameFail()
{
using (FileSystemHelper files = new FileSystemHelper(this))
{
Testing.AssertThrows<ArgumentException>(() => new CloudServiceProject(files.RootPath, null, null), string.Format(Resources.InvalidOrEmptyArgumentMessage, "Name"));
}
}
[Fact]
[Trait(Category.AcceptanceType, Category.CheckIn)]
public void AzureServiceCreateNewInvalidServiceNameFail()
{
foreach (string invalidFileName in Test.Utilities.Common.Data.InvalidFileName)
{
using (FileSystemHelper files = new FileSystemHelper(this))
{
Testing.AssertThrows<ArgumentException>(() => new CloudServiceProject(files.RootPath, invalidFileName, null), string.Format(Resources.InvalidFileName, "Name"));
}
}
}
[Fact]
[Trait(Category.AcceptanceType, Category.CheckIn)]
public void AzureServiceCreateNewInvalidDnsServiceNameFail()
{
char[] invalidFileNameChars = Path.GetInvalidFileNameChars();
foreach (string invalidDnsName in Test.Utilities.Common.Data.InvalidServiceNames)
{
using (FileSystemHelper files = new FileSystemHelper(this))
{
// This case is handled in AzureServiceCreateNewInvalidDnsServiceNameFail test
//
if (invalidFileNameChars.Any(c => invalidFileNameChars.Contains<char>(c))) continue;
Testing.AssertThrows<ArgumentException>(() => new CloudServiceProject(files.RootPath, invalidDnsName, null), string.Format(Resources.InvalidDnsName, invalidDnsName, "Name"));
}
}
}
[Fact]
[Trait(Category.AcceptanceType, Category.CheckIn)]
public void AzureServiceCreateNewExistingServiceFail()
{
using (FileSystemHelper files = new FileSystemHelper(this))
{
new CloudServiceProject(files.RootPath, serviceName, null);
Testing.AssertThrows<ArgumentException>(() => new CloudServiceProject(files.RootPath, serviceName, null), string.Format(Resources.ServiceAlreadyExistsOnDisk, serviceName, Path.Combine(files.RootPath, serviceName)));
}
}
[Fact]
[Trait(Category.AcceptanceType, Category.CheckIn)]
public void AzureNodeServiceLoadExistingSimpleService()
{
AddNodeRoleTest(0, 0, 0);
}
[Fact]
[Trait(Category.AcceptanceType, Category.CheckIn)]
public void AzureNodeServiceLoadExistingOneWebRoleService()
{
AddNodeRoleTest(1, 0, 0);
}
[Fact]
[Trait(Category.AcceptanceType, Category.CheckIn)]
public void AzureNodeServiceLoadExistingOneWorkerRoleService()
{
AddNodeRoleTest(0, 1, 0);
}
[Fact]
[Trait(Category.AcceptanceType, Category.CheckIn)]
public void AzureNodeServiceLoadExistingMultipleWebRolesService()
{
AddNodeRoleTest(5, 0, 0);
}
[Fact]
[Trait(Category.AcceptanceType, Category.CheckIn)]
public void AzureNodeServiceLoadExistingMultipleWorkerRolesService()
{
AddNodeRoleTest(0, 5, 0);
}
[Fact]
[Trait(Category.AcceptanceType, Category.CheckIn)]
public void AzureNodeServiceLoadExistingMultipleWebAndOneWorkerRolesService()
{
int order = 0;
AddNodeRoleTest(3, 4, order++);
AddNodeRoleTest(2, 4, order++);
AddNodeRoleTest(4, 2, order++);
AddNodeRoleTest(3, 5, order++);
}
[Fact]
[Trait(Category.AcceptanceType, Category.CheckIn)]
public void AzurePHPServiceLoadExistingSimpleService()
{
AddPHPRoleTest(0, 0, 0);
}
[Fact]
[Trait(Category.AcceptanceType, Category.CheckIn)]
public void AzurePHPServiceLoadExistingOneWebRoleService()
{
AddPHPRoleTest(1, 0, 0);
}
[Fact]
[Trait(Category.AcceptanceType, Category.CheckIn)]
public void AzurePHPServiceLoadExistingOneWorkerRoleService()
{
AddPHPRoleTest(0, 1, 0);
}
[Fact]
[Trait(Category.AcceptanceType, Category.CheckIn)]
public void AzurePHPServiceLoadExistingMultipleWebRolesService()
{
AddPHPRoleTest(5, 0, 0);
}
[Fact]
[Trait(Category.AcceptanceType, Category.CheckIn)]
public void AzurePHPServiceLoadExistingMultipleWorkerRolesService()
{
AddPHPRoleTest(0, 5, 0);
}
[Fact]
[Trait(Category.AcceptanceType, Category.CheckIn)]
public void AzurePHPServiceLoadExistingMultipleWebAndOneWorkerRolesService()
{
int order = 0;
AddPHPRoleTest(3, 4, order++);
AddPHPRoleTest(2, 4, order++);
AddPHPRoleTest(4, 2, order++);
AddPHPRoleTest(3, 5, order++);
}
[Fact]
[Trait(Category.AcceptanceType, Category.CheckIn)]
public void AzureServiceAddNewNodeWebRoleTest()
{
using (FileSystemHelper files = new FileSystemHelper(this))
{
CloudServiceProject service = new CloudServiceProject(files.RootPath, serviceName, null);
RoleInfo webRole = service.AddWebRole(Test.Utilities.Common.Data.NodeWebRoleScaffoldingPath, "MyWebRole", 10);
AzureAssert.AzureServiceExists(Path.Combine(files.RootPath, serviceName), Resources.GeneralScaffolding, serviceName, webRoles: new WebRoleInfo[] { (WebRoleInfo)webRole }, webScaff: Path.Combine(Resources.NodeScaffolding, Resources.WebRole), roles: new RoleInfo[] { webRole });
}
}
[Fact]
[Trait(Category.AcceptanceType, Category.CheckIn)]
public void AzureServiceAddNewPHPWebRoleTest()
{
using (FileSystemHelper files = new FileSystemHelper(this))
{
CloudServiceProject service = new CloudServiceProject(files.RootPath, serviceName, null);
RoleInfo webRole = service.AddWebRole(Test.Utilities.Common.Data.PHPWebRoleScaffoldingPath, "MyWebRole", 10);
AzureAssert.AzureServiceExists(Path.Combine(files.RootPath, serviceName), Resources.GeneralScaffolding, serviceName, webRoles: new WebRoleInfo[] { (WebRoleInfo)webRole }, webScaff: Path.Combine(Resources.PHPScaffolding, Resources.WebRole), roles: new RoleInfo[] { webRole });
}
}
[Fact]
[Trait(Category.AcceptanceType, Category.CheckIn)]
public void AzureServiceAddNewNodeWorkerRoleTest()
{
using (FileSystemHelper files = new FileSystemHelper(this))
{
CloudServiceProject service = new CloudServiceProject(files.RootPath, serviceName, null);
RoleInfo workerRole = service.AddWorkerRole(Test.Utilities.Common.Data.NodeWorkerRoleScaffoldingPath, "MyWorkerRole", 10);
AzureAssert.AzureServiceExists(Path.Combine(files.RootPath, serviceName), Resources.GeneralScaffolding, serviceName, workerRoles: new WorkerRoleInfo[] { (WorkerRoleInfo)workerRole }, workerScaff: Path.Combine(Resources.NodeScaffolding, Resources.WorkerRole), roles: new RoleInfo[] { workerRole });
}
}
[Fact]
[Trait(Category.AcceptanceType, Category.CheckIn)]
public void AzureServiceAddNewPHPWorkerRoleTest()
{
using (FileSystemHelper files = new FileSystemHelper(this))
{
CloudServiceProject service = new CloudServiceProject(files.RootPath, serviceName, null);
RoleInfo workerRole = service.AddWorkerRole(Test.Utilities.Common.Data.PHPWorkerRoleScaffoldingPath, "MyWorkerRole", 10);
AzureAssert.AzureServiceExists(Path.Combine(files.RootPath, serviceName), Resources.GeneralScaffolding, serviceName, workerRoles: new WorkerRoleInfo[] { (WorkerRoleInfo)workerRole }, workerScaff: Path.Combine(Resources.PHPScaffolding, Resources.WorkerRole), roles: new RoleInfo[] { workerRole });
}
}
[Fact]
[Trait(Category.AcceptanceType, Category.CheckIn)]
public void AzureServiceAddNewNodeWorkerRoleWithWhiteCharFail()
{
using (FileSystemHelper files = new FileSystemHelper(this))
{
Testing.AssertThrows<ArgumentException>(() => new CloudServiceProject(files.RootPath, serviceName, null).AddWebRole(Test.Utilities.Common.Data.NodeWebRoleScaffoldingPath, "\tRole"), string.Format(Resources.InvalidRoleNameMessage, "\tRole"));
}
}
[Fact]
[Trait(Category.AcceptanceType, Category.CheckIn)]
public void AzureServiceAddNewPHPWorkerRoleWithWhiteCharFail()
{
using (FileSystemHelper files = new FileSystemHelper(this))
{
Testing.AssertThrows<ArgumentException>(() => new CloudServiceProject(files.RootPath, serviceName, null).AddWebRole(Test.Utilities.Common.Data.PHPWebRoleScaffoldingPath, "\tRole"), string.Format(Resources.InvalidRoleNameMessage, "\tRole"));
}
}
[Fact]
[Trait(Category.AcceptanceType, Category.CheckIn)]
public void AzureServiceAddExistingNodeRoleFail()
{
using (FileSystemHelper files = new FileSystemHelper(this))
{
CloudServiceProject service = new CloudServiceProject(files.RootPath, serviceName, null);
service.AddWebRole(Test.Utilities.Common.Data.NodeWebRoleScaffoldingPath, "WebRole");
Testing.AssertThrows<ArgumentException>(() => service.AddWebRole(Test.Utilities.Common.Data.NodeWebRoleScaffoldingPath, "WebRole"), string.Format(Resources.AddRoleMessageRoleExists, "WebRole"));
}
}
[Fact]
[Trait(Category.AcceptanceType, Category.CheckIn)]
public void AzureServiceAddExistingPHPRoleFail()
{
using (FileSystemHelper files = new FileSystemHelper(this))
{
CloudServiceProject service = new CloudServiceProject(files.RootPath, serviceName, null);
service.AddWebRole(Test.Utilities.Common.Data.PHPWebRoleScaffoldingPath, "WebRole");
Testing.AssertThrows<ArgumentException>(() => service.AddWebRole(Test.Utilities.Common.Data.PHPWebRoleScaffoldingPath, "WebRole"), string.Format(Resources.AddRoleMessageRoleExists, "WebRole"));
}
}
[Fact]
[Trait(Category.AcceptanceType, Category.CheckIn)]
public void GetServiceNameTest()
{
using (FileSystemHelper files = new FileSystemHelper(this))
{
NewAzureServiceProjectCommand newServiceCmdlet = new NewAzureServiceProjectCommand();
newServiceCmdlet.CommandRuntime = new MockCommandRuntime();
newServiceCmdlet.NewAzureServiceProcess(files.RootPath, serviceName);
Assert.Equal<string>(serviceName, new CloudServiceProject(Path.Combine(files.RootPath, serviceName), null).ServiceName);
}
}
[Fact]
[Trait(Category.AcceptanceType, Category.CheckIn)]
public void ChangeServiceNameTest()
{
string newName = "NodeAppService";
using (FileSystemHelper files = new FileSystemHelper(this))
{
CloudServiceProject service = new CloudServiceProject(files.RootPath, serviceName, null);
service.ChangeServiceName(newName, service.Paths);
Assert.Equal<string>(newName, service.Components.CloudConfig.serviceName);
Assert.Equal<string>(newName, service.Components.LocalConfig.serviceName);
Assert.Equal<string>(newName, service.Components.Definition.name);
}
}
[Fact]
[Trait(Category.AcceptanceType, Category.CheckIn)]
public void SetNodeRoleInstancesTest()
{
int newInstances = 10;
using (FileSystemHelper files = new FileSystemHelper(this))
{
CloudServiceProject service = new CloudServiceProject(files.RootPath, serviceName, null);
service.AddWebRole(Test.Utilities.Common.Data.NodeWebRoleScaffoldingPath, "WebRole", 1);
service.SetRoleInstances(service.Paths, "WebRole", newInstances);
Assert.Equal<int>(service.Components.CloudConfig.Role[0].Instances.count, newInstances);
Assert.Equal<int>(service.Components.LocalConfig.Role[0].Instances.count, newInstances);
}
}
[Fact]
[Trait(Category.AcceptanceType, Category.CheckIn)]
public void SetPHPRoleInstancesTest()
{
int newInstances = 10;
using (FileSystemHelper files = new FileSystemHelper(this))
{
CloudServiceProject service = new CloudServiceProject(files.RootPath, serviceName, null);
service.AddWebRole(Test.Utilities.Common.Data.PHPWebRoleScaffoldingPath, "WebRole", 1);
service.SetRoleInstances(service.Paths, "WebRole", newInstances);
Assert.Equal<int>(service.Components.CloudConfig.Role[0].Instances.count, newInstances);
Assert.Equal<int>(service.Components.LocalConfig.Role[0].Instances.count, newInstances);
}
}
[Fact]
[Trait(Category.AcceptanceType, Category.CheckIn)]
public void TestResolveRuntimePackageUrls()
{
// Create a temp directory that we'll use to "publish" our service
using (FileSystemHelper files = new FileSystemHelper(this) { EnableMonitoring = true })
{
// Import our default publish settings
files.CreateAzureSdkDirectoryAndImportPublishSettings();
// Create a new service that we're going to publish
string serviceName = "TEST_SERVICE_NAME";
string rootPath = files.CreateNewService(serviceName);
// Add web and worker roles
string defaultWebRoleName = "WebRoleDefault";
addNodeWebCmdlet = new AddAzureNodeWebRoleCommand() { RootPath = rootPath, CommandRuntime = mockCommandRuntime, Name = defaultWebRoleName, Instances = 2 };
addNodeWebCmdlet.ExecuteCmdlet();
string defaultWorkerRoleName = "WorkerRoleDefault";
addNodeWorkerCmdlet = new AddAzureNodeWorkerRoleCommand() { RootPath = rootPath, CommandRuntime = mockCommandRuntime, Name = defaultWorkerRoleName, Instances = 2 };
addNodeWorkerCmdlet.ExecuteCmdlet();
AddAzureNodeWebRoleCommand matchWebRole = addNodeWebCmdlet;
string matchWebRoleName = "WebRoleExactMatch";
addNodeWebCmdlet = new AddAzureNodeWebRoleCommand() { RootPath = rootPath, CommandRuntime = mockCommandRuntime, Name = matchWebRoleName, Instances = 2 };
addNodeWebCmdlet.ExecuteCmdlet();
AddAzureNodeWorkerRoleCommand matchWorkerRole = addNodeWorkerCmdlet;
string matchWorkerRoleName = "WorkerRoleExactMatch";
addNodeWorkerCmdlet = new AddAzureNodeWorkerRoleCommand() { RootPath = rootPath, CommandRuntime = mockCommandRuntime, Name = matchWorkerRoleName, Instances = 2 };
addNodeWorkerCmdlet.ExecuteCmdlet();
AddAzureNodeWebRoleCommand overrideWebRole = addNodeWebCmdlet;
string overrideWebRoleName = "WebRoleOverride";
addNodeWebCmdlet = new AddAzureNodeWebRoleCommand() { RootPath = rootPath, CommandRuntime = mockCommandRuntime, Name = overrideWebRoleName, Instances = 2 };
addNodeWebCmdlet.ExecuteCmdlet();
AddAzureNodeWorkerRoleCommand overrideWorkerRole = addNodeWorkerCmdlet;
string overrideWorkerRoleName = "WorkerRoleOverride";
addNodeWorkerCmdlet = new AddAzureNodeWorkerRoleCommand() { RootPath = rootPath, CommandRuntime = mockCommandRuntime, Name = overrideWorkerRoleName, Instances = 2 };
addNodeWorkerCmdlet.ExecuteCmdlet();
string webRole2Name = "WebRole2";
AddAzureNodeWebRoleCommand addAzureWebRole = new AddAzureNodeWebRoleCommand() { RootPath = rootPath, CommandRuntime = mockCommandRuntime, Name = webRole2Name };
addAzureWebRole.ExecuteCmdlet();
CloudServiceProject testService = new CloudServiceProject(rootPath, FileUtilities.GetContentFilePath(@"..\..\..\..\..\Package\Debug\ServiceManagement\Azure\Services"));
RuntimePackageHelper.SetRoleRuntime(testService.Components.Definition, matchWebRoleName, testService.Paths, version: "0.8.2");
RuntimePackageHelper.SetRoleRuntime(testService.Components.Definition, matchWorkerRoleName, testService.Paths, version: "0.8.2");
RuntimePackageHelper.SetRoleRuntime(testService.Components.Definition, overrideWebRoleName, testService.Paths, overrideUrl: "http://OVERRIDE");
RuntimePackageHelper.SetRoleRuntime(testService.Components.Definition, overrideWorkerRoleName, testService.Paths, overrideUrl: "http://OVERRIDE");
bool exceptionWasThrownOnSettingCacheRole = false;
try
{
string cacheRuntimeVersion = "1.7.0";
testService.AddRoleRuntime(testService.Paths, webRole2Name, Resources.CacheRuntimeValue, cacheRuntimeVersion, RuntimePackageHelper.GetTestManifest(files));
}
catch (NotSupportedException)
{
exceptionWasThrownOnSettingCacheRole = true;
}
Assert.True(exceptionWasThrownOnSettingCacheRole);
testService.Components.Save(testService.Paths);
// Get the publishing process started by creating the package
testService.ResolveRuntimePackageUrls(RuntimePackageHelper.GetTestManifest(files));
CloudServiceProject updatedService = new CloudServiceProject(testService.Paths.RootPath, null);
RuntimePackageHelper.ValidateRoleRuntime(updatedService.Components.Definition, defaultWebRoleName, "http://cdn/node/default.exe;http://cdn/iisnode/default.exe", null);
RuntimePackageHelper.ValidateRoleRuntime(updatedService.Components.Definition, defaultWorkerRoleName, "http://cdn/node/default.exe", null);
RuntimePackageHelper.ValidateRoleRuntime(updatedService.Components.Definition, matchWorkerRoleName, "http://cdn/node/foo.exe", null);
RuntimePackageHelper.ValidateRoleRuntime(updatedService.Components.Definition, matchWebRoleName, "http://cdn/node/foo.exe;http://cdn/iisnode/default.exe", null);
RuntimePackageHelper.ValidateRoleRuntime(updatedService.Components.Definition, overrideWebRoleName, null, "http://OVERRIDE");
RuntimePackageHelper.ValidateRoleRuntime(updatedService.Components.Definition, overrideWorkerRoleName, null, "http://OVERRIDE");
}
}
}
} | 52.563291 | 330 | 0.622607 | [
"MIT"
] | Andrean/azure-powershell | src/ServiceManagement/Services/Commands.Test/CloudService/Utilities/AzureServiceTests.cs | 32,591 | C# |
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
namespace pirates.GameObjects
{
/// <summary>
/// Class for the FlagShip, a special BattleShip with minor differences.
/// </summary>
public sealed class FlagShip : BattleShip
{
/// <summary>
/// Integer for the visibility of the Flagship.
/// </summary>
public int SightValue { get; set; }
/// <summary>
/// Integer for the visibility of the Flagship.
/// </summary>
public int SightValueToAdd { get; set; }
// ReSharper disable once UnusedMember.Global (needed for Xml Serialization.)
public FlagShip()
{
}
public FlagShip(Vector2 position) : base(position)
{
Initialize();
}
public override void Initialize()
{
Owned = true;
MaxHp = 100;
Hp = (int)MaxHp;
MaxFreePirates = 60;
AttackValue = 15;
EnterAttackValue = 15;
RepairingValue = 10;
SightValue = 10;
MovementSpeed = 0.25f;
InitialMovingSpeed = 0.25f;
AllPiratesOnShip = 50;
}
public override void LoadContent(ContentManager content)
{
mShipTexture = content.Load<Texture2D>("Ships/flagship_texture");
}
public override void UpdateMoving(GameTime gameTime)
{
base.UpdateMoving(gameTime);
if (mPiratesChangeDelay <= 0)
{
if (SightValueToAdd > 0)
{
SightValue++;
SightValueToAdd--;
}
}
}
}
}
| 28.015152 | 86 | 0.505138 | [
"MIT"
] | ShiroDevC/Old_Code | c#/Pirates/src/GameObjects/FlagShip.cs | 1,851 | C# |
using System;
using System.Collections.Generic;
using System.Text;
using IKende.com.core;
namespace Peanut.Mappings
{
/// <summary>
/// 存储过程参数描述
/// </summary>
[AttributeUsage(AttributeTargets.Property)]
public class ProcParameterAttribute:Attribute
{
/// <summary>
/// 参数名
/// </summary>
public string Name
{
get;
set;
}
/// <summary>
/// 参数类型
/// </summary>
public System.Data.ParameterDirection Direction
{
get;
set;
}
/// <summary>
/// 是否输出参数
/// </summary>
public bool Output
{
get;
set;
}
/// <summary>
/// 属性操作句柄
/// </summary>
public PropertyHandler Handler
{
get;
set;
}
}
}
| 18.791667 | 55 | 0.443459 | [
"MIT"
] | TracyHu/IKendeLib | Peanut/Peanut/Mappings/PorcParameterAttribute.cs | 958 | C# |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Net.Http;
using System.Text;
namespace Couchbase.Search
{
/// <summary>
/// The result of a search query.
/// </summary>
/// <seealso cref="Couchbase.Search.ISearchQueryResult" />
public class SearchQueryResult : ISearchQueryResult, IDisposable
{
private HttpClient _httpClient;
internal SearchQueryResult()
{
Hits = new List<ISearchQueryRow>();
Facets = new Dictionary<string, IFacetResult>();
Errors = new List<string>();
Metrics = new SearchMetrics();
}
internal SearchQueryResult(HttpClient httpClient)
: this()
{
_httpClient = httpClient;
}
public IEnumerator<ISearchQueryRow> GetEnumerator()
{
return Hits.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
/// <summary>
/// Gets a value indicating whether this <see cref="ISearchQueryResult" /> is success.
/// </summary>
/// <value>
/// <c>true</c> if success; otherwise, <c>false</c>.
/// </value>
public bool Success { get; internal set; }
/// <summary>
/// If the operation wasn't succesful, the first message returned in the <see cref="Errors"/>
/// </summary>
[Obsolete("Use the Errors collection.")]
string IResult.Message { get { return string.Empty; } }
/// <summary>
/// The rows returned by the search request.
/// </summary>
public IList<ISearchQueryRow> Hits { get; internal set; }
/// <summary>
/// The rows returned by the search request. Throws caugh exception if an execution error occured.
/// Throws Exception if an execution error occured while processing requst.
/// </summary>
public IList<ISearchQueryRow> HitsOrFail
{
get
{
if (Exception != null)
{
throw Exception;
}
return Hits;
}
}
/// <summary>
/// The facets for the result.
/// </summary>
public IDictionary<string, IFacetResult> Facets { get; internal set; }
/// <summary>
/// The errors returned from the server if the request failed.
/// </summary>
public IList<string> Errors { get; internal set; }
/// <summary>
/// If Success is false and an exception has been caught internally, this field will contain the exception.
/// </summary>
public Exception Exception { get; set; }
/// <summary>
/// Adds the specified row.
/// </summary>
/// <param name="row">The row.</param>
internal void Add(ISearchQueryRow row)
{
Hits.Add(row);
}
bool IResult.ShouldRetry()
{
throw new NotImplementedException();
}
/// <summary>
/// The status for the result.
/// </summary>
public SearchStatus Status { get; set; }
/// <summary>
/// The metrics for the search. Includes number of hits, time taken, etc.
/// </summary>
public SearchMetrics Metrics { get; internal set; }
public void Dispose()
{
if (_httpClient != null)
{
_httpClient.Dispose();
_httpClient = null;
}
}
public override string ToString()
{
var sb = new StringBuilder();
sb.AppendFormat("Status: {0}", Status);
if (Errors != null)
{
foreach (var error in Errors)
{
sb.AppendFormat("Error: {0}", error);
}
}
if (Exception != null)
{
sb.AppendFormat("Exception: {0}", Exception);
}
return sb.ToString();
}
}
}
#region [ License information ]
/* ************************************************************
*
* @author Couchbase <info@couchbase.com>
* @copyright 2015 Couchbase, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* ************************************************************/
#endregion
| 30.023952 | 115 | 0.528121 | [
"Apache-2.0"
] | Svizel/couchbase-net-client | Src/Couchbase/Search/SearchQueryResult.cs | 5,016 | 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 backup-2018-11-15.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.Backup.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using ThirdParty.Json.LitJson;
namespace Amazon.Backup.Model.Internal.MarshallTransformations
{
/// <summary>
/// Response Unmarshaller for GetBackupSelection operation
/// </summary>
public class GetBackupSelectionResponseUnmarshaller : 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)
{
GetBackupSelectionResponse response = new GetBackupSelectionResponse();
context.Read();
int targetDepth = context.CurrentDepth;
while (context.ReadAtDepth(targetDepth))
{
if (context.TestExpression("BackupPlanId", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
response.BackupPlanId = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("BackupSelection", targetDepth))
{
var unmarshaller = BackupSelectionUnmarshaller.Instance;
response.BackupSelection = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("CreationDate", targetDepth))
{
var unmarshaller = DateTimeUnmarshaller.Instance;
response.CreationDate = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("CreatorRequestId", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
response.CreatorRequestId = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("SelectionId", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
response.SelectionId = unmarshaller.Unmarshall(context);
continue;
}
}
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)
{
var errorResponse = JsonErrorResponseUnmarshaller.GetInstance().Unmarshall(context);
errorResponse.InnerException = innerException;
errorResponse.StatusCode = statusCode;
var responseBodyBytes = context.GetResponseBodyBytes();
using (var streamCopy = new MemoryStream(responseBodyBytes))
using (var contextCopy = new JsonUnmarshallerContext(streamCopy, false, null))
{
if (errorResponse.Code != null && errorResponse.Code.Equals("InvalidParameterValueException"))
{
return InvalidParameterValueExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("MissingParameterValueException"))
{
return MissingParameterValueExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("ResourceNotFoundException"))
{
return ResourceNotFoundExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("ServiceUnavailableException"))
{
return ServiceUnavailableExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse);
}
}
return new AmazonBackupException(errorResponse.Message, errorResponse.InnerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, errorResponse.StatusCode);
}
private static GetBackupSelectionResponseUnmarshaller _instance = new GetBackupSelectionResponseUnmarshaller();
internal static GetBackupSelectionResponseUnmarshaller GetInstance()
{
return _instance;
}
/// <summary>
/// Gets the singleton.
/// </summary>
public static GetBackupSelectionResponseUnmarshaller Instance
{
get
{
return _instance;
}
}
}
} | 41.178082 | 189 | 0.622089 | [
"Apache-2.0"
] | DetlefGolze/aws-sdk-net | sdk/src/Services/Backup/Generated/Model/Internal/MarshallTransformations/GetBackupSelectionResponseUnmarshaller.cs | 6,012 | 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 imagebuilder-2019-12-02.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.Imagebuilder.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using ThirdParty.Json.LitJson;
namespace Amazon.Imagebuilder.Model.Internal.MarshallTransformations
{
/// <summary>
/// Response Unmarshaller for ListImagePipelineImages operation
/// </summary>
public class ListImagePipelineImagesResponseUnmarshaller : 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)
{
ListImagePipelineImagesResponse response = new ListImagePipelineImagesResponse();
context.Read();
int targetDepth = context.CurrentDepth;
while (context.ReadAtDepth(targetDepth))
{
if (context.TestExpression("imageSummaryList", targetDepth))
{
var unmarshaller = new ListUnmarshaller<ImageSummary, ImageSummaryUnmarshaller>(ImageSummaryUnmarshaller.Instance);
response.ImageSummaryList = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("nextToken", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
response.NextToken = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("requestId", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
response.RequestId = unmarshaller.Unmarshall(context);
continue;
}
}
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)
{
var errorResponse = JsonErrorResponseUnmarshaller.GetInstance().Unmarshall(context);
errorResponse.InnerException = innerException;
errorResponse.StatusCode = statusCode;
var responseBodyBytes = context.GetResponseBodyBytes();
using (var streamCopy = new MemoryStream(responseBodyBytes))
using (var contextCopy = new JsonUnmarshallerContext(streamCopy, false, null))
{
if (errorResponse.Code != null && errorResponse.Code.Equals("CallRateLimitExceededException"))
{
return CallRateLimitExceededExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("ClientException"))
{
return ClientExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("ForbiddenException"))
{
return ForbiddenExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("InvalidPaginationTokenException"))
{
return InvalidPaginationTokenExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("InvalidRequestException"))
{
return InvalidRequestExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("ResourceNotFoundException"))
{
return ResourceNotFoundExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("ServiceException"))
{
return ServiceExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("ServiceUnavailableException"))
{
return ServiceUnavailableExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse);
}
}
return new AmazonImagebuilderException(errorResponse.Message, errorResponse.InnerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, errorResponse.StatusCode);
}
private static ListImagePipelineImagesResponseUnmarshaller _instance = new ListImagePipelineImagesResponseUnmarshaller();
internal static ListImagePipelineImagesResponseUnmarshaller GetInstance()
{
return _instance;
}
/// <summary>
/// Gets the singleton.
/// </summary>
public static ListImagePipelineImagesResponseUnmarshaller Instance
{
get
{
return _instance;
}
}
}
} | 43.38 | 195 | 0.631935 | [
"Apache-2.0"
] | ChristopherButtars/aws-sdk-net | sdk/src/Services/Imagebuilder/Generated/Model/Internal/MarshallTransformations/ListImagePipelineImagesResponseUnmarshaller.cs | 6,507 | C# |
using System.Collections.Generic;
using Magicalizer.Data.Entities.Abstractions;
namespace App.Data.Entities
{
public class Category : IEntity<int>
{
public int Id { get; set; }
public string Name { get; set; }
public virtual ICollection<Product> Products { get; set; }
}
} | 22.538462 | 62 | 0.703072 | [
"Apache-2.0"
] | Magicalizer/Magicalizer-Sample | App/Entities/Category.cs | 295 | C# |
using System;
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;
namespace KakuEditorTools
{
public abstract class WindowEditorBase<T> : EditorWindow where T : WindowEditorBase<T>
{
protected static string WindowTitle { get; set; }
protected static bool IsUtility { get; set; }
protected static T m_Window;
protected static void Init()
{
Type type = typeof(T);
WindowBaseAttribute info = null;
foreach (var item in type.GetCustomAttributes(false))
{
info = item as WindowBaseAttribute;
if (null != info)
{
break;
}
}
if (info != null)
{
m_Window = GetWindow<T>(info.IsUtility, info.Name, true);
}
else
{
m_Window = GetWindow<T>(false, typeof(T).Name, true);
}
}
protected virtual void OnEnable()
{
}
protected virtual void OnDisable()
{
}
protected virtual void OnGUI()
{
}
/// <summary>
/// 绘制顶部Toggle标签。
/// </summary>
/// <param name="bars">可选标签名字数组。</param>
/// <param name="lastIndex">当前选择的索引。</param>
/// <param name="width">标签的宽度。</param>
/// <returns>返回最后选择的索引。</returns>
protected int DrawToolBar(string[] bars, int lastIndex, int width = 120)
{
int currentIndex = lastIndex;
EditorGUILayout.BeginHorizontal(EditorStyles.toolbar);
for (int i = 0; i < bars.Length; i++)
{
GUILayout.BeginVertical(EditorStyles.toolbar);
if (GUILayout.Toggle(i == currentIndex, bars[i], EditorStyles.toolbarButton, GUILayout.Height(25), GUILayout.Width(width)))
{
currentIndex = i;
}
GUILayout.EndVertical();
}
GUILayout.Toolbar(0, new[] { "" }, EditorStyles.toolbar, GUILayout.ExpandWidth(true));
EditorGUILayout.EndHorizontal();
EditorGUILayout.Space(10);
return currentIndex;
}
Vector2 m_DrawGameObjectSelector_ScrollPos = Vector2.zero;
/// <summary>
/// 绘制添加GameObject功能的基础图形。
/// </summary>
/// <param name="goList">存放GameObject的列表。</param>
/// <param name="scrollPos">滚动列表的位置。</param>
/// <param name="height">滚动列表的最小高度。</param>
protected void DrawGameObjectSelector<AssetType>(List<AssetType> goList, bool allowSceneObject = true, int height = 120) where AssetType : UnityEngine.Object
{
EditorGUILayout.BeginVertical();
GUILayout.Label("手动添加的物体", EditorStyles.toolbarButton);
if (goList.Count == 0 || goList[goList.Count - 1] != null)
{
goList.Add(null);
}
m_DrawGameObjectSelector_ScrollPos = EditorGUILayout.BeginScrollView(m_DrawGameObjectSelector_ScrollPos, false, false, GUILayout.Height(height));
int length = goList.Count;
for (int i = 0; i < goList.Count; i++)
{
EditorGUILayout.BeginHorizontal();
AssetType obj = (AssetType)EditorGUILayout.ObjectField(goList[i], typeof(AssetType), true);
if (goList[i] != obj)
{
if (goList.Contains(obj))
{
goList.RemoveAt(i);
i--;
Debug.Log("该物体已经存在,不要添加重复物体。");
continue;
}
goList[i] = obj;
}
if ((goList[i] == null && i < length) || GUILayout.Button("Remove", GUILayout.Width(120)))
{
goList.RemoveAt(i);
i--;
}
EditorGUILayout.EndHorizontal();
}
EditorGUILayout.EndScrollView();
EditorGUILayout.EndVertical();
}
Vector2 m_DrawGameObjectSelectorArea_ScrollPos = Vector2.zero;
/// <summary>
/// 绘制检索文件夹物品功能的基础图形。
/// </summary>
/// <typeparam name="ObjectType">显示在GUI面板中的资源类型。</typeparam>
/// <typeparam name="AssetType">从文件夹中加载的资源类型。</typeparam>
/// <param name="btnName">按钮的名称。</param>
/// <param name="filter">资源过滤条件。</param>
/// <param name="goList">GameObject数组。</param>
/// <param name="objectList">显示在GUI面板中的资源列表。</param>
/// <param name="clickCallback">按钮点击回调。</param>
protected void DrawGameObjectSelectorArea<ObjectType>(string btnName, string filter, List<GameObject> goList, List<ObjectType> objectList, Action<List<GameObject>> clickCallback) where ObjectType : UnityEngine.Object
{
EditorGUILayout.BeginVertical();
if (GUILayout.Button(btnName))
{
clickCallback?.Invoke(goList);
}
EditorGUILayout.Space(5);
m_DrawGameObjectSelectorArea_ScrollPos = EditorGUILayout.BeginScrollView(m_DrawGameObjectSelectorArea_ScrollPos, false, false, GUILayout.Height(250));
for (int i = 0; i < objectList.Count; i++)
{
EditorGUILayout.ObjectField(objectList[i], typeof(ObjectType), false);
}
EditorGUILayout.EndScrollView();
EditorGUILayout.EndVertical();
}
Vector2 m_DrawFoldSelector_ScrollPos = Vector2.zero;
/// <summary>
/// 绘制添加文件夹功能的基础图形。
/// </summary>
/// <param name="foldPathList">记录文件夹路径的列表</param>
protected void DrawFoldSelector(List<string> foldPathList, int height = 120)
{
EditorGUILayout.BeginVertical();
GUILayout.Label("当前选中文件夹", EditorStyles.toolbarButton);
m_DrawFoldSelector_ScrollPos = EditorGUILayout.BeginScrollView(m_DrawFoldSelector_ScrollPos, false, false, GUILayout.Height(height));
for (int i = 0; i < foldPathList.Count; i++)
{
EditorGUILayout.BeginHorizontal();
EditorGUILayout.LabelField(foldPathList[i], EditorStyles.textField);
if (GUILayout.Button("Remove", GUILayout.Width(120)))
{
foldPathList.RemoveAt(i);
i--;
}
EditorGUILayout.EndHorizontal();
}
EditorGUILayout.EndScrollView();
if (GUILayout.Button("添加文件夹"))
{
string foldPath = EditorUtility.OpenFolderPanel("选择一个文件夹", Application.dataPath, "");
foldPath = Utility.AbsolutePathToRelativePath(foldPath);
if (!string.IsNullOrEmpty(foldPath))
{
foldPathList.Add(foldPath);
}
}
EditorGUILayout.EndVertical();
}
Vector2 m_DrawFoldObjectArea_ScrollPos = Vector2.zero;
/// <summary>
/// 绘制检索文件夹物品功能的基础图形。
/// </summary>
/// <typeparam name="ObjectType">显示在GUI面板中的资源类型。</typeparam>
/// <typeparam name="AssetType">从文件夹中加载的资源类型。</typeparam>
/// <param name="btnName">按钮的名称。</param>
/// <param name="filter">资源过滤条件。</param>
/// <param name="foldArray">文件夹数组。</param>
/// <param name="objectList">显示在GUI面板中的资源列表。</param>
/// <param name="clickCallback">按钮点击回调。</param>
protected void DrawFoldObjectArea<ObjectType, AssetType>(string btnName, string filter, string[] foldArray, List<ObjectType> objectList, Action<List<AssetType>> clickCallback) where AssetType : UnityEngine.Object where ObjectType : UnityEngine.Object
{
EditorGUILayout.BeginVertical();
if (GUILayout.Button(btnName))
{
List<AssetType> list = new List<AssetType>();
string[] guidList = AssetDatabase.FindAssets(filter, foldArray);
foreach (var guid in guidList)
{
AssetType obejct = AssetDatabase.LoadAssetAtPath<AssetType>(AssetDatabase.GUIDToAssetPath(guid));
list.Add(obejct);
}
clickCallback?.Invoke(list);
}
EditorGUILayout.Space(5);
m_DrawFoldObjectArea_ScrollPos = EditorGUILayout.BeginScrollView(m_DrawFoldObjectArea_ScrollPos, false, false, GUILayout.Height(250));
for (int i = 0; i < objectList.Count; i++)
{
EditorGUILayout.ObjectField(objectList[i], typeof(ObjectType), false);
}
EditorGUILayout.EndScrollView();
EditorGUILayout.EndVertical();
}
/// <summary>
/// 绘制水平线
/// </summary>
protected void DrawVerticalUILine(Color color, int thickness = 2, int padding = 10)
{
Rect r = EditorGUILayout.GetControlRect(GUILayout.Height(padding + thickness));
r.height = thickness;
r.y += padding / 2;
r.x -= 2;
r.width += 6;
EditorGUI.DrawRect(r, color);
}
/// <summary>
/// 绘制垂直线
/// </summary>
protected void DrawHorizalUILine(Color color, int height = 100, int thickness = 2, int padding = 10)
{
Rect r = EditorGUILayout.GetControlRect(GUILayout.Width(padding + thickness));
r.height = height;
r.y -= 2;
r.x += padding / 2;
r.width = thickness;
EditorGUI.DrawRect(r, color);
}
}
public sealed class FoldObjectArea<ObjectType, AssetType> where AssetType : UnityEngine.Object where ObjectType : UnityEngine.Object
{
public string btnName;
public string filter;
public string[] foldArray;
public List<ObjectType> objectList;
public Action<List<AssetType>> clickCallback;
public FoldObjectArea(string btnName, string filter, string[] foldArray, List<ObjectType> objectList, Action<List<AssetType>> clickCallback)
{
this.btnName = btnName;
this.filter = filter;
this.foldArray = foldArray;
this.objectList = objectList;
this.clickCallback = clickCallback;
}
}
[AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = true)]
public class WindowBaseAttribute : Attribute
{
public WindowBaseAttribute(string name, bool isUtility)
{
Name = name;
IsUtility = isUtility;
}
public string Name { get; set; }
public bool IsUtility { get; set; }
}
}
| 38.653571 | 258 | 0.556962 | [
"MIT"
] | gdut-kaku/UIGameTools | UIGameTools/Assets/UnityTools/UGUITools/EditorTools/Editor/Base/WindowEditorBase.cs | 11,445 | C# |
namespace LRS.NET.Core.Domain.Components {
public interface IComponent {}
} | 25.333333 | 42 | 0.789474 | [
"MIT"
] | m-sadegh-sh/LRS.NET | src/LRS.NET.Core/Domain/Components/IComponent.cs | 76 | C# |
using System;
using System.Reactive.Linq;
namespace Shiny.BluetoothLE
{
public interface ICanRequestMtu : IPeripheral
{
IObservable<int> RequestMtu(int size);
/// <summary>
/// Fires when MTU size changes
/// </summary>
/// <returns>The mtu change requested.</returns>
IObservable<int> WhenMtuChanged();
}
public static class FeatureExtensionsMtu
{
public static bool IsMtuRequestsAvailable(this IPeripheral peripheral) => peripheral is ICanRequestMtu;
public static IObservable<int> TryRequestMtu(this IPeripheral peripheral, int requestSize)
{
if (peripheral is ICanRequestMtu mtu)
return mtu.RequestMtu(requestSize);
return Observable.Return(peripheral.MtuSize);
}
public static IObservable<int> WhenMtuChanged(this IPeripheral periperhal)
{
if (periperhal is ICanRequestMtu mtu)
return mtu.WhenMtuChanged();
return Observable.Empty<int>();
}
}
}
| 26.073171 | 111 | 0.633302 | [
"MIT"
] | Codelisk/shiny | src/Shiny.BluetoothLE/Feature_Mtu.cs | 1,071 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Threading.Tasks;
namespace DataAccess
{
public class HistoryLogin
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
[Key]
public long HistoryLoginID { get; set; }
public DateTime DateTime { get; set; }
public string StudentID { get; set; }
public Member Student { get; set; }
public MethodLogin MethodLogin { get; set; }
}
public enum MethodLogin
{
Password,
FaceRecognized,
}
}
| 25.384615 | 61 | 0.675758 | [
"Apache-2.0"
] | nguyendev/DATN | Code/Models/HistoryLogin.cs | 662 | C# |
namespace SpaceEngineers.Core.DataAccess.Orm.PostgreSql.Translation
{
using System.Linq;
using System.Text;
using AutoRegistration.Api.Attributes;
using AutoRegistration.Api.Enumerations;
using Basics;
using CompositionRoot.Api.Abstractions.Container;
using Sql.Translation;
using Sql.Translation.Expressions;
using Sql.Translation.Extensions;
[Component(EnLifestyle.Singleton)]
internal class ProjectionExpressionTranslator : IExpressionTranslator<ProjectionExpression>
{
private readonly IDependencyContainer _dependencyContainer;
public ProjectionExpressionTranslator(IDependencyContainer dependencyContainer)
{
_dependencyContainer = dependencyContainer;
}
public string Translate(ProjectionExpression expression, int depth)
{
var sb = new StringBuilder();
sb.AppendLine(expression.IsDistinct ? "SELECT DISTINCT" : "SELECT");
var lastBindingIndex = expression.Bindings.Count - 1;
if (expression.Bindings.Any())
{
expression
.Bindings
.Select(binding => binding.Translate(_dependencyContainer, depth))
.Each((binding, i) =>
{
sb.Append(new string('\t', depth + 1));
sb.Append(binding);
var ending = i < lastBindingIndex
? ","
: string.Empty;
sb.AppendLine(ending);
});
}
else
{
sb.Append(new string('\t', depth + 1));
sb.AppendLine("*");
}
sb.Append(new string('\t', depth));
sb.AppendLine("FROM");
sb.Append(new string('\t', depth + 1));
sb.Append(expression.Source.Translate(_dependencyContainer, depth + 1));
return sb.ToString();
}
}
} | 33.42623 | 95 | 0.554193 | [
"MIT"
] | warning-explosive/Core | Modules/DataAccess.Orm.PostgreSql/Translation/ProjectionExpressionTranslator.cs | 2,039 | C# |
/*
* Author: © noblesigma
* Project: NWNLogRotator
* GitHub: https://github.com/noblesigma/NWNLogRotator
* Date: 3/3/2021
* License: MIT
* Purpose: This program is designed used alongside the Neverwinter Nights game, either Enhanced Edition, or 1.69.
* This program does not come with a warranty. Any support may be found on the GitHub page.
*/
namespace NWNLogRotator.Classes
{
public class Settings
{
public string OutputDirectory;
public string PathToLog;
public int MinimumRowsCount;
public string ServerName;
public string ServerNameColor;
public bool EventText;
public bool CombatText;
public string UseTheme;
public bool Silent;
public bool Tray;
public bool SaveBackup;
public bool SaveBackupOnly;
public bool SaveOnLaunch;
public bool Notifications;
public string OOCColor;
public string FilterLines;
public string PathToClient;
public bool RunClientOnLaunch;
public bool CloseOnLogGenerated;
public string ServerAddress;
public string ServerPassword;
public bool DM;
public bool ServerMode;
public string BackgroundColor;
public string TimestampColor;
public string DefaultColor;
public string ActorColor;
public string PartyColor;
public string EmoteColor;
public string ShoutColor;
public string TellColor;
public string WhisperColor;
public string MyColor;
public string MyCharacters;
public string FontName;
public string FontSize;
public string CustomEmoteOne;
public string CustomEmoteOneColor;
public string CustomEmoteTwo;
public string CustomEmoteTwoColor;
public string CustomEmoteThree;
public string CustomEmoteThreeColor;
// create singleton
public static Settings _instance = new Settings();
// prototype
public Settings()
{
this.OutputDirectory = "C:\\nwnlogs";
this.PathToLog = "C:\\nwnlogs\\nwClientLog1.txt";
this.MinimumRowsCount = 5;
this.ServerName = "";
this.ServerNameColor = "EECC00";
this.EventText = false;
this.CombatText = false;
this.UseTheme = "light";
this.Silent = false;
this.Tray = false;
this.SaveBackup = false;
this.SaveBackupOnly = false;
this.SaveOnLaunch = false;
this.Notifications = false;
this.OOCColor = "D70A53";
this.FilterLines = "";
this.PathToClient = "";
this.RunClientOnLaunch = false;
this.CloseOnLogGenerated = false;
this.ServerAddress = "";
this.ServerPassword = "";
this.DM = false;
this.ServerMode = false;
this.BackgroundColor = "000000";
this.TimestampColor = "B1A2BD";
this.DefaultColor = "FFFFFF";
this.ActorColor = "8F7FFF";
this.PartyColor = "FFAED6";
this.EmoteColor = "A6DDCE";
this.ShoutColor = "F0DBA5";
this.TellColor = "00FF00";
this.WhisperColor = "808080";
this.MyColor = "D6CEFD";
this.MyCharacters = "";
this.FontName = "Tahoma, Geneva, sans-serif";
this.FontSize = "calc(.7vw + .7vh + .5vmin)";
this.CustomEmoteOne = "";
this.CustomEmoteOneColor = "FF9944";
this.CustomEmoteTwo = "";
this.CustomEmoteTwoColor = "87CEEB";
this.CustomEmoteThree = "";
this.CustomEmoteThreeColor = "FFD8B1";
}
// binding
public Settings(string OutputDirectory,
string PathToLog,
int MinimumRowsCount,
string ServerName,
string ServerNameColor,
bool EventText,
bool CombatText,
string UseTheme,
bool Silent,
bool Tray,
bool SaveBackup,
bool SaveBackupOnly,
bool SaveOnLaunch,
bool Notifications,
string OOCColor,
string FilterLines,
string PathToClient,
bool RunClientOnLaunch,
bool CloseOnLogGenerated,
string ServerAddress,
string ServerPassword,
bool DM,
bool ServerMode,
string BackgroundColor,
string TimestampColor,
string DefaultColor,
string ActorColor,
string PartyColor,
string EmoteColor,
string ShoutColor,
string TellColor,
string WhisperColor,
string MyColor,
string MyCharacters,
string FontName,
string FontSize,
string CustomEmoteOne,
string CustomEmoteOneColor,
string CustomEmoteTwo,
string CustomEmoteTwoColor,
string CustomEmoteThree,
string CustomEmoteThreeColor)
{
this.OutputDirectory = OutputDirectory;
this.PathToLog = PathToLog;
this.MinimumRowsCount = MinimumRowsCount;
this.ServerName = ServerName;
this.ServerNameColor = ServerNameColor;
this.EventText = EventText;
this.CombatText = CombatText;
this.UseTheme = UseTheme;
this.Silent = Silent;
this.Tray = Tray;
this.SaveBackup = SaveBackup;
this.SaveBackupOnly = SaveBackupOnly;
this.SaveOnLaunch = SaveOnLaunch;
this.Notifications = Notifications;
this.OOCColor = OOCColor;
this.FilterLines = FilterLines;
this.PathToClient = PathToClient;
this.RunClientOnLaunch = RunClientOnLaunch;
this.CloseOnLogGenerated = CloseOnLogGenerated;
this.ServerAddress = ServerAddress;
this.ServerPassword = ServerPassword;
this.DM = DM;
this.ServerMode = ServerMode;
this.BackgroundColor = BackgroundColor;
this.TimestampColor = TimestampColor;
this.DefaultColor = DefaultColor;
this.ActorColor = ActorColor;
this.PartyColor = PartyColor;
this.EmoteColor = EmoteColor;
this.ShoutColor = ShoutColor;
this.TellColor = TellColor;
this.WhisperColor = WhisperColor;
this.MyColor = MyColor;
this.MyCharacters = MyCharacters;
this.FontName = FontName;
this.FontSize = FontSize;
this.CustomEmoteOne = CustomEmoteOne;
this.CustomEmoteOneColor = CustomEmoteOneColor;
this.CustomEmoteTwo = CustomEmoteTwo;
this.CustomEmoteTwoColor = CustomEmoteTwoColor;
this.CustomEmoteThree = CustomEmoteThree;
this.CustomEmoteThreeColor = CustomEmoteThreeColor;
}
// get singleton
public Settings Instance
{
get { return _instance; }
}
}
}
| 38.231527 | 119 | 0.541812 | [
"MIT"
] | noblesigma/NWNLogRotator | Classes/Settings.cs | 7,764 | C# |
/**
* Copyright 2019 Adobe Systems Incorporated. All rights reserved.
* This file is licensed to you under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. You may obtain a copy
* of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under
* the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
* OF ANY KIND, either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*
*
**/
/*
* No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
*
* OpenAPI spec version: 6.0.0
*
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*/
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using SwaggerDateConverter = AdobeSign.Rest.Client.SwaggerDateConverter;
namespace AdobeSign.Rest.Model.Agreements
{
/// <summary>
/// AgreementCreationInfo
/// </summary>
[DataContract]
public partial class AgreementCreationInfo : IEquatable<AgreementCreationInfo>, IValidatableObject
{
/// <summary>
/// Optional parameter that sets how often you want to send reminders to the participants. If it is not specified, the default frequency set for the account will be used. Should not be provided in offline agreement creation. If provided in PUT as a different value than the current one, an error will be thrown.
/// </summary>
/// <value>Optional parameter that sets how often you want to send reminders to the participants. If it is not specified, the default frequency set for the account will be used. Should not be provided in offline agreement creation. If provided in PUT as a different value than the current one, an error will be thrown.</value>
[JsonConverter(typeof(StringEnumConverter))]
public enum ReminderFrequencyEnum
{
/// <summary>
/// Enum DAILYUNTILSIGNED for value: DAILY_UNTIL_SIGNED
/// </summary>
[EnumMember(Value = "DAILY_UNTIL_SIGNED")]
DAILYUNTILSIGNED = 1,
/// <summary>
/// Enum WEEKDAILYUNTILSIGNED for value: WEEKDAILY_UNTIL_SIGNED
/// </summary>
[EnumMember(Value = "WEEKDAILY_UNTIL_SIGNED")]
WEEKDAILYUNTILSIGNED = 2,
/// <summary>
/// Enum EVERYOTHERDAYUNTILSIGNED for value: EVERY_OTHER_DAY_UNTIL_SIGNED
/// </summary>
[EnumMember(Value = "EVERY_OTHER_DAY_UNTIL_SIGNED")]
EVERYOTHERDAYUNTILSIGNED = 3,
/// <summary>
/// Enum EVERYTHIRDDAYUNTILSIGNED for value: EVERY_THIRD_DAY_UNTIL_SIGNED
/// </summary>
[EnumMember(Value = "EVERY_THIRD_DAY_UNTIL_SIGNED")]
EVERYTHIRDDAYUNTILSIGNED = 4,
/// <summary>
/// Enum EVERYFIFTHDAYUNTILSIGNED for value: EVERY_FIFTH_DAY_UNTIL_SIGNED
/// </summary>
[EnumMember(Value = "EVERY_FIFTH_DAY_UNTIL_SIGNED")]
EVERYFIFTHDAYUNTILSIGNED = 5,
/// <summary>
/// Enum WEEKLYUNTILSIGNED for value: WEEKLY_UNTIL_SIGNED
/// </summary>
[EnumMember(Value = "WEEKLY_UNTIL_SIGNED")]
WEEKLYUNTILSIGNED = 6,
/// <summary>
/// Enum ONCE for value: ONCE
/// </summary>
[EnumMember(Value = "ONCE")]
ONCE = 7
}
/// <summary>
/// Optional parameter that sets how often you want to send reminders to the participants. If it is not specified, the default frequency set for the account will be used. Should not be provided in offline agreement creation. If provided in PUT as a different value than the current one, an error will be thrown.
/// </summary>
/// <value>Optional parameter that sets how often you want to send reminders to the participants. If it is not specified, the default frequency set for the account will be used. Should not be provided in offline agreement creation. If provided in PUT as a different value than the current one, an error will be thrown.</value>
[DataMember(Name="reminderFrequency", EmitDefaultValue=false)]
public ReminderFrequencyEnum? ReminderFrequency { get; set; }
/// <summary>
/// Specifies the type of signature you would like to request - written or e-signature. The possible values are <br> ESIGN : Agreement needs to be signed electronically <br>, WRITTEN : Agreement will be signed using handwritten signature and signed document will be uploaded into the system
/// </summary>
/// <value>Specifies the type of signature you would like to request - written or e-signature. The possible values are <br> ESIGN : Agreement needs to be signed electronically <br>, WRITTEN : Agreement will be signed using handwritten signature and signed document will be uploaded into the system</value>
[JsonConverter(typeof(StringEnumConverter))]
public enum SignatureTypeEnum
{
/// <summary>
/// Enum ESIGN for value: ESIGN
/// </summary>
[EnumMember(Value = "ESIGN")]
ESIGN = 1,
/// <summary>
/// Enum WRITTEN for value: WRITTEN
/// </summary>
[EnumMember(Value = "WRITTEN")]
WRITTEN = 2
}
/// <summary>
/// Specifies the type of signature you would like to request - written or e-signature. The possible values are <br> ESIGN : Agreement needs to be signed electronically <br>, WRITTEN : Agreement will be signed using handwritten signature and signed document will be uploaded into the system
/// </summary>
/// <value>Specifies the type of signature you would like to request - written or e-signature. The possible values are <br> ESIGN : Agreement needs to be signed electronically <br>, WRITTEN : Agreement will be signed using handwritten signature and signed document will be uploaded into the system</value>
[DataMember(Name="signatureType", EmitDefaultValue=false)]
public SignatureTypeEnum? SignatureType { get; set; }
/// <summary>
/// The state in which the agreement should land. The state field can only be provided in POST calls, will never get returned in GET /agreements/{ID} and will be ignored if provided in PUT /agreements/{ID} call. The eventual status of the agreement can be obtained from GET /agreements/ID
/// </summary>
/// <value>The state in which the agreement should land. The state field can only be provided in POST calls, will never get returned in GET /agreements/{ID} and will be ignored if provided in PUT /agreements/{ID} call. The eventual status of the agreement can be obtained from GET /agreements/ID</value>
[JsonConverter(typeof(StringEnumConverter))]
public enum StateEnum
{
/// <summary>
/// Enum AUTHORING for value: AUTHORING
/// </summary>
[EnumMember(Value = "AUTHORING")]
AUTHORING = 1,
/// <summary>
/// Enum DRAFT for value: DRAFT
/// </summary>
[EnumMember(Value = "DRAFT")]
DRAFT = 2,
/// <summary>
/// Enum INPROCESS for value: IN_PROCESS
/// </summary>
[EnumMember(Value = "IN_PROCESS")]
INPROCESS = 3
}
/// <summary>
/// The state in which the agreement should land. The state field can only be provided in POST calls, will never get returned in GET /agreements/{ID} and will be ignored if provided in PUT /agreements/{ID} call. The eventual status of the agreement can be obtained from GET /agreements/ID
/// </summary>
/// <value>The state in which the agreement should land. The state field can only be provided in POST calls, will never get returned in GET /agreements/{ID} and will be ignored if provided in PUT /agreements/{ID} call. The eventual status of the agreement can be obtained from GET /agreements/ID</value>
[DataMember(Name="state", EmitDefaultValue=false)]
public StateEnum? State { get; set; }
/// <summary>
/// This is a server generated attribute which provides the detailed status of an agreement.
/// </summary>
/// <value>This is a server generated attribute which provides the detailed status of an agreement.</value>
[JsonConverter(typeof(StringEnumConverter))]
public enum StatusEnum
{
/// <summary>
/// Enum OUTFORSIGNATURE for value: OUT_FOR_SIGNATURE
/// </summary>
[EnumMember(Value = "OUT_FOR_SIGNATURE")]
OUTFORSIGNATURE = 1,
/// <summary>
/// Enum OUTFORDELIVERY for value: OUT_FOR_DELIVERY
/// </summary>
[EnumMember(Value = "OUT_FOR_DELIVERY")]
OUTFORDELIVERY = 2,
/// <summary>
/// Enum OUTFORACCEPTANCE for value: OUT_FOR_ACCEPTANCE
/// </summary>
[EnumMember(Value = "OUT_FOR_ACCEPTANCE")]
OUTFORACCEPTANCE = 3,
/// <summary>
/// Enum OUTFORFORMFILLING for value: OUT_FOR_FORM_FILLING
/// </summary>
[EnumMember(Value = "OUT_FOR_FORM_FILLING")]
OUTFORFORMFILLING = 4,
/// <summary>
/// Enum OUTFORAPPROVAL for value: OUT_FOR_APPROVAL
/// </summary>
[EnumMember(Value = "OUT_FOR_APPROVAL")]
OUTFORAPPROVAL = 5,
/// <summary>
/// Enum AUTHORING for value: AUTHORING
/// </summary>
[EnumMember(Value = "AUTHORING")]
AUTHORING = 6,
/// <summary>
/// Enum CANCELLED for value: CANCELLED
/// </summary>
[EnumMember(Value = "CANCELLED")]
CANCELLED = 7,
/// <summary>
/// Enum SIGNED for value: SIGNED
/// </summary>
[EnumMember(Value = "SIGNED")]
SIGNED = 8,
/// <summary>
/// Enum APPROVED for value: APPROVED
/// </summary>
[EnumMember(Value = "APPROVED")]
APPROVED = 9,
/// <summary>
/// Enum DELIVERED for value: DELIVERED
/// </summary>
[EnumMember(Value = "DELIVERED")]
DELIVERED = 10,
/// <summary>
/// Enum ACCEPTED for value: ACCEPTED
/// </summary>
[EnumMember(Value = "ACCEPTED")]
ACCEPTED = 11,
/// <summary>
/// Enum FORMFILLED for value: FORM_FILLED
/// </summary>
[EnumMember(Value = "FORM_FILLED")]
FORMFILLED = 12,
/// <summary>
/// Enum EXPIRED for value: EXPIRED
/// </summary>
[EnumMember(Value = "EXPIRED")]
EXPIRED = 13,
/// <summary>
/// Enum ARCHIVED for value: ARCHIVED
/// </summary>
[EnumMember(Value = "ARCHIVED")]
ARCHIVED = 14,
/// <summary>
/// Enum PREFILL for value: PREFILL
/// </summary>
[EnumMember(Value = "PREFILL")]
PREFILL = 15,
/// <summary>
/// Enum WIDGETWAITINGFORVERIFICATION for value: WIDGET_WAITING_FOR_VERIFICATION
/// </summary>
[EnumMember(Value = "WIDGET_WAITING_FOR_VERIFICATION")]
WIDGETWAITINGFORVERIFICATION = 16,
/// <summary>
/// Enum DRAFT for value: DRAFT
/// </summary>
[EnumMember(Value = "DRAFT")]
DRAFT = 17,
/// <summary>
/// Enum DOCUMENTSNOTYETPROCESSED for value: DOCUMENTS_NOT_YET_PROCESSED
/// </summary>
[EnumMember(Value = "DOCUMENTS_NOT_YET_PROCESSED")]
DOCUMENTSNOTYETPROCESSED = 18,
/// <summary>
/// Enum WAITINGFORFAXIN for value: WAITING_FOR_FAXIN
/// </summary>
[EnumMember(Value = "WAITING_FOR_FAXIN")]
WAITINGFORFAXIN = 19,
/// <summary>
/// Enum WAITINGFORVERIFICATION for value: WAITING_FOR_VERIFICATION
/// </summary>
[EnumMember(Value = "WAITING_FOR_VERIFICATION")]
WAITINGFORVERIFICATION = 20
}
/// <summary>
/// This is a server generated attribute which provides the detailed status of an agreement.
/// </summary>
/// <value>This is a server generated attribute which provides the detailed status of an agreement.</value>
[DataMember(Name="status", EmitDefaultValue=false)]
public StatusEnum? Status { get; set; }
/// <summary>
/// Initializes a new instance of the <see cref="AgreementCreationInfo" /> class.
/// </summary>
/// <param name="Ccs">A list of one or more CCs that will be copied in the agreement transaction. The CCs will each receive an email at the beginning of the transaction and also when the final document is signed. The email addresses will also receive a copy of the document, attached as a PDF file. Should not be provided in offline agreement creation..</param>
/// <param name="CreatedDate">Date when agreement was created. This is a server generated attributed and can not be provided in POST/PUT calls. Format would be yyyy-MM-dd'T'HH:mm:ssZ. For example, e.g 2016-02-25T18:46:19Z represents UTC time.</param>
/// <param name="DeviceInfo">Device info of the offline device. It should only be provided in case of offline agreement creation..</param>
/// <param name="DocumentVisibilityEnabled">If set to true, enable limited document visibility. Should not be provided in offline agreement creation..</param>
/// <param name="EmailOption">Email configurations for the agreement. Should not be provided in offline agreement creation or when updating a non draft agreement..</param>
/// <param name="ExpirationTime">Time after which Agreement expires and needs to be signed before it. Format should be yyyy-MM-dd'T'HH:mm:ssZ. For example, e.g 2016-02-25T18:46:19Z represents UTC time. Should not be provided in offline agreement creation..</param>
/// <param name="ExternalId">An arbitrary value from your system, which can be specified at sending time and then later returned or queried. Should not be provided in offline agreement creation..</param>
/// <param name="FileInfos">A list of one or more files (or references to files) that will be sent out for signature. If more than one file is provided, they will be combined into one PDF before being sent out. Note: Only one of the four parameters in every FileInfo object must be specified.</param>
/// <param name="FirstReminderDelay">Integer which specifies the delay in hours before sending the first reminder.<br>This is an optional field. The minimum value allowed is 1 hour and the maximum value can’t be more than the difference of agreement creation and expiry time of the agreement in hours.<br>If this is not specified but the reminder frequency is specified, then the first reminder will be sent based on frequency.<br>i.e. if the reminder is created with frequency specified as daily, the firstReminderDelay will be 24 hours. Should not be provided in offline agreement creation..</param>
/// <param name="FormFieldLayerTemplates">Specifies the form field layer template or source of form fields to apply on the files in this transaction. If specified, the FileInfo for this parameter must refer to a form field layer template via libraryDocumentId or libraryDocumentName, or if specified via transientDocumentId or documentURL, it must be of a supported file type. Note: Only one of the four parameters in every FileInfo object must be specified.</param>
/// <param name="Id">The unique identifier of the agreement.If provided in POST, it will simply be ignored.</param>
/// <param name="Locale">The locale associated with this agreement - specifies the language for the signing page and emails, for example en_US or fr_FR. If none specified, defaults to the language configured for the agreement sender.</param>
/// <param name="MergeFieldInfo">Optional default values for fields to merge into the document. The values will be presented to the signers for editable fields; for read-only fields the provided values will not be editable during the signing process. Merging data into fields is currently not supported when used with libraryDocumentId or libraryDocumentName. Only file and url are currently supported.</param>
/// <param name="Message">An optional message to the participants, describing what is being sent or why their signature is required.</param>
/// <param name="Name">The name of the agreement that will be used to identify it, in emails, website and other places.</param>
/// <param name="ParticipantSetsInfo">A list of one or more participant set. A participant set may have one or more participant. If any member of the participant set takes the action that has been assigned to the set(Sign/Approve/Acknowledge etc ), the action is considered as the action taken by whole participation set. For regular (non-MegaSign) documents, there is no limit on the number of electronic signatures in a single document. Written signatures are limited to four per document.</param>
/// <param name="PostSignOption">URL and associated properties for the success page the user will be taken to after completing the signing process. Should not be provided in offline agreement creation..</param>
/// <param name="ReminderFrequency">Optional parameter that sets how often you want to send reminders to the participants. If it is not specified, the default frequency set for the account will be used. Should not be provided in offline agreement creation. If provided in PUT as a different value than the current one, an error will be thrown..</param>
/// <param name="SecurityOption">Optional secondary security parameters for the agreement. Should not be provided in offline agreement creation..</param>
/// <param name="SenderEmail">Email of agreement sender. Only provided in GET. Can not be provided in POST/PUT request. If provided in POST/PUT, it will be ignored.</param>
/// <param name="SignatureType">Specifies the type of signature you would like to request - written or e-signature. The possible values are <br> ESIGN : Agreement needs to be signed electronically <br>, WRITTEN : Agreement will be signed using handwritten signature and signed document will be uploaded into the system.</param>
/// <param name="State">The state in which the agreement should land. The state field can only be provided in POST calls, will never get returned in GET /agreements/{ID} and will be ignored if provided in PUT /agreements/{ID} call. The eventual status of the agreement can be obtained from GET /agreements/ID.</param>
/// <param name="Status">This is a server generated attribute which provides the detailed status of an agreement..</param>
/// <param name="VaultingInfo">Vaulting properties that allows Adobe Sign to securely store documents with a vault provider.</param>
/// <param name="WorkflowId">The identifier of custom workflow which defines the routing path of an agreement. Should not be provided in offline agreement creation..</param>
public AgreementCreationInfo(List<AgreementCcInfo> Ccs = default(List<AgreementCcInfo>), DateTime? CreatedDate = default(DateTime?), OfflineDeviceInfo DeviceInfo = default(OfflineDeviceInfo), bool? DocumentVisibilityEnabled = default(bool?), EmailOption EmailOption = default(EmailOption), DateTime? ExpirationTime = default(DateTime?), ExternalId ExternalId = default(ExternalId), List<FileInfo> FileInfos = default(List<FileInfo>), int? FirstReminderDelay = default(int?), List<FileInfo> FormFieldLayerTemplates = default(List<FileInfo>), string Id = default(string), string Locale = default(string), List<MergefieldInfo> MergeFieldInfo = default(List<MergefieldInfo>), string Message = default(string), string Name = default(string), List<ParticipantSetInfo> ParticipantSetsInfo = default(List<ParticipantSetInfo>), PostSignOption PostSignOption = default(PostSignOption), ReminderFrequencyEnum? ReminderFrequency = default(ReminderFrequencyEnum?), SecurityOption SecurityOption = default(SecurityOption), string SenderEmail = default(string), SignatureTypeEnum? SignatureType = default(SignatureTypeEnum?), StateEnum? State = default(StateEnum?), StatusEnum? Status = default(StatusEnum?), VaultingInfo VaultingInfo = default(VaultingInfo), string WorkflowId = default(string))
{
this.Ccs = Ccs;
this.CreatedDate = CreatedDate;
this.DeviceInfo = DeviceInfo;
this.DocumentVisibilityEnabled = DocumentVisibilityEnabled;
this.EmailOption = EmailOption;
this.ExpirationTime = ExpirationTime;
this.ExternalId = ExternalId;
this.FileInfos = FileInfos;
this.FirstReminderDelay = FirstReminderDelay;
this.FormFieldLayerTemplates = FormFieldLayerTemplates;
this.Id = Id;
this.Locale = Locale;
this.MergeFieldInfo = MergeFieldInfo;
this.Message = Message;
this.Name = Name;
this.ParticipantSetsInfo = ParticipantSetsInfo;
this.PostSignOption = PostSignOption;
this.ReminderFrequency = ReminderFrequency;
this.SecurityOption = SecurityOption;
this.SenderEmail = SenderEmail;
this.SignatureType = SignatureType;
this.State = State;
this.Status = Status;
this.VaultingInfo = VaultingInfo;
this.WorkflowId = WorkflowId;
}
/// <summary>
/// A list of one or more CCs that will be copied in the agreement transaction. The CCs will each receive an email at the beginning of the transaction and also when the final document is signed. The email addresses will also receive a copy of the document, attached as a PDF file. Should not be provided in offline agreement creation.
/// </summary>
/// <value>A list of one or more CCs that will be copied in the agreement transaction. The CCs will each receive an email at the beginning of the transaction and also when the final document is signed. The email addresses will also receive a copy of the document, attached as a PDF file. Should not be provided in offline agreement creation.</value>
[DataMember(Name="ccs", EmitDefaultValue=false)]
public List<AgreementCcInfo> Ccs { get; set; }
/// <summary>
/// Date when agreement was created. This is a server generated attributed and can not be provided in POST/PUT calls. Format would be yyyy-MM-dd'T'HH:mm:ssZ. For example, e.g 2016-02-25T18:46:19Z represents UTC time
/// </summary>
/// <value>Date when agreement was created. This is a server generated attributed and can not be provided in POST/PUT calls. Format would be yyyy-MM-dd'T'HH:mm:ssZ. For example, e.g 2016-02-25T18:46:19Z represents UTC time</value>
[DataMember(Name="createdDate", EmitDefaultValue=false)]
[JsonConverter(typeof(SwaggerDateConverter))]
public DateTime? CreatedDate { get; set; }
/// <summary>
/// Device info of the offline device. It should only be provided in case of offline agreement creation.
/// </summary>
/// <value>Device info of the offline device. It should only be provided in case of offline agreement creation.</value>
[DataMember(Name="deviceInfo", EmitDefaultValue=false)]
public OfflineDeviceInfo DeviceInfo { get; set; }
/// <summary>
/// If set to true, enable limited document visibility. Should not be provided in offline agreement creation.
/// </summary>
/// <value>If set to true, enable limited document visibility. Should not be provided in offline agreement creation.</value>
[DataMember(Name="documentVisibilityEnabled", EmitDefaultValue=false)]
public bool? DocumentVisibilityEnabled { get; set; }
/// <summary>
/// Email configurations for the agreement. Should not be provided in offline agreement creation or when updating a non draft agreement.
/// </summary>
/// <value>Email configurations for the agreement. Should not be provided in offline agreement creation or when updating a non draft agreement.</value>
[DataMember(Name="emailOption", EmitDefaultValue=false)]
public EmailOption EmailOption { get; set; }
/// <summary>
/// Time after which Agreement expires and needs to be signed before it. Format should be yyyy-MM-dd'T'HH:mm:ssZ. For example, e.g 2016-02-25T18:46:19Z represents UTC time. Should not be provided in offline agreement creation.
/// </summary>
/// <value>Time after which Agreement expires and needs to be signed before it. Format should be yyyy-MM-dd'T'HH:mm:ssZ. For example, e.g 2016-02-25T18:46:19Z represents UTC time. Should not be provided in offline agreement creation.</value>
[DataMember(Name="expirationTime", EmitDefaultValue=false)]
[JsonConverter(typeof(SwaggerDateConverter))]
public DateTime? ExpirationTime { get; set; }
/// <summary>
/// An arbitrary value from your system, which can be specified at sending time and then later returned or queried. Should not be provided in offline agreement creation.
/// </summary>
/// <value>An arbitrary value from your system, which can be specified at sending time and then later returned or queried. Should not be provided in offline agreement creation.</value>
[DataMember(Name="externalId", EmitDefaultValue=false)]
public ExternalId ExternalId { get; set; }
/// <summary>
/// A list of one or more files (or references to files) that will be sent out for signature. If more than one file is provided, they will be combined into one PDF before being sent out. Note: Only one of the four parameters in every FileInfo object must be specified
/// </summary>
/// <value>A list of one or more files (or references to files) that will be sent out for signature. If more than one file is provided, they will be combined into one PDF before being sent out. Note: Only one of the four parameters in every FileInfo object must be specified</value>
[DataMember(Name="fileInfos", EmitDefaultValue=false)]
public List<FileInfo> FileInfos { get; set; }
/// <summary>
/// Integer which specifies the delay in hours before sending the first reminder.<br>This is an optional field. The minimum value allowed is 1 hour and the maximum value can’t be more than the difference of agreement creation and expiry time of the agreement in hours.<br>If this is not specified but the reminder frequency is specified, then the first reminder will be sent based on frequency.<br>i.e. if the reminder is created with frequency specified as daily, the firstReminderDelay will be 24 hours. Should not be provided in offline agreement creation.
/// </summary>
/// <value>Integer which specifies the delay in hours before sending the first reminder.<br>This is an optional field. The minimum value allowed is 1 hour and the maximum value can’t be more than the difference of agreement creation and expiry time of the agreement in hours.<br>If this is not specified but the reminder frequency is specified, then the first reminder will be sent based on frequency.<br>i.e. if the reminder is created with frequency specified as daily, the firstReminderDelay will be 24 hours. Should not be provided in offline agreement creation.</value>
[DataMember(Name="firstReminderDelay", EmitDefaultValue=false)]
public int? FirstReminderDelay { get; set; }
/// <summary>
/// Specifies the form field layer template or source of form fields to apply on the files in this transaction. If specified, the FileInfo for this parameter must refer to a form field layer template via libraryDocumentId or libraryDocumentName, or if specified via transientDocumentId or documentURL, it must be of a supported file type. Note: Only one of the four parameters in every FileInfo object must be specified
/// </summary>
/// <value>Specifies the form field layer template or source of form fields to apply on the files in this transaction. If specified, the FileInfo for this parameter must refer to a form field layer template via libraryDocumentId or libraryDocumentName, or if specified via transientDocumentId or documentURL, it must be of a supported file type. Note: Only one of the four parameters in every FileInfo object must be specified</value>
[DataMember(Name="formFieldLayerTemplates", EmitDefaultValue=false)]
public List<FileInfo> FormFieldLayerTemplates { get; set; }
/// <summary>
/// The unique identifier of the agreement.If provided in POST, it will simply be ignored
/// </summary>
/// <value>The unique identifier of the agreement.If provided in POST, it will simply be ignored</value>
[DataMember(Name="id", EmitDefaultValue=false)]
public string Id { get; set; }
/// <summary>
/// The locale associated with this agreement - specifies the language for the signing page and emails, for example en_US or fr_FR. If none specified, defaults to the language configured for the agreement sender
/// </summary>
/// <value>The locale associated with this agreement - specifies the language for the signing page and emails, for example en_US or fr_FR. If none specified, defaults to the language configured for the agreement sender</value>
[DataMember(Name="locale", EmitDefaultValue=false)]
public string Locale { get; set; }
/// <summary>
/// Optional default values for fields to merge into the document. The values will be presented to the signers for editable fields; for read-only fields the provided values will not be editable during the signing process. Merging data into fields is currently not supported when used with libraryDocumentId or libraryDocumentName. Only file and url are currently supported
/// </summary>
/// <value>Optional default values for fields to merge into the document. The values will be presented to the signers for editable fields; for read-only fields the provided values will not be editable during the signing process. Merging data into fields is currently not supported when used with libraryDocumentId or libraryDocumentName. Only file and url are currently supported</value>
[DataMember(Name="mergeFieldInfo", EmitDefaultValue=false)]
public List<MergefieldInfo> MergeFieldInfo { get; set; }
/// <summary>
/// An optional message to the participants, describing what is being sent or why their signature is required
/// </summary>
/// <value>An optional message to the participants, describing what is being sent or why their signature is required</value>
[DataMember(Name="message", EmitDefaultValue=false)]
public string Message { get; set; }
/// <summary>
/// The name of the agreement that will be used to identify it, in emails, website and other places
/// </summary>
/// <value>The name of the agreement that will be used to identify it, in emails, website and other places</value>
[DataMember(Name="name", EmitDefaultValue=false)]
public string Name { get; set; }
/// <summary>
/// A list of one or more participant set. A participant set may have one or more participant. If any member of the participant set takes the action that has been assigned to the set(Sign/Approve/Acknowledge etc ), the action is considered as the action taken by whole participation set. For regular (non-MegaSign) documents, there is no limit on the number of electronic signatures in a single document. Written signatures are limited to four per document
/// </summary>
/// <value>A list of one or more participant set. A participant set may have one or more participant. If any member of the participant set takes the action that has been assigned to the set(Sign/Approve/Acknowledge etc ), the action is considered as the action taken by whole participation set. For regular (non-MegaSign) documents, there is no limit on the number of electronic signatures in a single document. Written signatures are limited to four per document</value>
[DataMember(Name="participantSetsInfo", EmitDefaultValue=false)]
public List<ParticipantSetInfo> ParticipantSetsInfo { get; set; }
/// <summary>
/// URL and associated properties for the success page the user will be taken to after completing the signing process. Should not be provided in offline agreement creation.
/// </summary>
/// <value>URL and associated properties for the success page the user will be taken to after completing the signing process. Should not be provided in offline agreement creation.</value>
[DataMember(Name="postSignOption", EmitDefaultValue=false)]
public PostSignOption PostSignOption { get; set; }
/// <summary>
/// Optional secondary security parameters for the agreement. Should not be provided in offline agreement creation.
/// </summary>
/// <value>Optional secondary security parameters for the agreement. Should not be provided in offline agreement creation.</value>
[DataMember(Name="securityOption", EmitDefaultValue=false)]
public SecurityOption SecurityOption { get; set; }
/// <summary>
/// Email of agreement sender. Only provided in GET. Can not be provided in POST/PUT request. If provided in POST/PUT, it will be ignored
/// </summary>
/// <value>Email of agreement sender. Only provided in GET. Can not be provided in POST/PUT request. If provided in POST/PUT, it will be ignored</value>
[DataMember(Name="senderEmail", EmitDefaultValue=false)]
public string SenderEmail { get; set; }
/// <summary>
/// Vaulting properties that allows Adobe Sign to securely store documents with a vault provider
/// </summary>
/// <value>Vaulting properties that allows Adobe Sign to securely store documents with a vault provider</value>
[DataMember(Name="vaultingInfo", EmitDefaultValue=false)]
public VaultingInfo VaultingInfo { get; set; }
/// <summary>
/// The identifier of custom workflow which defines the routing path of an agreement. Should not be provided in offline agreement creation.
/// </summary>
/// <value>The identifier of custom workflow which defines the routing path of an agreement. Should not be provided in offline agreement creation.</value>
[DataMember(Name="workflowId", EmitDefaultValue=false)]
public string WorkflowId { get; set; }
/// <summary>
/// Returns the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("class AgreementCreationInfo {\n");
sb.Append(" Ccs: ").Append(Ccs).Append("\n");
sb.Append(" CreatedDate: ").Append(CreatedDate).Append("\n");
sb.Append(" DeviceInfo: ").Append(DeviceInfo).Append("\n");
sb.Append(" DocumentVisibilityEnabled: ").Append(DocumentVisibilityEnabled).Append("\n");
sb.Append(" EmailOption: ").Append(EmailOption).Append("\n");
sb.Append(" ExpirationTime: ").Append(ExpirationTime).Append("\n");
sb.Append(" ExternalId: ").Append(ExternalId).Append("\n");
sb.Append(" FileInfos: ").Append(FileInfos).Append("\n");
sb.Append(" FirstReminderDelay: ").Append(FirstReminderDelay).Append("\n");
sb.Append(" FormFieldLayerTemplates: ").Append(FormFieldLayerTemplates).Append("\n");
sb.Append(" Id: ").Append(Id).Append("\n");
sb.Append(" Locale: ").Append(Locale).Append("\n");
sb.Append(" MergeFieldInfo: ").Append(MergeFieldInfo).Append("\n");
sb.Append(" Message: ").Append(Message).Append("\n");
sb.Append(" Name: ").Append(Name).Append("\n");
sb.Append(" ParticipantSetsInfo: ").Append(ParticipantSetsInfo).Append("\n");
sb.Append(" PostSignOption: ").Append(PostSignOption).Append("\n");
sb.Append(" ReminderFrequency: ").Append(ReminderFrequency).Append("\n");
sb.Append(" SecurityOption: ").Append(SecurityOption).Append("\n");
sb.Append(" SenderEmail: ").Append(SenderEmail).Append("\n");
sb.Append(" SignatureType: ").Append(SignatureType).Append("\n");
sb.Append(" State: ").Append(State).Append("\n");
sb.Append(" Status: ").Append(Status).Append("\n");
sb.Append(" VaultingInfo: ").Append(VaultingInfo).Append("\n");
sb.Append(" WorkflowId: ").Append(WorkflowId).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public string ToJson()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="input">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object input)
{
return this.Equals(input as AgreementCreationInfo);
}
/// <summary>
/// Returns true if AgreementCreationInfo instances are equal
/// </summary>
/// <param name="input">Instance of AgreementCreationInfo to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(AgreementCreationInfo input)
{
if (input == null)
return false;
return
(
this.Ccs == input.Ccs ||
this.Ccs != null &&
this.Ccs.SequenceEqual(input.Ccs)
) &&
(
this.CreatedDate == input.CreatedDate ||
(this.CreatedDate != null &&
this.CreatedDate.Equals(input.CreatedDate))
) &&
(
this.DeviceInfo == input.DeviceInfo ||
(this.DeviceInfo != null &&
this.DeviceInfo.Equals(input.DeviceInfo))
) &&
(
this.DocumentVisibilityEnabled == input.DocumentVisibilityEnabled ||
(this.DocumentVisibilityEnabled != null &&
this.DocumentVisibilityEnabled.Equals(input.DocumentVisibilityEnabled))
) &&
(
this.EmailOption == input.EmailOption ||
(this.EmailOption != null &&
this.EmailOption.Equals(input.EmailOption))
) &&
(
this.ExpirationTime == input.ExpirationTime ||
(this.ExpirationTime != null &&
this.ExpirationTime.Equals(input.ExpirationTime))
) &&
(
this.ExternalId == input.ExternalId ||
(this.ExternalId != null &&
this.ExternalId.Equals(input.ExternalId))
) &&
(
this.FileInfos == input.FileInfos ||
this.FileInfos != null &&
this.FileInfos.SequenceEqual(input.FileInfos)
) &&
(
this.FirstReminderDelay == input.FirstReminderDelay ||
(this.FirstReminderDelay != null &&
this.FirstReminderDelay.Equals(input.FirstReminderDelay))
) &&
(
this.FormFieldLayerTemplates == input.FormFieldLayerTemplates ||
this.FormFieldLayerTemplates != null &&
this.FormFieldLayerTemplates.SequenceEqual(input.FormFieldLayerTemplates)
) &&
(
this.Id == input.Id ||
(this.Id != null &&
this.Id.Equals(input.Id))
) &&
(
this.Locale == input.Locale ||
(this.Locale != null &&
this.Locale.Equals(input.Locale))
) &&
(
this.MergeFieldInfo == input.MergeFieldInfo ||
this.MergeFieldInfo != null &&
this.MergeFieldInfo.SequenceEqual(input.MergeFieldInfo)
) &&
(
this.Message == input.Message ||
(this.Message != null &&
this.Message.Equals(input.Message))
) &&
(
this.Name == input.Name ||
(this.Name != null &&
this.Name.Equals(input.Name))
) &&
(
this.ParticipantSetsInfo == input.ParticipantSetsInfo ||
this.ParticipantSetsInfo != null &&
this.ParticipantSetsInfo.SequenceEqual(input.ParticipantSetsInfo)
) &&
(
this.PostSignOption == input.PostSignOption ||
(this.PostSignOption != null &&
this.PostSignOption.Equals(input.PostSignOption))
) &&
(
this.ReminderFrequency == input.ReminderFrequency ||
(this.ReminderFrequency != null &&
this.ReminderFrequency.Equals(input.ReminderFrequency))
) &&
(
this.SecurityOption == input.SecurityOption ||
(this.SecurityOption != null &&
this.SecurityOption.Equals(input.SecurityOption))
) &&
(
this.SenderEmail == input.SenderEmail ||
(this.SenderEmail != null &&
this.SenderEmail.Equals(input.SenderEmail))
) &&
(
this.SignatureType == input.SignatureType ||
(this.SignatureType != null &&
this.SignatureType.Equals(input.SignatureType))
) &&
(
this.State == input.State ||
(this.State != null &&
this.State.Equals(input.State))
) &&
(
this.Status == input.Status ||
(this.Status != null &&
this.Status.Equals(input.Status))
) &&
(
this.VaultingInfo == input.VaultingInfo ||
(this.VaultingInfo != null &&
this.VaultingInfo.Equals(input.VaultingInfo))
) &&
(
this.WorkflowId == input.WorkflowId ||
(this.WorkflowId != null &&
this.WorkflowId.Equals(input.WorkflowId))
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
unchecked // Overflow is fine, just wrap
{
int hashCode = 41;
if (this.Ccs != null)
hashCode = hashCode * 59 + this.Ccs.GetHashCode();
if (this.CreatedDate != null)
hashCode = hashCode * 59 + this.CreatedDate.GetHashCode();
if (this.DeviceInfo != null)
hashCode = hashCode * 59 + this.DeviceInfo.GetHashCode();
if (this.DocumentVisibilityEnabled != null)
hashCode = hashCode * 59 + this.DocumentVisibilityEnabled.GetHashCode();
if (this.EmailOption != null)
hashCode = hashCode * 59 + this.EmailOption.GetHashCode();
if (this.ExpirationTime != null)
hashCode = hashCode * 59 + this.ExpirationTime.GetHashCode();
if (this.ExternalId != null)
hashCode = hashCode * 59 + this.ExternalId.GetHashCode();
if (this.FileInfos != null)
hashCode = hashCode * 59 + this.FileInfos.GetHashCode();
if (this.FirstReminderDelay != null)
hashCode = hashCode * 59 + this.FirstReminderDelay.GetHashCode();
if (this.FormFieldLayerTemplates != null)
hashCode = hashCode * 59 + this.FormFieldLayerTemplates.GetHashCode();
if (this.Id != null)
hashCode = hashCode * 59 + this.Id.GetHashCode();
if (this.Locale != null)
hashCode = hashCode * 59 + this.Locale.GetHashCode();
if (this.MergeFieldInfo != null)
hashCode = hashCode * 59 + this.MergeFieldInfo.GetHashCode();
if (this.Message != null)
hashCode = hashCode * 59 + this.Message.GetHashCode();
if (this.Name != null)
hashCode = hashCode * 59 + this.Name.GetHashCode();
if (this.ParticipantSetsInfo != null)
hashCode = hashCode * 59 + this.ParticipantSetsInfo.GetHashCode();
if (this.PostSignOption != null)
hashCode = hashCode * 59 + this.PostSignOption.GetHashCode();
if (this.ReminderFrequency != null)
hashCode = hashCode * 59 + this.ReminderFrequency.GetHashCode();
if (this.SecurityOption != null)
hashCode = hashCode * 59 + this.SecurityOption.GetHashCode();
if (this.SenderEmail != null)
hashCode = hashCode * 59 + this.SenderEmail.GetHashCode();
if (this.SignatureType != null)
hashCode = hashCode * 59 + this.SignatureType.GetHashCode();
if (this.State != null)
hashCode = hashCode * 59 + this.State.GetHashCode();
if (this.Status != null)
hashCode = hashCode * 59 + this.Status.GetHashCode();
if (this.VaultingInfo != null)
hashCode = hashCode * 59 + this.VaultingInfo.GetHashCode();
if (this.WorkflowId != null)
hashCode = hashCode * 59 + this.WorkflowId.GetHashCode();
return hashCode;
}
}
/// <summary>
/// To validate all properties of the instance
/// </summary>
/// <param name="validationContext">Validation context</param>
/// <returns>Validation Result</returns>
IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> IValidatableObject.Validate(ValidationContext validationContext)
{
yield break;
}
}
}
| 63.344114 | 1,289 | 0.628122 | [
"Apache-2.0"
] | gabon/AdobeSignCSharpSDK | src/AdobeSign.Rest/Model.Agreements/AgreementCreationInfo.cs | 48,971 | C# |
using System;
using System.ComponentModel.DataAnnotations.Schema;
namespace AppGM.Core
{
/// <summary>
/// Representa el clima actual en un rol.
/// </summary>
public class ModeloClimaHorario : ModeloBase
{
/// <summary>
/// Tipo de clima general en un rol.
/// </summary>
public EClima Clima { get; set; }
/// <summary>
/// Clase de viento general en un rol.
/// </summary>
public EViento Viento { get; set; }
/// <summary>
/// Valor estimativo de la temperatura general en un rol.
/// </summary>
public ETemperatura Temperatura { get; set; }
/// <summary>
/// Valor estimativo de la humedad general en un rol.
/// </summary>
public EHumedad Humedad { get; set; }
/// <summary>
/// Dia de la semana en la que se encuentra un rol.
/// </summary>
public EDiaSemana DiaSemana { get; set; }
/// <summary>
/// Hora del rol.
/// </summary>
public int Hora { get; set; }
/// <summary>
/// Minuto del rol.
/// </summary>
public int Minuto { get; set; }
/// <summary>
/// Clave foranea que referencia al <see cref="ModeloRol"/> al que pertenece este clima-horario
/// </summary>
[ForeignKey(nameof(RolAlQuePertenece))]
public int? IdRol { get; set; }
/// <summary>
/// Rol al que pertenece este clima-horario
/// </summary>
public virtual ModeloRol RolAlQuePertenece { get; set; }
}
}
| 27.844828 | 103 | 0.534365 | [
"Unlicense"
] | ElGranNachito/AplicacionGM | AppGM/AppGMCore/Modelos/Datos/Juego/ModeloClimaHorario.cs | 1,617 | C# |
#region
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.Owin.Infrastructure;
using Microsoft.Owin.Logging;
using Microsoft.Owin.Security;
using Microsoft.Owin.Security.Infrastructure;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Microsoft.Owin;
using System.Net.Http.Headers;
#endregion
namespace Owin.Security.Providers.Podbean
{
public class PodbeanAuthenticationHandler : AuthenticationHandler<PodbeanAuthenticationOptions>
{
private const string XmlSchemaString = "http://www.w3.org/2001/XMLSchema#string";
private const string TokenEndpoint = "https://api.podbean.com/v1/oauth/token";
private const string PodcastIdEndpoint = "https://api.podbean.com/v1/oauth/debugToken";
private const string PodcastEndpoint = "https://api.podbean.com/v1/podcast";
private readonly HttpClient _httpClient;
private readonly ILogger _logger;
public PodbeanAuthenticationHandler(HttpClient httpClient, ILogger logger)
{
_httpClient = httpClient;
_logger = logger;
}
protected override async Task<AuthenticationTicket> AuthenticateCoreAsync()
{
AuthenticationProperties properties = null;
try
{
string code = null;
string state = null;
var query = Request.Query;
var values = query.GetValues("code");
if (values != null && values.Count == 1)
code = values[0];
values = query.GetValues("state");
if (values != null && values.Count == 1)
state = values[0];
properties = Options.StateDataFormat.Unprotect(state);
if (properties == null)
return null;
// OAuth2 10.12 CSRF
if (!ValidateCorrelationId(properties, _logger))
return new AuthenticationTicket(null, properties);
var requestPrefix = GetBaseUri(Request);
var redirectUri = requestPrefix + Request.PathBase + Options.CallbackPath;
// Build up the body for the token request
var body = new List<KeyValuePair<string, string>>
{
new KeyValuePair<string, string>("grant_type", "authorization_code"),
new KeyValuePair<string, string>("code", code),
new KeyValuePair<string, string>("redirect_uri", redirectUri)
};
// Request the token
var tokenRequest = new HttpRequestMessage(HttpMethod.Post, TokenEndpoint);
tokenRequest.Headers.Authorization =
new AuthenticationHeaderValue("Basic", Base64Encode($"{Options.AppId}:{Options.AppSecret}"));
tokenRequest.Content = new FormUrlEncodedContent(body);
var tokenResponse = await _httpClient.SendAsync(tokenRequest, Request.CallCancelled);
tokenResponse.EnsureSuccessStatusCode();
var text = await tokenResponse.Content.ReadAsStringAsync();
// Deserializes the token response
dynamic token = JsonConvert.DeserializeObject<dynamic>(text);
var accessToken = (string)token.access_token;
var refreshToken = (string)token.refresh_token;
var expires = (string)token.expires_in;
// Get the Podbean podcast
var podcastResponse = await _httpClient.GetAsync(
$"{PodcastEndpoint}?access_token={Uri.EscapeDataString(accessToken)}", Request.CallCancelled);
podcastResponse.EnsureSuccessStatusCode();
text = await podcastResponse.Content.ReadAsStringAsync();
var podcast = JObject.Parse(text)["podcast"].ToObject<Podcast>();
// Get the Podbean podcast id
var podcastIdRequest = new HttpRequestMessage(HttpMethod.Get, $"{PodcastIdEndpoint}?access_token={Uri.EscapeDataString(accessToken)}");
podcastIdRequest.Headers.Authorization =
new AuthenticationHeaderValue("Basic", Base64Encode($"{Options.AppId}:{Options.AppSecret}"));
var podcastIdResponse = await _httpClient.SendAsync(podcastIdRequest, Request.CallCancelled);
podcastIdResponse.EnsureSuccessStatusCode();
text = await podcastIdResponse.Content.ReadAsStringAsync();
var podcastId = JsonConvert.DeserializeObject<dynamic>(text);
podcast.Id = (string)podcastId.podcast_id;
var context = new PodbeanAuthenticatedContext(Context, podcast, accessToken, refreshToken, expires)
{
Identity = new ClaimsIdentity(
Options.AuthenticationType,
ClaimsIdentity.DefaultNameClaimType,
ClaimsIdentity.DefaultRoleClaimType)
};
if (!string.IsNullOrEmpty(context.Id))
context.Identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, context.Id, XmlSchemaString,
Options.AuthenticationType));
if (!string.IsNullOrEmpty(context.Name))
context.Identity.AddClaim(new Claim(ClaimsIdentity.DefaultNameClaimType, context.Name,
XmlSchemaString, Options.AuthenticationType));
context.Properties = properties;
await Options.Provider.Authenticated(context);
return new AuthenticationTicket(context.Identity, context.Properties);
}
catch (Exception ex)
{
_logger.WriteError(ex.Message);
}
return new AuthenticationTicket(null, properties);
}
protected override Task ApplyResponseChallengeAsync()
{
if (Response.StatusCode != 401)
return Task.FromResult<object>(null);
var challenge = Helper.LookupChallenge(Options.AuthenticationType, Options.AuthenticationMode);
if (challenge == null) return Task.FromResult<object>(null);
var baseUri = GetBaseUri(Request);
var currentUri =
baseUri +
Request.Path +
Request.QueryString;
var redirectUri =
baseUri +
Options.CallbackPath;
var properties = challenge.Properties;
if (string.IsNullOrEmpty(properties.RedirectUri))
properties.RedirectUri = currentUri;
// OAuth2 10.12 CSRF
GenerateCorrelationId(properties);
var state = Options.StateDataFormat.Protect(properties);
var scope = string.Join(" ", Options.Scope);
var authorizationEndpoint =
"https://api.podbean.com/v1/dialog/oauth" +
"?response_type=code" +
"&client_id=" + Uri.EscapeDataString(Options.AppId) +
"&redirect_uri=" + Uri.EscapeDataString(redirectUri) +
"&scope=" + Uri.EscapeDataString(scope) +
"&state=" + Uri.EscapeDataString(state);
Response.Redirect(authorizationEndpoint);
return Task.FromResult<object>(null);
}
public override async Task<bool> InvokeAsync()
{
return await InvokeReplyPathAsync();
}
private async Task<bool> InvokeReplyPathAsync()
{
if (!Options.CallbackPath.HasValue || Options.CallbackPath != Request.Path) return false;
// TODO: error responses
var ticket = await AuthenticateAsync();
if (ticket == null)
{
_logger.WriteWarning("Invalid return state, unable to redirect.");
Response.StatusCode = 500;
return true;
}
var context = new PodbeanReturnEndpointContext(Context, ticket)
{
SignInAsAuthenticationType = Options.SignInAsAuthenticationType,
RedirectUri = ticket.Properties.RedirectUri
};
await Options.Provider.ReturnEndpoint(context);
if (context.SignInAsAuthenticationType != null &&
context.Identity != null)
{
var grantIdentity = context.Identity;
if (!string.Equals(grantIdentity.AuthenticationType, context.SignInAsAuthenticationType,
StringComparison.Ordinal))
grantIdentity = new ClaimsIdentity(grantIdentity.Claims, context.SignInAsAuthenticationType,
grantIdentity.NameClaimType, grantIdentity.RoleClaimType);
Context.Authentication.SignIn(context.Properties, grantIdentity);
}
if (context.IsRequestCompleted || context.RedirectUri == null) return context.IsRequestCompleted;
var redirectUri = context.RedirectUri;
if (context.Identity == null)
redirectUri = WebUtilities.AddQueryString(redirectUri, "error", "access_denied");
Response.Redirect(redirectUri);
context.RequestCompleted();
return context.IsRequestCompleted;
}
private static string Base64Encode(string plainText)
{
var plainTextBytes = System.Text.Encoding.UTF8.GetBytes(plainText);
return System.Convert.ToBase64String(plainTextBytes);
}
private string GetBaseUri(IOwinRequest request)
{
if (Options.DebugUsingRequestHeadersToBuildBaseUri &&
request.Headers["X-Original-Host"] != null &&
request.Headers["X-Forwarded-Proto"] != null)
{
return request.Headers["X-Forwarded-Proto"] + Uri.SchemeDelimiter + request.Headers["X-Original-Host"];
}
var baseUri =
request.Scheme +
Uri.SchemeDelimiter +
request.Host +
request.PathBase;
return baseUri;
}
}
} | 33.99187 | 139 | 0.737025 | [
"MIT"
] | AliEbadi/OwinOAuthProviders | src/Owin.Security.Providers.Podbean/PodbeanAuthenticationHandler.cs | 8,364 | C# |
using System.Threading.Tasks;
using MediatR;
using Microsoft.AspNetCore.Mvc;
using NerdStore.Core.Messages.CommonMessages.Notifications;
namespace NerdStore.WebApp.MVC.Extensions
{
public class SummaryViewComponent : ViewComponent
{
private readonly DomainNotificationHandler _notifications;
public SummaryViewComponent(INotificationHandler<DomainNotification> notifications)
{
_notifications = (DomainNotificationHandler)notifications;
}
public async Task<IViewComponentResult> InvokeAsync()
{
var notificacoes = await Task.FromResult(_notifications.ObterNotificacoes());
notificacoes.ForEach(c => ViewData.ModelState.AddModelError(string.Empty, c.Value));
return View();
}
}
} | 31.96 | 96 | 0.713392 | [
"MIT"
] | MatheusNCarvalho/Curso-Teste-De-Software | 03 - Testes de Integracao/src/NerdStore.WebApp.MVC/Extensions/SummaryViewComponent.cs | 801 | C# |
using System;
using System.IO;
using DjvuNet.Compression;
using DjvuNet.Graphics;
using DjvuNet.Interfaces;
namespace DjvuNet.Wavelet
{
/// <summary> This class represents structured wavelette data.</summary>
public class IWPixelMap : ICodec
{
#region Private Variables
private IWCodec _cbcodec;
private IWMap _cbmap;
private int _cbytes;
private bool _crcbHalf;
private IWCodec _crcodec;
private IWMap _crmap;
private int _cserial;
private int _cslice;
private IWCodec _ycodec;
private IWMap _ymap;
#endregion Private Variables
#region Public Properties
#region CrcbDelay
private int _crcbDelay = 10;
/// <summary>
/// Gets or sets the crcb delay
/// </summary>
public int CrcbDelay
{
get { return _crcbDelay; }
set
{
if (CrcbDelay != value)
{
if (value >= 0)
{
_crcbDelay = value;
}
}
}
}
#endregion CrcbDelay
//public const int CRCBfull = 5;
//public const int CRCBhalf = 3;
//public const int CRCBMode = 1;
//public const int CRCBnone = 2;
//public const int CRCBnormal = 4;
//public static readonly float[][] RgbToYcc = new[]
// {
// new[] {0.304348F, 0.608696F, 0.086956F},
// new[] {0.463768F, -0.405797F, -0.057971F},
// new[] {-0.173913F, -0.347826F, 0.521739F}
// };
#region Height
/// <summary>
/// Gets the height of the pixel map
/// </summary>
public int Height
{
get { return (_ymap != null) ? _ymap.Ih : 0; }
}
#endregion Height
#region Width
/// <summary>
/// Gets the width of the pixel map
/// </summary>
public int Width
{
get { return (_ymap != null) ? _ymap.Iw : 0; }
}
#endregion Width
#region ImageData
/// <summary>
/// True if the item contains image data, false otherwise
/// </summary>
public bool ImageData
{
get { return true; }
}
#endregion ImageData
#endregion Public Properties
#region Constructors
#endregion Constructors
#region Public Methods
public virtual void Decode(BinaryReader bs)
{
if (_ycodec == null)
{
_cslice = _cserial = 0;
_ymap = null;
}
byte serial = bs.ReadByte();
if (serial != _cserial)
{
throw new IOException("Chunk does not bear expected serial number");
}
int nslices = _cslice + bs.ReadByte();
if (_cserial == 0)
{
int major = bs.ReadByte();
int minor = bs.ReadByte();
if ((major & 0x7f) != 1)
{
throw new IOException("File has been compressed with an incompatible Codec");
}
if (minor > 2)
{
throw new IOException("File has been compressed with a more recent Codec");
}
int header3size = 5;
if (minor < 2)
{
header3size = 4;
}
int w = (bs.ReadByte() << 8);
w |= bs.ReadByte();
int h = (bs.ReadByte() << 8);
h |= bs.ReadByte();
CrcbDelay = 0;
_crcbHalf = false;
int b = bs.ReadByte();
if (minor >= 2)
{
CrcbDelay = 0x7f & b;
}
if (minor >= 2)
{
_crcbHalf = ((0x80 & b) == 0);
}
if ((major & 0x80) != 0)
{
CrcbDelay = -1;
}
_ymap = new IWMap().Init(w, h);
_ycodec = new IWCodec().Init(_ymap);
if (CrcbDelay >= 0)
{
_cbmap = new IWMap().Init(w, h);
_crmap = new IWMap().Init(w, h);
_cbcodec = new IWCodec().Init(_cbmap);
_crcodec = new IWCodec().Init(_crmap);
}
}
ZPCodec zp = new ZPCodec().Init(bs.BaseStream);
for (int flag = 1; (flag != 0) && (_cslice < nslices); _cslice++)
{
flag = _ycodec.CodeSlice(zp);
if ((_crcodec != null) && (_cbcodec != null) && (CrcbDelay <= _cslice))
{
flag |= _cbcodec.CodeSlice(zp);
flag |= _crcodec.CodeSlice(zp);
}
}
_cserial++;
// return nslices;
}
public virtual void CloseCodec()
{
_ycodec = _crcodec = _cbcodec = null;
_cslice = _cbytes = _cserial = 0;
GC.Collect();
}
public virtual Graphics.PixelMap GetPixmap()
{
if (_ymap == null)
{
return null;
}
int w = _ymap.Iw;
int h = _ymap.Ih;
int pixsep = 3;
int rowsep = w * pixsep;
sbyte[] bytes = new sbyte[h * rowsep];
_ymap.Image(0, bytes, rowsep, pixsep, false);
if ((_crmap != null) && (_cbmap != null) && (CrcbDelay >= 0))
{
_cbmap.Image(1, bytes, rowsep, pixsep, _crcbHalf);
_crmap.Image(2, bytes, rowsep, pixsep, _crcbHalf);
}
// Convert image to RGB
Graphics.PixelMap ppm = new Graphics.PixelMap().Init(bytes, h, w);
PixelReference pixel = ppm.CreateGPixelReference(0);
for (int i = 0; i < h; )
{
pixel.SetOffset(i++, 0);
if ((_crmap != null) && (_cbmap != null) && (CrcbDelay >= 0))
{
pixel.YCC_to_RGB(w);
}
else
{
for (int x = w; x-- > 0; pixel.IncOffset())
{
pixel.SetGray((sbyte)(127 - pixel.Blue));
}
}
}
return ppm;
}
public Graphics.PixelMap GetPixmap(int subsample)
{
return GetPixmap(subsample, new Rectangle(0, 0, Width / subsample, Height / subsample), null);
}
public virtual Graphics.PixelMap GetPixmap(int subsample, Rectangle rect, Graphics.PixelMap retval)
{
if (_ymap == null)
{
return null;
}
if (retval == null)
{
retval = new Graphics.PixelMap();
}
int w = rect.Width;
int h = rect.Height;
int pixsep = 3;
int rowsep = w * pixsep;
sbyte[] bytes = retval.Init(h, w, null).Data;
_ymap.Image(subsample, rect, 0, bytes, rowsep, pixsep, false);
if ((_crmap != null) && (_cbmap != null) && (CrcbDelay >= 0))
{
_cbmap.Image(subsample, rect, 1, bytes, rowsep, pixsep, _crcbHalf);
_crmap.Image(subsample, rect, 2, bytes, rowsep, pixsep, _crcbHalf);
}
PixelReference pixel = retval.CreateGPixelReference(0);
for (int i = 0; i < h; )
{
pixel.SetOffset(i++, 0);
if ((_crmap != null) && (_cbmap != null) && (CrcbDelay >= 0))
{
pixel.YCC_to_RGB(w);
}
else
{
for (int x = w; x-- > 0; pixel.IncOffset())
{
pixel.SetGray((sbyte)(127 - pixel.Blue));
}
}
}
return retval;
}
#endregion Public Methods
}
} | 27.483974 | 107 | 0.413761 | [
"MIT"
] | fel88/CommonLibs | DjvuNet/Wavelet/Original_IWPixelMap.cs | 8,575 | C# |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Options;
namespace Microsoft.AspNetCore.Authentication
{
/// <summary>
/// Implements <see cref="IAuthenticationSchemeProvider"/>.
/// </summary>
public class AuthenticationSchemeProvider : IAuthenticationSchemeProvider
{
/// <summary>
/// Creates an instance of <see cref="AuthenticationSchemeProvider"/>
/// using the specified <paramref name="options"/>,
/// </summary>
/// <param name="options">The <see cref="AuthenticationOptions"/> options.</param>
public AuthenticationSchemeProvider(IOptions<AuthenticationOptions> options)
: this(options, new Dictionary<string, AuthenticationScheme>(StringComparer.Ordinal))
{ }
/// <summary>
/// Creates an instance of <see cref="AuthenticationSchemeProvider"/>
/// using the specified <paramref name="options"/> and <paramref name="schemes"/>.
/// </summary>
/// <param name="options">The <see cref="AuthenticationOptions"/> options.</param>
/// <param name="schemes">The dictionary used to store authentication schemes.</param>
protected AuthenticationSchemeProvider(
IOptions<AuthenticationOptions> options,
IDictionary<string, AuthenticationScheme> schemes
)
{
_options = options.Value;
_schemes = schemes ?? throw new ArgumentNullException(nameof(schemes));
_requestHandlers = new List<AuthenticationScheme>();
foreach (var builder in _options.Schemes)
{
var scheme = builder.Build();
AddScheme(scheme);
}
}
private readonly AuthenticationOptions _options;
private readonly object _lock = new object();
private readonly IDictionary<string, AuthenticationScheme> _schemes;
private readonly List<AuthenticationScheme> _requestHandlers;
// Used as a safe return value for enumeration apis
private IEnumerable<AuthenticationScheme> _schemesCopy =
Array.Empty<AuthenticationScheme>();
private IEnumerable<AuthenticationScheme> _requestHandlersCopy =
Array.Empty<AuthenticationScheme>();
private Task<AuthenticationScheme?> GetDefaultSchemeAsync() =>
_options.DefaultScheme != null
? GetSchemeAsync(_options.DefaultScheme)
: Task.FromResult<AuthenticationScheme?>(null);
/// <summary>
/// Returns the scheme that will be used by default for <see cref="IAuthenticationService.AuthenticateAsync(HttpContext, string)"/>.
/// This is typically specified via <see cref="AuthenticationOptions.DefaultAuthenticateScheme"/>.
/// Otherwise, this will fallback to <see cref="AuthenticationOptions.DefaultScheme"/>.
/// </summary>
/// <returns>The scheme that will be used by default for <see cref="IAuthenticationService.AuthenticateAsync(HttpContext, string)"/>.</returns>
public virtual Task<AuthenticationScheme?> GetDefaultAuthenticateSchemeAsync() =>
_options.DefaultAuthenticateScheme != null
? GetSchemeAsync(_options.DefaultAuthenticateScheme)
: GetDefaultSchemeAsync();
/// <summary>
/// Returns the scheme that will be used by default for <see cref="IAuthenticationService.ChallengeAsync(HttpContext, string, AuthenticationProperties)"/>.
/// This is typically specified via <see cref="AuthenticationOptions.DefaultChallengeScheme"/>.
/// Otherwise, this will fallback to <see cref="AuthenticationOptions.DefaultScheme"/>.
/// </summary>
/// <returns>The scheme that will be used by default for <see cref="IAuthenticationService.ChallengeAsync(HttpContext, string, AuthenticationProperties)"/>.</returns>
public virtual Task<AuthenticationScheme?> GetDefaultChallengeSchemeAsync() =>
_options.DefaultChallengeScheme != null
? GetSchemeAsync(_options.DefaultChallengeScheme)
: GetDefaultSchemeAsync();
/// <summary>
/// Returns the scheme that will be used by default for <see cref="IAuthenticationService.ForbidAsync(HttpContext, string, AuthenticationProperties)"/>.
/// This is typically specified via <see cref="AuthenticationOptions.DefaultForbidScheme"/>.
/// Otherwise, this will fallback to <see cref="GetDefaultChallengeSchemeAsync"/> .
/// </summary>
/// <returns>The scheme that will be used by default for <see cref="IAuthenticationService.ForbidAsync(HttpContext, string, AuthenticationProperties)"/>.</returns>
public virtual Task<AuthenticationScheme?> GetDefaultForbidSchemeAsync() =>
_options.DefaultForbidScheme != null
? GetSchemeAsync(_options.DefaultForbidScheme)
: GetDefaultChallengeSchemeAsync();
/// <summary>
/// Returns the scheme that will be used by default for <see cref="IAuthenticationService.SignInAsync(HttpContext, string, System.Security.Claims.ClaimsPrincipal, AuthenticationProperties)"/>.
/// This is typically specified via <see cref="AuthenticationOptions.DefaultSignInScheme"/>.
/// Otherwise, this will fallback to <see cref="AuthenticationOptions.DefaultScheme"/>.
/// </summary>
/// <returns>The scheme that will be used by default for <see cref="IAuthenticationService.SignInAsync(HttpContext, string, System.Security.Claims.ClaimsPrincipal, AuthenticationProperties)"/>.</returns>
public virtual Task<AuthenticationScheme?> GetDefaultSignInSchemeAsync() =>
_options.DefaultSignInScheme != null
? GetSchemeAsync(_options.DefaultSignInScheme)
: GetDefaultSchemeAsync();
/// <summary>
/// Returns the scheme that will be used by default for <see cref="IAuthenticationService.SignOutAsync(HttpContext, string, AuthenticationProperties)"/>.
/// This is typically specified via <see cref="AuthenticationOptions.DefaultSignOutScheme"/>.
/// Otherwise this will fallback to <see cref="GetDefaultSignInSchemeAsync"/> if that supports sign out.
/// </summary>
/// <returns>The scheme that will be used by default for <see cref="IAuthenticationService.SignOutAsync(HttpContext, string, AuthenticationProperties)"/>.</returns>
public virtual Task<AuthenticationScheme?> GetDefaultSignOutSchemeAsync() =>
_options.DefaultSignOutScheme != null
? GetSchemeAsync(_options.DefaultSignOutScheme)
: GetDefaultSignInSchemeAsync();
/// <summary>
/// Returns the <see cref="AuthenticationScheme"/> matching the name, or null.
/// </summary>
/// <param name="name">The name of the authenticationScheme.</param>
/// <returns>The scheme or null if not found.</returns>
public virtual Task<AuthenticationScheme?> GetSchemeAsync(string name) =>
Task.FromResult(_schemes.ContainsKey(name) ? _schemes[name] : null);
/// <summary>
/// Returns the schemes in priority order for request handling.
/// </summary>
/// <returns>The schemes in priority order for request handling</returns>
public virtual Task<IEnumerable<AuthenticationScheme>> GetRequestHandlerSchemesAsync() =>
Task.FromResult(_requestHandlersCopy);
/// <summary>
/// Registers a scheme for use by <see cref="IAuthenticationService"/>.
/// </summary>
/// <param name="scheme">The scheme.</param>
/// <returns>true if the scheme was added successfully.</returns>
public virtual bool TryAddScheme(AuthenticationScheme scheme)
{
if (_schemes.ContainsKey(scheme.Name))
{
return false;
}
lock (_lock)
{
if (_schemes.ContainsKey(scheme.Name))
{
return false;
}
if (typeof(IAuthenticationRequestHandler).IsAssignableFrom(scheme.HandlerType))
{
_requestHandlers.Add(scheme);
_requestHandlersCopy = _requestHandlers.ToArray();
}
_schemes[scheme.Name] = scheme;
_schemesCopy = _schemes.Values.ToArray();
return true;
}
}
/// <summary>
/// Registers a scheme for use by <see cref="IAuthenticationService"/>.
/// </summary>
/// <param name="scheme">The scheme.</param>
public virtual void AddScheme(AuthenticationScheme scheme)
{
if (_schemes.ContainsKey(scheme.Name))
{
throw new InvalidOperationException("Scheme already exists: " + scheme.Name);
}
lock (_lock)
{
if (!TryAddScheme(scheme))
{
throw new InvalidOperationException("Scheme already exists: " + scheme.Name);
}
}
}
/// <summary>
/// Removes a scheme, preventing it from being used by <see cref="IAuthenticationService"/>.
/// </summary>
/// <param name="name">The name of the authenticationScheme being removed.</param>
public virtual void RemoveScheme(string name)
{
if (!_schemes.ContainsKey(name))
{
return;
}
lock (_lock)
{
if (_schemes.ContainsKey(name))
{
var scheme = _schemes[name];
if (_requestHandlers.Remove(scheme))
{
_requestHandlersCopy = _requestHandlers.ToArray();
}
_schemes.Remove(name);
_schemesCopy = _schemes.Values.ToArray();
}
}
}
/// <inheritdoc />
public virtual Task<IEnumerable<AuthenticationScheme>> GetAllSchemesAsync() =>
Task.FromResult(_schemesCopy);
}
}
| 48.990654 | 211 | 0.631629 | [
"Apache-2.0"
] | belav/aspnetcore | src/Http/Authentication.Core/src/AuthenticationSchemeProvider.cs | 10,484 | C# |
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="Computing.cs" company="Naos Project">
// Copyright (c) Naos Project 2019. All rights reserved.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace Naos.Deployment.Console
{
using System.Collections.Generic;
/// <summary>
/// Utility class to help with mapping to cloud resources.
/// </summary>
public static class Computing
{
/// <summary>
/// Map of <see cref="string" /> to <see cref="ComputingProviderDetails" />.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Is not mutable.")]
public static readonly IReadOnlyDictionary<string, ComputingProviderDetails> Details =
new Dictionary<string, ComputingProviderDetails>
{
{
"production-1",
new ComputingProviderDetails
{
SecondCidrComponent = "31",
LocationName = "us-east-2",
LocationAbbreviation = "use2",
ContainerLocationName = "us-east-2a",
ContainerLocationAbbreviation = "az1-use2",
}
},
{
"production-2",
new ComputingProviderDetails
{
SecondCidrComponent = "32",
LocationName = "us-west-2",
LocationAbbreviation = "usw2",
ContainerLocationName = "us-west-2b",
ContainerLocationAbbreviation = "az2-usw2",
}
},
};
}
/// <summary>
/// Details about cloud.
/// </summary>
public class ComputingProviderDetails
{
/// <summary>
/// Gets or sets the second component of the CIDR (i.e. 10.XX.0.0/16).
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Cidr", Justification = "Spelling/name is correct.")]
public string SecondCidrComponent { get; set; }
/// <summary>
/// Gets or sets the location of resources (i.e. us-east-1).
/// </summary>
public string LocationName { get; set; }
/// <summary>
/// Gets or sets the abbreviation of the location for naming (i.e. use1).
/// </summary>
public string LocationAbbreviation { get; set; }
/// <summary>
/// Gets or sets the container to store resources in (i.e. us-east-1a).
/// </summary>
public string ContainerLocationName { get; set; }
/// <summary>
/// Gets or sets the abbreviation of the container (i.e. az1-use1).
/// </summary>
public string ContainerLocationAbbreviation { get; set; }
}
}
| 41.925 | 188 | 0.47734 | [
"MIT"
] | NaosFramework/Naos.Deployment | Naos.Deployment.Console/EnvironmentConfiguration/Computing.cs | 3,356 | C# |
using NBitcoin.Crypto;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace NBitcoin.BitcoinCore
{
/** Undo information for a CTxIn
*
* Contains the prevout's CTxOut being spent, and if this was the
* last output of the affected transaction, its metadata as well
* (coinbase or not, height, transaction version)
*/
public class TxInUndo : IBitcoinSerializable
{
public TxInUndo()
{
}
public TxInUndo(NBitcoin.TxOut txOut)
{
this.TxOut = txOut;
}
TxOut txout; // the txout data before being spent
public TxOut TxOut
{
get
{
return txout;
}
set
{
txout = value;
}
}
bool fCoinBase; // if the outpoint was the last unspent: whether it belonged to a coinbase
public bool CoinBase
{
get
{
return fCoinBase;
}
set
{
fCoinBase = value;
}
}
uint nHeight; // if the outpoint was the last unspent: its height
public uint Height
{
get
{
return nHeight;
}
set
{
nHeight = value;
}
}
uint nVersion; // if the outpoint was the last unspent: its version
public uint Version
{
get
{
return nVersion;
}
set
{
nVersion = value;
}
}
#region IBitcoinSerializable Members
public void ReadWrite(BitcoinStream stream)
{
if(stream.Serializing)
{
uint o = (uint)(nHeight * 2 + (fCoinBase ? 1 : 0));
stream.ReadWriteAsCompactVarInt(ref o);
if(nHeight > 0)
stream.ReadWriteAsCompactVarInt(ref nVersion);
TxOutCompressor compressor = new TxOutCompressor(txout);
stream.ReadWrite(ref compressor);
}
else
{
uint nCode = 0;
stream.ReadWriteAsCompactVarInt(ref nCode);
nHeight = nCode / 2;
fCoinBase = (nCode & 1) != 0;
if(nHeight > 0)
stream.ReadWriteAsCompactVarInt(ref nVersion);
TxOutCompressor compressor = new TxOutCompressor();
stream.ReadWrite(ref compressor);
txout = compressor.TxOut;
}
}
#endregion
}
public class TxUndo : IBitcoinSerializable
{
// undo information for all txins
List<TxInUndo> vprevout = new List<TxInUndo>();
public List<TxInUndo> Prevout
{
get
{
return vprevout;
}
}
#region IBitcoinSerializable Members
public void ReadWrite(BitcoinStream stream)
{
stream.ReadWrite(ref vprevout);
}
#endregion
}
public class BlockUndo : IBitcoinSerializable
{
List<TxUndo> vtxundo = new List<TxUndo>();
public List<TxUndo> TxUndo
{
get
{
return vtxundo;
}
}
#region IBitcoinSerializable Members
public void ReadWrite(BitcoinStream stream)
{
stream.ReadWrite(ref vtxundo);
}
#endregion
public uint256 CalculatedChecksum
{
get;
internal set;
}
public void ComputeChecksum(uint256 hashBlock)
{
MemoryStream ms = new MemoryStream();
hashBlock.AsBitcoinSerializable().ReadWrite(ms, true);
this.ReadWrite(ms, true);
CalculatedChecksum = Hashes.Hash256(ms.ToArray());
}
public uint256 BlockId
{
get;
set;
}
}
}
| 18.685714 | 99 | 0.622324 | [
"MIT"
] | knocte/NBitcoin | NBitcoin/BitcoinCore/BlockUndo.cs | 3,272 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.ComponentModel.Composition.Hosting;
using System.Linq;
using Microsoft.Practices.ServiceLocation;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Prism.Mef.Wpf.Tests
{
[TestClass]
public class MefServiceLocatorAdapterFixture
{
[TestMethod]
public void ShouldForwardResolveToInnerContainer()
{
object myInstance = new object();
CompositionContainer compositionContainer = new CompositionContainer();
compositionContainer.ComposeExportedValue<object>(myInstance);
IServiceLocator containerAdapter = new MefServiceLocatorAdapter(compositionContainer);
Assert.AreSame(myInstance, containerAdapter.GetInstance(typeof(object)));
}
[TestMethod]
public void ShouldForwardResolveToInnerContainerWhenKeyIsUsed()
{
object myInstance = new object();
CompositionContainer compositionContainer = new CompositionContainer();
compositionContainer.ComposeExportedValue<object>("key", myInstance);
IServiceLocator containerAdapter = new MefServiceLocatorAdapter(compositionContainer);
Assert.AreSame(myInstance, containerAdapter.GetInstance(typeof(object), "key"));
}
[TestMethod]
public void ShouldForwardResolveAllToInnerContainer()
{
object objectOne = new object();
object objectTwo = new object();
CompositionContainer compositionContainer = new CompositionContainer();
compositionContainer.ComposeExportedValue<object>(objectOne);
compositionContainer.ComposeExportedValue<object>(objectTwo);
IServiceLocator containerAdapter = new MefServiceLocatorAdapter(compositionContainer);
IList<object> returnedList = containerAdapter.GetAllInstances(typeof(object)).ToList();
Assert.AreSame(returnedList[0], objectOne);
Assert.AreSame(returnedList[1], objectTwo);
}
[TestMethod]
public void ShouldThrowActivationExceptionWhenMoreThanOneInstanceAvailble()
{
const int SEQUENCE_MORE_THAN_ONE_ELEMENT_HRESULT = -2146233079;
object myInstance = new object();
object myInstance2 = new object();
CompositionContainer compositionContainer = new CompositionContainer();
compositionContainer.ComposeExportedValue<object>(myInstance);
compositionContainer.ComposeExportedValue<object>(myInstance2);
IServiceLocator containerAdapter = new MefServiceLocatorAdapter(compositionContainer);
try
{
containerAdapter.GetInstance(typeof(object));
Assert.Fail("Expected exception not thrown.");
}
catch (ActivationException ex)
{
Assert.AreEqual(typeof(InvalidOperationException), ex.InnerException.GetType());
Assert.IsTrue(ex.InnerException.HResult == SEQUENCE_MORE_THAN_ONE_ELEMENT_HRESULT);
}
}
}
}
| 37.952381 | 99 | 0.683814 | [
"Apache-2.0"
] | aalice072/MVVMPrism | Source/Wpf/Prism.Mef.Wpf.Tests/MefServiceLocatorAdapterFixture.cs | 3,188 | C# |
/*
* Square Connect API
*
* Client library for accessing the Square Connect APIs
*
* OpenAPI spec version: 2.0
* Contact: developers@squareup.com
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*/
using NUnit.Framework;
using System;
using System.Linq;
using System.IO;
using System.Collections.Generic;
using Square.Connect.Api;
using Square.Connect.Model;
using Square.Connect.Client;
using System.Reflection;
namespace Square.Connect.Test
{
/// <summary>
/// Class for testing V1Order
/// </summary>
/// <remarks>
/// This file is automatically generated by Swagger Codegen.
/// Please update the test case below to test the model.
/// </remarks>
[TestFixture]
public class V1OrderTests
{
// TODO uncomment below to declare an instance variable for V1Order
//private V1Order instance;
/// <summary>
/// Setup before each test
/// </summary>
[SetUp]
public void Init()
{
// TODO uncomment below to create an instance of V1Order
//instance = new V1Order();
}
/// <summary>
/// Clean up after each test
/// </summary>
[TearDown]
public void Cleanup()
{
}
/// <summary>
/// Test an instance of V1Order
/// </summary>
[Test]
public void V1OrderInstanceTest()
{
// TODO uncomment below to test "IsInstanceOfType" V1Order
//Assert.IsInstanceOfType<V1Order> (instance, "variable 'instance' is a V1Order");
}
/// <summary>
/// Test the property 'Errors'
/// </summary>
[Test]
public void ErrorsTest()
{
// TODO unit test for the property 'Errors'
}
/// <summary>
/// Test the property 'Id'
/// </summary>
[Test]
public void IdTest()
{
// TODO unit test for the property 'Id'
}
/// <summary>
/// Test the property 'BuyerEmail'
/// </summary>
[Test]
public void BuyerEmailTest()
{
// TODO unit test for the property 'BuyerEmail'
}
/// <summary>
/// Test the property 'RecipientName'
/// </summary>
[Test]
public void RecipientNameTest()
{
// TODO unit test for the property 'RecipientName'
}
/// <summary>
/// Test the property 'RecipientPhoneNumber'
/// </summary>
[Test]
public void RecipientPhoneNumberTest()
{
// TODO unit test for the property 'RecipientPhoneNumber'
}
/// <summary>
/// Test the property 'State'
/// </summary>
[Test]
public void StateTest()
{
// TODO unit test for the property 'State'
}
/// <summary>
/// Test the property 'ShippingAddress'
/// </summary>
[Test]
public void ShippingAddressTest()
{
// TODO unit test for the property 'ShippingAddress'
}
/// <summary>
/// Test the property 'SubtotalMoney'
/// </summary>
[Test]
public void SubtotalMoneyTest()
{
// TODO unit test for the property 'SubtotalMoney'
}
/// <summary>
/// Test the property 'TotalShippingMoney'
/// </summary>
[Test]
public void TotalShippingMoneyTest()
{
// TODO unit test for the property 'TotalShippingMoney'
}
/// <summary>
/// Test the property 'TotalTaxMoney'
/// </summary>
[Test]
public void TotalTaxMoneyTest()
{
// TODO unit test for the property 'TotalTaxMoney'
}
/// <summary>
/// Test the property 'TotalPriceMoney'
/// </summary>
[Test]
public void TotalPriceMoneyTest()
{
// TODO unit test for the property 'TotalPriceMoney'
}
/// <summary>
/// Test the property 'TotalDiscountMoney'
/// </summary>
[Test]
public void TotalDiscountMoneyTest()
{
// TODO unit test for the property 'TotalDiscountMoney'
}
/// <summary>
/// Test the property 'CreatedAt'
/// </summary>
[Test]
public void CreatedAtTest()
{
// TODO unit test for the property 'CreatedAt'
}
/// <summary>
/// Test the property 'UpdatedAt'
/// </summary>
[Test]
public void UpdatedAtTest()
{
// TODO unit test for the property 'UpdatedAt'
}
/// <summary>
/// Test the property 'ExpiresAt'
/// </summary>
[Test]
public void ExpiresAtTest()
{
// TODO unit test for the property 'ExpiresAt'
}
/// <summary>
/// Test the property 'PaymentId'
/// </summary>
[Test]
public void PaymentIdTest()
{
// TODO unit test for the property 'PaymentId'
}
/// <summary>
/// Test the property 'BuyerNote'
/// </summary>
[Test]
public void BuyerNoteTest()
{
// TODO unit test for the property 'BuyerNote'
}
/// <summary>
/// Test the property 'CompletedNote'
/// </summary>
[Test]
public void CompletedNoteTest()
{
// TODO unit test for the property 'CompletedNote'
}
/// <summary>
/// Test the property 'RefundedNote'
/// </summary>
[Test]
public void RefundedNoteTest()
{
// TODO unit test for the property 'RefundedNote'
}
/// <summary>
/// Test the property 'CanceledNote'
/// </summary>
[Test]
public void CanceledNoteTest()
{
// TODO unit test for the property 'CanceledNote'
}
/// <summary>
/// Test the property 'Tender'
/// </summary>
[Test]
public void TenderTest()
{
// TODO unit test for the property 'Tender'
}
/// <summary>
/// Test the property 'OrderHistory'
/// </summary>
[Test]
public void OrderHistoryTest()
{
// TODO unit test for the property 'OrderHistory'
}
/// <summary>
/// Test the property 'PromoCode'
/// </summary>
[Test]
public void PromoCodeTest()
{
// TODO unit test for the property 'PromoCode'
}
/// <summary>
/// Test the property 'BtcReceiveAddress'
/// </summary>
[Test]
public void BtcReceiveAddressTest()
{
// TODO unit test for the property 'BtcReceiveAddress'
}
/// <summary>
/// Test the property 'BtcPriceSatoshi'
/// </summary>
[Test]
public void BtcPriceSatoshiTest()
{
// TODO unit test for the property 'BtcPriceSatoshi'
}
}
}
| 26.715867 | 94 | 0.505525 | [
"Apache-2.0"
] | NimmoJustin/connect-csharp-sdk | src/Square.Connect.Test/Model/V1OrderTests.cs | 7,240 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;
public class MustCollectItem : MonoBehaviour
{
[SerializeField] private UnityEvent getMustCollectItem;
private void OnTriggerEnter2D(Collider2D collision)
{
if (StageManager.Instance.ClearFlagType == E_ClearFlagType.CollectItem && collision.CompareTag("Player"))
{
SEManager.PlaySE(SEManager.getItem);
this.getMustCollectItem.Invoke();
ClearFlag_CollectItem.Instance.GetMustCollectItem();
Destroy(this.gameObject);
}
}
}
| 30.333333 | 114 | 0.684458 | [
"MIT"
] | Papyrustaro/UnityRocketGame | Assets/Scripts/StageManager/MustCollectItem.cs | 639 | C# |
/*
* This filePath is part of AceQL C# Client SDK.
* AceQL C# Client SDK: Remote SQL access over HTTP with AceQL HTTP.
* Copyright (C) 2021, KawanSoft SAS
* (http://www.kawansoft.com). All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this filePath 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;
namespace AceQL.Client.Api.Util
{
internal static class VersionValues
{
internal static readonly String PRODUCT = "AceQL HTTP Client SDK";
internal static readonly String VERSION = "v7.3";
internal static readonly String DATE = "03-Dec-2021";
}
}
| 39.483871 | 101 | 0.629085 | [
"Apache-2.0"
] | kawansoft/AceQL.Client2 | AceQLClient/src/Api.Util/VersionValues.cs | 1,226 | C# |
using Ryujinx.Common;
using Ryujinx.Graphics.Shader.IntermediateRepresentation;
using Ryujinx.Graphics.Shader.StructuredIr;
using Ryujinx.Graphics.Shader.Translation;
using System;
using System.Collections.Generic;
using System.Linq;
namespace Ryujinx.Graphics.Shader.CodeGen.Glsl
{
static class Declarations
{
// At least 16 attributes are guaranteed by the spec.
public const int MaxAttributes = 16;
public static void Declare(CodeGenContext context, StructuredProgramInfo info)
{
context.AppendLine("#version 450 core");
context.AppendLine("#extension GL_ARB_gpu_shader_int64 : enable");
context.AppendLine("#extension GL_ARB_shader_ballot : enable");
context.AppendLine("#extension GL_ARB_shader_group_vote : enable");
context.AppendLine("#extension GL_EXT_shader_image_load_formatted : enable");
if (context.Config.Stage == ShaderStage.Compute)
{
context.AppendLine("#extension GL_ARB_compute_shader : enable");
}
if (context.Config.GpPassthrough)
{
context.AppendLine("#extension GL_NV_geometry_shader_passthrough : enable");
}
context.AppendLine("#pragma optionNV(fastmath off)");
context.AppendLine();
context.AppendLine($"const int {DefaultNames.UndefinedName} = 0;");
context.AppendLine();
if (context.Config.Stage == ShaderStage.Compute)
{
int localMemorySize = BitUtils.DivRoundUp(context.Config.GpuAccessor.QueryComputeLocalMemorySize(), 4);
if (localMemorySize != 0)
{
string localMemorySizeStr = NumberFormatter.FormatInt(localMemorySize);
context.AppendLine($"uint {DefaultNames.LocalMemoryName}[{localMemorySizeStr}];");
context.AppendLine();
}
int sharedMemorySize = BitUtils.DivRoundUp(context.Config.GpuAccessor.QueryComputeSharedMemorySize(), 4);
if (sharedMemorySize != 0)
{
string sharedMemorySizeStr = NumberFormatter.FormatInt(sharedMemorySize);
context.AppendLine($"shared uint {DefaultNames.SharedMemoryName}[{sharedMemorySizeStr}];");
context.AppendLine();
}
}
else if (context.Config.LocalMemorySize != 0)
{
int localMemorySize = BitUtils.DivRoundUp(context.Config.LocalMemorySize, 4);
string localMemorySizeStr = NumberFormatter.FormatInt(localMemorySize);
context.AppendLine($"uint {DefaultNames.LocalMemoryName}[{localMemorySizeStr}];");
context.AppendLine();
}
if (info.CBuffers.Count != 0)
{
DeclareUniforms(context, info);
context.AppendLine();
}
if (info.SBuffers.Count != 0)
{
DeclareStorages(context, info);
context.AppendLine();
}
if (info.Samplers.Count != 0)
{
DeclareSamplers(context, info);
context.AppendLine();
}
if (info.Images.Count != 0)
{
DeclareImages(context, info);
context.AppendLine();
}
if (context.Config.Stage != ShaderStage.Compute)
{
if (context.Config.Stage == ShaderStage.Geometry)
{
string inPrimitive = context.Config.GpuAccessor.QueryPrimitiveTopology().ToGlslString();
context.AppendLine($"layout ({inPrimitive}) in;");
if (context.Config.GpPassthrough)
{
context.AppendLine($"layout (passthrough) in gl_PerVertex");
context.EnterScope();
context.AppendLine("vec4 gl_Position;");
context.AppendLine("float gl_PointSize;");
context.AppendLine("float gl_ClipDistance[];");
context.LeaveScope(";");
}
else
{
string outPrimitive = context.Config.OutputTopology.ToGlslString();
int maxOutputVertices = context.Config.MaxOutputVertices;
context.AppendLine($"layout ({outPrimitive}, max_vertices = {maxOutputVertices}) out;");
}
context.AppendLine();
}
if (info.IAttributes.Count != 0)
{
DeclareInputAttributes(context, info);
context.AppendLine();
}
if (info.OAttributes.Count != 0 || context.Config.Stage != ShaderStage.Fragment)
{
DeclareOutputAttributes(context, info);
context.AppendLine();
}
}
else
{
string localSizeX = NumberFormatter.FormatInt(context.Config.GpuAccessor.QueryComputeLocalSizeX());
string localSizeY = NumberFormatter.FormatInt(context.Config.GpuAccessor.QueryComputeLocalSizeY());
string localSizeZ = NumberFormatter.FormatInt(context.Config.GpuAccessor.QueryComputeLocalSizeZ());
context.AppendLine(
"layout (" +
$"local_size_x = {localSizeX}, " +
$"local_size_y = {localSizeY}, " +
$"local_size_z = {localSizeZ}) in;");
context.AppendLine();
}
if (context.Config.Stage == ShaderStage.Fragment || context.Config.Stage == ShaderStage.Compute)
{
if (context.Config.Stage == ShaderStage.Fragment)
{
if (context.Config.GpuAccessor.QueryEarlyZForce())
{
context.AppendLine("layout(early_fragment_tests) in;");
context.AppendLine();
}
context.AppendLine($"uniform bool {DefaultNames.IsBgraName}[8];");
context.AppendLine();
}
if (DeclareRenderScale(context))
{
context.AppendLine();
}
}
if ((info.HelperFunctionsMask & HelperFunctionsMask.AtomicMinMaxS32Shared) != 0)
{
AppendHelperFunction(context, "Ryujinx.Graphics.Shader/CodeGen/Glsl/HelperFunctions/AtomicMinMaxS32Shared.glsl");
}
if ((info.HelperFunctionsMask & HelperFunctionsMask.AtomicMinMaxS32Storage) != 0)
{
AppendHelperFunction(context, "Ryujinx.Graphics.Shader/CodeGen/Glsl/HelperFunctions/AtomicMinMaxS32Storage.glsl");
}
if ((info.HelperFunctionsMask & HelperFunctionsMask.MultiplyHighS32) != 0)
{
AppendHelperFunction(context, "Ryujinx.Graphics.Shader/CodeGen/Glsl/HelperFunctions/MultiplyHighS32.glsl");
}
if ((info.HelperFunctionsMask & HelperFunctionsMask.MultiplyHighU32) != 0)
{
AppendHelperFunction(context, "Ryujinx.Graphics.Shader/CodeGen/Glsl/HelperFunctions/MultiplyHighU32.glsl");
}
if ((info.HelperFunctionsMask & HelperFunctionsMask.Shuffle) != 0)
{
AppendHelperFunction(context, "Ryujinx.Graphics.Shader/CodeGen/Glsl/HelperFunctions/Shuffle.glsl");
}
if ((info.HelperFunctionsMask & HelperFunctionsMask.ShuffleDown) != 0)
{
AppendHelperFunction(context, "Ryujinx.Graphics.Shader/CodeGen/Glsl/HelperFunctions/ShuffleDown.glsl");
}
if ((info.HelperFunctionsMask & HelperFunctionsMask.ShuffleUp) != 0)
{
AppendHelperFunction(context, "Ryujinx.Graphics.Shader/CodeGen/Glsl/HelperFunctions/ShuffleUp.glsl");
}
if ((info.HelperFunctionsMask & HelperFunctionsMask.ShuffleXor) != 0)
{
AppendHelperFunction(context, "Ryujinx.Graphics.Shader/CodeGen/Glsl/HelperFunctions/ShuffleXor.glsl");
}
if ((info.HelperFunctionsMask & HelperFunctionsMask.SwizzleAdd) != 0)
{
AppendHelperFunction(context, "Ryujinx.Graphics.Shader/CodeGen/Glsl/HelperFunctions/SwizzleAdd.glsl");
}
}
public static void DeclareLocals(CodeGenContext context, StructuredFunction function)
{
foreach (AstOperand decl in function.Locals)
{
string name = context.OperandManager.DeclareLocal(decl);
context.AppendLine(GetVarTypeName(decl.VarType) + " " + name + ";");
}
}
public static string GetVarTypeName(VariableType type)
{
switch (type)
{
case VariableType.Bool: return "bool";
case VariableType.F32: return "precise float";
case VariableType.F64: return "double";
case VariableType.None: return "void";
case VariableType.S32: return "int";
case VariableType.U32: return "uint";
}
throw new ArgumentException($"Invalid variable type \"{type}\".");
}
private static void DeclareUniforms(CodeGenContext context, StructuredProgramInfo info)
{
string ubSize = "[" + NumberFormatter.FormatInt(Constants.ConstantBufferSize / 16) + "]";
if (info.UsesCbIndexing)
{
int count = info.CBuffers.Max() + 1;
int[] bindings = new int[count];
for (int i = 0; i < count; i++)
{
bindings[i] = context.Config.Counts.IncrementUniformBuffersCount();
}
foreach (int cbufSlot in info.CBuffers.OrderBy(x => x))
{
context.CBufferDescriptors.Add(new BufferDescriptor(bindings[cbufSlot], cbufSlot));
}
string ubName = OperandManager.GetShaderStagePrefix(context.Config.Stage);
ubName += "_" + DefaultNames.UniformNamePrefix;
string blockName = $"{ubName}_{DefaultNames.BlockSuffix}";
context.AppendLine($"layout (binding = {bindings[0]}, std140) uniform {blockName}");
context.EnterScope();
context.AppendLine("vec4 " + DefaultNames.DataName + ubSize + ";");
context.LeaveScope($" {ubName}[{NumberFormatter.FormatInt(count)}];");
}
else
{
foreach (int cbufSlot in info.CBuffers.OrderBy(x => x))
{
int binding = context.Config.Counts.IncrementUniformBuffersCount();
context.CBufferDescriptors.Add(new BufferDescriptor(binding, cbufSlot));
string ubName = OperandManager.GetShaderStagePrefix(context.Config.Stage);
ubName += "_" + DefaultNames.UniformNamePrefix + cbufSlot;
context.AppendLine($"layout (binding = {binding}, std140) uniform {ubName}");
context.EnterScope();
context.AppendLine("vec4 " + OperandManager.GetUbName(context.Config.Stage, cbufSlot, false) + ubSize + ";");
context.LeaveScope(";");
}
}
}
private static void DeclareStorages(CodeGenContext context, StructuredProgramInfo info)
{
string sbName = OperandManager.GetShaderStagePrefix(context.Config.Stage);
sbName += "_" + DefaultNames.StorageNamePrefix;
string blockName = $"{sbName}_{DefaultNames.BlockSuffix}";
int count = info.SBuffers.Max() + 1;
int[] bindings = new int[count];
for (int i = 0; i < count; i++)
{
bindings[i] = context.Config.Counts.IncrementStorageBuffersCount();
}
foreach (int sbufSlot in info.SBuffers)
{
context.SBufferDescriptors.Add(context.Config.GetSbDescriptor(bindings[sbufSlot], sbufSlot));
}
context.AppendLine($"layout (binding = {bindings[0]}, std430) buffer {blockName}");
context.EnterScope();
context.AppendLine("uint " + DefaultNames.DataName + "[];");
context.LeaveScope($" {sbName}[{NumberFormatter.FormatInt(count)}];");
}
private static void DeclareSamplers(CodeGenContext context, StructuredProgramInfo info)
{
HashSet<string> samplers = new HashSet<string>();
// Texture instructions other than TextureSample (like TextureSize)
// may have incomplete sampler type information. In those cases,
// we prefer instead the more accurate information from the
// TextureSample instruction, if both are available.
foreach (AstTextureOperation texOp in info.Samplers.OrderBy(x => x.Handle * 2 + (x.Inst == Instruction.TextureSample ? 0 : 1)))
{
string indexExpr = NumberFormatter.FormatInt(texOp.ArraySize);
string samplerName = OperandManager.GetSamplerName(context.Config.Stage, texOp, indexExpr);
if ((texOp.Flags & TextureFlags.Bindless) != 0 || !samplers.Add(samplerName))
{
continue;
}
int firstBinding = -1;
if ((texOp.Type & SamplerType.Indexed) != 0)
{
for (int index = 0; index < texOp.ArraySize; index++)
{
int binding = context.Config.Counts.IncrementTexturesCount();
if (firstBinding < 0)
{
firstBinding = binding;
}
var desc = new TextureDescriptor(binding, texOp.Type, texOp.Format, texOp.CbufSlot, texOp.Handle + index * 2);
context.TextureDescriptors.Add(desc);
}
}
else
{
firstBinding = context.Config.Counts.IncrementTexturesCount();
var desc = new TextureDescriptor(firstBinding, texOp.Type, texOp.Format, texOp.CbufSlot, texOp.Handle);
context.TextureDescriptors.Add(desc);
}
string samplerTypeName = texOp.Type.ToGlslSamplerType();
context.AppendLine($"layout (binding = {firstBinding}) uniform {samplerTypeName} {samplerName};");
}
}
private static void DeclareImages(CodeGenContext context, StructuredProgramInfo info)
{
HashSet<string> images = new HashSet<string>();
foreach (AstTextureOperation texOp in info.Images.OrderBy(x => x.Handle))
{
string indexExpr = NumberFormatter.FormatInt(texOp.ArraySize);
string imageName = OperandManager.GetImageName(context.Config.Stage, texOp, indexExpr);
if ((texOp.Flags & TextureFlags.Bindless) != 0 || !images.Add(imageName))
{
continue;
}
int firstBinding = -1;
if ((texOp.Type & SamplerType.Indexed) != 0)
{
for (int index = 0; index < texOp.ArraySize; index++)
{
int binding = context.Config.Counts.IncrementImagesCount();
if (firstBinding < 0)
{
firstBinding = binding;
}
var desc = new TextureDescriptor(binding, texOp.Type, texOp.Format, texOp.CbufSlot, texOp.Handle + index * 2);
context.ImageDescriptors.Add(desc);
}
}
else
{
firstBinding = context.Config.Counts.IncrementImagesCount();
var desc = new TextureDescriptor(firstBinding, texOp.Type, texOp.Format, texOp.CbufSlot, texOp.Handle);
context.ImageDescriptors.Add(desc);
}
string layout = texOp.Format.ToGlslFormat();
if (!string.IsNullOrEmpty(layout))
{
layout = ", " + layout;
}
string imageTypeName = texOp.Type.ToGlslImageType(texOp.Format.GetComponentType());
context.AppendLine($"layout (binding = {firstBinding}{layout}) uniform {imageTypeName} {imageName};");
}
}
private static void DeclareInputAttributes(CodeGenContext context, StructuredProgramInfo info)
{
string suffix = context.Config.Stage == ShaderStage.Geometry ? "[]" : string.Empty;
foreach (int attr in info.IAttributes.OrderBy(x => x))
{
string iq = string.Empty;
if (context.Config.Stage == ShaderStage.Fragment)
{
iq = context.Config.ImapTypes[attr].GetFirstUsedType() switch
{
PixelImap.Constant => "flat ",
PixelImap.ScreenLinear => "noperspective ",
_ => string.Empty
};
}
string pass = context.Config.GpPassthrough ? "passthrough, " : string.Empty;
string name = $"{DefaultNames.IAttributePrefix}{attr}";
if ((context.Config.Flags & TranslationFlags.Feedback) != 0)
{
for (int c = 0; c < 4; c++)
{
char swzMask = "xyzw"[c];
context.AppendLine($"layout ({pass}location = {attr}, component = {c}) {iq}in float {name}_{swzMask}{suffix};");
}
}
else
{
context.AppendLine($"layout ({pass}location = {attr}) {iq}in vec4 {name}{suffix};");
}
}
}
private static void DeclareOutputAttributes(CodeGenContext context, StructuredProgramInfo info)
{
if (context.Config.Stage == ShaderStage.Fragment)
{
DeclareUsedOutputAttributes(context, info);
}
else
{
DeclareAllOutputAttributes(context, info);
}
}
private static void DeclareUsedOutputAttributes(CodeGenContext context, StructuredProgramInfo info)
{
foreach (int attr in info.OAttributes.OrderBy(x => x))
{
context.AppendLine($"layout (location = {attr}) out vec4 {DefaultNames.OAttributePrefix}{attr};");
}
}
private static void DeclareAllOutputAttributes(CodeGenContext context, StructuredProgramInfo info)
{
for (int attr = 0; attr < MaxAttributes; attr++)
{
DeclareOutputAttribute(context, attr);
}
foreach (int attr in info.OAttributes.OrderBy(x => x).Where(x => x >= MaxAttributes))
{
DeclareOutputAttribute(context, attr);
}
}
private static void DeclareOutputAttribute(CodeGenContext context, int attr)
{
string name = $"{DefaultNames.OAttributePrefix}{attr}";
if ((context.Config.Flags & TranslationFlags.Feedback) != 0)
{
for (int c = 0; c < 4; c++)
{
char swzMask = "xyzw"[c];
context.AppendLine($"layout (location = {attr}, component = {c}) out float {name}_{swzMask};");
}
}
else
{
context.AppendLine($"layout (location = {attr}) out vec4 {name};");
}
}
private static bool DeclareRenderScale(CodeGenContext context)
{
if ((context.Config.UsedFeatures & (FeatureFlags.FragCoordXY | FeatureFlags.IntegerSampling)) != 0)
{
string stage = OperandManager.GetShaderStagePrefix(context.Config.Stage);
int scaleElements = context.TextureDescriptors.Count + context.ImageDescriptors.Count;
if (context.Config.Stage == ShaderStage.Fragment)
{
scaleElements++; // Also includes render target scale, for gl_FragCoord.
}
context.AppendLine($"uniform float {stage}_renderScale[{scaleElements}];");
if (context.Config.UsedFeatures.HasFlag(FeatureFlags.IntegerSampling))
{
context.AppendLine();
AppendHelperFunction(context, $"Ryujinx.Graphics.Shader/CodeGen/Glsl/HelperFunctions/TexelFetchScale_{stage}.glsl");
}
return true;
}
return false;
}
private static void AppendHelperFunction(CodeGenContext context, string filename)
{
string code = EmbeddedResources.ReadAllText(filename);
code = code.Replace("\t", CodeGenContext.Tab);
code = code.Replace("$SHARED_MEM$", DefaultNames.SharedMemoryName);
code = code.Replace("$STORAGE_MEM$", OperandManager.GetShaderStagePrefix(context.Config.Stage) + "_" + DefaultNames.StorageNamePrefix);
context.AppendLine(code);
context.AppendLine();
}
}
} | 39.008865 | 147 | 0.541612 | [
"MIT"
] | Shawnfr/Ryujinx | Ryujinx.Graphics.Shader/CodeGen/Glsl/Declarations.cs | 22,001 | C# |
// Copyright (c) Quarrel. All rights reserved.
namespace Quarrel.Helpers
{
/// <summary>
/// Contains tools methods for putting values in "humanized" form.
/// </summary>
public static class Humanize
{
/// <summary>
/// Converters a byte count to the most appropiate units.
/// </summary>
/// <param name="i">Byte count.</param>
/// <returns><paramref name="i"/> bytes in the most appropiate unit.</returns>
public static string HumanizeFileSize(long i)
{
long absolute_i = i < 0 ? -i : i;
string suffix;
double readable;
if (absolute_i >= 0x40000000)
{
// Gigabyte
suffix = "GB";
readable = i >> 20;
}
else if (absolute_i >= 0x100000)
{
// Megabyte
suffix = "MB";
readable = i >> 10;
}
else if (absolute_i >= 0x400)
{
// Kilobyte
suffix = "KB";
readable = i;
}
else
{
// Byte
return i.ToString("0 B");
}
readable = readable / 1024;
return readable.ToString("0.### ") + suffix;
}
}
}
| 27.12 | 86 | 0.432891 | [
"Apache-2.0"
] | UWPCommunity/Quarrel | src/Quarrel/Helpers/Humanize.cs | 1,358 | C# |
using System;
using System.ComponentModel;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using Util;
namespace Circuit.Spice
{
public class ParameterAlias : Attribute
{
private string alias;
public string Alias { get { return alias; } }
public ParameterAlias(string Alias) { alias = Alias.ToUpper(); }
}
/// <summary>
/// Represents the .MODEL SPICE statement.
/// </summary>
public class Model : Statement
{
private Component component;
/// <summary>
/// Component representing the model.
/// </summary>
public Component Component { get { return component; } }
private string desc;
/// <summary>
/// Log of information resulting from the import of this model.
/// </summary>
public string Description { get { return desc; } }
public Model(Component Component, string Description) { component = new Specialization(Component); desc = Description; }
public Model(Component Component) : this(Component, "") { }
/// <summary>
/// Mapping of SPICE model types to component templates.
/// </summary>
private static Dictionary<string, Component> ModelTemplates = new Dictionary<string, Component>()
{
{ "D", new Diode() },
{ "NPN", new BipolarJunctionTransistor() { Type = BjtType.NPN } },
{ "PNP", new BipolarJunctionTransistor() { Type = BjtType.PNP } },
{ "NJF", new JunctionFieldEffectTransistor() { Type = JfetType.N } },
{ "PJF", new JunctionFieldEffectTransistor() { Type = JfetType.P } },
};
public static Model Parse(TokenList Tokens)
{
string name = Tokens[1];
string type = Tokens[2];
Component template;
if (!ModelTemplates.TryGetValue(type, out template))
throw new NotSupportedException("Model type '" + type + "' not supported.");
Component impl = template.Clone();
impl.PartNumber = name;
for (int i = 3; i < Tokens.Count; ++i)
{
PropertyInfo p = FindTemplateProperty(template, Tokens[i]);
if (p != null)
{
TypeConverter tc = TypeDescriptor.GetConverter(p.PropertyType);
p.SetValue(impl, tc.ConvertFrom(ParseValue(Tokens[i + 1]).ToString()), null);
}
}
return new Model(impl, "Imported from SPICE model '" + Tokens.Text + "'.");
}
private static PropertyInfo FindTemplateProperty(Component Template, string Name)
{
Name = Name.ToUpper();
foreach (PropertyInfo i in Template.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public))
{
// Check all the parameter aliases for this parameter.
foreach (ParameterAlias j in i.CustomAttributes<ParameterAlias>())
if (Name == j.Alias)
return i;
// Check the name itself.
if (Name == i.Name.ToUpper())
return i;
}
return null;
}
}
}
| 34.697917 | 128 | 0.564095 | [
"MIT"
] | Auguschd/LiveSPICE | Circuit/Spice/Model.cs | 3,333 | C# |
using System;
namespace AntData.ORM.Mapping
{
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field)]
public sealed class NotNullAttribute : NullableAttribute
{
public NotNullAttribute()
: base(false)
{
}
public NotNullAttribute(string configuration)
: base(configuration, false)
{
}
}
}
| 17.157895 | 69 | 0.736196 | [
"MIT"
] | yuzd/AntData.ORM | AntData/AntData.ORM/Mapping/NotNullAttribute.cs | 328 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using NBitcoin;
using NBitcoin.Crypto;
using Xels.Bitcoin.Base.Deployments;
namespace Xels.Bitcoin.Features.Consensus.Rules.CommonRules
{
public class WitnessCommitmentsRule : ConsensusRule
{
/// <inheritdoc />
public override Task RunAsync(RuleContext context)
{
DeploymentFlags deploymentFlags = context.Flags;
Block block = context.BlockValidationContext.Block;
// Validation for witness commitments.
// * We compute the witness hash (which is the hash including witnesses) of all the block's transactions, except the
// coinbase (where 0x0000....0000 is used instead).
// * The coinbase scriptWitness is a stack of a single 32-byte vector, containing a witness nonce (unconstrained).
// * We build a merkle tree with all those witness hashes as leaves (similar to the hashMerkleRoot in the block header).
// * There must be at least one output whose scriptPubKey is a single 36-byte push, the first 4 bytes of which are
// {0xaa, 0x21, 0xa9, 0xed}, and the following 32 bytes are SHA256^2(witness root, witness nonce). In case there are
// multiple, the last one is used.
bool fHaveWitness = false;
if (deploymentFlags.ScriptFlags.HasFlag(ScriptVerify.Witness))
{
int commitpos = this.GetWitnessCommitmentIndex(block);
if (commitpos != -1)
{
uint256 hashWitness = BlockWitnessMerkleRoot(block, out bool malleated);
// The malleation check is ignored; as the transaction tree itself
// already does not permit it, it is impossible to trigger in the
// witness tree.
WitScript witness = block.Transactions[0].Inputs[0].WitScript;
if ((witness.PushCount != 1) || (witness.Pushes.First().Length != 32))
{
this.Logger.LogTrace("(-)[BAD_WITNESS_NONCE_SIZE]");
ConsensusErrors.BadWitnessNonceSize.Throw();
}
byte[] hashed = new byte[64];
Buffer.BlockCopy(hashWitness.ToBytes(), 0, hashed, 0, 32);
Buffer.BlockCopy(witness.Pushes.First(), 0, hashed, 32, 32);
hashWitness = Hashes.Hash256(hashed);
if (!this.EqualsArray(hashWitness.ToBytes(), block.Transactions[0].Outputs[commitpos].ScriptPubKey.ToBytes(true).Skip(6).ToArray(), 32))
{
this.Logger.LogTrace("(-)[WITNESS_MERKLE_MISMATCH]");
ConsensusErrors.BadWitnessMerkleMatch.Throw();
}
fHaveWitness = true;
}
}
if (!fHaveWitness)
{
for (int i = 0; i < block.Transactions.Count; i++)
{
if (block.Transactions[i].HasWitness)
{
this.Logger.LogTrace("(-)[UNEXPECTED_WITNESS]");
ConsensusErrors.UnexpectedWitness.Throw();
}
}
}
return Task.CompletedTask;
}
/// <summary>
/// Checks if first <paramref name="length"/> entries are equal between two arrays.
/// </summary>
/// <param name="a">First array.</param>
/// <param name="b">Second array.</param>
/// <param name="length">Number of entries to be checked.</param>
/// <returns><c>true</c> if <paramref name="length"/> entries are equal between two arrays. Otherwise <c>false</c>.</returns>
private bool EqualsArray(byte[] a, byte[] b, int length)
{
for (int i = 0; i < length; i++)
{
if (a[i] != b[i])
return false;
}
return true;
}
/// <summary>
/// Gets index of the last coinbase transaction output with SegWit flag.
/// </summary>
/// <param name="block">Block which coinbase transaction's outputs will be checked for SegWit flags.</param>
/// <returns>
/// <c>-1</c> if no SegWit flags were found.
/// If SegWit flag is found index of the last transaction's output that has SegWit flag is returned.
/// </returns>
private int GetWitnessCommitmentIndex(Block block)
{
int commitpos = -1;
for (int i = 0; i < block.Transactions[0].Outputs.Count; i++)
{
var scriptPubKey = block.Transactions[0].Outputs[i].ScriptPubKey;
if (scriptPubKey.Length >= 38)
{
byte[] scriptBytes = scriptPubKey.ToBytes(true);
if ((scriptBytes[0] == (byte)OpcodeType.OP_RETURN) &&
(scriptBytes[1] == 0x24) &&
(scriptBytes[2] == 0xaa) &&
(scriptBytes[3] == 0x21) &&
(scriptBytes[4] == 0xa9) &&
(scriptBytes[5] == 0xed))
{
commitpos = i;
}
}
}
return commitpos;
}
/// <summary>
/// Calculates merkle root for witness data.
/// </summary>
/// <param name="block">Block which transactions witness data is used for calculation.</param>
/// <param name="mutated"><c>true</c> if at least one leaf of the merkle tree has the same hash as any subtree. Otherwise: <c>false</c>.</param>
/// <returns>Merkle root.</returns>
public uint256 BlockWitnessMerkleRoot(Block block, out bool mutated)
{
var leaves = new List<uint256>();
leaves.Add(uint256.Zero); // The witness hash of the coinbase is 0.
foreach (Transaction tx in block.Transactions.Skip(1))
leaves.Add(tx.GetWitHash());
return BlockMerkleRootRule.ComputeMerkleRoot(leaves, out mutated);
}
}
} | 44.076923 | 156 | 0.541171 | [
"MIT"
] | rahhh/FullNodeUI | XelsBitcoinFullNode/src/Xels.Bitcoin.Features.Consensus/Rules/CommonRules/WitnessCommitmentsRule.cs | 6,303 | C# |
using Humanizer.Localisation;
using Xunit;
namespace Humanizer.Tests.Localisation.fiFI
{
[UseCulture("fi-FI")]
public class DateHumanizeTests
{
[Theory]
[InlineData(2, "2 päivää sitten")]
[InlineData(1, "eilen")]
public void DaysAgo(int days, string expected)
{
DateHumanize.Verify(expected, days, TimeUnit.Day, Tense.Past);
}
[Theory]
[InlineData(2, "2 tuntia sitten")]
[InlineData(1, "tunti sitten")]
public void HoursAgo(int hours, string expected)
{
DateHumanize.Verify(expected, hours, TimeUnit.Hour, Tense.Past);
}
[Theory]
[InlineData(2, "2 minuuttia sitten")]
[InlineData(1, "minuutti sitten")]
[InlineData(60, "tunti sitten")]
public void MinutesAgo(int minutes, string expected)
{
DateHumanize.Verify(expected, minutes, TimeUnit.Minute, Tense.Past);
}
[Theory]
[InlineData(2, "2 kuukautta sitten")]
[InlineData(1, "kuukausi sitten")]
public void MonthsAgo(int months, string expected)
{
DateHumanize.Verify(expected, months, TimeUnit.Month, Tense.Past);
}
[Theory]
[InlineData(2, "2 sekuntia sitten")]
[InlineData(1, "sekuntti sitten")]
public void SecondsAgo(int seconds, string expected)
{
DateHumanize.Verify(expected, seconds, TimeUnit.Second, Tense.Past);
}
[Theory]
[InlineData(2, "2 vuotta sitten")]
[InlineData(1, "vuosi sitten")]
public void YearsAgo(int years, string expected)
{
DateHumanize.Verify(expected, years, TimeUnit.Year, Tense.Past);
}
}
}
| 30.283333 | 81 | 0.567419 | [
"MIT"
] | NehaOberoi92/Humanizer | src/Humanizer.Tests.Shared/Localisation/fi-FI/DateHumanizeTests.cs | 1,763 | C# |
using System.Web.Http;
using System.Web.Mvc;
namespace DICOMcloud.Wado.Areas.HelpPage
{
public class HelpPageAreaRegistration : AreaRegistration
{
public override string AreaName
{
get
{
return "HelpPage";
}
}
public override void RegisterArea(AreaRegistrationContext context)
{
context.MapRoute(
"HelpPage_Default",
"Help/{action}/{apiId}",
new { controller = "Help", action = "Index", apiId = UrlParameter.Optional });
HelpPageConfig.Register(GlobalConfiguration.Configuration);
}
}
} | 25.884615 | 94 | 0.564636 | [
"Apache-2.0"
] | gitter-badger/DICOMcloud | DICOMcloud.Wado/Areas/HelpPage/HelpPageAreaRegistration.cs | 673 | C# |
// Copyright Epic Games, Inc. All Rights Reserved.
using UnrealBuildTool;
using System.Collections.Generic;
public class DemoProject1Target : TargetRules
{
public DemoProject1Target( TargetInfo Target) : base(Target)
{
Type = TargetType.Game;
DefaultBuildSettings = BuildSettingsVersion.V2;
ExtraModuleNames.AddRange( new string[] { "DemoProject1" } );
}
}
| 25.466667 | 64 | 0.73822 | [
"MIT"
] | gamedevfun/unreal_demo | Source/DemoProject1.Target.cs | 382 | C# |
// c:\program files (x86)\windows kits\10\include\10.0.18362.0\shared\ksmedia.h(8063,1)
using System.Runtime.InteropServices;
namespace DirectN
{
[StructLayout(LayoutKind.Sequential)]
public partial struct AUDIO_EFFECT_TYPE_SPEAKER_FILL
{
}
}
| 23.727273 | 88 | 0.743295 | [
"MIT"
] | bbday/DirectN | DirectN/DirectN/Generated/AUDIO_EFFECT_TYPE_SPEAKER_FILL.cs | 263 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using EasyAbp.EShop.Products.Products;
using EasyAbp.EShop.Products.Products.Dtos;
using EasyAbp.EShop.Products.Web.Pages.EShop.Products.Products.ProductSku.ViewModels;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Volo.Abp.Json;
namespace EasyAbp.EShop.Products.Web.Pages.EShop.Products.Products.ProductSku
{
public class CreateModalModel : ProductsPageModel
{
[HiddenInput]
[BindProperty(SupportsGet = true)]
public Guid StoreId { get; set; }
[HiddenInput]
[BindProperty(SupportsGet = true)]
public Guid ProductId { get; set; }
[BindProperty]
public CreateEditProductSkuViewModel ProductSku { get; set; }
[BindProperty]
public Dictionary<string, Guid> SelectedAttributeOptionIdDict { get; set; }
public Dictionary<string, ICollection<SelectListItem>> Attributes { get; set; }
private readonly IJsonSerializer _jsonSerializer;
private readonly IProductAppService _productAppService;
public CreateModalModel(
IJsonSerializer jsonSerializer,
IProductAppService productAppService)
{
_jsonSerializer = jsonSerializer;
_productAppService = productAppService;
}
public virtual async Task OnGetAsync()
{
var product = await _productAppService.GetAsync(ProductId, StoreId);
Attributes = new Dictionary<string, ICollection<SelectListItem>>();
foreach (var attribute in product.ProductAttributes.ToList())
{
Attributes.Add(attribute.DisplayName,
attribute.ProductAttributeOptions
.Select(dto => new SelectListItem(dto.DisplayName, dto.Id.ToString())).ToList());
}
}
public virtual async Task<IActionResult> OnPostAsync()
{
var createDto = ObjectMapper.Map<CreateEditProductSkuViewModel, CreateProductSkuDto>(ProductSku);
createDto.SerializedAttributeOptionIds = _jsonSerializer.Serialize(SelectedAttributeOptionIdDict.Values);
await _productAppService.CreateSkuAsync(ProductId, StoreId, createDto);
return NoContent();
}
}
} | 35.705882 | 117 | 0.66145 | [
"Apache-2.0"
] | p041911070/EShop | modules/EasyAbp.EShop.Products/src/EasyAbp.EShop.Products.Web/Pages/EShop/Products/Products/ProductSku/CreateModal.cshtml.cs | 2,428 | 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 WpfDataBase.Properties
{
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0")]
internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase
{
private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
public static Settings Default
{
get
{
return defaultInstance;
}
}
}
}
| 34.387097 | 151 | 0.581614 | [
"MIT"
] | djeada/Csharp-recipes | src/WpfDB_Project/WpfDataBase/Properties/Settings.Designer.cs | 1,068 | C# |
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using LinqToDB;
using NUnit.Framework;
namespace Tests.xUpdate
{
[TestFixture]
[Order(10000)]
public class CreateTempTableTests : TestBase
{
class IDTable
{
public int ID;
}
[Test]
public void CreateTable1([DataSources] string context)
{
using (var db = GetDataContext(context))
{
db.DropTable<int>("TempTable", throwExceptionIfNotExists:false);
using (var tmp = db.CreateTempTable(
"TempTable",
db.Parent.Select(p => new IDTable { ID = p.ParentID }),
tableOptions:TableOptions.CheckExistence))
{
var l = tmp.ToList();
var list =
(
from p in db.Parent
join t in tmp on p.ParentID equals t.ID
select t
).ToList();
}
}
}
[Test]
public void CreateTable2([DataSources] string context)
{
using (var db = GetDataContext(context))
{
db.DropTable<int>("TempTable", throwExceptionIfNotExists:false);
using (var tmp = db.CreateTempTable(
"TempTable",
db.Parent.Select(p => new { ID = p.ParentID }),
tableOptions:TableOptions.CheckExistence))
{
var list =
(
from p in db.Parent
join t in tmp on p.ParentID equals t.ID
select t
).ToList();
}
}
}
[Test]
public void CreateTable3([DataSources] string context)
{
using (var db = GetDataContext(context))
{
db.DropTable<int>("TempTable", throwExceptionIfNotExists:false);
using (var tmp = db.CreateTempTable(
"TempTable",
db.Parent.Select(p => new { ID = p.ParentID }),
em => em
.Property(e => e.ID)
.IsPrimaryKey(),
tableOptions:TableOptions.CheckExistence))
{
var list =
(
from p in db.Parent
join t in tmp on p.ParentID equals t.ID
select t
).ToList();
}
}
}
[Test]
public void CreateTableEnumerable([DataSources(false)] string context)
{
using (var db = GetDataContext(context))
{
db.DropTable<int>("TempTable", throwExceptionIfNotExists: false);
using (var tmp = db.CreateTempTable(
"TempTable",
db.Parent.Select(p => new IDTable { ID = p.ParentID }).ToList(),
tableOptions:TableOptions.CheckExistence))
{
var list =
(
from p in db.Parent
join t in tmp on p.ParentID equals t.ID
select t
).ToList();
}
}
}
[Test]
public async Task CreateTableAsync([DataSources] string context)
{
using (var db = GetDataContext(context))
{
await db.DropTableAsync<int>("TempTable", throwExceptionIfNotExists: false);
#if !NET472
await
#endif
using (var tmp = await db.CreateTempTableAsync(
"TempTable",
db.Parent.Select(p => new IDTable { ID = p.ParentID }),
tableOptions:TableOptions.CheckExistence))
{
var list =
(
from p in db.Parent
join t in tmp on p.ParentID equals t.ID
select t
).ToList();
}
}
}
[Test]
public async Task CreateTableAsyncEnumerable([DataSources(false)] string context)
{
using (var db = GetDataContext(context))
{
db.DropTable<int>("TempTable", throwExceptionIfNotExists: false);
#if !NET472
await
#endif
using (var tmp = await db.CreateTempTableAsync(
"TempTable",
db.Parent.Select(p => new IDTable { ID = p.ParentID }).ToList(),
tableOptions:TableOptions.CheckExistence))
{
var list =
(
from p in db.Parent
join t in tmp on p.ParentID equals t.ID
select t
).ToList();
}
}
}
[Test]
public async Task CreateTableAsyncCanceled([DataSources(false)] string context)
{
var cts = new CancellationTokenSource();
cts.Cancel();
using (var db = GetDataContext(context))
{
db.DropTable<int>("TempTable", throwExceptionIfNotExists: false);
try
{
#if !NET472
await
#endif
using (var tmp = await db.CreateTempTableAsync(
"TempTable",
db.Parent.Select(p => new IDTable { ID = p.ParentID }).ToList(),
cancellationToken: cts.Token))
{
var list =
(
from p in db.Parent
join t in tmp on p.ParentID equals t.ID
select t
).ToList();
}
Assert.Fail("Task should have been canceled but was not");
}
catch (OperationCanceledException) { }
var tableExists = true;
try
{
db.DropTable<int>("TempTable", throwExceptionIfNotExists: true);
}
catch
{
tableExists = false;
}
Assert.AreEqual(false, tableExists);
}
}
[Test]
public async Task CreateTableAsyncCanceled2([DataSources(false)] string context)
{
var cts = new CancellationTokenSource();
using (var db = GetDataContext(context))
{
db.DropTable<int>("TempTable", throwExceptionIfNotExists: false);
try
{
#if !NET472
await
#endif
using (var tmp = await db.CreateTempTableAsync(
"TempTable",
db.Parent.Select(p => new IDTable { ID = p.ParentID }),
action: (table) =>
{
cts.Cancel();
return Task.CompletedTask;
},
cancellationToken: cts.Token))
{
var list =
(
from p in db.Parent
join t in tmp on p.ParentID equals t.ID
select t
).ToList();
}
Assert.Fail("Task should have been canceled but was not");
}
catch (OperationCanceledException) { }
var tableExists = true;
try
{
db.DropTable<int>("TempTable", throwExceptionIfNotExists: true);
}
catch
{
tableExists = false;
}
Assert.AreEqual(false, tableExists);
}
}
[Test]
public void CreateTableSQLite([IncludeDataSources(TestProvName.AllSQLite)] string context)
{
using var db = GetDataContext(context);
var data = new[] { new { ID = 1, Field = 2 } };
using (var tmp = db.CreateTempTable(data, tableName : "#TempTable"))
{
var list = tmp.ToList();
Assert.That(list, Is.EquivalentTo(data));
}
}
}
}
| 22.97048 | 93 | 0.590522 | [
"MIT"
] | LiveFly/linq2db | Tests/Linq/Update/CreateTempTableTests.cs | 5,957 | C# |
using System.Data.Entity.ModelConfiguration;
using Wiz.Gringotts.UIWeb.Models.Organizations;
namespace Wiz.Gringotts.UIWeb.Data.Overrides
{
public class OrganizationConfiguration : EntityTypeConfiguration<Organization>
{
public OrganizationConfiguration()
{
this.HasMany(o => o.Features)
.WithMany()
.Map(mo =>
{
mo.MapLeftKey("OrganizationId");
mo.MapRightKey("FeatureId");
mo.ToTable("OrganizationFeatures");
});
}
}
} | 28.904762 | 82 | 0.546952 | [
"MIT"
] | NotMyself/Gringotts | src/UIWeb/Data/Overrides/OrganizationConfiguration.cs | 609 | C# |
using Microsoft.AspNet.Identity;
using OnlineStore.DataProvider.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace OnlineStore.DataProvider.Identity
{
public class ApplicationUserRoleManager : RoleManager<ApplicationUserRole>
{
public ApplicationUserRoleManager(IRoleStore<ApplicationUserRole, string> store) : base(store)
{
}
}
}
| 25.222222 | 102 | 0.764317 | [
"MIT"
] | RedDiamond69/Carnivorous-plants-store | Source/OnlineStore.DataProvider/Identity/ApplicationUserRoleManager.cs | 456 | C# |
using UBaseline.Shared.Node;
namespace Uintra.Features.Comments.Models
{
public class CommentsPanelModel : NodeModel
{
}
} | 17 | 47 | 0.727941 | [
"MIT"
] | Uintra/Uintra | src/Uintra/Features/Comments/Models/CommentsPanelModel.cs | 138 | C# |
// ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------------------------------------------------------------
namespace Microsoft.WindowsAzure.Commands.ServiceManagement.Test.FunctionalTests.PaasCmdletInfo
{
using PowershellCore;
using System.Security.Cryptography.X509Certificates;
using System.Xml;
public class NewAzureServiceDiagnosticsExtensionConfigCmdletInfo : CmdletsInfo
{
public NewAzureServiceDiagnosticsExtensionConfigCmdletInfo(string storage, XmlDocument config, string[] roles)
{
this.cmdletName = Utilities.NewAzureServiceDiagnosticsExtensionConfigCmdletName;
this.cmdletParams.Add(new CmdletParam("StorageAccountName", storage));
if (roles != null)
{
this.cmdletParams.Add(new CmdletParam("Role", roles));
}
if (config != null)
{
this.cmdletParams.Add(new CmdletParam("DiagnosticsConfiguration", config));
}
}
public NewAzureServiceDiagnosticsExtensionConfigCmdletInfo(string storage, X509Certificate2 cert, XmlDocument config, string[] roles)
: this(storage, config, roles)
{
this.cmdletParams.Add(new CmdletParam("X509Certificate", cert));
}
public NewAzureServiceDiagnosticsExtensionConfigCmdletInfo(string storage, string thumbprint, string algorithm, XmlDocument config, string[] roles)
: this(storage, config, roles)
{
this.cmdletParams.Add(new CmdletParam("CertificateThumbprint", thumbprint));
if (!string.IsNullOrEmpty(algorithm))
{
this.cmdletParams.Add(new CmdletParam("ThumbprintAlgorithm", algorithm));
}
}
}
}
| 44.571429 | 156 | 0.617788 | [
"MIT"
] | stankovski/azure-sdk-tools | src/ServiceManagement/Compute/Commands.ServiceManagement.Test/FunctionalTests/PaasCmdletInfo/NewAzureServiceDiagnosticsExtensionConfigCmdletInfo.cs | 2,443 | C# |
using System;
using AutoMapper;
using Core.Entities;
using Google.Apis.YouTube.v3.Data;
using Channel = Google.Apis.YouTube.v3.Data.Channel;
namespace Infrastructure.Mappings
{
public class DataMappingProfile : Profile
{
public DataMappingProfile()
{
CreateMap<PlaylistItem, VideoResult>()
.ForMember(dest => dest.Id, opt => opt.MapFrom(src => src.Snippet.ResourceId.VideoId))
.ForMember(dest => dest.Title, opt => opt.MapFrom(src => src.Snippet.Title))
.ForMember(dest => dest.Description, opt => opt.MapFrom(src => src.Snippet.Description))
.ForMember(dest => dest.ChannelId, opt => opt.MapFrom(src => src.Snippet.ChannelId))
.ForMember(dest => dest.PublishedAt, opt => opt.MapFrom(src =>
new DateTimeOffset(src.Snippet.PublishedAt.Value).ToUnixTimeSeconds()));
CreateMap<Channel, YouTubeChannel>()
.ForMember(dest => dest.Id, opt => opt.MapFrom(src => src.Id))
.ForMember(dest => dest.Title, opt => opt.MapFrom(src => src.Snippet.Title))
.ForMember(dest => dest.Description, opt => opt.MapFrom(src => src.Snippet.Description))
.ForMember(dest => dest.Thumbnail, opt => opt.MapFrom(src => src.Snippet.Thumbnails.Default__.Url))
.ForMember(dest => dest.VideoCount, opt => opt.MapFrom(src => src.Statistics.VideoCount ?? 0))
.ForMember(dest => dest.SubscriberCount, opt => opt.MapFrom(src => src.Statistics.SubscriberCount ?? 0))
.ForMember(dest => dest.ViewCount, opt => opt.MapFrom(src => src.Statistics.ViewCount ?? 0))
.ForMember(dest => dest.HiddenSubscriberCount, opt => opt.MapFrom(src => src.Statistics.HiddenSubscriberCount ?? false));
}
}
}
| 49.727273 | 125 | 0.697745 | [
"MIT"
] | sailingchannels/data | Infrastructure/Mappings/DataMappingProfile.cs | 1,643 | C# |
// un-batching functionality encapsulated into one class.
// -> less complexity
// -> easy to test
//
// includes timestamp for tick batching.
// -> allows NetworkTransform etc. to use timestamp without including it in
// every single message
using System;
using System.Collections.Generic;
namespace Mirror
{
public class Unbatcher
{
// supporting adding multiple batches before GetNextMessage is called.
// just in case.
Queue<NetworkWriterPooled> batches = new Queue<NetworkWriterPooled>();
public int BatchesCount => batches.Count;
// NetworkReader is only created once,
// then pointed to the first batch.
NetworkReader reader = new NetworkReader(new byte[0]);
// timestamp that was written into the batch remotely.
// for the batch that our reader is currently pointed at.
double readerRemoteTimeStamp;
// helper function to start reading a batch.
void StartReadingBatch(NetworkWriterPooled batch)
{
// point reader to it
reader.SetBuffer(batch.ToArraySegment());
// read remote timestamp (double)
// -> AddBatch quarantees that we have at least 8 bytes to read
readerRemoteTimeStamp = reader.ReadDouble();
}
// add a new batch.
// returns true if valid.
// returns false if not, in which case the connection should be disconnected.
public bool AddBatch(ArraySegment<byte> batch)
{
// IMPORTANT: ArraySegment is only valid until returning. we copy it!
//
// NOTE: it's not possible to create empty ArraySegments, so we
// don't need to check against that.
// make sure we have at least 8 bytes to read for tick timestamp
if (batch.Count < Batcher.HeaderSize)
return false;
// put into a (pooled) writer
// -> WriteBytes instead of WriteSegment because the latter
// would add a size header. we want to write directly.
// -> will be returned to pool when sending!
NetworkWriterPooled writer = NetworkWriterPool.Get();
writer.WriteBytes(batch.Array, batch.Offset, batch.Count);
// first batch? then point reader there
if (batches.Count == 0)
StartReadingBatch(writer);
// add batch
batches.Enqueue(writer);
//Debug.Log($"Adding Batch {BitConverter.ToString(batch.Array, batch.Offset, batch.Count)} => batches={batches.Count} reader={reader}");
return true;
}
// get next message, unpacked from batch (if any)
// timestamp is the REMOTE time when the batch was created remotely.
public bool GetNextMessage(out NetworkReader message, out double remoteTimeStamp)
{
// getting messages would be easy via
// <<size, message, size, message, ...>>
// but to save A LOT of bandwidth, we use
// <<message, message, ...>
// in other words, we don't know where the current message ends
//
// BUT: it doesn't matter!
// -> we simply return the reader
// * if we have one yet
// * and if there's more to read
// -> the caller can then read one message from it
// -> when the end is reached, we retire the batch!
//
// for example:
// while (GetNextMessage(out message))
// ProcessMessage(message);
//
message = null;
// do nothing if we don't have any batches.
// otherwise the below queue.Dequeue() would throw an
// InvalidOperationException if operating on empty queue.
if (batches.Count == 0)
{
remoteTimeStamp = 0;
return false;
}
// was our reader pointed to anything yet?
if (reader.Length == 0)
{
remoteTimeStamp = 0;
return false;
}
// no more data to read?
if (reader.Remaining == 0)
{
// retire the batch
NetworkWriterPooled writer = batches.Dequeue();
NetworkWriterPool.Return(writer);
// do we have another batch?
if (batches.Count > 0)
{
// point reader to the next batch.
// we'll return the reader below.
NetworkWriterPooled next = batches.Peek();
StartReadingBatch(next);
}
// otherwise there's nothing more to read
else
{
remoteTimeStamp = 0;
return false;
}
}
// use the current batch's remote timestamp
// AFTER potentially moving to the next batch ABOVE!
remoteTimeStamp = readerRemoteTimeStamp;
// if we got here, then we have more data to read.
message = reader;
return true;
}
}
}
| 36.923077 | 148 | 0.547727 | [
"MPL-2.0"
] | danyow/Card-Game-Simulator | Assets/Mirror/Runtime/Batching/Unbatcher.cs | 5,280 | C# |
namespace ServiceWatcherWebRole.Areas.HelpPage.ModelDescriptions
{
public class CollectionModelDescription : ModelDescription
{
public ModelDescription ElementDescription { get; set; }
}
} | 30.571429 | 65 | 0.742991 | [
"MIT"
] | brakmic/ServiceWatcher | ServiceWatcherWebRole/Areas/HelpPage/ModelDescriptions/CollectionModelDescription.cs | 214 | C# |
namespace SFA.Apprenticeships.Infrastructure.Communication.Configuration
{
public class CommunicationConfiguration
{
public bool IsEnabled { get; set; }
public string CandidateSiteDomainName { get; set; }
public string RecruitSiteDomainName { get; set; }
public string ManageSiteDomainName { get; set; }
public string EmailDispatcher { get; set; }
public string SmsDispatcher { get; set; }
}
}
| 25.555556 | 73 | 0.676087 | [
"MIT"
] | BugsUK/FindApprenticeship | src/SFA.Apprenticeships.Infrastructure.Communication/Configuration/CommunicationConfiguration.cs | 462 | C# |
namespace LH.CommandLine.UnitTests.OptionsParser.Options
{
public partial class WhenParsingUsingInvalidOptionsDefinition
{
public class OptionsWithOnlyNonZeroPositionalArgs
{
[Argument(1)]
public string SomeArg { get; set; }
}
}
} | 26.454545 | 65 | 0.652921 | [
"MIT"
] | lholota/LH.CommandLine | tests/LH.CommandLine.UnitTests/OptionsParser/Options/OptionsWithOnlyNonZeroPositionalArgs.cs | 293 | C# |
namespace EIDSS.Reports.BaseControls
{
partial class ReportView
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Component Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(ReportView));
this.printingSystemReports = new DevExpress.XtraPrinting.PrintingSystem(this.components);
this.printControlReport = new EIDSS.Reports.BaseControls.ReportPrintControl();
this.barDockControlLeft = new DevExpress.XtraBars.BarDockControl();
this.barDockControlRight = new DevExpress.XtraBars.BarDockControl();
this.barDockControlBottom = new DevExpress.XtraBars.BarDockControl();
this.barDockControlTop = new DevExpress.XtraBars.BarDockControl();
this.printBarManager = new DevExpress.XtraPrinting.Preview.PrintBarManager();
this.previewBar1 = new DevExpress.XtraPrinting.Preview.PreviewBar();
this.biLoadDefault = new DevExpress.XtraBars.BarButtonItem();
this.biEdit = new DevExpress.XtraBars.BarButtonItem();
this.biFind = new DevExpress.XtraPrinting.Preview.PrintPreviewBarItem();
this.biPrint = new DevExpress.XtraPrinting.Preview.PrintPreviewBarItem();
this.biPrintDirect = new DevExpress.XtraPrinting.Preview.PrintPreviewBarItem();
this.biPageSetup = new DevExpress.XtraPrinting.Preview.PrintPreviewBarItem();
this.biScale = new DevExpress.XtraPrinting.Preview.PrintPreviewBarItem();
this.biHandTool = new DevExpress.XtraPrinting.Preview.PrintPreviewBarItem();
this.biMagnifier = new DevExpress.XtraPrinting.Preview.PrintPreviewBarItem();
this.biZoomOut = new DevExpress.XtraPrinting.Preview.PrintPreviewBarItem();
this.biZoom = new DevExpress.XtraPrinting.Preview.ZoomBarEditItem();
this.printPreviewRepositoryItemComboBox1 = new DevExpress.XtraPrinting.Preview.PrintPreviewRepositoryItemComboBox();
this.ZoomIn = new DevExpress.XtraPrinting.Preview.PrintPreviewBarItem();
this.biShowFirstPage = new DevExpress.XtraPrinting.Preview.PrintPreviewBarItem();
this.biShowPrevPage = new DevExpress.XtraPrinting.Preview.PrintPreviewBarItem();
this.biShowNextPage = new DevExpress.XtraPrinting.Preview.PrintPreviewBarItem();
this.biShowLastPage = new DevExpress.XtraPrinting.Preview.PrintPreviewBarItem();
this.biMultiplePages = new DevExpress.XtraPrinting.Preview.PrintPreviewBarItem();
this.biFillBackground = new DevExpress.XtraPrinting.Preview.PrintPreviewBarItem();
this.biExportFile = new DevExpress.XtraPrinting.Preview.PrintPreviewBarItem();
this.barStatus = new DevExpress.XtraPrinting.Preview.PreviewBar();
this.biPage = new DevExpress.XtraPrinting.Preview.PrintPreviewStaticItem();
this.barStaticItem1 = new DevExpress.XtraBars.BarStaticItem();
this.biProgressBar = new DevExpress.XtraPrinting.Preview.ProgressBarEditItem();
this.repositoryItemProgressBar1 = new DevExpress.XtraEditors.Repository.RepositoryItemProgressBar();
this.biStatusStatus = new DevExpress.XtraPrinting.Preview.PrintPreviewBarItem();
this.barButtonItem1 = new DevExpress.XtraBars.BarButtonItem();
this.biStatusZoom = new DevExpress.XtraPrinting.Preview.PrintPreviewStaticItem();
this.barMainMenu = new DevExpress.XtraPrinting.Preview.PreviewBar();
this.printPreviewSubItem4 = new DevExpress.XtraPrinting.Preview.PrintPreviewSubItem();
this.printPreviewBarItem27 = new DevExpress.XtraPrinting.Preview.PrintPreviewBarItem();
this.printPreviewBarItem28 = new DevExpress.XtraPrinting.Preview.PrintPreviewBarItem();
this.barToolbarsListItem1 = new DevExpress.XtraBars.BarToolbarsListItem();
this.biExportPdf = new DevExpress.XtraPrinting.Preview.PrintPreviewBarCheckItem();
this.biExportHtm = new DevExpress.XtraPrinting.Preview.PrintPreviewBarCheckItem();
this.biExportMht = new DevExpress.XtraPrinting.Preview.PrintPreviewBarCheckItem();
this.biExportRtf = new DevExpress.XtraPrinting.Preview.PrintPreviewBarCheckItem();
this.biExportXls = new DevExpress.XtraPrinting.Preview.PrintPreviewBarCheckItem();
this.biExportCsv = new DevExpress.XtraPrinting.Preview.PrintPreviewBarCheckItem();
this.biExportTxt = new DevExpress.XtraPrinting.Preview.PrintPreviewBarCheckItem();
this.biExportGraphic = new DevExpress.XtraPrinting.Preview.PrintPreviewBarCheckItem();
this.printPreviewBarItem2 = new DevExpress.XtraPrinting.Preview.PrintPreviewBarItem();
this.timerScroll = new System.Windows.Forms.Timer(this.components);
((System.ComponentModel.ISupportInitialize)(this.printingSystemReports)).BeginInit();
this.printControlReport.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.printBarManager)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.printPreviewRepositoryItemComboBox1)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.repositoryItemProgressBar1)).BeginInit();
this.SuspendLayout();
//
// printControlReport
//
this.printControlReport.AccessibleDescription = null;
this.printControlReport.AccessibleName = null;
resources.ApplyResources(this.printControlReport, "printControlReport");
this.printControlReport.BackgroundImage = null;
this.printControlReport.Controls.Add(this.barDockControlLeft);
this.printControlReport.Controls.Add(this.barDockControlRight);
this.printControlReport.Controls.Add(this.barDockControlBottom);
this.printControlReport.Controls.Add(this.barDockControlTop);
this.printControlReport.Font = null;
this.printControlReport.LookAndFeel.SkinName = "Blue";
this.printControlReport.Name = "printControlReport";
this.printControlReport.PrintingSystem = this.printingSystemReports;
//
// barDockControlLeft
//
this.barDockControlLeft.AccessibleDescription = null;
this.barDockControlLeft.AccessibleName = null;
resources.ApplyResources(this.barDockControlLeft, "barDockControlLeft");
this.barDockControlLeft.Font = null;
//
// barDockControlRight
//
this.barDockControlRight.AccessibleDescription = null;
this.barDockControlRight.AccessibleName = null;
resources.ApplyResources(this.barDockControlRight, "barDockControlRight");
this.barDockControlRight.Font = null;
//
// barDockControlBottom
//
this.barDockControlBottom.AccessibleDescription = null;
this.barDockControlBottom.AccessibleName = null;
resources.ApplyResources(this.barDockControlBottom, "barDockControlBottom");
this.barDockControlBottom.Font = null;
//
// barDockControlTop
//
this.barDockControlTop.AccessibleDescription = null;
this.barDockControlTop.AccessibleName = null;
resources.ApplyResources(this.barDockControlTop, "barDockControlTop");
this.barDockControlTop.Font = null;
//
// printBarManager
//
this.printBarManager.AllowCustomization = false;
this.printBarManager.AllowQuickCustomization = false;
this.printBarManager.Bars.AddRange(new DevExpress.XtraBars.Bar[] {
this.previewBar1,
this.barStatus,
this.barMainMenu});
this.printBarManager.DockControls.Add(this.barDockControlTop);
this.printBarManager.DockControls.Add(this.barDockControlBottom);
this.printBarManager.DockControls.Add(this.barDockControlLeft);
this.printBarManager.DockControls.Add(this.barDockControlRight);
this.printBarManager.Form = this.printControlReport;
this.printBarManager.ImageStream = ((DevExpress.Utils.ImageCollectionStreamer)(resources.GetObject("printBarManager.ImageStream")));
this.printBarManager.Items.AddRange(new DevExpress.XtraBars.BarItem[] {
this.biPage,
this.barStaticItem1,
this.biProgressBar,
this.biStatusStatus,
this.barButtonItem1,
this.biStatusZoom,
this.biFind,
this.biPrint,
this.biPrintDirect,
this.biPageSetup,
this.biScale,
this.biHandTool,
this.biMagnifier,
this.biZoomOut,
this.biZoom,
this.ZoomIn,
this.biShowFirstPage,
this.biShowPrevPage,
this.biShowNextPage,
this.biShowLastPage,
this.biMultiplePages,
this.biFillBackground,
this.biExportFile,
this.printPreviewSubItem4,
this.printPreviewBarItem27,
this.printPreviewBarItem28,
this.barToolbarsListItem1,
this.biExportPdf,
this.biExportHtm,
this.biExportMht,
this.biExportRtf,
this.biExportXls,
this.biExportCsv,
this.biExportTxt,
this.biExportGraphic,
this.biEdit,
this.biLoadDefault});
this.printBarManager.MainMenu = this.barMainMenu;
this.printBarManager.MaxItemId = 60;
this.printBarManager.PreviewBar = this.previewBar1;
this.printBarManager.PrintControl = this.printControlReport;
this.printBarManager.RepositoryItems.AddRange(new DevExpress.XtraEditors.Repository.RepositoryItem[] {
this.repositoryItemProgressBar1,
this.printPreviewRepositoryItemComboBox1});
this.printBarManager.StatusBar = this.barStatus;
//
// previewBar1
//
this.previewBar1.BarName = "Toolbar";
this.previewBar1.DockCol = 0;
this.previewBar1.DockRow = 1;
this.previewBar1.DockStyle = DevExpress.XtraBars.BarDockStyle.Top;
this.previewBar1.LinksPersistInfo.AddRange(new DevExpress.XtraBars.LinkPersistInfo[] {
new DevExpress.XtraBars.LinkPersistInfo(this.biLoadDefault, true),
new DevExpress.XtraBars.LinkPersistInfo(this.biEdit),
new DevExpress.XtraBars.LinkPersistInfo(this.biFind, true),
new DevExpress.XtraBars.LinkPersistInfo(this.biPrint),
new DevExpress.XtraBars.LinkPersistInfo(this.biPrintDirect),
new DevExpress.XtraBars.LinkPersistInfo(this.biPageSetup),
new DevExpress.XtraBars.LinkPersistInfo(this.biScale),
new DevExpress.XtraBars.LinkPersistInfo(this.biHandTool, true),
new DevExpress.XtraBars.LinkPersistInfo(this.biMagnifier),
new DevExpress.XtraBars.LinkPersistInfo(this.biZoomOut, true),
new DevExpress.XtraBars.LinkPersistInfo(DevExpress.XtraBars.BarLinkUserDefines.Width, this.biZoom, "", false, true, true, 70),
new DevExpress.XtraBars.LinkPersistInfo(this.ZoomIn),
new DevExpress.XtraBars.LinkPersistInfo(this.biShowFirstPage, true),
new DevExpress.XtraBars.LinkPersistInfo(this.biShowPrevPage),
new DevExpress.XtraBars.LinkPersistInfo(this.biShowNextPage),
new DevExpress.XtraBars.LinkPersistInfo(this.biShowLastPage),
new DevExpress.XtraBars.LinkPersistInfo(this.biMultiplePages, true),
new DevExpress.XtraBars.LinkPersistInfo(this.biFillBackground),
new DevExpress.XtraBars.LinkPersistInfo(this.biExportFile, true)});
this.previewBar1.OptionsBar.AllowQuickCustomization = false;
this.previewBar1.OptionsBar.DisableClose = true;
this.previewBar1.OptionsBar.DisableCustomization = true;
this.previewBar1.OptionsBar.DrawDragBorder = false;
resources.ApplyResources(this.previewBar1, "previewBar1");
//
// biLoadDefault
//
this.biLoadDefault.AccessibleDescription = null;
this.biLoadDefault.AccessibleName = null;
resources.ApplyResources(this.biLoadDefault, "biLoadDefault");
this.biLoadDefault.Enabled = false;
this.biLoadDefault.Glyph = global::EIDSS.Reports.Properties.Resources.restore;
this.biLoadDefault.Id = 59;
this.biLoadDefault.Name = "biLoadDefault";
this.biLoadDefault.Visibility = DevExpress.XtraBars.BarItemVisibility.Never;
this.biLoadDefault.ItemClick += new DevExpress.XtraBars.ItemClickEventHandler(this.biLoadDefault_ItemClick);
//
// biEdit
//
this.biEdit.AccessibleDescription = null;
this.biEdit.AccessibleName = null;
resources.ApplyResources(this.biEdit, "biEdit");
this.biEdit.Enabled = false;
this.biEdit.Glyph = global::EIDSS.Reports.Properties.Resources.msg_edit;
this.biEdit.Id = 58;
this.biEdit.Name = "biEdit";
this.biEdit.Visibility = DevExpress.XtraBars.BarItemVisibility.Never;
this.biEdit.ItemClick += new DevExpress.XtraBars.ItemClickEventHandler(this.biEdit_ItemClick);
//
// biFind
//
this.biFind.AccessibleDescription = null;
this.biFind.AccessibleName = null;
resources.ApplyResources(this.biFind, "biFind");
this.biFind.Command = DevExpress.XtraPrinting.PrintingSystemCommand.Find;
this.biFind.Enabled = false;
this.biFind.Id = 8;
this.biFind.ImageIndex = 20;
this.biFind.Name = "biFind";
//
// biPrint
//
this.biPrint.AccessibleDescription = null;
this.biPrint.AccessibleName = null;
this.biPrint.ButtonStyle = DevExpress.XtraBars.BarButtonStyle.Check;
resources.ApplyResources(this.biPrint, "biPrint");
this.biPrint.Command = DevExpress.XtraPrinting.PrintingSystemCommand.Print;
this.biPrint.Enabled = false;
this.biPrint.Id = 12;
this.biPrint.ImageIndex = 0;
this.biPrint.Name = "biPrint";
//
// biPrintDirect
//
this.biPrintDirect.AccessibleDescription = null;
this.biPrintDirect.AccessibleName = null;
resources.ApplyResources(this.biPrintDirect, "biPrintDirect");
this.biPrintDirect.Command = DevExpress.XtraPrinting.PrintingSystemCommand.PrintDirect;
this.biPrintDirect.Enabled = false;
this.biPrintDirect.Id = 13;
this.biPrintDirect.ImageIndex = 1;
this.biPrintDirect.Name = "biPrintDirect";
//
// biPageSetup
//
this.biPageSetup.AccessibleDescription = null;
this.biPageSetup.AccessibleName = null;
this.biPageSetup.ButtonStyle = DevExpress.XtraBars.BarButtonStyle.Check;
resources.ApplyResources(this.biPageSetup, "biPageSetup");
this.biPageSetup.Command = DevExpress.XtraPrinting.PrintingSystemCommand.PageSetup;
this.biPageSetup.Enabled = false;
this.biPageSetup.Id = 14;
this.biPageSetup.ImageIndex = 2;
this.biPageSetup.Name = "biPageSetup";
//
// biScale
//
this.biScale.AccessibleDescription = null;
this.biScale.AccessibleName = null;
this.biScale.ActAsDropDown = true;
this.biScale.ButtonStyle = DevExpress.XtraBars.BarButtonStyle.DropDown;
resources.ApplyResources(this.biScale, "biScale");
this.biScale.Command = DevExpress.XtraPrinting.PrintingSystemCommand.Scale;
this.biScale.Enabled = false;
this.biScale.Id = 16;
this.biScale.ImageIndex = 25;
this.biScale.Name = "biScale";
//
// biHandTool
//
this.biHandTool.AccessibleDescription = null;
this.biHandTool.AccessibleName = null;
this.biHandTool.ButtonStyle = DevExpress.XtraBars.BarButtonStyle.Check;
resources.ApplyResources(this.biHandTool, "biHandTool");
this.biHandTool.Command = DevExpress.XtraPrinting.PrintingSystemCommand.HandTool;
this.biHandTool.Enabled = false;
this.biHandTool.Id = 17;
this.biHandTool.ImageIndex = 16;
this.biHandTool.Name = "biHandTool";
//
// biMagnifier
//
this.biMagnifier.AccessibleDescription = null;
this.biMagnifier.AccessibleName = null;
this.biMagnifier.ButtonStyle = DevExpress.XtraBars.BarButtonStyle.Check;
resources.ApplyResources(this.biMagnifier, "biMagnifier");
this.biMagnifier.Command = DevExpress.XtraPrinting.PrintingSystemCommand.Magnifier;
this.biMagnifier.Enabled = false;
this.biMagnifier.Id = 18;
this.biMagnifier.ImageIndex = 3;
this.biMagnifier.Name = "biMagnifier";
//
// biZoomOut
//
this.biZoomOut.AccessibleDescription = null;
this.biZoomOut.AccessibleName = null;
resources.ApplyResources(this.biZoomOut, "biZoomOut");
this.biZoomOut.Command = DevExpress.XtraPrinting.PrintingSystemCommand.ZoomOut;
this.biZoomOut.Enabled = false;
this.biZoomOut.Id = 19;
this.biZoomOut.ImageIndex = 5;
this.biZoomOut.Name = "biZoomOut";
//
// biZoom
//
this.biZoom.AccessibleDescription = null;
this.biZoom.AccessibleName = null;
resources.ApplyResources(this.biZoom, "biZoom");
this.biZoom.Edit = this.printPreviewRepositoryItemComboBox1;
this.biZoom.EditValue = "100%";
this.biZoom.Enabled = false;
this.biZoom.Id = 20;
this.biZoom.Name = "biZoom";
//
// printPreviewRepositoryItemComboBox1
//
this.printPreviewRepositoryItemComboBox1.AccessibleDescription = null;
this.printPreviewRepositoryItemComboBox1.AccessibleName = null;
this.printPreviewRepositoryItemComboBox1.AutoComplete = false;
resources.ApplyResources(this.printPreviewRepositoryItemComboBox1, "printPreviewRepositoryItemComboBox1");
this.printPreviewRepositoryItemComboBox1.Buttons.AddRange(new DevExpress.XtraEditors.Controls.EditorButton[] {
new DevExpress.XtraEditors.Controls.EditorButton(((DevExpress.XtraEditors.Controls.ButtonPredefines)(resources.GetObject("printPreviewRepositoryItemComboBox1.Buttons"))))});
this.printPreviewRepositoryItemComboBox1.DropDownRows = 11;
this.printPreviewRepositoryItemComboBox1.Name = "printPreviewRepositoryItemComboBox1";
//
// ZoomIn
//
this.ZoomIn.AccessibleDescription = null;
this.ZoomIn.AccessibleName = null;
resources.ApplyResources(this.ZoomIn, "ZoomIn");
this.ZoomIn.Command = DevExpress.XtraPrinting.PrintingSystemCommand.ZoomIn;
this.ZoomIn.Enabled = false;
this.ZoomIn.Id = 21;
this.ZoomIn.ImageIndex = 4;
this.ZoomIn.Name = "ZoomIn";
//
// biShowFirstPage
//
this.biShowFirstPage.AccessibleDescription = null;
this.biShowFirstPage.AccessibleName = null;
resources.ApplyResources(this.biShowFirstPage, "biShowFirstPage");
this.biShowFirstPage.Command = DevExpress.XtraPrinting.PrintingSystemCommand.ShowFirstPage;
this.biShowFirstPage.Enabled = false;
this.biShowFirstPage.Id = 22;
this.biShowFirstPage.ImageIndex = 7;
this.biShowFirstPage.Name = "biShowFirstPage";
//
// biShowPrevPage
//
this.biShowPrevPage.AccessibleDescription = null;
this.biShowPrevPage.AccessibleName = null;
resources.ApplyResources(this.biShowPrevPage, "biShowPrevPage");
this.biShowPrevPage.Command = DevExpress.XtraPrinting.PrintingSystemCommand.ShowPrevPage;
this.biShowPrevPage.Enabled = false;
this.biShowPrevPage.Id = 23;
this.biShowPrevPage.ImageIndex = 8;
this.biShowPrevPage.Name = "biShowPrevPage";
//
// biShowNextPage
//
this.biShowNextPage.AccessibleDescription = null;
this.biShowNextPage.AccessibleName = null;
resources.ApplyResources(this.biShowNextPage, "biShowNextPage");
this.biShowNextPage.Command = DevExpress.XtraPrinting.PrintingSystemCommand.ShowNextPage;
this.biShowNextPage.Enabled = false;
this.biShowNextPage.Id = 24;
this.biShowNextPage.ImageIndex = 9;
this.biShowNextPage.Name = "biShowNextPage";
//
// biShowLastPage
//
this.biShowLastPage.AccessibleDescription = null;
this.biShowLastPage.AccessibleName = null;
resources.ApplyResources(this.biShowLastPage, "biShowLastPage");
this.biShowLastPage.Command = DevExpress.XtraPrinting.PrintingSystemCommand.ShowLastPage;
this.biShowLastPage.Enabled = false;
this.biShowLastPage.Id = 25;
this.biShowLastPage.ImageIndex = 10;
this.biShowLastPage.Name = "biShowLastPage";
//
// biMultiplePages
//
this.biMultiplePages.AccessibleDescription = null;
this.biMultiplePages.AccessibleName = null;
this.biMultiplePages.ButtonStyle = DevExpress.XtraBars.BarButtonStyle.DropDown;
resources.ApplyResources(this.biMultiplePages, "biMultiplePages");
this.biMultiplePages.Command = DevExpress.XtraPrinting.PrintingSystemCommand.MultiplePages;
this.biMultiplePages.Enabled = false;
this.biMultiplePages.Id = 26;
this.biMultiplePages.ImageIndex = 11;
this.biMultiplePages.Name = "biMultiplePages";
//
// biFillBackground
//
this.biFillBackground.AccessibleDescription = null;
this.biFillBackground.AccessibleName = null;
this.biFillBackground.ButtonStyle = DevExpress.XtraBars.BarButtonStyle.DropDown;
resources.ApplyResources(this.biFillBackground, "biFillBackground");
this.biFillBackground.Command = DevExpress.XtraPrinting.PrintingSystemCommand.FillBackground;
this.biFillBackground.Enabled = false;
this.biFillBackground.Id = 27;
this.biFillBackground.ImageIndex = 12;
this.biFillBackground.Name = "biFillBackground";
//
// biExportFile
//
this.biExportFile.AccessibleDescription = null;
this.biExportFile.AccessibleName = null;
this.biExportFile.ButtonStyle = DevExpress.XtraBars.BarButtonStyle.DropDown;
resources.ApplyResources(this.biExportFile, "biExportFile");
this.biExportFile.Command = DevExpress.XtraPrinting.PrintingSystemCommand.ExportFile;
this.biExportFile.Enabled = false;
this.biExportFile.Id = 29;
this.biExportFile.ImageIndex = 18;
this.biExportFile.Name = "biExportFile";
//
// barStatus
//
this.barStatus.BarName = "Status Bar";
this.barStatus.CanDockStyle = DevExpress.XtraBars.BarCanDockStyle.Bottom;
this.barStatus.DockCol = 0;
this.barStatus.DockRow = 0;
this.barStatus.DockStyle = DevExpress.XtraBars.BarDockStyle.Bottom;
this.barStatus.LinksPersistInfo.AddRange(new DevExpress.XtraBars.LinkPersistInfo[] {
new DevExpress.XtraBars.LinkPersistInfo(this.biPage),
new DevExpress.XtraBars.LinkPersistInfo(this.barStaticItem1, true),
new DevExpress.XtraBars.LinkPersistInfo(this.biProgressBar),
new DevExpress.XtraBars.LinkPersistInfo(this.biStatusStatus),
new DevExpress.XtraBars.LinkPersistInfo(this.barButtonItem1),
new DevExpress.XtraBars.LinkPersistInfo(this.biStatusZoom, true)});
this.barStatus.OptionsBar.AllowQuickCustomization = false;
this.barStatus.OptionsBar.DrawDragBorder = false;
this.barStatus.OptionsBar.UseWholeRow = true;
resources.ApplyResources(this.barStatus, "barStatus");
//
// biPage
//
this.biPage.AccessibleDescription = null;
this.biPage.AccessibleName = null;
this.biPage.Border = DevExpress.XtraEditors.Controls.BorderStyles.NoBorder;
resources.ApplyResources(this.biPage, "biPage");
this.biPage.Id = 0;
this.biPage.LeftIndent = 1;
this.biPage.Name = "biPage";
this.biPage.RightIndent = 1;
this.biPage.TextAlignment = System.Drawing.StringAlignment.Near;
this.biPage.Type = "PageOfPages";
//
// barStaticItem1
//
this.barStaticItem1.AccessibleDescription = null;
this.barStaticItem1.AccessibleName = null;
this.barStaticItem1.Border = DevExpress.XtraEditors.Controls.BorderStyles.NoBorder;
resources.ApplyResources(this.barStaticItem1, "barStaticItem1");
this.barStaticItem1.Id = 1;
this.barStaticItem1.Name = "barStaticItem1";
this.barStaticItem1.TextAlignment = System.Drawing.StringAlignment.Near;
//
// biProgressBar
//
this.biProgressBar.AccessibleDescription = null;
this.biProgressBar.AccessibleName = null;
this.biProgressBar.Edit = this.repositoryItemProgressBar1;
this.biProgressBar.EditHeight = 12;
resources.ApplyResources(this.biProgressBar, "biProgressBar");
this.biProgressBar.Id = 2;
this.biProgressBar.Name = "biProgressBar";
this.biProgressBar.Visibility = DevExpress.XtraBars.BarItemVisibility.Never;
//
// repositoryItemProgressBar1
//
this.repositoryItemProgressBar1.AccessibleDescription = null;
this.repositoryItemProgressBar1.AccessibleName = null;
resources.ApplyResources(this.repositoryItemProgressBar1, "repositoryItemProgressBar1");
this.repositoryItemProgressBar1.Name = "repositoryItemProgressBar1";
//
// biStatusStatus
//
this.biStatusStatus.AccessibleDescription = null;
this.biStatusStatus.AccessibleName = null;
resources.ApplyResources(this.biStatusStatus, "biStatusStatus");
this.biStatusStatus.Command = DevExpress.XtraPrinting.PrintingSystemCommand.StopPageBuilding;
this.biStatusStatus.Enabled = false;
this.biStatusStatus.Id = 3;
this.biStatusStatus.Name = "biStatusStatus";
this.biStatusStatus.Visibility = DevExpress.XtraBars.BarItemVisibility.Never;
//
// barButtonItem1
//
this.barButtonItem1.AccessibleDescription = null;
this.barButtonItem1.AccessibleName = null;
this.barButtonItem1.Alignment = DevExpress.XtraBars.BarItemLinkAlignment.Left;
this.barButtonItem1.Enabled = false;
resources.ApplyResources(this.barButtonItem1, "barButtonItem1");
this.barButtonItem1.Id = 4;
this.barButtonItem1.Name = "barButtonItem1";
//
// biStatusZoom
//
this.biStatusZoom.AccessibleDescription = null;
this.biStatusZoom.AccessibleName = null;
this.biStatusZoom.Alignment = DevExpress.XtraBars.BarItemLinkAlignment.Right;
this.biStatusZoom.Border = DevExpress.XtraEditors.Controls.BorderStyles.NoBorder;
resources.ApplyResources(this.biStatusZoom, "biStatusZoom");
this.biStatusZoom.Id = 5;
this.biStatusZoom.Name = "biStatusZoom";
this.biStatusZoom.TextAlignment = System.Drawing.StringAlignment.Near;
this.biStatusZoom.Type = "ZoomFactor";
//
// barMainMenu
//
this.barMainMenu.BarName = "Main Menu";
this.barMainMenu.DockCol = 0;
this.barMainMenu.DockRow = 0;
this.barMainMenu.DockStyle = DevExpress.XtraBars.BarDockStyle.Top;
this.barMainMenu.OptionsBar.MultiLine = true;
this.barMainMenu.OptionsBar.UseWholeRow = true;
resources.ApplyResources(this.barMainMenu, "barMainMenu");
this.barMainMenu.Visible = false;
//
// printPreviewSubItem4
//
this.printPreviewSubItem4.AccessibleDescription = null;
this.printPreviewSubItem4.AccessibleName = null;
resources.ApplyResources(this.printPreviewSubItem4, "printPreviewSubItem4");
this.printPreviewSubItem4.Command = DevExpress.XtraPrinting.PrintingSystemCommand.PageLayout;
this.printPreviewSubItem4.Id = 35;
this.printPreviewSubItem4.LinksPersistInfo.AddRange(new DevExpress.XtraBars.LinkPersistInfo[] {
new DevExpress.XtraBars.LinkPersistInfo(this.printPreviewBarItem27),
new DevExpress.XtraBars.LinkPersistInfo(this.printPreviewBarItem28)});
this.printPreviewSubItem4.Name = "printPreviewSubItem4";
//
// printPreviewBarItem27
//
this.printPreviewBarItem27.AccessibleDescription = null;
this.printPreviewBarItem27.AccessibleName = null;
this.printPreviewBarItem27.ButtonStyle = DevExpress.XtraBars.BarButtonStyle.Check;
resources.ApplyResources(this.printPreviewBarItem27, "printPreviewBarItem27");
this.printPreviewBarItem27.Command = DevExpress.XtraPrinting.PrintingSystemCommand.PageLayoutFacing;
this.printPreviewBarItem27.Enabled = false;
this.printPreviewBarItem27.GroupIndex = 100;
this.printPreviewBarItem27.Id = 36;
this.printPreviewBarItem27.Name = "printPreviewBarItem27";
//
// printPreviewBarItem28
//
this.printPreviewBarItem28.AccessibleDescription = null;
this.printPreviewBarItem28.AccessibleName = null;
this.printPreviewBarItem28.ButtonStyle = DevExpress.XtraBars.BarButtonStyle.Check;
resources.ApplyResources(this.printPreviewBarItem28, "printPreviewBarItem28");
this.printPreviewBarItem28.Command = DevExpress.XtraPrinting.PrintingSystemCommand.PageLayoutContinuous;
this.printPreviewBarItem28.Enabled = false;
this.printPreviewBarItem28.GroupIndex = 100;
this.printPreviewBarItem28.Id = 37;
this.printPreviewBarItem28.Name = "printPreviewBarItem28";
//
// barToolbarsListItem1
//
this.barToolbarsListItem1.AccessibleDescription = null;
this.barToolbarsListItem1.AccessibleName = null;
resources.ApplyResources(this.barToolbarsListItem1, "barToolbarsListItem1");
this.barToolbarsListItem1.Id = 38;
this.barToolbarsListItem1.Name = "barToolbarsListItem1";
//
// biExportPdf
//
this.biExportPdf.AccessibleDescription = null;
this.biExportPdf.AccessibleName = null;
resources.ApplyResources(this.biExportPdf, "biExportPdf");
this.biExportPdf.Checked = true;
this.biExportPdf.Command = DevExpress.XtraPrinting.PrintingSystemCommand.ExportPdf;
this.biExportPdf.Enabled = false;
this.biExportPdf.GroupIndex = 1;
this.biExportPdf.Id = 39;
this.biExportPdf.Name = "biExportPdf";
//
// biExportHtm
//
this.biExportHtm.AccessibleDescription = null;
this.biExportHtm.AccessibleName = null;
resources.ApplyResources(this.biExportHtm, "biExportHtm");
this.biExportHtm.Command = DevExpress.XtraPrinting.PrintingSystemCommand.ExportHtm;
this.biExportHtm.Enabled = false;
this.biExportHtm.GroupIndex = 1;
this.biExportHtm.Id = 40;
this.biExportHtm.Name = "biExportHtm";
//
// biExportMht
//
this.biExportMht.AccessibleDescription = null;
this.biExportMht.AccessibleName = null;
resources.ApplyResources(this.biExportMht, "biExportMht");
this.biExportMht.Command = DevExpress.XtraPrinting.PrintingSystemCommand.ExportMht;
this.biExportMht.Enabled = false;
this.biExportMht.GroupIndex = 1;
this.biExportMht.Id = 41;
this.biExportMht.Name = "biExportMht";
//
// biExportRtf
//
this.biExportRtf.AccessibleDescription = null;
this.biExportRtf.AccessibleName = null;
resources.ApplyResources(this.biExportRtf, "biExportRtf");
this.biExportRtf.Command = DevExpress.XtraPrinting.PrintingSystemCommand.ExportRtf;
this.biExportRtf.Enabled = false;
this.biExportRtf.GroupIndex = 1;
this.biExportRtf.Id = 42;
this.biExportRtf.Name = "biExportRtf";
//
// biExportXls
//
this.biExportXls.AccessibleDescription = null;
this.biExportXls.AccessibleName = null;
resources.ApplyResources(this.biExportXls, "biExportXls");
this.biExportXls.Command = DevExpress.XtraPrinting.PrintingSystemCommand.ExportXls;
this.biExportXls.Enabled = false;
this.biExportXls.GroupIndex = 1;
this.biExportXls.Id = 43;
this.biExportXls.Name = "biExportXls";
//
// biExportCsv
//
this.biExportCsv.AccessibleDescription = null;
this.biExportCsv.AccessibleName = null;
resources.ApplyResources(this.biExportCsv, "biExportCsv");
this.biExportCsv.Command = DevExpress.XtraPrinting.PrintingSystemCommand.ExportCsv;
this.biExportCsv.Enabled = false;
this.biExportCsv.GroupIndex = 1;
this.biExportCsv.Id = 44;
this.biExportCsv.Name = "biExportCsv";
//
// biExportTxt
//
this.biExportTxt.AccessibleDescription = null;
this.biExportTxt.AccessibleName = null;
resources.ApplyResources(this.biExportTxt, "biExportTxt");
this.biExportTxt.Command = DevExpress.XtraPrinting.PrintingSystemCommand.ExportTxt;
this.biExportTxt.Enabled = false;
this.biExportTxt.GroupIndex = 1;
this.biExportTxt.Id = 45;
this.biExportTxt.Name = "biExportTxt";
//
// biExportGraphic
//
this.biExportGraphic.AccessibleDescription = null;
this.biExportGraphic.AccessibleName = null;
resources.ApplyResources(this.biExportGraphic, "biExportGraphic");
this.biExportGraphic.Command = DevExpress.XtraPrinting.PrintingSystemCommand.ExportGraphic;
this.biExportGraphic.Enabled = false;
this.biExportGraphic.GroupIndex = 1;
this.biExportGraphic.Id = 46;
this.biExportGraphic.Name = "biExportGraphic";
//
// printPreviewBarItem2
//
this.printPreviewBarItem2.AccessibleDescription = null;
this.printPreviewBarItem2.AccessibleName = null;
this.printPreviewBarItem2.ButtonStyle = DevExpress.XtraBars.BarButtonStyle.Check;
resources.ApplyResources(this.printPreviewBarItem2, "printPreviewBarItem2");
this.printPreviewBarItem2.Command = DevExpress.XtraPrinting.PrintingSystemCommand.PageSetup;
this.printPreviewBarItem2.Enabled = false;
this.printPreviewBarItem2.Id = 14;
this.printPreviewBarItem2.ImageIndex = 2;
this.printPreviewBarItem2.Name = "printPreviewBarItem2";
//
// timerScroll
//
this.timerScroll.Interval = 300;
this.timerScroll.Tick += new System.EventHandler(this.timerScroll_Tick);
//
// ReportView
//
this.AccessibleDescription = null;
this.AccessibleName = null;
resources.ApplyResources(this, "$this");
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.BackgroundImage = null;
this.Controls.Add(this.printControlReport);
this.DoubleBuffered = true;
this.Font = null;
this.Name = "ReportView";
((System.ComponentModel.ISupportInitialize)(this.printingSystemReports)).EndInit();
this.printControlReport.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.printBarManager)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.printPreviewRepositoryItemComboBox1)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.repositoryItemProgressBar1)).EndInit();
this.ResumeLayout(false);
}
#endregion
private DevExpress.XtraPrinting.PrintingSystem printingSystemReports;
private ReportPrintControl printControlReport;
private DevExpress.XtraPrinting.Preview.PrintBarManager printBarManager;
private DevExpress.XtraPrinting.Preview.PreviewBar previewBar1;
private DevExpress.XtraPrinting.Preview.PrintPreviewBarItem biFind;
private DevExpress.XtraPrinting.Preview.PrintPreviewBarItem biPrint;
private DevExpress.XtraPrinting.Preview.PrintPreviewBarItem biPrintDirect;
private DevExpress.XtraPrinting.Preview.PrintPreviewBarItem biPageSetup;
private DevExpress.XtraPrinting.Preview.PrintPreviewBarItem biScale;
private DevExpress.XtraPrinting.Preview.PrintPreviewBarItem biHandTool;
private DevExpress.XtraPrinting.Preview.PrintPreviewBarItem biMagnifier;
private DevExpress.XtraPrinting.Preview.PrintPreviewBarItem biZoomOut;
private DevExpress.XtraPrinting.Preview.ZoomBarEditItem biZoom;
private DevExpress.XtraPrinting.Preview.PrintPreviewRepositoryItemComboBox printPreviewRepositoryItemComboBox1;
private DevExpress.XtraPrinting.Preview.PrintPreviewBarItem ZoomIn;
private DevExpress.XtraPrinting.Preview.PrintPreviewBarItem biShowFirstPage;
private DevExpress.XtraPrinting.Preview.PrintPreviewBarItem biShowPrevPage;
private DevExpress.XtraPrinting.Preview.PrintPreviewBarItem biShowNextPage;
private DevExpress.XtraPrinting.Preview.PrintPreviewBarItem biShowLastPage;
private DevExpress.XtraPrinting.Preview.PrintPreviewBarItem biMultiplePages;
private DevExpress.XtraPrinting.Preview.PrintPreviewBarItem biFillBackground;
private DevExpress.XtraPrinting.Preview.PrintPreviewBarItem biExportFile;
private DevExpress.XtraPrinting.Preview.PreviewBar barStatus;
private DevExpress.XtraPrinting.Preview.PrintPreviewStaticItem biPage;
private DevExpress.XtraBars.BarStaticItem barStaticItem1;
private DevExpress.XtraPrinting.Preview.ProgressBarEditItem biProgressBar;
private DevExpress.XtraEditors.Repository.RepositoryItemProgressBar repositoryItemProgressBar1;
private DevExpress.XtraPrinting.Preview.PrintPreviewBarItem biStatusStatus;
private DevExpress.XtraBars.BarButtonItem barButtonItem1;
private DevExpress.XtraPrinting.Preview.PrintPreviewStaticItem biStatusZoom;
private DevExpress.XtraPrinting.Preview.PreviewBar barMainMenu;
private DevExpress.XtraPrinting.Preview.PrintPreviewSubItem printPreviewSubItem4;
private DevExpress.XtraPrinting.Preview.PrintPreviewBarItem printPreviewBarItem27;
private DevExpress.XtraPrinting.Preview.PrintPreviewBarItem printPreviewBarItem28;
private DevExpress.XtraBars.BarToolbarsListItem barToolbarsListItem1;
private DevExpress.XtraBars.BarDockControl barDockControlTop;
private DevExpress.XtraBars.BarDockControl barDockControlBottom;
private DevExpress.XtraBars.BarDockControl barDockControlLeft;
private DevExpress.XtraBars.BarDockControl barDockControlRight;
private DevExpress.XtraPrinting.Preview.PrintPreviewBarCheckItem biExportPdf;
private DevExpress.XtraPrinting.Preview.PrintPreviewBarCheckItem biExportHtm;
private DevExpress.XtraPrinting.Preview.PrintPreviewBarCheckItem biExportMht;
private DevExpress.XtraPrinting.Preview.PrintPreviewBarCheckItem biExportRtf;
private DevExpress.XtraPrinting.Preview.PrintPreviewBarCheckItem biExportXls;
private DevExpress.XtraPrinting.Preview.PrintPreviewBarCheckItem biExportCsv;
private DevExpress.XtraPrinting.Preview.PrintPreviewBarCheckItem biExportTxt;
private DevExpress.XtraPrinting.Preview.PrintPreviewBarCheckItem biExportGraphic;
private DevExpress.XtraPrinting.Preview.PrintPreviewBarItem printPreviewBarItem2;
private DevExpress.XtraBars.BarButtonItem biEdit;
private DevExpress.XtraBars.BarButtonItem biLoadDefault;
private System.Windows.Forms.Timer timerScroll;
}
} | 56.074968 | 186 | 0.647708 | [
"BSD-2-Clause"
] | EIDSS/EIDSS-Legacy | EIDSS v5/vb/EIDSS/EIDSS.Reports/BaseControls/ReportView.designer.cs | 44,131 | C# |
// Copyright (c) 2015 Alachisoft
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Alachisoft.NCache.Integrations.Memcached.ProxyServer.Commands;
using Alachisoft.NCache.Integrations.Memcached.ProxyServer.NetworkGateway;
using Alachisoft.NCache.Integrations.Memcached.ProxyServer.BinaryProtocol;
using Alachisoft.NCache.Integrations.Memcached.ProxyServer.Common;
using Alachisoft.NCache.Common.Stats;
namespace Alachisoft.NCache.Integrations.Memcached.ProxyServer.Parsing
{
class BinaryProtocolParser : ProtocolParser
{
private BinaryRequestHeader _requestHeader;
public BinaryProtocolParser(DataStream inputSream, MemTcpClient parent, LogManager logManager)
: base(inputSream, parent, logManager)
{
}
private int CommandDataSize
{
get { return _requestHeader == null ? 0 : _requestHeader.TotalBodyLenght; }
}
public override void StartParser()
{
try
{
int noOfBytes = 0;
bool go = true;
do
{
lock (this)
{
if (_inputDataStream.Lenght == 0 && this.State != ParserState.ReadyToDispatch)
{
this.Alive = false;
return;
}
}
switch (this.State)
{
case ParserState.Ready:
noOfBytes = _inputDataStream.Read(_rawData, _rawDataOffset, 24 - _rawDataOffset);
_rawDataOffset += noOfBytes;
if (_rawDataOffset == 24)
{
_rawDataOffset = 0;
this.Parse();
}
break;
case ParserState.WaitingForData:
noOfBytes = _inputDataStream.Read(_rawData, _rawDataOffset, this.CommandDataSize - _rawDataOffset);
_rawDataOffset += noOfBytes;
if (_rawDataOffset == this.CommandDataSize)
{
_rawDataOffset = 0;
this.Build();
}
break;
case ParserState.ReadyToDispatch:
_logManager.Debug("BinaryProtocolParser", _command.Opcode + " command recieved.");
ConsumerStatus executionMgrStatus = _commandConsumer.RegisterCommand(_command);//this.RegisterForExecution(_command);
this.State = ParserState.Ready;
go = executionMgrStatus == ConsumerStatus.Running;
break;
}
} while (go);
}
catch (Exception e)
{
_logManager.Fatal("BinaryProtocolParser", "Exception occured while parsing text command. " + e.Message);
TcpNetworkGateway.DisposeClient(_memTcpClient);
return;
}
this.Dispatch();
}
void Parse()
{
_requestHeader = new BinaryRequestHeader(_rawData);
this.State = ParserState.WaitingForData;
ProcessHeader();
}
void ProcessHeader()
{
bool valid = true;
if (_requestHeader.TotalBodyLenght < _requestHeader.KeyLength + _requestHeader.ExtraLength)
valid = false;
if (_requestHeader.MagicByte != Magic.Request)
valid = false;
if (!valid)
{
_requestHeader = new BinaryRequestHeader();
_requestHeader.Opcode = Opcode.Invalid_Command;
this.State = ParserState.ReadyToDispatch;
}
if (_requestHeader.TotalBodyLenght == 0)
this.Build();
}
void Build()
{
switch (_requestHeader.Opcode)
{
//Get command
case Opcode.Get:
//GetK command
case Opcode.GetK:
CreateGetCommand(_requestHeader.Opcode, false);
break;
//Set command
case Opcode.Set:
//Add command
case Opcode.Add:
//Replace command
case Opcode.Replace:
//Append command
case Opcode.Append:
//Prepend command
case Opcode.Prepend:
CreateStorageCommand(_requestHeader.Opcode, false);
break;
//Delete command
case Opcode.Delete:
CreateDeleteCommand(_requestHeader.Opcode, false);
break;
//Increment command
case Opcode.Increment:
//Decrement command
case Opcode.Decrement:
CreateCounterCommand(_requestHeader.Opcode, false);
break;
//Quit command
case Opcode.Quit:
_command = new QuitCommand(_requestHeader.Opcode);
break;
//Flush command
case Opcode.Flush:
CreateFlushCommand(_requestHeader.Opcode,false);
break;
//GetQ command
case Opcode.GetQ:
//GetKQ command
case Opcode.GetKQ:
CreateGetCommand(_requestHeader.Opcode, true);
break;
//No-op command
case Opcode.No_op:
_command = new NoOperationCommand();
break;
//Version command
case Opcode.Version:
CreateVersionCommand();
break;
//Stat command
case Opcode.Stat:
CreateStatsCommand();
break;
//SetQ command
case Opcode.SetQ:
//AddQ command
case Opcode.AddQ:
//ReplaceQ command
case Opcode.ReplaceQ:
//AppendQ command
case Opcode.AppendQ:
//PrependQ command
case Opcode.PrependQ:
CreateStorageCommand(_requestHeader.Opcode, true);
break;
//DeleteQ command
case Opcode.DeleteQ:
CreateDeleteCommand(_requestHeader.Opcode,true);
break;
//IncrementQ command
case Opcode.IncrementQ:
//DecrementQ command
case Opcode.DecrementQ:
CreateCounterCommand(_requestHeader.Opcode, true);
break;
//QuitQ command
case Opcode.QuitQ:
_command = new QuitCommand(_requestHeader.Opcode);
_command.NoReply = true;
break;
//FlushQ command
case Opcode.FlushQ:
CreateFlushCommand(_requestHeader.Opcode, true);
break;
default:
CreateInvalidCommand();
_command.Opcode = Opcode.unknown_command;
break;
}
_command.Opaque = _requestHeader.Opaque;
this.State = ParserState.ReadyToDispatch;
}
private void CreateStorageCommand(Opcode cmdType, bool noreply)
{
int offset = 0;
uint flags = 0;
long exp = 0;
switch (cmdType)
{
case Opcode.Append:
case Opcode.Prepend:
case Opcode.AppendQ:
case Opcode.PrependQ:
break;
default:
flags = MemcachedEncoding.BinaryConverter.ToUInt32(_rawData,offset);
exp = (long)MemcachedEncoding.BinaryConverter.ToInt32(_rawData,offset+4);;
offset += 8;
break;
}
string key = MemcachedEncoding.BinaryConverter.GetString(_rawData, offset, _requestHeader.KeyLength);
byte[] value = new byte[_requestHeader.ValueLength];
Buffer.BlockCopy(_rawData, _requestHeader.KeyLength + offset, value, 0, _requestHeader.ValueLength);
StorageCommand cmd = new StorageCommand(cmdType, key, flags, exp, _requestHeader.CAS, _requestHeader.ValueLength);
cmd.DataBlock = value;
cmd.NoReply = noreply;
cmd.Opaque = _requestHeader.Opaque;
_command = cmd;
}
private void CreateGetCommand(Opcode cmdType, bool noreply)
{
string key = MemcachedEncoding.BinaryConverter.GetString(_rawData, 0, _requestHeader.KeyLength);
GetCommand cmd = new GetCommand(cmdType);
cmd.Keys = new string[] { key };
cmd.NoReply = noreply;
_command = cmd;
}
private void CreateDeleteCommand(Opcode type, bool noreply)
{
string key = MemcachedEncoding.BinaryConverter.GetString(_rawData, 0, _requestHeader.KeyLength);
DeleteCommand cmd = new DeleteCommand(type);
cmd.Key = key;
cmd.NoReply = noreply;
_command = cmd;
}
private void CreateCounterCommand(Opcode cmdType, bool noreply)
{
CounterCommand cmd = new CounterCommand(cmdType);
cmd.Delta = MemcachedEncoding.BinaryConverter.ToUInt64(_rawData, 0);
cmd.InitialValue = MemcachedEncoding.BinaryConverter.ToUInt64(_rawData, 8);
cmd.ExpirationTimeInSeconds = (long)MemcachedEncoding.BinaryConverter.ToUInt32(_rawData, 16);
cmd.Key = MemcachedEncoding.BinaryConverter.GetString(_rawData, 20, _requestHeader.KeyLength);
cmd.CAS = _requestHeader.CAS;
cmd.NoReply = noreply;
_command = cmd;
}
public void CreateFlushCommand(Opcode type, bool noreply)
{
int delay = 0;
if (_requestHeader.ExtraLength > 0)
delay = ((_rawData[0] << 24) | (_rawData[1] << 16) | (_rawData[2] << 8) | _rawData[3]);
_command = new FlushCommand(type,delay);
_command.NoReply = noreply;
}
public void CreateVersionCommand()
{
_command = new VersionCommand();
}
public void CreateStatsCommand()
{
string argument = null;
if (_requestHeader.KeyLength > 0)
argument = MemcachedEncoding.BinaryConverter.GetString(_rawData, 0, _requestHeader.KeyLength);
_command = new StatsCommand(argument);
}
public void CreateVerbosityCommand()
{
int level = ((_rawData[0] << 24) | (_rawData[1] << 16) | (_rawData[2] << 8) | _rawData[3]);
_command = new VerbosityCommand(level);
}
public void CreateInvalidCommand()
{
_command = new InvalidCommand();
}
}
}
| 36.574018 | 145 | 0.517512 | [
"Apache-2.0"
] | NCacheDev/NCache | Integration/MemCached/ProxyServer/src/Alachisoft.NCache.Integrations.Memcached.ProxyServer/Parsing/BinaryProtocolParser.cs | 12,106 | C# |
//Copyright (c) Microsoft Corporation. All rights reserved.
using System;
using System.Xml;
using System.Xml.Schema;
using System.Xml.Linq;
using System.Collections.Generic;
using System.CodeDom;
using System.Diagnostics;
namespace Xml.Schema.Linq.CodeGen
{
internal abstract class TypePropertyBuilder {
protected CodeTypeDeclItems declItems;
protected CodeTypeDeclaration decl;
public TypePropertyBuilder(CodeTypeDeclaration decl, CodeTypeDeclItems declItems) {
this.decl = decl;
this.declItems = declItems;
}
public virtual void StartCodeGen() {
}
public virtual void GenerateCode(
ClrBasePropertyInfo property, List<ClrAnnotation> annotations)
{
property.AddToType(decl, annotations);
}
public virtual void EndCodeGen() {
//Do Nothing
}
public virtual bool IsRepeating {
get {
return false;
}
}
public static TypePropertyBuilder Create(GroupingInfo groupingInfo, CodeTypeDeclaration decl, CodeTypeDeclItems declItems) {
switch (groupingInfo.ContentModelType) {
case ContentModelType.None:
case ContentModelType.All:
return new DefaultPropertyBuilder(decl, declItems);
case ContentModelType.Sequence:
if (groupingInfo.IsComplex) {
return new DefaultPropertyBuilder(decl, declItems);
}
return new SequencePropertyBuilder(groupingInfo, decl, declItems);
case ContentModelType.Choice:
if (groupingInfo.IsComplex) {
return new DefaultPropertyBuilder(decl, declItems);
}
return new ChoicePropertyBuilder(groupingInfo, decl, declItems);
default:
throw new InvalidOperationException();
}
}
public static TypePropertyBuilder Create(CodeTypeDeclaration decl, CodeTypeDeclItems declItems) {
return new DefaultPropertyBuilder(decl, declItems);
}
}
internal abstract class ContentModelPropertyBuilder : TypePropertyBuilder {
protected GroupingInfo grouping;
protected CodeObjectCreateExpression contentModelExpression;
public ContentModelPropertyBuilder(GroupingInfo grouping, CodeTypeDeclaration decl, CodeTypeDeclItems declItems) : base(decl, declItems) {
this.grouping = grouping; //The grouping the contentmodelbuilder works on
}
public abstract CodeObjectCreateExpression CreateContentModelExpression();
public virtual void GenerateConstructorCode(ClrBasePropertyInfo property) {
//Do nothing for sequences and all
}
public override void StartCodeGen() {
AddToContentModel();
}
public override void GenerateCode(ClrBasePropertyInfo property, List<ClrAnnotation> annotations) {
GenerateConstructorCode(property);
property.AddToType(decl, annotations);
if (!declItems.hasElementWildCards) property.AddToContentModel(contentModelExpression);
}
private void AddToContentModel() {
contentModelExpression = CreateContentModelExpression();
CodeObjectCreateExpression typeContentModelExp = declItems.contentModelExpression;
if (typeContentModelExp == null) {
declItems.contentModelExpression = contentModelExpression;
}
else {
typeContentModelExp.Parameters.Add(contentModelExpression);
}
}
}
internal class SequencePropertyBuilder : ContentModelPropertyBuilder {
public SequencePropertyBuilder(GroupingInfo grouping, CodeTypeDeclaration decl, CodeTypeDeclItems declItems) : base(grouping, decl, declItems) {
}
public override CodeObjectCreateExpression CreateContentModelExpression() {
return new CodeObjectCreateExpression(new CodeTypeReference(Constants.SequenceContentModelEntity));
}
}
internal class ChoicePropertyBuilder : ContentModelPropertyBuilder {
List<CodeConstructor> choiceConstructors;
bool flatChoice; //No nested groups, no child groups and not repeating
bool hasDuplicateType;
Dictionary<string, ClrBasePropertyInfo> propertyTypeNameTable;
public ChoicePropertyBuilder(GroupingInfo grouping, CodeTypeDeclaration decl, CodeTypeDeclItems declItems) : base(grouping, decl, declItems) {
flatChoice = !grouping.IsNested && !grouping.IsRepeating && !grouping.HasChildGroups;
hasDuplicateType = false;
if (flatChoice) {
propertyTypeNameTable = new Dictionary<string,ClrBasePropertyInfo>();
}
}
public override void GenerateConstructorCode(ClrBasePropertyInfo property) {
if (flatChoice && !hasDuplicateType && property.ContentType != ContentType.WildCardProperty) {
ClrBasePropertyInfo prevProperty = null;
string propertyReturnType = property.ClrTypeName;
if (propertyTypeNameTable.TryGetValue(propertyReturnType, out prevProperty)) {
hasDuplicateType = true;
return;
}
else {
propertyTypeNameTable.Add(propertyReturnType, property);
}
if (choiceConstructors == null) {
choiceConstructors = new List<CodeConstructor>();
}
CodeConstructor choiceConstructor = CodeDomHelper.CreateConstructor(MemberAttributes.Public);
property.AddToConstructor(choiceConstructor);
choiceConstructors.Add(choiceConstructor);
}
}
public override void EndCodeGen() {
if (choiceConstructors != null && !hasDuplicateType) {
foreach(CodeConstructor choiceConst in choiceConstructors) {
decl.Members.Add(choiceConst);
}
}
}
public override CodeObjectCreateExpression CreateContentModelExpression() {
return new CodeObjectCreateExpression(new CodeTypeReference(Constants.ChoiceContentModelEntity));
}
}
internal class DefaultPropertyBuilder : TypePropertyBuilder {
internal DefaultPropertyBuilder(CodeTypeDeclaration decl, CodeTypeDeclItems declItems) : base(decl, declItems) {
}
}
} | 39.855491 | 153 | 0.624656 | [
"MIT"
] | omatrot/LinqToEdmx | LinqToXsd/Src/PropertyBuilder.cs | 6,895 | C# |
/*
* Copyright 2018 Randy Lynn, Zach Jones. 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 Liense 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.
*
*
* Original Author in JAVA: Ben Manes (ben.manes@gmail.com)
* Ported to C# .NET by: Randy Lynn (randy.lynn.klex@gmail.com), Zach Jones (zachary.b.jones@gmail.com)
*
*/
using System.Collections.Specialized;
using System.Collections.Generic;
namespace Caffeine.Cache
{
public interface IExpiration<K, V>
{
/// <summary>
/// Returns the age of the entry based on the expiration policy. The entry's age is the cache's
/// estimate of the amount of time since the entry's expiration was last reset.
///
/// An expiration policy uses the age to determine if an entry is fresh or stale by comparing
/// it to the freshness lifetime. This is calculated as <code>fresh = freshnessLifetime > age;</code>
/// where <code>freshnessLifetime = expires - currentTime;</code>
/// </summary>
/// <param name="key">key for the entry being queried</param>
/// <returns>the age if the entry is present in the cache</returns>
long? AgeOf(K key);
/// <summary>
/// Returns the fixed duration used to determine if an entry should be automatically removed due
/// to elapsing this time bound. An entry is considered fresh if its age is less than this duration,
/// and stale otherwise. The expiration policy determines when the entry's age is reset.
///
/// value is always expressed in nanoseconds.
/// </summary>
long ExpiresAfter { get; set; }
/// <summary>
/// Returns a snapshot <see cref="IOrderedDictionary"/> view of the cache with ordered
/// traversal. The order of iteration is from the entries most likely to expire (oldest)
/// to the entries least likely to expire (youngest). This order is determined by the expiration
/// policy's best guess at the time of creating this snapshot view.
/// </summary>
/// <param name="limit"></param>
/// <returns></returns>
IOrderedDictionary Oldest(uint limit);
/// <summary>
/// Returns a snapshot <see cref="Dictionary{TKey, TValue}"/> view of the cache with ordered
/// traversal. The order of iteration is from the entries least likely to expire (youngest)
/// to the entries most likely to expire (oldest). This order is determined by the
/// expiration policy's best guess at the time of creating this snapshot view.
/// </summary>
/// <param name="limit"></param>
/// <returns></returns>
IOrderedDictionary Youngest(uint limit);
}
}
| 45.408451 | 109 | 0.657568 | [
"Apache-2.0"
] | randyklex/caffeine.net | Caffeine.Cache/Interfaces/IExpiration.cs | 3,226 | C# |
using Microsoft.EntityFrameworkCore.Migrations;
using System;
namespace Aiursoft.Gateway.Migrations
{
public partial class AddBindTimeForThirdParty : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<DateTime>(
name: "BindTime",
table: "ThirdPartyAccounts",
nullable: false,
defaultValue: new DateTime(2019, 1, 1, 0, 0, 0, 0, DateTimeKind.Unspecified));
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "BindTime",
table: "ThirdPartyAccounts");
}
}
}
| 29.64 | 94 | 0.605938 | [
"MIT"
] | AiursoftWeb/Infrastructures | src/WebServices/Basic/Gateway/Migrations/20191023101519_AddBindTimeForThirdParty.cs | 743 | C# |
#if !UNITY_METRO
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using UtyRx.InternalUtil;
namespace UtyRx
{
public static partial class Scheduler
{
public static readonly IScheduler ThreadPool = new ThreadPoolScheduler();
class ThreadPoolScheduler : IScheduler, ISchedulerPeriodic, ISchedulerQueueing
{
public ThreadPoolScheduler()
{
}
public DateTimeOffset Now
{
get { return Scheduler.Now; }
}
public IDisposable Schedule(Action action)
{
var d = new BooleanDisposable();
System.Threading.ThreadPool.QueueUserWorkItem(_ =>
{
if (!d.IsDisposed)
{
action();
}
});
return d;
}
public IDisposable Schedule(DateTimeOffset dueTime, Action action)
{
return Schedule(dueTime - Now, action);
}
public IDisposable Schedule(TimeSpan dueTime, Action action)
{
return new Timer(dueTime, action);
}
public IDisposable SchedulePeriodic(TimeSpan period, Action action)
{
return new PeriodicTimer(period, action);
}
public void ScheduleQueueing<T>(ICancelable cancel, T state, Action<T> action)
{
System.Threading.ThreadPool.QueueUserWorkItem(callBackState =>
{
if (!cancel.IsDisposed)
{
action((T)callBackState);
}
}, state);
}
// timer was borrwed from Rx Official
sealed class Timer : IDisposable
{
static readonly HashSet<System.Threading.Timer> s_timers = new HashSet<System.Threading.Timer>();
private readonly SingleAssignmentDisposable _disposable;
private Action _action;
private System.Threading.Timer _timer;
private bool _hasAdded;
private bool _hasRemoved;
public Timer(TimeSpan dueTime, Action action)
{
_disposable = new SingleAssignmentDisposable();
_disposable.Disposable = Disposable.Create(Unroot);
_action = action;
_timer = new System.Threading.Timer(Tick, null, dueTime, TimeSpan.FromMilliseconds(System.Threading.Timeout.Infinite));
lock (s_timers)
{
if (!_hasRemoved)
{
s_timers.Add(_timer);
_hasAdded = true;
}
}
}
private void Tick(object state)
{
try
{
if (!_disposable.IsDisposed)
{
_action();
}
}
finally
{
Unroot();
}
}
private void Unroot()
{
_action = Stubs.Nop;
var timer = default(System.Threading.Timer);
lock (s_timers)
{
if (!_hasRemoved)
{
timer = _timer;
_timer = null;
if (_hasAdded && timer != null)
s_timers.Remove(timer);
_hasRemoved = true;
}
}
if (timer != null)
timer.Dispose();
}
public void Dispose()
{
_disposable.Dispose();
}
}
sealed class PeriodicTimer : IDisposable
{
static readonly HashSet<System.Threading.Timer> s_timers = new HashSet<System.Threading.Timer>();
private Action _action;
private System.Threading.Timer _timer;
private readonly AsyncLock _gate;
public PeriodicTimer(TimeSpan period, Action action)
{
this._action = action;
this._timer = new System.Threading.Timer(Tick, null, period, period);
this._gate = new AsyncLock();
lock (s_timers)
{
s_timers.Add(_timer);
}
}
private void Tick(object state)
{
_gate.Wait(() =>
{
_action();
});
}
public void Dispose()
{
var timer = default(System.Threading.Timer);
lock (s_timers)
{
timer = _timer;
_timer = null;
if (timer != null)
s_timers.Remove(timer);
}
if (timer != null)
{
timer.Dispose();
_action = Stubs.Nop;
}
}
}
}
}
}
#endif | 29.248731 | 139 | 0.405762 | [
"Apache-2.0"
] | reinterpretcat/csharp-libs | utyrx/UtyRx/Schedulers/Scheduler.ThreadPool.cs | 5,764 | C# |
using UnityEngine;
using System.Collections;
using AssetBundles.Manager;
public class LoadVariants : MonoBehaviour
{
const string variantSceneAssetBundle = "variants/variant-scene";
const string variantSceneName = "VariantScene";
private string[] activeVariants;
private bool bundlesLoaded; // used to remove the loading buttons
void Awake ()
{
activeVariants = new string[1];
bundlesLoaded = false;
}
void OnGUI ()
{
if (!bundlesLoaded)
{
GUILayout.Space (20);
GUILayout.BeginHorizontal ();
GUILayout.Space (20);
GUILayout.BeginVertical ();
if (GUILayout.Button ("Load SD"))
{
activeVariants[0] = "sd";
bundlesLoaded = true;
StartCoroutine (BeginExample ());
BeginExample ();
}
GUILayout.Space (5);
if (GUILayout.Button ("Load HD"))
{
activeVariants[0] = "hd";
bundlesLoaded = true;
StartCoroutine (BeginExample ());
Debug.Log ("Loading HD");
}
GUILayout.EndVertical ();
GUILayout.EndHorizontal ();
}
}
// Use this for initialization
IEnumerator BeginExample ()
{
yield return StartCoroutine(Initialize() );
// Set active variants.
AssetBundleManager.ActiveVariants = activeVariants;
// Load variant level which depends on variants.
yield return StartCoroutine(InitializeLevelAsync (variantSceneName, true) );
}
// Initialize the downloading url and AssetBundleManifest object.
protected IEnumerator Initialize()
{
// Don't destroy this gameObject as we depend on it to run the loading script.
DontDestroyOnLoad(gameObject);
// Initialize AssetBundleManifest which loads the AssetBundleManifest object.
var request = AssetBundleManager.Initialize();
if (request != null)
yield return StartCoroutine(request);
}
protected IEnumerator InitializeLevelAsync (string levelName, bool isAdditive)
{
// This is simply to get the elapsed time for this phase of AssetLoading.
float startTime = Time.realtimeSinceStartup;
// Load level from assetBundle.
AssetBundleLoadOperation request = AssetBundleManager.LoadLevelAsync(variantSceneAssetBundle, levelName, isAdditive);
if (request == null)
yield break;
yield return StartCoroutine(request);
// Calculate and display the elapsed time.
float elapsedTime = Time.realtimeSinceStartup - startTime;
Debug.Log("Finished loading scene " + levelName + " in " + elapsedTime + " seconds" );
}
}
| 26.988764 | 119 | 0.721482 | [
"MIT"
] | hiroki-o/SimpleABGTExample | Assets/AssetBundleSample/Scripts/LoadVariants.cs | 2,404 | C# |
using System;
using NetRuntimeSystem = System;
using System.Runtime.InteropServices;
using System.ComponentModel;
using System.Runtime.CompilerServices;
using System.Reflection;
using System.Collections.Generic;
using System.Collections;
using NetOffice;
namespace NetOffice.ExcelApi
{
///<summary>
/// Interface IPoints
/// SupportByVersion Excel, 9,10,11,12,14,15,16
///</summary>
[SupportByVersionAttribute("Excel", 9,10,11,12,14,15,16)]
[EntityTypeAttribute(EntityType.IsInterface)]
public class IPoints : COMObject ,IEnumerable<NetOffice.ExcelApi.Point>
{
#pragma warning disable
#region Type Information
private static Type _type;
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public static Type LateBindingApiWrapperType
{
get
{
if (null == _type)
_type = typeof(IPoints);
return _type;
}
}
#endregion
#region Construction
///<param name="factory">current used factory core</param>
///<param name="parentObject">object there has created the proxy</param>
///<param name="comProxy">inner wrapped COM proxy</param>
public IPoints(Core factory, COMObject parentObject, object comProxy) : base(factory, parentObject, comProxy)
{
}
///<param name="parentObject">object there has created the proxy</param>
///<param name="comProxy">inner wrapped COM proxy</param>
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public IPoints(COMObject parentObject, object comProxy) : base(parentObject, comProxy)
{
}
///<param name="factory">current used factory core</param>
///<param name="parentObject">object there has created the proxy</param>
///<param name="comProxy">inner wrapped COM proxy</param>
///<param name="comProxyType">Type of inner wrapped COM proxy"</param>
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public IPoints(Core factory, COMObject parentObject, object comProxy, NetRuntimeSystem.Type comProxyType) : base(factory, parentObject, comProxy, comProxyType)
{
}
///<param name="parentObject">object there has created the proxy</param>
///<param name="comProxy">inner wrapped COM proxy</param>
///<param name="comProxyType">Type of inner wrapped COM proxy"</param>
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public IPoints(COMObject parentObject, object comProxy, NetRuntimeSystem.Type comProxyType) : base(parentObject, comProxy, comProxyType)
{
}
///<param name="replacedObject">object to replaced. replacedObject are not usable after this action</param>
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public IPoints(COMObject replacedObject) : base(replacedObject)
{
}
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public IPoints() : base()
{
}
/// <param name="progId">registered ProgID</param>
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public IPoints(string progId) : base(progId)
{
}
#endregion
#region Properties
/// <summary>
/// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16
/// Get
/// </summary>
[SupportByVersionAttribute("Excel", 9,10,11,12,14,15,16)]
public NetOffice.ExcelApi.Application Application
{
get
{
object[] paramsArray = null;
object returnItem = Invoker.PropertyGet(this, "Application", paramsArray);
NetOffice.ExcelApi.Application newObject = Factory.CreateKnownObjectFromComProxy(this,returnItem,NetOffice.ExcelApi.Application.LateBindingApiWrapperType) as NetOffice.ExcelApi.Application;
return newObject;
}
}
/// <summary>
/// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16
/// Get
/// </summary>
[SupportByVersionAttribute("Excel", 9,10,11,12,14,15,16)]
public NetOffice.ExcelApi.Enums.XlCreator Creator
{
get
{
object[] paramsArray = null;
object returnItem = Invoker.PropertyGet(this, "Creator", paramsArray);
int intReturnItem = NetRuntimeSystem.Convert.ToInt32(returnItem);
return (NetOffice.ExcelApi.Enums.XlCreator)intReturnItem;
}
}
/// <summary>
/// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16
/// Get
/// Unknown COM Proxy
/// </summary>
[SupportByVersionAttribute("Excel", 9,10,11,12,14,15,16)]
public object Parent
{
get
{
object[] paramsArray = null;
object returnItem = Invoker.PropertyGet(this, "Parent", paramsArray);
COMObject newObject = Factory.CreateObjectFromComProxy(this,returnItem);
return newObject;
}
}
/// <summary>
/// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16
/// Get
/// </summary>
[SupportByVersionAttribute("Excel", 9,10,11,12,14,15,16)]
public Int32 Count
{
get
{
object[] paramsArray = null;
object returnItem = Invoker.PropertyGet(this, "Count", paramsArray);
return NetRuntimeSystem.Convert.ToInt32(returnItem);
}
}
#endregion
#region Methods
/// <summary>
/// SupportByVersion Excel 12, 14, 15, 16
///
/// </summary>
/// <param name="index">Int32 Index</param>
[SupportByVersionAttribute("Excel", 12,14,15,16)]
[NetRuntimeSystem.Runtime.CompilerServices.IndexerName("Item")]
public NetOffice.ExcelApi.Point this[Int32 index]
{
get
{
object[] paramsArray = Invoker.ValidateParamsArray(index);
object returnItem = Invoker.MethodReturn(this, "_Default", paramsArray);
NetOffice.ExcelApi.Point newObject = Factory.CreateKnownObjectFromComProxy(this, returnItem,NetOffice.ExcelApi.Point.LateBindingApiWrapperType) as NetOffice.ExcelApi.Point;
return newObject;
}
}
#endregion
#region IEnumerable<NetOffice.ExcelApi.Point> Member
/// <summary>
/// SupportByVersionAttribute Excel, 9,10,11,12,14,15,16
/// </summary>
[SupportByVersionAttribute("Excel", 9,10,11,12,14,15,16)]
public IEnumerator<NetOffice.ExcelApi.Point> GetEnumerator()
{
NetRuntimeSystem.Collections.IEnumerable innerEnumerator = (this as NetRuntimeSystem.Collections.IEnumerable);
foreach (NetOffice.ExcelApi.Point item in innerEnumerator)
yield return item;
}
#endregion
#region IEnumerable Members
/// <summary>
/// SupportByVersionAttribute Excel, 9,10,11,12,14,15,16
/// </summary>
[SupportByVersionAttribute("Excel", 9,10,11,12,14,15,16)]
IEnumerator NetRuntimeSystem.Collections.IEnumerable.GetEnumerator()
{
return NetOffice.Utils.GetProxyEnumeratorAsMethod(this);
}
#endregion
#pragma warning restore
}
} | 31.683962 | 193 | 0.690636 | [
"MIT"
] | Engineerumair/NetOffice | Source/Excel/Interfaces/IPoints.cs | 6,719 | C# |
//-----------------------------------------------------------------------
// <copyright file="Dial180South.xaml.cs" company="David Black">
// Copyright 2008 David Black
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>
//-----------------------------------------------------------------------
namespace Codeplex.Dashboarding
{
using System;
using System.Diagnostics.CodeAnalysis;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
/// <summary>
/// A needle and dial face control where the needle sweeps a 180 degree path from west to east. A Dial180 can be instantiated
/// in XAML or in code.
/// </summary>
public partial class Dial180South : Dial180
{
/// <summary>
/// Initializes a new instance of the <see cref="Dial180South"/> class.
/// </summary>
public Dial180South()
{
InitializeComponent();
InitializeDial180();
}
/// <summary>
/// Gets the resource root. This allow us to access the Storyboards in a Silverlight/WPf
/// neutral manner
/// </summary>
/// <value>The resource root.</value>
protected override FrameworkElement ResourceRoot
{
get { return LayoutRoot; }
}
/// <summary>
/// Determines the angle of the needle based on the mouse
/// position.
/// </summary>
/// <param name="currentPoint">Mouse position</param>
/// <returns>The angle in degrees</returns>
protected override double CalculateRotationAngle(Point currentPoint)
{
double opposite = currentPoint.Y -6;
opposite = opposite > 0 ? opposite : 0;
double adjacent = (ActualWidth / 2) - currentPoint.X;
double tan = opposite / adjacent;
double angleInDegrees = Math.Atan(tan) * (180.0 / Math.PI);
if (angleInDegrees < 0)
{
angleInDegrees = 180 + angleInDegrees;
}
////_debug.Text = String.Format("{0:0.0} {1:0.0} {2:0.0}", opposite, adjacent, angleInDegrees);
return angleInDegrees;
}
/// <summary>
/// Calculate the rotation angle from the normalized actual value
/// </summary>
/// <returns>
/// angle in degrees to position the transform
/// </returns>
protected override double CalculatePointFromNormalisedValue()
{
return 90 - (NormalizedValue * 180);
}
/// <summary>
/// Calculate the rotation angle from the normalized current value
/// </summary>
/// <returns>
/// angle in degrees to position the transform
/// </returns>
protected override double CalculatePointFromCurrentNormalisedValue()
{
return 90 - (CurrentNormalizedValue * 180);
}
}
}
| 37.16 | 130 | 0.55436 | [
"Apache-2.0"
] | dotnetprojects/Dashboarding | Codeplex.Dashboarding/Dial180South.xaml.cs | 3,718 | C# |
using DevExpress.ExpressApp.Model;
namespace Xpand.Extensions.XAF.ModelExtensions {
public static partial class ModelExtensions {
public static IModelSources Sources(this IModelApplication application) => ((IModelSources)application);
}
} | 36.428571 | 112 | 0.780392 | [
"Apache-2.0"
] | eXpandFramework/DevExpress.XAF | src/Extensions/Xpand.Extensions.XAF/ModelExtensions/Sources.cs | 255 | C# |
// Copyright 2021 Google LLC
//
// 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
//
// https://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.
// Generated code. DO NOT EDIT!
namespace Google.Cloud.Dialogflow.V2beta1.Snippets
{
using Google.Cloud.Dialogflow.V2beta1;
using System.Threading.Tasks;
public sealed partial class GeneratedConversationsClientStandaloneSnippets
{
/// <summary>Snippet for CreateConversationAsync</summary>
/// <remarks>
/// This snippet has been automatically generated for illustrative purposes only.
/// It may require modifications to work in your environment.
/// </remarks>
public async Task CreateConversationAsync()
{
// Create client
ConversationsClient conversationsClient = await ConversationsClient.CreateAsync();
// Initialize request argument(s)
string parent = "projects/[PROJECT]";
Conversation conversation = new Conversation();
// Make the request
Conversation response = await conversationsClient.CreateConversationAsync(parent, conversation);
}
}
}
| 39.292683 | 108 | 0.697703 | [
"Apache-2.0"
] | googleapis/googleapis-gen | google/cloud/dialogflow/v2beta1/google-cloud-dialogflow-v2beta1-csharp/Google.Cloud.Dialogflow.V2beta1.StandaloneSnippets/ConversationsClient.CreateConversationAsyncSnippet.g.cs | 1,611 | C# |
namespace SLW.ClientBase.Mixer.Video
{
public enum CanvasStyle : byte
{
Empty,
Image,
Video,
String
}
}
| 13.727273 | 37 | 0.516556 | [
"BSD-2-Clause"
] | 7956968/gb28181-sip | GB28181.Client/Player/Mixer/Video/CanvasStyle.cs | 153 | C# |
using Autofac;
using Company.BLL;
using Company.IBLL;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Company.BLLContainer
{
public class Container
{
/// <summary>
/// IOC 容器
/// </summary>
public static IContainer container = null;
/// <summary>
/// 获取 IDal 的实例化对象
/// </summary>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
public static T Resolve<T>()
{
try
{
if (container == null)
{
Initialise();
}
}
catch (System.Exception ex)
{
throw new System.Exception("IOC实例化出错!" + ex.Message);
}
return container.Resolve<T>();
}
/// <summary>
/// 初始化
/// </summary>
public static void Initialise()
{
var builder = new ContainerBuilder();
//格式:builder.RegisterType<xxxx>().As<Ixxxx>().InstancePerLifetimeScope();
builder.RegisterType<StaffService>().As<IStaffService>().InstancePerLifetimeScope();
container = builder.Build();
}
}
}
| 24.074074 | 96 | 0.504615 | [
"MIT"
] | Huzc15717/MVC_EF_DB | Company.BLLContainer/Container.cs | 1,344 | C# |
using System.IO;
using Veldrid;
namespace Toe.ContentPipeline.VeldridMesh
{
internal interface IStreamAccessor
{
VertexElementFormat VertexElementFormat { get; }
VertexElementSemantic VertexElementSemantic { get; }
int Count { get; }
void Write(int index, BinaryWriter stream);
}
} | 25.153846 | 60 | 0.69419 | [
"MIT"
] | gleblebedev/TinyOpenEngine | src/Toe.ContentPipeline.VeldridMesh/IStreamAccessor.cs | 329 | C# |
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Xml.Serialization;
using NewLife.Collections;
using NewLife.Reflection;
namespace NewLife.Serialization
{
/// <summary>二进制名值对</summary>
public class BinaryPair : BinaryHandlerBase
{
#region 构造
/// <summary>初始化</summary>
public BinaryPair()
{
// 优先级
Priority = 15;
}
#endregion
#region 核心方法
/// <summary>写入一个对象</summary>
/// <param name="value">目标对象</param>
/// <param name="type">类型</param>
/// <returns></returns>
public override Boolean Write(Object value, Type type)
{
// 不支持基本类型
if (Type.GetTypeCode(type) != TypeCode.Object) return false;
// 不写空名值对
if (value == null) return true;
//todo 名值对还不能很好的支持数组
if (WriteDictionary(value, type)) return true;
if (WriteArray(value, type)) return true;
if (WriteObject(value, type)) return true;
return false;
}
/// <summary>尝试读取指定类型对象</summary>
/// <param name="type"></param>
/// <param name="value"></param>
/// <returns></returns>
public override Boolean TryRead(Type type, ref Object value)
{
if (type == null)
{
if (value == null) return false;
type = value.GetType();
}
if (TryReadDictionary(type, ref value)) return true;
if (TryReadArray(type, ref value)) return true;
if (TryReadObject(type, ref value)) return true;
return false;
}
#endregion
#region 原始读写名值对
/// <summary>写入名值对</summary>
/// <param name="name"></param>
/// <param name="value"></param>
public Boolean WritePair(String name, Object value)
{
if (value == null) return true;
var host = Host;
// 检测循环引用。名值对不支持循环引用
var hs = host.Hosts.ToArray();
if (hs.Contains(value)) return true;
var type = value.GetType();
Byte[] buf = null;
if (value is String)
buf = (value as String).GetBytes(host.Encoding);
else if (value is Byte[])
buf = (Byte[])value;
else
{
// 准备好名值对再一起写入。为了得到数据长度,需要提前计算好数据长度,所以需要临时切换数据流
var ms = Pool.MemoryStream.Get();
var old = host.Stream;
host.Stream = ms;
var rs = host.Write(value, type);
host.Stream = old;
if (!rs) return false;
buf = ms.Put(true);
}
WriteLog(" WritePair {0}\t= {1}", name, value);
// 开始写入
var key = name.GetBytes(host.Encoding);
if (!host.Write(key, key.GetType())) return false;
if (!host.Write(buf, buf.GetType())) return false;
return true;
}
/// <summary>读取原始名值对</summary>
/// <returns></returns>
public IDictionary<String, Byte[]> ReadPair() => ReadPair(Host.Stream, Host.Encoding);
/// <summary>读取原始名值对</summary>
/// <param name="ms">数据流</param>
/// <param name="encoding">编码</param>
/// <returns></returns>
public static IDictionary<String, Byte[]> ReadPair(Stream ms, Encoding encoding = null)
{
var dic = new Dictionary<String, Byte[]>();
while (ms.Position < ms.Length)
{
var len = ms.ReadEncodedInt();
if (len > ms.Length - ms.Position) break;
var name = ms.ReadBytes(len).ToStr(encoding);
// 避免名称为空导致dic[name]报错
name += "";
len = ms.ReadEncodedInt();
if (len > ms.Length - ms.Position) break;
dic[name] = ms.ReadBytes(len);
}
return dic;
}
/// <summary>从原始名值对读取数据</summary>
/// <param name="dic"></param>
/// <param name="name"></param>
/// <param name="type"></param>
/// <param name="value"></param>
/// <returns></returns>
public Boolean TryReadPair(IDictionary<String, Byte[]> dic, String name, Type type, ref Object value)
{
if (!dic.TryGetValue(name, out var buf)) return false;
if (type == null)
{
if (value == null) return false;
type = value.GetType();
}
WriteLog(" TryReadPair {0}\t= {1}", name, buf.ToHex("-", 0, 32));
if (type == typeof(String))
{
value = buf.ToStr(Host.Encoding);
WriteLog(" " + value + "");
return true;
}
if (type == typeof(Byte[]))
{
value = buf;
return true;
}
var old = Host.Stream;
Host.Stream = new MemoryStream(buf);
try
{
return Host.TryRead(type, ref value);
}
finally
{
Host.Stream = old;
WriteLog(" {0}".F(value));
}
}
#endregion
#region 字典名值对
private Boolean WriteDictionary(Object value, Type type)
{
if (!type.As<IDictionary>() && !(value is IDictionary)) return false;
var dic = value as IDictionary;
var gs = type.GetGenericArguments();
if (gs.Length != 2) throw new NotSupportedException("字典类型仅支持 {0}".F(typeof(Dictionary<,>).FullName));
if (gs[0] != typeof(String)) throw new NotSupportedException("字典类型仅支持Key=String的名值对");
foreach (DictionaryEntry item in dic)
{
WritePair(item.Key as String, item.Value);
}
return true;
}
private Boolean TryReadDictionary(Type type, ref Object value)
{
if (!type.As<IDictionary>()) return false;
// 子元素类型
var gs = type.GetGenericArguments();
if (gs.Length != 2) throw new NotSupportedException("字典类型仅支持 {0}".F(typeof(Dictionary<,>).FullName));
var keyType = gs[0];
var valType = gs[1];
// 创建字典
if (value == null && type != null)
{
value = type.CreateInstance();
}
var dic = value as IDictionary;
if (keyType != typeof(String)) throw new NotSupportedException("字典类型仅支持Key=String的名值对");
var ds = ReadPair();
foreach (var item in ds)
{
Object v = null;
if (TryReadPair(ds, item.Key, valType, ref v))
dic[item.Key] = v;
}
return true;
}
#endregion
#region 数组名值对
private Boolean WriteArray(Object value, Type type)
{
if (!type.As<IList>() && !(value is IList)) return false;
var list = value as IList;
if (list == null || list.Count == 0) return true;
// 循环写入数据
for (var i = 0; i < list.Count; i++)
{
WritePair(i + "", list[i]);
}
return true;
}
private Boolean TryReadArray(Type type, ref Object value)
{
if (!type.As<IList>()) return false;
// 子元素类型
var elmType = type.GetElementTypeEx();
var list = typeof(List<>).MakeGenericType(elmType).CreateInstance() as IList;
var ds = ReadPair();
for (var i = 0; i < ds.Count; i++)
{
Object v = null;
if (TryReadPair(ds, i + "", elmType, ref v)) list.Add(v);
}
// 数组的创建比较特别
if (type.IsArray)
{
var arr = Array.CreateInstance(elmType, list.Count);
list.CopyTo(arr, 0);
value = arr;
}
else
value = list;
return true;
}
#endregion
#region 复杂对象名值对
private Boolean WriteObject(Object value, Type type)
{
var ims = Host.IgnoreMembers;
var ms = GetMembers(type).Where(e => !ims.Contains(e.Name)).ToList();
WriteLog("BinaryWrite类{0} 共有成员{1}个", type.Name, ms.Count);
Host.Hosts.Push(value);
// 获取成员
foreach (var member in ms)
{
var mtype = GetMemberType(member);
Host.Member = member;
var v = value.GetValue(member);
WriteLog(" {0}.{1} {2}", type.Name, member.Name, v);
var name = member.Name;
var att = member.GetCustomAttribute<XmlElementAttribute>();
if (att != null) name = att.ElementName;
// 特殊处理写入名值对
if (!WritePair(name, v))
{
Host.Hosts.Pop();
return false;
}
}
Host.Hosts.Pop();
return true;
}
private Boolean TryReadObject(Type type, ref Object value)
{
// 不支持基本类型
if (Type.GetTypeCode(type) != TypeCode.Object) return false;
// 不支持基类不是Object的特殊类型
//if (type.BaseType != typeof(Object)) return false;
//if (!type.As<Object>()) return false;
if (!typeof(Object).IsAssignableFrom(type)) return false;
var ims = Host.IgnoreMembers;
var ms = GetMembers(type).Where(e => !ims.Contains(e.Name)).ToList();
WriteLog("BinaryRead类{0} 共有成员{1}个", type.Name, ms.Count);
if (value == null) value = type.CreateInstance();
// 提前准备名值对
var dic = ReadPair();
if (dic.Count == 0) return true;
Host.Hosts.Push(value);
// 获取成员
for (var i = 0; i < ms.Count; i++)
{
var member = ms[i];
var mtype = GetMemberType(member);
Host.Member = member;
WriteLog(" {0}.{1}", member.DeclaringType.Name, member.Name);
var name = member.Name;
var att = member.GetCustomAttribute<XmlElementAttribute>();
if (att != null) name = att.ElementName;
Object v = null;
if (TryReadPair(dic, name, mtype, ref v)) value.SetValue(member, v);
}
Host.Hosts.Pop();
return true;
}
#endregion
#region 获取成员
/// <summary>获取成员</summary>
/// <param name="type"></param>
/// <param name="baseFirst"></param>
/// <returns></returns>
protected virtual List<MemberInfo> GetMembers(Type type, Boolean baseFirst = true)
{
if (Host.UseProperty)
return type.GetProperties(baseFirst).Cast<MemberInfo>().ToList();
else
return type.GetFields(baseFirst).Cast<MemberInfo>().ToList();
}
static Type GetMemberType(MemberInfo member)
{
return member.MemberType switch
{
MemberTypes.Field => (member as FieldInfo).FieldType,
MemberTypes.Property => (member as PropertyInfo).PropertyType,
_ => throw new NotSupportedException(),
};
}
#endregion
}
} | 31.463731 | 114 | 0.468341 | [
"MIT"
] | Gavin-Peking/X | NewLife.Core/Serialization/Binary/BinaryPair.cs | 12,801 | C# |
using System.Collections.Generic;
using Essensoft.AspNetCore.Payment.Alipay.Response;
namespace Essensoft.AspNetCore.Payment.Alipay.Request
{
/// <summary>
/// alipay.open.mini.aliminiabilityprod.jsapi.query
/// </summary>
public class AlipayOpenMiniAliminiabilityprodJsapiQueryRequest : IAlipayRequest<AlipayOpenMiniAliminiabilityprodJsapiQueryResponse>
{
/// <summary>
/// 交换中心JSAPI查询
/// </summary>
public string BizContent { get; set; }
#region IAlipayRequest Members
private bool needEncrypt = false;
private string apiVersion = "1.0";
private string terminalType;
private string terminalInfo;
private string prodCode;
private string notifyUrl;
private string returnUrl;
private AlipayObject bizModel;
public void SetNeedEncrypt(bool needEncrypt)
{
this.needEncrypt = needEncrypt;
}
public bool GetNeedEncrypt()
{
return needEncrypt;
}
public void SetNotifyUrl(string notifyUrl)
{
this.notifyUrl = notifyUrl;
}
public string GetNotifyUrl()
{
return notifyUrl;
}
public void SetReturnUrl(string returnUrl)
{
this.returnUrl = returnUrl;
}
public string GetReturnUrl()
{
return returnUrl;
}
public void SetTerminalType(string terminalType)
{
this.terminalType = terminalType;
}
public string GetTerminalType()
{
return terminalType;
}
public void SetTerminalInfo(string terminalInfo)
{
this.terminalInfo = terminalInfo;
}
public string GetTerminalInfo()
{
return terminalInfo;
}
public void SetProdCode(string prodCode)
{
this.prodCode = prodCode;
}
public string GetProdCode()
{
return prodCode;
}
public string GetApiName()
{
return "alipay.open.mini.aliminiabilityprod.jsapi.query";
}
public void SetApiVersion(string apiVersion)
{
this.apiVersion = apiVersion;
}
public string GetApiVersion()
{
return apiVersion;
}
public IDictionary<string, string> GetParameters()
{
var parameters = new AlipayDictionary
{
{ "biz_content", BizContent }
};
return parameters;
}
public AlipayObject GetBizModel()
{
return bizModel;
}
public void SetBizModel(AlipayObject bizModel)
{
this.bizModel = bizModel;
}
#endregion
}
}
| 23.185484 | 135 | 0.556522 | [
"MIT"
] | lzw316/payment | src/Essensoft.AspNetCore.Payment.Alipay/Request/AlipayOpenMiniAliminiabilityprodJsapiQueryRequest.cs | 2,889 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
namespace Microsoft.Azure.Management.ContainerService.Fluent
{
using Microsoft.Azure.Management.ContainerService.Fluent.ContainerService.Definition;
using Microsoft.Azure.Management.ContainerService.Fluent.ContainerServiceAgentPool.Definition;
using Microsoft.Azure.Management.ContainerService.Fluent.Models;
using Microsoft.Azure.Management.ResourceManager.Fluent.Core;
using Microsoft.Azure.Management.ResourceManager.Fluent.Core.ChildResource.Definition;
internal partial class ContainerServiceAgentPoolImpl
{
/// <summary>
/// Gets the number of agents (virtual machines) to host docker containers.
/// </summary>
int Microsoft.Azure.Management.ContainerService.Fluent.IContainerServiceAgentPool.Count
{
get
{
return this.Count();
}
}
/// <summary>
/// Gets DNS prefix to be used to create the FQDN for the agent pool.
/// </summary>
string Microsoft.Azure.Management.ContainerService.Fluent.IContainerServiceAgentPool.DnsPrefix
{
get
{
return this.DnsPrefix();
}
}
/// <summary>
/// Gets FDQN for the agent pool.
/// </summary>
string Microsoft.Azure.Management.ContainerService.Fluent.IContainerServiceAgentPool.Fqdn
{
get
{
return this.Fqdn();
}
}
/// <summary>
/// Gets the name of the resource.
/// </summary>
string Microsoft.Azure.Management.ResourceManager.Fluent.Core.IHasName.Name
{
get
{
return this.Name();
}
}
/// <summary>
/// Gets the ID of the virtual network used by each virtual machine in the agent pool.
/// </summary>
string Microsoft.Azure.Management.ContainerService.Fluent.IContainerServiceAgentPool.NetworkId
{
get
{
return this.NetworkId();
}
}
/// <summary>
/// Gets OS disk size in GB set for each virtual machine in the agent pool.
/// </summary>
int Microsoft.Azure.Management.ContainerService.Fluent.IContainerServiceAgentPool.OSDiskSizeInGB
{
get
{
return this.OSDiskSizeInGB();
}
}
/// <summary>
/// Gets OS of each virtual machine in the agent pool.
/// </summary>
OSType Microsoft.Azure.Management.ContainerService.Fluent.IContainerServiceAgentPool.OSType
{
get
{
return this.OSType();
}
}
/// <summary>
/// Gets array of ports opened on this agent pool.
/// </summary>
int[] Microsoft.Azure.Management.ContainerService.Fluent.IContainerServiceAgentPool.Ports
{
get
{
return this.Ports();
}
}
/// <summary>
/// Gets the storage kind (managed or classic) set for each virtual machine in the agent pool.
/// </summary>
ContainerServiceStorageProfileTypes Microsoft.Azure.Management.ContainerService.Fluent.IContainerServiceAgentPool.StorageProfile
{
get
{
return this.StorageProfile();
}
}
/// <summary>
/// Gets the name of the subnet used by each virtual machine in the agent pool.
/// </summary>
string Microsoft.Azure.Management.ContainerService.Fluent.IContainerServiceAgentPool.SubnetName
{
get
{
return this.SubnetName();
}
}
/// <summary>
/// Gets the size of each virtual machine in the agent pool.
/// </summary>
ContainerServiceVMSizeTypes Microsoft.Azure.Management.ContainerService.Fluent.IContainerServiceAgentPool.VMSize
{
get
{
return this.VMSize();
}
}
/// <summary>
/// Attaches the child definition to the parent resource definiton.
/// </summary>
/// <return>The next stage of the parent definition.</return>
ContainerService.Definition.IWithCreate Microsoft.Azure.Management.ResourceManager.Fluent.Core.ChildResource.Definition.IInDefinition<ContainerService.Definition.IWithCreate>.Attach()
{
return this.Attach();
}
/// <summary>
/// Specify the DNS prefix to be used in the FQDN for the agent pool.
/// </summary>
/// <param name="dnsPrefix">The DNS prefix.</param>
/// <return>The next stage of the definition.</return>
ContainerServiceAgentPool.Definition.IWithAttach<ContainerService.Definition.IWithCreate> ContainerServiceAgentPool.Definition.IWithLeafDomainLabel<ContainerService.Definition.IWithCreate>.WithDnsPrefix(string dnsPrefix)
{
return this.WithDnsPrefix(dnsPrefix);
}
/// <summary>
/// OS Disk Size in GB to be used for every machine in the agent pool.
/// </summary>
/// <param name="osDiskSizeInGB">OS disk size in GB to be used for each virtual machine in the agent pool.</param>
/// <return>The next stage of the definition.</return>
ContainerServiceAgentPool.Definition.IWithAttach<ContainerService.Definition.IWithCreate> ContainerServiceAgentPool.Definition.IWithOSDiskSize<ContainerService.Definition.IWithCreate>.WithOSDiskSizeInGB(int osDiskSizeInGB)
{
return this.WithOSDiskSizeInGB(osDiskSizeInGB);
}
/// <summary>
/// OS type to be used for every machine in the agent pool.
/// Default is Linux.
/// </summary>
/// <param name="osType">OS type to be used for every machine in the agent pool.</param>
/// <return>The next stage of the definition.</return>
ContainerServiceAgentPool.Definition.IWithAttach<ContainerService.Definition.IWithCreate> ContainerServiceAgentPool.Definition.IWithOSType<ContainerService.Definition.IWithCreate>.WithOSType(OSType osType)
{
return this.WithOSType(osType);
}
/// <summary>
/// Ports to be exposed on this agent pool.
/// The default exposed ports are different based on your choice of orchestrator.
/// </summary>
/// <param name="ports">Port numbers that will be exposed on this agent pool.</param>
/// <return>The next stage of the definition.</return>
ContainerServiceAgentPool.Definition.IWithAttach<ContainerService.Definition.IWithCreate> ContainerServiceAgentPool.Definition.IWithPorts<ContainerService.Definition.IWithCreate>.WithPorts(params int[] ports)
{
return this.WithPorts(ports);
}
/// <summary>
/// Specifies the storage kind to be used for each virtual machine in the agent pool.
/// </summary>
/// <param name="storageProfile">The storage kind to be used for each virtual machine in the agent pool.</param>
/// <return>The next stage of the definition.</return>
ContainerServiceAgentPool.Definition.IWithAttach<ContainerService.Definition.IWithCreate> ContainerServiceAgentPool.Definition.IWithStorageProfile<ContainerService.Definition.IWithCreate>.WithStorageProfile(ContainerServiceStorageProfileTypes storageProfile)
{
return this.WithStorageProfile(storageProfile);
}
/// <summary>
/// Specifies the number of agents (virtual machines) to host docker containers.
/// </summary>
/// <param name="count">A number between 1 and 100.</param>
/// <return>The next stage of the definition.</return>
ContainerServiceAgentPool.Definition.IWithVMSize<ContainerService.Definition.IWithCreate> ContainerServiceAgentPool.Definition.IBlank<ContainerService.Definition.IWithCreate>.WithVirtualMachineCount(int count)
{
return this.WithVirtualMachineCount(count);
}
/// <summary>
/// Specifies the size of the agent virtual machines.
/// </summary>
/// <param name="vmSize">The size of the virtual machine.</param>
/// <return>The next stage of the definition.</return>
ContainerServiceAgentPool.Definition.IWithLeafDomainLabel<ContainerService.Definition.IWithCreate> ContainerServiceAgentPool.Definition.IWithVMSize<ContainerService.Definition.IWithCreate>.WithVirtualMachineSize(ContainerServiceVMSizeTypes vmSize)
{
return this.WithVirtualMachineSize(vmSize);
}
/// <summary>
/// Specifies the virtual network to be used for the agents.
/// </summary>
/// <param name="virtualNetworkId">The ID of a virtual network.</param>
/// <param name="subnetName">
/// The name of the subnet within the virtual network.; the subnet must have the service
/// endpoints enabled for 'Microsoft.ContainerService'.
/// </param>
/// <return>The next stage.</return>
ContainerServiceAgentPool.Definition.IWithAttach<ContainerService.Definition.IWithCreate> ContainerServiceAgentPool.Definition.IWithVirtualNetwork<ContainerService.Definition.IWithCreate>.WithVirtualNetwork(string virtualNetworkId, string subnetName)
{
return this.WithVirtualNetwork(virtualNetworkId, subnetName);
}
}
} | 42.550218 | 266 | 0.637726 | [
"MIT"
] | Azure/azure-libraries-for-net | src/ResourceManagement/ContainerService/Domain/InterfaceImpl/ContainerServiceAgentPoolImpl.cs | 9,744 | C# |
// ==========================================================================
// Squidex Headless CMS
// ==========================================================================
// Copyright (c) Squidex UG (haftungsbeschränkt)
// All rights reserved. Licensed under the MIT license.
// ==========================================================================
using Squidex.Domain.Apps.Core.Apps;
using Xunit;
#pragma warning disable SA1310 // Field names must not contain underscore
namespace Squidex.Domain.Apps.Core.Model.Apps
{
public class AppContributorsTests
{
private readonly AppContributors contributors_0 = AppContributors.Empty;
[Fact]
public void Should_assign_new_contributor()
{
var contributors_1 = contributors_0.Assign("1", Role.Developer);
var contributors_2 = contributors_1.Assign("2", Role.Editor);
Assert.Equal(Role.Developer, contributors_2["1"]);
Assert.Equal(Role.Editor, contributors_2["2"]);
}
[Fact]
public void Should_replace_contributor_if_already_exists()
{
var contributors_1 = contributors_0.Assign("1", Role.Developer);
var contributors_2 = contributors_1.Assign("1", Role.Owner);
Assert.Equal(Role.Owner, contributors_2["1"]);
}
[Fact]
public void Should_return_same_contributors_if_contributor_is_updated_with_same_role()
{
var contributors_1 = contributors_0.Assign("1", Role.Developer);
var contributors_2 = contributors_1.Assign("1", Role.Developer);
Assert.Same(contributors_1, contributors_2);
}
[Fact]
public void Should_remove_contributor()
{
var contributors_1 = contributors_0.Assign("1", Role.Developer);
var contributors_2 = contributors_1.Remove("1");
Assert.Empty(contributors_2);
}
[Fact]
public void Should_do_nothing_if_contributor_to_remove_not_found()
{
var contributors_1 = contributors_0.Remove("2");
Assert.Same(contributors_0, contributors_1);
}
}
}
| 33.676923 | 94 | 0.576062 | [
"MIT"
] | andrewcampkin/squidex | backend/tests/Squidex.Domain.Apps.Core.Tests/Model/Apps/AppContributorsTests.cs | 2,192 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
namespace aWhere.Api.Business {
public class Weather {
#region Fields
public const string WEATHER_ENDPOINT = "/v2/weather/fields/";
#endregion Fields
#region Methods
public string GenerateRandomFieldName() {
StringBuilder baseName = new StringBuilder();
baseName.Append("DemoField-");
// Generate random number
Random randomNum = new Random(DateTime.Now.Millisecond);
string randomNumber = randomNum.Next().ToString();
// Combine the base name and the random number, then cast to String
baseName.Append(randomNumber);
string completedName = baseName.ToString();
return completedName;
}
#endregion Methods
}
public class Location {
public float latitude { get; set; }
public float longitude { get; set; }
public string fieldId { get; set; }
}
public class Temperatures {
public float max { get; set; }
public float min { get; set; }
public string units { get; set; }
}
public class Precipitation {
public float amount { get; set; }
public float average { get; set; }
public float stdDev { get; set; }
public string units { get; set; }
}
public class Solar {
public float amount { get; set; }
public string units { get; set; }
}
public class Relativehumidity {
public float? max { get; set; }
public float? min { get; set; }
}
public class Wind {
public float morningMax { get; set; }
public float dayMax { get; set; }
public float average { get; set; }
public string units { get; set; }
}
public class Dewpoint {
public float amount { get; set; }
public string units { get; set; }
}
public class Sky {
public double cloudCover { get; set; }
public double sunshine { get; set; }
}
public class Meantemp {
public float average { get; set; }
public float stdDev { get; set; }
public string units { get; set; }
}
public class Maxtemp {
public float average { get; set; }
public float stdDev { get; set; }
public string units { get; set; }
}
public class Mintemp {
public float average { get; set; }
public float stdDev { get; set; }
public string units { get; set; }
}
public class Minhumidity {
public float average { get; set; }
public float stdDev { get; set; }
}
public class Maxhumidity {
public float average { get; set; }
public float stdDev { get; set; }
}
public class Dailymaxwind {
public float average { get; set; }
public float stdDev { get; set; }
public string units { get; set; }
}
public class Averagewind {
public float average { get; set; }
public float stdDev { get; set; }
public string units { get; set; }
}
}
| 26.040323 | 79 | 0.578198 | [
"MIT"
] | aWhereAPI/API-Code-Samples | c#/aWhere.Api.CodeSample/aWhere.Api.Business/Weather.cs | 3,231 | C# |
/*
This file was generated and should not be modified directly
*/
using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.Common;
using Bam.Net.Data;
namespace Bam.Net.Services.DataReplication.Data.Dao
{
public class DataPointQuery: Query<DataPointColumns, DataPoint>
{
public DataPointQuery(){}
public DataPointQuery(WhereDelegate<DataPointColumns> where, OrderBy<DataPointColumns> orderBy = null, Database db = null) : base(where, orderBy, db) { }
public DataPointQuery(Func<DataPointColumns, QueryFilter<DataPointColumns>> where, OrderBy<DataPointColumns> orderBy = null, Database db = null) : base(where, orderBy, db) { }
public DataPointQuery(Delegate where, Database db = null) : base(where, db) { }
public static DataPointQuery Where(WhereDelegate<DataPointColumns> where)
{
return Where(where, null, null);
}
public static DataPointQuery Where(WhereDelegate<DataPointColumns> where, OrderBy<DataPointColumns> orderBy = null, Database db = null)
{
return new DataPointQuery(where, orderBy, db);
}
public DataPointCollection Execute()
{
return new DataPointCollection(this, true);
}
}
} | 35.742857 | 179 | 0.718625 | [
"MIT"
] | BryanApellanes/bam.net.shared | Services/DataReplication/Data/Generated_Dao/DataPointQuery.cs | 1,251 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Microsoft.Dynamics365.UIAutomation.Api.UCI;
namespace Microsoft.Dynamics365.UIAutomation.Sample.UCI
{
[TestClass]
public class OpenNavigationUci: TestsBase
{
[TestMethod]
public void UCITestOpenOptions()
{
TestSettings.Options.UCIPerformanceMode = false;
var client = new WebClient(TestSettings.Options);
using (var xrmApp = new XrmApp(client))
{
xrmApp.OnlineLogin.Login(_xrmUri, _username, _password, _mfaSecrectKey);
xrmApp.Navigation.OpenApp(UCIAppName.Sales);
xrmApp.Navigation.OpenOptions();
xrmApp.Navigation.OpenOptInForLearningPath();
xrmApp.Navigation.OpenPrivacy();
xrmApp.Navigation.SignOut();
}
}
[TestMethod]
public void UCITestOpenGuidedHelp()
{
var client = new WebClient(TestSettings.Options);
using (var xrmApp = new XrmApp(client))
{
xrmApp.OnlineLogin.Login(_xrmUri, _username, _password, _mfaSecrectKey);
xrmApp.Navigation.OpenApp(UCIAppName.Sales);
xrmApp.Navigation.OpenGuidedHelp();
}
}
[TestMethod]
public void UCITestOpenSoftwareLicensing()
{
var client = new WebClient(TestSettings.Options);
using (var xrmApp = new XrmApp(client))
{
xrmApp.OnlineLogin.Login(_xrmUri, _username, _password, _mfaSecrectKey);
xrmApp.Navigation.OpenApp(UCIAppName.Sales);
xrmApp.Navigation.OpenSoftwareLicensing();
}
}
[TestMethod]
public void UCITestOpenToastNotifications()
{
var client = new WebClient(TestSettings.Options);
using (var xrmApp = new XrmApp(client))
{
xrmApp.OnlineLogin.Login(_xrmUri, _username, _password, _mfaSecrectKey);
xrmApp.Navigation.OpenApp(UCIAppName.Sales);
xrmApp.Navigation.OpenToastNotifications();
}
}
[TestMethod]
public void UCITestOpenAbout()
{
var client = new WebClient(TestSettings.Options);
using (var xrmApp = new XrmApp(client))
{
xrmApp.OnlineLogin.Login(_xrmUri, _username, _password, _mfaSecrectKey);
xrmApp.Navigation.OpenApp(UCIAppName.Sales);
xrmApp.Navigation.OpenAbout();
}
}
[TestMethod]
public void UCITestOpenAppSettings()
{
var client = new WebClient(TestSettings.Options);
using (var xrmApp = new XrmApp(client))
{
xrmApp.OnlineLogin.Login(_xrmUri, _username, _password);
xrmApp.Navigation.OpenApp(UCIAppName.Sales);
xrmApp.Navigation.OpenSubArea("App Settings", "PDF generation");
}
}
[TestMethod]
public void UCITestOpenHelp()
{
var client = new WebClient(TestSettings.Options);
using (var xrmApp = new XrmApp(client))
{
xrmApp.OnlineLogin.Login(_xrmUri, _username, _password);
xrmApp.Navigation.OpenApp(UCIAppName.Sales);
xrmApp.Navigation.OpenArea("Help and Support");
xrmApp.Navigation.OpenSubArea("Help Center");
}
}
[TestMethod]
public void UCITestOpenRelatedCommonActivities()
{
var client = new WebClient(TestSettings.Options);
using (var xrmApp = new XrmApp(client))
{
xrmApp.OnlineLogin.Login(_xrmUri, _username, _password, _mfaSecrectKey);
xrmApp.Navigation.OpenApp(UCIAppName.Sales);
xrmApp.Navigation.OpenSubArea("Sales", "Accounts");
xrmApp.Grid.OpenRecord(0);
xrmApp.Navigation.OpenMenu(Reference.MenuRelated.Related, Reference.MenuRelated.CommonActivities);
}
}
[TestMethod]
public void UCITestOpenGroupSubArea()
{
var client = new WebClient(TestSettings.Options);
using (var xrmApp = new XrmApp(client))
{
xrmApp.OnlineLogin.Login(_xrmUri, _username, _password, _mfaSecrectKey);
xrmApp.Navigation.OpenApp(UCIAppName.Sales);
xrmApp.Navigation.OpenGroupSubArea("Customers", "Accounts");
xrmApp.Grid.OpenRecord(0);
xrmApp.ThinkTime(3000);
}
}
}
} | 35.072993 | 114 | 0.578564 | [
"MIT"
] | chauhanrupesh/CRM | Microsoft.Dynamics365.UIAutomation.Sample/UCI/Navigation/OpenNavigation.cs | 4,807 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace System.Runtime.InteropServices
{
public enum VarEnum
{
VT_EMPTY = 0,
VT_NULL = 1,
VT_I2 = 2,
VT_I4 = 3,
VT_R4 = 4,
VT_R8 = 5,
VT_CY = 6,
VT_DATE = 7,
VT_BSTR = 8,
VT_DISPATCH = 9,
VT_ERROR = 10,
VT_BOOL = 11,
VT_VARIANT = 12,
VT_UNKNOWN = 13,
VT_DECIMAL = 14,
VT_I1 = 16,
VT_UI1 = 17,
VT_UI2 = 18,
VT_UI4 = 19,
VT_I8 = 20,
VT_UI8 = 21,
VT_INT = 22,
VT_UINT = 23,
VT_VOID = 24,
VT_HRESULT = 25,
VT_PTR = 26,
VT_SAFEARRAY = 27,
VT_CARRAY = 28,
VT_USERDEFINED = 29,
VT_LPSTR = 30,
VT_LPWSTR = 31,
VT_RECORD = 36,
VT_FILETIME = 64,
VT_BLOB = 65,
VT_STREAM = 66,
VT_STORAGE = 67,
VT_STREAMED_OBJECT = 68,
VT_STORED_OBJECT = 69,
VT_BLOB_OBJECT = 70,
VT_CF = 71,
VT_CLSID = 72,
VT_VECTOR = 0x1000,
VT_ARRAY = 0x2000,
VT_BYREF = 0x4000
}
}
| 23.818182 | 71 | 0.50687 | [
"MIT"
] | 06needhamt/runtime | src/libraries/System.Private.CoreLib/src/System/Runtime/InteropServices/VarEnum.cs | 1,310 | 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.Collections.Generic;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.Extensions.DependencyInjection;
namespace Microsoft.EntityFrameworkCore.ChangeTracking.Internal
{
/// <summary>
/// <para>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </para>
/// <para>
/// The service lifetime is <see cref="ServiceLifetime.Scoped" />. This means that each
/// <see cref="DbContext" /> instance will use its own instance of this service.
/// The implementation may depend on other services registered with any lifetime.
/// The implementation does not need to be thread-safe.
/// </para>
/// </summary>
public interface IInternalEntityEntryNotifier
{
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
void StateChanging(InternalEntityEntry entry, EntityState newState);
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
void StateChanged(InternalEntityEntry entry, EntityState oldState, bool fromQuery);
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
void TrackedFromQuery(InternalEntityEntry entry);
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
void NavigationReferenceChanged(
InternalEntityEntry entry,
INavigation navigation,
object? oldValue,
object? newValue
);
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
void NavigationCollectionChanged(
InternalEntityEntry entry,
INavigationBase navigationBase,
IEnumerable<object> added,
IEnumerable<object> removed
);
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
void KeyPropertyChanged(
InternalEntityEntry entry,
IProperty property,
IEnumerable<IKey> keys,
IEnumerable<IForeignKey> foreignKeys,
object? oldValue,
object? newValue
);
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
void PropertyChanged(InternalEntityEntry entry, IPropertyBase property, bool setModified);
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
void PropertyChanging(InternalEntityEntry entry, IPropertyBase property);
}
}
| 59.813084 | 113 | 0.670625 | [
"Apache-2.0"
] | belav/efcore | src/EFCore/ChangeTracking/Internal/IInternalEntityEntryNotifier.cs | 6,400 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.