content stringlengths 5 1.04M | avg_line_length float64 1.75 12.9k | max_line_length int64 2 244k | alphanum_fraction float64 0 0.98 | licenses list | repository_name stringlengths 7 92 | path stringlengths 3 249 | size int64 5 1.04M | lang stringclasses 2
values |
|---|---|---|---|---|---|---|---|---|
using Blog.Dal.Infrastructure.Extensions;
using Blog.Dal.Models.Category;
using Blog.Dal.Models.Common;
using Blog.Dal.Models.Common.Contracts;
using Blog.Dal.Services.Categories.Contracts;
using Blog.Data;
using Blog.Models;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;
namespace Blog.Dal.Services.Categories
{
public class CategoryService : ICategoryService
{
private readonly BlogDbContext _dbContext;
public CategoryService(BlogDbContext dbContext)
=> this._dbContext = dbContext;
public async Task<CategoryViewModel> GetById(string id)
=> await this.Get(c => c.Id == id);
public async Task<CategoryViewModel> GetByName(string name)
=> await this.Get(c => c.Name == name);
public async Task<IEnumerable<CategoryDropdownListModel>> GetAllForDropdown()
{
var categories = await this._dbContext
.Categories
.Select(c => new CategoryDropdownListModel
{
Id = c.Id,
Name = c.Name
})
.ToListAsync();
return categories;
}
public async Task<ISearchResponseModel<CategorySearchViewModel>> GetAll(IBaseSearchModel searchModel)
{
var filteredCategories = await this._dbContext
.Categories
.Where(c => searchModel.Keywords.IsNullOrEmpty() || c.Name.StartsWith(searchModel.Keywords))
.Select(c => new CategorySearchViewModel
{
Id = c.Id,
Name = c.Name,
CreatedOn = c.CreatedOn,
CreatorName = c.CreatorId != null ? c.Creator.UserName : "None"
})
.ToListAsync();
var data = filteredCategories
.OptimizedSkip((searchModel.Page.Value - 1) * searchModel.Size.Value)
.Take(searchModel.Size.Value);
var pagesCount = (double)(filteredCategories.Count) / (double)searchModel.Size.Value;
var responseModel = new SearchResponseModel<CategorySearchViewModel>(data, (int)Math.Ceiling(pagesCount));
return responseModel;
}
public async Task Create(CategoryInputModel model)
{
var categoryEntity = new Category
{
Name = model.Name,
CreatorId = model.CreatorId
};
await this._dbContext.AddAsync(categoryEntity);
await this._dbContext.SaveChangesAsync();
}
public async Task Edit(CategoryEditModel model)
{
var category = await this._dbContext.Categories.FirstOrDefaultAsync(c => c.Id == model.Id);
if (category == null) return;
category.Name = model.Name;
this._dbContext.Update(category);
await this._dbContext.SaveChangesAsync();
}
public async Task Copy(string id)
{
var category = await this._dbContext.Categories.FirstOrDefaultAsync(c => c.Id == id);
if (category == null) return;
var newCategory = new Category
{
Name = category.Name + " - Copy",
CreatorId = category.CreatorId,
CreatedOn = category.CreatedOn
};
await this._dbContext.AddAsync(newCategory);
await this._dbContext.SaveChangesAsync();
}
public async Task Delete(string id)
{
var category = await this._dbContext.Categories.FirstOrDefaultAsync(c => c.Id == id);
if (category != null)
{
this._dbContext.Categories.Remove(category);
await this._dbContext.SaveChangesAsync();
}
}
private async Task<CategoryViewModel> Get(Expression<Func<Category, bool>> findCategoryfunc)
{
var categoryEntity = await this._dbContext.Categories.FirstOrDefaultAsync(findCategoryfunc);
if (categoryEntity == null)
return null;
var categoryViewModel = new CategoryViewModel
{
Id = categoryEntity.Id,
Name = categoryEntity.Name,
CreatedOn = categoryEntity.CreatedOn,
CreatorId = categoryEntity.CreatorId
};
return categoryViewModel;
}
}
} | 32.971223 | 118 | 0.580624 | [
"MIT"
] | GMihalkow/Blog | Blog.Dal/Services/Categories/CategoryService.cs | 4,585 | C# |
using System;
using Xamarin.Forms;
using FluentXamarinForms.FluentBase;
namespace FluentXamarinForms
{
public class FluentBoxView : FluentBoxViewBase<FluentBoxView, BoxView>
{
public FluentBoxView ()
:base()
{
}
public FluentBoxView (BoxView instance)
:base(instance)
{
}
}
} | 19.052632 | 74 | 0.60221 | [
"MIT"
] | MarcelMalik/FluentXamarinForms | src/FluentXamarinForms/FluentBoxView.cs | 364 | C# |
using System;
using Sg4Mvc.Generator.CodeGen;
using Xunit;
namespace Sg4Mvc.Test.CodeGen;
public class BodyBuilderTests
{
[Fact]
public void BodyEmpty()
{
var result = new BodyBuilder()
.Build();
Assert.Equal("{}", result.ToString());
}
[Theory]
[InlineData("result", "ActionResult", "controller")]
[InlineData("result", "ActionResult", "controller", "action")]
[InlineData("obj", "object")]
public void Body_WithVariableFromObject(String name, String type, params String[] arguments)
{
var result = new BodyBuilder()
.VariableFromNewObject(name, type, arguments)
.Build();
Assert.Equal($"{{var{name}=new{type}({String.Join(",", arguments)});}}", result.ToString());
}
[Theory]
[InlineData("result", "action", "ToString")]
[InlineData("obj", "value", "GetValues", "param1")]
[InlineData("obj", "value", "GetValues", "param1", "param2")]
public void Body_WithVariableFromMethod(String name, String entity, String method, params String[] arguments)
{
var result = new BodyBuilder()
.VariableFromMethodCall(name, entity, method, arguments)
.Build();
Assert.Equal($"{{var{name}={entity}.{method}({String.Join(",", arguments)});}}", result.ToString());
}
[Theory]
[InlineData("result")]
[InlineData("value")]
public void Body_ReturnsVariable(String name)
{
var result = new BodyBuilder()
.ReturnVariable(name)
.Build();
Assert.Equal($"{{return{name};}}", result.ToString());
}
[Theory]
[InlineData("ActionResult", "controller")]
[InlineData("ActionResult", "controller", "action")]
[InlineData("object")]
public void Body_ReturnsNewObject(String type, params String[] arguments)
{
var result = new BodyBuilder()
.ReturnNewObject(type, arguments)
.Build();
Assert.Equal($"{{returnnew{type}({String.Join(",", arguments)});}}", result.ToString());
}
[Theory]
[InlineData("action", "ToUrl", "controller")]
[InlineData("action", "ToUrl", "controller", "action")]
[InlineData("entity", "ToString")]
public void Body_ReturnsMethodCall(String entity, String method, params String[] arguments)
{
var result = new BodyBuilder()
.ReturnMethodCall(entity, method, arguments)
.Build();
Assert.Equal($"{{return{entity}.{method}({String.Join(",", arguments)});}}", result.ToString());
}
[Theory]
[InlineData("action", "ToUrl", "controller")]
[InlineData("action", "ToUrl", "controller", "action")]
[InlineData("entity", "ToString")]
public void Body_MethodCall(String entity, String method, params String[] arguments)
{
var result = new BodyBuilder()
.MethodCall(entity, method, arguments)
.Build();
Assert.Equal($"{{{entity}.{method}({String.Join(",", arguments)});}}", result.ToString());
}
[Fact]
public void Body_MultiMethods()
{
var result = new BodyBuilder()
.VariableFromNewObject("result", "object")
.ReturnVariable("result")
.Build();
Assert.Equal("{varresult=newobject();returnresult;}", result.ToString());
}
[Fact]
public void Body_Statement()
{
var result = new BodyBuilder()
.Statement(b => b
.VariableFromNewObject("result", "object")
.ReturnVariable("result"))
.Build();
Assert.Equal("{varresult=newobject();returnresult;}", result.ToString());
}
}
| 31.09322 | 113 | 0.593077 | [
"Apache-2.0"
] | MarkFl12/R4MVC | test/Sg4Mvc.Test/CodeGen/BodyBuilderTests.cs | 3,671 | C# |
version https://git-lfs.github.com/spec/v1
oid sha256:07a91f0bb65c36b34dee43dab8bfd7f5af5b4e8f41bd7176fd7de8f9a5097c81
size 1413
| 32.25 | 75 | 0.883721 | [
"MIT"
] | kenx00x/ahhhhhhhhhhhh | ahhhhhhhhhh/Library/PackageCache/com.unity.render-pipelines.high-definition@7.1.8/Runtime/Sky/GradientSky/GradientSky.cs | 129 | C# |
using System.Collections.Generic;
namespace MangMana
{
internal static class Global
{
public const string DataCatalog = "data";
public const string ThumbnailsCatalog = "data/thumbnails";
public const string MetadataPath = "data/metadata.json";
public static List<string> ImageExtensions { get; } = new List<string> { ".jpg", ".png", ".bmp" };
}
} | 30.230769 | 106 | 0.656489 | [
"MIT"
] | Qrcze/MangMana | MangMana/Global.cs | 395 | C# |
using System;
using System.Collections.Generic;
using System.Web.Mvc;
using Orchard.Users.Models;
namespace Orchard.Users.ViewModels {
public class UsersIndexViewModel {
public IList<UserEntry> Users { get; set; }
public UserIndexOptions Options { get; set; }
public dynamic Pager { get; set; }
}
public class UserEntry {
public UserEntry() {
AdditionalActionLinks = new List<Func<HtmlHelper, MvcHtmlString>>();
}
public UserPart UserPart { get; set; }
public UserPartRecord User { get; set; }
public bool IsChecked { get; set; }
public List<Func<HtmlHelper, MvcHtmlString>> AdditionalActionLinks { get; set; }
}
public class UserIndexOptions {
public string Search { get; set; }
public UsersOrder Order { get; set; }
public UsersFilter Filter { get; set; }
public UsersBulkAction BulkAction { get; set; }
}
public enum UsersOrder {
Name,
Email,
CreatedUtc,
LastLoginUtc
}
public enum UsersFilter {
All,
Approved,
Pending,
EmailPending
}
public enum UsersBulkAction {
None,
Delete,
Disable,
Approve,
ChallengeEmail
}
}
| 24.018519 | 88 | 0.599075 | [
"BSD-3-Clause"
] | OrchardCMS/orchard | src/Orchard.Web/Modules/Orchard.Users/ViewModels/UsersIndexViewModel.cs | 1,299 | C# |
using Microsoft.JSInterop;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Tarjeta.Services
{
public class BrowserService
{
private readonly IJSRuntime _js;
public BrowserService(IJSRuntime js)
{
_js = js;
}
public async Task<BrowserDimension> GetDimensions()
{
return await _js.InvokeAsync<BrowserDimension>("getDimensions");
}
}
public class BrowserDimension
{
public int Width { get; set; }
public int Height { get; set; }
}
}
| 19.83871 | 76 | 0.622764 | [
"MIT"
] | hprez21/Blazor3dCard | Tarjeta/Services/BrowserService.cs | 617 | 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 sesv2-2019-09-27.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.SimpleEmailV2.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using ThirdParty.Json.LitJson;
namespace Amazon.SimpleEmailV2.Model.Internal.MarshallTransformations
{
/// <summary>
/// Response Unmarshaller for CreateEmailIdentityPolicy operation
/// </summary>
public class CreateEmailIdentityPolicyResponseUnmarshaller : 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)
{
CreateEmailIdentityPolicyResponse response = new CreateEmailIdentityPolicyResponse();
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("AlreadyExistsException"))
{
return AlreadyExistsExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("BadRequestException"))
{
return BadRequestExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("LimitExceededException"))
{
return LimitExceededExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("NotFoundException"))
{
return NotFoundExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("TooManyRequestsException"))
{
return TooManyRequestsExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse);
}
}
return new AmazonSimpleEmailServiceV2Exception(errorResponse.Message, errorResponse.InnerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, errorResponse.StatusCode);
}
private static CreateEmailIdentityPolicyResponseUnmarshaller _instance = new CreateEmailIdentityPolicyResponseUnmarshaller();
internal static CreateEmailIdentityPolicyResponseUnmarshaller GetInstance()
{
return _instance;
}
/// <summary>
/// Gets the singleton.
/// </summary>
public static CreateEmailIdentityPolicyResponseUnmarshaller Instance
{
get
{
return _instance;
}
}
}
} | 41.565217 | 204 | 0.645188 | [
"Apache-2.0"
] | philasmar/aws-sdk-net | sdk/src/Services/SimpleEmailV2/Generated/Model/Internal/MarshallTransformations/CreateEmailIdentityPolicyResponseUnmarshaller.cs | 4,780 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Surging.Core.Swagger.SwaggerUI
{
public static class SwaggerUIOptionsExtensions
{
/// <summary>
/// Injects additional CSS stylesheets into the index.html page
/// </summary>
/// <param name="options"></param>
/// <param name="path">A path to the stylesheet - i.e. the link "href" attribute</param>
/// <param name="media">The target media - i.e. the link "media" attribute</param>
public static void InjectStylesheet(this SwaggerUIOptions options, string path, string media = "screen")
{
var builder = new StringBuilder(options.HeadContent);
builder.AppendLine($"<link href='{path}' rel='stylesheet' media='{media}' type='text/css' />");
options.HeadContent = builder.ToString();
}
/// <summary>
/// Injects additional Javascript files into the index.html page
/// </summary>
/// <param name="options"></param>
/// <param name="path">A path to the javascript - i.e. the script "src" attribute</param>
/// <param name="type">The script type - i.e. the script "type" attribute</param>
public static void InjectJavascript(this SwaggerUIOptions options, string path, string type = "text/javascript")
{
var builder = new StringBuilder(options.HeadContent);
builder.AppendLine($"<script src='{path}' type='{type}'></script>");
options.HeadContent = builder.ToString();
}
/// <summary>
/// Adds Swagger JSON endpoints. Can be fully-qualified or relative to the UI page
/// </summary>
/// <param name="options"></param>
/// <param name="url">Can be fully qualified or relative to the current host</param>
/// <param name="name">The description that appears in the document selector drop-down</param>
public static void SwaggerEndpoint(this SwaggerUIOptions options, string url, string name)
{
var urls = new List<UrlDescriptor>(options.ConfigObject.Urls ?? Enumerable.Empty<UrlDescriptor>());
urls.Add(new UrlDescriptor { Url = url, Name = name });
options.ConfigObject.Urls = urls;
}
/// <summary>
/// Enables deep linking for tags and operations
/// </summary>
/// <param name="options"></param>
public static void EnableDeepLinking(this SwaggerUIOptions options)
{
options.ConfigObject.DeepLinking = true;
}
/// <summary>
/// Controls the display of operationId in operations list
/// </summary>
/// <param name="options"></param>
public static void DisplayOperationId(this SwaggerUIOptions options)
{
options.ConfigObject.DisplayOperationId = true;
}
/// <summary>
/// The default expansion depth for models (set to -1 completely hide the models)
/// </summary>
/// <param name="options"></param>
/// <param name="depth"></param>
public static void DefaultModelsExpandDepth(this SwaggerUIOptions options, int depth)
{
options.ConfigObject.DefaultModelsExpandDepth = depth;
}
/// <summary>
/// The default expansion depth for the model on the model-example section
/// </summary>
/// <param name="options"></param>
/// <param name="depth"></param>
public static void DefaultModelExpandDepth(this SwaggerUIOptions options, int depth)
{
options.ConfigObject.DefaultModelExpandDepth = depth;
}
/// <summary>
/// Controls how the model is shown when the API is first rendered.
/// (The user can always switch the rendering for a given model by clicking the 'Model' and 'Example Value' links.)
/// </summary>
/// <param name="options"></param>
/// <param name="modelRendering"></param>
public static void DefaultModelRendering(this SwaggerUIOptions options, ModelRendering modelRendering)
{
options.ConfigObject.DefaultModelRendering = modelRendering;
}
/// <summary>
/// Controls the display of the request duration (in milliseconds) for Try-It-Out requests
/// </summary>
/// <param name="options"></param>
public static void DisplayRequestDuration(this SwaggerUIOptions options)
{
options.ConfigObject.DisplayRequestDuration = true;
}
/// <summary>
/// Controls the default expansion setting for the operations and tags.
/// It can be 'List' (expands only the tags), 'Full' (expands the tags and operations) or 'None' (expands nothing)
/// </summary>
/// <param name="options"></param>
/// <param name="docExpansion"></param>
public static void DocExpansion(this SwaggerUIOptions options, DocExpansion docExpansion)
{
options.ConfigObject.DocExpansion = docExpansion;
}
/// <summary>
/// Enables filtering. The top bar will show an edit box that you can use to filter the tagged operations that are shown.
/// If an expression is provided it will be used and applied initially.
/// Filtering is case sensitive matching the filter expression anywhere inside the tag
/// </summary>
/// <param name="options"></param>
/// <param name="expression"></param>
public static void EnableFilter(this SwaggerUIOptions options, string expression = null)
{
options.ConfigObject.Filter = expression ?? "";
}
/// <summary>
/// Limits the number of tagged operations displayed to at most this many. The default is to show all operations
/// </summary>
/// <param name="options"></param>
/// <param name="count"></param>
public static void MaxDisplayedTags(this SwaggerUIOptions options, int count)
{
options.ConfigObject.MaxDisplayedTags = count;
}
/// <summary>
/// Controls the display of vendor extension (x-) fields and values for Operations, Parameters, and Schema
/// </summary>
/// <param name="options"></param>
public static void ShowExtensions(this SwaggerUIOptions options)
{
options.ConfigObject.ShowExtensions = true;
}
/// <summary>
/// List of HTTP methods that have the Try it out feature enabled. An empty array disables Try it out for all operations.
/// This does not filter the operations from the display
/// </summary>
/// <param name="options"></param>
/// <param name="submitMethods"></param>
public static void SupportedSubmitMethods(this SwaggerUIOptions options, params SubmitMethod[] submitMethods)
{
options.ConfigObject.SupportedSubmitMethods = submitMethods;
}
/// <summary>
/// OAuth redirect URL
/// </summary>
/// <param name="options"></param>
/// <param name="url"></param>
public static void OAuth2RedirectUrl(this SwaggerUIOptions options, string url)
{
options.ConfigObject.OAuth2RedirectUrl = url;
}
[Obsolete("The validator is disabled by default. Use EnableValidator to enable it")]
public static void ValidatorUrl(this SwaggerUIOptions options, string url)
{
options.ConfigObject.ValidatorUrl = url;
}
/// <summary>
/// You can use this parameter to enable the swagger-ui's built-in validator (badge) functionality
/// Setting it to null will disable validation
/// </summary>
/// <param name="options"></param>
/// <param name="url"></param>
public static void EnableValidator(this SwaggerUIOptions options, string url = "https://online.swagger.io/validator")
{
options.ConfigObject.ValidatorUrl = url;
}
/// <summary>
/// Default clientId
/// </summary>
/// <param name="options"></param>
/// <param name="value"></param>
public static void OAuthClientId(this SwaggerUIOptions options, string value)
{
options.OAuthConfigObject.ClientId = value;
}
/// <summary>
/// Default clientSecret
/// </summary>
/// <param name="options"></param>
/// <param name="value"></param>
public static void OAuthClientSecret(this SwaggerUIOptions options, string value)
{
options.OAuthConfigObject.ClientSecret = value;
}
/// <summary>
/// realm query parameter (for oauth1) added to authorizationUrl and tokenUrl
/// </summary>
/// <param name="options"></param>
/// <param name="value"></param>
public static void OAuthRealm(this SwaggerUIOptions options, string value)
{
options.OAuthConfigObject.Realm = value;
}
/// <summary>
/// Application name, displayed in authorization popup
/// </summary>
/// <param name="options"></param>
/// <param name="value"></param>
public static void OAuthAppName(this SwaggerUIOptions options, string value)
{
options.OAuthConfigObject.AppName = value;
}
/// <summary>
/// Scope separator for passing scopes, encoded before calling, default value is a space (encoded value %20)
/// </summary>
/// <param name="options"></param>
/// <param name="value"></param>
public static void OAuthScopeSeparator(this SwaggerUIOptions options, string value)
{
options.OAuthConfigObject.ScopeSeperator = value;
}
/// <summary>
/// Additional query parameters added to authorizationUrl and tokenUrl
/// </summary>
/// <param name="options"></param>
/// <param name="value"></param>
public static void OAuthAdditionalQueryStringParams(
this SwaggerUIOptions options,
Dictionary<string, string> value)
{
options.OAuthConfigObject.AdditionalQueryStringParams = value;
}
/// <summary>
/// Only activated for the accessCode flow. During the authorization_code request to the tokenUrl,
/// pass the Client Password using the HTTP Basic Authentication scheme (Authorization header with
/// Basic base64encoded[client_id:client_secret]). The default is false
/// </summary>
/// <param name="options"></param>
public static void OAuthUseBasicAuthenticationWithAccessCodeGrant(this SwaggerUIOptions options)
{
options.OAuthConfigObject.UseBasicAuthenticationWithAccessCodeGrant = true;
}
}
} | 42.223077 | 129 | 0.610038 | [
"MIT"
] | DotNetExample/Surging.Sample | src/Core/Surging.Core.Swagger/SwaggerUI/SwaggerUIOptionsExtensions.cs.cs | 10,980 | C# |
using Microsoft.TeamFoundation.DistributedTask.WebApi;
using Microsoft.VisualStudio.Services.Agent.Util;
using System;
using System.Collections.Generic;
using System.Collections.Concurrent;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace Microsoft.VisualStudio.Services.Agent
{
[ServiceLocator(Default = typeof(JobServerQueue))]
public interface IJobServerQueue : IAgentService, IThrottlingReporter
{
event EventHandler<ThrottlingEventArgs> JobServerQueueThrottling;
Task ShutdownAsync();
void Start(JobRequestMessage jobRequest);
void QueueWebConsoleLine(string line);
void QueueFileUpload(Guid timelineId, Guid timelineRecordId, string type, string name, string path, bool deleteSource);
void QueueTimelineRecordUpdate(Guid timelineId, TimelineRecord timelineRecord);
}
public sealed class JobServerQueue : AgentService, IJobServerQueue
{
// Default delay for Dequeue process
private static readonly TimeSpan _aggressiveDelayForWebConsoleLineDequeue = TimeSpan.FromMilliseconds(250);
private static readonly TimeSpan _delayForWebConsoleLineDequeue = TimeSpan.FromMilliseconds(500);
private static readonly TimeSpan _delayForTimelineUpdateDequeue = TimeSpan.FromMilliseconds(500);
private static readonly TimeSpan _delayForFileUploadDequeue = TimeSpan.FromMilliseconds(1000);
// Job message information
private Guid _scopeIdentifier;
private string _hubName;
private Guid _planId;
private Guid _jobTimelineId;
private Guid _jobTimelineRecordId;
// queue for web console line
private readonly ConcurrentQueue<string> _webConsoleLineQueue = new ConcurrentQueue<string>();
// queue for file upload (log file or attachment)
private readonly ConcurrentQueue<UploadFileInfo> _fileUploadQueue = new ConcurrentQueue<UploadFileInfo>();
// queue for timeline or timeline record update (one queue per timeline)
private readonly ConcurrentDictionary<Guid, ConcurrentQueue<TimelineRecord>> _timelineUpdateQueue = new ConcurrentDictionary<Guid, ConcurrentQueue<TimelineRecord>>();
// indicate how many timelines we have, we will process _timelineUpdateQueue base on the order of timeline in this list
private readonly List<Guid> _allTimelines = new List<Guid>();
// bufferd timeline records that fail to update
private readonly Dictionary<Guid, List<TimelineRecord>> _bufferedRetryRecords = new Dictionary<Guid, List<TimelineRecord>>();
// Task for each queue's dequeue process
private Task _webConsoleLineDequeueTask;
private Task _fileUploadDequeueTask;
private Task _timelineUpdateDequeueTask;
// common
private IJobServer _jobServer;
private Task[] _allDequeueTasks;
private readonly TaskCompletionSource<int> _jobCompletionSource = new TaskCompletionSource<int>();
private bool _queueInProcess = false;
private ITerminal _term;
public event EventHandler<ThrottlingEventArgs> JobServerQueueThrottling;
// Web console dequeue will start with process queue every 250ms for the first 60*4 times (~60 seconds).
// Then the dequeue will happen every 500ms.
// In this way, customer still can get instance live console output on job start,
// at the same time we can cut the load to server after the build run for more than 60s
private int _webConsoleLineAggressiveDequeueCount = 0;
private const int _webConsoleLineAggressiveDequeueLimit = 4 * 60;
private bool _webConsoleLineAggressiveDequeue = true;
public override void Initialize(IHostContext hostContext)
{
base.Initialize(hostContext);
_jobServer = hostContext.GetService<IJobServer>();
}
public void Start(JobRequestMessage jobRequest)
{
Trace.Entering();
if (HostContext.RunMode == RunMode.Local)
{
_term = HostContext.GetService<ITerminal>();
return;
}
if (_queueInProcess)
{
Trace.Info("No-opt, all queue process tasks are running.");
return;
}
ArgUtil.NotNull(jobRequest, nameof(jobRequest));
ArgUtil.NotNull(jobRequest.Plan, nameof(jobRequest.Plan));
ArgUtil.NotNull(jobRequest.Timeline, nameof(jobRequest.Timeline));
_scopeIdentifier = jobRequest.Plan.ScopeIdentifier;
_hubName = jobRequest.Plan.PlanType;
_planId = jobRequest.Plan.PlanId;
_jobTimelineId = jobRequest.Timeline.Id;
_jobTimelineRecordId = jobRequest.JobId;
// Server already create the job timeline
_timelineUpdateQueue[_jobTimelineId] = new ConcurrentQueue<TimelineRecord>();
_allTimelines.Add(_jobTimelineId);
// Start three dequeue task
Trace.Info("Start process web console line queue.");
_webConsoleLineDequeueTask = ProcessWebConsoleLinesQueueAsync();
Trace.Info("Start process file upload queue.");
_fileUploadDequeueTask = ProcessFilesUploadQueueAsync();
Trace.Info("Start process timeline update queue.");
_timelineUpdateDequeueTask = ProcessTimelinesUpdateQueueAsync();
_allDequeueTasks = new Task[] { _webConsoleLineDequeueTask, _fileUploadDequeueTask, _timelineUpdateDequeueTask };
_queueInProcess = true;
}
// WebConsoleLine queue and FileUpload queue are always best effort
// TimelineUpdate queue error will become critical when timeline records contain output variabls.
public async Task ShutdownAsync()
{
if (HostContext.RunMode == RunMode.Local)
{
return;
}
if (!_queueInProcess)
{
Trace.Info("No-op, all queue process tasks have been stopped.");
}
Trace.Info("Fire signal to shutdown all queues.");
_jobCompletionSource.TrySetResult(0);
await Task.WhenAll(_allDequeueTasks);
_queueInProcess = false;
Trace.Info("All queue process task stopped.");
// Drain the queue
// ProcessWebConsoleLinesQueueAsync() will never throw exception, live console update is always best effort.
Trace.Verbose("Draining web console line queue.");
await ProcessWebConsoleLinesQueueAsync(runOnce: true);
Trace.Info("Web console line queue drained.");
// ProcessFilesUploadQueueAsync() will never throw exception, log file upload is always best effort.
Trace.Verbose("Draining file upload queue.");
await ProcessFilesUploadQueueAsync(runOnce: true);
Trace.Info("File upload queue drained.");
// ProcessTimelinesUpdateQueueAsync() will throw exception during shutdown
// if there is any timeline records that failed to update contains output variabls.
Trace.Verbose("Draining timeline update queue.");
await ProcessTimelinesUpdateQueueAsync(runOnce: true);
Trace.Info("Timeline update queue drained.");
Trace.Info("All queue process tasks have been stopped, and all queues are drained.");
}
public void QueueWebConsoleLine(string line)
{
Trace.Verbose("Enqueue web console line queue: {0}", line);
if (HostContext.RunMode == RunMode.Local)
{
if ((line ?? string.Empty).StartsWith("##[section]"))
{
Console.WriteLine("******************************************************************************");
Console.WriteLine(line.Substring("##[section]".Length));
Console.WriteLine("******************************************************************************");
}
else
{
Console.WriteLine(line);
}
return;
}
_webConsoleLineQueue.Enqueue(line);
}
public void QueueFileUpload(Guid timelineId, Guid timelineRecordId, string type, string name, string path, bool deleteSource)
{
if (HostContext.RunMode == RunMode.Local)
{
return;
}
ArgUtil.NotEmpty(timelineId, nameof(timelineId));
ArgUtil.NotEmpty(timelineRecordId, nameof(timelineRecordId));
// all parameter not null, file path exist.
var newFile = new UploadFileInfo()
{
TimelineId = timelineId,
TimelineRecordId = timelineRecordId,
Type = type,
Name = name,
Path = path,
DeleteSource = deleteSource
};
Trace.Verbose("Enqueue file upload queue: file '{0}' attach to record {1}", newFile.Path, timelineRecordId);
_fileUploadQueue.Enqueue(newFile);
}
public void QueueTimelineRecordUpdate(Guid timelineId, TimelineRecord timelineRecord)
{
if (HostContext.RunMode == RunMode.Local)
{
return;
}
ArgUtil.NotEmpty(timelineId, nameof(timelineId));
ArgUtil.NotNull(timelineRecord, nameof(timelineRecord));
ArgUtil.NotEmpty(timelineRecord.Id, nameof(timelineRecord.Id));
_timelineUpdateQueue.TryAdd(timelineId, new ConcurrentQueue<TimelineRecord>());
Trace.Verbose("Enqueue timeline {0} update queue: {1}", timelineId, timelineRecord.Id);
_timelineUpdateQueue[timelineId].Enqueue(timelineRecord.Clone());
}
public void ReportThrottling(TimeSpan delay, DateTime expiration)
{
Trace.Info($"Receive server throttling report, expect delay {delay} milliseconds till {expiration}");
var throttlingEvent = JobServerQueueThrottling;
if (throttlingEvent != null)
{
throttlingEvent(this, new ThrottlingEventArgs(delay, expiration));
}
}
private async Task ProcessWebConsoleLinesQueueAsync(bool runOnce = false)
{
while (!_jobCompletionSource.Task.IsCompleted || runOnce)
{
if (_webConsoleLineAggressiveDequeue && ++_webConsoleLineAggressiveDequeueCount > _webConsoleLineAggressiveDequeueLimit)
{
Trace.Info("Stop aggressive process web console line queue.");
_webConsoleLineAggressiveDequeue = false;
}
List<List<string>> batchedLines = new List<List<string>>();
List<string> currentBatch = new List<string>();
string line;
while (_webConsoleLineQueue.TryDequeue(out line))
{
if (!string.IsNullOrEmpty(line) && line.Length > 1024)
{
Trace.Verbose("Web console line is more than 1024 chars, truncate to first 1024 chars");
line = $"{line.Substring(0, 1024)}...";
}
currentBatch.Add(line);
// choose 100 lines since the whole web console UI will only shows about 40 lines in a 15" monitor.
if (currentBatch.Count > 100)
{
batchedLines.Add(currentBatch.ToList());
currentBatch.Clear();
}
// process at most about 500 lines of web console line during regular timer dequeue task.
if (!runOnce && batchedLines.Count > 5)
{
break;
}
}
if (currentBatch.Count > 0)
{
batchedLines.Add(currentBatch.ToList());
currentBatch.Clear();
}
if (batchedLines.Count > 0)
{
int errorCount = 0;
foreach (var batch in batchedLines)
{
try
{
// we will not requeue failed batch, since the web console lines are time sensitive.
await _jobServer.AppendTimelineRecordFeedAsync(_scopeIdentifier, _hubName, _planId, _jobTimelineId, _jobTimelineRecordId, batch, default(CancellationToken));
}
catch (Exception ex)
{
Trace.Info("Catch exception during append web console line, keep going since the process is best effort.");
Trace.Error(ex);
errorCount++;
}
}
Trace.Info("Try to append {0} batches web console lines, success rate: {1}/{0}.", batchedLines.Count, batchedLines.Count - errorCount);
}
if (runOnce)
{
break;
}
else
{
await Task.Delay(_webConsoleLineAggressiveDequeue ? _aggressiveDelayForWebConsoleLineDequeue : _delayForWebConsoleLineDequeue);
}
}
}
private async Task ProcessFilesUploadQueueAsync(bool runOnce = false)
{
while (!_jobCompletionSource.Task.IsCompleted || runOnce)
{
List<UploadFileInfo> filesToUpload = new List<UploadFileInfo>();
UploadFileInfo dequeueFile;
while (_fileUploadQueue.TryDequeue(out dequeueFile))
{
filesToUpload.Add(dequeueFile);
// process at most 10 file upload.
if (!runOnce && filesToUpload.Count > 10)
{
break;
}
}
if (filesToUpload.Count > 0)
{
// TODO: upload all file in parallel
int errorCount = 0;
foreach (var file in filesToUpload)
{
try
{
await UploadFile(file);
}
catch (Exception ex)
{
Trace.Info("Catch exception during log or attachment file upload, keep going since the process is best effort.");
Trace.Error(ex);
errorCount++;
// put the failed upload file back to queue.
// TODO: figure out how should we retry paging log upload.
//lock (_fileUploadQueueLock)
//{
// _fileUploadQueue.Enqueue(file);
//}
}
}
Trace.Info("Try to upload {0} log files or attachments, success rate: {1}/{0}.", filesToUpload.Count, filesToUpload.Count - errorCount);
}
if (runOnce)
{
break;
}
else
{
await Task.Delay(_delayForFileUploadDequeue);
}
}
}
private async Task ProcessTimelinesUpdateQueueAsync(bool runOnce = false)
{
while (!_jobCompletionSource.Task.IsCompleted || runOnce)
{
List<PendingTimelineRecord> pendingUpdates = new List<PendingTimelineRecord>();
foreach (var timeline in _allTimelines)
{
ConcurrentQueue<TimelineRecord> recordQueue;
if (_timelineUpdateQueue.TryGetValue(timeline, out recordQueue))
{
List<TimelineRecord> records = new List<TimelineRecord>();
TimelineRecord record;
while (recordQueue.TryDequeue(out record))
{
records.Add(record);
// process at most 25 timeline records update for each timeline.
if (!runOnce && records.Count > 25)
{
break;
}
}
if (records.Count > 0)
{
pendingUpdates.Add(new PendingTimelineRecord() { TimelineId = timeline, PendingRecords = records.ToList() });
}
}
}
// we need track whether we have new sub-timeline been created on the last run.
// if so, we need continue update timeline record even we on the last run.
bool pendingSubtimelineUpdate = false;
List<Exception> mainTimelineRecordsUpdateErrors = new List<Exception>();
if (pendingUpdates.Count > 0)
{
foreach (var update in pendingUpdates)
{
List<TimelineRecord> bufferedRecords;
if (_bufferedRetryRecords.TryGetValue(update.TimelineId, out bufferedRecords))
{
update.PendingRecords.InsertRange(0, bufferedRecords);
}
update.PendingRecords = MergeTimelineRecords(update.PendingRecords);
foreach (var detailTimeline in update.PendingRecords.Where(r => r.Details != null))
{
if (!_allTimelines.Contains(detailTimeline.Details.Id))
{
try
{
Timeline newTimeline = await _jobServer.CreateTimelineAsync(_scopeIdentifier, _hubName, _planId, detailTimeline.Details.Id, default(CancellationToken));
_allTimelines.Add(newTimeline.Id);
pendingSubtimelineUpdate = true;
}
catch (TimelineExistsException)
{
Trace.Info("Catch TimelineExistsException during timeline creation. Ignore the error since server already had this timeline.");
_allTimelines.Add(detailTimeline.Details.Id);
}
catch (Exception ex)
{
Trace.Error(ex);
}
}
}
try
{
await _jobServer.UpdateTimelineRecordsAsync(_scopeIdentifier, _hubName, _planId, update.TimelineId, update.PendingRecords, default(CancellationToken));
if (_bufferedRetryRecords.Remove(update.TimelineId))
{
Trace.Verbose("Cleanup buffered timeline record for timeline: {0}.", update.TimelineId);
}
}
catch (Exception ex)
{
Trace.Info("Catch exception during update timeline records, try to update these timeline records next time.");
Trace.Error(ex);
_bufferedRetryRecords[update.TimelineId] = update.PendingRecords.ToList();
if (update.TimelineId == _jobTimelineId)
{
mainTimelineRecordsUpdateErrors.Add(ex);
}
}
}
}
if (runOnce)
{
// continue process timeline records update,
// we might have more records need update,
// since we just create a new sub-timeline
if (pendingSubtimelineUpdate)
{
continue;
}
else
{
if (mainTimelineRecordsUpdateErrors.Count > 0 &&
_bufferedRetryRecords.ContainsKey(_jobTimelineId) &&
_bufferedRetryRecords[_jobTimelineId] != null &&
_bufferedRetryRecords[_jobTimelineId].Any(r => r.Variables.Count > 0))
{
Trace.Info("Fail to update timeline records with output variables. Throw exception to fail the job since output variables are critical to downstream jobs.");
throw new AggregateException(StringUtil.Loc("OutputVariablePublishFailed"), mainTimelineRecordsUpdateErrors);
}
else
{
break;
}
}
}
else
{
await Task.Delay(_delayForTimelineUpdateDequeue);
}
}
}
private List<TimelineRecord> MergeTimelineRecords(List<TimelineRecord> timelineRecords)
{
if (timelineRecords == null || timelineRecords.Count <= 1)
{
return timelineRecords;
}
Dictionary<Guid, TimelineRecord> dict = new Dictionary<Guid, TimelineRecord>();
foreach (TimelineRecord rec in timelineRecords)
{
if (rec == null)
{
continue;
}
TimelineRecord timelineRecord;
if (dict.TryGetValue(rec.Id, out timelineRecord))
{
// Merge rec into timelineRecord
timelineRecord.CurrentOperation = rec.CurrentOperation ?? timelineRecord.CurrentOperation;
timelineRecord.Details = rec.Details ?? timelineRecord.Details;
timelineRecord.FinishTime = rec.FinishTime ?? timelineRecord.FinishTime;
timelineRecord.Log = rec.Log ?? timelineRecord.Log;
timelineRecord.Name = rec.Name ?? timelineRecord.Name;
timelineRecord.RefName = rec.RefName ?? timelineRecord.RefName;
timelineRecord.PercentComplete = rec.PercentComplete ?? timelineRecord.PercentComplete;
timelineRecord.RecordType = rec.RecordType ?? timelineRecord.RecordType;
timelineRecord.Result = rec.Result ?? timelineRecord.Result;
timelineRecord.ResultCode = rec.ResultCode ?? timelineRecord.ResultCode;
timelineRecord.StartTime = rec.StartTime ?? timelineRecord.StartTime;
timelineRecord.State = rec.State ?? timelineRecord.State;
timelineRecord.WorkerName = rec.WorkerName ?? timelineRecord.WorkerName;
if (rec.ErrorCount != null && rec.ErrorCount > 0)
{
timelineRecord.ErrorCount = rec.ErrorCount;
}
if (rec.WarningCount != null && rec.WarningCount > 0)
{
timelineRecord.WarningCount = rec.WarningCount;
}
if (rec.Issues.Count > 0)
{
timelineRecord.Issues.Clear();
timelineRecord.Issues.AddRange(rec.Issues.Select(i => i.Clone()));
}
if (rec.Variables.Count > 0)
{
foreach (var variable in rec.Variables)
{
timelineRecord.Variables[variable.Key] = variable.Value.Clone();
}
}
}
else
{
dict.Add(rec.Id, rec);
}
}
var mergedRecords = dict.Values.ToList();
Trace.Verbose("Merged Timeline records");
foreach (var record in mergedRecords)
{
Trace.Verbose($" Record: t={record.RecordType}, n={record.Name}, s={record.State}, st={record.StartTime}, {record.PercentComplete}%, ft={record.FinishTime}, r={record.Result}: {record.CurrentOperation}");
if (record.Issues != null && record.Issues.Count > 0)
{
foreach (var issue in record.Issues)
{
String source;
issue.Data.TryGetValue("sourcepath", out source);
Trace.Verbose($" Issue: c={issue.Category}, t={issue.Type}, s={source ?? string.Empty}, m={issue.Message}");
}
}
if (record.Variables != null && record.Variables.Count > 0)
{
foreach (var variable in record.Variables)
{
Trace.Verbose($" Variable: n={variable.Key}, secret={variable.Value.IsSecret}");
}
}
}
return mergedRecords;
}
private async Task UploadFile(UploadFileInfo file)
{
bool uploadSucceed = false;
try
{
if (String.Equals(file.Type, CoreAttachmentType.Log, StringComparison.OrdinalIgnoreCase))
{
// Create the log
var taskLog = await _jobServer.CreateLogAsync(_scopeIdentifier, _hubName, _planId, new TaskLog(String.Format(@"logs\{0:D}", file.TimelineRecordId)), default(CancellationToken));
// Upload the contents
using (FileStream fs = File.Open(file.Path, FileMode.Open, FileAccess.Read, FileShare.Read))
{
var logUploaded = await _jobServer.AppendLogContentAsync(_scopeIdentifier, _hubName, _planId, taskLog.Id, fs, default(CancellationToken));
}
// Create a new record and only set the Log field
var attachmentUpdataRecord = new TimelineRecord() { Id = file.TimelineRecordId, Log = taskLog };
QueueTimelineRecordUpdate(file.TimelineId, attachmentUpdataRecord);
}
else
{
// Create attachment
using (FileStream fs = File.Open(file.Path, FileMode.Open, FileAccess.Read, FileShare.Read))
{
var result = await _jobServer.CreateAttachmentAsync(_scopeIdentifier, _hubName, _planId, file.TimelineId, file.TimelineRecordId, file.Type, file.Name, fs, default(CancellationToken));
}
}
uploadSucceed = true;
}
finally
{
if (uploadSucceed && file.DeleteSource)
{
try
{
File.Delete(file.Path);
}
catch (Exception ex)
{
Trace.Info("Catch exception during delete success uploaded file.");
Trace.Error(ex);
}
}
}
}
}
internal class PendingTimelineRecord
{
public Guid TimelineId { get; set; }
public List<TimelineRecord> PendingRecords { get; set; }
}
internal class UploadFileInfo
{
public Guid TimelineId { get; set; }
public Guid TimelineRecordId { get; set; }
public string Type { get; set; }
public string Name { get; set; }
public string Path { get; set; }
public bool DeleteSource { get; set; }
}
} | 44.5 | 223 | 0.526345 | [
"MIT"
] | SpillChek2/Spill-Chek-vsts-agent | src/Microsoft.VisualStudio.Services.Agent/JobServerQueue.cs | 28,658 | C# |
namespace Chartreuse.Today.Exchange.Ews.Schema
{
public static class EwsPropertySet
{
public const string PropertySetTask = "00062003-0000-0000-C000-000000000046";
public const string PropertySetCommon = "00062008-0000-0000-C000-000000000046";
}
} | 34.625 | 87 | 0.729242 | [
"MIT"
] | 2DayApp/2day | src/2Day.Exchange.Shared/Ews/Schema/EwsPropertySet.cs | 277 | C# |
using System;
using System.Windows.Data;
using System.Windows.Media;
using WpfConverters.Converters.Base;
namespace WpfConverters.Converters {
[ValueConversion(typeof(Object), typeof(Brush))]
public class NullToBrushConverter : NullConverter<Brush> {
public NullToBrushConverter() : this(Brushes.Red, Brushes.Green) { }
public NullToBrushConverter(Brush @null, Brush notNull) : base(@null, notNull) { }
}
}
| 24.555556 | 90 | 0.726244 | [
"MIT"
] | MikeLimaSierra/Examples | Blog/2021-03-WpfConverters/WpfConverters/Converters/NullToBrushConverter.cs | 444 | C# |
// Copyright (c) Josef Pihrt. 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;
namespace Roslynator
{
internal static class EnumerableExtensions
{
public static bool IsSorted<T>(this IEnumerable<T> enumerable, IComparer<T> comparer)
{
using (IEnumerator<T> en = enumerable.GetEnumerator())
{
if (en.MoveNext())
{
T member1 = en.Current;
while (en.MoveNext())
{
T member2 = en.Current;
if (comparer.Compare(member1, member2) > 0)
return false;
member1 = member2;
}
}
}
return true;
}
public static IEnumerable<T> ModifyRange<T>(
this IEnumerable<T> enumerable,
int startIndex,
int count,
Func<T, T> selector)
{
if (enumerable == null)
throw new ArgumentNullException(nameof(enumerable));
if (selector == null)
throw new ArgumentNullException(nameof(selector));
if (startIndex < 0)
throw new ArgumentOutOfRangeException(nameof(startIndex), startIndex, "");
if (count < 0)
throw new ArgumentOutOfRangeException(nameof(count), count, "");
return ModifyRange();
IEnumerable<T> ModifyRange()
{
using (IEnumerator<T> en = enumerable.GetEnumerator())
{
int i = 0;
while (i < startIndex)
{
if (!en.MoveNext())
throw new InvalidOperationException();
yield return en.Current;
i++;
}
int endIndex = startIndex + count;
while (i < endIndex)
{
if (!en.MoveNext())
throw new InvalidOperationException();
yield return selector(en.Current);
i++;
}
while (en.MoveNext())
yield return en.Current;
}
}
}
}
}
| 29.44186 | 160 | 0.445498 | [
"Apache-2.0"
] | ADIX7/Roslynator | src/Core/Extensions/EnumerableExtensions.cs | 2,534 | C# |
namespace Ancestry.Daisy.Language.AST.Trace
{
public class TraceNode : IDaisyAstNode
{
protected TraceNode(object scope,bool outcome)
{
Outcome = outcome;
Scope = scope;
}
public bool Outcome { get; private set; }
public object Scope { get; private set; }
}
}
| 22.125 | 55 | 0.550847 | [
"MIT"
] | erikhejl/Daisy | Daisy/Language/AST/Trace/TraceNode.cs | 341 | C# |
//using System.Collections.Generic;
//using System.Linq;
//using Mono.Cecil;
//using Xels.ModuleValidation.Net;
//using Xels.ModuleValidation.Net.Format;
//namespace Xels.SmartContracts.CLR.Validation
//{
// /// <summary>
// /// Validates the Type definitions contained within a module definition
// /// </summary>
// public class SmartContractTypeDefinitionValidator : IModuleDefinitionValidator
// {
// private static readonly IEnumerable<ITypeDefinitionValidator> TypeDefinitionValidators = new List<ITypeDefinitionValidator>
// {
// new NestedTypeValidator(),
// new NamespaceValidator(),
// new InheritsSmartContractValidator(),
// new SingleConstructorValidator(),
// new ConstructorParamValidator(),
// new AsyncValidator()
// };
// public IEnumerable<ValidationResult> Validate(ModuleDefinition moduleDefinition)
// {
// var errors = new List<ValidationResult>();
// IEnumerable<TypeDefinition> contractTypes = moduleDefinition.Types.Where(x => !TypesToIgnoreUtil.Ignore.Contains(x.FullName)).ToList();
// foreach(TypeDefinition contractType in contractTypes)
// {
// foreach (ITypeDefinitionValidator typeDefValidator in TypeDefinitionValidators)
// {
// errors.AddRange(typeDefValidator.Validate(contractType));
// }
// }
// return errors;
// }
// }
//} | 37.195122 | 149 | 0.633443 | [
"MIT"
] | xels-io/SideChain-SmartContract | src/Xels.SmartContracts.CLR.Validation/SmartContractTypeDefinitionValidator.cs | 1,527 | C# |
/*
* Copyright 2018 JDCLOUD.COM
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http:#www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Disk
* 与云硬盘相关的接口
*
* OpenAPI spec version: v1
* Contact:
*
* NOTE: This class is auto generated by the jdcloud code generator program.
*/
using System;
using System.Collections.Generic;
using System.Text;
using JDCloudSDK.Core.Service;
using JDCloudSDK.Jdfusion.Model;
using JDCloudSDK.Core.Annotation;
namespace JDCloudSDK.Jdfusion.Apis
{
/// <summary>
/// 根据云提供商创建云硬盘
/// </summary>
public class CreateDiskRequest : JdcloudRequest
{
///<summary>
/// 创建云硬盘
///Required:true
///</summary>
[Required]
public CreateDataDisk Disk{ get; set; }
///<summary>
/// 地域ID
///Required:true
///</summary>
[Required]
public override string RegionId{ get; set; }
}
} | 25.181818 | 76 | 0.661372 | [
"Apache-2.0"
] | jdcloud-api/jdcloud-sdk-net | sdk/src/Service/Jdfusion/Apis/CreateDiskRequest.cs | 1,439 | C# |
using System.Collections.Generic;
using Stateless.Reflection;
namespace Stateless.Graph
{
/// <summary>
/// Used to keep track of transitions between states
/// </summary>
public class Transition
{
/// <summary>
/// List of actions to be performed by the destination state (the one being entered)
/// </summary>
public List<ActionInfo> destinationEntryActions = new List<ActionInfo>();
/// <summary>
/// Base class of transitions
/// </summary>
/// <param name="sourceState"></param>
/// <param name="trigger"></param>
public Transition(State sourceState, TriggerInfo trigger)
{
this.SourceState = sourceState;
this.Trigger = trigger;
}
/// <summary>
/// The trigger that causes this transition
/// </summary>
public TriggerInfo Trigger { get; }
/// <summary>
/// Should the entry and exit actions be executed when this transition takes place
/// </summary>
public bool ExecuteEntryExitActions { get; protected set; } = true;
/// <summary>
/// The state where this transition starts
/// </summary>
public State SourceState { get; }
}
internal class FixedTransition : Transition
{
public FixedTransition(State sourceState, State destinationState, TriggerInfo trigger,
IEnumerable<InvocationInfo> guards)
: base(sourceState, trigger)
{
this.DestinationState = destinationState;
this.Guards = guards;
}
/// <summary>
/// The state where this transition finishes
/// </summary>
public State DestinationState { get; }
/// <summary>
/// Guard functions for this transition (null if none)
/// </summary>
public IEnumerable<InvocationInfo> Guards { get; }
}
internal class DynamicTransition : Transition
{
public DynamicTransition(State sourceState, State destinationState, TriggerInfo trigger, string criterion)
: base(sourceState, trigger)
{
this.DestinationState = destinationState;
this.Criterion = criterion;
}
/// <summary>
/// The state where this transition finishes
/// </summary>
public State DestinationState { get; }
/// <summary>
/// When is this transition followed
/// </summary>
public string Criterion { get; }
}
internal class StayTransition : Transition
{
public StayTransition(State sourceState, TriggerInfo trigger, IEnumerable<InvocationInfo> guards,
bool executeEntryExitActions)
: base(sourceState, trigger)
{
this.ExecuteEntryExitActions = executeEntryExitActions;
this.Guards = guards;
}
public IEnumerable<InvocationInfo> Guards { get; }
}
} | 31.5625 | 114 | 0.585479 | [
"Apache-2.0"
] | shoff/stateless | src/Stateless/Graph/Transition.cs | 3,032 | C# |
// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information.
// Ported from um/ShObjIdl_core.h in the Windows SDK for Windows 10.0.22000.0
// Original source is Copyright © Microsoft. All rights reserved.
namespace TerraFX.Interop.Windows;
/// <include file='SVUIA_STATUS.xml' path='doc/member[@name="SVUIA_STATUS"]/*' />
public enum SVUIA_STATUS
{
/// <include file='SVUIA_STATUS.xml' path='doc/member[@name="SVUIA_STATUS.SVUIA_DEACTIVATE"]/*' />
SVUIA_DEACTIVATE = 0,
/// <include file='SVUIA_STATUS.xml' path='doc/member[@name="SVUIA_STATUS.SVUIA_ACTIVATE_NOFOCUS"]/*' />
SVUIA_ACTIVATE_NOFOCUS = 1,
/// <include file='SVUIA_STATUS.xml' path='doc/member[@name="SVUIA_STATUS.SVUIA_ACTIVATE_FOCUS"]/*' />
SVUIA_ACTIVATE_FOCUS = 2,
/// <include file='SVUIA_STATUS.xml' path='doc/member[@name="SVUIA_STATUS.SVUIA_INPLACEACTIVATE"]/*' />
SVUIA_INPLACEACTIVATE = 3,
}
| 42.956522 | 145 | 0.723684 | [
"MIT"
] | reflectronic/terrafx.interop.windows | sources/Interop/Windows/Windows/um/ShObjIdl_core/SVUIA_STATUS.cs | 990 | C# |
namespace Server.Infrastructure.Mappings.Contracts
{
public interface IMapTo<T>
{
}
} | 16.333333 | 51 | 0.693878 | [
"MIT"
] | Dreed657/QuizSystem | Server/Server/Infrastructure/Mappings/Contracts/IMapTo.cs | 100 | C# |
using FileExplorer.UIEventHub.Defines;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;
namespace FileExplorer.UIEventHub
{
public enum DragState { Normal, Touched, Pressed, TouchDragging, Dragging, Released }
public class DragInputProcessor : InputProcessorBase
{
#region Constructors
public DragInputProcessor()
{
ProcessAllEvents = false;
_processEvents.AddRange(new[] {
UIElement.PreviewMouseDownEvent,
UIElement.PreviewTouchDownEvent,
UIElement.MouseMoveEvent,
UIElement.TouchMoveEvent,
UIElement.PreviewMouseUpEvent,
UIElement.PreviewTouchUpEvent
}
);
}
#endregion
#region Methods
public override void Update(ref IUIInput input)
{
switch (input.InputState)
{
case UIInputState.Pressed:
UpdateInputPressed(input);
break;
case UIInputState.Released:
UpdatInputReleased(input);
break;
default:
UpdateInputPosition(input);
break;
}
input.IsDragging = IsDragging;
if (IsDragging)
input.TouchGesture = UITouchGesture.Drag;
}
public void UpdateInputPosition(IUIInput input)
{
if (_dragState == DragState.Touched && input.EventArgs is TouchEventArgs)
{
if (DateTime.UtcNow.Subtract(_touchTime).TotalMilliseconds >= Defaults.MaximumTouchHoldInterval)
{
var rect = (input.EventArgs as TouchEventArgs).GetTouchPoint(null).Size;
if ((input as TouchInput).IsDragThresholdReached(_startTouchInput as TouchInput))
{
StartInput = _startTouchInput;
_dragState = DragState.Pressed;
//_touchTime = DateTime.MinValue;
//_isDragging = true;
//DragStartedFunc(input);
}
else
{
_touchTime = DateTime.MinValue;
_dragState = DragState.Normal;
}
}
}
//Console.WriteLine(String.Format("UpdateInputPosition - {0}", _dragState));
if (_dragState == DragState.Pressed && input.IsDragThresholdReached(_startInput))
{
_dragState = DragState.Dragging;
_isDragging = true;
DragStartedFunc(input);
}
}
public void UpdatInputReleased(IUIInput input)
{
//Console.WriteLine("UpdatInputReleased -" + input.ToString());
if (input.IsSameSource(_startInput))
{
if (_isDragging && _dragState == DragState.Dragging)
{
DragStoppedFunc(input);
}
_isDragging = false;
_dragState = DragState.Released;
}
//Console.WriteLine(String.Format("UpdatInputReleased - {0}", _dragState));
}
public void UpdateInputPressed(IUIInput input)
{
if (_dragState == DragState.Released)
{
StartInput = InvalidInput.Instance;
_dragState = DragState.Normal;
}
if (!_isDragging && input.IsValidPositionForLisView(true))
if (input.ClickCount <= 1) //Touch/Stylus input 's ClickCount = 0
{
//When touch and hold it raise a mouse right click command, skip it.
if (_dragState == DragState.Touched && input.InputType == UIInputType.MouseRight)
return;
//Console.WriteLine(input);
StartInput = input;
_isDragging = false;
switch (input.InputType)
{
case UIInputType.Touch:
_startTouchInput = input;
_dragState = DragState.Touched;
_touchTime = DateTime.UtcNow;
//input.EventArgs.Handled = true;
break;
default:
switch (_dragState)
{
case DragState.Touched:
break;
case DragState.Normal:
case DragState.Released:
IsDragging = false;
_dragState = DragState.Pressed;
break;
}
break;
}
}
//Console.WriteLine(String.Format("UpdateInputPressed - {0}", _dragState));
}
#endregion
#region Data
private DateTime _touchTime = DateTime.MinValue;
private DragState _dragState = DragState.Normal;
private bool _isDragging = false;
private IUIInput _startInput = InvalidInput.Instance;
private IUIInput _startTouchInput = InvalidInput.Instance;
//private Func<Point, Point> _positionAdjustFunc = pt => pt;
#endregion
#region Public Properties
//public Func<Point, Point> PositionAdjustFunc { get { return _positionAdjustFunc; } set { _positionAdjustFunc = value; } }
public DragState DragState { get { return _dragState; } set { _dragState = value; } }
public IUIInput StartInput
{
get { return _startInput; }
private set { _startInput = value; /*Console.WriteLine("StartInput =" + value.ToString());*/ }
}
public bool IsDragging
{
get { return _isDragging; }
set
{
_isDragging = value;
if (!value && _dragState == DragState.Dragging)
StartInput = InvalidInput.Instance;
_dragState = DragState.Normal;
}
}
public Action<IUIInput> DragStartedFunc = (currentInput) => { };
public Action<IUIInput> DragStoppedFunc = (currentInput) => { };
#endregion
}
}
| 35.765306 | 132 | 0.477033 | [
"MIT"
] | chengming0916/FileExplorer | src/FileExplorer3/app/FileExplorer.UIEventHub/Implements/DragInputProcessor.cs | 7,012 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// <auto-generated/>
#nullable disable
using System;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using Azure;
using Azure.Core;
using Azure.Core.Pipeline;
using Azure.ResourceManager.Core;
using Azure.ResourceManager.Network.Models;
namespace Azure.ResourceManager.Network
{
internal partial class NetworkVirtualAppliancesRestOperations
{
private readonly string _userAgent;
private readonly HttpPipeline _pipeline;
private readonly Uri _endpoint;
private readonly string _apiVersion;
/// <summary> Initializes a new instance of NetworkVirtualAppliancesRestOperations. </summary>
/// <param name="pipeline"> The HTTP pipeline for sending and receiving REST requests and responses. </param>
/// <param name="applicationId"> The application id to use for user agent. </param>
/// <param name="endpoint"> server parameter. </param>
/// <param name="apiVersion"> Api Version. </param>
/// <exception cref="ArgumentNullException"> <paramref name="pipeline"/> or <paramref name="apiVersion"/> is null. </exception>
public NetworkVirtualAppliancesRestOperations(HttpPipeline pipeline, string applicationId, Uri endpoint = null, string apiVersion = default)
{
_pipeline = pipeline ?? throw new ArgumentNullException(nameof(pipeline));
_endpoint = endpoint ?? new Uri("https://management.azure.com");
_apiVersion = apiVersion ?? "2021-02-01";
_userAgent = Core.HttpMessageUtilities.GetUserAgentName(this, applicationId);
}
internal HttpMessage CreateDeleteRequest(string subscriptionId, string resourceGroupName, string networkVirtualApplianceName)
{
var message = _pipeline.CreateMessage();
var request = message.Request;
request.Method = RequestMethod.Delete;
var uri = new RawRequestUriBuilder();
uri.Reset(_endpoint);
uri.AppendPath("/subscriptions/", false);
uri.AppendPath(subscriptionId, true);
uri.AppendPath("/resourceGroups/", false);
uri.AppendPath(resourceGroupName, true);
uri.AppendPath("/providers/Microsoft.Network/networkVirtualAppliances/", false);
uri.AppendPath(networkVirtualApplianceName, true);
uri.AppendQuery("api-version", _apiVersion, true);
request.Uri = uri;
request.Headers.Add("Accept", "application/json");
message.SetProperty("SDKUserAgent", _userAgent);
return message;
}
/// <summary> Deletes the specified Network Virtual Appliance. </summary>
/// <param name="subscriptionId"> The subscription credentials which uniquely identify the Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. </param>
/// <param name="resourceGroupName"> The name of the resource group. </param>
/// <param name="networkVirtualApplianceName"> The name of Network Virtual Appliance. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/> or <paramref name="networkVirtualApplianceName"/> is null. </exception>
/// <exception cref="ArgumentException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/> or <paramref name="networkVirtualApplianceName"/> is an empty string, and was expected to be non-empty. </exception>
public async Task<Response> DeleteAsync(string subscriptionId, string resourceGroupName, string networkVirtualApplianceName, CancellationToken cancellationToken = default)
{
Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId));
Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName));
Argument.AssertNotNullOrEmpty(networkVirtualApplianceName, nameof(networkVirtualApplianceName));
using var message = CreateDeleteRequest(subscriptionId, resourceGroupName, networkVirtualApplianceName);
await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false);
switch (message.Response.Status)
{
case 200:
case 202:
case 204:
return message.Response;
default:
throw new RequestFailedException(message.Response);
}
}
/// <summary> Deletes the specified Network Virtual Appliance. </summary>
/// <param name="subscriptionId"> The subscription credentials which uniquely identify the Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. </param>
/// <param name="resourceGroupName"> The name of the resource group. </param>
/// <param name="networkVirtualApplianceName"> The name of Network Virtual Appliance. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/> or <paramref name="networkVirtualApplianceName"/> is null. </exception>
/// <exception cref="ArgumentException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/> or <paramref name="networkVirtualApplianceName"/> is an empty string, and was expected to be non-empty. </exception>
public Response Delete(string subscriptionId, string resourceGroupName, string networkVirtualApplianceName, CancellationToken cancellationToken = default)
{
Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId));
Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName));
Argument.AssertNotNullOrEmpty(networkVirtualApplianceName, nameof(networkVirtualApplianceName));
using var message = CreateDeleteRequest(subscriptionId, resourceGroupName, networkVirtualApplianceName);
_pipeline.Send(message, cancellationToken);
switch (message.Response.Status)
{
case 200:
case 202:
case 204:
return message.Response;
default:
throw new RequestFailedException(message.Response);
}
}
internal HttpMessage CreateGetRequest(string subscriptionId, string resourceGroupName, string networkVirtualApplianceName, string expand)
{
var message = _pipeline.CreateMessage();
var request = message.Request;
request.Method = RequestMethod.Get;
var uri = new RawRequestUriBuilder();
uri.Reset(_endpoint);
uri.AppendPath("/subscriptions/", false);
uri.AppendPath(subscriptionId, true);
uri.AppendPath("/resourceGroups/", false);
uri.AppendPath(resourceGroupName, true);
uri.AppendPath("/providers/Microsoft.Network/networkVirtualAppliances/", false);
uri.AppendPath(networkVirtualApplianceName, true);
uri.AppendQuery("api-version", _apiVersion, true);
if (expand != null)
{
uri.AppendQuery("$expand", expand, true);
}
request.Uri = uri;
request.Headers.Add("Accept", "application/json");
message.SetProperty("SDKUserAgent", _userAgent);
return message;
}
/// <summary> Gets the specified Network Virtual Appliance. </summary>
/// <param name="subscriptionId"> The subscription credentials which uniquely identify the Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. </param>
/// <param name="resourceGroupName"> The name of the resource group. </param>
/// <param name="networkVirtualApplianceName"> The name of Network Virtual Appliance. </param>
/// <param name="expand"> Expands referenced resources. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/> or <paramref name="networkVirtualApplianceName"/> is null. </exception>
/// <exception cref="ArgumentException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/> or <paramref name="networkVirtualApplianceName"/> is an empty string, and was expected to be non-empty. </exception>
public async Task<Response<NetworkVirtualApplianceData>> GetAsync(string subscriptionId, string resourceGroupName, string networkVirtualApplianceName, string expand = null, CancellationToken cancellationToken = default)
{
Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId));
Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName));
Argument.AssertNotNullOrEmpty(networkVirtualApplianceName, nameof(networkVirtualApplianceName));
using var message = CreateGetRequest(subscriptionId, resourceGroupName, networkVirtualApplianceName, expand);
await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false);
switch (message.Response.Status)
{
case 200:
{
NetworkVirtualApplianceData value = default;
using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, default, cancellationToken).ConfigureAwait(false);
value = NetworkVirtualApplianceData.DeserializeNetworkVirtualApplianceData(document.RootElement);
return Response.FromValue(value, message.Response);
}
case 404:
return Response.FromValue((NetworkVirtualApplianceData)null, message.Response);
default:
throw new RequestFailedException(message.Response);
}
}
/// <summary> Gets the specified Network Virtual Appliance. </summary>
/// <param name="subscriptionId"> The subscription credentials which uniquely identify the Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. </param>
/// <param name="resourceGroupName"> The name of the resource group. </param>
/// <param name="networkVirtualApplianceName"> The name of Network Virtual Appliance. </param>
/// <param name="expand"> Expands referenced resources. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/> or <paramref name="networkVirtualApplianceName"/> is null. </exception>
/// <exception cref="ArgumentException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/> or <paramref name="networkVirtualApplianceName"/> is an empty string, and was expected to be non-empty. </exception>
public Response<NetworkVirtualApplianceData> Get(string subscriptionId, string resourceGroupName, string networkVirtualApplianceName, string expand = null, CancellationToken cancellationToken = default)
{
Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId));
Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName));
Argument.AssertNotNullOrEmpty(networkVirtualApplianceName, nameof(networkVirtualApplianceName));
using var message = CreateGetRequest(subscriptionId, resourceGroupName, networkVirtualApplianceName, expand);
_pipeline.Send(message, cancellationToken);
switch (message.Response.Status)
{
case 200:
{
NetworkVirtualApplianceData value = default;
using var document = JsonDocument.Parse(message.Response.ContentStream);
value = NetworkVirtualApplianceData.DeserializeNetworkVirtualApplianceData(document.RootElement);
return Response.FromValue(value, message.Response);
}
case 404:
return Response.FromValue((NetworkVirtualApplianceData)null, message.Response);
default:
throw new RequestFailedException(message.Response);
}
}
internal HttpMessage CreateUpdateTagsRequest(string subscriptionId, string resourceGroupName, string networkVirtualApplianceName, TagsObject parameters)
{
var message = _pipeline.CreateMessage();
var request = message.Request;
request.Method = RequestMethod.Patch;
var uri = new RawRequestUriBuilder();
uri.Reset(_endpoint);
uri.AppendPath("/subscriptions/", false);
uri.AppendPath(subscriptionId, true);
uri.AppendPath("/resourceGroups/", false);
uri.AppendPath(resourceGroupName, true);
uri.AppendPath("/providers/Microsoft.Network/networkVirtualAppliances/", false);
uri.AppendPath(networkVirtualApplianceName, true);
uri.AppendQuery("api-version", _apiVersion, true);
request.Uri = uri;
request.Headers.Add("Accept", "application/json");
request.Headers.Add("Content-Type", "application/json");
var content = new Utf8JsonRequestContent();
content.JsonWriter.WriteObjectValue(parameters);
request.Content = content;
message.SetProperty("SDKUserAgent", _userAgent);
return message;
}
/// <summary> Updates a Network Virtual Appliance. </summary>
/// <param name="subscriptionId"> The subscription credentials which uniquely identify the Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. </param>
/// <param name="resourceGroupName"> The resource group name of Network Virtual Appliance. </param>
/// <param name="networkVirtualApplianceName"> The name of Network Virtual Appliance being updated. </param>
/// <param name="parameters"> Parameters supplied to Update Network Virtual Appliance Tags. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/>, <paramref name="networkVirtualApplianceName"/> or <paramref name="parameters"/> is null. </exception>
/// <exception cref="ArgumentException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/> or <paramref name="networkVirtualApplianceName"/> is an empty string, and was expected to be non-empty. </exception>
public async Task<Response<NetworkVirtualApplianceData>> UpdateTagsAsync(string subscriptionId, string resourceGroupName, string networkVirtualApplianceName, TagsObject parameters, CancellationToken cancellationToken = default)
{
Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId));
Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName));
Argument.AssertNotNullOrEmpty(networkVirtualApplianceName, nameof(networkVirtualApplianceName));
Argument.AssertNotNull(parameters, nameof(parameters));
using var message = CreateUpdateTagsRequest(subscriptionId, resourceGroupName, networkVirtualApplianceName, parameters);
await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false);
switch (message.Response.Status)
{
case 200:
{
NetworkVirtualApplianceData value = default;
using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, default, cancellationToken).ConfigureAwait(false);
value = NetworkVirtualApplianceData.DeserializeNetworkVirtualApplianceData(document.RootElement);
return Response.FromValue(value, message.Response);
}
default:
throw new RequestFailedException(message.Response);
}
}
/// <summary> Updates a Network Virtual Appliance. </summary>
/// <param name="subscriptionId"> The subscription credentials which uniquely identify the Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. </param>
/// <param name="resourceGroupName"> The resource group name of Network Virtual Appliance. </param>
/// <param name="networkVirtualApplianceName"> The name of Network Virtual Appliance being updated. </param>
/// <param name="parameters"> Parameters supplied to Update Network Virtual Appliance Tags. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/>, <paramref name="networkVirtualApplianceName"/> or <paramref name="parameters"/> is null. </exception>
/// <exception cref="ArgumentException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/> or <paramref name="networkVirtualApplianceName"/> is an empty string, and was expected to be non-empty. </exception>
public Response<NetworkVirtualApplianceData> UpdateTags(string subscriptionId, string resourceGroupName, string networkVirtualApplianceName, TagsObject parameters, CancellationToken cancellationToken = default)
{
Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId));
Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName));
Argument.AssertNotNullOrEmpty(networkVirtualApplianceName, nameof(networkVirtualApplianceName));
Argument.AssertNotNull(parameters, nameof(parameters));
using var message = CreateUpdateTagsRequest(subscriptionId, resourceGroupName, networkVirtualApplianceName, parameters);
_pipeline.Send(message, cancellationToken);
switch (message.Response.Status)
{
case 200:
{
NetworkVirtualApplianceData value = default;
using var document = JsonDocument.Parse(message.Response.ContentStream);
value = NetworkVirtualApplianceData.DeserializeNetworkVirtualApplianceData(document.RootElement);
return Response.FromValue(value, message.Response);
}
default:
throw new RequestFailedException(message.Response);
}
}
internal HttpMessage CreateCreateOrUpdateRequest(string subscriptionId, string resourceGroupName, string networkVirtualApplianceName, NetworkVirtualApplianceData parameters)
{
var message = _pipeline.CreateMessage();
var request = message.Request;
request.Method = RequestMethod.Put;
var uri = new RawRequestUriBuilder();
uri.Reset(_endpoint);
uri.AppendPath("/subscriptions/", false);
uri.AppendPath(subscriptionId, true);
uri.AppendPath("/resourceGroups/", false);
uri.AppendPath(resourceGroupName, true);
uri.AppendPath("/providers/Microsoft.Network/networkVirtualAppliances/", false);
uri.AppendPath(networkVirtualApplianceName, true);
uri.AppendQuery("api-version", _apiVersion, true);
request.Uri = uri;
request.Headers.Add("Accept", "application/json");
request.Headers.Add("Content-Type", "application/json");
var content = new Utf8JsonRequestContent();
content.JsonWriter.WriteObjectValue(parameters);
request.Content = content;
message.SetProperty("SDKUserAgent", _userAgent);
return message;
}
/// <summary> Creates or updates the specified Network Virtual Appliance. </summary>
/// <param name="subscriptionId"> The subscription credentials which uniquely identify the Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. </param>
/// <param name="resourceGroupName"> The name of the resource group. </param>
/// <param name="networkVirtualApplianceName"> The name of Network Virtual Appliance. </param>
/// <param name="parameters"> Parameters supplied to the create or update Network Virtual Appliance. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/>, <paramref name="networkVirtualApplianceName"/> or <paramref name="parameters"/> is null. </exception>
/// <exception cref="ArgumentException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/> or <paramref name="networkVirtualApplianceName"/> is an empty string, and was expected to be non-empty. </exception>
public async Task<Response> CreateOrUpdateAsync(string subscriptionId, string resourceGroupName, string networkVirtualApplianceName, NetworkVirtualApplianceData parameters, CancellationToken cancellationToken = default)
{
Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId));
Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName));
Argument.AssertNotNullOrEmpty(networkVirtualApplianceName, nameof(networkVirtualApplianceName));
Argument.AssertNotNull(parameters, nameof(parameters));
using var message = CreateCreateOrUpdateRequest(subscriptionId, resourceGroupName, networkVirtualApplianceName, parameters);
await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false);
switch (message.Response.Status)
{
case 200:
case 201:
return message.Response;
default:
throw new RequestFailedException(message.Response);
}
}
/// <summary> Creates or updates the specified Network Virtual Appliance. </summary>
/// <param name="subscriptionId"> The subscription credentials which uniquely identify the Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. </param>
/// <param name="resourceGroupName"> The name of the resource group. </param>
/// <param name="networkVirtualApplianceName"> The name of Network Virtual Appliance. </param>
/// <param name="parameters"> Parameters supplied to the create or update Network Virtual Appliance. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/>, <paramref name="networkVirtualApplianceName"/> or <paramref name="parameters"/> is null. </exception>
/// <exception cref="ArgumentException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/> or <paramref name="networkVirtualApplianceName"/> is an empty string, and was expected to be non-empty. </exception>
public Response CreateOrUpdate(string subscriptionId, string resourceGroupName, string networkVirtualApplianceName, NetworkVirtualApplianceData parameters, CancellationToken cancellationToken = default)
{
Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId));
Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName));
Argument.AssertNotNullOrEmpty(networkVirtualApplianceName, nameof(networkVirtualApplianceName));
Argument.AssertNotNull(parameters, nameof(parameters));
using var message = CreateCreateOrUpdateRequest(subscriptionId, resourceGroupName, networkVirtualApplianceName, parameters);
_pipeline.Send(message, cancellationToken);
switch (message.Response.Status)
{
case 200:
case 201:
return message.Response;
default:
throw new RequestFailedException(message.Response);
}
}
internal HttpMessage CreateListByResourceGroupRequest(string subscriptionId, string resourceGroupName)
{
var message = _pipeline.CreateMessage();
var request = message.Request;
request.Method = RequestMethod.Get;
var uri = new RawRequestUriBuilder();
uri.Reset(_endpoint);
uri.AppendPath("/subscriptions/", false);
uri.AppendPath(subscriptionId, true);
uri.AppendPath("/resourceGroups/", false);
uri.AppendPath(resourceGroupName, true);
uri.AppendPath("/providers/Microsoft.Network/networkVirtualAppliances", false);
uri.AppendQuery("api-version", _apiVersion, true);
request.Uri = uri;
request.Headers.Add("Accept", "application/json");
message.SetProperty("SDKUserAgent", _userAgent);
return message;
}
/// <summary> Lists all Network Virtual Appliances in a resource group. </summary>
/// <param name="subscriptionId"> The subscription credentials which uniquely identify the Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. </param>
/// <param name="resourceGroupName"> The name of the resource group. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/> or <paramref name="resourceGroupName"/> is null. </exception>
/// <exception cref="ArgumentException"> <paramref name="subscriptionId"/> or <paramref name="resourceGroupName"/> is an empty string, and was expected to be non-empty. </exception>
public async Task<Response<NetworkVirtualApplianceListResult>> ListByResourceGroupAsync(string subscriptionId, string resourceGroupName, CancellationToken cancellationToken = default)
{
Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId));
Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName));
using var message = CreateListByResourceGroupRequest(subscriptionId, resourceGroupName);
await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false);
switch (message.Response.Status)
{
case 200:
{
NetworkVirtualApplianceListResult value = default;
using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, default, cancellationToken).ConfigureAwait(false);
value = NetworkVirtualApplianceListResult.DeserializeNetworkVirtualApplianceListResult(document.RootElement);
return Response.FromValue(value, message.Response);
}
default:
throw new RequestFailedException(message.Response);
}
}
/// <summary> Lists all Network Virtual Appliances in a resource group. </summary>
/// <param name="subscriptionId"> The subscription credentials which uniquely identify the Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. </param>
/// <param name="resourceGroupName"> The name of the resource group. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/> or <paramref name="resourceGroupName"/> is null. </exception>
/// <exception cref="ArgumentException"> <paramref name="subscriptionId"/> or <paramref name="resourceGroupName"/> is an empty string, and was expected to be non-empty. </exception>
public Response<NetworkVirtualApplianceListResult> ListByResourceGroup(string subscriptionId, string resourceGroupName, CancellationToken cancellationToken = default)
{
Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId));
Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName));
using var message = CreateListByResourceGroupRequest(subscriptionId, resourceGroupName);
_pipeline.Send(message, cancellationToken);
switch (message.Response.Status)
{
case 200:
{
NetworkVirtualApplianceListResult value = default;
using var document = JsonDocument.Parse(message.Response.ContentStream);
value = NetworkVirtualApplianceListResult.DeserializeNetworkVirtualApplianceListResult(document.RootElement);
return Response.FromValue(value, message.Response);
}
default:
throw new RequestFailedException(message.Response);
}
}
internal HttpMessage CreateListRequest(string subscriptionId)
{
var message = _pipeline.CreateMessage();
var request = message.Request;
request.Method = RequestMethod.Get;
var uri = new RawRequestUriBuilder();
uri.Reset(_endpoint);
uri.AppendPath("/subscriptions/", false);
uri.AppendPath(subscriptionId, true);
uri.AppendPath("/providers/Microsoft.Network/networkVirtualAppliances", false);
uri.AppendQuery("api-version", _apiVersion, true);
request.Uri = uri;
request.Headers.Add("Accept", "application/json");
message.SetProperty("SDKUserAgent", _userAgent);
return message;
}
/// <summary> Gets all Network Virtual Appliances in a subscription. </summary>
/// <param name="subscriptionId"> The subscription credentials which uniquely identify the Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/> is null. </exception>
/// <exception cref="ArgumentException"> <paramref name="subscriptionId"/> is an empty string, and was expected to be non-empty. </exception>
public async Task<Response<NetworkVirtualApplianceListResult>> ListAsync(string subscriptionId, CancellationToken cancellationToken = default)
{
Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId));
using var message = CreateListRequest(subscriptionId);
await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false);
switch (message.Response.Status)
{
case 200:
{
NetworkVirtualApplianceListResult value = default;
using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, default, cancellationToken).ConfigureAwait(false);
value = NetworkVirtualApplianceListResult.DeserializeNetworkVirtualApplianceListResult(document.RootElement);
return Response.FromValue(value, message.Response);
}
default:
throw new RequestFailedException(message.Response);
}
}
/// <summary> Gets all Network Virtual Appliances in a subscription. </summary>
/// <param name="subscriptionId"> The subscription credentials which uniquely identify the Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/> is null. </exception>
/// <exception cref="ArgumentException"> <paramref name="subscriptionId"/> is an empty string, and was expected to be non-empty. </exception>
public Response<NetworkVirtualApplianceListResult> List(string subscriptionId, CancellationToken cancellationToken = default)
{
Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId));
using var message = CreateListRequest(subscriptionId);
_pipeline.Send(message, cancellationToken);
switch (message.Response.Status)
{
case 200:
{
NetworkVirtualApplianceListResult value = default;
using var document = JsonDocument.Parse(message.Response.ContentStream);
value = NetworkVirtualApplianceListResult.DeserializeNetworkVirtualApplianceListResult(document.RootElement);
return Response.FromValue(value, message.Response);
}
default:
throw new RequestFailedException(message.Response);
}
}
internal HttpMessage CreateListByResourceGroupNextPageRequest(string nextLink, string subscriptionId, string resourceGroupName)
{
var message = _pipeline.CreateMessage();
var request = message.Request;
request.Method = RequestMethod.Get;
var uri = new RawRequestUriBuilder();
uri.Reset(_endpoint);
uri.AppendRawNextLink(nextLink, false);
request.Uri = uri;
request.Headers.Add("Accept", "application/json");
message.SetProperty("SDKUserAgent", _userAgent);
return message;
}
/// <summary> Lists all Network Virtual Appliances in a resource group. </summary>
/// <param name="nextLink"> The URL to the next page of results. </param>
/// <param name="subscriptionId"> The subscription credentials which uniquely identify the Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. </param>
/// <param name="resourceGroupName"> The name of the resource group. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="nextLink"/>, <paramref name="subscriptionId"/> or <paramref name="resourceGroupName"/> is null. </exception>
/// <exception cref="ArgumentException"> <paramref name="subscriptionId"/> or <paramref name="resourceGroupName"/> is an empty string, and was expected to be non-empty. </exception>
public async Task<Response<NetworkVirtualApplianceListResult>> ListByResourceGroupNextPageAsync(string nextLink, string subscriptionId, string resourceGroupName, CancellationToken cancellationToken = default)
{
Argument.AssertNotNull(nextLink, nameof(nextLink));
Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId));
Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName));
using var message = CreateListByResourceGroupNextPageRequest(nextLink, subscriptionId, resourceGroupName);
await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false);
switch (message.Response.Status)
{
case 200:
{
NetworkVirtualApplianceListResult value = default;
using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, default, cancellationToken).ConfigureAwait(false);
value = NetworkVirtualApplianceListResult.DeserializeNetworkVirtualApplianceListResult(document.RootElement);
return Response.FromValue(value, message.Response);
}
default:
throw new RequestFailedException(message.Response);
}
}
/// <summary> Lists all Network Virtual Appliances in a resource group. </summary>
/// <param name="nextLink"> The URL to the next page of results. </param>
/// <param name="subscriptionId"> The subscription credentials which uniquely identify the Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. </param>
/// <param name="resourceGroupName"> The name of the resource group. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="nextLink"/>, <paramref name="subscriptionId"/> or <paramref name="resourceGroupName"/> is null. </exception>
/// <exception cref="ArgumentException"> <paramref name="subscriptionId"/> or <paramref name="resourceGroupName"/> is an empty string, and was expected to be non-empty. </exception>
public Response<NetworkVirtualApplianceListResult> ListByResourceGroupNextPage(string nextLink, string subscriptionId, string resourceGroupName, CancellationToken cancellationToken = default)
{
Argument.AssertNotNull(nextLink, nameof(nextLink));
Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId));
Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName));
using var message = CreateListByResourceGroupNextPageRequest(nextLink, subscriptionId, resourceGroupName);
_pipeline.Send(message, cancellationToken);
switch (message.Response.Status)
{
case 200:
{
NetworkVirtualApplianceListResult value = default;
using var document = JsonDocument.Parse(message.Response.ContentStream);
value = NetworkVirtualApplianceListResult.DeserializeNetworkVirtualApplianceListResult(document.RootElement);
return Response.FromValue(value, message.Response);
}
default:
throw new RequestFailedException(message.Response);
}
}
internal HttpMessage CreateListNextPageRequest(string nextLink, string subscriptionId)
{
var message = _pipeline.CreateMessage();
var request = message.Request;
request.Method = RequestMethod.Get;
var uri = new RawRequestUriBuilder();
uri.Reset(_endpoint);
uri.AppendRawNextLink(nextLink, false);
request.Uri = uri;
request.Headers.Add("Accept", "application/json");
message.SetProperty("SDKUserAgent", _userAgent);
return message;
}
/// <summary> Gets all Network Virtual Appliances in a subscription. </summary>
/// <param name="nextLink"> The URL to the next page of results. </param>
/// <param name="subscriptionId"> The subscription credentials which uniquely identify the Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="nextLink"/> or <paramref name="subscriptionId"/> is null. </exception>
/// <exception cref="ArgumentException"> <paramref name="subscriptionId"/> is an empty string, and was expected to be non-empty. </exception>
public async Task<Response<NetworkVirtualApplianceListResult>> ListNextPageAsync(string nextLink, string subscriptionId, CancellationToken cancellationToken = default)
{
Argument.AssertNotNull(nextLink, nameof(nextLink));
Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId));
using var message = CreateListNextPageRequest(nextLink, subscriptionId);
await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false);
switch (message.Response.Status)
{
case 200:
{
NetworkVirtualApplianceListResult value = default;
using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, default, cancellationToken).ConfigureAwait(false);
value = NetworkVirtualApplianceListResult.DeserializeNetworkVirtualApplianceListResult(document.RootElement);
return Response.FromValue(value, message.Response);
}
default:
throw new RequestFailedException(message.Response);
}
}
/// <summary> Gets all Network Virtual Appliances in a subscription. </summary>
/// <param name="nextLink"> The URL to the next page of results. </param>
/// <param name="subscriptionId"> The subscription credentials which uniquely identify the Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="nextLink"/> or <paramref name="subscriptionId"/> is null. </exception>
/// <exception cref="ArgumentException"> <paramref name="subscriptionId"/> is an empty string, and was expected to be non-empty. </exception>
public Response<NetworkVirtualApplianceListResult> ListNextPage(string nextLink, string subscriptionId, CancellationToken cancellationToken = default)
{
Argument.AssertNotNull(nextLink, nameof(nextLink));
Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId));
using var message = CreateListNextPageRequest(nextLink, subscriptionId);
_pipeline.Send(message, cancellationToken);
switch (message.Response.Status)
{
case 200:
{
NetworkVirtualApplianceListResult value = default;
using var document = JsonDocument.Parse(message.Response.ContentStream);
value = NetworkVirtualApplianceListResult.DeserializeNetworkVirtualApplianceListResult(document.RootElement);
return Response.FromValue(value, message.Response);
}
default:
throw new RequestFailedException(message.Response);
}
}
}
}
| 67.298762 | 237 | 0.670891 | [
"MIT"
] | KurnakovMaksim/azure-sdk-for-net | sdk/network/Azure.ResourceManager.Network/src/Generated/RestOperations/NetworkVirtualAppliancesRestOperations.cs | 43,475 | C# |
using System;
namespace TogglDesktop.Tutorial
{
public partial class BasicTutorialScreen4
{
private IDisposable _timerStateObservable;
public BasicTutorialScreen4()
{
this.InitializeComponent();
}
protected override void initialise()
{
Toggl.OnTimeEntryEditor += this.onTimeEntryEditor;
_timerStateObservable = Toggl.StoppedTimerState.Subscribe(_ => this.onStoppedTimerState());
}
protected override void cleanup()
{
Toggl.OnTimeEntryEditor -= this.onTimeEntryEditor;
_timerStateObservable?.Dispose();
}
private void onTimeEntryEditor(bool open, Toggl.TogglTimeEntryView te, string focusedFieldName)
{
this.activateScreen<BasicTutorialScreen5>();
}
private void onStoppedTimerState()
{
this.activateScreen<BasicTutorialScreen7>();
}
}
}
| 25.25 | 104 | 0.59802 | [
"BSD-3-Clause"
] | CancerGary/toggldesktop | src/ui/windows/TogglDesktop/TogglDesktop/ui/Tutorial/BasicTutorialScreen4.xaml.cs | 1,012 | C# |
using MetalCore.CQS.Common.Results;
using MetalCore.CQS.Validation;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace MetalCore.CQS.Command
{
/// <summary>
/// This class ensures the current user has permission to process this command.
/// </summary>
/// <typeparam name="TCommand">The type of command being handled.</typeparam>
public class CommandHandlerPermissionDecorator<TCommand> : ICommandHandler<TCommand> where TCommand : ICommand
{
private readonly ICommandHandler<TCommand> _commandHandler;
private readonly IEnumerable<ICommandPermission<TCommand>> _permissions;
/// <summary>
/// Constructor to enable IoC decoration.
/// </summary>
/// <param name="commandHandler">The next command handler to call in the chain.</param>
/// <param name="permissions">The list of permission classes to execute for this type of command.</param>
public CommandHandlerPermissionDecorator(
ICommandHandler<TCommand> commandHandler,
ICollection<ICommandPermission<TCommand>> permissions)
{
Guard.IsNotNull(commandHandler, nameof(commandHandler));
Guard.IsNotNull(permissions, nameof(permissions));
_commandHandler = commandHandler;
_permissions = permissions;
}
/// <summary>
/// Ensures current user has permission to process this command and
/// then calls the next command handler in the chain.
/// </summary>
/// <param name="command">The state of the command.</param>
/// <param name="token">
/// A System.Threading.CancellationToken to observe while waiting for the task to complete.
/// </param>
/// <returns>An awaitable task with a command result.</returns>
public async Task<IResult> ExecuteAsync(TCommand command, CancellationToken token = default)
{
bool[] result = await Task.WhenAll(_permissions.AsParallel().Select(a => a.HasPermissionAsync(command, token)))
.ConfigureAwait(false);
if (result.Any(hasPermission => !hasPermission))
{
return ResultHelper.NoPermissionError();
}
return await _commandHandler.ExecuteAsync(command, token).ConfigureAwait(false);
}
}
} | 42.315789 | 123 | 0.660033 | [
"MIT"
] | MetalKid/MetalCore.CQS | src/MetalCore.CQS/Command/Decorators/CommandHandlerPermissionDecorator.cs | 2,414 | C# |
#pragma checksum "..\..\..\Views\CalculatorView.xaml" "{ff1816ec-aa5e-4d10-87f7-6f4963833460}" "A33575606422293069DD1FF6410306BF2DEB0E47"
//------------------------------------------------------------------------------
// <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>
//------------------------------------------------------------------------------
using Calculator.Models;
using Calculator.ViewModels;
using Calculator.Views;
using OxyPlot.Wpf;
using System;
using System.Diagnostics;
using System.Windows;
using System.Windows.Automation;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Markup;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Media.Effects;
using System.Windows.Media.Imaging;
using System.Windows.Media.Media3D;
using System.Windows.Media.TextFormatting;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Shell;
namespace Calculator.Views {
/// <summary>
/// CalculatorView
/// </summary>
public partial class CalculatorView : System.Windows.Controls.UserControl, System.Windows.Markup.IComponentConnector {
#line 31 "..\..\..\Views\CalculatorView.xaml"
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
internal System.Windows.Controls.Button ButtonPoint;
#line default
#line hidden
#line 32 "..\..\..\Views\CalculatorView.xaml"
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
internal System.Windows.Controls.Button Button0;
#line default
#line hidden
#line 33 "..\..\..\Views\CalculatorView.xaml"
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
internal System.Windows.Controls.Button ButtonEqual;
#line default
#line hidden
#line 35 "..\..\..\Views\CalculatorView.xaml"
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
internal System.Windows.Controls.Button Button1;
#line default
#line hidden
#line 36 "..\..\..\Views\CalculatorView.xaml"
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
internal System.Windows.Controls.Button Button2;
#line default
#line hidden
#line 37 "..\..\..\Views\CalculatorView.xaml"
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
internal System.Windows.Controls.Button Button3;
#line default
#line hidden
#line 39 "..\..\..\Views\CalculatorView.xaml"
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
internal System.Windows.Controls.Button Button4;
#line default
#line hidden
#line 40 "..\..\..\Views\CalculatorView.xaml"
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
internal System.Windows.Controls.Button Button5;
#line default
#line hidden
#line 41 "..\..\..\Views\CalculatorView.xaml"
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
internal System.Windows.Controls.Button Button6;
#line default
#line hidden
#line 43 "..\..\..\Views\CalculatorView.xaml"
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
internal System.Windows.Controls.Button Button7;
#line default
#line hidden
#line 44 "..\..\..\Views\CalculatorView.xaml"
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
internal System.Windows.Controls.Button Button8;
#line default
#line hidden
#line 45 "..\..\..\Views\CalculatorView.xaml"
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
internal System.Windows.Controls.Button Button9;
#line default
#line hidden
#line 47 "..\..\..\Views\CalculatorView.xaml"
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
internal System.Windows.Controls.Button ButtonA;
#line default
#line hidden
#line 48 "..\..\..\Views\CalculatorView.xaml"
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
internal System.Windows.Controls.Button ButtonB;
#line default
#line hidden
#line 50 "..\..\..\Views\CalculatorView.xaml"
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
internal System.Windows.Controls.Button ButtonC;
#line default
#line hidden
#line 51 "..\..\..\Views\CalculatorView.xaml"
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
internal System.Windows.Controls.Button ButtonD;
#line default
#line hidden
#line 53 "..\..\..\Views\CalculatorView.xaml"
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
internal System.Windows.Controls.Button ButtonE;
#line default
#line hidden
#line 54 "..\..\..\Views\CalculatorView.xaml"
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
internal System.Windows.Controls.Button ButtonF;
#line default
#line hidden
#line 56 "..\..\..\Views\CalculatorView.xaml"
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
internal System.Windows.Controls.Button ButtonFactorial;
#line default
#line hidden
#line 57 "..\..\..\Views\CalculatorView.xaml"
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
internal System.Windows.Controls.Button ButtonChangeSign;
#line default
#line hidden
#line 58 "..\..\..\Views\CalculatorView.xaml"
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
internal System.Windows.Controls.Button ButtonPosition;
#line default
#line hidden
#line 59 "..\..\..\Views\CalculatorView.xaml"
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
internal System.Windows.Controls.Button ButtonInverse;
#line default
#line hidden
#line 61 "..\..\..\Views\CalculatorView.xaml"
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
internal System.Windows.Controls.Button ButtonDivide;
#line default
#line hidden
#line 62 "..\..\..\Views\CalculatorView.xaml"
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
internal System.Windows.Controls.Button ButtonMultiply;
#line default
#line hidden
#line 63 "..\..\..\Views\CalculatorView.xaml"
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
internal System.Windows.Controls.Button ButtonMinus;
#line default
#line hidden
#line 64 "..\..\..\Views\CalculatorView.xaml"
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
internal System.Windows.Controls.Button ButtonPlus;
#line default
#line hidden
#line 66 "..\..\..\Views\CalculatorView.xaml"
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
internal System.Windows.Controls.Button ButtonClear;
#line default
#line hidden
#line 67 "..\..\..\Views\CalculatorView.xaml"
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
internal System.Windows.Controls.Button ButtonDel;
#line default
#line hidden
#line 69 "..\..\..\Views\CalculatorView.xaml"
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
internal System.Windows.Controls.TextBox DisplayBox;
#line default
#line hidden
private bool _contentLoaded;
/// <summary>
/// InitializeComponent
/// </summary>
[System.Diagnostics.DebuggerNonUserCodeAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("PresentationBuildTasks", "4.0.0.0")]
public void InitializeComponent() {
if (_contentLoaded) {
return;
}
_contentLoaded = true;
System.Uri resourceLocater = new System.Uri("/Calculator;component/views/calculatorview.xaml", System.UriKind.Relative);
#line 1 "..\..\..\Views\CalculatorView.xaml"
System.Windows.Application.LoadComponent(this, resourceLocater);
#line default
#line hidden
}
[System.Diagnostics.DebuggerNonUserCodeAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("PresentationBuildTasks", "4.0.0.0")]
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Design", "CA1033:InterfaceMethodsShouldBeCallableByChildTypes")]
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")]
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1800:DoNotCastUnnecessarily")]
void System.Windows.Markup.IComponentConnector.Connect(int connectionId, object target) {
switch (connectionId)
{
case 1:
this.ButtonPoint = ((System.Windows.Controls.Button)(target));
return;
case 2:
this.Button0 = ((System.Windows.Controls.Button)(target));
return;
case 3:
this.ButtonEqual = ((System.Windows.Controls.Button)(target));
return;
case 4:
this.Button1 = ((System.Windows.Controls.Button)(target));
return;
case 5:
this.Button2 = ((System.Windows.Controls.Button)(target));
return;
case 6:
this.Button3 = ((System.Windows.Controls.Button)(target));
return;
case 7:
this.Button4 = ((System.Windows.Controls.Button)(target));
return;
case 8:
this.Button5 = ((System.Windows.Controls.Button)(target));
return;
case 9:
this.Button6 = ((System.Windows.Controls.Button)(target));
return;
case 10:
this.Button7 = ((System.Windows.Controls.Button)(target));
return;
case 11:
this.Button8 = ((System.Windows.Controls.Button)(target));
return;
case 12:
this.Button9 = ((System.Windows.Controls.Button)(target));
return;
case 13:
this.ButtonA = ((System.Windows.Controls.Button)(target));
return;
case 14:
this.ButtonB = ((System.Windows.Controls.Button)(target));
return;
case 15:
this.ButtonC = ((System.Windows.Controls.Button)(target));
return;
case 16:
this.ButtonD = ((System.Windows.Controls.Button)(target));
return;
case 17:
this.ButtonE = ((System.Windows.Controls.Button)(target));
return;
case 18:
this.ButtonF = ((System.Windows.Controls.Button)(target));
return;
case 19:
this.ButtonFactorial = ((System.Windows.Controls.Button)(target));
return;
case 20:
this.ButtonChangeSign = ((System.Windows.Controls.Button)(target));
return;
case 21:
this.ButtonPosition = ((System.Windows.Controls.Button)(target));
return;
case 22:
this.ButtonInverse = ((System.Windows.Controls.Button)(target));
return;
case 23:
this.ButtonDivide = ((System.Windows.Controls.Button)(target));
return;
case 24:
this.ButtonMultiply = ((System.Windows.Controls.Button)(target));
return;
case 25:
this.ButtonMinus = ((System.Windows.Controls.Button)(target));
return;
case 26:
this.ButtonPlus = ((System.Windows.Controls.Button)(target));
return;
case 27:
this.ButtonClear = ((System.Windows.Controls.Button)(target));
return;
case 28:
this.ButtonDel = ((System.Windows.Controls.Button)(target));
return;
case 29:
this.DisplayBox = ((System.Windows.Controls.TextBox)(target));
return;
}
this._contentLoaded = true;
}
}
}
| 39.543641 | 142 | 0.599672 | [
"MIT"
] | jcflow/WPFPlotterCalculator | Calculator/obj/Release/Views/CalculatorView.g.i.cs | 15,859 | 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 states-2016-11-23.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using System.Net;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.StepFunctions.Model
{
/// <summary>
/// Contains details about a resource timeout that occurred during an execution.
/// </summary>
public partial class TaskTimedOutEventDetails
{
private string _cause;
private string _error;
private string _resource;
private string _resourceType;
/// <summary>
/// Gets and sets the property Cause.
/// <para>
/// A more detailed explanation of the cause of the failure.
/// </para>
/// </summary>
[AWSProperty(Min=0, Max=32768)]
public string Cause
{
get { return this._cause; }
set { this._cause = value; }
}
// Check to see if Cause property is set
internal bool IsSetCause()
{
return this._cause != null;
}
/// <summary>
/// Gets and sets the property Error.
/// <para>
/// The error code of the failure.
/// </para>
/// </summary>
[AWSProperty(Min=0, Max=256)]
public string Error
{
get { return this._error; }
set { this._error = value; }
}
// Check to see if Error property is set
internal bool IsSetError()
{
return this._error != null;
}
/// <summary>
/// Gets and sets the property Resource.
/// <para>
/// The service name of the resource in a task state.
/// </para>
/// </summary>
[AWSProperty(Required=true, Min=1, Max=80)]
public string Resource
{
get { return this._resource; }
set { this._resource = value; }
}
// Check to see if Resource property is set
internal bool IsSetResource()
{
return this._resource != null;
}
/// <summary>
/// Gets and sets the property ResourceType.
/// <para>
/// The action of the resource called by a task state.
/// </para>
/// </summary>
[AWSProperty(Required=true, Min=1, Max=80)]
public string ResourceType
{
get { return this._resourceType; }
set { this._resourceType = value; }
}
// Check to see if ResourceType property is set
internal bool IsSetResourceType()
{
return this._resourceType != null;
}
}
} | 28.491525 | 104 | 0.574063 | [
"Apache-2.0"
] | DetlefGolze/aws-sdk-net | sdk/src/Services/StepFunctions/Generated/Model/TaskTimedOutEventDetails.cs | 3,362 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Components;
using System.Net.Http;
using System.Net.Http.Json;
using TaskManager.Shared;
namespace TaskManager.Client.Pages
{
public partial class Index
{
[Inject] public HttpClient Http { get; set; }
private IList<TaskItem> tasks;
private string error;
private string newTask;
protected override async Task OnInitializedAsync()
{
try
{
string requestUri = "TaskItems";
tasks = await
Http.GetFromJsonAsync<IList<TaskItem>>
(requestUri);
}
catch (Exception)
{
error = "Error Encountered";
};
}
private async Task CheckboxChecked(TaskItem task)
{
task.IsComplete = !task.IsComplete;
string requestUri = $"TaskItems/{task.TaskItemId}";
var response = await
Http.PutAsJsonAsync<TaskItem>(requestUri, task);
if (!response.IsSuccessStatusCode)
{
error = response.ReasonPhrase;
};
}
private async Task DeleteTask(TaskItem taskItem)
{
tasks.Remove(taskItem);
string requestUri =
$"TaskItems/{taskItem.TaskItemId}";
var response = await Http.DeleteAsync(requestUri);
if (!response.IsSuccessStatusCode)
{
error = response.ReasonPhrase;
};
}
private async Task AddTask()
{
if (!string.IsNullOrWhiteSpace(newTask))
{
TaskItem newTaskItem = new TaskItem
{
TaskName = newTask,
IsComplete = false
};
tasks.Add(newTaskItem);
string requestUri = "TaskItems";
var response = await Http.PostAsJsonAsync(requestUri, newTaskItem);
if (response.IsSuccessStatusCode)
{
newTask = string.Empty;
var task =
await response.Content.ReadFromJsonAsync
<TaskItem>();
}
else
{
error = response.ReasonPhrase;
};
};
}
}
}
| 28.191011 | 83 | 0.497409 | [
"MIT"
] | PacktPublishing/Blazor-WebAssembly-Projects | Chapter08/TaskManager/Client/Pages/Index.razor.cs | 2,511 | C# |
using System;
using ObjCRuntime;
using UIKit;
namespace Microsoft.Maui.Platform
{
internal static class PlatformVersion
{
public static bool IsAtLeast(int version)
{
return OperatingSystem.IsIOSVersionAtLeast(version) || OperatingSystem.IsTvOSVersionAtLeast(version);
}
private static bool? SetNeedsUpdateOfHomeIndicatorAutoHidden;
public static bool Supports(string capability)
{
switch (capability)
{
case PlatformApis.RespondsToSetNeedsUpdateOfHomeIndicatorAutoHidden:
if (!SetNeedsUpdateOfHomeIndicatorAutoHidden.HasValue)
{
SetNeedsUpdateOfHomeIndicatorAutoHidden = new UIViewController().RespondsToSelector(new ObjCRuntime.Selector("setNeedsUpdateOfHomeIndicatorAutoHidden"));
}
return SetNeedsUpdateOfHomeIndicatorAutoHidden.Value;
}
return false;
}
public static bool Supports(int capability)
{
return IsAtLeast(capability);
}
}
internal static class PlatformApis
{
public const string RespondsToSetNeedsUpdateOfHomeIndicatorAutoHidden = "RespondsToSetNeedsUpdateOfHomeIndicatorAutoHidden";
public const int UIActivityIndicatorViewStyleMedium = 13;
}
} | 26.627907 | 159 | 0.79214 | [
"MIT"
] | AlexanderSemenyak/maui | src/Core/src/Platform/iOS/PlatformVersion.cs | 1,145 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Sultanlar.DatabaseObject;
using System.Collections;
namespace Sultanlar.UI
{
public partial class frmAT2bolgeler : Form
{
public frmAT2bolgeler()
{
InitializeComponent();
}
private void frmAT2bolgeler_Load(object sender, EventArgs e)
{
GetObjects();
}
private void GetObjects()
{
AT2_Bolgeler.GetObjects(lbBolgeler.Items, cbPasifler.Checked, true);
}
private void Temizle()
{
txtEkle.Text = string.Empty;
txtGuncelle.Text = string.Empty;
txtSil.Text = string.Empty;
lbBolgeler.SelectedIndex = -1;
txtGuncelle.Enabled = false;
btnGuncelle.Enabled = false;
btnSil.Enabled = false;
}
private void btnEkle_Click(object sender, EventArgs e)
{
if (txtEkle.Text.Trim() != string.Empty)
{
AT2_Bolgeler bg = new AT2_Bolgeler(false, txtEkle.Text.Trim().ToUpper());
bg.DoInsert();
MessageBox.Show("Ekleme işlemi başarılı.", "Sonuç", MessageBoxButtons.OK, MessageBoxIcon.Information);
GetObjects();
Temizle();
}
else
{
MessageBox.Show("Eksik seçim var.", "Hata", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
private void btnGuncelle_Click(object sender, EventArgs e)
{
if (lbBolgeler.SelectedIndex > -1)
{
int index = lbBolgeler.SelectedIndex;
AT2_Bolgeler bg = ((AT2_Bolgeler)lbBolgeler.SelectedItem);
bg.strBolge = txtGuncelle.Text.Trim().ToUpper();
bg.DoUpdate();
MessageBox.Show("Güncelleme işlemi başarılı.", "Sonuç", MessageBoxButtons.OK, MessageBoxIcon.Information);
GetObjects();
lbBolgeler.SelectedIndex = index;
}
else
{
MessageBox.Show("Eksik seçim var.", "Hata", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
private void lbBolgeler_SelectedIndexChanged(object sender, EventArgs e)
{
if (lbBolgeler.SelectedIndex > -1)
{
txtGuncelle.Enabled = true;
btnGuncelle.Enabled = true;
btnSil.Enabled = true;
txtGuncelle.Text = lbBolgeler.SelectedItem.ToString();
txtSil.Text = lbBolgeler.SelectedItem.ToString();
btnSil.Text = ((AT2_Bolgeler)lbBolgeler.SelectedItem).blPasif ? "Geri Al" : "Sil";
}
}
private void btnSil_Click(object sender, EventArgs e)
{
if (lbBolgeler.SelectedIndex > -1)
{
if (MessageBox.Show("Devam etmek istediğinize emin misiniz?", "Uyarı", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == System.Windows.Forms.DialogResult.Yes)
{
AT2_Bolgeler bg = ((AT2_Bolgeler)lbBolgeler.SelectedItem);
bg.blPasif = !bg.blPasif;
bg.DoUpdate();
if (bg.blPasif)
{
ArrayList bedeller = new ArrayList();
AT2_AracBedeller.GetObjectsByBolgeID(bedeller, false, bg.pkID, true, true);
for (int i = 0; i < bedeller.Count; i++)
{
AT2_AracBedeller bedel = (AT2_AracBedeller)bedeller[i];
bedel.blPasif = true;
bedel.DoUpdate();
}
}
MessageBox.Show("İşlem başarılı.", "Sonuç", MessageBoxButtons.OK, MessageBoxIcon.Information);
GetObjects();
Temizle();
}
}
else
{
MessageBox.Show("Eksik seçim var.", "Hata", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
private void btnYenile_Click(object sender, EventArgs e)
{
GetObjects();
Temizle();
}
private void frmAT2bolgeler_SizeChanged(object sender, EventArgs e)
{
btnYenile.Location = new Point(this.Width - 40, btnYenile.Location.Y);
cbPasifler.Location = new Point(this.Width - 115, cbPasifler.Location.Y);
label1.Location = new Point(this.Width - 236, label1.Location.Y);
label2.Location = new Point(this.Width - 236, label2.Location.Y);
label3.Location = new Point(this.Width - 236, label3.Location.Y);
txtEkle.Location = new Point(this.Width - 236, txtEkle.Location.Y);
txtGuncelle.Location = new Point(this.Width - 236, txtGuncelle.Location.Y);
txtSil.Location = new Point(this.Width - 236, txtSil.Location.Y);
btnEkle.Location = new Point(this.Width - 102, btnEkle.Location.Y);
btnGuncelle.Location = new Point(this.Width - 102, btnGuncelle.Location.Y);
btnSil.Location = new Point(this.Width - 102, btnSil.Location.Y);
lbBolgeler.Width = this.Width - 246;
}
}
}
| 36.476821 | 181 | 0.546841 | [
"MIT"
] | dogukanalan/Sultanlar | Sultanlar/Sultanlar.UI/frmAT2bolgeler.cs | 5,532 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using System;
using Microsoft.Practices.ObjectBuilder2;
using Microsoft.Practices.Unity.Utility;
namespace Microsoft.Practices.Unity.InterceptionExtension
{
/// <summary>
/// A <see cref="InjectionMember"/> that can be passed to the
/// <see cref="IUnityContainer.RegisterType"/> method to specify
/// which interceptor to use. This member sets up the default
/// interceptor for a type - this will be used regardless of which
/// name is used to resolve the type.
/// </summary>
public class DefaultInterceptor : InjectionMember
{
private readonly IInterceptor interceptor;
private readonly NamedTypeBuildKey interceptorKey;
/// <summary>
/// Construct a new <see cref="DefaultInterceptor"/> instance that,
/// when applied to a container, will register the given
/// interceptor as the default one.
/// </summary>
/// <param name="interceptor">Interceptor to use.</param>
public DefaultInterceptor(IInterceptor interceptor)
{
Guard.ArgumentNotNull(interceptor, "intereptor");
this.interceptor = interceptor;
}
/// <summary>
/// Construct a new <see cref="DefaultInterceptor"/> that, when
/// applied to a container, will register the given type as
/// the default interceptor.
/// </summary>
/// <param name="interceptorType">Type of interceptor.</param>
/// <param name="name">Name to use to resolve the interceptor.</param>
public DefaultInterceptor(Type interceptorType, string name)
{
Guard.ArgumentNotNull(interceptorType, "interceptorType");
Guard.TypeIsAssignable(typeof(IInterceptor), interceptorType, "interceptorType");
this.interceptorKey = new NamedTypeBuildKey(interceptorType, name);
}
/// <summary>
/// Construct a new <see cref="DefaultInterceptor"/> that, when
/// applied to a container, will register the given type as
/// the default interceptor.
/// </summary>
/// <param name="interceptorType">Type of interceptor.</param>
public DefaultInterceptor(Type interceptorType)
: this(interceptorType, null)
{
}
/// <summary>
/// Add policies to the <paramref name="policies"/> to configure the
/// container to call this constructor with the appropriate parameter values.
/// </summary>
/// <param name="serviceType">Type of interface being registered. If no interface,
/// this will be null.</param>
/// <param name="implementationType">Type of concrete type being registered.</param>
/// <param name="name">Name used to resolve the type object.</param>
/// <param name="policies">Policy list to add policies to.</param>
public override void AddPolicies(Type serviceType, Type implementationType, string name, IPolicyList policies)
{
if (this.IsInstanceInterceptor)
{
this.AddDefaultInstanceInterceptor(implementationType, policies);
}
else
{
this.AddDefaultTypeInterceptor(implementationType, policies);
}
}
private bool IsInstanceInterceptor
{
get
{
if (this.interceptor != null)
{
return this.interceptor is IInstanceInterceptor;
}
return typeof(IInstanceInterceptor).IsAssignableFrom(this.interceptorKey.Type);
}
}
private void AddDefaultInstanceInterceptor(Type typeToIntercept, IPolicyList policies)
{
IInstanceInterceptionPolicy policy;
if (this.interceptor != null)
{
policy = new FixedInstanceInterceptionPolicy((IInstanceInterceptor)this.interceptor);
}
else
{
policy = new ResolvedInstanceInterceptionPolicy(this.interceptorKey);
}
policies.Set<IInstanceInterceptionPolicy>(policy, typeToIntercept);
}
private void AddDefaultTypeInterceptor(Type typeToIntercept, IPolicyList policies)
{
ITypeInterceptionPolicy policy;
if (this.interceptor != null)
{
policy = new FixedTypeInterceptionPolicy((ITypeInterceptor)this.interceptor);
}
else
{
policy = new ResolvedTypeInterceptionPolicy(this.interceptorKey);
}
policies.Set<ITypeInterceptionPolicy>(policy, typeToIntercept);
}
}
/// <summary>
/// A generic version of <see cref="DefaultInterceptor"/> so that
/// you can specify the interceptor type using generics.
/// </summary>
/// <typeparam name="TInterceptor"></typeparam>
public class DefaultInterceptor<TInterceptor> : DefaultInterceptor
where TInterceptor : ITypeInterceptor
{
/// <summary>
/// Create a new instance of <see cref="DefaultInterceptor{TInterceptor}"/>.
/// </summary>
/// <param name="name">Name to use when resolving interceptor.</param>
public DefaultInterceptor(string name)
: base(typeof(TInterceptor), name)
{
}
/// <summary>
/// Create a new instance of <see cref="DefaultInterceptor{TInterceptor}"/>.
/// </summary>
public DefaultInterceptor()
: base(typeof(TInterceptor))
{
}
}
} | 38.059603 | 122 | 0.611449 | [
"Apache-2.0",
"MIT"
] | drcarver/unity | source/Unity.Interception/Src/ContainerIntegration/DefaultInterceptor.cs | 5,749 | 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.Globalization;
using System.IO;
using Microsoft.Extensions.CommandLineUtils;
using NuGet.Common;
using NuGet.Packaging.Core;
using NuGet.Versioning;
namespace NuGet.CommandLine.XPlat
{
public static class AddPackageReferenceCommand
{
public static void Register(CommandLineApplication app, Func<ILogger> getLogger,
Func<IPackageReferenceCommandRunner> getCommandRunner)
{
app.Command("add", addpkg =>
{
addpkg.Description = Strings.AddPkg_Description;
addpkg.HelpOption(XPlatUtility.HelpOption);
addpkg.Option(
CommandConstants.ForceEnglishOutputOption,
Strings.ForceEnglishOutput_Description,
CommandOptionType.NoValue);
var id = addpkg.Option(
"--package",
Strings.AddPkg_PackageIdDescription,
CommandOptionType.SingleValue);
var version = addpkg.Option(
"--version",
Strings.AddPkg_PackageVersionDescription,
CommandOptionType.SingleValue);
var dgFilePath = addpkg.Option(
"-d|--dg-file",
Strings.AddPkg_DgFileDescription,
CommandOptionType.SingleValue);
var projectPath = addpkg.Option(
"-p|--project",
Strings.AddPkg_ProjectPathDescription,
CommandOptionType.SingleValue);
var frameworks = addpkg.Option(
"-f|--framework",
Strings.AddPkg_FrameworksDescription,
CommandOptionType.MultipleValue);
var noRestore = addpkg.Option(
"-n|--no-restore",
Strings.AddPkg_NoRestoreDescription,
CommandOptionType.NoValue);
var sources = addpkg.Option(
"-s|--source",
Strings.AddPkg_SourcesDescription,
CommandOptionType.MultipleValue);
var packageDirectory = addpkg.Option(
"--package-directory",
Strings.AddPkg_PackageDirectoryDescription,
CommandOptionType.SingleValue);
addpkg.OnExecute(() =>
{
ValidateArgument(id, addpkg.Name);
ValidateArgument(projectPath, addpkg.Name);
ValidateProjectPath(projectPath, addpkg.Name);
if (!noRestore.HasValue())
{
ValidateArgument(dgFilePath, addpkg.Name);
}
var logger = getLogger();
var noVersion = !version.HasValue();
var packageVersion = version.HasValue() ? version.Value() : "*";
var packageDependency = new PackageDependency(id.Values[0], VersionRange.Parse(packageVersion));
var packageRefArgs = new PackageReferenceArgs(projectPath.Value(), packageDependency, logger)
{
Frameworks = CommandLineUtility.SplitAndJoinAcrossMultipleValues(frameworks.Values),
Sources = CommandLineUtility.SplitAndJoinAcrossMultipleValues(sources.Values),
PackageDirectory = packageDirectory.Value(),
NoRestore = noRestore.HasValue(),
NoVersion = noVersion,
DgFilePath = dgFilePath.Value()
};
var msBuild = new MSBuildAPIUtility(logger);
var addPackageRefCommandRunner = getCommandRunner();
return addPackageRefCommandRunner.ExecuteCommand(packageRefArgs, msBuild);
});
});
}
private static void ValidateArgument(CommandOption arg, string commandName)
{
if (arg.Values.Count < 1)
{
throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, Strings.Error_PkgMissingArgument,
commandName,
arg.Template));
}
}
private static void ValidateProjectPath(CommandOption projectPath, string commandName)
{
if (!File.Exists(projectPath.Value()) || !projectPath.Value().EndsWith("proj", StringComparison.OrdinalIgnoreCase))
{
throw new ArgumentException(string.Format(CultureInfo.CurrentCulture,
Strings.Error_PkgMissingOrInvalidProjectFile,
commandName,
projectPath.Value()));
}
}
}
} | 42.016807 | 127 | 0.5536 | [
"Apache-2.0"
] | brywang-msft/NuGet.Client | src/NuGet.Core/NuGet.CommandLine.XPlat/Commands/PackageReferenceCommands/AddPackageReferenceCommand.cs | 5,000 | C# |
public class Cargo
{
public Cargo(int weight, string type)
{
Weight = weight;
Type = type;
}
public int Weight { get; set; }
public string Type { get; set; }
} | 16.5 | 41 | 0.550505 | [
"MIT"
] | ViktorAleksandrov/SoftUni--CSharp-Fundamentals | 2. CSharp OOP Basics/01.2. Defining Classes - Exercise/P08.RawData/Cargo.cs | 200 | C# |
using System.Threading.Tasks;
using BookLovers.Auth.Integration.IntegrationEvents;
using BookLovers.Base.Infrastructure.Commands;
using BookLovers.Base.Infrastructure.Events.IntegrationEvents;
using BookLovers.Ratings.Application.Commands.RatingGivers;
namespace BookLovers.Ratings.Application.IntegrationEvents.Readers
{
internal class SuperAdminCreatedHandler :
IIntegrationEventHandler<SuperAdminCreatedIntegrationEvent>,
IIntegrationEventHandler
{
private readonly IInternalCommandDispatcher _commandDispatcher;
public SuperAdminCreatedHandler(IInternalCommandDispatcher commandDispatcher)
{
this._commandDispatcher = commandDispatcher;
}
public Task HandleAsync(SuperAdminCreatedIntegrationEvent @event)
{
return this._commandDispatcher.SendInternalCommandAsync(
new CreateRatingGiverInternalCommand(@event.ReaderGuid, @event.ReaderId));
}
}
} | 37.538462 | 90 | 0.764344 | [
"MIT"
] | kamilk08/BookLoversApi | BookLovers.Ratings.Application/IntegrationEvents/Readers/SuperAdminCreatedHandler.cs | 978 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// <auto-generated/>
#nullable disable
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Azure;
using Azure.Core;
using Azure.Core.Pipeline;
using Azure.ResourceManager;
using Azure.ResourceManager.Core;
using Azure.ResourceManager.Network.Models;
namespace Azure.ResourceManager.Network
{
/// <summary> A class representing collection of VpnConnection and their operations over a VpnGateway. </summary>
public partial class VpnConnectionCollection : ArmCollection, IEnumerable<VpnConnection>, IAsyncEnumerable<VpnConnection>
{
private readonly ClientDiagnostics _clientDiagnostics;
private readonly VpnConnectionsRestOperations _restClient;
/// <summary> Initializes a new instance of the <see cref="VpnConnectionCollection"/> class for mocking. </summary>
protected VpnConnectionCollection()
{
}
/// <summary> Initializes a new instance of VpnConnectionCollection class. </summary>
/// <param name="parent"> The resource representing the parent resource. </param>
internal VpnConnectionCollection(ArmResource parent) : base(parent)
{
_clientDiagnostics = new ClientDiagnostics(ClientOptions);
_restClient = new VpnConnectionsRestOperations(_clientDiagnostics, Pipeline, ClientOptions, Id.SubscriptionId, BaseUri);
}
IEnumerator<VpnConnection> IEnumerable<VpnConnection>.GetEnumerator()
{
return GetAll().GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetAll().GetEnumerator();
}
IAsyncEnumerator<VpnConnection> IAsyncEnumerable<VpnConnection>.GetAsyncEnumerator(CancellationToken cancellationToken)
{
return GetAllAsync(cancellationToken: cancellationToken).GetAsyncEnumerator(cancellationToken);
}
/// <summary> Gets the valid resource type for this object. </summary>
protected override ResourceType ValidResourceType => VpnGateway.ResourceType;
// Collection level operations.
/// <summary> Creates a vpn connection to a scalable vpn gateway if it doesn't exist else updates the existing connection. </summary>
/// <param name="connectionName"> The name of the connection. </param>
/// <param name="vpnConnectionParameters"> Parameters supplied to create or Update a VPN Connection. </param>
/// <param name="waitForCompletion"> Waits for the completion of the long running operations. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="connectionName"/> or <paramref name="vpnConnectionParameters"/> is null. </exception>
public virtual VpnConnectionCreateOrUpdateOperation CreateOrUpdate(string connectionName, VpnConnectionData vpnConnectionParameters, bool waitForCompletion = true, CancellationToken cancellationToken = default)
{
if (connectionName == null)
{
throw new ArgumentNullException(nameof(connectionName));
}
if (vpnConnectionParameters == null)
{
throw new ArgumentNullException(nameof(vpnConnectionParameters));
}
using var scope = _clientDiagnostics.CreateScope("VpnConnectionCollection.CreateOrUpdate");
scope.Start();
try
{
var response = _restClient.CreateOrUpdate(Id.ResourceGroupName, Id.Name, connectionName, vpnConnectionParameters, cancellationToken);
var operation = new VpnConnectionCreateOrUpdateOperation(Parent, _clientDiagnostics, Pipeline, _restClient.CreateCreateOrUpdateRequest(Id.ResourceGroupName, Id.Name, connectionName, vpnConnectionParameters).Request, response);
if (waitForCompletion)
operation.WaitForCompletion(cancellationToken);
return operation;
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary> Creates a vpn connection to a scalable vpn gateway if it doesn't exist else updates the existing connection. </summary>
/// <param name="connectionName"> The name of the connection. </param>
/// <param name="vpnConnectionParameters"> Parameters supplied to create or Update a VPN Connection. </param>
/// <param name="waitForCompletion"> Waits for the completion of the long running operations. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="connectionName"/> or <paramref name="vpnConnectionParameters"/> is null. </exception>
public async virtual Task<VpnConnectionCreateOrUpdateOperation> CreateOrUpdateAsync(string connectionName, VpnConnectionData vpnConnectionParameters, bool waitForCompletion = true, CancellationToken cancellationToken = default)
{
if (connectionName == null)
{
throw new ArgumentNullException(nameof(connectionName));
}
if (vpnConnectionParameters == null)
{
throw new ArgumentNullException(nameof(vpnConnectionParameters));
}
using var scope = _clientDiagnostics.CreateScope("VpnConnectionCollection.CreateOrUpdate");
scope.Start();
try
{
var response = await _restClient.CreateOrUpdateAsync(Id.ResourceGroupName, Id.Name, connectionName, vpnConnectionParameters, cancellationToken).ConfigureAwait(false);
var operation = new VpnConnectionCreateOrUpdateOperation(Parent, _clientDiagnostics, Pipeline, _restClient.CreateCreateOrUpdateRequest(Id.ResourceGroupName, Id.Name, connectionName, vpnConnectionParameters).Request, response);
if (waitForCompletion)
await operation.WaitForCompletionAsync(cancellationToken).ConfigureAwait(false);
return operation;
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary> Gets details for this resource from the service. </summary>
/// <param name="connectionName"> The name of the vpn connection. </param>
/// <param name="cancellationToken"> A token to allow the caller to cancel the call to the service. The default value is <see cref="CancellationToken.None" />. </param>
public virtual Response<VpnConnection> Get(string connectionName, CancellationToken cancellationToken = default)
{
using var scope = _clientDiagnostics.CreateScope("VpnConnectionCollection.Get");
scope.Start();
try
{
if (connectionName == null)
{
throw new ArgumentNullException(nameof(connectionName));
}
var response = _restClient.Get(Id.ResourceGroupName, Id.Name, connectionName, cancellationToken: cancellationToken);
if (response.Value == null)
throw _clientDiagnostics.CreateRequestFailedException(response.GetRawResponse());
return Response.FromValue(new VpnConnection(Parent, response.Value), response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary> Gets details for this resource from the service. </summary>
/// <param name="connectionName"> The name of the vpn connection. </param>
/// <param name="cancellationToken"> A token to allow the caller to cancel the call to the service. The default value is <see cref="CancellationToken.None" />. </param>
public async virtual Task<Response<VpnConnection>> GetAsync(string connectionName, CancellationToken cancellationToken = default)
{
using var scope = _clientDiagnostics.CreateScope("VpnConnectionCollection.Get");
scope.Start();
try
{
if (connectionName == null)
{
throw new ArgumentNullException(nameof(connectionName));
}
var response = await _restClient.GetAsync(Id.ResourceGroupName, Id.Name, connectionName, cancellationToken: cancellationToken).ConfigureAwait(false);
if (response.Value == null)
throw await _clientDiagnostics.CreateRequestFailedExceptionAsync(response.GetRawResponse()).ConfigureAwait(false);
return Response.FromValue(new VpnConnection(Parent, response.Value), response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary> Tries to get details for this resource from the service. </summary>
/// <param name="connectionName"> The name of the vpn connection. </param>
/// <param name="cancellationToken"> A token to allow the caller to cancel the call to the service. The default value is <see cref="CancellationToken.None" />. </param>
public virtual Response<VpnConnection> GetIfExists(string connectionName, CancellationToken cancellationToken = default)
{
using var scope = _clientDiagnostics.CreateScope("VpnConnectionCollection.GetIfExists");
scope.Start();
try
{
if (connectionName == null)
{
throw new ArgumentNullException(nameof(connectionName));
}
var response = _restClient.Get(Id.ResourceGroupName, Id.Name, connectionName, cancellationToken: cancellationToken);
return response.Value == null
? Response.FromValue<VpnConnection>(null, response.GetRawResponse())
: Response.FromValue(new VpnConnection(this, response.Value), response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary> Tries to get details for this resource from the service. </summary>
/// <param name="connectionName"> The name of the vpn connection. </param>
/// <param name="cancellationToken"> A token to allow the caller to cancel the call to the service. The default value is <see cref="CancellationToken.None" />. </param>
public async virtual Task<Response<VpnConnection>> GetIfExistsAsync(string connectionName, CancellationToken cancellationToken = default)
{
using var scope = _clientDiagnostics.CreateScope("VpnConnectionCollection.GetIfExists");
scope.Start();
try
{
if (connectionName == null)
{
throw new ArgumentNullException(nameof(connectionName));
}
var response = await _restClient.GetAsync(Id.ResourceGroupName, Id.Name, connectionName, cancellationToken: cancellationToken).ConfigureAwait(false);
return response.Value == null
? Response.FromValue<VpnConnection>(null, response.GetRawResponse())
: Response.FromValue(new VpnConnection(this, response.Value), response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary> Tries to get details for this resource from the service. </summary>
/// <param name="connectionName"> The name of the vpn connection. </param>
/// <param name="cancellationToken"> A token to allow the caller to cancel the call to the service. The default value is <see cref="CancellationToken.None" />. </param>
public virtual Response<bool> CheckIfExists(string connectionName, CancellationToken cancellationToken = default)
{
using var scope = _clientDiagnostics.CreateScope("VpnConnectionCollection.CheckIfExists");
scope.Start();
try
{
if (connectionName == null)
{
throw new ArgumentNullException(nameof(connectionName));
}
var response = GetIfExists(connectionName, cancellationToken: cancellationToken);
return Response.FromValue(response.Value != null, response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary> Tries to get details for this resource from the service. </summary>
/// <param name="connectionName"> The name of the vpn connection. </param>
/// <param name="cancellationToken"> A token to allow the caller to cancel the call to the service. The default value is <see cref="CancellationToken.None" />. </param>
public async virtual Task<Response<bool>> CheckIfExistsAsync(string connectionName, CancellationToken cancellationToken = default)
{
using var scope = _clientDiagnostics.CreateScope("VpnConnectionCollection.CheckIfExists");
scope.Start();
try
{
if (connectionName == null)
{
throw new ArgumentNullException(nameof(connectionName));
}
var response = await GetIfExistsAsync(connectionName, cancellationToken: cancellationToken).ConfigureAwait(false);
return Response.FromValue(response.Value != null, response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary> Retrieves all vpn connections for a particular virtual wan vpn gateway. </summary>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <returns> A collection of <see cref="VpnConnection" /> that may take multiple service requests to iterate over. </returns>
public virtual Pageable<VpnConnection> GetAll(CancellationToken cancellationToken = default)
{
Page<VpnConnection> FirstPageFunc(int? pageSizeHint)
{
using var scope = _clientDiagnostics.CreateScope("VpnConnectionCollection.GetAll");
scope.Start();
try
{
var response = _restClient.GetAllByVpnGateway(Id.ResourceGroupName, Id.Name, cancellationToken: cancellationToken);
return Page.FromValues(response.Value.Value.Select(value => new VpnConnection(Parent, value)), response.Value.NextLink, response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
Page<VpnConnection> NextPageFunc(string nextLink, int? pageSizeHint)
{
using var scope = _clientDiagnostics.CreateScope("VpnConnectionCollection.GetAll");
scope.Start();
try
{
var response = _restClient.GetAllByVpnGatewayNextPage(nextLink, Id.ResourceGroupName, Id.Name, cancellationToken: cancellationToken);
return Page.FromValues(response.Value.Value.Select(value => new VpnConnection(Parent, value)), response.Value.NextLink, response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
return PageableHelpers.CreateEnumerable(FirstPageFunc, NextPageFunc);
}
/// <summary> Retrieves all vpn connections for a particular virtual wan vpn gateway. </summary>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <returns> An async collection of <see cref="VpnConnection" /> that may take multiple service requests to iterate over. </returns>
public virtual AsyncPageable<VpnConnection> GetAllAsync(CancellationToken cancellationToken = default)
{
async Task<Page<VpnConnection>> FirstPageFunc(int? pageSizeHint)
{
using var scope = _clientDiagnostics.CreateScope("VpnConnectionCollection.GetAll");
scope.Start();
try
{
var response = await _restClient.GetAllByVpnGatewayAsync(Id.ResourceGroupName, Id.Name, cancellationToken: cancellationToken).ConfigureAwait(false);
return Page.FromValues(response.Value.Value.Select(value => new VpnConnection(Parent, value)), response.Value.NextLink, response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
async Task<Page<VpnConnection>> NextPageFunc(string nextLink, int? pageSizeHint)
{
using var scope = _clientDiagnostics.CreateScope("VpnConnectionCollection.GetAll");
scope.Start();
try
{
var response = await _restClient.GetAllByVpnGatewayNextPageAsync(nextLink, Id.ResourceGroupName, Id.Name, cancellationToken: cancellationToken).ConfigureAwait(false);
return Page.FromValues(response.Value.Value.Select(value => new VpnConnection(Parent, value)), response.Value.NextLink, response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
return PageableHelpers.CreateAsyncEnumerable(FirstPageFunc, NextPageFunc);
}
// Builders.
// public ArmBuilder<ResourceIdentifier, VpnConnection, VpnConnectionData> Construct() { }
}
}
| 50.955801 | 242 | 0.623712 | [
"MIT"
] | Ochirkhuyag/azure-sdk-for-net | sdk/network/Azure.ResourceManager.Network/src/Generated/VpnConnectionCollection.cs | 18,446 | C# |
//using System.Linq.Expressions;
//namespace Z.EntityFramework.Plus
//{
// /// <summary>A batch update visitor.</summary>
// public class BatchUpdateVisitor : ExpressionVisitor
// {
// /// <summary>Gets or sets a value indicating whether the expression contains an OrderBy method.</summary>
// /// <value>true if the expression contains an OrderBy metho has order by, false if not.</value>
// public bool HasOrderBy { get; set; }
// /// <summary>
// /// Visits the children of the <see cref="T:System.Linq.Expressions.MethodCallExpression" />.
// /// </summary>
// /// <param name="node">The expression to visit.</param>
// /// <returns>
// /// The modified expression, if it or any subexpression was modified; otherwise, returns the
// /// original expression.
// /// </returns>
// protected override Expression VisitMethodCall(MethodCallExpression node)
// {
// if (node.Method.Name == "OrderBy")
// {
// HasOrderBy = true;
// }
// return base.VisitMethodCall(node);
// }
// }
//} | 38.9 | 115 | 0.577549 | [
"MIT"
] | Ahmed-Abdelhameed/EntityFramework-Plus | src/shared/Z.EF.Plus.BatchUpdate.Shared/BatchUpdateVisitor.cs | 1,169 | C# |
// *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
// *** 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.Auth0.Outputs
{
[OutputType]
public sealed class GuardianPhone
{
/// <summary>
/// List(String). Message types to use, array of `phone` and or `voice`. Adding both to array should enable the user to choose.
/// </summary>
public readonly ImmutableArray<string> MessageTypes;
/// <summary>
/// List(Resource). Options for the various providers. See Options.
/// </summary>
public readonly Outputs.GuardianPhoneOptions? Options;
/// <summary>
/// String, Case-sensitive. Provider to use, one of `auth0`, `twilio` or `phone-message-hook`.
/// </summary>
public readonly string Provider;
[OutputConstructor]
private GuardianPhone(
ImmutableArray<string> messageTypes,
Outputs.GuardianPhoneOptions? options,
string provider)
{
MessageTypes = messageTypes;
Options = options;
Provider = provider;
}
}
}
| 31.372093 | 135 | 0.629355 | [
"ECL-2.0",
"Apache-2.0"
] | pulumi/pulumi-auth0 | sdk/dotnet/Outputs/GuardianPhone.cs | 1,349 | C# |
using System.ComponentModel;
namespace RedditSaveTransfer.Threading
{
/// <summary>
/// Basic class used for threading
/// </summary>
public class WorkerThread
{
public BackgroundWorker Thread { get; private set; }
public WorkerThread()
{
Thread = new BackgroundWorker { WorkerReportsProgress = true, WorkerSupportsCancellation = true };
Thread.DoWork += thread_DoWork;
Thread.ProgressChanged += thread_ProgressChanged;
Thread.RunWorkerCompleted += thread_RunWorkerCompleted;
}
public void Start()
{
Thread.RunWorkerAsync();
}
public void Stop()
{
Thread.CancelAsync();
Thread.Dispose();
}
protected virtual void thread_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
}
protected virtual void thread_DoWork(object sender, DoWorkEventArgs e)
{
if (Thread.CancellationPending)
return;
}
protected virtual void thread_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
}
}
}
| 24.02 | 110 | 0.597002 | [
"MIT"
] | mavispuford/RedditSaveTransfer | Threading/WorkerThread.cs | 1,203 | C# |
using System;
using System.Collections.Generic;
using Newtonsoft.Json;
using Comformation.IntrinsicFunctions;
namespace Comformation.MediaLive.Channel
{
/// <summary>
/// AWS::MediaLive::Channel VideoSelectorColorSpaceSettings
/// https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-medialive-channel-videoselectorcolorspacesettings.html
/// </summary>
public class VideoSelectorColorSpaceSettings
{
/// <summary>
/// Hdr10Settings
/// Settings to configure color space settings in the incoming video.
/// Required: No
/// Type: Hdr10Settings
/// Update requires: No interruption
/// </summary>
[JsonProperty("Hdr10Settings")]
public Hdr10Settings Hdr10Settings { get; set; }
}
}
| 29.962963 | 140 | 0.684796 | [
"MIT"
] | stanb/Comformation | src/Comformation/Generated/MediaLive/Channel/VideoSelectorColorSpaceSettings.cs | 809 | C# |
// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information.
// Ported from um/wingdi.h in the Windows SDK for Windows 10.0.20348.0
// Original source is Copyright © Microsoft. All rights reserved.
using NUnit.Framework;
using System.Runtime.InteropServices;
namespace TerraFX.Interop.Windows.UnitTests;
/// <summary>Provides validation of the <see cref="DISPLAYCONFIG_TARGET_PREFERRED_MODE" /> struct.</summary>
public static unsafe partial class DISPLAYCONFIG_TARGET_PREFERRED_MODETests
{
/// <summary>Validates that the <see cref="DISPLAYCONFIG_TARGET_PREFERRED_MODE" /> struct is blittable.</summary>
[Test]
public static void IsBlittableTest()
{
Assert.That(Marshal.SizeOf<DISPLAYCONFIG_TARGET_PREFERRED_MODE>(), Is.EqualTo(sizeof(DISPLAYCONFIG_TARGET_PREFERRED_MODE)));
}
/// <summary>Validates that the <see cref="DISPLAYCONFIG_TARGET_PREFERRED_MODE" /> struct has the right <see cref="LayoutKind" />.</summary>
[Test]
public static void IsLayoutSequentialTest()
{
Assert.That(typeof(DISPLAYCONFIG_TARGET_PREFERRED_MODE).IsLayoutSequential, Is.True);
}
/// <summary>Validates that the <see cref="DISPLAYCONFIG_TARGET_PREFERRED_MODE" /> struct has the correct size.</summary>
[Test]
public static void SizeOfTest()
{
Assert.That(sizeof(DISPLAYCONFIG_TARGET_PREFERRED_MODE), Is.EqualTo(80));
}
}
| 42.171429 | 145 | 0.75 | [
"MIT"
] | IngmarBitter/terrafx.interop.windows | tests/Interop/Windows/Windows/um/wingdi/DISPLAYCONFIG_TARGET_PREFERRED_MODETests.cs | 1,478 | 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 Maten.App.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.322581 | 151 | 0.579887 | [
"MIT"
] | balbarak/Maten | src/Maten.App/Properties/Settings.Designer.cs | 1,066 | C# |
using System;
namespace CSharpGL
{
public class BlendFactorHelper
{
private int currentSource;
private int currentDest;
private static BlendSrcFactor[] sourceFactors;
private static BlendDestFactor[] destFactors;
static BlendFactorHelper()
{
{
Array sources = Enum.GetValues(typeof(BlendSrcFactor));
sourceFactors = new BlendSrcFactor[sources.Length];
int i = 0;
foreach (var item in sources)
{
sourceFactors[i++] = (BlendSrcFactor)item;
}
}
{
Array dests = Enum.GetValues(typeof(BlendDestFactor));
destFactors = new BlendDestFactor[dests.Length];
int i = 0;
foreach (var item in dests)
{
destFactors[i++] = (BlendDestFactor)item;
}
}
}
public void GetNext(out BlendSrcFactor source, out BlendDestFactor dest)
{
source = sourceFactors[currentSource];
dest = destFactors[currentDest];
currentDest++;
if (currentDest >= destFactors.Length)
{
currentDest = 0;
currentSource++;
if (currentSource >= sourceFactors.Length)
{
currentSource = 0;
}
}
}
public override string ToString()
{
return string.Format("glBlendFunc({0}, {1});", sourceFactors[currentSource], destFactors[currentDest]);
}
}
} | 29.403509 | 115 | 0.49642 | [
"MIT"
] | AugusZhan/CSharpGL | Infrastructure/CSharpGL.TestHelpers/BlendFactorHelper.cs | 1,678 | C# |
using System;
using NUnit.Framework;
using System.Linq;
using System.Linq.Expressions;
using System.Collections.Generic;
namespace DynamicExpresso.UnitTest
{
[TestFixture]
public class InvalidExpressionTest
{
[Test]
[ExpectedException(typeof(UnknownIdentifierException))]
public void Not_existing_variable()
{
var target = new Interpreter();
target.Eval("not_existing");
}
[Test]
[ExpectedException(typeof(ParseException))]
public void Invalid_equal_assignment_operator_left()
{
var target = new Interpreter();
target.Eval("=234");
}
[Test]
[ExpectedException(typeof(ArgumentException))]
public void Invalid_equal_assignment_operator_left_is_literal()
{
var target = new Interpreter();
target.Eval("352=234");
}
[Test]
[ExpectedException(typeof(ParseException))]
public void Unkonwn_operator_triple_equal()
{
var target = new Interpreter();
target.Eval("352===234");
}
[Test]
[ExpectedException(typeof(UnknownIdentifierException))]
public void Not_existing_function()
{
var target = new Interpreter();
target.Eval("pippo()");
}
[Test]
[ExpectedException(typeof(ParseException))]
public void Not_valid_function()
{
var target = new Interpreter();
target.Eval("2()");
}
[Test]
[ExpectedException(typeof(UnknownIdentifierException))]
public void Not_valid_expression()
{
var target = new Interpreter();
target.Eval("'5' + 3 /(asda");
}
[Test]
[ExpectedException(typeof(UnknownIdentifierException))]
public void TryParse_an_invalid_expression_unknown_identifier_x()
{
var target = new Interpreter();
try
{
target.Parse("x + y * Math.Pow(x, 2)", typeof(void));
}
catch(UnknownIdentifierException ex)
{
Assert.AreEqual("Unknown identifier 'x' (at index 0).", ex.Message);
Assert.AreEqual("x", ex.Identifier);
Assert.AreEqual(0, ex.Position);
throw;
}
}
[Test]
[ExpectedException(typeof(UnknownIdentifierException))]
public void Parse_an_invalid_expression_unknown_identifier_y()
{
var target = new Interpreter()
.SetVariable("x", 10.0);
try
{
target.Parse("x + y * Math.Pow(x, 2)", typeof(void));
}
catch (UnknownIdentifierException ex)
{
Assert.AreEqual("y", ex.Identifier);
Assert.AreEqual(4, ex.Position);
throw;
}
}
[Test]
[ExpectedException(typeof(NoApplicableMethodException))]
public void Parse_an_invalid_expression_unknown_method()
{
var target = new Interpreter()
.SetVariable("x", 10.0);
try
{
target.Parse("Math.NotExistingMethod(x, 2)", typeof(void));
}
catch (NoApplicableMethodException ex)
{
Assert.AreEqual("NotExistingMethod", ex.MethodName);
Assert.AreEqual("Math", ex.MethodTypeName);
Assert.AreEqual(5, ex.Position);
throw;
}
}
[ExpectedException(typeof(InvalidOperationException))]
[Test]
public void SystemExceptions_are_preserved_using_delegate_variable()
{
var target = new Interpreter();
Func<string> testException = new Func<string>(() =>
{
throw new InvalidOperationException("Test");
});
target.SetVariable("testException", testException);
target.Eval("testException()");
}
[ExpectedException(typeof(MyException))]
[Test]
public void CustomExceptions_WithoutSerializationConstructor_are_preserved()
{
var target = new Interpreter();
Func<string> testException = new Func<string>(() =>
{
throw new MyException("Test");
});
target.SetVariable("testException", testException);
target.Eval("testException()");
}
[ExpectedException(typeof(NotImplementedException))]
[Test]
public void SystemExceptions_are_preserved_using_method_invocation()
{
var target = new Interpreter();
target.SetVariable("a", new MyTestService());
target.Eval("a.ThrowException()");
}
public class MyException : Exception
{
public MyException(string message) : base(message) { }
}
class MyTestService
{
public string ThrowException()
{
throw new NotImplementedException("AppException");
}
}
}
}
| 21.767196 | 78 | 0.691541 | [
"Unlicense"
] | andrewhoi/DynamicExpresso | test/DynamicExpresso.UnitTest/InvalidExpressionTest.cs | 4,116 | C# |
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
// **NOTE** This file was generated by a tool and any changes will be overwritten.
// <auto-generated/>
// Template Source: EntityRequestBuilder.cs.tt
namespace Microsoft.Graph
{
using System;
using System.Collections.Generic;
using System.IO;
/// <summary>
/// The type GroupPolicyObjectFileRequestBuilder.
/// </summary>
public partial class GroupPolicyObjectFileRequestBuilder : EntityRequestBuilder, IGroupPolicyObjectFileRequestBuilder
{
/// <summary>
/// Constructs a new GroupPolicyObjectFileRequestBuilder.
/// </summary>
/// <param name="requestUrl">The URL for the built request.</param>
/// <param name="client">The <see cref="IBaseClient"/> for handling requests.</param>
public GroupPolicyObjectFileRequestBuilder(
string requestUrl,
IBaseClient client)
: base(requestUrl, client)
{
}
/// <summary>
/// Builds the request.
/// </summary>
/// <returns>The built request.</returns>
public new IGroupPolicyObjectFileRequest Request()
{
return this.Request(null);
}
/// <summary>
/// Builds the request.
/// </summary>
/// <param name="options">The query and header options for the request.</param>
/// <returns>The built request.</returns>
public new IGroupPolicyObjectFileRequest Request(IEnumerable<Option> options)
{
return new GroupPolicyObjectFileRequest(this.RequestUrl, this.Client, options);
}
}
}
| 35.018182 | 153 | 0.579958 | [
"MIT"
] | GeertVL/msgraph-beta-sdk-dotnet | src/Microsoft.Graph/Generated/requests/GroupPolicyObjectFileRequestBuilder.cs | 1,926 | C# |
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using osu.Framework.Platform;
using System.Linq;
using System.Threading;
using osu.Framework.Development;
using osu.Framework.Threading;
namespace osu.Framework.Logging
{
/// <summary>
/// This class allows statically (globally) configuring and using logging functionality.
/// </summary>
public class Logger
{
private static readonly object static_sync_lock = new object();
// separate locking object for flushing so that we don't lock too long on the staticSyncLock object, since we have to
// hold this lock for the entire duration of the flush (waiting for I/O etc) before we can resume scheduling logs
// but other operations like GetLogger(), ApplyFilters() etc. can still be executed while a flush is happening.
private static readonly object flush_sync_lock = new object();
/// <summary>
/// Whether logging is enabled. Setting this to false will disable all logging.
/// </summary>
public static bool Enabled = true;
/// <summary>
/// The minimum log-level a logged message needs to have to be logged. Default is <see cref="LogLevel.Verbose"/>. Please note that setting this to <see cref="LogLevel.Debug"/> will log input events, including keypresses when entering a password.
/// </summary>
public static LogLevel Level = DebugUtils.IsDebugBuild ? LogLevel.Debug : LogLevel.Verbose;
/// <summary>
/// An identifier used in log file headers to figure where the log file came from.
/// </summary>
public static string UserIdentifier = Environment.UserName;
/// <summary>
/// An identifier for the game written to log file headers to indicate where the log file came from.
/// </summary>
public static string GameIdentifier = @"game";
/// <summary>
/// An identifier for the version written to log file headers to indicate where the log file came from.
/// </summary>
public static string VersionIdentifier = @"unknown";
private static Storage storage;
/// <summary>
/// The storage to place logs inside.
/// </summary>
public static Storage Storage
{
private get => storage;
set => storage = value ?? throw new ArgumentNullException(nameof(value));
}
/// <summary>
/// Add a plain-text phrase which should always be filtered from logs. The filtered phrase will be replaced with asterisks (*).
/// Useful for avoiding logging of credentials.
/// See also <seealso cref="ApplyFilters(string)"/>.
/// </summary>
public static void AddFilteredText(string text)
{
if (string.IsNullOrEmpty(text)) return;
lock (static_sync_lock)
filters.Add(text);
}
/// <summary>
/// Removes phrases which should be filtered from logs.
/// Useful for avoiding logging of credentials.
/// See also <seealso cref="AddFilteredText(string)"/>.
/// </summary>
public static string ApplyFilters(string message)
{
lock (static_sync_lock)
{
foreach (string f in filters)
message = message.Replace(f, string.Empty.PadRight(f.Length, '*'));
}
return message;
}
/// <summary>
/// Logs the given exception with the given description to the specified logging target.
/// </summary>
/// <param name="e">The exception that should be logged.</param>
/// <param name="description">The description of the error that should be logged with the exception.</param>
/// <param name="target">The logging target (file).</param>
/// <param name="recursive">Whether the inner exceptions of the given exception <paramref name="e"/> should be logged recursively.</param>
public static void Error(Exception e, string description, LoggingTarget target = LoggingTarget.Runtime, bool recursive = false)
{
error(e, description, target, null, recursive);
}
/// <summary>
/// Logs the given exception with the given description to the logger with the given name.
/// </summary>
/// <param name="e">The exception that should be logged.</param>
/// <param name="description">The description of the error that should be logged with the exception.</param>
/// <param name="name">The logger name (file).</param>
/// <param name="recursive">Whether the inner exceptions of the given exception <paramref name="e"/> should be logged recursively.</param>
public static void Error(Exception e, string description, string name, bool recursive = false)
{
error(e, description, null, name, recursive);
}
private static void error(Exception e, string description, LoggingTarget? target, string name, bool recursive)
{
log($@"{description}", target, name, LogLevel.Error, e);
if (recursive && e.InnerException != null)
error(e.InnerException, $"{description} (inner)", target, name, true);
}
/// <summary>
/// Log an arbitrary string to the specified logging target.
/// </summary>
/// <param name="message">The message to log. Can include newline (\n) characters to split into multiple lines.</param>
/// <param name="target">The logging target (file).</param>
/// <param name="level">The verbosity level.</param>
public static void Log(string message, LoggingTarget target = LoggingTarget.Runtime, LogLevel level = LogLevel.Verbose)
{
log(message, target, null, level);
}
/// <summary>
/// Log an arbitrary string to the logger with the given name.
/// </summary>
/// <param name="message">The message to log. Can include newline (\n) characters to split into multiple lines.</param>
/// <param name="name">The logger name (file).</param>
/// <param name="level">The verbosity level.</param>
public static void Log(string message, string name, LogLevel level = LogLevel.Verbose)
{
log(message, null, name, level);
}
private static void log(string message, LoggingTarget? target, string loggerName, LogLevel level, Exception exception = null)
{
try
{
if (target.HasValue)
GetLogger(target.Value).Add(message, level, exception);
else
GetLogger(loggerName).Add(message, level, exception);
}
catch
{
}
}
/// <summary>
/// Logs a message to the specified logging target and also displays a print statement.
/// </summary>
/// <param name="message">The message to log. Can include newline (\n) characters to split into multiple lines.</param>
/// <param name="target">The logging target (file).</param>
/// <param name="level">The verbosity level.</param>
public static void LogPrint(string message, LoggingTarget target = LoggingTarget.Runtime, LogLevel level = LogLevel.Verbose)
{
if (Enabled && DebugUtils.IsDebugBuild)
System.Diagnostics.Debug.Print(message);
Log(message, target, level);
}
/// <summary>
/// Logs a message to the logger with the given name and also displays a print statement.
/// </summary>
/// <param name="message">The message to log. Can include newline (\n) characters to split into multiple lines.</param>
/// <param name="name">The logger name (file).</param>
/// <param name="level">The verbosity level.</param>
public static void LogPrint(string message, string name, LogLevel level = LogLevel.Verbose)
{
if (Enabled && DebugUtils.IsDebugBuild)
System.Diagnostics.Debug.Print(message);
Log(message, name, level);
}
/// <summary>
/// For classes that regularly log to the same target, this method may be preferred over the static Log method.
/// </summary>
/// <param name="target">The logging target.</param>
/// <returns>The logger responsible for the given logging target.</returns>
public static Logger GetLogger(LoggingTarget target = LoggingTarget.Runtime)
{
// there can be no name conflicts between LoggingTarget-based Loggers and named loggers because
// every name that would coincide with a LoggingTarget-value is reserved and cannot be used (see ctor).
return GetLogger(target.ToString());
}
/// <summary>
/// For classes that regularly log to the same target, this method may be preferred over the static Log method.
/// </summary>
/// <param name="name">The name of the custom logger.</param>
/// <returns>The logger responsible for the given logging target.</returns>
public static Logger GetLogger(string name)
{
lock (static_sync_lock)
{
var nameLower = name.ToLower();
if (!static_loggers.TryGetValue(nameLower, out Logger l))
{
static_loggers[nameLower] = l = Enum.TryParse(name, true, out LoggingTarget target) ? new Logger(target) : new Logger(name);
l.clear();
}
return l;
}
}
/// <summary>
/// The target for which this logger logs information. This will only be null if the logger has a name.
/// </summary>
public LoggingTarget? Target { get; }
/// <summary>
/// The name of the logger. This will only have a value if <see cref="Target"/> is null.
/// </summary>
public string Name { get; }
/// <summary>
/// Gets the name of the file that this logger is logging to.
/// </summary>
public string Filename => $@"{(Target?.ToString() ?? Name).ToLower()}.log";
private Logger(LoggingTarget target = LoggingTarget.Runtime)
{
Target = target;
}
private static readonly HashSet<string> reserved_names = new HashSet<string>(Enum.GetNames(typeof(LoggingTarget)).Select(n => n.ToLower()));
private Logger(string name)
{
if (string.IsNullOrWhiteSpace(name))
throw new ArgumentException("The name of a logger must be non-null and may not contain only white space.", nameof(name));
if (reserved_names.Contains(name.ToLower()))
throw new ArgumentException($"The name \"{name}\" is reserved. Please use the {nameof(LoggingTarget)}-value corresponding to the name instead.");
Name = name;
}
/// <summary>
/// Logs a new message with the <see cref="LogLevel.Debug"/> and will only be logged if your project is built in the Debug configuration. Please note that the default setting for <see cref="Level"/> is <see cref="LogLevel.Verbose"/> so unless you increase the <see cref="Level"/> to <see cref="LogLevel.Debug"/> messages printed with this method will not appear in the output.
/// </summary>
/// <param name="message">The message that should be logged.</param>
[Conditional("DEBUG")]
public void Debug(string message = @"")
{
Add(message, LogLevel.Debug);
}
/// <summary>
/// Log an arbitrary string to current log.
/// </summary>
/// <param name="message">The message to log. Can include newline (\n) characters to split into multiple lines.</param>
/// <param name="level">The verbosity level.</param>
/// <param name="exception">An optional related exception.</param>
public void Add(string message = @"", LogLevel level = LogLevel.Verbose, Exception exception = null) =>
add(message, level, exception, OutputToListeners);
private readonly RollingTime debugOutputRollingTime = new RollingTime(50, 10000);
private void add(string message = @"", LogLevel level = LogLevel.Verbose, Exception exception = null, bool outputToListeners = true)
{
if (!Enabled || level < Level)
return;
ensureHeader();
message = ApplyFilters(message);
string logOutput = message;
if (exception != null)
// add exception output to console / logfile output (but not the LogEntry's message).
logOutput += $"\n{ApplyFilters(exception.ToString())}";
IEnumerable<string> lines = logOutput
.Replace(@"\r\n", @"\n")
.Split('\n')
.Select(s => $@"{DateTime.UtcNow.ToString(NumberFormatInfo.InvariantInfo)}: {s.Trim()}");
if (outputToListeners)
{
NewEntry?.Invoke(new LogEntry
{
Level = level,
Target = Target,
LoggerName = Name,
Message = message,
Exception = exception
});
if (DebugUtils.IsDebugBuild)
{
void consoleLog(string msg)
{
// fire to all debug listeners (like visual studio's output window)
System.Diagnostics.Debug.Print(msg);
// fire for console displays (appveyor/CI).
Console.WriteLine(msg);
}
bool bypassRateLimit = level >= LogLevel.Verbose;
foreach (var line in lines)
{
if (bypassRateLimit || debugOutputRollingTime.RequestEntry())
{
consoleLog($"[{Target?.ToString().ToLower() ?? Name}:{level.ToString().ToLower()}] {line}");
if (!bypassRateLimit && debugOutputRollingTime.IsAtLimit)
consoleLog($"Console output is being limited. Please check {Filename} for full logs.");
}
}
}
}
if (Target == LoggingTarget.Information)
// don't want to log this to a file
return;
lock (flush_sync_lock)
{
// we need to check if the logger is still enabled here, since we may have been waiting for a
// flush and while the flush was happening, the logger might have been disabled. In that case
// we want to make sure that we don't accidentally write anything to a file after that flush.
if (!Enabled)
return;
scheduler.Add(delegate
{
try
{
using (var stream = Storage.GetStream(Filename, FileAccess.Write, FileMode.Append))
using (var writer = new StreamWriter(stream))
foreach (var line in lines)
writer.WriteLine(line);
}
catch
{
}
});
writer_idle.Reset();
}
}
/// <summary>
/// Whether the output of this logger should be sent to listeners of <see cref="Debug"/> and <see cref="Console"/>.
/// Defaults to true.
/// </summary>
public bool OutputToListeners { get; set; } = true;
/// <summary>
/// Fires whenever any logger tries to log a new entry, but before the entry is actually written to the logfile.
/// </summary>
public static event Action<LogEntry> NewEntry;
/// <summary>
/// Deletes log file from disk.
/// </summary>
private void clear()
{
lock (flush_sync_lock)
{
scheduler.Add(() => Storage.Delete(Filename));
writer_idle.Reset();
}
}
private bool headerAdded;
private void ensureHeader()
{
if (headerAdded) return;
headerAdded = true;
add("----------------------------------------------------------", outputToListeners: false);
add($"{Target} Log for {UserIdentifier} (LogLevel: {Level})", outputToListeners: false);
add($"{GameIdentifier} {VersionIdentifier}", outputToListeners: false);
add($"Running on {Environment.OSVersion}, {Environment.ProcessorCount} cores", outputToListeners: false);
add("----------------------------------------------------------", outputToListeners: false);
}
private static readonly List<string> filters = new List<string>();
private static readonly Dictionary<string, Logger> static_loggers = new Dictionary<string, Logger>();
private static readonly Scheduler scheduler = new Scheduler();
private static readonly ManualResetEvent writer_idle = new ManualResetEvent(true);
private static readonly Timer timer;
static Logger()
{
// timer has a very low overhead.
timer = new Timer(_ =>
{
if ((Storage != null ? scheduler.Update() : 0) == 0)
writer_idle.Set();
// reschedule every 50ms. avoids overlapping callbacks.
timer.Change(50, Timeout.Infinite);
}, null, 0, Timeout.Infinite);
}
/// <summary>
/// Pause execution until all logger writes have completed and file handles have been closed.
/// This will also unbind all handlers bound to <see cref="NewEntry"/>.
/// </summary>
public static void Flush()
{
lock (flush_sync_lock)
{
writer_idle.WaitOne(500);
NewEntry = null;
}
}
}
/// <summary>
/// Captures information about a logged message.
/// </summary>
public class LogEntry
{
/// <summary>
/// The level for which the message was logged.
/// </summary>
public LogLevel Level;
/// <summary>
/// The target to which this message is being logged, or null if it is being logged to a custom named logger.
/// </summary>
public LoggingTarget? Target;
/// <summary>
/// The name of the logger to which this message is being logged, or null if it is being logged to a specific <see cref="LoggingTarget"/>.
/// </summary>
public string LoggerName;
/// <summary>
/// The message that was logged.
/// </summary>
public string Message;
/// <summary>
/// An optional related exception.
/// </summary>
public Exception Exception;
}
/// <summary>
/// The level on which a log-message is logged.
/// </summary>
public enum LogLevel
{
/// <summary>
/// Log-level for debugging-related log-messages. This is the lowest level (highest verbosity). Please note that this will log input events, including keypresses when entering a password.
/// </summary>
Debug,
/// <summary>
/// Log-level for most log-messages. This is the second-lowest level (second-highest verbosity).
/// </summary>
Verbose,
/// <summary>
/// Log-level for important log-messages. This is the second-highest level (second-lowest verbosity).
/// </summary>
Important,
/// <summary>
/// Log-level for error messages. This is the highest level (lowest verbosity).
/// </summary>
Error
}
/// <summary>
/// The target for logging. Different targets can have different logfiles, are displayed differently in the LogOverlay and are generally useful for organizing logs into groups.
/// </summary>
public enum LoggingTarget
{
/// <summary>
/// Logging target for general information. Everything logged with this target will not be written to a logfile.
/// </summary>
Information,
/// <summary>
/// Logging target for information about the runtime.
/// </summary>
Runtime,
/// <summary>
/// Logging target for network-related events.
/// </summary>
Network,
/// <summary>
/// Logging target for performance-related information.
/// </summary>
Performance,
/// <summary>
/// Logging target for database-related events.
/// </summary>
Database
}
}
| 41.904398 | 385 | 0.557492 | [
"MIT"
] | chrisny286/osu-framework | osu.Framework/Logging/Logger.cs | 21,396 | C# |
using CG.Blazor.Plugins;
using CG.Blazor.Plugins.Options;
using CG.Runtime;
using CG.Validations;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.FileProviders;
using Microsoft.Extensions.Options;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
namespace Microsoft.AspNetCore.Builder
{
/// <summary>
/// This class contains extension methods related to the <see cref="IApplicationBuilder"/>
/// </summary>
public static partial class ApplicationBuilderExtensions
{
// *******************************************************************
// Public methods.
// *******************************************************************
#region Public methods
/// <summary>
/// This method wires up services needed to support Blazor plugins.
/// </summary>
/// <param name="applicationBuilder">The application builder to use
/// for the operation.</param>
/// <param name="webHostEnvironment">The hosting environment to use
/// for the operation.</param>
/// <returns>the value of the <paramref name="applicationBuilder"/>
/// parameter, for chaining method calls together.</returns>
/// <exception cref="ArgumentException">This exception is thrown whenever
/// one or more arguments is missing, or invalid.</exception>
/// <exception cref="BlazorPluginException">This exception is thrown whenever
/// the operation fails.</exception>
public static IApplicationBuilder UseBlazorPlugins(
this IApplicationBuilder applicationBuilder,
IWebHostEnvironment webHostEnvironment
)
{
// Validate the parameters before attempting to use them.
Guard.Instance().ThrowIfNull(applicationBuilder, nameof(applicationBuilder))
.ThrowIfNull(webHostEnvironment, nameof(webHostEnvironment));
// One of the things we need to do, in order to support static resources
// in late-bound, dynamically loaded assemblies, is to create an embedded
// file provider for each plugin assembly and wire everything together with
// a composite file provider. We'll do that here.
// Ensure we're setup to use static files.
applicationBuilder.UseStaticFiles();
var allProviders = new List<IFileProvider>();
// Is there already a file provider?
if (webHostEnvironment.WebRootFileProvider != null)
{
// Add the existing file provider.
allProviders.Add(
webHostEnvironment.WebRootFileProvider
);
}
var asmNameSet = new HashSet<string>();
// Add providers for any embedded style sheets.
BuildStyleSheetProviders(
asmNameSet,
allProviders
);
// Add providers for any embedded scripts.
BuildScriptProviders(
asmNameSet,
allProviders
);
// Get the plugin options.
var options = applicationBuilder.ApplicationServices
.GetRequiredService<IOptions<BlazorPluginsOptions>>();
// Add any remaining providers.
BuildRemainingProviders(
options,
asmNameSet,
allProviders
);
// Replace the existing file provider with a composite provider.
webHostEnvironment.WebRootFileProvider = new CompositeFileProvider(
allProviders
);
var errors = new List<Exception>();
// The final thing we need to do is walk through the list of modules
// and call the Configure method on each one, just in case any of
// them are expecting that to happen.
foreach (var module in BlazorResources.Modules)
{
try
{
// Configure any services in the module.
module.Configure(
applicationBuilder,
webHostEnvironment
);
}
catch (Exception ex)
{
errors.Add(ex);
}
}
// Were there errors?
if (errors.Any())
{
throw new AggregateException(
message: $"One or more errors were detected while configuring " +
$"Blazor plugin modules. See inner exceptions for more details.",
innerExceptions: errors
);
}
// At this point we clear the cached modules because we no longer
// require those resources in memory.
BlazorResources.Modules.Clear();
// Return the application builder.
return applicationBuilder;
}
#endregion
// *******************************************************************
// Private methods.
// *******************************************************************
#region Private methods
/// <summary>
/// This method looks through the script tags in the <see cref="BlazorResources.Scripts"/>
/// collection and ensures that each plugin has a file provider in the
/// <paramref name="allProviders"/> collection, to read the static
/// resource at runtime.
/// </summary>
/// <param name="asmNameSet">The set of all previously processed plugin
/// assemblies.</param>
/// <param name="allProviders">The list of all previously added file
/// providers.</param>
private static void BuildScriptProviders(
HashSet<string> asmNameSet,
List<IFileProvider> allProviders
)
{
// Loop through all the script tags.
foreach (var resource in BlazorResources.Scripts)
{
// We won't check these tags for embedded HTML since that
// was already done in the AddPlugins method.
// Look for the leading content portion.
var index1 = resource.IndexOf("_content/");
if (index1 == -1)
{
// Panic.
throw new BlazorPluginException(
message: $"It appears the script tag '{resource}' " +
$"is missing the '_content/' portion of the tag."
);
}
// Adjust the index.
index1 += "_content/".Length;
// Look for the first '/' character.
var index2 = resource.IndexOf("/", index1);
if (index2 == -1)
{
// Panic.
throw new BlazorPluginException(
message: $"It appears the script tag '{resource}'" +
$"is missing a '/' after the assembly name."
);
}
// Parse out the assembly name.
var asmName = resource[index1..index2];
// Have we already created a file provider for this assembly?
if (asmNameSet.Contains(asmName))
{
continue; // Nothing to do.
}
// If we get here then we need to create an embedded file provider
// for the plugin assembly.
// Create a loader instance.
var loader = new AssemblyLoader();
Assembly? asm = null;
try
{
// Get the assembly reference.
asm = loader.LoadFromAssemblyName(
new AssemblyName(asmName)
);
}
catch (FileNotFoundException ex)
{
// Provide better context for the error.
throw new BlazorPluginException(
message: $"It appears the plugin assembly '{asmName}' " +
$"can't be found. See inner exception for more detail.",
innerException: ex
);
}
try
{
// Create a file provider to read embedded resources.
var fileProvider = new ManifestEmbeddedFileProviderEx(
asm,
$"wwwroot"
);
// Add the provider to the collection.
allProviders.Insert(0, fileProvider);
}
catch (InvalidOperationException)
{
// Not really an error, the plugin assembly might not have,
// or event need an embedded stream of resources.
}
}
}
// *******************************************************************
/// <summary>
/// This method looks through the style sheet links in the <see cref="BlazorResources.StyleSheets"/>
/// collection and ensures that each plugin has a file provider in the
/// <paramref name="allProviders"/> collection, to read the static
/// resource at runtime.
/// </summary>
/// <param name="asmNameSet">The set of all previously processed plugin
/// assemblies.</param>
/// <param name="allProviders">The list of all previously added file
/// providers.</param>
private static void BuildStyleSheetProviders(
HashSet<string> asmNameSet,
List<IFileProvider> allProviders
)
{
// Loop through all the style sheets links.
foreach (var resource in BlazorResources.StyleSheets)
{
// We won't check these tags for embedded HTML since that
// was already done in the AddPlugins method.
// Look for the leading content portion.
var index1 = resource.IndexOf("_content/");
if (index1 == -1)
{
// Panic.
throw new BlazorPluginException(
message: $"It appears the script tag '{resource}' " +
$"is missing the '_content/' portion of the tag."
);
}
// Adjust the index.
index1 += "_content/".Length;
// Look for the first '/' character.
var index2 = resource.IndexOf("/", index1);
if (index2 == -1)
{
// Panic.
throw new BlazorPluginException(
message: $"It appears the script tag '{resource}' " +
$"is missing a '/' after the assembly name."
);
}
// Parse out the assembly name.
var asmName = resource[index1..index2];
// Have we already created a file provider for this assembly?
if (asmNameSet.Contains(asmName))
{
continue; // Nothing to do.
}
// If we get here then we need to create an embedded file provider
// for the plugin assembly.
// Create a loader instance.
var loader = new AssemblyLoader();
Assembly? asm = null;
try
{
// Get the assembly reference.
asm = loader.LoadFromAssemblyName(
new AssemblyName(asmName)
);
}
catch (FileNotFoundException ex)
{
// Provide better context for the error.
throw new BlazorPluginException(
message: $"It appears the plugin assembly '{asmName}' " +
$"can't be found. See inner exception for more detail.",
innerException: ex
);
}
try
{
// Create a file provider to read embedded resources.
var fileProvider = new ManifestEmbeddedFileProviderEx(
asm,
$"wwwroot"
);
// Add the provider to the collection.
allProviders.Insert(0, fileProvider);
}
catch (InvalidOperationException)
{
// Not really an error, the plugin assembly might not have,
// or event need an embedded stream of resources.
}
}
}
// *******************************************************************
/// <summary>
/// This method adds a file provider for any plugin assembly that doesn't
/// contain links to embedded style sheets, or javascripts.
/// </summary>
/// <param name="options">The options to use for the operation.</param>
/// <param name="asmNameSet">The set of all previously processed plugin
/// assemblies.</param>
/// <param name="allProviders">The list of all previously added file
/// providers.</param>
private static void BuildRemainingProviders(
IOptions<BlazorPluginsOptions> options,
HashSet<string> asmNameSet,
List<IFileProvider> allProviders
)
{
// Create a loader instance.
var loader = new AssemblyLoader();
// Loop through all the plugin modules.
foreach (var module in options.Value.Modules)
{
Assembly? asm;
// Is this module configured with a path?
if (module.AssemblyNameOrPath.EndsWith(".dll"))
{
// Strip out just the assembly file name.
var fileName = Path.GetFileNameWithoutExtension(
module.AssemblyNameOrPath
);
// Have we already processed this assembly?
if (asmNameSet.Contains(fileName))
{
continue; // Nothing left to do.
}
// Check for relative paths.
if (false == Path.IsPathRooted(
module.AssemblyNameOrPath
))
{
// Expand the path (the load expects a rooted path).
var completePath = Path.GetFullPath(
module.AssemblyNameOrPath
);
// Load the assembly from the path.
asm = loader.LoadFromAssemblyPath(
completePath
);
}
else
{
// Load the assembly from the path.
asm = loader.LoadFromAssemblyPath(
module.AssemblyNameOrPath
);
}
}
else
{
// Have we already processed this assembly?
if (asmNameSet.Contains(module.AssemblyNameOrPath))
{
continue; // Nothing left to do.
}
// Make an assembly name.
var asmName = new AssemblyName(
module.AssemblyNameOrPath
);
// Load the assembly by name.
asm = loader.LoadFromAssemblyName(
asmName
);
}
// At this point we have a reference to the loaded assembly so we
// can use that to try to find an embedded resource manifest.
try
{
// Create a file provider to read embedded resources.
var fileProvider = new ManifestEmbeddedFileProviderEx(
asm,
$"wwwroot"
);
// Add the provider to the collection.
allProviders.Insert(0, fileProvider);
}
catch (InvalidOperationException)
{
// Not really an error, the plugin assembly might not have,
// or event need an embedded stream of resources.
}
}
}
#endregion
}
}
| 38.635556 | 108 | 0.473484 | [
"MIT"
] | CodeGator/CG.Blazor.Plugins | src/CG.Blazor.Plugins/ApplicationBuilderExtensions.cs | 17,388 | C# |
// <copyright file="IBlob.cs" company="nett">
// Copyright (c) 2015 All Right Reserved, http://q.nett.gr
// Please see the License.txt file for more information. All other rights reserved.
// </copyright>
// <author>James Kavakopoulos</author>
// <email>ofthetimelords@gmail.com</email>
// <date>2015/02/06</date>
// <summary>
//
// </summary>
using System;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace TheQ.Utilities.CloudTools.Storage.Models.ObjectModel
{
/// <summary>
/// Defines a BLOB, with the least required functionality for CloudTools
/// </summary>
public interface IBlob
{
/// <summary>
/// Gets the name of the blob.
/// </summary>
/// <value>
/// A string containing the name of the blob.
/// </value>
string Name { get; }
/// <summary>
/// <para>Gets a <see cref="IBlobContainer" /></para>
/// <para>object representing the blob's container.</para>
/// </summary>
/// <value>
/// <para>A <see cref="IBlobContainer" /></para>
/// <para>object.</para>
/// </value>
IBlobContainer Container { get; }
/// <summary>
/// Gets the properties of this BLOB.
/// </summary>
/// <value>
/// <para>A <see cref="IBlobProperties" /></para>
/// <para>object.</para>
/// </value>
IBlobProperties Properties { get; }
/// <summary>
/// Initiates an asynchronous operation to open a stream for reading from the blob.
/// </summary>
Task<Stream> OpenReadAsync();
/// <summary>
/// Initiates an asynchronous operation to open a stream for reading from the blob.
/// </summary>
Task<Stream> OpenReadAsync(CancellationToken cancellationToken);
/// <summary>
/// Initiates an asynchronous operation to populate the blob's properties and metadata.
/// </summary>
/// <returns>
/// <para>A <see cref="Task" /></para>
/// <para>object that represents the asynchronous operation.</para>
/// </returns>
Task FetchAttributesAsync();
/// <summary>
/// Initiates an asynchronous operation to populate the blob's properties and metadata.
/// </summary>
/// <param name="cancellationToken">
/// <para>A <see cref="CancellationToken" /></para>
/// <para>to observe while waiting for a task to complete.</para>
/// </param>
/// <returns>
/// <para>A <see cref="Task" /></para>
/// <para>object that represents the asynchronous operation.</para>
/// </returns>
Task FetchAttributesAsync(CancellationToken cancellationToken);
/// <summary>
/// Initiates an asynchronous operation to download the contents of a blob to a <see langword="byte" /> array.
/// </summary>
/// <param name="target">The target <see langword="byte" /> array.</param>
/// <param name="index">The starting offset in the <see langword="byte" /> array.</param>
/// <returns>
/// <para>A <see cref="Task" /></para>
/// <para>object of type <c>int</c></para>
/// <para>that represents the asynchronous operation.</para>
/// </returns>
Task<int> DownloadToByteArrayAsync(byte[] target, int index);
/// <summary>
/// Initiates an asynchronous operation to download the contents of a blob to a <see langword="byte" /> array.
/// </summary>
/// <param name="target">The target <see langword="byte" /> array.</param>
/// <param name="index">The starting offset in the <see langword="byte" /> array.</param>
/// <param name="cancellationToken">
/// <para>A <see cref="CancellationToken" /></para>
/// <para>to observe while waiting for a task to complete.</para>
/// </param>
/// <returns>
/// <para>A <see cref="Task" /></para>
/// <para>object of type <c>int</c></para>
/// <para>that represents the asynchronous operation.</para>
/// </returns>
Task<int> DownloadToByteArrayAsync(byte[] target, int index, CancellationToken cancellationToken);
/// <summary>
/// Initiates an asynchronous operation to upload a stream to a block blob.
/// </summary>
/// <param name="source">
/// <para>A <see cref="Stream" /></para>
/// <para>object providing the blob content.</para>
/// </param>
/// <returns>
/// <para>A <see cref="Task" /></para>
/// <para>object that represents the asynchronous operation.</para>
/// </returns>
Task UploadFromStreamAsync(Stream source);
/// <summary>
/// Initiates an asynchronous operation to upload a stream to a block blob.
/// </summary>
/// <param name="source">
/// <para>A <see cref="Stream" /></para>
/// <para>object providing the blob content.</para>
/// </param>
/// <param name="cancellationToken">
/// <para>A <see cref="CancellationToken" /></para>
/// <para>to observe while waiting for a task to complete.</para>
/// </param>
/// <returns>
/// <para>A <see cref="Task" /></para>
/// <para>object that represents the asynchronous operation.</para>
/// </returns>
Task UploadFromStreamAsync(Stream source, CancellationToken cancellationToken);
/// <summary>
/// Initiates an asynchronous operation to upload the contents of a <see langword="byte" /> array to a blob.
/// </summary>
/// <param name="buffer">An array of bytes.</param>
/// <param name="index">The zero-based <see langword="byte" /> offset in <paramref name="buffer" /> at which to begin uploading bytes to the blob.</param>
/// <param name="count">The number of bytes to be written to the blob.</param>
/// <returns>
/// <para>A <see cref="Task" /></para>
/// <para>object that represents the asynchronous operation.</para>
/// </returns>
Task UploadFromByteArrayAsync(byte[] buffer, int index, int count);
/// <summary>
/// Initiates an asynchronous operation to upload the contents of a <see langword="byte" /> array to a blob.
/// </summary>
/// <param name="buffer">An array of bytes.</param>
/// <param name="index">The zero-based <see langword="byte" /> offset in <paramref name="buffer" /> at which to begin uploading bytes to the blob.</param>
/// <param name="count">The number of bytes to be written to the blob.</param>
/// <param name="cancellationToken">
/// <para>A <see cref="CancellationToken" /></para>
/// <para>to observe while waiting for a task to complete.</para>
/// </param>
/// <returns>
/// <para>A <see cref="Task" /></para>
/// <para>object that represents the asynchronous operation.</para>
/// </returns>
Task UploadFromByteArrayAsync(byte[] buffer, int index, int count, CancellationToken cancellationToken);
/// <summary>
/// Initiates an asynchronous operation to check existence of the blob.
/// </summary>
/// <returns>
/// <para>A <see cref="Task" /></para>
/// <para>object of type <c>bool</c></para>
/// <para>that represents the asynchronous operation.</para>
/// </returns>
Task<bool> ExistsAsync();
/// <summary>
/// Initiates an asynchronous operation to check existence of the blob.
/// </summary>
/// <param name="cancellationToken">
/// <para>A <see cref="CancellationToken" /></para>
/// <para>to observe while waiting for a task to complete.</para>
/// </param>
/// <returns>
/// <para>A <see cref="Task" /></para>
/// <para>object of type <c>bool</c></para>
/// <para>that represents the asynchronous operation.</para>
/// </returns>
Task<bool> ExistsAsync(CancellationToken cancellationToken);
/// <summary>
/// Downloads the contents of a blob to a <see langword="byte" /> array.
/// </summary>
/// <param name="target">The target <see langword="byte" /> array.</param>
/// <param name="index">The starting offset in the <see langword="byte" /> array.</param>
/// <returns>
/// The total number of bytes read into the buffer.
/// </returns>
int DownloadToByteArray(byte[] target, int index);
/// <summary>
/// Deletes the current BLOB if it already exists.
/// </summary>
bool DeleteIfExists();
/// <summary>
/// Deletes the current BLOB if it already exists.
/// </summary>
Task<bool> DeleteIfExistsAsync();
/// <summary>
/// Initiates an asynchronous operation to upload a string of text to a blob. If the blob already exists, it will be overwritten.
///
/// </summary>
/// <param name="content">A string containing the text to upload.</param>
/// <returns>
/// A <see cref="T:System.Threading.Tasks.Task"/> object that represents the asynchronous operation.
/// </returns>
Task UploadTextAsync(string content);
/// <summary>
/// Initiates an asynchronous operation to upload a string of text to a blob. If the blob already exists, it will be overwritten.
///
/// </summary>
/// <param name="content">A string containing the text to upload.</param><param name="cancellationToken">A <see cref="T:System.Threading.CancellationToken"/> to observe while waiting for a task to complete.</param>
/// <returns>
/// A <see cref="T:System.Threading.Tasks.Task"/> object that represents the asynchronous operation.
/// </returns>
Task UploadTextAsync(string content, CancellationToken cancellationToken);
/// <summary>
/// Initiates an asynchronous operation to download the blob's contents as a string.
///
/// </summary>
/// <returns>
/// A <see cref="T:System.Threading.Tasks.Task`1"/> object of type <c>string</c> that represents the asynchronous operation.
/// </returns>
Task<string> DownloadTextAsync();
/// <summary>
/// Initiates an asynchronous operation to download the blob's contents as a string.
///
/// </summary>
/// <param name="cancellationToken">A <see cref="T:System.Threading.CancellationToken"/> to observe while waiting for a task to complete.</param>
/// <returns>
/// A <see cref="T:System.Threading.Tasks.Task`1"/> object of type <c>string</c> that represents the asynchronous operation.
/// </returns>
Task<string> DownloadTextAsync(CancellationToken cancellationToken);
}
} | 34.114865 | 216 | 0.639235 | [
"MIT"
] | ofthetimelords/CloudTools | TheQ.Utilities.CloudTools/Models/ObjectModel/IBlob.cs | 10,100 | C# |
using System;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Threading;
namespace MatterHackers.MatterControl.Launcher
{
public class LauncherApp
{
public LauncherApp()
{
}
[STAThread]
public static void Main(string[] args)
{
// this sets the global culture for the app and all new threads
CultureInfo.DefaultThreadCurrentCulture = CultureInfo.InvariantCulture;
CultureInfo.DefaultThreadCurrentUICulture = CultureInfo.InvariantCulture;
// and make sure the app is set correctly
Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
Thread.CurrentThread.CurrentUICulture = CultureInfo.InvariantCulture;
if (args.Length == 2 && File.Exists(args[0]))
{
ProcessStartInfo runAppLauncherStartInfo = new ProcessStartInfo();
runAppLauncherStartInfo.FileName = args[0];
int timeToWait = 0;
int.TryParse(args[1], out timeToWait);
Stopwatch waitTime = new Stopwatch();
waitTime.Start();
while (waitTime.ElapsedMilliseconds < timeToWait)
{
}
Process.Start(runAppLauncherStartInfo);
}
}
}
} | 25.454545 | 76 | 0.740179 | [
"BSD-2-Clause"
] | Bhalddin/MatterControl | Launcher/Launcher.cs | 1,122 | C# |
using System.Threading.Tasks;
using PuppeteerSharp;
namespace PuppeteerExtraSharp.Plugins.ExtraStealth.Evasions
{
public class LoadTimes : PuppeteerExtraPlugin
{
public LoadTimes() : base("stealth-loadTimes") { }
public override Task OnPageCreated(Page page)
{
var script = Utils.GetScript("LoadTimes.js");
return Utils.EvaluateOnNewPage(page, script);
}
}
}
| 25.294118 | 59 | 0.662791 | [
"MIT"
] | Overmiind/PuppeteerExtraSharp | PuppeteerExtraSharp/Plugins/ExtraStealth/Evasions/LoadTimes.cs | 432 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace Charlotte.Tools
{
/// <summary>
/// thread safe
/// </summary>
public class ThreadCenter : IDisposable
{
public delegate void operation_d();
private object SYNCROOT = new object();
private Thread _th;
private bool _death = false;
private PostQueue<operation_d> _operations = new PostQueue<operation_d>();
private NamedEventPair _evCatnap = new NamedEventPair();
public ThreadCenter()
{
_th = new Thread((ThreadStart)delegate
{
while (_death == false)
{
operation_d operation;
lock (SYNCROOT)
{
operation = _operations.dequeue();
}
if (operation == null)
{
_evCatnap.waitForMillis(2000);
}
else
{
try
{
operation();
}
catch
{ }
}
}
});
_th.Start();
}
public void add(operation_d operation)
{
lock (SYNCROOT)
{
_operations.enqueue(operation);
}
_evCatnap.set();
}
public int getCount()
{
lock (SYNCROOT)
{
return _operations.getCount();
}
}
public void Dispose()
{
if (_th != null)
{
_death = true;
_evCatnap.set();
_th.Join();
_th = null;
_evCatnap.Dispose();
_evCatnap = null;
}
}
}
}
| 15.448276 | 76 | 0.594494 | [
"MIT"
] | stackprobe/CSharp | Module/Module/Tools/ThreadCenter.cs | 1,346 | C# |
using Jagerts.Arie.Standard.Controls;
using Jagerts.Arie.Standard.Mvvm;
using Jagerts.Arie.Windows.Classic.Test.Models;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;
namespace Jagerts.Arie.Windows.Classic.Test.ViewModels
{
class MainViewModel : ViewModel
{
#region Constructor
public MainViewModel()
: base()
{
this.ToggleCommand = new RelayCommand(this.Toggle);
}
#endregion
#region Properties
private int Index { get; set; }
private ColorScheme ColorScheme { get; set; } = ColorSchemes.Default;
public ICommand ToggleCommand { get; private set; }
public ObservableCollection<TestModel> TestModels { get; private set; } = new ObservableCollection<TestModel>()
{
new TestModel() { Name = "Test Model 1" },
new TestModel() { Name = "Test Model 2" },
new TestModel() { Name = "Test Model 3" },
new TestModel() { Name = "Test Model 4" },
};
public ObservableCollection<string> TestItems { get; private set; } = new ObservableCollection<string>()
{
"Item 1",
"Item 2",
"Item 3",
"Item 4",
};
#endregion
#region Methods
public void Toggle()
{
Application app = App.Current;
this.Index = (this.Index + 1) % ColorSchemes.All.Count;
ColorSchemes.All[this.Index].Apply();
}
#endregion
}
}
| 25.969231 | 119 | 0.593602 | [
"MIT"
] | Jagreaper/Project-Arie | Jagerts.Arie.Windows.Classic.Test/Viewmodels/MainViewModel.cs | 1,690 | C# |
using Main;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Utilities;
using Xunit;
namespace Tests.AlgorithmsTests.Observers
{
public class VertexTimeStampObsTests
{
[Theory]
[MemberData(nameof(GetInputFiles))]
public void Test0(string inputFile)
{
string directory = Path.GetDirectoryName(inputFile);
string file = Path.GetFileNameWithoutExtension(inputFile);
var outputFile = @$"{directory}\Observers\VertexDiscoverTimeStamp\{file}";
var expectedfile = @$"{outputFile}.a";
var resultsfile = $"{outputFile}.r";
List<string> inputs = File.ReadAllLines(inputFile).ToList();
inputs = Parser.RemoveComments(inputs);
var nodes = inputs[0].Split(' ').ToList(); // First line is a space delimited list of node names: "1 2 3" or "a b c"
// Remove line of node name
inputs.RemoveAt(0);
List<List<string>> edges = new List<List<string>>();
foreach (var e in inputs)
{
edges.Add(e.Split(' ').ToList()); // Remaining lines are space delimited list of edges (nodeA nodeB tag(optional)): "1 2" or "a b 5"
}
List<string> actual = ObserverHelper.VertexDiscoverTimeStamp(nodes, edges);
File.WriteAllLines(resultsfile, actual);
// Verify results
List<string> expected = File.ReadAllLines(expectedfile).ToList();
Assert.Equal(expected.Count, actual.Count);
for (int i = 0; i < expected.Count; i++)
{
Assert.Equal(expected[i], actual[i]);
}
}
[Theory]
[MemberData(nameof(GetInputFiles))]
public void Test1(string inputFile)
{
string directory = Path.GetDirectoryName(inputFile);
string file = Path.GetFileNameWithoutExtension(inputFile);
var outputFile = @$"{directory}\Observers\VertexFinishTimeStamp\{file}";
var expectedfile = @$"{outputFile}.a";
var resultsfile = $"{outputFile}.r";
List<string> inputs = File.ReadAllLines(inputFile).ToList();
inputs = Parser.RemoveComments(inputs);
var nodes = inputs[0].Split(' ').ToList(); // First line is a space delimited list of node names: "1 2 3" or "a b c"
// Remove line of node name
inputs.RemoveAt(0);
List<List<string>> edges = new List<List<string>>();
foreach (var e in inputs)
{
edges.Add(e.Split(' ').ToList()); // Remaining lines are space delimited list of edges (nodeA nodeB tag(optional)): "1 2" or "a b 5"
}
List<string> actual = ObserverHelper.VertexFinishTimeStamp(nodes, edges);
File.WriteAllLines(resultsfile, actual);
// Verify results
List<string> expected = File.ReadAllLines(expectedfile).ToList();
Assert.Equal(expected.Count, actual.Count);
for (int i = 0; i < expected.Count; i++)
{
Assert.Equal(expected[i], actual[i]);
}
}
public static IEnumerable<object[]> GetInputFiles =>
new List<object[]>
{
new object[] { new string(@"..\..\..\Cases\01") },
new object[] { new string(@"..\..\..\Cases\02") },
new object[] { new string(@"..\..\..\Cases\03") },
new object[] { new string(@"..\..\..\Cases\04") },
};
}
}
| 39.977778 | 149 | 0.558922 | [
"MIT"
] | TXCodeDancer/OpenSource | Demos/QuikGraph/Tests/AlgorithmsTests/Observers/VertexTimeStampObsTests.cs | 3,600 | 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.ServiceBus
{
/// <summary>
/// Single item in List or Get Alias(Disaster Recovery configuration) operation
/// API Version: 2017-04-01.
/// </summary>
[AzureNativeResourceType("azure-native:servicebus:DisasterRecoveryConfig")]
public partial class DisasterRecoveryConfig : Pulumi.CustomResource
{
/// <summary>
/// Primary/Secondary eventhub namespace name, which is part of GEO DR pairing
/// </summary>
[Output("alternateName")]
public Output<string?> AlternateName { get; private set; } = null!;
/// <summary>
/// Resource name
/// </summary>
[Output("name")]
public Output<string> Name { get; private set; } = null!;
/// <summary>
/// ARM Id of the Primary/Secondary eventhub namespace name, which is part of GEO DR pairing
/// </summary>
[Output("partnerNamespace")]
public Output<string?> PartnerNamespace { get; private set; } = null!;
/// <summary>
/// Number of entities pending to be replicated.
/// </summary>
[Output("pendingReplicationOperationsCount")]
public Output<double> PendingReplicationOperationsCount { get; private set; } = null!;
/// <summary>
/// Provisioning state of the Alias(Disaster Recovery configuration) - possible values 'Accepted' or 'Succeeded' or 'Failed'
/// </summary>
[Output("provisioningState")]
public Output<string> ProvisioningState { get; private set; } = null!;
/// <summary>
/// role of namespace in GEO DR - possible values 'Primary' or 'PrimaryNotReplicating' or 'Secondary'
/// </summary>
[Output("role")]
public Output<string> Role { get; private set; } = null!;
/// <summary>
/// Resource type
/// </summary>
[Output("type")]
public Output<string> Type { get; private set; } = null!;
/// <summary>
/// Create a DisasterRecoveryConfig 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 DisasterRecoveryConfig(string name, DisasterRecoveryConfigArgs args, CustomResourceOptions? options = null)
: base("azure-native:servicebus:DisasterRecoveryConfig", name, args ?? new DisasterRecoveryConfigArgs(), MakeResourceOptions(options, ""))
{
}
private DisasterRecoveryConfig(string name, Input<string> id, CustomResourceOptions? options = null)
: base("azure-native:servicebus:DisasterRecoveryConfig", 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:servicebus:DisasterRecoveryConfig"},
new Pulumi.Alias { Type = "azure-native:servicebus/v20170401:DisasterRecoveryConfig"},
new Pulumi.Alias { Type = "azure-nextgen:servicebus/v20170401:DisasterRecoveryConfig"},
new Pulumi.Alias { Type = "azure-native:servicebus/v20180101preview:DisasterRecoveryConfig"},
new Pulumi.Alias { Type = "azure-nextgen:servicebus/v20180101preview:DisasterRecoveryConfig"},
new Pulumi.Alias { Type = "azure-native:servicebus/v20210101preview:DisasterRecoveryConfig"},
new Pulumi.Alias { Type = "azure-nextgen:servicebus/v20210101preview:DisasterRecoveryConfig"},
},
};
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 DisasterRecoveryConfig 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 DisasterRecoveryConfig Get(string name, Input<string> id, CustomResourceOptions? options = null)
{
return new DisasterRecoveryConfig(name, id, options);
}
}
public sealed class DisasterRecoveryConfigArgs : Pulumi.ResourceArgs
{
/// <summary>
/// The Disaster Recovery configuration name
/// </summary>
[Input("alias")]
public Input<string>? Alias { get; set; }
/// <summary>
/// Primary/Secondary eventhub namespace name, which is part of GEO DR pairing
/// </summary>
[Input("alternateName")]
public Input<string>? AlternateName { get; set; }
/// <summary>
/// The namespace name
/// </summary>
[Input("namespaceName", required: true)]
public Input<string> NamespaceName { get; set; } = null!;
/// <summary>
/// ARM Id of the Primary/Secondary eventhub namespace name, which is part of GEO DR pairing
/// </summary>
[Input("partnerNamespace")]
public Input<string>? PartnerNamespace { get; set; }
/// <summary>
/// Name of the Resource group within the Azure subscription.
/// </summary>
[Input("resourceGroupName", required: true)]
public Input<string> ResourceGroupName { get; set; } = null!;
public DisasterRecoveryConfigArgs()
{
}
}
}
| 43.139073 | 150 | 0.618821 | [
"Apache-2.0"
] | sebtelko/pulumi-azure-native | sdk/dotnet/ServiceBus/DisasterRecoveryConfig.cs | 6,514 | 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 redshift-data-2019-12-20.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.RedshiftDataAPIService.Model
{
/// <summary>
/// The SQL statement to run.
/// </summary>
public partial class StatementData
{
private DateTime? _createdAt;
private string _id;
private string _queryString;
private string _secretArn;
private string _statementName;
private StatusString _status;
private DateTime? _updatedAt;
/// <summary>
/// Gets and sets the property CreatedAt.
/// <para>
/// The date and time (UTC) the statement was created.
/// </para>
/// </summary>
public DateTime CreatedAt
{
get { return this._createdAt.GetValueOrDefault(); }
set { this._createdAt = value; }
}
// Check to see if CreatedAt property is set
internal bool IsSetCreatedAt()
{
return this._createdAt.HasValue;
}
/// <summary>
/// Gets and sets the property Id.
/// <para>
/// The SQL statement identifier. This value is a universally unique identifier (UUID)
/// generated by Amazon Redshift Data API.
/// </para>
/// </summary>
[AWSProperty(Required=true)]
public string Id
{
get { return this._id; }
set { this._id = value; }
}
// Check to see if Id property is set
internal bool IsSetId()
{
return this._id != null;
}
/// <summary>
/// Gets and sets the property QueryString.
/// <para>
/// The SQL statement.
/// </para>
/// </summary>
public string QueryString
{
get { return this._queryString; }
set { this._queryString = value; }
}
// Check to see if QueryString property is set
internal bool IsSetQueryString()
{
return this._queryString != null;
}
/// <summary>
/// Gets and sets the property SecretArn.
/// <para>
/// The name or Amazon Resource Name (ARN) of the secret that enables access to the database.
///
/// </para>
/// </summary>
public string SecretArn
{
get { return this._secretArn; }
set { this._secretArn = value; }
}
// Check to see if SecretArn property is set
internal bool IsSetSecretArn()
{
return this._secretArn != null;
}
/// <summary>
/// Gets and sets the property StatementName.
/// <para>
/// The name of the SQL statement.
/// </para>
/// </summary>
[AWSProperty(Min=0, Max=500)]
public string StatementName
{
get { return this._statementName; }
set { this._statementName = value; }
}
// Check to see if StatementName property is set
internal bool IsSetStatementName()
{
return this._statementName != null;
}
/// <summary>
/// Gets and sets the property Status.
/// <para>
/// The status of the SQL statement. An example is the that the SQL statement finished.
///
/// </para>
/// </summary>
public StatusString Status
{
get { return this._status; }
set { this._status = value; }
}
// Check to see if Status property is set
internal bool IsSetStatus()
{
return this._status != null;
}
/// <summary>
/// Gets and sets the property UpdatedAt.
/// <para>
/// The date and time (UTC) that the statement metadata was last updated.
/// </para>
/// </summary>
public DateTime UpdatedAt
{
get { return this._updatedAt.GetValueOrDefault(); }
set { this._updatedAt = value; }
}
// Check to see if UpdatedAt property is set
internal bool IsSetUpdatedAt()
{
return this._updatedAt.HasValue;
}
}
} | 29.647727 | 112 | 0.535646 | [
"Apache-2.0"
] | philasmar/aws-sdk-net | sdk/src/Services/RedshiftDataAPIService/Generated/Model/StatementData.cs | 5,218 | C# |
namespace Orc.Controls.Automation
{
using System.Collections;
using Orc.Automation;
[ActiveAutomationModel]
public class FilterBoxModel : FrameworkElementModel
{
public FilterBoxModel(AutomationElementAccessor accessor)
: base(accessor)
{
}
public string Text { get; set; }
public bool AllowAutoCompletion { get; set; }
public IEnumerable FilterSource { get; set; }
public string PropertyName { get; set; }
public string Watermark { get; set; }
}
}
| 25.181818 | 66 | 0.633574 | [
"MIT"
] | Orcomp/Orc.Controls | src/Orc.Controls/Automation/Controls/FilterBox/Models/FilterBoxModel.cs | 556 | C# |
using System.Xml.Linq;
namespace Cassette.Stylesheets
{
class StylesheetBundleSerializerBase<T> : BundleSerializer<T>
where T : StylesheetBundle
{
protected StylesheetBundleSerializerBase(XContainer container)
: base(container)
{
}
protected override XElement CreateElement()
{
var element = base.CreateElement();
if (Bundle.Condition != null)
{
element.Add(new XAttribute("Condition", Bundle.Condition));
}
return element;
}
}
} | 26.478261 | 76 | 0.555008 | [
"MIT"
] | BluewireTechnologies/cassette | src/Cassette/Stylesheets/StylesheetBundleSerializerBase.cs | 609 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// Generated by the MSBuild WriteCodeFragment class.
// </auto-generated>
//------------------------------------------------------------------------------
using System;
using System.Reflection;
[assembly: Microsoft.AspNetCore.Mvc.ApplicationParts.ProvideApplicationPartFactoryAttribute("Microsoft.AspNetCore.Mvc.ApplicationParts.CompiledRazorAssemblyApplicationPartFac" +
"tory, Microsoft.AspNetCore.Mvc.Razor")]
[assembly: System.Reflection.AssemblyCompanyAttribute("rpsgame")]
[assembly: System.Reflection.AssemblyConfigurationAttribute("Debug")]
[assembly: System.Reflection.AssemblyProductAttribute("rpsgame")]
[assembly: System.Reflection.AssemblyFileVersionAttribute("1.0.0.0")]
[assembly: System.Reflection.AssemblyInformationalVersionAttribute("1.0.0")]
[assembly: System.Reflection.AssemblyTitleAttribute("rpsgame.Views")]
[assembly: System.Reflection.AssemblyVersionAttribute("1.0.0.0")]
| 52.894737 | 177 | 0.688557 | [
"MIT"
] | wallysonlima/rpsgame | Backend/rpsgame/obj/Debug/netcoreapp3.0/rpsgame.RazorTargetAssemblyInfo.cs | 1,005 | C# |
using Lucene.Net.QueryParsers.Flexible.Core.Nodes;
using Lucene.Net.QueryParsers.Flexible.Core.Processors;
using Lucene.Net.QueryParsers.Flexible.Standard.Nodes;
using System.Collections.Generic;
namespace Lucene.Net.QueryParsers.Flexible.Standard.Processors
{
/*
* 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.
*/
/// <summary>
/// This processor removes invalid <see cref="SlopQueryNode"/> objects in the query
/// node tree. A <see cref="SlopQueryNode"/> is invalid if its child is neither a
/// <see cref="TokenizedPhraseQueryNode"/> nor a <see cref="MultiPhraseQueryNode"/>.
/// </summary>
/// <seealso cref="SlopQueryNode"/>
public class PhraseSlopQueryNodeProcessor : QueryNodeProcessor
{
public PhraseSlopQueryNodeProcessor()
{
// empty constructor
}
protected override IQueryNode PostProcessNode(IQueryNode node)
{
if (node is SlopQueryNode)
{
SlopQueryNode phraseSlopNode = (SlopQueryNode)node;
if (!(phraseSlopNode.GetChild() is TokenizedPhraseQueryNode)
&& !(phraseSlopNode.GetChild() is MultiPhraseQueryNode))
{
return phraseSlopNode.GetChild();
}
}
return node;
}
protected override IQueryNode PreProcessNode(IQueryNode node)
{
return node;
}
protected override IList<IQueryNode> SetChildrenOrder(IList<IQueryNode> children)
{
return children;
}
}
}
| 37.969231 | 90 | 0.632901 | [
"Apache-2.0"
] | NikolayXHD/Lucene.Net.Contrib | Lucene.Net.QueryParser/Flexible/Standard/Processors/PhraseSlopQueryNodeProcessor.cs | 2,470 | C# |
namespace MachineLearning.Data
{
/// <summary>
/// Interfaccia per i provider di dati
/// </summary>
public interface IDataStorageProvider
{
#region Properties
/// <summary>
/// Storage di dati
/// </summary>
IDataStorage DataStorage { get; }
#endregion
}
}
| 19.5625 | 41 | 0.587859 | [
"MIT"
] | darth-vader-lg/MachineLearning | src/MachineLearning/Data/IDataStorageProvider.cs | 315 | C# |
#region Copyright
// Copyright 2014 Myrcon Pty. Ltd.
//
// 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
using System;
namespace Potato.Fuzzy.Tokens.Primitive.Temporal.Variable.Months {
public class MarchMonthsVariableTemporalPrimitiveToken : MonthMonthsVariableTemporalPrimitiveToken {
public static Phrase Parse(IFuzzyState state, Phrase phrase) {
return TokenReflection.CreateDescendants<MarchMonthsVariableTemporalPrimitiveToken>(state, phrase);
}
public MarchMonthsVariableTemporalPrimitiveToken() {
this.Pattern = new FuzzyDateTimePattern() {
Rule = TimeType.Definitive,
Year = DateTime.Now.Month <= 3 ? DateTime.Now.Year : DateTime.Now.Year + 1,
Month = 3
};
}
}
} | 41.1875 | 111 | 0.704097 | [
"Apache-2.0"
] | phogue/Potato | src/Potato.Fuzzy/Tokens/Primitive/Temporal/Variable/Months/MarchMonthsVariableTemporalPrimitiveToken.cs | 1,320 | C# |
// Copyright 2016 Esri.
//
// 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 Esri.ArcGISRuntime.Data;
using Esri.ArcGISRuntime.Geometry;
using Esri.ArcGISRuntime.Mapping;
using Esri.ArcGISRuntime.UI.Controls;
using Foundation;
using System;
using UIKit;
namespace ArcGISRuntime.Samples.ServiceFeatureTableCache
{
[Register("ServiceFeatureTableCache")]
[ArcGISRuntime.Samples.Shared.Attributes.Sample(
name: "Service feature table (on interaction cache)",
category: "Data",
description: "Display a feature layer from a service using the **on interaction cache** feature request mode.",
instructions: "Run the sample and pan and zoom around the map. With each interaction, features will be requested and stored in a local cache. Each subsequent interaction will display features from the cache and only request new features from the service.",
tags: new[] { "cache", "feature request mode", "performance" })]
public class ServiceFeatureTableCache : UIViewController
{
// Hold references to UI controls.
private MapView _myMapView;
public ServiceFeatureTableCache()
{
Title = "Service feature table (cache)";
}
private void Initialize()
{
// Create new Map with basemap.
Map myMap = new Map(Basemap.CreateTopographic());
// Create and set initial map area.
Envelope initialLocation = new Envelope(-1.30758164047166E7, 4014771.46954516, -1.30730056797177E7, 4016869.78617381, SpatialReferences.WebMercator);
myMap.InitialViewpoint = new Viewpoint(initialLocation);
// Create URI to the used feature service.
Uri serviceUri = new Uri("https://sampleserver6.arcgisonline.com/arcgis/rest/services/PoolPermits/FeatureServer/0");
// Create feature table for the pools feature service.
ServiceFeatureTable poolsFeatureTable = new ServiceFeatureTable(serviceUri)
{
// Define the request mode.
FeatureRequestMode = FeatureRequestMode.OnInteractionCache
};
// Create FeatureLayer that uses the created table.
FeatureLayer poolsFeatureLayer = new FeatureLayer(poolsFeatureTable);
// Add created layer to the map.
myMap.OperationalLayers.Add(poolsFeatureLayer);
// Assign the map to the MapView.
_myMapView.Map = myMap;
// Feature table initialization.
poolsFeatureTable.RetryLoadAsync();
}
public override void ViewDidLoad()
{
base.ViewDidLoad();
Initialize();
}
public override void LoadView()
{
// Create the views.
View = new UIView() { BackgroundColor = UIColor.White };
_myMapView = new MapView();
_myMapView.TranslatesAutoresizingMaskIntoConstraints = false;
// Add the views.
View.AddSubviews(_myMapView);
// Lay out the views.
NSLayoutConstraint.ActivateConstraints(new[]
{
_myMapView.TopAnchor.ConstraintEqualTo(View.SafeAreaLayoutGuide.TopAnchor),
_myMapView.BottomAnchor.ConstraintEqualTo(View.BottomAnchor),
_myMapView.LeadingAnchor.ConstraintEqualTo(View.LeadingAnchor),
_myMapView.TrailingAnchor.ConstraintEqualTo(View.TrailingAnchor)
});
}
}
} | 41.739583 | 264 | 0.664088 | [
"Apache-2.0"
] | praveensri1265/public | src/iOS/Xamarin.iOS/Samples/Data/ServiceFeatureTableCache/ServiceFeatureTableCache.cs | 4,007 | C# |
using System.ServiceModel;
namespace BleSock.Windows
{
[ServiceContract]
internal interface IWcfPeripheralCallback
{
[OperationContract(IsOneWay = true)]
void OnBluetoothRequire();
[OperationContract(IsOneWay = true)]
void OnReady();
[OperationContract(IsOneWay = true)]
void OnFail();
[OperationContract(IsOneWay = true)]
void OnConnect(int connectionId);
[OperationContract(IsOneWay = true)]
void OnDisconnect(int connectionId);
[OperationContract(IsOneWay = true)]
void OnReceiveDirect(byte[] message, int connectionId);
[OperationContract(IsOneWay = true)]
void OnReceive(byte[] message, int sender);
}
}
| 24.833333 | 63 | 0.648322 | [
"MIT"
] | KzoNag/blesock-unity-plugin | WinBle/WinBleHost/IWcfPeripheralCallback.cs | 747 | C# |
/*
* Decorations - Images, text or other things that can be rendered onto an ObjectListView
*
* Author: Phillip Piper
* Date: 19/08/2009 10:56 PM
*
* Change log:
* v2.4
* 2010-04-15 JPP - Tweaked LightBoxDecoration a little
* v2.3
* 2009-09-23 JPP - Added LeftColumn and RightColumn to RowBorderDecoration
* 2009-08-23 JPP - Added LightBoxDecoration
* 2009-08-19 JPP - Initial version. Separated from Overlays.cs
*
* To do:
*
* Copyright (C) 2009 Phillip Piper
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* If you wish to use this code in a closed source application, please contact phillip_piper@bigfoot.com.
*/
using System;
using System.ComponentModel;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.Windows.Forms;
namespace BrightIdeasSoftware
{
/// <summary>
/// A decoration is an overlay that draws itself in relation to a given row or cell.
/// Decorations scroll when the listview scrolls.
/// </summary>
public interface IDecoration : IOverlay
{
/// <summary>
/// Gets or sets the row that is to be decorated
/// </summary>
OLVListItem ListItem { get; set; }
/// <summary>
/// Gets or sets the subitem that is to be decorated
/// </summary>
OLVListSubItem SubItem { get; set; }
}
/// <summary>
/// An AbstractDecoration is a safe do-nothing implementation of the IDecoration interface
/// </summary>
public class AbstractDecoration : IDecoration
{
#region IDecoration Members
/// <summary>
/// Gets or sets the row that is to be decorated
/// </summary>
public OLVListItem ListItem {
get { return listItem; }
set { listItem = value; }
}
private OLVListItem listItem;
/// <summary>
/// Gets or sets the subitem that is to be decorated
/// </summary>
public OLVListSubItem SubItem {
get { return subItem; }
set { subItem = value; }
}
private OLVListSubItem subItem;
#endregion
#region Public properties
/// <summary>
/// Gets the bounds of the decorations row
/// </summary>
public Rectangle RowBounds {
get {
if (this.ListItem == null)
return Rectangle.Empty;
else
return this.ListItem.Bounds;
}
}
/// <summary>
/// Get the bounds of the decorations cell
/// </summary>
public Rectangle CellBounds {
get {
if (this.ListItem == null || this.SubItem == null)
return Rectangle.Empty;
else
return this.ListItem.GetSubItemBounds(this.ListItem.SubItems.IndexOf(this.SubItem));
}
}
#endregion
#region IOverlay Members
/// <summary>
/// Draw the decoration
/// </summary>
/// <param name="olv"></param>
/// <param name="g"></param>
/// <param name="r"></param>
public virtual void Draw(ObjectListView olv, Graphics g, Rectangle r) {
}
#endregion
}
/// <summary>
/// This decoration draws a slight tint over a column of the
/// owning listview. If no column is explicitly set, the selected
/// column in the listview will be used.
/// The selected column is normally the sort column, but does not have to be.
/// </summary>
public class TintedColumnDecoration : AbstractDecoration
{
#region Constructors
/// <summary>
/// Create a TintedColumnDecoration
/// </summary>
public TintedColumnDecoration() {
this.Tint = Color.FromArgb(15, Color.Blue);
}
/// <summary>
/// Create a TintedColumnDecoration
/// </summary>
/// <param name="column"></param>
public TintedColumnDecoration(OLVColumn column)
: this() {
this.ColumnToTint = column;
}
#endregion
#region Properties
/// <summary>
/// Gets or sets the column that will be tinted
/// </summary>
public OLVColumn ColumnToTint {
get { return this.columnToTint; }
set { this.columnToTint = value; }
}
private OLVColumn columnToTint;
/// <summary>
/// Gets or sets the color that will be 'tinted' over the selected column
/// </summary>
public Color Tint {
get { return this.tint; }
set {
if (this.tint == value)
return;
if (this.tintBrush != null) {
this.tintBrush.Dispose();
this.tintBrush = null;
}
this.tint = value;
this.tintBrush = new SolidBrush(this.tint);
}
}
private Color tint;
private SolidBrush tintBrush;
#endregion
#region IOverlay Members
/// <summary>
/// Draw a slight colouring over our tinted column
/// </summary>
/// <remarks>
/// This overlay only works when:
/// - the list is in Details view
/// - there is at least one row
/// - there is a selected column (or a specified tint column)
/// </remarks>
/// <param name="olv"></param>
/// <param name="g"></param>
/// <param name="r"></param>
public override void Draw(ObjectListView olv, Graphics g, Rectangle r) {
if (olv.View != System.Windows.Forms.View.Details)
return;
if (olv.GetItemCount() == 0)
return;
OLVColumn column = this.ColumnToTint ?? olv.SelectedColumn;
if (column == null)
return;
Point sides = NativeMethods.GetScrolledColumnSides(olv, column.Index);
if (sides.X == -1)
return;
Rectangle columnBounds = new Rectangle(sides.X, r.Top, sides.Y - sides.X, r.Bottom);
// Find the bottom of the last item. The tinting should extend only to there.
OLVListItem lastItem = olv.GetLastItemInDisplayOrder();
if (lastItem != null) {
Rectangle lastItemBounds = lastItem.Bounds;
if (!lastItemBounds.IsEmpty && lastItemBounds.Bottom < columnBounds.Bottom)
columnBounds.Height = lastItemBounds.Bottom - columnBounds.Top;
}
g.FillRectangle(this.tintBrush, columnBounds);
}
#endregion
}
/// <summary>
/// This decoration draws an optionally filled border around a rectangle.
/// Subclasses must override CalculateBounds().
/// </summary>
public class BorderDecoration : AbstractDecoration
{
#region Constructors
/// <summary>
/// Create a BorderDecoration
/// </summary>
public BorderDecoration()
: this(new Pen(Color.FromArgb(64, Color.Blue), 1)) {
}
/// <summary>
/// Create a BorderDecoration
/// </summary>
/// <param name="borderPen">The pen used to draw the border</param>
public BorderDecoration(Pen borderPen) {
this.BorderPen = borderPen;
}
/// <summary>
/// Create a BorderDecoration
/// </summary>
/// <param name="borderPen">The pen used to draw the border</param>
/// <param name="fill">The brush used to fill the rectangle</param>
public BorderDecoration(Pen borderPen, Brush fill) {
this.BorderPen = borderPen;
this.FillBrush = fill;
}
#endregion
#region Properties
/// <summary>
/// Gets or sets the pen that will be used to draw the border
/// </summary>
public Pen BorderPen {
get { return this.borderPen; }
set { this.borderPen = value; }
}
private Pen borderPen;
/// <summary>
/// Gets or sets the padding that will be added to the bounds of the item
/// before drawing the border and fill.
/// </summary>
public Size BoundsPadding {
get { return this.boundsPadding; }
set { this.boundsPadding = value; }
}
private Size boundsPadding = new Size(-1, 2);
/// <summary>
/// How rounded should the corners of the border be? 0 means no rounding.
/// </summary>
/// <remarks>If this value is too large, the edges of the border will appear odd.</remarks>
public float CornerRounding {
get { return this.cornerRounding; }
set { this.cornerRounding = value; }
}
private float cornerRounding = 16.0f;
/// <summary>
/// Gets or sets the brush that will be used to fill the border
/// </summary>
public Brush FillBrush {
get { return this.fillBrush; }
set { this.fillBrush = value; }
}
private Brush fillBrush = new SolidBrush(Color.FromArgb(64, Color.Blue));
#endregion
#region IOverlay Members
/// <summary>
/// Draw a filled border
/// </summary>
/// <param name="olv"></param>
/// <param name="g"></param>
/// <param name="r"></param>
public override void Draw(ObjectListView olv, Graphics g, Rectangle r) {
Rectangle bounds = this.CalculateBounds();
if (!bounds.IsEmpty)
this.DrawFilledBorder(g, bounds);
}
#endregion
#region Subclass responsibility
/// <summary>
/// Subclasses should override this to say where the border should be drawn
/// </summary>
/// <returns></returns>
protected virtual Rectangle CalculateBounds() {
return Rectangle.Empty;
}
#endregion
#region Implementation utlities
/// <summary>
/// Do the actual work of drawing the filled border
/// </summary>
/// <param name="g"></param>
/// <param name="bounds"></param>
protected void DrawFilledBorder(Graphics g, Rectangle bounds) {
bounds.Inflate(this.BoundsPadding);
GraphicsPath path = this.GetRoundedRect(bounds, this.CornerRounding);
if (this.FillBrush != null)
g.FillPath(this.FillBrush, path);
if (this.BorderPen != null)
g.DrawPath(this.BorderPen, path);
}
/// <summary>
/// Create a GraphicsPath that represents a round cornered rectangle.
/// </summary>
/// <param name="rect"></param>
/// <param name="diameter">If this is 0 or less, the rectangle will not be rounded.</param>
/// <returns></returns>
protected GraphicsPath GetRoundedRect(RectangleF rect, float diameter) {
GraphicsPath path = new GraphicsPath();
if (diameter <= 0.0f) {
path.AddRectangle(rect);
} else {
RectangleF arc = new RectangleF(rect.X, rect.Y, diameter, diameter);
path.AddArc(arc, 180, 90);
arc.X = rect.Right - diameter;
path.AddArc(arc, 270, 90);
arc.Y = rect.Bottom - diameter;
path.AddArc(arc, 0, 90);
arc.X = rect.Left;
path.AddArc(arc, 90, 90);
path.CloseFigure();
}
return path;
}
#endregion
}
/// <summary>
/// Instances of this class draw a border around the decorated row
/// </summary>
public class RowBorderDecoration : BorderDecoration
{
/// <summary>
/// Gets or sets the index of the left most column to be used for the border
/// </summary>
public int LeftColumn {
get { return leftColumn; }
set { leftColumn = value; }
}
private int leftColumn = -1;
/// <summary>
/// Gets or sets the index of the right most column to be used for the border
/// </summary>
public int RightColumn {
get { return rightColumn; }
set { rightColumn = value; }
}
private int rightColumn = -1;
/// <summary>
/// Calculate the boundaries of the border
/// </summary>
/// <returns></returns>
protected override Rectangle CalculateBounds() {
Rectangle bounds = this.RowBounds;
if (this.ListItem == null)
return bounds;
if (this.LeftColumn >= 0) {
Rectangle leftCellBounds = this.ListItem.GetSubItemBounds(this.LeftColumn);
if (!leftCellBounds.IsEmpty) {
bounds.Width = bounds.Right - leftCellBounds.Left;
bounds.X = leftCellBounds.Left;
}
}
if (this.RightColumn >= 0) {
Rectangle rightCellBounds = this.ListItem.GetSubItemBounds(this.RightColumn);
if (!rightCellBounds.IsEmpty) {
bounds.Width = rightCellBounds.Right - bounds.Left;
}
}
return bounds;
}
}
/// <summary>
/// Instances of this class draw a border around the decorated subitem.
/// </summary>
public class CellBorderDecoration : BorderDecoration
{
/// <summary>
/// Calculate the boundaries of the border
/// </summary>
/// <returns></returns>
protected override Rectangle CalculateBounds() {
return this.CellBounds;
}
}
/// <summary>
/// This decoration puts a border around the cell being edited and
/// optionally "lightboxes" the cell (makes the rest of the control dark).
/// </summary>
public class EditingCellBorderDecoration : BorderDecoration
{
#region Life and death
/// <summary>
/// Create a EditingCellBorderDecoration
/// </summary>
public EditingCellBorderDecoration() {
this.FillBrush = null;
this.BorderPen = new Pen(Color.DarkBlue, 2);
this.CornerRounding = 8;
this.BoundsPadding = new Size(10, 8);
}
#endregion
#region Configuration properties
/// <summary>
/// Gets or set whether the decoration should make the rest of
/// the control dark when a cell is being edited
/// </summary>
/// <remarks>If this is true, FillBrush is used to overpaint
/// the control.</remarks>
public bool UseLightbox {
get { return this.useLightbox; }
set {
if (this.useLightbox == value)
return;
this.useLightbox = value;
if (this.useLightbox) {
if (this.FillBrush == null)
this.FillBrush = new SolidBrush(Color.FromArgb(64, Color.Black));
}
}
}
private bool useLightbox;
#endregion
#region Implementation
/// <summary>
/// Draw the decoration
/// </summary>
/// <param name="olv"></param>
/// <param name="g"></param>
/// <param name="r"></param>
public override void Draw(ObjectListView olv, Graphics g, Rectangle r) {
if (!olv.IsCellEditing)
return;
Rectangle bounds = olv.CellEditor.Bounds;
if (bounds.IsEmpty)
return;
bounds.Inflate(this.BoundsPadding);
GraphicsPath path = this.GetRoundedRect(bounds, this.CornerRounding);
if (this.FillBrush != null) {
if (this.UseLightbox) {
using (Region newClip = new Region(r)) {
newClip.Exclude(path);
Region originalClip = g.Clip;
g.Clip = newClip;
g.FillRectangle(this.FillBrush, r);
g.Clip = originalClip;
}
} else {
g.FillPath(this.FillBrush, path);
}
}
if (this.BorderPen != null)
g.DrawPath(this.BorderPen, path);
}
#endregion
}
/// <summary>
/// This decoration causes everything *except* the row under the mouse to be overpainted
/// with a tint, making the row under the mouse stand out in comparison.
/// The darker and more opaque the fill color, the more obvious the
/// decorated row becomes.
/// </summary>
public class LightBoxDecoration : BorderDecoration
{
/// <summary>
/// Create a LightBoxDecoration
/// </summary>
public LightBoxDecoration() {
this.BoundsPadding = new Size(-1, 4);
this.CornerRounding = 8.0f;
this.FillBrush = new SolidBrush(Color.FromArgb(72, Color.Black));
}
/// <summary>
/// Draw a tint over everything in the ObjectListView except the
/// row under the mouse.
/// </summary>
/// <param name="olv"></param>
/// <param name="g"></param>
/// <param name="r"></param>
public override void Draw(ObjectListView olv, Graphics g, Rectangle r) {
if (!r.Contains(olv.PointToClient(Cursor.Position)))
return;
Rectangle bounds = this.RowBounds;
if (bounds.IsEmpty) {
if (olv.View == View.Tile)
g.FillRectangle(this.FillBrush, r);
return;
}
using (Region newClip = new Region(r)) {
bounds.Inflate(this.BoundsPadding);
newClip.Exclude(this.GetRoundedRect(bounds, this.CornerRounding));
Region originalClip = g.Clip;
g.Clip = newClip;
g.FillRectangle(this.FillBrush, r);
g.Clip = originalClip;
}
}
}
/// <summary>
/// Instances of this class put an Image over the row/cell that it is decorating
/// </summary>
public class ImageDecoration : ImageAdornment, IDecoration
{
#region Constructors
/// <summary>
/// Create an image decoration
/// </summary>
public ImageDecoration() {
this.Alignment = ContentAlignment.MiddleRight;
}
/// <summary>
/// Create an image decoration
/// </summary>
/// <param name="image"></param>
public ImageDecoration(Image image)
: this() {
this.Image = image;
}
/// <summary>
/// Create an image decoration
/// </summary>
/// <param name="image"></param>
/// <param name="transparency"></param>
public ImageDecoration(Image image, int transparency)
: this() {
this.Image = image;
this.Transparency = transparency;
}
/// <summary>
/// Create an image decoration
/// </summary>
/// <param name="image"></param>
/// <param name="alignment"></param>
public ImageDecoration(Image image, ContentAlignment alignment)
: this() {
this.Image = image;
this.Alignment = alignment;
}
/// <summary>
/// Create an image decoration
/// </summary>
/// <param name="image"></param>
/// <param name="transparency"></param>
/// <param name="alignment"></param>
public ImageDecoration(Image image, int transparency, ContentAlignment alignment)
: this() {
this.Image = image;
this.Transparency = transparency;
this.Alignment = alignment;
}
#endregion
#region IDecoration Members
/// <summary>
/// Gets or sets the item being decorated
/// </summary>
public OLVListItem ListItem {
get { return listItem; }
set { listItem = value; }
}
private OLVListItem listItem;
/// <summary>
/// Gets or sets the sub item being decorated
/// </summary>
public OLVListSubItem SubItem {
get { return subItem; }
set { subItem = value; }
}
private OLVListSubItem subItem;
#endregion
#region Commands
/// <summary>
/// Draw this decoration
/// </summary>
/// <param name="olv">The ObjectListView being decorated</param>
/// <param name="g">The Graphics used for drawing</param>
/// <param name="r">The bounds of the rendering</param>
public virtual void Draw(ObjectListView olv, Graphics g, Rectangle r) {
this.DrawImage(g, this.CalculateItemBounds(this.ListItem, this.SubItem));
}
#endregion
}
/// <summary>
/// Instances of this class draw some text over the row/cell that they are decorating
/// </summary>
public class TextDecoration : TextAdornment, IDecoration
{
#region Constructors
/// <summary>
/// Create a TextDecoration
/// </summary>
public TextDecoration() {
this.Alignment = ContentAlignment.MiddleRight;
}
/// <summary>
/// Create a TextDecoration
/// </summary>
/// <param name="text"></param>
public TextDecoration(string text)
: this() {
this.Text = text;
}
/// <summary>
/// Create a TextDecoration
/// </summary>
/// <param name="text"></param>
/// <param name="transparency"></param>
public TextDecoration(string text, int transparency)
: this() {
this.Text = text;
this.Transparency = transparency;
}
/// <summary>
/// Create a TextDecoration
/// </summary>
/// <param name="text"></param>
/// <param name="alignment"></param>
public TextDecoration(string text, ContentAlignment alignment)
: this() {
this.Text = text;
this.Alignment = alignment;
}
/// <summary>
/// Create a TextDecoration
/// </summary>
/// <param name="text"></param>
/// <param name="transparency"></param>
/// <param name="alignment"></param>
public TextDecoration(string text, int transparency, ContentAlignment alignment)
: this() {
this.Text = text;
this.Transparency = transparency;
this.Alignment = alignment;
}
#endregion
#region IDecoration Members
/// <summary>
/// Gets or sets the item being decorated
/// </summary>
public OLVListItem ListItem {
get { return listItem; }
set { listItem = value; }
}
private OLVListItem listItem;
/// <summary>
/// Gets or sets the sub item being decorated
/// </summary>
public OLVListSubItem SubItem {
get { return subItem; }
set { subItem = value; }
}
private OLVListSubItem subItem;
#endregion
#region Commands
/// <summary>
/// Draw this decoration
/// </summary>
/// <param name="olv">The ObjectListView being decorated</param>
/// <param name="g">The Graphics used for drawing</param>
/// <param name="r">The bounds of the rendering</param>
public virtual void Draw(ObjectListView olv, Graphics g, Rectangle r) {
this.DrawText(g, this.CalculateItemBounds(this.ListItem, this.SubItem));
}
#endregion
}
}
| 31.856959 | 105 | 0.541766 | [
"MIT"
] | dbgate/datadmin | ObjectListView/Decorations.cs | 24,723 | 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>
//------------------------------------------------------------------------------
//
// This source code was auto-generated by xsd, Version=4.6.1055.0.
//
namespace DbKeeperNet.Extensions.MsSqlMembershipAndRolesSetup {
using System.Xml.Serialization;
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.6.1055.0")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(Namespace="http://code.google.com/p/dbkeepernet/MsSqlMembershipAndRolesSetup-1.0.xsd")]
public partial class MsSqlMembershipAndRolesSetupType : UpdateStepBaseType {
}
}
| 39.074074 | 134 | 0.614218 | [
"BSD-3-Clause"
] | DbKeeperNet/DbKeeperNet | DbKeeperNet.Extensions.MsSqlMembershipAndRolesSetup/XmlClasses.cs | 1,057 | C# |
/*
* OpenAPI Petstore
*
* This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\
*
* OpenAPI spec version: 1.0.0
*
* Generated by: https://github.com/openapitools/openapi-generator.git
*/
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System.ComponentModel.DataAnnotations;
using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter;
using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils;
namespace Org.OpenAPITools.Model
{
/// <summary>
/// Category
/// </summary>
[DataContract]
public partial class Category : IEquatable<Category>, IValidatableObject
{
/// <summary>
/// Initializes a new instance of the <see cref="Category" /> class.
/// </summary>
[JsonConstructorAttribute]
protected Category() { }
/// <summary>
/// Initializes a new instance of the <see cref="Category" /> class.
/// </summary>
/// <param name="id">id.</param>
/// <param name="name">name (required) (default to "default-name").</param>
public Category(long? id = default(long?), string name = "default-name")
{
// to ensure "name" is required (not null)
if (name == null)
{
throw new InvalidDataException("name is a required property for Category and cannot be null");
}
else
{
this.Name = name;
}
this.Id = id;
}
/// <summary>
/// Gets or Sets Id
/// </summary>
[DataMember(Name="id", EmitDefaultValue=false)]
public long? Id { get; set; }
/// <summary>
/// Gets or Sets Name
/// </summary>
[DataMember(Name="name", EmitDefaultValue=false)]
public string Name { 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 Category {\n");
sb.Append(" Id: ").Append(Id).Append("\n");
sb.Append(" Name: ").Append(Name).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 virtual 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 OpenAPIClientUtils.compareLogic.Compare(this, input as Category).AreEqual;
}
/// <summary>
/// Returns true if Category instances are equal
/// </summary>
/// <param name="input">Instance of Category to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(Category input)
{
return OpenAPIClientUtils.compareLogic.Compare(this, input).AreEqual;
}
/// <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.Id != null)
hashCode = hashCode * 59 + this.Id.GetHashCode();
if (this.Name != null)
hashCode = hashCode * 59 + this.Name.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;
}
}
}
| 32.888112 | 159 | 0.572826 | [
"Apache-2.0"
] | ccozzolino/openapi-generator | samples/client/petstore/csharp-refactor/OpenAPIClient/src/Org.OpenAPITools/Model/Category.cs | 4,703 | C# |
using System;
using Expanse.Utilities;
using UnityEngine;
namespace Expanse.Extensions
{
/// <summary>
/// A collection of Transform related extension methods.
/// </summary>
public static class TransformExt
{
/// <summary>
/// Destroys all game objects parented to a transform.
/// </summary>
/// <param name="source">Source Transform component.</param>
/// <param name="immediate">If true DestroyImmediate() is used instead of Destroy().</param>
public static void DestroyAllChildren(this Transform source, bool immediate = false)
{
if (source == null)
throw new ArgumentNullException("source");
for (int i = source.childCount - 1; i >= 0; i--)
{
if (immediate)
UnityEngine.Object.DestroyImmediate(source.GetChild(i).gameObject);
else
UnityEngine.Object.Destroy(source.GetChild(i).gameObject);
}
}
/// <summary>
/// Detaches all game objects parented to a transform.
/// </summary>
/// <param name="source">Source Transform component.</param>
/// <param name="newParent">Transform component of the new parent.</param>
/// <param name="worldPositionStays">If true the world position of the children will not change.</param>
public static void DetachAllChildren(this Transform source, Transform newParent = null, bool worldPositionStays = true)
{
if (source == null)
throw new ArgumentNullException("source");
if (newParent == null)
throw new ArgumentNullException("newParent");
for (int i = source.childCount - 1; i >= 0; i--)
{
source.GetChild(i).SetParent(newParent, worldPositionStays);
}
}
/// <summary>
/// Resets the position, rotation and scale to default values.
/// </summary>
/// <param name="source">Source Transform component.</param>
public static void Reset(this Transform source)
{
if (source == null)
throw new ArgumentNullException("source");
source.localPosition = Vector3.zero;
source.localRotation = Quaternion.identity;
source.localScale = Vector3.one;
}
/// <summary>
/// Performs a breadth-first search to find a deep child transform with name.
/// </summary>
/// <param name="parent">Root parent to search under.</param>
/// <param name="name">Name of the child game object to find.</param>
/// <returns>Returns the transform of the child game object with name.</returns>
public static Transform FindDeepChildByBreadth(this Transform parent, string name)
{
return TransformUtil.FindDeepChildByBreadth(parent, name);
}
/// <summary>
/// Performs a depth-first search to find a deep child transform with name.
/// </summary>
/// <param name="parent">Root parent to search under.</param>
/// <param name="name">Name of the child game object to find.</param>
/// <returns>Returns the transform of the child game object with name.</returns>
public static Transform FindDeepChildByDepth(this Transform parent, string name)
{
return TransformUtil.FindDeepChildByDepth(parent, name);
}
/// <summary>
/// Sets the position and rotation to that of another transform.
/// </summary>
/// <param name="source">Source Transform component to apply values to..</param>
/// <param name="other">Other transform component to copy the values from.</param>
/// <param name="copyParent">If true the parent of other is also applied to the source transform.</param>
public static void CopyFrom(this Transform source, Transform other, bool copyParent)
{
if (source == null)
throw new ArgumentNullException("transform");
if (other == null)
throw new ArgumentNullException("other");
if (copyParent)
source.SetParent(other.parent, true);
source.SetPositionAndRotation(other.position, other.rotation);
}
#region Position
/// <summary>
/// Sets the X position of a transform.
/// </summary>
/// <param name="transform">Source Transform component.</param>
/// <param name="value">X position value to set.</param>
public static void SetPosX(this Transform transform, float value)
{
Vector3 position = transform.position;
position.x = value;
transform.position = position;
}
/// <summary>
/// Adds to the X position of a transform.
/// </summary>
/// <param name="transform">Source Transform component.</param>
/// <param name="value">X position value to add.</param>
public static float AddPosX(this Transform transform, float value)
{
Vector3 position = transform.position;
position.x += value;
transform.position = position;
return position.x;
}
/// <summary>
/// Gets the X position of a transform.
/// </summary>
/// <param name="transform">Source Transform component.</param>
/// <returns>Returns the X position value.</returns>
public static float GetPosX(this Transform transform)
{
return transform.position.x;
}
/// <summary>
/// Sets the Y position of a transform.
/// </summary>
/// <param name="transform">Source Transform component.</param>
/// <param name="value">Y position value to set.</param>
public static void SetPosY(this Transform transform, float value)
{
Vector3 position = transform.position;
position.y = value;
transform.position = position;
}
/// <summary>
/// Adds to the Y position of a transform.
/// </summary>
/// <param name="transform">Source Transform component.</param>
/// <param name="value">Y position value to add.</param>
public static float AddPosY(this Transform transform, float value)
{
Vector3 position = transform.position;
position.y += value;
transform.position = position;
return position.y;
}
/// <summary>
/// Gets the Y position of a transform.
/// </summary>
/// <param name="transform">Source Transform component.</param>
/// <returns>Returns the Y position value.</returns>
public static float GetPosY(this Transform transform)
{
return transform.position.y;
}
/// <summary>
/// Sets the Z position of a transform.
/// </summary>
/// <param name="transform">Source Transform component.</param>
/// <param name="value">Z position value to set.</param>
public static void SetPosZ(this Transform transform, float value)
{
Vector3 position = transform.position;
position.z = value;
transform.position = position;
}
/// <summary>
/// Adds to the Z position of a transform.
/// </summary>
/// <param name="transform">Source Transform component.</param>
/// <param name="value">Z positon value to add.</param>
public static float AddPosZ(this Transform transform, float value)
{
Vector3 position = transform.position;
position.z += value;
transform.position = position;
return position.z;
}
/// <summary>
/// Gets the Z position of a transform.
/// </summary>
/// <param name="transform">Source Transform component.</param>
/// <returns>Returns the Z position value.</returns>
public static float GetPosZ(this Transform transform)
{
return transform.position.z;
}
#endregion
#region LocalPosition
/// <summary>
/// Sets the local X position of a transform.
/// </summary>
/// <param name="transform">Source Transform component.</param>
/// <param name="value">X local position value to set.</param>
public static void SetLocalPosX(this Transform transform, float value)
{
Vector3 localPosition = transform.localPosition;
localPosition.x = value;
transform.localPosition = localPosition;
}
/// <summary>
/// Adds to the local X position of a transform.
/// </summary>
/// <param name="transform">Source Transform component.</param>
/// <param name="value">X local position value to add.</param>
public static float AddLocalPosX(this Transform transform, float value)
{
Vector3 localPosition = transform.localPosition;
localPosition.x += value;
transform.localPosition = localPosition;
return localPosition.x;
}
/// <summary>
/// Gets the local X position of a transform.
/// </summary>
/// <param name="transform">Source Transform component.</param>
/// <returns>Returns the X local position value.</returns>
public static float GetLocalPosX(this Transform transform)
{
return transform.localPosition.x;
}
/// <summary>
/// Sets the local Y position of a transform.
/// </summary>
/// <param name="transform">Source Transform component.</param>
/// <param name="value">Y local position value to set.</param>
public static void SetLocalPosY(this Transform transform, float value)
{
Vector3 localPosition = transform.localPosition;
localPosition.y = value;
transform.localPosition = localPosition;
}
/// <summary>
/// Adds to the local Y position of a transform.
/// </summary>
/// <param name="transform">Source Transform component.</param>
/// <param name="value">Y local position value to add.</param>
public static float AddLocalPosY(this Transform transform, float value)
{
Vector3 localPosition = transform.localPosition;
localPosition.y += value;
transform.localPosition = localPosition;
return localPosition.y;
}
/// <summary>
/// Gets the local Y position of a transform.
/// </summary>
/// <param name="transform">Source Transform component.</param>
/// <returns>Returns the Y local position value.</returns>
public static float GetLocalPosY(this Transform transform)
{
return transform.localPosition.y;
}
/// <summary>
/// Sets the local Z position of a transform.
/// </summary>
/// <param name="transform">Source Transform component.</param>
/// <param name="value">Z local position value to set.</param>
public static void SetLocalPosZ(this Transform transform, float value)
{
Vector3 localPosition = transform.localPosition;
localPosition.z = value;
transform.localPosition = localPosition;
}
/// <summary>
/// Adds to the local Z position of a transform.
/// </summary>
/// <param name="transform">Source Transform component.</param>
/// <param name="value">Z local position value to add.</param>
public static float AddLocalPosZ(this Transform transform, float value)
{
Vector3 localPosition = transform.localPosition;
localPosition.z += value;
transform.localPosition = localPosition;
return localPosition.z;
}
/// <summary>
/// Gets the local Z position of a transform.
/// </summary>
/// <param name="transform">Source Transform component.</param>
/// <returns>Returns the Z local position value.</returns>
public static float GetLocalPosZ(this Transform transform)
{
return transform.localPosition.z;
}
#endregion
#region EulerAngles
/// <summary>
/// Sets the X Euler Angle of a transform.
/// </summary>
/// <param name="transform">Source Transform component.</param>
/// <param name="value">X euler value to set.</param>
public static void SetEulerX(this Transform transform, float value)
{
Vector3 eulerAngles = transform.eulerAngles;
eulerAngles.x = value;
transform.eulerAngles = eulerAngles;
}
/// <summary>
/// Adds to the X Euler Angle of a transform.
/// </summary>
/// <param name="transform">Source Transform component.</param>
/// <param name="value">X euler value to add.</param>
public static float AddEulerX(this Transform transform, float value)
{
Vector3 eulerAngles = transform.eulerAngles;
eulerAngles.x += value;
transform.eulerAngles = eulerAngles;
return eulerAngles.x;
}
/// <summary>
/// Gets the X Euler Angle of a transform.
/// </summary>
/// <param name="transform">Source Transform component.</param>
/// <returns>Returns the X euler value.</returns>
public static float GetEulerX(this Transform transform)
{
return transform.eulerAngles.x;
}
/// <summary>
/// Sets the Y Euler Angle of a transform.
/// </summary>
/// <param name="transform">Source Transform component.</param>
/// <param name="value">Y euler value to set.</param>
public static void SetEulerY(this Transform transform, float value)
{
Vector3 eulerAngles = transform.eulerAngles;
eulerAngles.y = value;
transform.eulerAngles = eulerAngles;
}
/// <summary>
/// Adds to the Y Euler Angle of a transform.
/// </summary>
/// <param name="transform">Source Transform component.</param>
/// <param name="value">Y euler value to add.</param>
public static float AddEulerY(this Transform transform, float value)
{
Vector3 eulerAngles = transform.eulerAngles;
eulerAngles.y += value;
transform.eulerAngles = eulerAngles;
return eulerAngles.y;
}
/// <summary>
/// Gets the Y Euler Angle of a transform.
/// </summary>
/// <param name="transform">Source Transform component.</param>
/// <returns>Returns the Y euler value.</returns>
public static float GetEulerY(this Transform transform)
{
return transform.eulerAngles.y;
}
/// <summary>
/// Sets the Z Euler Angle of a transform.
/// </summary>
/// <param name="transform">Source Transform component.</param>
/// <param name="value">Z euler value to set.</param>
public static void SetEulerZ(this Transform transform, float value)
{
Vector3 eulerAngles = transform.eulerAngles;
eulerAngles.z = value;
transform.eulerAngles = eulerAngles;
}
/// <summary>
/// Adds to the Z Euler Angle of a transform.
/// </summary>
/// <param name="transform">Source Transform component.</param>
/// <param name="value">Z euler value to add.</param>
public static float AddEulerZ(this Transform transform, float value)
{
Vector3 eulerAngles = transform.eulerAngles;
eulerAngles.z += value;
transform.eulerAngles = eulerAngles;
return eulerAngles.z;
}
/// <summary>
/// Gets the Z Euler Angle of a transform.
/// </summary>
/// <param name="transform">Source Transform component.</param>
/// <returns>Returns the Z euler value.</returns>
public static float GetEulerZ(this Transform transform)
{
return transform.eulerAngles.z;
}
#endregion
#region LocalEulerAngles
/// <summary>
/// Sets the local X Euler Angle of a transform.
/// </summary>
/// <param name="transform">Source Transform component.</param>
/// <param name="value">X local euler value to set.</param>
public static void SetLocalEulerX(this Transform transform, float value)
{
Vector3 localEulerAngles = transform.localEulerAngles;
localEulerAngles.x = value;
transform.localEulerAngles = localEulerAngles;
}
/// <summary>
/// Adds to the local X Euler Angle of a transform.
/// </summary>
/// <param name="transform">Source Transform component.</param>
/// <param name="value">X local euler value to add.</param>
public static float AddLocalEulerX(this Transform transform, float value)
{
Vector3 localEulerAngles = transform.localEulerAngles;
localEulerAngles.x += value;
transform.localEulerAngles = localEulerAngles;
return localEulerAngles.x;
}
/// <summary>
/// Gets the local X Euler Angle of a transform.
/// </summary>
/// <param name="transform">Source Transform component.</param>
/// <returns>Returns the X local euler value.</returns>
public static float GetLocalEulerX(this Transform transform)
{
return transform.localEulerAngles.x;
}
/// <summary>
/// Sets the local Y Euler Angle of a transform.
/// </summary>
/// <param name="transform">Source Transform component.</param>
/// <param name="value">Y local euler value to set.</param>
public static void SetLocalEulerY(this Transform transform, float value)
{
Vector3 localEulerAngles = transform.localEulerAngles;
localEulerAngles.y = value;
transform.localEulerAngles = localEulerAngles;
}
/// <summary>
/// Adds to the local Y Euler Angle of a transform.
/// </summary>
/// <param name="transform">Source Transform component.</param>
/// <param name="value">Y local euler value to add.</param>
public static float AddLocalEulerY(this Transform transform, float value)
{
Vector3 localEulerAngles = transform.localEulerAngles;
localEulerAngles.y += value;
transform.localEulerAngles = localEulerAngles;
return localEulerAngles.y;
}
/// <summary>
/// Gets the local Y Euler Angle of a transform.
/// </summary>
/// <param name="transform">Source Transform component.</param>
/// <returns>Returns the Y local euler value.</returns>
public static float GetLocalEulerY(this Transform transform)
{
return transform.localEulerAngles.y;
}
/// <summary>
/// Sets the local Z Euler Angle of a transform.
/// </summary>
/// <param name="transform">Source Transform component.</param>
/// <param name="value">Z local euler value to set.</param>
public static void SetLocalEulerZ(this Transform transform, float value)
{
Vector3 localEulerAngles = transform.localEulerAngles;
localEulerAngles.z = value;
transform.localEulerAngles = localEulerAngles;
}
/// <summary>
/// Adds to the local Z Euler Angle of a transform.
/// </summary>
/// <param name="transform">Source Transform component.</param>
/// <param name="value">Z local euler value to add.</param>
public static float AddLocalEulerZ(this Transform transform, float value)
{
Vector3 localEulerAngles = transform.localEulerAngles;
localEulerAngles.z += value;
transform.localEulerAngles = localEulerAngles;
return localEulerAngles.z;
}
/// <summary>
/// Gets the local Z Euler Angle of a transform.
/// </summary>
/// <param name="transform">Source Transform component.</param>
/// <returns>Returns the Z local euler value.</returns>
public static float GetLocalEulerZ(this Transform transform)
{
return transform.localEulerAngles.z;
}
#endregion
#region LocalScale
/// <summary>
/// Sets the local X scale of a transform.
/// </summary>
/// <param name="transform">Source Transform component.</param>
/// <param name="value">X local scale value to set.</param>
public static void SetLocalScaleX(this Transform transform, float value)
{
Vector3 localScale = transform.localScale;
localScale.x = value;
transform.localScale = localScale;
}
/// <summary>
/// Adds to the local X scale of a transform.
/// </summary>
/// <param name="transform">Source Transform component.</param>
/// <param name="value">X local scale value to add.</param>
public static float AddLocalScaleX(this Transform transform, float value)
{
Vector3 localScale = transform.localScale;
localScale.x += value;
transform.localScale = localScale;
return localScale.x;
}
/// <summary>
/// Gets the local X scale of a transform.
/// </summary>
/// <param name="transform">Source Transform component.</param>
/// <returns>Returns the X local scale value.</returns>
public static float GetLocalScaleX(this Transform transform)
{
return transform.localScale.x;
}
/// <summary>
/// Sets the local Y scale of a transform.
/// </summary>
/// <param name="transform">Source Transform component.</param>
/// <param name="value">Y local scale value to set.</param>
public static void SetLocalScaleY(this Transform transform, float value)
{
Vector3 localScale = transform.localScale;
localScale.y = value;
transform.localScale = localScale;
}
/// <summary>
/// Adds to the local Y scale of a transform.
/// </summary>
/// <param name="transform">Source Transform component.</param>
/// <param name="value">Y local scale value to add.</param>
public static float AddLocalScaleY(this Transform transform, float value)
{
Vector3 localScale = transform.localScale;
localScale.y += value;
transform.localScale = localScale;
return localScale.y;
}
/// <summary>
/// Gets the local Y scale of a transform.
/// </summary>
/// <param name="transform">Source Transform component.</param>
/// <returns>Returns the Y local scale value.</returns>
public static float GetLocalScaleY(this Transform transform)
{
return transform.localScale.y;
}
/// <summary>
/// Sets the local Z scale of a transform.
/// </summary>
/// <param name="transform">Source Transform component.</param>
/// <param name="value">Z local scale value to set.</param>
public static void SetLocalScaleZ(this Transform transform, float value)
{
Vector3 localScale = transform.localScale;
localScale.z = value;
transform.localScale = localScale;
}
/// <summary>
/// Adds to the local Z scale of a transform.
/// </summary>
/// <param name="transform">Source Transform component.</param>
/// <param name="value">Z local scale value to add.</param>
public static float AddLocalScaleZ(this Transform transform, float value)
{
Vector3 localScale = transform.localScale;
localScale.z += value;
transform.localScale = localScale;
return localScale.z;
}
/// <summary>
/// Gets the local Z scale of a transform.
/// </summary>
/// <param name="transform">Source Transform component.</param>
/// <returns>Returns the Z local scale value.</returns>
public static float GetLocalScaleZ(this Transform transform)
{
return transform.localScale.z;
}
#endregion
}
}
| 38.364472 | 127 | 0.582548 | [
"MIT"
] | AikenParker/Expanse | Extensions/TransformExt.cs | 25,054 | C# |
using System;
using System.IO;
using System.Net;
using NBitcoin;
using NBitcoin.Protocol;
using Stratis.Bitcoin.Configuration;
using Stratis.Bitcoin.Configuration.Logging;
using Stratis.Bitcoin.Configuration.Settings;
using Stratis.Bitcoin.Connection;
using Stratis.Bitcoin.P2P;
using Stratis.Bitcoin.P2P.Peer;
using Stratis.Bitcoin.Utilities;
using Xunit;
namespace Stratis.Bitcoin.Tests.P2P
{
public sealed class PeerConnectorTests : TestBase
{
private readonly IAsyncLoopFactory asyncLoopFactory;
private readonly ExtendedLoggerFactory extendedLoggerFactory;
private readonly INetworkPeerFactory networkPeerFactory;
private readonly NetworkPeerConnectionParameters networkPeerParameters;
private readonly NodeLifetime nodeLifetime;
private readonly Network network;
public PeerConnectorTests()
{
this.extendedLoggerFactory = new ExtendedLoggerFactory();
this.extendedLoggerFactory.AddConsoleWithFilters();
this.asyncLoopFactory = new AsyncLoopFactory(this.extendedLoggerFactory);
this.network = Network.Main;
this.networkPeerParameters = new NetworkPeerConnectionParameters();
this.networkPeerFactory = new NetworkPeerFactory(this.network, DateTimeProvider.Default, this.extendedLoggerFactory);
this.nodeLifetime = new NodeLifetime();
}
[Fact]
public void PeerConnectorAddNode_FindPeerToConnectTo_Returns_AddNodePeers()
{
var peerFolder = AssureEmptyDirAsDataFolder(Path.Combine(AppContext.BaseDirectory, "PeerConnectorTests"));
var peerAddressManager = new PeerAddressManager(peerFolder, this.extendedLoggerFactory);
var ipAddressOne = IPAddress.Parse("::ffff:192.168.0.1");
var networkAddressAddNode = new NetworkAddress(ipAddressOne, 80);
var ipAddressTwo = IPAddress.Parse("::ffff:192.168.0.2");
var networkAddressDiscoverNode = new NetworkAddress(ipAddressTwo, 80);
peerAddressManager.AddPeer(networkAddressAddNode, IPAddress.Loopback);
peerAddressManager.AddPeer(networkAddressDiscoverNode, IPAddress.Loopback);
var nodeSettings = new NodeSettings();
nodeSettings.LoadArguments(new string[] { });
var connectionSettings = new ConnectionManagerSettings();
connectionSettings.Load(nodeSettings);
connectionSettings.AddNode.Add(networkAddressAddNode.Endpoint);
// TODO: Once we have an interface on NetworkPeer we can test this properly.
//var connector = this.CreatePeerConnecterAddNode(nodeSettings, peerAddressManager);
//connector.OnConnectAsync().GetAwaiter().GetResult();
//Assert.Contains(networkAddressAddNode, connector.ConnectedPeers.Select(p => p.PeerAddress));
}
[Fact]
public void PeerConnectorAddNode_CanAlwaysStart()
{
var peerFolder = AssureEmptyDirAsDataFolder(Path.Combine(AppContext.BaseDirectory, "PeerConnectorTests"));
var peerAddressManager = new PeerAddressManager(peerFolder, this.extendedLoggerFactory);
var nodeSettings = new NodeSettings();
nodeSettings.LoadArguments(new string[] { });
var connectionSettings = new ConnectionManagerSettings();
connectionSettings.Load(nodeSettings);
var connector = this.CreatePeerConnecterAddNode(nodeSettings, connectionSettings, peerAddressManager);
Assert.True(connector.CanStartConnect);
}
[Fact]
public void PeerConnectorConnect_FindPeerToConnectTo_Returns_ConnectNodePeers()
{
var peerFolder = AssureEmptyDirAsDataFolder(Path.Combine(AppContext.BaseDirectory, "PeerConnectorTests"));
var peerAddressManager = new PeerAddressManager(peerFolder, this.extendedLoggerFactory);
var ipAddressOne = IPAddress.Parse("::ffff:192.168.0.1");
var networkAddressAddNode = new NetworkAddress(ipAddressOne, 80);
var ipAddressTwo = IPAddress.Parse("::ffff:192.168.0.2");
var networkAddressDiscoverNode = new NetworkAddress(ipAddressTwo, 80);
var ipAddressThree = IPAddress.Parse("::ffff:192.168.0.3");
var networkAddressConnectNode = new NetworkAddress(ipAddressThree, 80);
peerAddressManager.AddPeer(networkAddressAddNode, IPAddress.Loopback);
peerAddressManager.AddPeer(networkAddressConnectNode, IPAddress.Loopback);
peerAddressManager.AddPeer(networkAddressDiscoverNode, IPAddress.Loopback);
var nodeSettings = new NodeSettings();
nodeSettings.LoadArguments(new string[] { });
var connectionSettings = new ConnectionManagerSettings();
connectionSettings.Load(nodeSettings);
connectionSettings.Connect.Add(networkAddressConnectNode.Endpoint);
var connector = this.CreatePeerConnectorConnectNode(nodeSettings, connectionSettings, peerAddressManager);
// TODO: Once we have an interface on NetworkPeer we can test this properly.
//var connector = this.CreatePeerConnecterAddNode(nodeSettings, peerAddressManager);
//connector.OnConnectAsync().GetAwaiter().GetResult();
//Assert.Contains(networkAddressConnectNode, connector.ConnectedPeers.Select(p => p.PeerAddress));
}
[Fact]
public void PeerConnectorConnect_WithConnectPeersSpecified_CanStart()
{
var peerFolder = AssureEmptyDirAsDataFolder(Path.Combine(AppContext.BaseDirectory, "PeerConnectorTests"));
var peerAddressManager = new PeerAddressManager(peerFolder, this.extendedLoggerFactory);
var ipAddressThree = IPAddress.Parse("::ffff:192.168.0.3");
var networkAddressConnectNode = new NetworkAddress(ipAddressThree, 80);
var nodeSettings = new NodeSettings();
nodeSettings.LoadArguments(new string[] { });
var connectionSettings = new ConnectionManagerSettings();
connectionSettings.Load(nodeSettings);
connectionSettings.Connect.Add(networkAddressConnectNode.Endpoint);
var connector = this.CreatePeerConnectorConnectNode(nodeSettings, connectionSettings, peerAddressManager);
Assert.True(connector.CanStartConnect);
}
[Fact]
public void PeerConnectorConnect_WithNoConnectPeersSpecified_CanNotStart()
{
var peerFolder = AssureEmptyDirAsDataFolder(Path.Combine(AppContext.BaseDirectory, "PeerConnectorTests"));
var peerAddressManager = new PeerAddressManager(peerFolder, this.extendedLoggerFactory);
var nodeSettings = new NodeSettings();
nodeSettings.LoadArguments(new string[] { });
var connectionSettings = new ConnectionManagerSettings();
connectionSettings.Load(nodeSettings);
var connector = this.CreatePeerConnectorConnectNode(nodeSettings, connectionSettings, peerAddressManager);
Assert.False(connector.CanStartConnect);
}
[Fact]
public void PeerConnectorDiscovery_FindPeerToConnectTo_Returns_DiscoveredPeers()
{
var peerFolder = AssureEmptyDirAsDataFolder(Path.Combine(AppContext.BaseDirectory, "PeerConnectorTests"));
var peerAddressManager = new PeerAddressManager(peerFolder, this.extendedLoggerFactory);
var ipAddressOne = IPAddress.Parse("::ffff:192.168.0.1");
var networkAddressAddNode = new NetworkAddress(ipAddressOne, 80);
var ipAddressThree = IPAddress.Parse("::ffff:192.168.0.3");
var networkAddressConnectNode = new NetworkAddress(ipAddressThree, 80);
var ipAddressTwo = IPAddress.Parse("::ffff:192.168.0.2");
var networkAddressDiscoverNode = new NetworkAddress(ipAddressTwo, 80);
peerAddressManager.AddPeer(networkAddressAddNode, IPAddress.Loopback);
peerAddressManager.AddPeer(networkAddressConnectNode, IPAddress.Loopback);
peerAddressManager.AddPeer(networkAddressDiscoverNode, IPAddress.Loopback);
var nodeSettings = new NodeSettings();
nodeSettings.LoadArguments(new string[] { });
var connectionSettings = new ConnectionManagerSettings();
connectionSettings.Load(nodeSettings);
connectionSettings.AddNode.Add(networkAddressAddNode.Endpoint);
connectionSettings.Connect.Add(networkAddressConnectNode.Endpoint);
var connector = this.CreatePeerConnectorDiscovery(nodeSettings, connectionSettings, peerAddressManager);
// TODO: Once we have an interface on NetworkPeer we can test this properly.
//var connector = this.CreatePeerConnecterAddNode(nodeSettings, peerAddressManager);
//connector.OnConnectAsync().GetAwaiter().GetResult();
//Assert.Contains(networkAddressDiscoverNode, connector.ConnectedPeers.Select(p => p.PeerAddress));
}
[Fact]
public void PeerConnectorDiscover_WithNoConnectPeersSpecified_CanStart()
{
var peerFolder = AssureEmptyDirAsDataFolder(Path.Combine(AppContext.BaseDirectory, "PeerConnectorTests"));
var peerAddressManager = new PeerAddressManager(peerFolder, this.extendedLoggerFactory);
var nodeSettings = new NodeSettings();
nodeSettings.LoadArguments(new string[] { });
var connectionSettings = new ConnectionManagerSettings();
connectionSettings.Load(nodeSettings);
var connector = this.CreatePeerConnectorDiscovery(nodeSettings, connectionSettings, peerAddressManager);
Assert.True(connector.CanStartConnect);
}
[Fact]
public void PeerConnectorDiscover_WithConnectPeersSpecified_CanNotStart()
{
var nodeSettings = new NodeSettings();
nodeSettings.LoadArguments(new string[] { });
var connectionSettings = new ConnectionManagerSettings();
connectionSettings.Load(nodeSettings);
var ipAddressThree = IPAddress.Parse("::ffff:192.168.0.3");
var networkAddressConnectNode = new NetworkAddress(ipAddressThree, 80);
connectionSettings.Connect.Add(networkAddressConnectNode.Endpoint);
var peerFolder = AssureEmptyDirAsDataFolder(Path.Combine(AppContext.BaseDirectory, "PeerConnectorTests"));
var peerAddressManager = new PeerAddressManager(peerFolder, this.extendedLoggerFactory);
var connector = this.CreatePeerConnectorDiscovery(nodeSettings, connectionSettings, peerAddressManager);
Assert.False(connector.CanStartConnect);
}
private PeerConnectorAddNode CreatePeerConnecterAddNode(NodeSettings nodeSettings, ConnectionManagerSettings connectionSettings, IPeerAddressManager peerAddressManager)
{
var peerConnector = new PeerConnectorAddNode(this.asyncLoopFactory, DateTimeProvider.Default, this.extendedLoggerFactory, this.network, this.networkPeerFactory, this.nodeLifetime, nodeSettings, connectionSettings, peerAddressManager);
var connectionManager = CreateConnectionManager(nodeSettings, connectionSettings, peerAddressManager, peerConnector);
peerConnector.Initialize(connectionManager);
return peerConnector;
}
private PeerConnectorConnectNode CreatePeerConnectorConnectNode(NodeSettings nodeSettings, ConnectionManagerSettings connectionSettings, IPeerAddressManager peerAddressManager)
{
var peerConnector = new PeerConnectorConnectNode(this.asyncLoopFactory, DateTimeProvider.Default, this.extendedLoggerFactory, this.network, this.networkPeerFactory, this.nodeLifetime, nodeSettings, connectionSettings, peerAddressManager);
var connectionManager = CreateConnectionManager(nodeSettings, connectionSettings, peerAddressManager, peerConnector);
peerConnector.Initialize(connectionManager);
return peerConnector;
}
private PeerConnectorDiscovery CreatePeerConnectorDiscovery(NodeSettings nodeSettings, ConnectionManagerSettings connectionSettings, IPeerAddressManager peerAddressManager)
{
var peerConnector = new PeerConnectorDiscovery(this.asyncLoopFactory, DateTimeProvider.Default, this.extendedLoggerFactory, this.network, this.networkPeerFactory, this.nodeLifetime, nodeSettings, connectionSettings, peerAddressManager);
var connectionManager = CreateConnectionManager(nodeSettings, connectionSettings, peerAddressManager, peerConnector);
peerConnector.Initialize(connectionManager);
return peerConnector;
}
private IConnectionManager CreateConnectionManager(NodeSettings nodeSettings, ConnectionManagerSettings connectionSettings, IPeerAddressManager peerAddressManager, IPeerConnector peerConnector)
{
var connectionManager = new ConnectionManager(
DateTimeProvider.Default,
this.loggerFactory,
this.network,
this.networkPeerFactory,
nodeSettings,
this.nodeLifetime,
this.networkPeerParameters,
peerAddressManager,
new IPeerConnector[] { peerConnector },
null,
connectionSettings);
return connectionManager;
}
}
} | 51.328302 | 250 | 0.709528 | [
"MIT"
] | danielgerlag/StratisBitcoinFullNode | src/Stratis.Bitcoin.Tests/P2P/PeerConnectorTests.cs | 13,604 | C# |
using SharpAudio.FFMPEG;
using System;
using System.IO;
using System.Threading;
using CommandLine;
using System.Collections.Generic;
using SharpAudio.FFMPEG;
using System.Linq;
namespace SharpAudio.Sample
{
class Program
{
public class Options
{
[Option('i', "input", Required = true, HelpText = "Specify the file(s) that should be played")]
public IEnumerable<string> InputFiles { get; set; }
[Option('v', "volume", Required = false, HelpText = "Set the output volume (0-100).", Default = 100)]
public int Volume { get; set; }
}
static void Main(string[] args)
{
CommandLine.Parser.Default.ParseArguments<Options>(args)
.WithParsed<Options>(opts => RunOptionsAndReturnExitCode(opts));
}
private static void RunOptionsAndReturnExitCode(Options opts)
{
var engine = AudioEngine.CreateDefault();
if (engine == null)
{
Console.WriteLine("Failed to create an audio backend!");
}
foreach (var file in opts.InputFiles)
{
var soundStream = new SoundStream(File.OpenRead(file), engine);
soundStream.Volume = opts.Volume / 100.0f;
soundStream.Play();
while (soundStream.IsPlaying)
{
var xx = string.Join(", ", soundStream.Metadata.Artists ?? new List<string>());
Console.Write($"Playing [{soundStream.Metadata.Title ?? Path.GetFileNameWithoutExtension(file)}] by [{(xx.Length > 0 ? xx : "Unknown")}] {soundStream.Position}/{(soundStream.Duration.TotalSeconds < 0 ? "\u221E" : soundStream.Duration.ToString())}\r");
Thread.Sleep(10);
}
Console.Write("\n");
}
}
}
}
| 31.633333 | 271 | 0.566386 | [
"MIT"
] | maxkatz6/SharpAudio | src/SharpAudio.Sample/Program.cs | 1,900 | C# |
using System;
using UnityEngine;
namespace EditorExtensions
{
public class SettingsWindow : MonoBehaviour
{
//public static SettingsWindow Instance { get; private set; }
//public bool Visible { get; set; }
public delegate void WindowDisabledEventHandler();
public event WindowDisabledEventHandler WindowDisabled;
protected virtual void OnWindowDisabled()
{
if (WindowDisabled != null)
WindowDisabled();
}
ConfigData _config;
string _configFilePath;
KeyCode _lastKeyPressed = KeyCode.None;
string _windowTitle = string.Empty;
string _version = string.Empty;
Rect _windowRect = new Rect () {
xMin = Screen.width - 325,
xMax = Screen.width - 50,
yMin = 50,
yMax = 50 //0 height, GUILayout resizes it
};
//ctor
public SettingsWindow ()
{
//start disabled
this.enabled = false;
}
void Awake ()
{
Log.Debug ("SettingsWindow Awake()");
}
void Update ()
{
if (Event.current.isKey) {
_lastKeyPressed = Event.current.keyCode;
}
}
void OnEnable ()
{
Log.Debug ("SettingsWindow OnEnable()");
if(_config == null || string.IsNullOrEmpty(_configFilePath)){
this.enabled = false;
}
}
void CloseWindow(){
this.enabled = false;
OnWindowDisabled ();
}
void OnDisable(){
}
void OnGUI ()
{
if (Event.current.type == EventType.Layout) {
_windowRect.yMax = _windowRect.yMin;
_windowRect = GUILayout.Window (this.GetInstanceID (), _windowRect, WindowContent, _windowTitle);
}
}
void OnDestroy ()
{
}
/// <summary>
/// Initializes the window content and enables it
/// </summary>
public void Show (ConfigData config, string configFilePath, Version version)
{
Log.Debug ("SettingsWindow Show()");
_config = config;
_configFilePath = configFilePath;
_windowTitle = string.Format ("Editor Extensions v{0}.{1}", version.Major.ToString (), version.Minor.ToString ());;
_version = version.ToString();
this.enabled = true;
}
private int toolbarInt = 0;
private string[] _toolbarStrings = { "Settings", "Angle Snap"};
string keyMapToUpdate = string.Empty;
string newAngleString = string.Empty;
public int angleGridIndex = -1;
public string[] angleStrings = new string[] { string.Empty };
object anglesLock = new object ();
GUILayoutOption[] settingsLabelLayout = new GUILayoutOption[] { GUILayout.MinWidth (150) };
void WindowContent (int windowID)
{
toolbarInt = GUILayout.Toolbar (toolbarInt, _toolbarStrings);
GUILayout.BeginVertical ("box");
# region Settings
if (toolbarInt == 0) {
GUILayout.BeginHorizontal ();
GUILayout.Label ("Version: " + _version.ToString());
GUILayout.EndHorizontal ();
#if DEBUG
GUILayout.Label ("Debug Build");
#endif
GUILayout.BeginHorizontal ();
GUILayout.Label ("Message delay:", settingsLabelLayout);
if (GUILayout.Button ("-")) {
_config.OnScreenMessageTime -= 0.5f;
}
GUILayout.Label (_config.OnScreenMessageTime.ToString (), "TextField");
if (GUILayout.Button ("+")) {
_config.OnScreenMessageTime += 0.5f;
}
GUILayout.EndHorizontal ();
GUILayout.BeginHorizontal ();
GUILayout.Label ("Max symmetry:", settingsLabelLayout);
if (GUILayout.Button ("-")) {
_config.MaxSymmetry--;
}
GUILayout.Label (_config.MaxSymmetry.ToString (), "TextField");
if (GUILayout.Button ("+")) {
_config.MaxSymmetry++;
}
GUILayout.EndHorizontal ();
//GUILayout.BeginHorizontal ();
//GUILayout.Label ("Show debug info:", settingsLabelLayout);
//_config.ShowDebugInfo = GUILayout.Toggle(_config.ShowDebugInfo, _config.ShowDebugInfo ? "Yep" : "Nope");
//GUILayout.EndHorizontal ();
if (keyMapToUpdate == string.Empty) {
GUILayout.Label ("Click button and press key to change");
} else {
GUILayout.Label ("Waiting for key");
}
#if DEBUG
GUILayout.Label ("_lastKeyPressed: " + _lastKeyPressed.ToString ());
#endif
GUILayout.BeginHorizontal ();
GUILayout.Label ("Surface attachment:", settingsLabelLayout);
if (keyMapToUpdate == "am" && _lastKeyPressed != KeyCode.None) {
_config.KeyMap.AttachmentMode = _lastKeyPressed;
keyMapToUpdate = string.Empty;
}
if (GUILayout.Button (_config.KeyMap.AttachmentMode.ToString ())) {
_lastKeyPressed = KeyCode.None;
keyMapToUpdate = "am";
}
GUILayout.EndHorizontal ();
GUILayout.BeginHorizontal ();
GUILayout.Label ("Vertical snap:", settingsLabelLayout);
if (keyMapToUpdate == "vs" && _lastKeyPressed != KeyCode.None) {
_config.KeyMap.VerticalSnap = _lastKeyPressed;
keyMapToUpdate = string.Empty;
}
if (GUILayout.Button (_config.KeyMap.VerticalSnap.ToString ())) {
_lastKeyPressed = KeyCode.None;
keyMapToUpdate = "vs";
}
GUILayout.EndHorizontal ();
GUILayout.BeginHorizontal ();
GUILayout.Label ("Horizontal snap:", settingsLabelLayout);
if (keyMapToUpdate == "hs" && _lastKeyPressed != KeyCode.None) {
_config.KeyMap.HorizontalSnap = _lastKeyPressed;
keyMapToUpdate = string.Empty;
}
if (GUILayout.Button (_config.KeyMap.HorizontalSnap.ToString ())) {
_lastKeyPressed = KeyCode.None;
keyMapToUpdate = "hs";
}
GUILayout.EndHorizontal ();
GUILayout.BeginHorizontal ();
GUILayout.Label ("Strut/fuel align:", settingsLabelLayout);
if (keyMapToUpdate == "cpa" && _lastKeyPressed != KeyCode.None) {
_config.KeyMap.CompoundPartAlign = _lastKeyPressed;
keyMapToUpdate = string.Empty;
}
if (GUILayout.Button (_config.KeyMap.CompoundPartAlign.ToString ())) {
_lastKeyPressed = KeyCode.None;
keyMapToUpdate = "cpa";
}
GUILayout.EndHorizontal ();
GUILayout.BeginHorizontal ();
GUILayout.Label ("Reset camera:", settingsLabelLayout);
if (keyMapToUpdate == "rc" && _lastKeyPressed != KeyCode.None) {
_config.KeyMap.ResetCamera = _lastKeyPressed;
keyMapToUpdate = string.Empty;
}
if (GUILayout.Button (_config.KeyMap.ResetCamera.ToString ())) {
_lastKeyPressed = KeyCode.None;
keyMapToUpdate = "rc";
}
GUILayout.EndHorizontal ();
}
#endregion
#region angle snap values settings
if (toolbarInt == 1) {
try {
//float[] tmpAngles;
//_config.AngleSnapValues.CopyTo (tmpAngles);
lock (anglesLock) {
foreach (float a in _config.AngleSnapValues) {
if (a != 0.0f) {
GUILayout.BeginHorizontal ();
GUILayout.Label (a.ToString (), settingsLabelLayout);
if (GUILayout.Button ("Remove")) {
_config.AngleSnapValues.Remove (a);
}
GUILayout.EndHorizontal ();
}
}
}
GUILayout.BeginHorizontal ();
GUILayout.Label ("Add angle: ");
newAngleString = GUILayout.TextField (newAngleString);
if (GUILayout.Button ("Add")) {
float newAngle = 0.0f;
if (!string.IsNullOrEmpty (newAngleString) && float.TryParse (newAngleString, out newAngle)) {
lock (anglesLock) {
if (newAngle > 0.0f && newAngle <= 90.0f && _config.AngleSnapValues.IndexOf (newAngle) == -1) {
_config.AngleSnapValues.Add (newAngle);
_config.AngleSnapValues.Sort ();
}
}
}
}
GUILayout.EndHorizontal ();
}
#if DEBUG
catch (Exception ex) {
//potential for some intermittent locking/threading issues here
//Debug only to avoid log spam
Log.Error ("Error updating AngleSnapValues: " + ex.Message);
}
#else
catch(Exception){
//just ignore the error and continue since it's non-critical
}
#endif
}
#endregion
GUILayout.EndVertical ();//end main content
GUILayout.BeginHorizontal ();
if (GUILayout.Button ("Close")) {
_config = ConfigManager.LoadConfig (_configFilePath);
CloseWindow ();
}
if (GUILayout.Button ("Defaults")) {
_config = ConfigManager.CreateDefaultConfig (_configFilePath, _version);;
}
if (GUILayout.Button ("Save")) {
ConfigManager.SaveConfig (_config, _configFilePath);
CloseWindow ();
}
GUILayout.EndHorizontal ();
GUI.DragWindow ();
}
}
//end class
}
| 27.505051 | 118 | 0.658343 | [
"MIT"
] | Gerry1135/EditorExtensions | EditorExtensions/SettingsWindow.cs | 8,171 | C# |
namespace L2dotNET.Network.serverpackets
{
class PetInfo : GameserverPacket
{
public PetInfo()
{
}
public override void Write()
{
WriteByte(0xb1);
}
}
} | 15.666667 | 41 | 0.485106 | [
"MPL-2.0",
"MPL-2.0-no-copyleft-exception"
] | Elfocrash/L2dotNET | src/L2dotNET/Network/serverpackets/PetInfo.cs | 237 | C# |
// <copyright file="PostIconManager.cs" company="Drastic Actions">
// Copyright (c) Drastic Actions. All rights reserved.
// </copyright>
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Awful.Exceptions;
using Awful.Parser.Core;
using Awful.Parser.Handlers;
using Awful.Parser.Models.PostIcons;
namespace Awful.Parser.Managers
{
/// <summary>
/// Manager for Post Icons on Something Awful.
/// </summary>
public class PostIconManager
{
private readonly WebClient webManager;
/// <summary>
/// Initializes a new instance of the <see cref="PostIconManager"/> class.
/// </summary>
/// <param name="webManager">The SA WebClient.</param>
public PostIconManager(WebClient webManager)
{
this.webManager = webManager;
}
/// <summary>
/// Gets post icons for Threads.
/// </summary>
/// <param name="forumId">The Forum Id.</param>
/// <param name="token">A CancellationToken.</param>
/// <returns>A list of PostIcon's for Threads.</returns>
public async Task<List<PostIcon>> GetForumPostIconsAsync(int forumId = 0, CancellationToken token = default)
{
return await this.GetPostIcons_InternalAsync(false, forumId, token).ConfigureAwait(false);
}
/// <summary>
/// Gets post icons for Private Messages.
/// </summary>
/// <param name="token">A CancellationToken.</param>
/// <returns>A list of PostIcon's that can be used for Private Messages.</returns>
public async Task<List<PostIcon>> GetPrivateMessagePostIconsAsync(CancellationToken token = default)
{
return await this.GetPostIcons_InternalAsync(true, 0, token).ConfigureAwait(false);
}
private async Task<List<PostIcon>> GetPostIcons_InternalAsync(bool isPrivateMessage = false, int forumId = 0, CancellationToken token = default)
{
if (!this.webManager.IsAuthenticated)
{
throw new UserAuthenticationException(Awful.Core.Resources.ExceptionMessages.UserAuthenticationError);
}
string url = isPrivateMessage ? EndPoints.NewPrivateMessageBase : string.Format(CultureInfo.InvariantCulture, EndPoints.NewThread, forumId);
var result = await this.webManager.GetDataAsync(url, token).ConfigureAwait(false);
var document = await this.webManager.Parser.ParseDocumentAsync(result.ResultHtml, token).ConfigureAwait(false);
return PostIconHandler.ParsePostIconList(document);
}
}
}
| 39.391304 | 152 | 0.665195 | [
"MIT"
] | drasticactions/Awful.Core | Awful/Managers/PostIconManager.cs | 2,720 | C# |
using System;
public class Program
{
public static void Main(string[] args)
{
DateTime dt = new DateTime(1999, 7, 7);
dt.AddDays(1);
Console.WriteLine(dt.ToShortDateString());
}
}
| 18.166667 | 50 | 0.600917 | [
"MIT"
] | autumn009/TanoCSharpSamples | Chap5/C5Q14/C5Q14/Program.cs | 220 | C# |
using System.Resources;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("XamarinWeb")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("XamarinWeb")]
[assembly: AssemblyCopyright("Copyright © 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: NeutralResourcesLanguage("en")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 34.677419 | 84 | 0.743256 | [
"MIT"
] | alexandrecz/Xamarin | XamarinWeb/XamarinWeb/Properties/AssemblyInfo.cs | 1,078 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
namespace SimplCommerce.WebHost
{
public class Program
{
public static void Main(string[] args)
{
BuildWebHost(args).Run();
}
public static IWebHost BuildWebHost(string[] args) =>
Microsoft.AspNetCore.WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.UseDefaultServiceProvider(options => options.ValidateScopes = false)
.Build();
}
}
| 26.592593 | 85 | 0.674095 | [
"Apache-2.0"
] | danielfn/example-dotnet-simplcommerce | src/SimplCommerce.WebHost/Program.cs | 720 | C# |
using System;
using ChartDirector;
namespace CSharpChartExplorer
{
public class dualhbar : DemoModule
{
//Name of demo module
public string getName() { return "Dual Horizontal Bar Charts"; }
//Number of charts produced in this demo module
public int getNoOfCharts() { return 1; }
//Main code for creating chart.
//Note: the argument chartIndex is unused because this demo only has 1 chart.
public void createChart(WinChartViewer viewer, int chartIndex)
{
// The age groups
string[] labels = {"0 - 4", "5 - 9", "10 - 14", "15 - 19", "20 - 24", "24 - 29",
"30 - 34", "35 - 39", "40 - 44", "44 - 49", "50 - 54", "55 - 59", "60 - 64",
"65 - 69", "70 - 74", "75 - 79", "80+"};
// The male population (in thousands)
double[] male = {215, 238, 225, 236, 235, 260, 286, 340, 363, 305, 259, 164, 135, 127,
102, 68, 66};
// The female population (in thousands)
double[] female = {194, 203, 201, 220, 228, 271, 339, 401, 384, 304, 236, 137, 116, 122,
112, 85, 110};
//=============================================================
// Draw the right bar chart
//=============================================================
// Create a XYChart object of size 320 x 300 pixels
XYChart c = new XYChart(320, 300);
// Set the plotarea at (50, 0) and of size 250 x 255 pixels. Use pink (0xffdddd) as the
// background.
c.setPlotArea(50, 0, 250, 255, 0xffdddd);
// Add a custom text label at the top right corner of the right bar chart
c.addText(300, 0, "Female", "Times New Roman Bold Italic", 12, 0xa07070).setAlignment(
Chart.TopRight);
// Add the pink (0xf0c0c0) bar chart layer using the female data
BarLayer femaleLayer = c.addBarLayer(female, 0xf0c0c0, "Female");
// Swap the axis so that the bars are drawn horizontally
c.swapXY(true);
// Set the bar to touch each others
femaleLayer.setBarGap(Chart.TouchBar);
// Set the border style of the bars to 1 pixel 3D border
femaleLayer.setBorderColor(-1, 1);
// Add a Transparent line layer to the chart using the male data. As it is Transparent,
// only the female bar chart can be seen. We need to put both male and female data in
// both left and right charts, because we want auto-scaling to produce the same scale
// for both chart.
c.addLineLayer(male, Chart.Transparent);
// Set the y axis label font to Arial Bold
c.yAxis().setLabelStyle("Arial Bold");
// Set the labels between the two bar charts, which can be considered as the x-axis
// labels for the right chart
ChartDirector.TextBox tb = c.xAxis().setLabels(labels);
// Use a fix width of 50 for the labels (height = automatic) with center alignment
tb.setSize(50, 0);
tb.setAlignment(Chart.Center);
// Set the label font to Arial Bold
tb.setFontStyle("Arial Bold");
// Disable ticks on the x-axis by setting the tick length to 0
c.xAxis().setTickLength(0);
//=============================================================
// Draw the left bar chart
//=============================================================
// Create a XYChart object of size 280 x 300 pixels with a transparent background.
XYChart c2 = new XYChart(280, 300, Chart.Transparent);
// Set the plotarea at (20, 0) and of size 250 x 255 pixels. Use pale blue (0xddddff) as
// the background.
c2.setPlotArea(20, 0, 250, 255, 0xddddff);
// Add a custom text label at the top left corner of the left bar chart
c2.addText(20, 0, "Male", "Times New Roman Bold Italic", 12, 0x7070a0);
// Add the pale blue (0xaaaaff) bar chart layer using the male data
BarLayer maleLayer = c2.addBarLayer(male, 0xaaaaff, "Male");
// Swap the axis so that the bars are drawn horizontally
c2.swapXY(true);
// Reverse the direction of the y-axis so it runs from right to left
c2.yAxis().setReverse();
// Set the bar to touch each others
maleLayer.setBarGap(Chart.TouchBar);
// Set the border style of the bars to 1 pixel 3D border
maleLayer.setBorderColor(-1, 1);
// Add a Transparent line layer to the chart using the female data. As it is
// Transparent, only the male bar chart can be seen. We need to put both male and female
// data in both left and right charts, because we want auto-scaling to produce the same
// scale for both chart.
c2.addLineLayer(female, Chart.Transparent);
// Set the y axis label font to Arial Bold
c2.yAxis().setLabelStyle("Arial Bold");
// Set the x-axis labels for tool tip purposes.
c2.xAxis().setLabels(labels);
// Hide the x-axis labels by setting them to Transparent. We only need to display the
// x-axis labels for the right chart.
c2.xAxis().setColors(0x000000, Chart.Transparent, -1, Chart.Transparent);
//=============================================================
// Use a MultiChart to contain both bar charts
//=============================================================
// Create a MultiChart object of size 590 x 320 pixels.
MultiChart m = new MultiChart(590, 320);
// Add a title to the chart using Arial Bold Italic font
m.addTitle("Demographics Hong Kong Year 2002", "Arial Bold Italic");
// Add another title at the bottom using Arial Bold Italic font
m.addTitle2(Chart.Bottom, "Population (in thousands)", "Arial Bold Italic", 10);
// Put the right chart at (270, 25)
m.addChart(270, 25, c);
// Put the left chart at (0, 25)
m.addChart(0, 25, c2);
// Output the chart
viewer.Chart = m;
//include tool tip for the chart
viewer.ImageMap = m.getHTMLImageMap("clickable", "",
"title='{dataSetName} (Age {xLabel}): Population {value}K'");
}
}
}
| 42.608974 | 100 | 0.537385 | [
"Apache-2.0"
] | jojogreen/Orbital-Mechanix-Suite | NetWinCharts/CSharpWinCharts/dualhbar.cs | 6,647 | C# |
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.CompilerServices;
using GeometricAlgebraFulcrumLib.Processors.LinearAlgebra;
using GeometricAlgebraFulcrumLib.Processors.ScalarAlgebra;
using GeometricAlgebraFulcrumLib.Storage.LinearAlgebra.Matrices;
using GeometricAlgebraFulcrumLib.Storage.LinearAlgebra.Vectors;
using GeometricAlgebraFulcrumLib.Utilities.Factories;
using GeometricAlgebraFulcrumLib.Utilities.Structures.Records;
namespace GeometricAlgebraFulcrumLib.Algebra.LinearAlgebra.LinearMaps
{
public class LinUnilinearMap<T> :
ILinUnilinearMap<T>
{
public IScalarAlgebraProcessor<T> ScalarProcessor
=> LinearProcessor;
public ILinearAlgebraProcessor<T> LinearProcessor { get; }
public ILinMatrixStorage<T> MatrixStorage { get; }
internal LinUnilinearMap([NotNull] ILinearAlgebraProcessor<T> linearProcessor, [NotNull] ILinMatrixStorage<T> matrixStorage)
{
LinearProcessor = linearProcessor;
MatrixStorage = matrixStorage;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public ILinUnilinearMap<T> GetLinAdjoint()
{
return new LinUnilinearMap<T>(
LinearProcessor,
MatrixStorage.GetTranspose()
);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public ILinVectorStorage<T> LinMapBasisVector(ulong index)
{
return MatrixStorage.GetColumn(index);
}
public ILinVectorStorage<T> LinMapVector(ILinVectorStorage<T> vectorStorage)
{
var composer = LinearProcessor.CreateVectorStorageComposer();
foreach (var (index, scalar) in vectorStorage.GetIndexScalarRecords())
composer.AddScaledTerms(
scalar,
LinMapBasisVector(index).GetIndexScalarRecords()
);
return composer.CreateLinVectorStorage();
}
public ILinMatrixStorage<T> LinMapMatrix(ILinMatrixStorage<T> matrixStorage)
{
throw new System.NotImplementedException();
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public ILinMatrixStorage<T> GetLinMappingMatrix()
{
return MatrixStorage;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public IEnumerable<IndexLinVectorStorageRecord<T>> GetLinMappedBasisVectors()
{
return MatrixStorage.GetColumns();
}
}
} | 33.986842 | 132 | 0.681765 | [
"MIT"
] | ga-explorer/GeometricAlgebraFulcrumLib | GeometricAlgebraFulcrumLib/GeometricAlgebraFulcrumLib/Algebra/LinearAlgebra/LinearMaps/LinUnilinearMap.cs | 2,585 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Collections.ObjectModel;
using System.ComponentModel;
using AppAlmacenPF.Entities;
using AppAlmacenPF.ModelView;
using System.Windows.Input;
using System.Windows;
namespace AppAlmacenPF.ModelView
{
public class TelefonoProveedorModelView : INotifyPropertyChanged, ICommand//INTERFAZ
{
//Enlace a la base de datos
private AppAlmacenPFDataContext db = new AppAlmacenPFDataContext();
private bool _IsReadOnlyCodigoTelefono = true;
private bool _IsReadOnlyNumero = true;
private bool _IsReadOnlyDescripcion = true;
private bool _IsReadOnlyCodigoProveedor = true;
private string _CodigoTelefono;
private string _Numero;
private string _CodigoProveedor;
private string _Descripcion;
public string CodigoTelefono
{
get
{
return this._CodigoTelefono;
}
set
{
this._CodigoTelefono = value;
ChangedNotify("CodigoTelefono");
}
}
public string Numero
{
get
{
return this._Numero;
}
set
{
this._Numero = value;
ChangedNotify("Numero");
}
}
public string CodigoProveedor
{
get
{
return this._CodigoProveedor;
}
set
{
this._CodigoProveedor = value;
ChangedNotify("CodigoProveedor");
}
}
public string Descripcion
{
get
{
return this._Descripcion;
}
set
{
this._Descripcion = value;
ChangedNotify("Descripcion");
}
}
private TelefonoProveedorModelView _Instancia;
public TelefonoProveedorModelView Instancia
{
get
{
return this._Instancia;
}
set
{
this._Instancia = value;
ChangedNotify("Instancia");
}
}
public Boolean IsReadOnlyCodigoTelefono
{
get
{
return this._IsReadOnlyCodigoTelefono;
}
set
{
this._IsReadOnlyCodigoTelefono = value;
ChangedNotify("IsReadOnlyCodigoTelefono");
}
}
public Boolean IsReadOnlyNumero
{
get
{
return this._IsReadOnlyNumero;
}
set
{
this._IsReadOnlyNumero = value;
ChangedNotify("IsReadOnlyNumero");
}
}
public Boolean IsReadOnlyDescripcion
{
get
{
return this._IsReadOnlyDescripcion;
}
set
{
this._IsReadOnlyDescripcion = value;
ChangedNotify("IsReadOnlyDescripcion");
}
}
public Boolean IsReadOnlyCodigoProveedor
{
get
{
return this._IsReadOnlyCodigoProveedor;
}
set
{
this._IsReadOnlyCodigoProveedor = value;
ChangedNotify("IsReadOnlyCodigoProveedor");
}
}
private ObservableCollection<TelefonoProveedor> _TelefonoProveedor;
public ObservableCollection<TelefonoProveedor> TelefonoProveedores
{
get
{
if (this._TelefonoProveedor == null)
{
this._TelefonoProveedor = new ObservableCollection<TelefonoProveedor>();
foreach(TelefonoProveedor elemento in db.TelefonoProveedores.ToList())
{
this._TelefonoProveedor.Add(elemento);
}
}
return this._TelefonoProveedor;
}
set { this._TelefonoProveedor = value; }
}
public TelefonoProveedorModelView()
{
this.Titulo = "Telefonos de proveedores:";
this.Instancia = this;
}
public string Titulo { get; set; }
public event PropertyChangedEventHandler PropertyChanged;
public void ChangedNotify(string property)
{
if(PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(property));
}
}
public event EventHandler CanExecuteChanged;
public bool CanExecute(object parameter)
{
return true;
/*throw new NotImplementedException();*/
}
public void Execute(object parameter)
{
if(parameter.Equals("Add"))
{
this.IsReadOnlyCodigoProveedor = false;
this.IsReadOnlyCodigoTelefono = false;
this.IsReadOnlyDescripcion = false;
this.IsReadOnlyNumero = false;
}
if(parameter.Equals("Save"))
{
TelefonoProveedor parametro = new TelefonoProveedor();
parametro.Codigo_Telefono = Convert.ToInt16(this.CodigoTelefono);
parametro.Numero = this.Numero;
parametro.Descripcion = this.Descripcion;
parametro.Codigo_Proveedor = Convert.ToInt16(this.CodigoProveedor);
db.TelefonoProveedores.Add(parametro);
db.SaveChanges();
this.TelefonoProveedores.Add(parametro);
MessageBox.Show("Registro Almacenado");
}
/*throw new NotImplementedException();*/
}
}
}
| 29.70297 | 92 | 0.5155 | [
"MIT"
] | johnsvill/proyecto-final-backend-app | ModelView/TelefonoProveedorModelView.cs | 6,002 | C# |
using System;
using EventStore.ClientAPI.SystemData;
using NUnit.Framework;
namespace EventStore.Core.Tests.ClientAPI.UserManagement
{
[TestFixture]
public class updating_a_user : TestWithNode
{
[Test]
public void updating_a_user_with_null_username_throws()
{
Assert.Throws<ArgumentNullException>(() => _manager.UpdateUserAsync(null, "greg", new[] { "foo", "bar" }, new UserCredentials("admin", "changeit")));
}
[Test]
public void updating_a_user_with_empty_username_throws()
{
Assert.Throws<ArgumentNullException>(() => _manager.UpdateUserAsync("", "greg", new[] { "foo", "bar" }, new UserCredentials("admin", "changeit")));
}
[Test]
public void updating_a_user_with_null_name_throws()
{
Assert.Throws<ArgumentNullException>(() => _manager.UpdateUserAsync("greg", null, new[] { "foo", "bar" }, new UserCredentials("admin", "changeit")));
}
[Test]
public void updating_a_user_with_empty_name_throws()
{
Assert.Throws<ArgumentNullException>(() => _manager.UpdateUserAsync("greg", "", new[] { "foo", "bar" }, new UserCredentials("admin", "changeit")));
}
[Test]
public void updating_non_existing_user_throws()
{
Assert.Throws<AggregateException>(() => _manager.UpdateUserAsync(Guid.NewGuid().ToString(), "bar", new []{"foo"}, new UserCredentials("admin", "changeit")).Wait());
}
//[Test] //TODO: needs to be changed for running against single instance
//public void updating_a_user_with_parameters_can_be_read()
//{
// UserDetails d = null;
// _manager.CreateUserAsync("ouro", "ourofull", new[] {"foo", "bar"}, "password",
// new UserCredentials("admin", "changeit")).Wait();
// _manager.UpdateUserAsync("ouro", "something", new[] {"bar", "baz"}, new UserCredentials("admin", "changeit"))
// .Wait();
// Assert.DoesNotThrow(() =>
// {
// d = _manager.GetUserAsync("ouro", new UserCredentials("admin", "changeit")).Result;
// });
// Assert.AreEqual("ouro", d.LoginName);
// Assert.AreEqual("something", d.FullName);
// Assert.AreEqual("bar", d.Groups[0]);
// Assert.AreEqual("baz", d.Groups[1]);
//}
}
}
| 41.20339 | 176 | 0.588235 | [
"Apache-2.0"
] | EventStore/ClientAPI.NetCore | test/EventStore.ClientAPI.NetCore.Tests/UserManagement/updating_a_user.cs | 2,433 | C# |
using SharedTrip.Models;
using SharedTrip.ViewModels.Trips;
using System.Linq;
namespace SharedTrip.Services
{
public interface ITripsService
{
IQueryable<AllTripsViewModel> GetAllTrips();
void Create(string startPoint, string endPoint, string departureTime, string imagePath, int seats, string description);
DetailsViewModel GetDetails(string tripId);
void AddUserToTrip(string tripId, string userId);
}
}
| 25.333333 | 127 | 0.739035 | [
"MIT"
] | TihomirIvanovIvanov/SoftUni | C#WebDevelopment/C#-Web-Basics/MyExamSharedTrip/src/SharedTrip/Services/ITripsService.cs | 458 | C# |
// This file is part of Silk.NET.
//
// You may modify and distribute Silk.NET under the terms
// of the MIT license. See the LICENSE file for details.
using System;
#pragma warning disable 1591
namespace Silk.NET.OpenGL.Legacy
{
public enum CopyBufferSubDataTarget
{
ArrayBuffer = 0x8892,
ElementArrayBuffer = 0x8893,
PixelPackBuffer = 0x88EB,
PixelUnpackBuffer = 0x88EC,
UniformBuffer = 0x8A11,
TextureBuffer = 0x8C2A,
TransformFeedbackBuffer = 0x8C8E,
CopyReadBuffer = 0x8F36,
CopyWriteBuffer = 0x8F37,
DrawIndirectBuffer = 0x8F3F,
ShaderStorageBuffer = 0x90D2,
DispatchIndirectBuffer = 0x90EE,
QueryBuffer = 0x9192,
AtomicCounterBuffer = 0x92C0,
}
}
| 25.258065 | 57 | 0.661558 | [
"MIT"
] | AzyIsCool/Silk.NET | src/OpenGL/Silk.NET.OpenGL.Legacy/Enums/CopyBufferSubDataTarget.gen.cs | 783 | C# |
/* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov
*
* 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.Security;
using System.Text;
namespace Alphaleonis.Win32.Filesystem
{
public static partial class File
{
/// <summary>[AlphaFS] Opens a text file, reads all lines of the file, and then closes the file.</summary>
/// <param name="transaction">The transaction.</param>
/// <param name="path">The file to open for reading.</param>
/// <returns>All lines of the file.</returns>
[SecurityCritical]
public static string ReadAllTextTransacted(KernelTransaction transaction, string path)
{
return ReadAllTextCore(transaction, path, NativeMethods.DefaultFileEncoding, PathFormat.RelativePath);
}
/// <summary>[AlphaFS] Opens a file, reads all lines of the file with the specified encoding, and then closes the file.</summary>
/// <param name="transaction">The transaction.</param>
/// <param name="path">The file to open for reading.</param>
/// <param name="encoding">The <see cref="Encoding"/> applied to the contents of the file.</param>
/// <returns>All lines of the file.</returns>
[SecurityCritical]
public static string ReadAllTextTransacted(KernelTransaction transaction, string path, Encoding encoding)
{
return ReadAllTextCore(transaction, path, encoding, PathFormat.RelativePath);
}
/// <summary>[AlphaFS] Opens a text file, reads all lines of the file, and then closes the file.</summary>
/// <param name="transaction">The transaction.</param>
/// <param name="path">The file to open for reading.</param>
/// <param name="pathFormat">Indicates the format of the path parameter(s).</param>
/// <returns>All lines of the file.</returns>
[SecurityCritical]
public static string ReadAllTextTransacted(KernelTransaction transaction, string path, PathFormat pathFormat)
{
return ReadAllTextCore(transaction, path, NativeMethods.DefaultFileEncoding, pathFormat);
}
/// <summary>[AlphaFS] Opens a file, reads all lines of the file with the specified encoding, and then closes the file.</summary>
/// <param name="transaction">The transaction.</param>
/// <param name="path">The file to open for reading.</param>
/// <param name="encoding">The <see cref="Encoding"/> applied to the contents of the file.</param>
/// <param name="pathFormat">Indicates the format of the path parameter(s).</param>
/// <returns>All lines of the file.</returns>
[SecurityCritical]
public static string ReadAllTextTransacted(KernelTransaction transaction, string path, Encoding encoding, PathFormat pathFormat)
{
return ReadAllTextCore(transaction, path, encoding, pathFormat);
}
}
}
| 51.051948 | 135 | 0.704147 | [
"MIT"
] | DamirAinullin/AlphaFS | src/AlphaFS/Filesystem/File Class/File.ReadAllTextTransacted.cs | 3,931 | C# |
using System;
using System.Collections.Generic;
using System.Text;
namespace COSXML.Model.Object
{
/// <summary>
/// 删除对象返回的结果
/// <see cref="https://cloud.tencent.com/document/product/436/7743"/>
/// </summary>
public sealed class DeleteObjectResult : CosResult
{
}
}
| 18.6875 | 73 | 0.658863 | [
"MIT"
] | Noname-Studio/ET | Unity/Assets/ThirdParty/CloudServices/Tencent/COS/Model/Object/DeleteObjectResult.cs | 317 | C# |
using System;
using System.Collections.Generic;
namespace EasyTree.Iterators
{
internal class LevelOrderIterator : IteratorBase, IEnumerable<Node>
{
public LevelOrderIterator(Node node, bool includeRoot = true) : base(node)
{
LevelOrder(_node, includeRoot);
}
public LevelOrderIterator(Node node, PerformFunction function, bool includeRoot = true) : base(node)
{
LevelOrder(_node, function, includeRoot);
}
private void LevelOrder(Node node, bool includeRoot)
{
var queue = new Queue<Node>();
if (includeRoot)
_nodelist.Add(node);
queue.Enqueue(node);
while (queue.Count > 0)
{
foreach(Node currentNode in queue.Dequeue().Children)
{
_nodelist.Add(currentNode);
queue.Enqueue(currentNode);
}
}
}
private void LevelOrder(Node node, PerformFunction function, bool includeRoot)
{
var queue = new Queue<Node>();
if (includeRoot)
_nodelist.Add(node);
function(node);
queue.Enqueue(node);
while (queue.Count > 0)
{
foreach (Node currentNode in queue.Dequeue().Children)
{
_nodelist.Add(currentNode);
function(node);
queue.Enqueue(currentNode);
}
}
}
}
}
| 28.438596 | 108 | 0.494756 | [
"MIT"
] | kvonkoni/EasyTree | EasyTree/Iterators/LevelOrderIterator.cs | 1,623 | C# |
using System.Collections.Generic;
using System.Threading.Tasks;
namespace FunctionMonkey.Tests.Integration.Common.Commands.Model
{
public class SimpleResponse
{
public int Value { get; set; }
public string Message { get; set; }
public static Task<SimpleResponse> Success()
{
return Task.FromResult(new SimpleResponse
{
Message = "success",
Value = 1
});
}
public static Task<IReadOnlyCollection<SimpleResponse>> SuccessCollection()
{
IReadOnlyCollection<SimpleResponse> collection = new SimpleResponse[]
{
new SimpleResponse
{
Message = "success1",
Value = 1
},
new SimpleResponse
{
Message = "success2",
Value = 2
}
};
return Task.FromResult(collection);
}
}
}
| 25.268293 | 83 | 0.490347 | [
"MIT"
] | AKomyshan/FunctionMonkey | Tests/FunctionMonkey.Tests.Integration.Common/Commands/Model/SimpleResponse.cs | 1,038 | C# |
// Copyright 2017 the original author or authors.
//
// 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.
using Steeltoe.Stream.Binder;
using System;
namespace Steeltoe.Stream.Util
{
internal static class GenericsUtils
{
internal static Type GetParameterType(Type evaluatedClass, Type interfaceClass, int position)
{
Type bindableType = null;
if (!interfaceClass.IsInterface)
{
throw new ArgumentException(nameof(interfaceClass) + " is not an interface");
}
var currentType = evaluatedClass;
while (!typeof(object).Equals(currentType) && bindableType == null)
{
var interfaces = currentType.GetInterfaces();
Type resolvableType = null;
foreach (var interfaceType in interfaces)
{
var typeToCheck = interfaceType;
if (interfaceType.IsGenericType)
{
typeToCheck = interfaceType.GetGenericTypeDefinition();
}
if (interfaceClass == typeToCheck)
{
resolvableType = interfaceType;
break;
}
}
if (resolvableType == null)
{
currentType = currentType.BaseType;
}
else
{
if (resolvableType.IsGenericType)
{
var genArgs = resolvableType.GetGenericArguments();
bindableType = genArgs[position];
}
else
{
bindableType = typeof(object);
}
}
}
if (bindableType == null)
{
throw new InvalidOperationException("Cannot find parameter of " + evaluatedClass.Name + " for " + interfaceClass + " at position " + position);
}
return bindableType;
}
internal static bool CheckCompatiblePollableBinder(IBinder binderInstance, Type bindingTargetType)
{
var binderInstanceType = binderInstance.GetType();
var binderInterfaces = binderInstanceType.GetInterfaces();
foreach (var intf in binderInterfaces)
{
if (typeof(IPollableConsumerBinder).IsAssignableFrom(intf))
{
var targetInterfaces = bindingTargetType.GetInterfaces();
var psType = FindPollableSourceType(targetInterfaces);
if (psType != null)
{
return GetParameterType(binderInstance.GetType(), intf, 0).IsAssignableFrom(psType);
}
}
}
return false;
}
internal static Type FindPollableSourceType(Type[] targetInterfaces)
{
foreach (var targetIntf in targetInterfaces)
{
if (typeof(IPollableSource).IsAssignableFrom(targetIntf))
{
var supers = targetIntf.GetInterfaces();
foreach (var type in supers)
{
if (type.IsGenericType)
{
var resolvableType = type.GetGenericTypeDefinition();
if (resolvableType.Equals(typeof(IPollableSource<>)))
{
return type.GetGenericArguments()[0];
}
}
}
}
}
return null;
}
}
}
| 35.884298 | 159 | 0.506449 | [
"Apache-2.0"
] | Karql/steeltoe | src/Stream/src/Base/Util/GenericsUtils.cs | 4,344 | C# |
// <copyright file="TrivialQuest.cs" company="Google Inc.">
// Copyright (C) 2015 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>
namespace TrivialQuest
{
using UnityEngine;
using UnityEngine.UI;
using GooglePlayGames;
using GooglePlayGames.BasicApi;
using GooglePlayGames.BasicApi.Quests;
public class TrivialQuest : MonoBehaviour
{
private GameObject[] signedInObjects;
private GameObject[] signedOutObjects;
private Text statusText;
void Start()
{
// Lock the screen to landscape
Screen.orientation = ScreenOrientation.LandscapeLeft;
// Buttons
signedInObjects = GameObject.FindGameObjectsWithTag("SignedIn");
signedOutObjects = GameObject.FindGameObjectsWithTag("SignedOut");
statusText = GameObject.Find("statusText").GetComponent<Text>();
// Google Play Games
PlayGamesClientConfiguration config =
new PlayGamesClientConfiguration.Builder().Build();
PlayGamesPlatform.DebugLogEnabled = true;
PlayGamesPlatform.InitializeInstance(config);
PlayGamesPlatform.Activate();
// Try silent sign-in
UpdateButtonVisibility(false);
PlayGamesPlatform.Instance.Authenticate(SignInCallback, true);
}
private void UpdateButtonVisibility(bool signedIn)
{
Debug.Log("UpdateButtonVisibility:signedIn:" + signedIn);
// GameObjects tagged as 'SignedIn' should be shown only when we are signed in
foreach (GameObject go in signedInObjects)
{
go.SetActive(signedIn);
}
// GameObjects tagged as 'SignedOut' should be shown only when we are signed out
foreach (GameObject go in signedOutObjects)
{
go.SetActive(!signedIn);
}
}
private void SignInCallback(bool success)
{
if (success)
{
statusText.text = "Signed In: " +
PlayGamesPlatform.Instance.localUser.userName;
}
else
{
statusText.text = "Sign-in failed.";
}
UpdateButtonVisibility(success);
}
public void SignIn()
{
Debug.Log("clicked:SignIn");
PlayGamesPlatform.Instance.Authenticate(SignInCallback);
}
public void SignOut()
{
Debug.Log("clicked:SignOut");
PlayGamesPlatform.Instance.SignOut();
statusText.text = "Signed Out";
UpdateButtonVisibility(false);
}
public void ViewQuests()
{
Debug.Log("clicked:ViewQuests");
PlayGamesPlatform.Instance.Quests.ShowAllQuestsUI(
(QuestUiResult result, IQuest quest, IQuestMilestone milestone) =>
{
if (result == QuestUiResult.UserRequestsQuestAcceptance)
{
Debug.Log("User Requests Quest Acceptance");
AcceptQuest(quest);
}
if (result == QuestUiResult.UserRequestsMilestoneClaiming)
{
Debug.Log("User Requests Milestone Claim");
ClaimMilestone(milestone);
}
});
}
private void AcceptQuest(IQuest toAccept)
{
Debug.Log("Accepting Quest: " + toAccept);
PlayGamesPlatform.Instance.Quests.Accept(toAccept,
(QuestAcceptStatus status, IQuest quest) =>
{
if (status == QuestAcceptStatus.Success)
{
statusText.text = "Quest Accepted: " + quest.Name;
}
else
{
statusText.text = "Quest Accept Failed: " + status;
}
});
}
private void ClaimMilestone(IQuestMilestone toClaim)
{
Debug.Log("Claiming Milestone: " + toClaim);
PlayGamesPlatform.Instance.Quests.ClaimMilestone(toClaim,
(QuestClaimMilestoneStatus status, IQuest quest, IQuestMilestone milestone) =>
{
if (status == QuestClaimMilestoneStatus.Success)
{
statusText.text = "Milestone Claimed";
}
else
{
statusText.text = "Milestone Claim Failed: " + status;
}
});
}
public void AttackRed()
{
Debug.Log("clicked:AttackRed");
PlayGamesPlatform.Instance.Events.IncrementEvent(GPGSIds.event_red, 1);
}
public void AttackYellow()
{
Debug.Log("clicked:AttackYellow");
PlayGamesPlatform.Instance.Events.IncrementEvent(GPGSIds.event_yellow, 1);
}
public void AttackBlue()
{
Debug.Log("clicked:AttackBlue");
PlayGamesPlatform.Instance.Events.IncrementEvent(GPGSIds.event_blue, 1);
}
public void AttackGreen()
{
Debug.Log("clicked:AttackGreen");
PlayGamesPlatform.Instance.Events.IncrementEvent(GPGSIds.event_green, 1);
}
}
}
| 34 | 94 | 0.55304 | [
"Apache-2.0"
] | Acidburn0zzz/play-games-plugin-for-unity | samples/TrivialQuest/Source/Assets/TrivialQuest/TrivialQuest.cs | 6,054 | C# |
#region License
// Copyright (c) 2011, ClearCanvas Inc.
// All rights reserved.
// http://www.clearcanvas.ca
//
// This software is licensed under the Open Software License v3.0.
// For the complete license, see http://www.clearcanvas.ca/OSLv3.0
#endregion
using ClearCanvas.Common;
using ClearCanvas.Desktop.Configuration.Standard;
namespace ClearCanvas.Desktop.View.WinForms.Configuration
{
[ExtensionOf(typeof (ToolbarConfigurationComponentViewExtensionPoint))]
public sealed class ToolbarConfigurationComponentView : WinFormsView, IApplicationComponentView
{
private ToolbarConfigurationComponent _component;
private ToolbarConfigurationComponentControl _control;
public void SetComponent(IApplicationComponent component)
{
_component = (ToolbarConfigurationComponent)component;
}
public override object GuiElement
{
get
{
if (_control == null)
_control = new ToolbarConfigurationComponentControl(_component);
return _control;
}
}
}
} | 27 | 97 | 0.753411 | [
"Apache-2.0"
] | SNBnani/Xian | Desktop/View/WinForms/Configuration/ToolbarConfigurationComponentView.cs | 1,026 | C# |
// ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See License.txt in the repo root for license information.
// ------------------------------------------------------------
namespace System.Fabric.Data.Services
{
using System.Threading;
using System.Threading.Tasks;
using System.Fabric;
using System.Fabric.Data.Replicator;
/// <summary>
/// Interface usd to manipulate the state provider by the hosting stateful replica.
/// </summary>
public interface IStateProviderBroker
{
/// <summary>
/// Initialization of the state provider broker.
/// </summary>
/// <param name="initializationParameters">State provider initialization data.</param>
void Initialize(StatefulServiceInitializationParameters initializationParameters);
/// <summary>
/// Opens the state provider when the replica opens.
/// </summary>
/// <param name="openMode">Replica is either new or existent.</param>
/// <param name="statefulPartition">Partition hosting this state provider.</param>
/// <param name="stateReplicator">Replicator used by this state provider.</param>
/// <param name="cancellationToken">Propagates notification that operation should be canceled.</param>
/// <returns></returns>
Task OpenAsync(
ReplicaOpenMode openMode,
IStatefulServicePartitionEx statefulPartition,
IAtomicGroupStateReplicatorEx stateReplicator,
CancellationToken cancellationToken);
/// <summary>
/// Called on the state provider when the replica is changing role.
/// </summary>
/// <param name="newRole">New role for the state provider.</param>
/// <param name="cancellationToken">Propagates notification that operation should be canceled.</param>
/// <returns></returns>
Task ChangeRoleAsync(ReplicaRole newRole, CancellationToken cancellationToken);
/// <summary>
/// Called on the state provider when the replica is being closed.
/// </summary>
/// <param name="cancellationToken">Propagates notification that operation should be canceled.</param>
/// <returns></returns>
Task CloseAsync(CancellationToken cancellationToken);
/// <summary>
/// Called on the state provider when the replica is being aborted.
/// </summary>
void Abort();
}
} | 44.206897 | 110 | 0.628315 | [
"MIT"
] | AndreyTretyak/service-fabric | src/prod/src/managed/Api/src/System/Fabric/btree/services/IStateProviderBroker.cs | 2,564 | C# |
namespace NoodleExtensions.HarmonyPatches
{
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using HarmonyLib;
using UnityEngine;
using static NoodleExtensions.NoodleObjectDataManager;
internal static class FakeNoteHelper
{
internal static readonly MethodInfo _boundsNullCheck = AccessTools.Method(typeof(FakeNoteHelper), nameof(BoundsNullCheck));
private static readonly MethodInfo _intersectingObstaclesGetter = AccessTools.PropertyGetter(typeof(PlayerHeadAndObstacleInteraction), nameof(PlayerHeadAndObstacleInteraction.intersectingObstacles));
private static readonly MethodInfo _obstacleFakeCheck = AccessTools.Method(typeof(FakeNoteHelper), nameof(ObstacleFakeCheck));
internal static bool GetFakeNote(NoteController noteController)
{
NoodleNoteData? noodleData = TryGetObjectData<NoodleNoteData>(noteController.noteData);
if (noodleData != null)
{
bool? fake = noodleData.Fake;
if (fake.HasValue && fake.Value)
{
return false;
}
}
return true;
}
internal static bool GetCuttable(NoteData noteData)
{
NoodleNoteData? noodleData = TryGetObjectData<NoodleNoteData>(noteData);
if (noodleData != null)
{
bool? cuttable = noodleData.Cuttable;
if (cuttable.HasValue && !cuttable.Value)
{
return false;
}
}
return true;
}
internal static IEnumerable<CodeInstruction> ObstaclesTranspiler(IEnumerable<CodeInstruction> instructions)
{
return new CodeMatcher(instructions)
.MatchForward(false, new CodeMatch(OpCodes.Callvirt, _intersectingObstaclesGetter))
.Advance(1)
.Insert(new CodeInstruction(OpCodes.Call, _obstacleFakeCheck))
.InstructionEnumeration();
}
private static bool BoundsNullCheck(ObstacleController obstacleController)
{
return obstacleController.bounds.size == Vector3.zero;
}
private static List<ObstacleController> ObstacleFakeCheck(List<ObstacleController> intersectingObstacles)
{
return intersectingObstacles.Where(n =>
{
NoodleObstacleData? noodleData = TryGetObjectData<NoodleObstacleData>(n.obstacleData);
if (noodleData != null)
{
bool? fake = noodleData.Fake;
if (fake.HasValue && fake.Value)
{
return false;
}
}
return true;
}).ToList();
}
}
}
| 36.024691 | 207 | 0.598698 | [
"MIT"
] | Aeroluna/NoodleExtensions | NoodleExtensions/HarmonyPatches/FakeNotes/FakeNoteHelper.cs | 2,920 | C# |
//
// UriQueryBuilderTests.cs
//
// Authors:
// Olivier Dufour <olivier.duff@gmail.com>
// Alan McGovern <alan.mcgovern@gmail.com>
//
// Copyright (C) 2009 Olivier Dufour
// Alan McGovern
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using NUnit.Framework;
namespace MonoTorrent.Common
{
[TestFixture]
public class UriQueryBuilderTest
{
[Test]
public void TestToString ()
{
UriQueryBuilder bld = new UriQueryBuilder ("http://mytest.com/announce.aspx?key=1");
bld.Add ("key", 2);
bld.Add ("foo", 2);
bld.Add ("foo", "bar");
Assert.AreEqual (new Uri ("http://mytest.com/announce.aspx?key=2&foo=bar"), bld.ToUri (), "#1");
bld = new UriQueryBuilder ("http://mytest.com/announce.aspx?passkey=1");
bld.Add ("key", 2);
Assert.AreEqual (new Uri ("http://mytest.com/announce.aspx?passkey=1&key=2"), bld.ToUri (), "#2");
bld = new UriQueryBuilder ("http://mytest.com/announce.aspx");
Assert.AreEqual (new Uri ("http://mytest.com/announce.aspx"), bld.ToUri (), "#3");
bld = new UriQueryBuilder ("http://mytest.com/announce.aspx");
byte[] infoHash = new byte[] { 0x01, 0x47, 0xff, 0xaa, 0xbb, 0xcc };
bld.Add ("key", UriHelper.UrlEncode (infoHash));
Assert.AreEqual (new Uri ("http://mytest.com/announce.aspx?key=%01G%ff%aa%bb%cc"), bld.ToUri (), "#4");
}
[Test]
public void ContainQuery ()
{
UriQueryBuilder bld = new UriQueryBuilder ("http://mytest.com/announce.aspx?key=1&foo=bar");
Assert.IsTrue (bld.Contains ("key"), "#1");
Assert.IsTrue (bld.Contains ("foo"), "#2");
Assert.IsFalse (bld.Contains ("bar"), "#3");
}
[Test]
public void CaseInsensitiveTest ()
{
UriQueryBuilder b = new UriQueryBuilder ("http://www.example.com?first=1&second=2&third=4");
Assert.IsTrue (b.Contains ("FiRsT"));
Assert.AreEqual (b["FiRst"], "1");
}
[Test]
public void AddParams ()
{
UriQueryBuilder b = new UriQueryBuilder ("http://example.com");
b["Test"] = "2";
b["Test"] = "7";
Assert.AreEqual ("7", b["Test"], "#1");
}
}
} | 36.88172 | 115 | 0.61137 | [
"MIT"
] | OneFingerCodingWarrior/monotorrent | src/MonoTorrent.Tests/Common/UriQueryBuilderTests.cs | 3,432 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Microsoft.ProgramSynthesis.Extraction.Text.Sample")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("Microsoft.ProgramSynthesis.Extraction.Text.Sample")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("80fa46f0-36e2-4a1a-b4ec-414676d2a38d")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("2.0.1")]
[assembly: AssemblyInformationalVersion("2.0.1")]
[assembly: AssemblyFileVersion("2.0.1.0")]
| 40.210526 | 84 | 0.755236 | [
"MIT"
] | optician-tool/Optician-Tool | Optician-Standalone/comparisons/prose/Extraction.Text/Properties/AssemblyInfo.cs | 1,531 | C# |
using System;
using System.Linq.Expressions;
using JetBrains.Annotations;
using Sitko.ModelSelector.Base;
namespace Sitko.ModelSelector.Predicates
{
public class GreaterThanPredicate<TModel, TProperty> : SinglePredicate<TModel, TProperty>
{
public GreaterThanPredicate(Expression<Func<TModel, TProperty>> property, TProperty value)
: base(property, value)
{
}
[UsedImplicitly]
public GreaterThanPredicate(string propertyName, TProperty value) : base(propertyName, value)
{
}
public override PredicateType Type { get; } = PredicateType.GreaterThan;
public override string ToDynamicLinqString(int index)
{
return $"{PropertyName}>@{index}";
}
}
} | 28.62963 | 101 | 0.668823 | [
"MIT"
] | sitkoru/ModelSelector | Predicates/GreaterThanPredicate.cs | 775 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace Petzak
{
public class CameraController : MonoBehaviour
{
//public static CameraController main = new CameraController();
//public Camera[] cameras;
public static int currentCameraIndex;
private CameraController()
{
//Camera.GetAllCameras(cameras);
}
//public static CameraController GetInstance()
//{
// if (main == null)
// main = new CameraController();
// return main;
//}
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
}
}
} | 21.842105 | 72 | 0.528916 | [
"MIT"
] | apetzak/255-LD | Assets/Petzak/Scripts/CameraController.cs | 832 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
namespace WebApplication6.Content
{
public class PrivacyModel : PageModel
{
public void OnGet()
{
}
}
} | 19.5625 | 42 | 0.709265 | [
"Apache-2.0"
] | tangdf/RazorPagesMultipleRootDirectory | RazorPagesMultipleRootDirectory/Content/Privacy.cshtml.cs | 315 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("3.FirstAlbum")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("3.FirstAlbum")]
[assembly: AssemblyCopyright("Copyright © 2018")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("1a19468f-1fe0-4210-bebf-116fcc6d167f")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 37.621622 | 84 | 0.746408 | [
"MIT"
] | BorisLechev/Programming-Basics | Documents/Github/Programming-Fundamentals/11. Programming Fundamentals Extended/Exams/Extended Exam - 15.04.2018/3.FirstAlbum/Properties/AssemblyInfo.cs | 1,395 | C# |
using Quasar.Client.Extensions;
using Quasar.Client.Helper;
using Quasar.Client.Registry;
using Quasar.Common.Messages;
using Quasar.Common.Models;
using Quasar.Common.Networking;
using System;
namespace Quasar.Client.Messages
{
public class RegistryHandler : IMessageProcessor
{
public bool CanExecute(IMessage message) => message is DoLoadRegistryKey ||
message is DoCreateRegistryKey ||
message is DoDeleteRegistryKey ||
message is DoRenameRegistryKey ||
message is DoCreateRegistryValue ||
message is DoDeleteRegistryValue ||
message is DoRenameRegistryValue ||
message is DoChangeRegistryValue;
public bool CanExecuteFrom(ISender sender) => true;
public void Execute(ISender sender, IMessage message)
{
switch (message)
{
case DoLoadRegistryKey msg:
Execute(sender, msg);
break;
case DoCreateRegistryKey msg:
Execute(sender, msg);
break;
case DoDeleteRegistryKey msg:
Execute(sender, msg);
break;
case DoRenameRegistryKey msg:
Execute(sender, msg);
break;
case DoCreateRegistryValue msg:
Execute(sender, msg);
break;
case DoDeleteRegistryValue msg:
Execute(sender, msg);
break;
case DoRenameRegistryValue msg:
Execute(sender, msg);
break;
case DoChangeRegistryValue msg:
Execute(sender, msg);
break;
}
}
private void Execute(ISender client, DoLoadRegistryKey message)
{
GetRegistryKeysResponse responsePacket = new GetRegistryKeysResponse();
try
{
RegistrySeeker seeker = new RegistrySeeker();
seeker.BeginSeeking(message.RootKeyName);
responsePacket.Matches = seeker.Matches;
responsePacket.IsError = false;
}
catch (Exception e)
{
responsePacket.IsError = true;
responsePacket.ErrorMsg = e.Message;
}
responsePacket.RootKey = message.RootKeyName;
client.Send(responsePacket);
}
private void Execute(ISender client, DoCreateRegistryKey message)
{
GetCreateRegistryKeyResponse responsePacket = new GetCreateRegistryKeyResponse();
string errorMsg;
string newKeyName = "";
try
{
responsePacket.IsError = !(RegistryEditor.CreateRegistryKey(message.ParentPath, out newKeyName, out errorMsg));
}
catch (Exception ex)
{
responsePacket.IsError = true;
errorMsg = ex.Message;
}
responsePacket.ErrorMsg = errorMsg;
responsePacket.Match = new RegSeekerMatch
{
Key = newKeyName,
Data = RegistryKeyHelper.GetDefaultValues(),
HasSubKeys = false
};
responsePacket.ParentPath = message.ParentPath;
client.Send(responsePacket);
}
private void Execute(ISender client, DoDeleteRegistryKey message)
{
GetDeleteRegistryKeyResponse responsePacket = new GetDeleteRegistryKeyResponse();
string errorMsg;
try
{
responsePacket.IsError = !(RegistryEditor.DeleteRegistryKey(message.KeyName, message.ParentPath, out errorMsg));
}
catch (Exception ex)
{
responsePacket.IsError = true;
errorMsg = ex.Message;
}
responsePacket.ErrorMsg = errorMsg;
responsePacket.ParentPath = message.ParentPath;
responsePacket.KeyName = message.KeyName;
client.Send(responsePacket);
}
private void Execute(ISender client, DoRenameRegistryKey message)
{
GetRenameRegistryKeyResponse responsePacket = new GetRenameRegistryKeyResponse();
string errorMsg;
try
{
responsePacket.IsError = !(RegistryEditor.RenameRegistryKey(message.OldKeyName, message.NewKeyName, message.ParentPath, out errorMsg));
}
catch (Exception ex)
{
responsePacket.IsError = true;
errorMsg = ex.Message;
}
responsePacket.ErrorMsg = errorMsg;
responsePacket.ParentPath = message.ParentPath;
responsePacket.OldKeyName = message.OldKeyName;
responsePacket.NewKeyName = message.NewKeyName;
client.Send(responsePacket);
}
private void Execute(ISender client, DoCreateRegistryValue message)
{
GetCreateRegistryValueResponse responsePacket = new GetCreateRegistryValueResponse();
string errorMsg;
string newKeyName = "";
try
{
responsePacket.IsError = !(RegistryEditor.CreateRegistryValue(message.KeyPath, message.Kind, out newKeyName, out errorMsg));
}
catch (Exception ex)
{
responsePacket.IsError = true;
errorMsg = ex.Message;
}
responsePacket.ErrorMsg = errorMsg;
responsePacket.Value = RegistryKeyHelper.CreateRegValueData(newKeyName, message.Kind, message.Kind.GetDefault());
responsePacket.KeyPath = message.KeyPath;
client.Send(responsePacket);
}
private void Execute(ISender client, DoDeleteRegistryValue message)
{
GetDeleteRegistryValueResponse responsePacket = new GetDeleteRegistryValueResponse();
string errorMsg;
try
{
responsePacket.IsError = !(RegistryEditor.DeleteRegistryValue(message.KeyPath, message.ValueName, out errorMsg));
}
catch (Exception ex)
{
responsePacket.IsError = true;
errorMsg = ex.Message;
}
responsePacket.ErrorMsg = errorMsg;
responsePacket.ValueName = message.ValueName;
responsePacket.KeyPath = message.KeyPath;
client.Send(responsePacket);
}
private void Execute(ISender client, DoRenameRegistryValue message)
{
GetRenameRegistryValueResponse responsePacket = new GetRenameRegistryValueResponse();
string errorMsg;
try
{
responsePacket.IsError = !(RegistryEditor.RenameRegistryValue(message.OldValueName, message.NewValueName, message.KeyPath, out errorMsg));
}
catch (Exception ex)
{
responsePacket.IsError = true;
errorMsg = ex.Message;
}
responsePacket.ErrorMsg = errorMsg;
responsePacket.KeyPath = message.KeyPath;
responsePacket.OldValueName = message.OldValueName;
responsePacket.NewValueName = message.NewValueName;
client.Send(responsePacket);
}
private void Execute(ISender client, DoChangeRegistryValue message)
{
GetChangeRegistryValueResponse responsePacket = new GetChangeRegistryValueResponse();
string errorMsg;
try
{
responsePacket.IsError = !(RegistryEditor.ChangeRegistryValue(message.Value, message.KeyPath, out errorMsg));
}
catch (Exception ex)
{
responsePacket.IsError = true;
errorMsg = ex.Message;
}
responsePacket.ErrorMsg = errorMsg;
responsePacket.KeyPath = message.KeyPath;
responsePacket.Value = message.Value;
client.Send(responsePacket);
}
/// <summary>
/// Disposes all managed and unmanaged resources associated with this message processor.
/// </summary>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
}
}
}
| 36.761317 | 154 | 0.543602 | [
"MIT"
] | wbflike/QuasarRAT | Quasar.Client/Messages/RegistryHandler.cs | 8,935 | C# |
/*Amicable Numbers
https://projecteuler.net/problem=21
Problem Description:
Let d(n) be defined as the sum of proper divisors of n (numbers less than n which divide evenly into n).
If d(a) = b and d(b) = a, where a ≠ b, then a and b are an amicable pair and each of a and b are called amicable numbers.
For example, the proper divisors of 220 are 1, 2, 4, 5, 10, 11, 20, 22, 44, 55 and 110; therefore d(220) = 284. The proper divisors of 284 are 1, 2, 4, 71 and 142; so d(284) = 220.
Evaluate the sum of all the amicable numbers under 10000.*/
using System;
using System.Collections.Generic;
static class Module1
{
private static int finalSum = 0;
private static SortedList<int, int> propDivisorSumList = new SortedList<int, int>();
private static List<int> amicableNumberList = new List<int>();
public static int GetDivisorsSum(int i)
{
int Sum = 0;
for (int n = 1; n <= i / 2; n++)
{
if (i % n == 0)
Sum += n;
}
return Sum;
}
public static void Main()
{
for (int i = 1; i <= 10000; i++)
propDivisorSumList.Add(i, GetDivisorsSum(i));
foreach (var Item in propDivisorSumList)
{
if (GetDivisorsSum(Item.Value) == Item.Key)
{
if (Item.Value != Item.Key)
{
if ((!amicableNumberList.Contains(Item.Value)))
amicableNumberList.Add(Item.Value);
if ((!amicableNumberList.Contains(Item.Key)))
amicableNumberList.Add(Item.Key);
}
}
}
foreach (int Item in amicableNumberList)
finalSum += Item;
Console.Write(finalSum + "\n");
//Answer: 31626
}
}
| 30.423729 | 180 | 0.567688 | [
"MIT"
] | Christian-Pickett/Euler_Project | 20_through_29/prob21.cs | 1,797 | C# |
namespace Cordy.AST
{
public sealed class Event : FunctionalMember
{
public Event(EventDef def, BasicNode body)
: base(def, body)
{}
}
}
| 16.916667 | 51 | 0.497537 | [
"MIT"
] | The-White-Dragon/Cordy-Sharp | Cordy/AST/TypeMembers/Declarations/Event.cs | 205 | C# |
using CharlieBackend.Business.Services.FileServices.Importers;
using CharlieBackend.Business.Services.FileServices.ImportFileServices.Importers;
using CharlieBackend.Business.Services.FileServices.ImportFileServices.ImportReaders;
using CharlieBackend.Business.Services.Interfaces;
using CharlieBackend.Core.DTO.Export;
using CharlieBackend.Core.DTO.StudentGroups;
using CharlieBackend.Core.DTO.Theme;
using CharlieBackend.Core.Models.ResultModel;
using Microsoft.AspNetCore.Http;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace CharlieBackend.Business.Services.FileServices.ImportFileServices
{
public class ServiceImport : IServiseImport
{
private readonly IFileReaderProvider _provider;
private readonly IStudentService _studentService;
private readonly IStudentGroupService _studentGroupService;
private readonly IAccountService _accountService;
private readonly IThemeService _themeService;
public ServiceImport(IFileReaderProvider provider,
IStudentService studentService,
IStudentGroupService studentGroupService,
IAccountService accountService,
IThemeService themeService)
{
_provider = provider;
_studentService = studentService;
_studentGroupService = studentGroupService;
_accountService = accountService;
_themeService = themeService;
}
public async Task<Result<GroupWithStudentsDto>> ImportGroupAsync(
IFormFile file, CreateStudentGroupDto group)
{
using FileService fileService = new FileService();
var fileReader = GetImportReader(file, fileService);
if (fileReader.Error != null)
{
return Result<GroupWithStudentsDto>.GetError(
fileReader.Error.Code,
fileReader.Error.Message);
}
string filePath = await fileService.UploadFileAsync(file);
var accounts = await fileReader.Data.ReadAccountsAsync(filePath);
var groupImporter = new StudentGroupImporter(_studentService,
_studentGroupService, _accountService);
var result = await groupImporter.ImportGroupAsync(group, accounts.Data);
return result;
}
public async Task<Result<IList<ThemeDto>>> ImportThemesAsync(IFormFile file)
{
using FileService fileService = new FileService();
var importOperator = GetImportReader(file, fileService);
if (importOperator.Error != null)
{
return Result<IList<ThemeDto>>.GetError(
importOperator.Error.Code,
importOperator.Error.Message);
}
var filePath = await fileService.UploadFileAsync(file);
var themes = await importOperator.Data.ReadThemesAsync(filePath);
var themeImporter = new ThemeImporter(_themeService);
var themeResult = await themeImporter.ImportThemesAsync(themes.Data);
return themeResult;
}
public Result<IFileReader> GetImportReader(IFormFile file,
FileService fileService)
{
if (file == null)
{
return Result<IFileReader>.GetError(ErrorCode.ValidationError,
"File was not provided");
}
FileExtension extension = default;
if (!fileService.IsFileExtensionValid(file, out extension))
{
return Result<IFileReader>.GetError(
ErrorCode.ValidationError,
"File extension not supported");
}
var importReader = _provider.GetFileReader(extension);
if (importReader == null)
{
return Result<IFileReader>.GetError(ErrorCode.ValidationError,
"Extension wasn't chosen");
}
else
{
return Result<IFileReader>.GetSuccess(importReader);
}
}
}
} | 36.495652 | 85 | 0.631403 | [
"MIT"
] | ViktorMarhitich/WhatBackend | CharlieBackend.Business/Services/FileServices/ImportFileServices/ServiceImport.cs | 4,199 | 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 comprehend-2017-11-27.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.Comprehend.Model
{
/// <summary>
/// This is the response object from the ListDocumentClassifiers operation.
/// </summary>
public partial class ListDocumentClassifiersResponse : AmazonWebServiceResponse
{
private List<DocumentClassifierProperties> _documentClassifierPropertiesList = new List<DocumentClassifierProperties>();
private string _nextToken;
/// <summary>
/// Gets and sets the property DocumentClassifierPropertiesList.
/// <para>
/// A list containing the properties of each job returned.
/// </para>
/// </summary>
public List<DocumentClassifierProperties> DocumentClassifierPropertiesList
{
get { return this._documentClassifierPropertiesList; }
set { this._documentClassifierPropertiesList = value; }
}
// Check to see if DocumentClassifierPropertiesList property is set
internal bool IsSetDocumentClassifierPropertiesList()
{
return this._documentClassifierPropertiesList != null && this._documentClassifierPropertiesList.Count > 0;
}
/// <summary>
/// Gets and sets the property NextToken.
/// <para>
/// Identifies the next page of results to return.
/// </para>
/// </summary>
[AWSProperty(Min=1)]
public string NextToken
{
get { return this._nextToken; }
set { this._nextToken = value; }
}
// Check to see if NextToken property is set
internal bool IsSetNextToken()
{
return this._nextToken != null;
}
}
} | 33.298701 | 128 | 0.663807 | [
"Apache-2.0"
] | ChristopherButtars/aws-sdk-net | sdk/src/Services/Comprehend/Generated/Model/ListDocumentClassifiersResponse.cs | 2,564 | C# |
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata;
using Projeto_WSTower.Domains;
namespace Projeto_WSTower.Contexts
{
public partial class Projeto_WSTowerContext : DbContext
{
public Projeto_WSTowerContext()
{
}
public Projeto_WSTowerContext(DbContextOptions<Projeto_WSTowerContext> options)
: base(options)
{
}
public virtual DbSet<Jogador> Jogador { get; set; }
public virtual DbSet<Jogo> Jogo { get; set; }
public virtual DbSet<Selecao> Selecao { get; set; }
public virtual DbSet<Usuario> Usuario { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
if (!optionsBuilder.IsConfigured)
{
#warning To protect potentially sensitive information in your connection string, you should move it out of source code. See http://go.microsoft.com/fwlink/?LinkId=723263 for guidance on storing connection strings.
optionsBuilder.UseSqlServer("Data Source=LAPTOP-H6D1FPPQ\\SQLEXPRESS; Initial Catalog=Campeonato; Integrated Security=True");
}
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Jogador>(entity =>
{
entity.Property(e => e.Foto).HasColumnType("image");
entity.Property(e => e.Informacoes)
.IsRequired()
.HasColumnType("text");
entity.Property(e => e.Nascimento).HasColumnType("datetime");
entity.Property(e => e.Nome)
.IsRequired()
.HasMaxLength(255)
.IsUnicode(false);
entity.Property(e => e.Posicao)
.IsRequired()
.HasMaxLength(255)
.IsUnicode(false);
entity.Property(e => e.QtdecartoesAmarelo).HasColumnName("QTDECartoesAmarelo");
entity.Property(e => e.QtdecartoesVermelho).HasColumnName("QTDECartoesVermelho");
entity.Property(e => e.Qtdefaltas).HasColumnName("QTDEFaltas");
entity.Property(e => e.Qtdegols).HasColumnName("QTDEGols");
entity.Property(e => e.SelecaoId).HasColumnName("SelecaoID");
entity.HasOne(d => d.Selecao)
.WithMany(p => p.Jogador)
.HasForeignKey(d => d.SelecaoId)
.HasConstraintName("FK__Jogador__Selecao__2A4B4B5E");
});
modelBuilder.Entity<Jogo>(entity =>
{
entity.Property(e => e.Data).HasColumnType("datetime");
entity.Property(e => e.Estadio)
.IsRequired()
.HasMaxLength(255)
.IsUnicode(false);
entity.HasOne(d => d.SelecaoCasaNavigation)
.WithMany(p => p.JogoSelecaoCasaNavigation)
.HasForeignKey(d => d.SelecaoCasa)
.HasConstraintName("FK__Jogo__SelecaoCas__2D27B809");
entity.HasOne(d => d.SelecaoVisitanteNavigation)
.WithMany(p => p.JogoSelecaoVisitanteNavigation)
.HasForeignKey(d => d.SelecaoVisitante)
.HasConstraintName("FK__Jogo__SelecaoVis__2E1BDC42");
});
modelBuilder.Entity<Selecao>(entity =>
{
entity.Property(e => e.Bandeira).HasColumnType("image");
entity.Property(e => e.Escalacao)
.HasMaxLength(10)
.IsUnicode(false);
entity.Property(e => e.Nome)
.IsRequired()
.HasMaxLength(255)
.IsUnicode(false);
entity.Property(e => e.Uniforme).HasColumnType("image");
});
modelBuilder.Entity<Usuario>(entity =>
{
entity.HasIndex(e => e.Apelido)
.HasName("UQ__Usuario__571DBAE694A3ED8A")
.IsUnique();
entity.HasIndex(e => e.Email)
.HasName("UQ__Usuario__A9D10534F00A712B")
.IsUnique();
entity.Property(e => e.Apelido)
.IsRequired()
.HasMaxLength(255)
.IsUnicode(false);
entity.Property(e => e.Email)
.IsRequired()
.HasMaxLength(255)
.IsUnicode(false);
entity.Property(e => e.Foto).HasColumnType("image");
entity.Property(e => e.Nome)
.IsRequired()
.HasMaxLength(255)
.IsUnicode(false);
entity.Property(e => e.Senha)
.IsRequired()
.HasMaxLength(255)
.IsUnicode(false);
});
OnModelCreatingPartial(modelBuilder);
}
partial void OnModelCreatingPartial(ModelBuilder modelBuilder);
}
}
| 35.520548 | 213 | 0.531431 | [
"MIT"
] | AnaLauraFeltrim/Projeto2Semestre | Projeto WSTower/Projeto WSTower/Contexts/Projeto_WSTowerContext.cs | 5,188 | C# |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.CodeFixes.AddImport;
using Microsoft.CodeAnalysis.CSharp.Diagnostics;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Editing;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Shared.Options;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics.AddUsing
{
public partial class AddUsingTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest
{
internal override Tuple<DiagnosticAnalyzer, CodeFixProvider> CreateDiagnosticProviderAndFixer(Workspace workspace)
{
return Tuple.Create<DiagnosticAnalyzer, CodeFixProvider>(
null, new CSharpAddImportCodeFixProvider());
}
private async Task TestAsync(
string initialMarkup,
string expected,
bool systemSpecialCase,
int index = 0,
object fixProviderData = null)
{
await TestAsync(initialMarkup, expected, index, fixProviderData: fixProviderData, options: new Dictionary<OptionKey, object>
{
{ new OptionKey(GenerationOptions.PlaceSystemNamespaceFirst, LanguageNames.CSharp), systemSpecialCase }
});
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddUsing)]
public async Task TestTypeFromMultipleNamespaces1()
{
await TestAsync(
@"class Class { [|IDictionary|] Method() { Foo(); } }",
@"using System.Collections; class Class { IDictionary Method() { Foo(); } }");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddUsing)]
[WorkItem(11241, "https://github.com/dotnet/roslyn/issues/11241")]
public async Task TestAddImportWithCaseChange()
{
await TestAsync(
@"namespace N1
{
public class TextBox { }
}
class Class1 : [|Textbox|] { }
",
@"
using N1;
namespace N1
{
public class TextBox { }
}
class Class1 : TextBox { }
", priority: CodeActionPriority.Low);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddUsing)]
public async Task TestTypeFromMultipleNamespaces2()
{
await TestAsync(
@"class Class { [|IDictionary|] Method() { Foo(); } }",
@"using System.Collections.Generic; class Class { IDictionary Method() { Foo(); } }",
index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddUsing)]
public async Task TestGenericWithNoArgs()
{
await TestAsync(
@"class Class { [|List|] Method() { Foo(); } }",
@"using System.Collections.Generic; class Class { List Method() { Foo(); } }");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddUsing)]
public async Task TestGenericWithCorrectArgs()
{
await TestAsync(
@"class Class { [|List<int>|] Method() { Foo(); } }",
@"using System.Collections.Generic; class Class { List<int> Method() { Foo(); } }");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddUsing)]
public async Task TestGenericWithWrongArgs1()
{
await TestMissingAsync(
@"class Class { [|List<int,string,bool>|] Method() { Foo(); } }");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddUsing)]
public async Task TestGenericWithWrongArgs2()
{
await TestMissingAsync(
@"class Class { [|List<int,string>|] Method() { Foo(); } }");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddUsing)]
public async Task TestGenericInLocalDeclaration()
{
await TestAsync(
@"class Class { void Foo() { [|List<int>|] a = new List<int>(); } }",
@"using System.Collections.Generic; class Class { void Foo() { List<int> a = new List<int>(); } }");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddUsing)]
public async Task TestGenericItemType()
{
await TestAsync(
@"using System.Collections.Generic; class Class { List<[|Int32|]> l; }",
@"using System; using System.Collections.Generic; class Class { List<Int32> l; }");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddUsing)]
public async Task TestGenerateWithExistingUsings()
{
await TestAsync(
@"using System; class Class { [|List<int>|] Method() { Foo(); } }",
@"using System; using System.Collections.Generic; class Class { List<int> Method() { Foo(); } }");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddUsing)]
public async Task TestGenerateInNamespace()
{
await TestAsync(
@"namespace N { class Class { [|List<int>|] Method() { Foo(); } } }",
@"using System.Collections.Generic; namespace N { class Class { List<int> Method() { Foo(); } } }");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddUsing)]
public async Task TestGenerateInNamespaceWithUsings()
{
await TestAsync(
@"namespace N { using System; class Class { [|List<int>|] Method() { Foo(); } } }",
@"namespace N { using System; using System.Collections.Generic; class Class { List<int> Method() { Foo(); } } }");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddUsing)]
public async Task TestExistingUsing()
{
await TestActionCountAsync(
@"using System.Collections.Generic; class Class { [|IDictionary|] Method() { Foo(); } }",
count: 1);
await TestAsync(
@"using System.Collections.Generic; class Class { [|IDictionary|] Method() { Foo(); } }",
@"using System.Collections; using System.Collections.Generic; class Class { IDictionary Method() { Foo(); } }");
}
[WorkItem(541730, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541730")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddUsing)]
public async Task TestAddUsingForGenericExtensionMethod()
{
await TestAsync(
@"using System.Collections.Generic; class Class { void Method(IList<int> args) { args.[|Where|]() } }",
@"using System.Collections.Generic; using System.Linq; class Class { void Method(IList<int> args) { args.Where() } }");
}
[WorkItem(541730, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541730")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddUsing)]
public async Task TestAddUsingForNormalExtensionMethod()
{
await TestAsync(
@"class Class { void Method(Class args) { args.[|Where|]() } } namespace N { static class E { public static void Where(this Class c) { } } }",
@"using N; class Class { void Method(Class args) { args.Where() } } namespace N { static class E { public static void Where(this Class c) { } } }",
parseOptions: Options.Regular);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddUsing)]
public async Task TestOnEnum()
{
await TestAsync(
@"class Class { void Foo() { var a = [|Colors|].Red; } } namespace A { enum Colors {Red, Green, Blue} }",
@"using A; class Class { void Foo() { var a = Colors.Red; } } namespace A { enum Colors {Red, Green, Blue} }");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddUsing)]
public async Task TestOnClassInheritance()
{
await TestAsync(
@"class Class : [|Class2|] { } namespace A { class Class2 { } }",
@"using A; class Class : Class2 { } namespace A { class Class2 { } }");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddUsing)]
public async Task TestOnImplementedInterface()
{
await TestAsync(
@"class Class : [|IFoo|] { } namespace A { interface IFoo { } }",
@"using A; class Class : IFoo { } namespace A { interface IFoo { } }");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddUsing)]
public async Task TestAllInBaseList()
{
await TestAsync(
@"class Class : [|IFoo|], Class2 { } namespace A { class Class2 { } } namespace B { interface IFoo { } } ",
@"using B; class Class : IFoo, Class2 { } namespace A { class Class2 { } } namespace B { interface IFoo { } }");
await TestAsync(
@"using B; class Class : IFoo, [|Class2|] { } namespace A { class Class2 { } } namespace B { interface IFoo { } } ",
@"using A; using B; class Class : IFoo, Class2 { } namespace A { class Class2 { } } namespace B { interface IFoo { } }");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddUsing)]
public async Task TestAttributeUnexpanded()
{
await TestAsync(
@"[[|Obsolete|]]class Class { }",
@"using System; [Obsolete]class Class { }");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddUsing)]
public async Task TestAttributeExpanded()
{
await TestAsync(
@"[[|ObsoleteAttribute|]]class Class { }",
@"using System; [ObsoleteAttribute]class Class { }");
}
[WorkItem(538018, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538018")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddUsing)]
public async Task TestAfterNew()
{
await TestAsync(
@"class Class { void Foo() { List<int> l; l = new [|List<int>|](); } }",
@"using System.Collections.Generic; class Class { void Foo() { List<int> l; l = new List<int>(); } }");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddUsing)]
public async Task TestArgumentsInMethodCall()
{
await TestAsync(
@"class Class { void Test() { Console.WriteLine([|DateTime|].Today); } }",
@"using System; class Class { void Test() { Console.WriteLine(DateTime.Today); } }");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddUsing)]
public async Task TestCallSiteArgs()
{
await TestAsync(
@"class Class { void Test([|DateTime|] dt) { } }",
@"using System; class Class { void Test(DateTime dt) { } }");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddUsing)]
public async Task TestUsePartialClass()
{
await TestAsync(
@"namespace A { public class Class { [|PClass|] c; } } namespace B{ public partial class PClass { } }",
@"using B; namespace A { public class Class { PClass c; } } namespace B{ public partial class PClass { } }");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddUsing)]
public async Task TestGenericClassInNestedNamespace()
{
await TestAsync(
@"namespace A { namespace B { class GenericClass<T> { } } } namespace C { class Class { [|GenericClass<int>|] c; } }",
@"using A.B; namespace A { namespace B { class GenericClass<T> { } } } namespace C { class Class { GenericClass<int> c; } }");
}
[WorkItem(541730, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541730")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddUsing)]
public async Task TestExtensionMethods()
{
await TestAsync(
@"using System . Collections . Generic ; class Foo { void Bar ( ) { var values = new List < int > ( ) ; values . [|Where|] ( i => i > 1 ) ; } } ",
@"using System . Collections . Generic ; using System . Linq ; class Foo { void Bar ( ) { var values = new List < int > ( ) ; values . Where ( i => i > 1 ) ; } } ");
}
[WorkItem(541730, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541730")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddUsing)]
public async Task TestQueryPatterns()
{
await TestAsync(
@"using System . Collections . Generic ; class Foo { void Bar ( ) { var values = new List < int > ( ) ; var q = [|from v in values where v > 1 select v + 10|] ; } } ",
@"using System . Collections . Generic ; using System . Linq ; class Foo { void Bar ( ) { var values = new List < int > ( ) ; var q = from v in values where v > 1 select v + 10 ; } } ");
}
// Tests for Insertion Order
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddUsing)]
public async Task TestSimplePresortedUsings1()
{
await TestAsync(
@"using B; using C; class Class { void Method() { [|Foo|].Bar(); } } namespace D { class Foo { public static void Bar() { } } }",
@"using B; using C; using D; class Class { void Method() { Foo.Bar(); } } namespace D { class Foo { public static void Bar() { } } }");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddUsing)]
public async Task TestSimplePresortedUsings2()
{
await TestAsync(
@"using B; using C; class Class { void Method() { [|Foo|].Bar(); } } namespace A { class Foo { public static void Bar() { } } }",
@"using A; using B; using C; class Class { void Method() { Foo.Bar(); } } namespace A { class Foo { public static void Bar() { } } }");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddUsing)]
public async Task TestSimpleUnsortedUsings1()
{
await TestAsync(
@"using C; using B; class Class { void Method() { [|Foo|].Bar(); } } namespace A { class Foo { public static void Bar() { } } }",
@"using C; using B; using A; class Class { void Method() { Foo.Bar(); } } namespace A { class Foo { public static void Bar() { } } }");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddUsing)]
public async Task TestSimpleUnsortedUsings2()
{
await TestAsync(
@"using D; using B; class Class { void Method() { [|Foo|].Bar(); } } namespace C { class Foo { public static void Bar() { } } }",
@"using D; using B; using C; class Class { void Method() { Foo.Bar(); } } namespace C { class Foo { public static void Bar() { } } }");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddUsing)]
public async Task TestMultiplePresortedUsings1()
{
await TestAsync(
@"using B.X; using B.Y; class Class { void Method() { [|Foo|].Bar(); } } namespace B { class Foo { public static void Bar() { } } }",
@"using B; using B.X; using B.Y; class Class { void Method() { Foo.Bar(); } } namespace B { class Foo { public static void Bar() { } } }");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddUsing)]
public async Task TestMultiplePresortedUsings2()
{
await TestAsync(
@"using B.X;
using B.Y;
class Class {
void Method() {
[|Foo|].Bar();
}
}
namespace B.A {
class Foo {
public static void Bar() { }
}
}",
@"using B.A;
using B.X;
using B.Y;
class Class {
void Method() {
Foo.Bar();
}
}
namespace B.A {
class Foo {
public static void Bar() { }
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddUsing)]
public async Task TestMultiplePresortedUsings3()
{
await TestAsync(
@"using B.X; using B.Y; class Class { void Method() { [|Foo|].Bar(); } } namespace B { namespace A { class Foo { public static void Bar() { } } } }",
@"using B.A; using B.X; using B.Y; class Class { void Method() { Foo.Bar(); } } namespace B { namespace A { class Foo { public static void Bar() { } } } }");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddUsing)]
public async Task TestMultipleUnsortedUsings1()
{
await TestAsync(
@"using B.Y; using B.X; class Class { void Method() { [|Foo|].Bar(); } } namespace B { namespace A { class Foo { public static void Bar() { } } } }",
@"using B.Y; using B.X; using B.A; class Class { void Method() { Foo.Bar(); } } namespace B { namespace A { class Foo { public static void Bar() { } } } }");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddUsing)]
public async Task TestMultipleUnsortedUsings2()
{
await TestAsync(
@"using B.Y; using B.X; class Class { void Method() { [|Foo|].Bar(); } } namespace B { class Foo { public static void Bar() { } } }",
@"using B.Y; using B.X; using B; class Class { void Method() { Foo.Bar(); } } namespace B { class Foo { public static void Bar() { } } }");
}
// System on top cases
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddUsing)]
public async Task TestSimpleSystemSortedUsings1()
{
await TestAsync(
@"using System; using B; class Class { void Method() { [|Foo|].Bar(); } } namespace A { class Foo { public static void Bar() { } } }",
@"using System; using A; using B; class Class { void Method() { Foo.Bar(); } } namespace A { class Foo { public static void Bar() { } } }",
systemSpecialCase: true);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddUsing)]
public async Task TestSimpleSystemSortedUsings2()
{
await TestAsync(
@"using System; using System.Collections.Generic; using B; class Class { void Method() { [|Foo|].Bar(); } } namespace A { class Foo { public static void Bar() { } } }",
@"using System; using System.Collections.Generic; using A; using B; class Class { void Method() { Foo.Bar(); } } namespace A { class Foo { public static void Bar() { } } }",
systemSpecialCase: true);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddUsing)]
public async Task TestSimpleSystemSortedUsings3()
{
await TestAsync(
@"using A; using B; class Class { void Method() { [|Console|].Write(1); } }",
@"using System; using A; using B; class Class { void Method() { Console.Write(1); } }",
systemSpecialCase: true);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddUsing)]
public async Task TestSimpleSystemUnsortedUsings1()
{
await TestAsync(
@"using B; using System; class Class { void Method() { [|Foo|].Bar(); } } namespace A { class Foo { public static void Bar() { } } }",
@"using B; using System; using A; class Class { void Method() { Foo.Bar(); } } namespace A { class Foo { public static void Bar() { } } }",
systemSpecialCase: true);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddUsing)]
public async Task TestSimpleSystemUnsortedUsings2()
{
await TestAsync(
@"using System.Collections.Generic; using System; using B; class Class { void Method() { [|Foo|].Bar(); } } namespace A { class Foo { public static void Bar() { } } }",
@"using System.Collections.Generic; using System; using B; using A; class Class { void Method() { Foo.Bar(); } } namespace A { class Foo { public static void Bar() { } } }",
systemSpecialCase: true);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddUsing)]
public async Task TestSimpleSystemUnsortedUsings3()
{
await TestAsync(
@"using B; using A; class Class { void Method() { [|Console|].Write(1); } }",
@"using B; using A; using System; class Class { void Method() { Console.Write(1); } }",
systemSpecialCase: true);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddUsing)]
public async Task TestSimpleBogusSystemUsings1()
{
await TestAsync(
@"using A.System; class Class { void Method() { [|Console|].Write(1); } }",
@"using System; using A.System; class Class { void Method() { Console.Write(1); } }",
systemSpecialCase: true);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddUsing)]
public async Task TestSimpleBogusSystemUsings2()
{
await TestAsync(
@"using System.System; class Class { void Method() { [|Console|].Write(1); } }",
@"using System; using System.System; class Class { void Method() { Console.Write(1); } }",
systemSpecialCase: true);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddUsing)]
public async Task TestUsingsWithComments()
{
await TestAsync(
@"using System./*...*/.Collections.Generic; class Class { void Method() { [|Console|].Write(1); } }",
@"using System; using System./*...*/.Collections.Generic; class Class { void Method() { Console.Write(1); } }",
systemSpecialCase: true);
}
// System Not on top cases
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddUsing)]
public async Task TestSimpleSystemUnsortedUsings4()
{
await TestAsync(
@"using System; using B; class Class { void Method() { [|Foo|].Bar(); } } namespace A { class Foo { public static void Bar() { } } }",
@"using System; using B; using A; class Class { void Method() { Foo.Bar(); } } namespace A { class Foo { public static void Bar() { } } }",
systemSpecialCase: false);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddUsing)]
public async Task TestSimpleSystemSortedUsings5()
{
await TestAsync(
@"using B; using System; class Class { void Method() { [|Foo|].Bar(); } } namespace A { class Foo { public static void Bar() { } } }",
@"using A; using B; using System; class Class { void Method() { Foo.Bar(); } } namespace A { class Foo { public static void Bar() { } } }",
systemSpecialCase: false);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddUsing)]
public async Task TestSimpleSystemSortedUsings4()
{
await TestAsync(
@"using A; using B; class Class { void Method() { [|Console|].Write(1); } }",
@"using A; using B; using System; class Class { void Method() { Console.Write(1); } }",
systemSpecialCase: false);
}
[WorkItem(538136, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538136")]
[WorkItem(538763, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538763")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddUsing)]
public async Task TestAddUsingForNamespace()
{
await TestMissingAsync(
@"namespace A { class Class { [|C|].Test t; } } namespace B { namespace C { class Test { } } }");
}
[WorkItem(538220, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538220")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddUsing)]
public async Task TestAddUsingForFieldWithFormatting()
{
await TestAsync(
@"class C { [|DateTime|] t; }",
@"using System;
class C { DateTime t; }",
compareTokens: false);
}
[WorkItem(539657, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539657")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddUsing)]
public async Task BugFix5688()
{
await TestAsync(
@"class Program { static void Main ( string [ ] args ) { [|Console|] . Out . NewLine = ""\r\n\r\n"" ; } } ",
@"using System ; class Program { static void Main ( string [ ] args ) { Console . Out . NewLine = ""\r\n\r\n"" ; } } ");
}
[WorkItem(539853, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539853")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddUsing)]
public async Task BugFix5950()
{
await TestAsync(
@"using System.Console; WriteLine([|Expression|].Constant(123));",
@"using System.Console; using System.Linq.Expressions; WriteLine(Expression.Constant(123));",
parseOptions: GetScriptOptions());
}
[WorkItem(540339, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540339")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddUsing)]
public async Task TestAddAfterDefineDirective1()
{
await TestAsync(
@"#define foo
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main(string[] args)
{
[|Console|].WriteLine();
}
}",
@"#define foo
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main(string[] args)
{
Console.WriteLine();
}
}",
compareTokens: false);
}
[WorkItem(540339, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540339")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddUsing)]
public async Task TestAddAfterDefineDirective2()
{
await TestAsync(
@"#define foo
class Program
{
static void Main(string[] args)
{
[|Console|].WriteLine();
}
}",
@"#define foo
using System;
class Program
{
static void Main(string[] args)
{
Console.WriteLine();
}
}",
compareTokens: false);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddUsing)]
public async Task TestAddAfterDefineDirective3()
{
await TestAsync(
@"#define foo
/// Foo
class Program
{
static void Main(string[] args)
{
[|Console|].WriteLine();
}
}",
@"#define foo
using System;
/// Foo
class Program
{
static void Main(string[] args)
{
Console.WriteLine();
}
}",
compareTokens: false);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddUsing)]
public async Task TestAddAfterDefineDirective4()
{
await TestAsync(
@"#define foo
// Foo
class Program
{
static void Main(string[] args)
{
[|Console|].WriteLine();
}
}",
@"#define foo
// Foo
using System;
class Program
{
static void Main(string[] args)
{
Console.WriteLine();
}
}",
compareTokens: false);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddUsing)]
public async Task TestAddAfterExistingBanner()
{
await TestAsync(
@"// Banner
// Banner
class Program
{
static void Main(string[] args)
{
[|Console|].WriteLine();
}
}",
@"// Banner
// Banner
using System;
class Program
{
static void Main(string[] args)
{
Console.WriteLine();
}
}",
compareTokens: false);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddUsing)]
public async Task TestAddAfterExternAlias1()
{
await TestAsync(
@"#define foo
extern alias Foo;
class Program
{
static void Main(string[] args)
{
[|Console|].WriteLine();
}
}",
@"#define foo
extern alias Foo;
using System;
class Program
{
static void Main(string[] args)
{
Console.WriteLine();
}
}",
compareTokens: false);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddUsing)]
public async Task TestAddAfterExternAlias2()
{
await TestAsync(
@"#define foo
extern alias Foo;
using System.Collections;
class Program
{
static void Main(string[] args)
{
[|Console|].WriteLine();
}
}",
@"#define foo
extern alias Foo;
using System;
using System.Collections;
class Program
{
static void Main(string[] args)
{
Console.WriteLine();
}
}",
compareTokens: false);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddUsing)]
public async Task TestWithReferenceDirective()
{
var resolver = new TestMetadataReferenceResolver(assemblyNames: new Dictionary<string, PortableExecutableReference>()
{
{ "exprs", AssemblyMetadata.CreateFromImage(TestResources.NetFX.v4_0_30319.System_Core).GetReference() }
});
await TestAsync(
@"#r ""exprs""
[|Expression|]",
@"#r ""exprs""
using System.Linq.Expressions;
Expression",
parseOptions: GetScriptOptions(),
compilationOptions: TestOptions.ReleaseDll.WithMetadataReferenceResolver(resolver),
compareTokens: false);
}
[WorkItem(542643, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542643")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddUsing)]
public async Task TestAssemblyAttribute()
{
await TestAsync(
@"[ assembly : [|InternalsVisibleTo|] ( ""Project"" ) ] ",
@"using System . Runtime . CompilerServices ; [ assembly : InternalsVisibleTo ( ""Project"" ) ] ");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddUsing)]
public async Task TestDoNotAddIntoHiddenRegion()
{
await TestMissingAsync(
@"#line hidden
using System.Collections.Generic;
#line default
class Program
{
void Main()
{
[|DateTime|] d;
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddUsing)]
public async Task TestAddToVisibleRegion()
{
await TestAsync(
@"#line default
using System.Collections.Generic;
#line hidden
class Program
{
void Main()
{
#line default
[|DateTime|] d;
#line hidden
}
}
#line default",
@"#line default
using System;
using System.Collections.Generic;
#line hidden
class Program
{
void Main()
{
#line default
DateTime d;
#line hidden
}
}
#line default",
compareTokens: false);
}
[WorkItem(545248, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545248")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddUsing)]
public async Task TestVenusGeneration1()
{
await TestMissingAsync(
@"
class C
{
void Foo()
{
#line 1 ""Default.aspx""
using (new [|StreamReader|]()) {
#line default
#line hidden
}
}");
}
[WorkItem(545774, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545774")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddUsing)]
public async Task TestAttribute()
{
var input = @"[ assembly : [|Guid|] ( ""9ed54f84-a89d-4fcd-a854-44251e925f09"" ) ] ";
await TestActionCountAsync(input, 1);
await TestAsync(
input,
@"using System . Runtime . InteropServices ; [ assembly : Guid ( ""9ed54f84-a89d-4fcd-a854-44251e925f09"" ) ] ");
}
[WorkItem(546833, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546833")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddUsing)]
public async Task TestNotOnOverloadResolutionError()
{
await TestMissingAsync(
@"namespace ConsoleApplication1 { class Program { void Main ( ) { var test = new [|Test|] ( """" ) ; } } class Test { } } ");
}
[WorkItem(17020, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddUsing)]
public async Task TestAddUsingForGenericArgument()
{
await TestAsync(
@"namespace ConsoleApplication10 { class Program { static void Main ( string [ ] args ) { var inArgument = new InArgument < [|IEnumerable < int >|] > ( new int [ ] { 1 , 2 , 3 } ) ; } } public class InArgument < T > { public InArgument ( T constValue ) { } } } ",
@"using System . Collections . Generic ; namespace ConsoleApplication10 { class Program { static void Main ( string [ ] args ) { var inArgument = new InArgument < IEnumerable < int > > ( new int [ ] { 1 , 2 , 3 } ) ; } } public class InArgument < T > { public InArgument ( T constValue ) { } } } ");
}
[WorkItem(775448, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/775448")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddUsing)]
public async Task ShouldTriggerOnCS0308()
{
// CS0308: The non-generic type 'A' cannot be used with type arguments
await TestAsync(
@"using System.Collections;
class Test
{
static void Main(string[] args)
{
[|IEnumerable<int>|] f;
}
}",
@"using System.Collections;
using System.Collections.Generic;
class Test
{
static void Main(string[] args)
{
IEnumerable<int> f;
}
}");
}
[WorkItem(838253, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/838253")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddUsing)]
public async Task TestConflictedInaccessibleType()
{
await TestAsync(
@"using System.Diagnostics; namespace N { public class Log { } } class C { static void Main(string[] args) { [|Log|] } }",
@"using System.Diagnostics; using N; namespace N { public class Log { } } class C { static void Main(string[] args) { Log } }",
systemSpecialCase: true);
}
[WorkItem(858085, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/858085")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddUsing)]
public async Task TestConflictedAttributeName()
{
await TestAsync(
@"[[|Description|]]class Description { }",
@"using System.ComponentModel; [Description]class Description { }");
}
[WorkItem(872908, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/872908")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddUsing)]
public async Task TestConflictedGenericName()
{
await TestAsync(
@"using Task = System.AccessViolationException; class X { [|Task<X> x;|] }",
@"using System.Threading.Tasks; using Task = System.AccessViolationException; class X { Task<X> x; }");
}
[WorkItem(913300, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/913300")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddUsing)]
public async Task TestNoDuplicateReport()
{
await TestActionCountInAllFixesAsync(
@"class C
{
void M(P p)
{
[| Console |]
}
static void Main(string[] args)
{
}
}", count: 1);
await TestAsync(
@"class C { void M(P p) { [|Console|] } static void Main(string[] args) { } }",
@"using System; class C { void M(P p) { Console } static void Main(string[] args) { } }");
}
[WorkItem(938296, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/938296")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddUsing)]
public async Task TestNullParentInNode()
{
await TestMissingAsync(
@"using System.Collections.Generic;
class MultiDictionary<K, V> : Dictionary<K, HashSet<V>>
{
void M()
{
new HashSet<V>([|Comparer|]);
}
}");
}
[WorkItem(968303, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/968303")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddUsing)]
public async Task TestMalformedUsingSection()
{
await TestMissingAsync("[ class Class { [|List<|] }");
}
[WorkItem(875899, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/875899")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddUsing)]
public async Task TestAddUsingsWithExternAlias()
{
const string InitialWorkspace = @"
<Workspace>
<Project Language=""C#"" AssemblyName=""lib"" CommonReferences=""true"">
<Document FilePath=""lib.cs"">
namespace ProjectLib
{
public class Project
{
}
}
</Document>
</Project>
<Project Language=""C#"" AssemblyName=""Console"" CommonReferences=""true"">
<ProjectReference Alias=""P"">lib</ProjectReference>
<Document FilePath=""Program.cs"">
namespace ExternAliases
{
class Program
{
static void Main(string[] args)
{
Project p = new [|Project()|];
}
}
}
</Document>
</Project>
</Workspace>";
const string ExpectedDocumentText = @"extern alias P;
using P::ProjectLib;
namespace ExternAliases
{
class Program
{
static void Main(string[] args)
{
Project p = new Project();
}
}
}
";
await TestAsync(InitialWorkspace, ExpectedDocumentText);
}
[WorkItem(875899, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/875899")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddUsing)]
public async Task TestAddUsingsWithPreExistingExternAlias()
{
const string InitialWorkspace = @"
<Workspace>
<Project Language=""C#"" AssemblyName=""lib"" CommonReferences=""true"">
<Document FilePath=""lib.cs"">
namespace ProjectLib
{
public class Project
{
}
}
namespace AnotherNS
{
public class AnotherClass
{
}
}
</Document>
</Project>
<Project Language=""C#"" AssemblyName=""Console"" CommonReferences=""true"">
<ProjectReference Alias=""P"">lib</ProjectReference>
<Document FilePath=""Program.cs"">
extern alias P;
using P::ProjectLib;
namespace ExternAliases
{
class Program
{
static void Main(string[] args)
{
Project p = new Project();
var x = new [|AnotherClass()|];
}
}
}
</Document>
</Project>
</Workspace>";
const string ExpectedDocumentText = @"extern alias P;
using P::AnotherNS;
using P::ProjectLib;
namespace ExternAliases
{
class Program
{
static void Main(string[] args)
{
Project p = new Project();
var x = new [|AnotherClass()|];
}
}
}
";
await TestAsync(InitialWorkspace, ExpectedDocumentText);
}
[WorkItem(875899, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/875899")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddUsing)]
public async Task TestAddUsingsNoExtern()
{
const string InitialWorkspace = @"
<Workspace>
<Project Language=""C#"" AssemblyName=""lib"" CommonReferences=""true"">
<Document FilePath=""lib.cs"">
namespace AnotherNS
{
public class AnotherClass
{
}
}
</Document>
</Project>
<Project Language=""C#"" AssemblyName=""Console"" CommonReferences=""true"">
<ProjectReference Alias=""P"">lib</ProjectReference>
<Document FilePath=""Program.cs"">
using P::AnotherNS;
namespace ExternAliases
{
class Program
{
static void Main(string[] args)
{
var x = new [|AnotherClass()|];
}
}
}
</Document>
</Project>
</Workspace>";
const string ExpectedDocumentText = @"extern alias P;
using P::AnotherNS;
namespace ExternAliases
{
class Program
{
static void Main(string[] args)
{
var x = new AnotherClass();
}
}
}
";
await TestAsync(InitialWorkspace, ExpectedDocumentText);
}
[WorkItem(875899, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/875899")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddUsing)]
public async Task TestAddUsingsNoExternFilterGlobalAlias()
{
await TestAsync(
@"class Program
{
static void Main(string[] args)
{
[|INotifyPropertyChanged.PropertyChanged|]
}
}",
@"using System.ComponentModel;
class Program
{
static void Main(string[] args)
{
INotifyPropertyChanged.PropertyChanged
}
}");
}
[WorkItem(916368, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/916368")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddUsing)]
public async Task TestAddUsingForCref()
{
var initialText =
@"/// <summary>
/// This is just like <see cref='[|INotifyPropertyChanged|]'/>, but this one is mine.
/// </summary>
interface MyNotifyPropertyChanged { }";
var expectedText =
@"using System.ComponentModel;
/// <summary>
/// This is just like <see cref='INotifyPropertyChanged'/>, but this one is mine.
/// </summary>
interface MyNotifyPropertyChanged { }";
var options = new CSharpParseOptions(documentationMode: DocumentationMode.Diagnose);
await TestAsync(initialText, expectedText, parseOptions: options);
}
[WorkItem(916368, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/916368")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddUsing)]
public async Task TestAddUsingForCref2()
{
var initialText =
@"/// <summary>
/// This is just like <see cref='[|INotifyPropertyChanged.PropertyChanged|]'/>, but this one is mine.
/// </summary>
interface MyNotifyPropertyChanged { }";
var expectedText =
@"using System.ComponentModel;
/// <summary>
/// This is just like <see cref='INotifyPropertyChanged.PropertyChanged'/>, but this one is mine.
/// </summary>
interface MyNotifyPropertyChanged { }";
var options = new CSharpParseOptions(documentationMode: DocumentationMode.Diagnose);
await TestAsync(initialText, expectedText, parseOptions: options);
}
[WorkItem(916368, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/916368")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddUsing)]
public async Task TestAddUsingForCref3()
{
var initialText =
@"namespace N1
{
public class D { }
}
public class MyClass
{
public static explicit operator N1.D (MyClass f)
{
return default(N1.D);
}
}
/// <seealso cref='MyClass.explicit operator [|D(MyClass)|]'/>
public class MyClass2
{
}";
var expectedText =
@"using N1;
namespace N1
{
public class D { }
}
public class MyClass
{
public static explicit operator N1.D(MyClass f)
{
return default(N1.D);
}
}
/// <seealso cref='MyClass.explicit operator D(MyClass)'/>
public class MyClass2
{
}";
var options = new CSharpParseOptions(documentationMode: DocumentationMode.Diagnose);
await TestAsync(initialText, expectedText, parseOptions: options);
}
[WorkItem(916368, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/916368")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddUsing)]
public async Task TestAddUsingForCref4()
{
var initialText =
@"namespace N1
{
public class D { }
}
/// <seealso cref='[|Test(D)|]'/>
public class MyClass
{
public void Test(N1.D i)
{
}
}";
var expectedText =
@"using N1;
namespace N1
{
public class D { }
}
/// <seealso cref='Test(D)'/>
public class MyClass
{
public void Test(N1.D i)
{
}
}";
var options = new CSharpParseOptions(documentationMode: DocumentationMode.Diagnose);
await TestAsync(initialText, expectedText, parseOptions: options);
}
[WorkItem(773614, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/773614")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddUsing)]
public async Task TestAddStaticType()
{
var initialText =
@"using System;
public static class Outer
{
[AttributeUsage(AttributeTargets.All)]
public class MyAttribute : Attribute
{
}
}
[[|My|]]
class Test
{}";
var expectedText =
@"using System;
using static Outer;
public static class Outer
{
[AttributeUsage(AttributeTargets.All)]
public class MyAttribute : Attribute
{
}
}
[My]
class Test
{}";
await TestAsync(initialText, expectedText);
}
[WorkItem(773614, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/773614")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddUsing)]
public async Task TestAddStaticType2()
{
var initialText =
@"using System;
public static class Outer
{
public static class Inner
{
[AttributeUsage(AttributeTargets.All)]
public class MyAttribute : Attribute
{
}
}
}
[[|My|]]
class Test
{}";
var expectedText =
@"using System;
using static Outer.Inner;
public static class Outer
{
public static class Inner
{
[AttributeUsage(AttributeTargets.All)]
public class MyAttribute : Attribute
{
}
}
}
[My]
class Test
{}";
await TestAsync(initialText, expectedText);
}
[WorkItem(773614, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/773614")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddUsing)]
public async Task TestAddStaticType3()
{
await TestAsync(
@"using System ; public static class Outer { public class Inner { [ AttributeUsage ( AttributeTargets . All ) ] public class MyAttribute : Attribute { } } } [ [|My|] ] class Test { } ",
@"using System ; using static Outer . Inner ; public static class Outer { public class Inner { [ AttributeUsage ( AttributeTargets . All ) ] public class MyAttribute : Attribute { } } } [ My ] class Test { } ");
}
[WorkItem(773614, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/773614")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddUsing)]
public async Task TestAddStaticType4()
{
var initialText =
@"using System;
using Outer;
public static class Outer
{
public static class Inner
{
[AttributeUsage(AttributeTargets.All)]
public class MyAttribute : Attribute
{
}
}
}
[[|My|]]
class Test
{}";
var expectedText =
@"using System;
using Outer;
using static Outer.Inner;
public static class Outer
{
public static class Inner
{
[AttributeUsage(AttributeTargets.All)]
public class MyAttribute : Attribute
{
}
}
}
[My]
class Test
{}";
await TestAsync(initialText, expectedText);
}
[WorkItem(991463, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/991463")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddUsing)]
public async Task TestAddInsideUsingDirective1()
{
await TestAsync(
@"namespace ns { using B = [|Byte|]; }",
@"using System; namespace ns { using B = Byte; }");
}
[WorkItem(991463, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/991463")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddUsing)]
public async Task TestAddInsideUsingDirective2()
{
await TestAsync(
@"using System.Collections; namespace ns { using B = [|Byte|]; }",
@"using System; using System.Collections; namespace ns { using B = Byte; }");
}
[WorkItem(991463, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/991463")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddUsing)]
public async Task TestAddInsideUsingDirective3()
{
await TestAsync(
@"namespace ns2 { namespace ns3 { namespace ns { using B = [|Byte|]; namespace ns4 { } } } }",
@"using System; namespace ns2 { namespace ns3 { namespace ns { using B = Byte; namespace ns4 { } } } }");
}
[WorkItem(991463, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/991463")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddUsing)]
public async Task TestAddInsideUsingDirective4()
{
await TestAsync(
@"namespace ns2 { using System.Collections; namespace ns3 { namespace ns { using System.IO; using B = [|Byte|]; } } }",
@"namespace ns2 { using System; using System.Collections; namespace ns3 { namespace ns { using System.IO; using B = Byte; } } }");
}
[WorkItem(991463, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/991463")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddUsing)]
public async Task TestAddInsideUsingDirective5()
{
await TestAsync(
@"using System.IO;
namespace ns2 {
using System.Diagnostics;
namespace ns3 {
using System.Collections;
namespace ns {
using B = [|Byte|];
}
}
}",
@"using System.IO;
namespace ns2 {
using System.Diagnostics;
namespace ns3 {
using System;
using System.Collections;
namespace ns {
using B = Byte;
}
}
}");
}
[WorkItem(991463, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/991463")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddUsing)]
public async Task TestAddInsideUsingDirective6()
{
await TestMissingAsync(
@"using B = [|Byte|];");
}
[WorkItem(1064748, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064748")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddUsing)]
public async Task TestAddConditionalAccessExpression()
{
var initialText =
@"<Workspace>
<Project Language=""C#"" AssemblyName=""CSAssembly"" CommonReferences=""true"">
<Document FilePath = ""Program"">
public class C
{
void Main(C a)
{
C x = a?[|.B()|];
}
}
</Document>
<Document FilePath = ""Extensions"">
namespace Extensions
{
public static class E
{
public static C B(this C c) { return c; }
}
}
</Document>
</Project>
</Workspace> ";
var expectedText =
@"using Extensions;
public class C
{
void Main(C a)
{
C x = a?.B();
}
}";
await TestAsync(initialText, expectedText);
}
[WorkItem(1064748, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064748")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddUsing)]
public async Task TestAddConditionalAccessExpression2()
{
var initialText =
@"<Workspace>
<Project Language=""C#"" AssemblyName=""CSAssembly"" CommonReferences=""true"">
<Document FilePath = ""Program"">
public class C
{
public E B { get; private set; }
void Main(C a)
{
int? x = a?.B.[|C()|];
}
public class E
{
}
}
</Document>
<Document FilePath = ""Extensions"">
namespace Extensions
{
public static class D
{
public static C.E C(this C.E c) { return c; }
}
}
</Document>
</Project>
</Workspace> ";
var expectedText =
@"using Extensions;
public class C
{
public E B { get; private set; }
void Main(C a)
{
int? x = a?.B.C();
}
public class E
{
}
}";
await TestAsync(initialText, expectedText);
}
[WorkItem(1089138, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1089138")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddUsing)]
public async Task TestAmbiguousUsingName()
{
await TestAsync(
@"namespace ClassLibrary1 {
using System ;
public class SomeTypeUser {
[|SomeType|] field ;
}
}
namespace SubNamespaceName {
using System ;
class SomeType { }
}
namespace ClassLibrary1 . SubNamespaceName {
using System ;
class SomeOtherFile { }
} ",
@"namespace ClassLibrary1 {
using System ;
using global::SubNamespaceName ;
public class SomeTypeUser {
SomeType field ;
}
}
namespace SubNamespaceName {
using System ;
class SomeType { }
}
namespace ClassLibrary1 . SubNamespaceName {
using System ;
class SomeOtherFile { }
} ");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddUsing)]
public async Task TestAddUsingInDirective()
{
await TestAsync(
@"#define DEBUG
#if DEBUG
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Text;
#endif
class Program { static void Main ( string [ ] args ) { var a = [|File|] . OpenRead ( """" ) ; } } ",
@"#define DEBUG
#if DEBUG
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Text;
using System.IO;
#endif
class Program { static void Main ( string [ ] args ) { var a = File . OpenRead ( """" ) ; } } ");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddUsing)]
public async Task TestAddUsingInDirective2()
{
await TestAsync(
@"#define DEBUG
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
#if DEBUG
using System.Text;
#endif
class Program { static void Main ( string [ ] args ) { var a = [|File|] . OpenRead ( """" ) ; } } ",
@"#define DEBUG
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.IO;
#if DEBUG
using System.Text;
#endif
class Program { static void Main ( string [ ] args ) { var a = File . OpenRead ( """" ) ; } } ", compareTokens: false);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddUsing)]
public async Task TestAddUsingInDirective3()
{
await TestAsync(
@"#define DEBUG
using System;
using System.Collections.Generic;
#if DEBUG
using System.Text;
#endif
using System.Linq;
using System.Threading.Tasks;
class Program { static void Main ( string [ ] args ) { var a = [|File|] . OpenRead ( """" ) ; } } ",
@"#define DEBUG
using System;
using System.Collections.Generic;
#if DEBUG
using System.Text;
#endif
using System.Linq;
using System.Threading.Tasks;
using System.IO;
class Program { static void Main ( string [ ] args ) { var a = File . OpenRead ( """" ) ; } } ", compareTokens: false);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddUsing)]
public async Task TestAddUsingInDirective4()
{
await TestAsync(
@"#define DEBUG
#if DEBUG
using System;
#endif
using System.Collections.Generic;
using System.Text;
using System.Linq;
using System.Threading.Tasks;
class Program { static void Main ( string [ ] args ) { var a = [|File|] . OpenRead ( """" ) ; } } ",
@"#define DEBUG
#if DEBUG
using System;
#endif
using System.Collections.Generic;
using System.Text;
using System.Linq;
using System.Threading.Tasks;
using System.IO;
class Program { static void Main ( string [ ] args ) { var a = File . OpenRead ( """" ) ; } } ", compareTokens: false);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddUsing)]
public async Task TestInaccessibleExtensionMethod()
{
const string initial = @"
namespace N1
{
public static class C
{
private static bool ExtMethod1(this string arg1)
{
return true;
}
}
}
namespace N2
{
class Program
{
static void Main(string[] args)
{
var x = ""str1"".[|ExtMethod1()|];
}
}
}";
await TestMissingAsync(initial);
}
[WorkItem(1116011, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1116011")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddUsing)]
public async Task TestAddUsingForProperty()
{
await TestAsync(
@"using System ; using System . Collections . Generic ; using System . Linq ; using System . Threading . Tasks ; class Program { public BindingFlags BindingFlags { get { return BindingFlags . [|Instance|] ; } } } ",
@"using System ; using System . Collections . Generic ; using System . Linq ; using System . Reflection ; using System . Threading . Tasks ; class Program { public BindingFlags BindingFlags { get { return BindingFlags . Instance ; } } } ");
}
[WorkItem(1116011, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1116011")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddUsing)]
public async Task TestAddUsingForField()
{
await TestAsync(
@"using System ; using System . Collections . Generic ; using System . Linq ; using System . Threading . Tasks ; class Program { public B B { get { return B . [|Instance|] ; } } } namespace A { public class B { public static readonly B Instance ; } } ",
@"using System ; using System . Collections . Generic ; using System . Linq ; using System . Threading . Tasks ; using A ; class Program { public B B { get { return B . Instance ; } } } namespace A { public class B { public static readonly B Instance ; } } ");
}
[WorkItem(1893, "https://github.com/dotnet/roslyn/issues/1893")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddUsing)]
public async Task TestNameSimplification()
{
// Generated using directive must be simplified from "using A.B;" to "using B;" below.
await TestAsync(
@"
namespace A.B
{
class T1 { }
}
namespace A.C
{
using System;
class T2
{
void Test()
{
Console.WriteLine();
[|T1|] t1;
}
}
}",
@"
namespace A.B
{
class T1 { }
}
namespace A.C
{
using System;
using A.B;
class T2
{
void Test()
{
Console.WriteLine();
T1 t1;
}
}
}", systemSpecialCase: true);
}
[WorkItem(935, "https://github.com/dotnet/roslyn/issues/935")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddUsing)]
public async Task TestAddUsingWithOtherExtensionsInScope()
{
await TestAsync(
@"using System . Linq ; using System . Collections ; using X ; namespace X { public static class Ext { public static void ExtMethod ( this int a ) { } } } namespace Y { public static class Ext { public static void ExtMethod ( this int a , int v ) { } } } public class B { static void Main ( ) { var b = 0 ; b . [|ExtMethod|] ( 0 ) ; } } ",
@"using System . Linq ; using System . Collections ; using X ; using Y ; namespace X { public static class Ext { public static void ExtMethod ( this int a ) { } } } namespace Y { public static class Ext { public static void ExtMethod ( this int a , int v ) { } } } public class B { static void Main ( ) { var b = 0 ; b . ExtMethod ( 0 ) ; } } ");
}
[WorkItem(935, "https://github.com/dotnet/roslyn/issues/935")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddUsing)]
public async Task TestAddUsingWithOtherExtensionsInScope2()
{
await TestAsync(
@"using System . Linq ; using System . Collections ; using X ; namespace X { public static class Ext { public static void ExtMethod ( this int ? a ) { } } } namespace Y { public static class Ext { public static void ExtMethod ( this int ? a , int v ) { } } } public class B { static void Main ( ) { var b = new int ? ( ) ; b ? [|. ExtMethod|] ( 0 ) ; } } ",
@"using System . Linq ; using System . Collections ; using X ; using Y ; namespace X { public static class Ext { public static void ExtMethod ( this int ? a ) { } } } namespace Y { public static class Ext { public static void ExtMethod ( this int ? a , int v ) { } } } public class B { static void Main ( ) { var b = new int ? ( ) ; b ? . ExtMethod ( 0 ) ; } } ");
}
[WorkItem(562, "https://github.com/dotnet/roslyn/issues/562")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddUsing)]
public async Task TestAddUsingWithOtherExtensionsInScope3()
{
await TestAsync(
@"using System . Linq ; class C { int i = 0 . [|All|] ( ) ; } namespace X { static class E { public static int All ( this int o ) => 0 ; } } ",
@"using System . Linq ; using X ; class C { int i = 0 . All ( ) ; } namespace X { static class E { public static int All ( this int o ) => 0 ; } } ");
}
[WorkItem(562, "https://github.com/dotnet/roslyn/issues/562")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddUsing)]
public async Task TestAddUsingWithOtherExtensionsInScope4()
{
await TestAsync(
@"using System . Linq ; class C { static void Main ( string [ ] args ) { var a = new int ? ( ) ; int ? i = a ? [|. All|] ( ) ; } } namespace X { static class E { public static int ? All ( this int ? o ) => 0 ; } } ",
@"using System . Linq ; using X ; class C { static void Main ( string [ ] args ) { var a = new int ? ( ) ; int ? i = a ? . All ( ) ; } } namespace X { static class E { public static int ? All ( this int ? o ) => 0 ; } } ");
}
[WorkItem(3080, "https://github.com/dotnet/roslyn/issues/3080")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddUsing)]
public async Task TestNestedNamespaceSimplified()
{
await TestAsync(
@"namespace Microsoft . MyApp {
using Win32 ;
class Program {
static void Main ( string [ ] args ) {
[|SafeRegistryHandle|] h ;
}
}
} ",
@"namespace Microsoft . MyApp {
using Microsoft.Win32 . SafeHandles ;
using Win32 ;
class Program {
static void Main ( string [ ] args ) {
SafeRegistryHandle h ;
}
}
} ");
}
[WorkItem(3080, "https://github.com/dotnet/roslyn/issues/3080")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddUsing)]
public async Task TestNestedNamespaceSimplified2()
{
await TestAsync(
@"namespace Microsoft . MyApp {
using Zin32 ;
class Program {
static void Main ( string [ ] args ) {
[|SafeRegistryHandle|] h ;
}
}
} ",
@"namespace Microsoft . MyApp {
using Microsoft . Win32 . SafeHandles ;
using Zin32 ;
class Program {
static void Main ( string [ ] args ) {
SafeRegistryHandle h ;
}
}
} ");
}
[WorkItem(3080, "https://github.com/dotnet/roslyn/issues/3080")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddUsing)]
public async Task TestNestedNamespaceSimplified3()
{
await TestAsync(
@"namespace Microsoft . MyApp {
using System ;
using Win32 ;
class Program {
static void Main ( string [ ] args ) {
[|SafeRegistryHandle|] h ;
}
}
} ",
@"namespace Microsoft . MyApp {
using System ;
using Microsoft.Win32 . SafeHandles ;
using Win32 ;
class Program {
static void Main ( string [ ] args ) {
SafeRegistryHandle h ;
}
}
} ");
}
[WorkItem(3080, "https://github.com/dotnet/roslyn/issues/3080")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddUsing)]
public async Task TestNestedNamespaceSimplified4()
{
await TestAsync(
@"namespace Microsoft . MyApp {
using System ;
using Zin32 ;
class Program {
static void Main ( string [ ] args ) {
[|SafeRegistryHandle|] h ;
}
}
} ",
@"namespace Microsoft . MyApp {
using System ;
using Microsoft . Win32 . SafeHandles ;
using Zin32 ;
class Program {
static void Main ( string [ ] args ) {
SafeRegistryHandle h ;
}
}
} ");
}
[WorkItem(3080, "https://github.com/dotnet/roslyn/issues/3080")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddUsing)]
public async Task TestNestedNamespaceSimplified5()
{
await TestAsync(
@"namespace Microsoft.MyApp
{
#if true
using Win32;
#else
using System;
#endif
class Program
{
static void Main(string[] args)
{
[|SafeRegistryHandle|] h;
}
}
}",
@"namespace Microsoft.MyApp
{
#if true
using Microsoft.Win32.SafeHandles;
using Win32;
#else
using System;
#endif
class Program
{
static void Main(string[] args)
{
SafeRegistryHandle h;
}
}
}");
}
[WorkItem(3080, "https://github.com/dotnet/roslyn/issues/3080")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddUsing)]
public async Task TestNestedNamespaceSimplified6()
{
await TestAsync(
@"namespace Microsoft.MyApp
{
using System;
#if false
using Win32;
#endif
using Win32;
class Program
{
static void Main(string[] args)
{
[|SafeRegistryHandle|] h;
}
}
}",
@"namespace Microsoft.MyApp
{
using System;
using Microsoft.Win32.SafeHandles;
#if false
using Win32;
#endif
using Win32;
class Program
{
static void Main(string[] args)
{
SafeRegistryHandle h;
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddUsing)]
public async Task TestAddUsingOrdinalUppercase()
{
await TestAsync(
@"namespace A { class A { static void Main ( string [ ] args ) { var b = new [|B|] ( ) ; } } } namespace lowercase { class b { } } namespace Uppercase { class B { } } ",
@"using Uppercase ; namespace A { class A { static void Main ( string [ ] args ) { var b = new B ( ) ; } } } namespace lowercase { class b { } } namespace Uppercase { class B { } } ");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddUsing)]
public async Task TestAddUsingOrdinalLowercase()
{
await TestAsync(
@"namespace A { class A { static void Main ( string [ ] args ) { var a = new [|b|] ( ) ; } } } namespace lowercase { class b { } } namespace Uppercase { class B { } } ",
@"using lowercase ; namespace A { class A { static void Main ( string [ ] args ) { var a = new b ( ) ; } } } namespace lowercase { class b { } } namespace Uppercase { class B { } } ");
}
[WorkItem(7443, "https://github.com/dotnet/roslyn/issues/7443")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddUsing)]
public async Task TestWithExistingIncompatibleExtension()
{
await TestAsync(
@"using N;
class C
{
int x()
{
System.Collections.Generic.IEnumerable<int> x = null;
return x.[|Any|]
}
}
namespace N
{
static class Extensions
{
public static void Any(this string s)
{
}
}
}",
@"using System.Linq;
using N;
class C
{
int x()
{
System.Collections.Generic.IEnumerable<int> x = null;
return x.Any
}
}
namespace N
{
static class Extensions
{
public static void Any(this string s)
{
}
}
}");
}
[WorkItem(1744, @"https://github.com/dotnet/roslyn/issues/1744")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddUsing)]
public async Task TestIncompleteCatchBlockInLambda()
{
await TestAsync(
@"class A { System . Action a = ( ) => { try { } catch ( [|Exception|] ",
@"using System ; class A { System . Action a = ( ) => { try { } catch ( Exception ");
}
[WorkItem(1033612, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1033612")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddUsing)]
public async Task TestAddInsideLambda()
{
var initialText =
@"using System;
static void Main(string[] args)
{
Func<int> f = () => { [|List<int>|]. }
}";
var expectedText =
@"using System;
using System.Collections.Generic;
static void Main(string[] args)
{
Func<int> f = () => { List<int>.}
}";
await TestAsync(initialText, expectedText);
}
[WorkItem(1033612, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1033612")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddUsing)]
public async Task TestAddInsideLambda2()
{
var initialText =
@"using System;
static void Main(string[] args)
{
Func<int> f = () => { [|List<int>|] }
}";
var expectedText =
@"using System;
using System.Collections.Generic;
static void Main(string[] args)
{
Func<int> f = () => { List<int>}
}";
await TestAsync(initialText, expectedText);
}
[WorkItem(1033612, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1033612")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddUsing)]
public async Task TestAddInsideLambda3()
{
var initialText =
@"using System;
static void Main(string[] args)
{
Func<int> f = () => {
var a = 3;
[|List<int>|].
return a;
};
}";
var expectedText =
@"using System;
using System.Collections.Generic;
static void Main(string[] args)
{
Func<int> f = () => {
var a = 3;
List<int>.
return a;
};
}";
await TestAsync(initialText, expectedText);
}
[WorkItem(1033612, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1033612")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddUsing)]
public async Task TestAddInsideLambda4()
{
var initialText =
@"using System;
static void Main(string[] args)
{
Func<int> f = () => {
var a = 3;
[|List<int>|]
return a;
};
}";
var expectedText =
@"using System;
using System.Collections.Generic;
static void Main(string[] args)
{
Func<int> f = () => {
var a = 3;
List<int>
return a;
};
}";
await TestAsync(initialText, expectedText);
}
[WorkItem(860648, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/860648")]
[WorkItem(902014, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/902014")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddUsing)]
public async Task TestIncompleteParenthesizedLambdaExpression()
{
await TestAsync(
@"using System;
class Test
{
void Foo()
{
Action a = () => { [|IBindCtx|] };
string a;
}
}",
@"using System;
using System.Runtime.InteropServices.ComTypes;
class Test
{
void Foo()
{
Action a = () => { IBindCtx };
string a;
}
}");
}
[WorkItem(7461, "https://github.com/dotnet/roslyn/issues/7461")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddUsing)]
public async Task TestExtensionWithIncompatibleInstance()
{
await TestAsync(
@"using System.IO;
namespace Namespace1
{
static class StreamExtensions
{
public static void Write(this Stream stream, byte[] bytes)
{
}
}
}
namespace Namespace2
{
class Foo
{
void Bar()
{
Stream stream = null;
stream.[|Write|](new byte[] { 1, 2, 3 });
}
}
}",
@"using System.IO;
using Namespace1;
namespace Namespace1
{
static class StreamExtensions
{
public static void Write(this Stream stream, byte[] bytes)
{
}
}
}
namespace Namespace2
{
class Foo
{
void Bar()
{
Stream stream = null;
stream.Write(new byte[] { 1, 2, 3 });
}
}
}");
}
[WorkItem(5499, "https://github.com/dotnet/roslyn/issues/5499")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddUsing)]
public async Task TestFormattingForNamespaceUsings()
{
await TestAsync(
@"namespace N
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
class Program
{
void Main()
{
[|Task<int>|]
}
}
}",
@"namespace N
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
class Program
{
void Main()
{
Task<int>
}
}
}",
compareTokens: false);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddUsing)]
public async Task TestGenericAmbiguityInSameNamespace()
{
await TestMissingAsync(
@"
namespace NS
{
class C<T> where T : [|C|].N
{
public class N { }
}
}");
}
public partial class AddUsingTestsWithAddImportDiagnosticProvider : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest
{
internal override Tuple<DiagnosticAnalyzer, CodeFixProvider> CreateDiagnosticProviderAndFixer(Workspace workspace)
{
return Tuple.Create<DiagnosticAnalyzer, CodeFixProvider>(
new CSharpUnboundIdentifiersDiagnosticAnalyzer(),
new CSharpAddImportCodeFixProvider());
}
private Task TestAsync(
string initialMarkup,
string expected,
bool systemSpecialCase,
int index = 0)
{
return TestAsync(initialMarkup, expected, index: index, options: new Dictionary<OptionKey, object>
{
{ new OptionKey(GenerationOptions.PlaceSystemNamespaceFirst, LanguageNames.CSharp), systemSpecialCase }
});
}
[WorkItem(1239, @"https://github.com/dotnet/roslyn/issues/1239")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddUsing)]
public async Task TestIncompleteLambda1()
{
await TestAsync(
@"using System . Linq ; class C { C ( ) { """" . Select ( ( ) => { new [|Byte|] ",
@"using System ; using System . Linq ; class C { C ( ) { """" . Select ( ( ) => { new Byte ");
}
[WorkItem(1239, @"https://github.com/dotnet/roslyn/issues/1239")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddUsing)]
public async Task TestIncompleteLambda2()
{
await TestAsync(
@"using System . Linq ; class C { C ( ) { """" . Select ( ( ) => { new [|Byte|] ( ) } ",
@"using System ; using System . Linq ; class C { C ( ) { """" . Select ( ( ) => { new Byte ( ) } ");
}
[WorkItem(860648, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/860648")]
[WorkItem(902014, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/902014")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddUsing)]
public async Task TestIncompleteSimpleLambdaExpression()
{
await TestAsync(
@"using System.Linq;
class Program
{
static void Main(string[] args)
{
args[0].Any(x => [|IBindCtx|]
string a;
}
}",
@"using System.Linq;
using System.Runtime.InteropServices.ComTypes;
class Program
{
static void Main(string[] args)
{
args[0].Any(x => IBindCtx
string a;
}
}");
}
[WorkItem(829970, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/829970")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddUsing)]
public async Task TestUnknownIdentifierGenericName()
{
await TestAsync(
@"class C { private [|List<int>|] } ",
@"using System.Collections.Generic; class C { private List<int> } ");
}
[WorkItem(829970, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/829970")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddUsing)]
public async Task TestUnknownIdentifierInAttributeSyntaxWithoutTarget()
{
await TestAsync(
@"class C { [[|Extension|]] } ",
@"using System.Runtime.CompilerServices; class C { [Extension] } ");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddUsing)]
public async Task TestOutsideOfMethodWithMalformedGenericParameters()
{
await TestAsync(
@"using System ; class Program { Func < [|FlowControl|] x } ",
@"using System ; using System . Reflection . Emit ; class Program { Func < FlowControl x } ");
}
[WorkItem(752640, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/752640")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddUsing)]
public async Task TestUnknownIdentifierWithSyntaxError()
{
await TestAsync(
@"class C { [|Directory|] private int i ; } ",
@"using System . IO ; class C { Directory private int i ; } ");
}
[WorkItem(855748, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/855748")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddUsing)]
public async Task TestGenericNameWithBrackets()
{
await TestAsync(
@"class Class { [|List|] }",
@"using System.Collections.Generic; class Class { List }");
await TestAsync(
@"class Class { [|List<>|] }",
@"using System.Collections.Generic; class Class { List<> }");
await TestAsync(
@"class Class { List[|<>|] }",
@"using System.Collections.Generic; class Class { List<> }");
}
[WorkItem(867496, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/867496")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddUsing)]
public async Task TestMalformedGenericParameters()
{
await TestAsync(
@"class Class { [|List<|] }",
@"using System.Collections.Generic; class Class { List< }");
await TestAsync(
@"class Class { [|List<Y x;|] }",
@"using System.Collections.Generic; class Class { List<Y x; }");
}
}
}
}
| 31.236568 | 364 | 0.610996 | [
"Apache-2.0"
] | svick/roslyn-not-a-fork | src/EditorFeatures/CSharpTest/Diagnostics/AddUsing/AddUsingTests.cs | 77,904 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.